File size: 17,701 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 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 |
use anyhow::{Context, Result, bail};
use tracing::Instrument;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TaskInput, TryJoinIterExt, Upcast, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
asset::Asset,
chunk::{
Chunk, ChunkGroupResult, ChunkItem, ChunkType, ChunkableModule, ChunkingConfig,
ChunkingConfigs, ChunkingContext, EntryChunkGroupResult, EvaluatableAssets, MinifyType,
ModuleId, SourceMapsType,
availability_info::AvailabilityInfo,
chunk_group::{MakeChunkGroupResult, make_chunk_group},
module_id_strategies::{DevModuleIdStrategy, ModuleIdStrategy},
},
environment::Environment,
ident::AssetIdent,
module::Module,
module_graph::{
ModuleGraph,
chunk_group_info::ChunkGroup,
export_usage::{ExportUsageInfo, ModuleExportUsageInfo},
},
output::{OutputAsset, OutputAssets},
};
use turbopack_ecmascript::{
async_chunk::module::AsyncLoaderModule,
chunk::EcmascriptChunk,
manifest::{chunk_asset::ManifestAsyncModule, loader_item::ManifestLoaderChunkItem},
};
use turbopack_ecmascript_runtime::RuntimeType;
use crate::ecmascript::node::{
chunk::EcmascriptBuildNodeChunk, entry::chunk::EcmascriptBuildNodeEntryChunk,
};
/// A builder for [`Vc<NodeJsChunkingContext>`].
pub struct NodeJsChunkingContextBuilder {
chunking_context: NodeJsChunkingContext,
}
impl NodeJsChunkingContextBuilder {
pub fn asset_prefix(mut self, asset_prefix: Option<RcStr>) -> Self {
self.chunking_context.asset_prefix = asset_prefix;
self
}
pub fn minify_type(mut self, minify_type: MinifyType) -> Self {
self.chunking_context.minify_type = minify_type;
self
}
pub fn source_maps(mut self, source_maps: SourceMapsType) -> Self {
self.chunking_context.source_maps_type = source_maps;
self
}
pub fn file_tracing(mut self, enable_tracing: bool) -> Self {
self.chunking_context.enable_file_tracing = enable_tracing;
self
}
pub fn module_merging(mut self, enable_module_merging: bool) -> Self {
self.chunking_context.enable_module_merging = enable_module_merging;
self
}
pub fn dynamic_chunk_content_loading(
mut self,
enable_dynamic_chunk_content_loading: bool,
) -> Self {
self.chunking_context.enable_dynamic_chunk_content_loading =
enable_dynamic_chunk_content_loading;
self
}
pub fn runtime_type(mut self, runtime_type: RuntimeType) -> Self {
self.chunking_context.runtime_type = runtime_type;
self
}
pub fn manifest_chunks(mut self, manifest_chunks: bool) -> Self {
self.chunking_context.manifest_chunks = manifest_chunks;
self
}
pub fn use_file_source_map_uris(mut self) -> Self {
self.chunking_context.should_use_file_source_map_uris = true;
self
}
pub fn module_id_strategy(
mut self,
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
) -> Self {
self.chunking_context.module_id_strategy = module_id_strategy;
self
}
pub fn export_usage(mut self, export_usage: Option<ResolvedVc<ExportUsageInfo>>) -> Self {
self.chunking_context.export_usage = export_usage;
self
}
pub fn chunking_config<T>(mut self, ty: ResolvedVc<T>, chunking_config: ChunkingConfig) -> Self
where
T: Upcast<Box<dyn ChunkType>>,
{
self.chunking_context
.chunking_configs
.push((ResolvedVc::upcast(ty), chunking_config));
self
}
/// Builds the chunking context.
pub fn build(self) -> Vc<NodeJsChunkingContext> {
NodeJsChunkingContext::cell(self.chunking_context)
}
}
/// A chunking context for build mode.
#[turbo_tasks::value]
#[derive(Debug, Clone, Hash, TaskInput)]
pub struct NodeJsChunkingContext {
/// The root path of the project
root_path: FileSystemPath,
/// This path is used to compute the url to request chunks or assets from
output_root: FileSystemPath,
/// The relative path from the output_root to the root_path.
output_root_to_root_path: RcStr,
/// This path is used to compute the url to request chunks or assets from
client_root: FileSystemPath,
/// Chunks are placed at this path
chunk_root_path: FileSystemPath,
/// Static assets are placed at this path
asset_root_path: FileSystemPath,
/// Static assets requested from this url base
asset_prefix: Option<RcStr>,
/// The environment chunks will be evaluated in.
environment: ResolvedVc<Environment>,
/// The kind of runtime to include in the output.
runtime_type: RuntimeType,
/// Enable tracing for this chunking
enable_file_tracing: bool,
/// Enable module merging
enable_module_merging: bool,
/// Enable dynamic chunk content loading.
enable_dynamic_chunk_content_loading: bool,
/// Whether to minify resulting chunks
minify_type: MinifyType,
/// Whether to generate source maps
source_maps_type: SourceMapsType,
/// Whether to use manifest chunks for lazy compilation
manifest_chunks: bool,
/// The strategy to use for generating module ids
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
/// The module export usage info, if available.
export_usage: Option<ResolvedVc<ExportUsageInfo>>,
/// Whether to use file:// uris for source map sources
should_use_file_source_map_uris: bool,
/// The chunking configs
chunking_configs: Vec<(ResolvedVc<Box<dyn ChunkType>>, ChunkingConfig)>,
}
impl NodeJsChunkingContext {
/// Creates a new chunking context builder.
pub fn builder(
root_path: FileSystemPath,
output_root: FileSystemPath,
output_root_to_root_path: RcStr,
client_root: FileSystemPath,
chunk_root_path: FileSystemPath,
asset_root_path: FileSystemPath,
environment: ResolvedVc<Environment>,
runtime_type: RuntimeType,
) -> NodeJsChunkingContextBuilder {
NodeJsChunkingContextBuilder {
chunking_context: NodeJsChunkingContext {
root_path,
output_root,
output_root_to_root_path,
client_root,
chunk_root_path,
asset_root_path,
asset_prefix: None,
enable_file_tracing: false,
enable_module_merging: false,
enable_dynamic_chunk_content_loading: false,
environment,
runtime_type,
minify_type: MinifyType::NoMinify,
source_maps_type: SourceMapsType::Full,
manifest_chunks: false,
should_use_file_source_map_uris: false,
module_id_strategy: ResolvedVc::upcast(DevModuleIdStrategy::new_resolved()),
export_usage: None,
chunking_configs: Default::default(),
},
}
}
}
#[turbo_tasks::value_impl]
impl NodeJsChunkingContext {
#[turbo_tasks::function]
async fn generate_chunk(
self: Vc<Self>,
chunk: Vc<Box<dyn Chunk>>,
) -> Result<Vc<Box<dyn OutputAsset>>> {
Ok(
if let Some(ecmascript_chunk) =
Vc::try_resolve_downcast_type::<EcmascriptChunk>(chunk).await?
{
Vc::upcast(EcmascriptBuildNodeChunk::new(self, ecmascript_chunk))
} else if let Some(output_asset) =
Vc::try_resolve_sidecast::<Box<dyn OutputAsset>>(chunk).await?
{
output_asset
} else {
bail!("Unable to generate output asset for chunk");
},
)
}
/// Returns the kind of runtime to include in output chunks.
///
/// This is defined directly on `NodeJsChunkingContext` so it is zero-cost
/// when `RuntimeType` has a single variant.
#[turbo_tasks::function]
pub fn runtime_type(&self) -> Vc<RuntimeType> {
self.runtime_type.cell()
}
/// Returns the minify type.
#[turbo_tasks::function]
pub fn minify_type(&self) -> Vc<MinifyType> {
self.minify_type.cell()
}
#[turbo_tasks::function]
pub fn asset_prefix(&self) -> Vc<Option<RcStr>> {
Vc::cell(self.asset_prefix.clone())
}
}
#[turbo_tasks::value_impl]
impl ChunkingContext for NodeJsChunkingContext {
#[turbo_tasks::function]
fn name(&self) -> Vc<RcStr> {
Vc::cell(rcstr!("unknown"))
}
#[turbo_tasks::function]
fn root_path(&self) -> Vc<FileSystemPath> {
self.root_path.clone().cell()
}
#[turbo_tasks::function]
fn output_root(&self) -> Vc<FileSystemPath> {
self.output_root.clone().cell()
}
#[turbo_tasks::function]
fn output_root_to_root_path(&self) -> Vc<RcStr> {
Vc::cell(self.output_root_to_root_path.clone())
}
#[turbo_tasks::function]
fn environment(&self) -> Vc<Environment> {
*self.environment
}
#[turbo_tasks::function]
fn is_tracing_enabled(&self) -> Vc<bool> {
Vc::cell(self.enable_file_tracing)
}
#[turbo_tasks::function]
fn is_module_merging_enabled(&self) -> Vc<bool> {
Vc::cell(self.enable_module_merging)
}
#[turbo_tasks::function]
fn is_dynamic_chunk_content_loading_enabled(&self) -> Vc<bool> {
Vc::cell(self.enable_dynamic_chunk_content_loading)
}
#[turbo_tasks::function]
pub fn minify_type(&self) -> Vc<MinifyType> {
self.minify_type.cell()
}
#[turbo_tasks::function]
async fn asset_url(&self, ident: FileSystemPath) -> Result<Vc<RcStr>> {
let asset_path = ident.to_string();
let asset_path = asset_path
.strip_prefix(&format!("{}/", self.client_root.path))
.context("expected client root to contain asset path")?;
Ok(Vc::cell(
format!(
"{}{}",
self.asset_prefix.clone().unwrap_or(rcstr!("/")),
asset_path
)
.into(),
))
}
#[turbo_tasks::function]
fn chunk_root_path(&self) -> Vc<FileSystemPath> {
self.chunk_root_path.clone().cell()
}
#[turbo_tasks::function]
async fn chunk_path(
&self,
_asset: Option<Vc<Box<dyn Asset>>>,
ident: Vc<AssetIdent>,
prefix: Option<RcStr>,
extension: RcStr,
) -> Result<Vc<FileSystemPath>> {
let root_path = self.chunk_root_path.clone();
let name = ident
.output_name(self.root_path.clone(), prefix, extension)
.owned()
.await?;
Ok(root_path.join(&name)?.cell())
}
#[turbo_tasks::function]
fn reference_chunk_source_maps(&self, _chunk: Vc<Box<dyn OutputAsset>>) -> Vc<bool> {
Vc::cell(match self.source_maps_type {
SourceMapsType::Full => true,
SourceMapsType::None => false,
})
}
#[turbo_tasks::function]
fn reference_module_source_maps(&self, _module: Vc<Box<dyn Module>>) -> Vc<bool> {
Vc::cell(match self.source_maps_type {
SourceMapsType::Full => true,
SourceMapsType::None => false,
})
}
#[turbo_tasks::function]
fn should_use_file_source_map_uris(&self) -> Vc<bool> {
Vc::cell(self.should_use_file_source_map_uris)
}
#[turbo_tasks::function]
fn chunking_configs(&self) -> Result<Vc<ChunkingConfigs>> {
Ok(Vc::cell(self.chunking_configs.iter().cloned().collect()))
}
#[turbo_tasks::function]
async fn asset_path(
&self,
content_hash: RcStr,
original_asset_ident: Vc<AssetIdent>,
) -> Result<Vc<FileSystemPath>> {
let source_path = original_asset_ident.path().await?;
let basename = source_path.file_name();
let asset_path = match source_path.extension_ref() {
Some(ext) => format!(
"{basename}.{content_hash}.{ext}",
basename = &basename[..basename.len() - ext.len() - 1],
content_hash = &content_hash[..8]
),
None => format!(
"{basename}.{content_hash}",
content_hash = &content_hash[..8]
),
};
Ok(self.asset_root_path.join(&asset_path)?.cell())
}
#[turbo_tasks::function]
async fn chunk_group(
self: ResolvedVc<Self>,
ident: Vc<AssetIdent>,
chunk_group: ChunkGroup,
module_graph: Vc<ModuleGraph>,
availability_info: AvailabilityInfo,
) -> Result<Vc<ChunkGroupResult>> {
let span = tracing::info_span!("chunking", name = ident.to_string().await?.to_string());
async move {
let modules = chunk_group.entries();
let MakeChunkGroupResult {
chunks,
availability_info,
} = make_chunk_group(
modules,
module_graph,
ResolvedVc::upcast(self),
availability_info,
)
.await?;
let assets = chunks
.iter()
.map(|chunk| self.generate_chunk(**chunk).to_resolved())
.try_join()
.await?;
Ok(ChunkGroupResult {
assets: ResolvedVc::cell(assets),
availability_info,
}
.cell())
}
.instrument(span)
.await
}
#[turbo_tasks::function]
pub async fn entry_chunk_group(
self: ResolvedVc<Self>,
path: FileSystemPath,
evaluatable_assets: Vc<EvaluatableAssets>,
module_graph: Vc<ModuleGraph>,
extra_chunks: Vc<OutputAssets>,
availability_info: AvailabilityInfo,
) -> Result<Vc<EntryChunkGroupResult>> {
let evaluatable_assets_ref = evaluatable_assets.await?;
let entries = evaluatable_assets_ref
.iter()
.map(|&asset| ResolvedVc::upcast::<Box<dyn Module>>(asset));
let MakeChunkGroupResult {
chunks,
availability_info,
} = make_chunk_group(
entries,
module_graph,
ResolvedVc::upcast(self),
availability_info,
)
.await?;
let extra_chunks = extra_chunks.await?;
let other_chunks: Vec<_> = extra_chunks
.iter()
.copied()
.chain(
chunks
.iter()
.map(|chunk| self.generate_chunk(**chunk).to_resolved())
.try_join()
.await?,
)
.collect();
let Some(module) = ResolvedVc::try_sidecast(*evaluatable_assets_ref.last().unwrap()) else {
bail!("module must be placeable in an ecmascript chunk");
};
let asset = ResolvedVc::upcast(
EcmascriptBuildNodeEntryChunk::new(
path,
Vc::cell(other_chunks),
evaluatable_assets,
*module,
module_graph,
*self,
)
.to_resolved()
.await?,
);
Ok(EntryChunkGroupResult {
asset,
availability_info,
}
.cell())
}
#[turbo_tasks::function]
fn evaluated_chunk_group(
self: Vc<Self>,
_ident: Vc<AssetIdent>,
_chunk_group: ChunkGroup,
_module_graph: Vc<ModuleGraph>,
_availability_info: AvailabilityInfo,
) -> Result<Vc<ChunkGroupResult>> {
// TODO(alexkirsz) This method should be part of a separate trait that is
// only implemented for client/edge runtimes.
bail!("the build chunking context does not support evaluated chunk groups")
}
#[turbo_tasks::function]
fn chunk_item_id_from_ident(&self, ident: Vc<AssetIdent>) -> Vc<ModuleId> {
self.module_id_strategy.get_module_id(ident)
}
#[turbo_tasks::function]
async fn async_loader_chunk_item(
self: Vc<Self>,
module: Vc<Box<dyn ChunkableModule>>,
module_graph: Vc<ModuleGraph>,
availability_info: AvailabilityInfo,
) -> Result<Vc<Box<dyn ChunkItem>>> {
Ok(if self.await?.manifest_chunks {
let manifest_asset =
ManifestAsyncModule::new(module, module_graph, Vc::upcast(self), availability_info);
Vc::upcast(ManifestLoaderChunkItem::new(
manifest_asset,
module_graph,
Vc::upcast(self),
))
} else {
let module = AsyncLoaderModule::new(module, Vc::upcast(self), availability_info);
Vc::upcast(module.as_chunk_item(module_graph, Vc::upcast(self)))
})
}
#[turbo_tasks::function]
async fn async_loader_chunk_item_id(
self: Vc<Self>,
module: Vc<Box<dyn ChunkableModule>>,
) -> Result<Vc<ModuleId>> {
Ok(if self.await?.manifest_chunks {
self.chunk_item_id_from_ident(ManifestLoaderChunkItem::asset_ident_for(module))
} else {
self.chunk_item_id_from_ident(AsyncLoaderModule::asset_ident_for(module))
})
}
#[turbo_tasks::function]
async fn module_export_usage(
self: Vc<Self>,
module: ResolvedVc<Box<dyn Module>>,
) -> Result<Vc<ModuleExportUsageInfo>> {
if let Some(export_usage) = self.await?.export_usage {
Ok(export_usage.await?.used_exports(module))
} else {
Ok(ModuleExportUsageInfo::all())
}
}
}
|