File size: 9,886 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
use anyhow::Result;
use rustc_hash::FxHashSet;
use serde::Serialize;
use tracing::{Level, instrument};
use turbo_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,
};
#[instrument(level = Level::INFO, 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().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_all_edges_unordered(|(parent_node, r), current| {
edges.push((
parent_node.module,
RcStr::from(format!("{}: {}", r.chunking_type, r.export)),
current.module,
));
Ok(())
})
.await?;
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 = RcStr::from(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).into()))
.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).into()))
.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: "asset".into(),
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().owned().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) -> String {
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>,
}
|