Unverified Commit ee1f9d79 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Remove webpack stats generation from Turbopack (#91515)

### What?

Remove the `TURBOPACK_STATS` feature that generated webpack-compatible
`webpack-stats.json` files from Turbopack's output.

**Deleted:**
- `crates/next-api/src/webpack_stats.rs` — the entire 305-line Rust
implementation that built webpack-format stats (assets, chunks, modules,
entrypoints) from Turbopack's module graph

**Rust changes:**
- `crates/next-api/src/lib.rs` — removed `mod webpack_stats;`
- `crates/next-api/src/project.rs` — removed
`should_create_webpack_stats()` which read the `TURBOPACK_STATS` env var
- `crates/next-api/src/pages.rs` — removed `generate_webpack_stats`
import and stats output emission
- `crates/next-api/src/app.rs` — same

**TypeScript changes:**
- `packages/next/src/shared/lib/constants.ts` — removed `WEBPACK_STATS =
'webpack-stats.json'` constant
- `packages/next/src/shared/lib/turbopack/manifest-loader.ts` — removed
`loadWebpackStats()`, `writeWebpackStats()`, `mergeWebpackStats()`, the
`webpackStats` field, webpack type imports, and the `TURBOPACK_STATS`
env guard in `writeManifests()`
- `packages/next/src/server/dev/turbopack-utils.ts` — removed
`shouldCreateWebpackStats` flag and two `loadWebpackStats()` call sites
- `packages/next/src/build/handle-entrypoints.ts` — same

### Why?

This feature is no longer needed and adds dead complexity. It was opt-in
via `TURBOPACK_STATS=1` but nothing in the current codebase or tooling
depends on it.

### How?

Pure deletion — no behavior change for any existing user, as the feature
was opt-in via an environment variable that is no longer checked.

**Intentionally left untouched:**
- Webpack's own `stats.json` generation (non-Turbopack path)
- The Turbopack bundle analyzer / `analyze` feature
- `route-bundle-stats.json` in `.next/diagnostics/`
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent d0a0474d
......@@ -88,7 +88,6 @@ use crate::{
},
server_actions::{build_server_actions_loader, create_server_actions_manifest},
sri_manifest::get_sri_manifest_asset,
webpack_stats::generate_webpack_stats,
};
#[turbo_tasks::value]
......@@ -1407,34 +1406,6 @@ impl AppEndpoint {
ResolvedVc::cell(client_assets.into_iter().collect::<Vec<_>>());
if emit_manifests != EmitManifests::None {
if *this
.app_project
.project()
.should_create_webpack_stats()
.await?
{
let webpack_stats = generate_webpack_stats(
*module_graphs.base,
app_entry.original_name.clone(),
client_assets.await?.into_iter().copied(),
)
.await?;
let stats_output = VirtualOutputAsset::new(
node_root.join(&format!(
"server/app{manifest_path_prefix}/webpack-stats.json",
))?,
AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty(
&webpack_stats,
)?))
.cell(),
),
)
.to_resolved()
.await?;
server_assets.insert(ResolvedVc::upcast(stats_output));
}
let build_manifest = BuildManifest {
output_path: node_root.join(&format!(
"server/app{manifest_path_prefix}/build-manifest.json",
......
......@@ -27,4 +27,3 @@ pub mod routes_hashes_manifest;
mod server_actions;
mod sri_manifest;
mod versioned_content_map;
mod webpack_stats;
......@@ -81,7 +81,6 @@ use crate::{
project::Project,
route::{Endpoint, EndpointOutput, EndpointOutputPaths, ModuleGraphs, Route, Routes},
sri_manifest::get_sri_manifest_asset,
webpack_stats::generate_webpack_stats,
};
#[turbo_tasks::value]
......@@ -1348,32 +1347,6 @@ impl PageEndpoint {
server_assets.push(next_font_manifest_output);
}
if *this
.pages_project
.project()
.should_create_webpack_stats()
.await?
{
let webpack_stats = generate_webpack_stats(
self.client_module_graph(),
this.original_name.clone(),
client_assets.await?.into_iter().copied(),
)
.await?;
let stats_output = VirtualOutputAsset::new(
node_root.join(&format!(
"server/pages{manifest_path_prefix}/webpack-stats.json",
))?,
AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty(&webpack_stats)?))
.cell(),
),
)
.to_resolved()
.await?;
server_assets.push(ResolvedVc::upcast(stats_output));
}
let page_output = match *ssr_chunk.await? {
SsrChunk::NodeJs {
entry,
......
......@@ -1221,13 +1221,6 @@ impl Project {
Vc::cell(self.no_mangling)
}
#[turbo_tasks::function]
pub(super) async fn should_create_webpack_stats(&self) -> Result<Vc<bool>> {
Ok(Vc::cell(
self.env.read(rcstr!("TURBOPACK_STATS")).await?.is_some(),
))
}
#[turbo_tasks::function]
pub(super) async fn execution_context(self: Vc<Self>) -> Result<Vc<ExecutionContext>> {
let node_root = self.node_root().owned().await?;
......
use anyhow::Result;
use rustc_hash::FxHashSet;
use serde::Serialize;
use tracing::instrument;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
FxIndexMap, FxIndexSet, ResolvedVc, TryJoinIterExt, ValueToString, Vc, fxindexmap,
};
use turbopack_browser::ecmascript::EcmascriptBrowserChunk;
use turbopack_core::{
chunk::{Chunk, ChunkItem, ChunkItemExt, ModuleId},
module::Module,
module_graph::ModuleGraph,
output::{OutputAsset, OutputAssetsReference},
};
#[instrument(level = "info", name = "generate webpack stats", skip_all)]
pub async fn generate_webpack_stats<I>(
module_graph: Vc<ModuleGraph>,
entry_name: RcStr,
entry_assets: I,
) -> Result<WebpackStats>
where
I: IntoIterator<Item = ResolvedVc<Box<dyn OutputAsset>>>,
{
let mut assets = vec![];
let mut chunks = vec![];
let mut chunk_items: FxIndexMap<Vc<Box<dyn ChunkItem>>, FxIndexSet<RcStr>> =
FxIndexMap::default();
let entry_assets = entry_assets.into_iter().collect::<Vec<_>>();
let (asset_parents, asset_children) = {
let mut asset_children =
FxIndexMap::with_capacity_and_hasher(entry_assets.len(), Default::default());
let mut visited =
FxHashSet::with_capacity_and_hasher(entry_assets.len(), Default::default());
let mut queue = entry_assets.clone();
while let Some(asset) = queue.pop() {
if visited.insert(asset) {
let references = asset.references().all_assets().await?;
asset_children.insert(asset, references.clone());
queue.extend(references);
}
}
let mut asset_parents: FxIndexMap<_, Vec<_>> =
FxIndexMap::with_capacity_and_hasher(entry_assets.len(), Default::default());
for (&parent, children) in &asset_children {
for child in children {
asset_parents.entry(*child).or_default().push(parent);
}
}
(asset_parents, asset_children)
};
let asset_reasons = {
let module_graph = module_graph.await?;
let mut edges = vec![];
module_graph.traverse_edges_unordered(|parent, current| {
if let Some((parent_node, r)) = parent {
edges.push((
parent_node,
RcStr::from(format!("{}: {}", r.chunking_type, r.binding_usage.export)),
current,
));
}
Ok(())
})?;
let edges = edges
.into_iter()
.map(async |(parent, ty, child)| {
let parent_path = parent.ident().path().await?.path.clone();
Ok((
child,
WebpackStatsReason {
module: parent_path.clone(),
module_identifier: parent.ident().to_string().owned().await?,
module_name: parent_path,
ty,
},
))
})
.try_join()
.await?;
let mut asset_reasons: FxIndexMap<_, Vec<_>> = FxIndexMap::default();
for (child, reason) in edges {
asset_reasons.entry(child).or_default().push(reason);
}
asset_reasons
};
for asset in entry_assets {
let path = normalize_client_path(&asset.path().await?.path);
let Some(asset_len) = *asset.size_bytes().await? else {
continue;
};
if let Some(chunk) = ResolvedVc::try_downcast_type::<EcmascriptBrowserChunk>(asset) {
chunks.push(WebpackStatsChunk {
size: asset_len,
files: vec![path.clone()],
id: path.clone(),
parents: if let Some(parents) = asset_parents.get(&asset) {
parents
.iter()
.map(async |c| Ok(normalize_client_path(&c.path().await?.path)))
.try_join()
.await?
} else {
vec![]
},
children: if let Some(children) = asset_children.get(&asset) {
children
.iter()
.map(async |c| Ok(normalize_client_path(&c.path().await?.path)))
.try_join()
.await?
} else {
vec![]
},
..Default::default()
});
for item in chunk.chunk().chunk_items().await? {
chunk_items.entry(**item).or_default().insert(path.clone());
}
}
assets.push(WebpackStatsAsset {
ty: rcstr!("asset"),
name: path.clone(),
chunk_names: vec![path],
size: asset_len,
..Default::default()
});
}
// TODO try to downcast modules to `EcmascriptMergedModule` to include the scope hoisted modules
// as well
let modules = chunk_items
.into_iter()
.map(async |(chunk_item, chunks)| {
let size = *chunk_item
.content_ident()
.path()
.await?
.read()
.len()
.await?;
Ok(WebpackStatsModule {
name: chunk_item.asset_ident().path().await?.path.clone(),
id: chunk_item.id().await?,
identifier: chunk_item.asset_ident().to_string().owned().await?,
chunks: chunks.into_iter().collect(),
size,
// TODO Find all incoming edges to this module
reasons: asset_reasons
.get(&chunk_item.module().to_resolved().await?)
.cloned()
.unwrap_or_default(),
})
})
.try_join()
.await?;
let entrypoints: FxIndexMap<_, _> = fxindexmap!(
entry_name.clone() =>
WebpackStatsEntrypoint {
name: entry_name.clone(),
chunks: chunks.iter().map(|c| c.id.clone()).collect(),
assets: assets
.iter()
.map(|a| WebpackStatsEntrypointAssets {
name: a.name.clone(),
})
.collect(),
}
);
Ok(WebpackStats {
assets,
entrypoints,
chunks,
modules,
})
}
fn normalize_client_path(path: &str) -> RcStr {
let next_re = regex::Regex::new(r"^_next/").unwrap();
next_re.replace(path, ".next/").into()
}
#[derive(Serialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct WebpackStatsAssetInfo {}
#[derive(Serialize, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct WebpackStatsAsset {
#[serde(rename = "type")]
pub ty: RcStr,
/// The `output` filename
pub name: RcStr,
pub info: WebpackStatsAssetInfo,
/// The size of the file in bytes
pub size: u64,
/// Indicates whether or not the asset made it to the `output` directory
pub emitted: bool,
/// Indicates whether or not the asset was compared with the same file on the output file
/// system
pub compared_for_emit: bool,
pub cached: bool,
/// The chunks this asset contains
pub chunk_names: Vec<RcStr>,
/// The chunk IDs this asset contains
pub chunks: Vec<RcStr>,
}
#[derive(Serialize, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct WebpackStatsChunk {
/// Indicates whether or not the chunk went through Code Generation
pub rendered: bool,
/// Indicates whether this chunk is loaded on initial page load or lazily.
pub initial: bool,
/// Indicates whether or not the chunk contains the webpack runtime
pub entry: bool,
pub recorded: bool,
/// The ID of this chunk
pub id: RcStr,
/// Chunk size in bytes
pub size: u64,
pub hash: RcStr,
/// An array of filename strings that contain this chunk
pub files: Vec<RcStr>,
/// An list of chunk names contained within this chunk
pub names: Vec<RcStr>,
/// Parent chunk IDs
pub parents: Vec<RcStr>,
/// Child chunk IDs
pub children: Vec<RcStr>,
}
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct WebpackStatsModule {
/// Path to the actual file
pub name: RcStr,
/// The ID of the module
pub id: ModuleId,
/// A unique ID used internally
pub identifier: RcStr,
pub chunks: Vec<RcStr>,
pub size: Option<u64>,
pub reasons: Vec<WebpackStatsReason>,
}
#[derive(Clone, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct WebpackStatsReason {
/// The [WebpackStatsModule::name]
pub module: RcStr,
// /// The [WebpackStatsModule::id]
// pub module_id: ModuleId,
/// The [WebpackStatsModule::identifier]
pub module_identifier: RcStr,
/// A more readable name for the module (used for "pretty-printing")
pub module_name: RcStr,
/// The [type of request](/api/module-methods) used
#[serde(rename = "type")]
pub ty: RcStr,
// /// Raw string used for the `import` or `require` request
// pub user_request: RcStr,
// /// Lines of code that caused the module to be included
// pub loc: RcStr
}
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct WebpackStatsEntrypointAssets {
pub name: RcStr,
}
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct WebpackStatsEntrypoint {
pub name: RcStr,
pub chunks: Vec<RcStr>,
pub assets: Vec<WebpackStatsEntrypointAssets>,
}
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct WebpackStats {
pub assets: Vec<WebpackStatsAsset>,
pub entrypoints: FxIndexMap<RcStr, WebpackStatsEntrypoint>,
pub chunks: Vec<WebpackStatsChunk>,
pub modules: Vec<WebpackStatsModule>,
}
......@@ -63,8 +63,6 @@ export async function handleRouteType({
route: PageRoute | AppRoute
manifestLoader: TurbopackManifestLoader
}) {
const shouldCreateWebpackStats = process.env.TURBOPACK_STATS != null
switch (route.type) {
case 'page': {
const serverKey = getEntryKey('pages', 'server', page)
......@@ -84,10 +82,6 @@ export async function handleRouteType({
await manifestLoader.loadSriManifest(page, 'pages')
if (shouldCreateWebpackStats) {
await manifestLoader.loadWebpackStats(page, 'pages')
}
break
}
case 'page-api': {
......@@ -118,10 +112,6 @@ export async function handleRouteType({
manifestLoader.loadSriManifest(page, 'app')
if (shouldCreateWebpackStats) {
manifestLoader.loadWebpackStats(page, 'app')
}
break
}
case 'app-route': {
......
......@@ -169,8 +169,6 @@ export async function handleRouteType({
hooks?: HandleRouteTypeHooks // dev
}) {
const shouldCreateWebpackStats = process.env.TURBOPACK_STATS != null
switch (route.type) {
case 'page': {
const clientKey = getEntryKey('pages', 'client', page)
......@@ -236,10 +234,6 @@ export async function handleRouteType({
await manifestLoader.loadFontManifest('/_app', 'pages')
await manifestLoader.loadFontManifest(page, 'pages')
if (shouldCreateWebpackStats) {
await manifestLoader.loadWebpackStats(page, 'pages')
}
manifestLoader.writeManifests({
devRewrites,
productionRewrites,
......@@ -389,10 +383,6 @@ export async function handleRouteType({
manifestLoader.loadActionManifest(page)
manifestLoader.loadFontManifest(page, 'app')
if (shouldCreateWebpackStats) {
manifestLoader.loadWebpackStats(page, 'app')
}
manifestLoader.writeManifests({
devRewrites,
productionRewrites,
......
......@@ -85,7 +85,6 @@ export type PHASE_TYPE =
| typeof PHASE_DEVELOPMENT_SERVER
export const PAGES_MANIFEST = 'pages-manifest.json'
export const WEBPACK_STATS = 'webpack-stats.json'
export const APP_PATHS_MANIFEST = 'app-paths-manifest.json'
export const APP_PATH_ROUTES_MANIFEST = 'app-path-routes-manifest.json'
export const BUILD_MANIFEST = 'build-manifest.json'
......
......@@ -2,13 +2,6 @@ import type {
EdgeFunctionDefinition,
MiddlewareManifest,
} from '../../../build/webpack/plugins/middleware-plugin'
import type {
StatsAsset,
StatsChunk,
StatsChunkGroup,
StatsModule,
StatsCompilation as WebpackStats,
} from 'webpack'
import type { BuildManifest } from '../../../server/get-page-files'
import type { PagesManifest } from '../../../build/webpack/plugins/pages-manifest-plugin'
import type { ActionManifest } from '../../../build/webpack/plugins/flight-client-entry-plugin'
......@@ -27,7 +20,6 @@ import {
SUBRESOURCE_INTEGRITY_MANIFEST,
TURBOPACK_CLIENT_BUILD_MANIFEST,
TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST,
WEBPACK_STATS,
} from '../constants'
import { join, posix } from 'path'
import { readFileSync } from 'fs'
......@@ -69,7 +61,6 @@ type ManifestName =
| typeof MIDDLEWARE_MANIFEST
| typeof BUILD_MANIFEST
| typeof PAGES_MANIFEST
| typeof WEBPACK_STATS
| typeof APP_PATHS_MANIFEST
| `${typeof SERVER_REFERENCE_MANIFEST}.json`
| `${typeof SUBRESOURCE_INTEGRITY_MANIFEST}.json`
......@@ -200,8 +191,6 @@ export class TurbopackManifestLoader {
> = new ManifestsMap()
private pagesManifests: ManifestsMap<string, PagesManifest> =
new ManifestsMap()
private webpackStats: ManifestsMap<EntryKey, WebpackStats> =
new ManifestsMap()
private sriManifests: ManifestsMap<EntryKey, SubresourceIntegrityManifest> =
new ManifestsMap()
private encryptionKey: string
......@@ -243,7 +232,6 @@ export class TurbopackManifestLoader {
this.fontManifests.delete(key)
this.middlewareManifests.delete(key)
this.pagesManifests.delete(key)
this.webpackStats.delete(key)
}
loadActionManifest(pageName: string): void {
......@@ -354,16 +342,6 @@ export class TurbopackManifestLoader {
)
}
private writeWebpackStats(): void {
if (!this.webpackStats.takeChanged()) {
return
}
const webpackStats = this.mergeWebpackStats(this.webpackStats.values())
const path = join(this.distDir, 'server', WEBPACK_STATS)
this.pendingCacheDeletes.push(path)
writeFileAtomic(path, JSON.stringify(webpackStats, null, 2))
}
private writeSriManifest(): void {
if (!this.sriEnabled || !this.sriManifests.takeChanged()) {
return
......@@ -412,13 +390,6 @@ export class TurbopackManifestLoader {
)
}
loadWebpackStats(pageName: string, type: 'app' | 'pages' = 'pages'): void {
this.webpackStats.set(
getEntryKey(type, 'client', pageName),
readPartialManifestContent(this.distDir, WEBPACK_STATS, pageName, type)
)
}
loadSriManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {
if (!this.sriEnabled) return
this.sriManifests.set(
......@@ -432,66 +403,6 @@ export class TurbopackManifestLoader {
)
}
private mergeWebpackStats(statsFiles: Iterable<WebpackStats>): WebpackStats {
const entrypoints: Record<string, StatsChunkGroup> = {}
const assets: Map<string, StatsAsset> = new Map()
const chunks: Map<string | number, StatsChunk> = new Map()
const modules: Map<string | number, StatsModule> = new Map()
for (const statsFile of statsFiles) {
if (statsFile.entrypoints) {
for (const [k, v] of Object.entries(statsFile.entrypoints)) {
if (!entrypoints[k]) {
entrypoints[k] = v
}
}
}
if (statsFile.assets) {
for (const asset of statsFile.assets) {
if (!assets.has(asset.name)) {
assets.set(asset.name, asset)
}
}
}
if (statsFile.chunks) {
for (const chunk of statsFile.chunks) {
if (!chunks.has(chunk.id!)) {
chunks.set(chunk.id!, chunk)
}
}
}
if (statsFile.modules) {
for (const module of statsFile.modules) {
const id = module.id
if (id != null) {
// Merge the chunk list for the module. This can vary across endpoints.
const existing = modules.get(id)
if (existing == null) {
modules.set(id, module)
} else if (module.chunks != null && existing.chunks != null) {
for (const chunk of module.chunks) {
if (!existing.chunks.includes(chunk)) {
existing.chunks.push(chunk)
}
}
}
}
}
}
}
return {
version: 'Turbopack',
entrypoints,
assets: [...assets.values()],
chunks: [...chunks.values()],
modules: [...modules.values()],
}
}
private mergeBuildManifests(
manifests: Iterable<BuildManifest>,
lowPriorityFiles: string[]
......@@ -956,10 +867,6 @@ export class TurbopackManifestLoader {
this.writeSriManifest()
if (process.env.TURBOPACK_STATS != null) {
this.writeWebpackStats()
}
// Flush all queued cache deletions in a single require.cache scan
if (this.pendingCacheDeletes.length > 0) {
deleteCache(this.pendingCacheDeletes)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment