Skip to main content

turbopack_core/chunk/
chunking_context.rs

1use anyhow::Result;
2use bincode::{Decode, Encode};
3use rustc_hash::{FxHashMap, FxHashSet};
4use serde::{Deserialize, Serialize};
5use smallvec::{SmallVec, smallvec};
6use turbo_rcstr::RcStr;
7use turbo_tasks::{ResolvedVc, Upcast, Vc, turbobail};
8use turbo_tasks_fs::FileSystemPath;
9use turbo_tasks_hash::DeterministicHash;
10
11use crate::{
12    asset::{Asset, AssetContent},
13    chunk::{
14        ChunkItem, ChunkType, ChunkableModule, availability_info::AvailabilityInfo,
15        chunk_id_strategy::ModuleIdStrategy,
16    },
17    environment::{ChunkLoading, Environment},
18    ident::AssetIdent,
19    json::RcJsonRawValue,
20    module::Module,
21    module_graph::{
22        ModuleGraph, binding_usage_info::ModuleExportUsage, chunk_group_info::ChunkGroupKey,
23        module_batches::BatchingConfig, style_groups::StyleGroupsAlgorithm,
24    },
25    output::{
26        ExpandOutputAssetsInput, OutputAsset, OutputAssets, OutputAssetsReferences,
27        OutputAssetsWithReferenced, expand_output_assets,
28    },
29    reference::ModuleReference,
30    source_map::{OptionSourceMapType, SourceMapGenerationOptions},
31};
32
33/// A marker trait for emit options that can be stored in a chunking context.
34///
35/// Different crates can define their own emit option types (e.g., `EcmascriptEmitOptions`,
36/// `CssEmitOptions`) without requiring the core crate to depend on their specific dependencies
37/// (e.g., SWC).
38#[turbo_tasks::value_trait]
39pub trait EmitOption {}
40
41/// A heterogeneous list of emit options stored in a chunking context.
42#[turbo_tasks::value(transparent)]
43pub struct EmitOptions(Vec<ResolvedVc<Box<dyn EmitOption>>>);
44
45/// Find a specific emit option type from the list, returning the last matching one.
46///
47/// Returns `None` if no matching option is found, in which case callers should use defaults.
48pub async fn find_emit_option<T>(list: Vc<EmitOptions>) -> Result<Option<Vc<T>>>
49where
50    T: turbo_tasks::VcValueType + turbo_tasks::UpcastStrict<Box<dyn EmitOption>>,
51{
52    let list = list.await?;
53    Ok(list
54        .iter()
55        .rev()
56        .filter_map(|item| ResolvedVc::try_downcast_type::<T>(*item))
57        .next()
58        .map(|v| *v))
59}
60
61/// Suffix to append to asset URLs.
62#[turbo_tasks::value(shared)]
63#[derive(Debug, Clone)]
64pub enum AssetSuffix {
65    /// No suffix.
66    None,
67    /// A constant suffix to append to URLs.
68    Constant(RcStr),
69    /// Infer the suffix at runtime from the script src attribute.
70    /// Only valid in browser runtime for chunk loading, not for static asset URL generation.
71    Inferred,
72    /// Read the suffix from a global variable at runtime.
73    /// Used for server-side rendering where the suffix is set via `globalThis.{global_name}`.
74    FromGlobal(RcStr),
75}
76
77/// URL behavior configuration for static assets.
78#[turbo_tasks::value(shared)]
79#[derive(Debug, Clone)]
80pub struct UrlBehavior {
81    pub suffix: AssetSuffix,
82    /// Static suffix for contexts that cannot use dynamic JS expressions (e.g., CSS `url()`
83    /// references). Must be a constant string known at build time (e.g., `?dpl=<deployment_id>`).
84    pub static_suffix: ResolvedVc<Option<RcStr>>,
85}
86
87#[turbo_tasks::task_input]
88#[derive(
89    Debug,
90    Clone,
91    Copy,
92    PartialEq,
93    Eq,
94    Hash,
95    Serialize,
96    Deserialize,
97    DeterministicHash,
98    Encode,
99    Decode,
100)]
101pub enum ChunkGroupType {
102    Entry,
103    Evaluated,
104}
105
106/// For each async module of a chunk group, the availability its async loader was created with,
107/// i.e. the availability passed to [`ChunkingContext::async_loader_chunk_item`]. A chunk group
108/// doesn't create an async loader for a module when an available chunk group already did.
109#[turbo_tasks::value(transparent, cell = "keyed")]
110pub struct AsyncLoaderAvailabilityMap(
111    FxHashMap<ResolvedVc<Box<dyn ChunkableModule>>, AvailabilityInfo>,
112);
113
114#[turbo_tasks::value(shared)]
115#[derive(Clone)]
116pub struct ChunkGroupResult {
117    pub assets: ResolvedVc<OutputAssets>,
118    pub referenced_assets: ResolvedVc<OutputAssets>,
119    pub references: ResolvedVc<OutputAssetsReferences>,
120    pub availability_info: AvailabilityInfo,
121    pub chunk_group_bootstrap_params: Option<RcJsonRawValue>,
122    /// The availability of the async loaders created by the chunk groups this result consists of,
123    /// one keyed map per chunk group, in the order the chunk groups are loaded (see
124    /// [`ChunkGroupResult::concatenate`]). It has one entry per concatenated chunk group. The maps
125    /// aren't merged: concatenation only copies the references, while merging would read and copy
126    /// every entry of every map for each concatenated result.
127    pub async_loader_availability: Vec<ResolvedVc<AsyncLoaderAvailabilityMap>>,
128}
129
130impl ChunkGroupResult {
131    pub fn empty() -> Vc<Self> {
132        ChunkGroupResult {
133            assets: ResolvedVc::cell(vec![]),
134            referenced_assets: ResolvedVc::cell(vec![]),
135            references: ResolvedVc::cell(vec![]),
136            availability_info: AvailabilityInfo::root(),
137            chunk_group_bootstrap_params: None,
138            async_loader_availability: vec![],
139        }
140        .cell()
141    }
142
143    pub fn empty_resolved() -> ResolvedVc<Self> {
144        ChunkGroupResult {
145            assets: ResolvedVc::cell(vec![]),
146            referenced_assets: ResolvedVc::cell(vec![]),
147            references: ResolvedVc::cell(vec![]),
148            availability_info: AvailabilityInfo::root(),
149            chunk_group_bootstrap_params: None,
150            async_loader_availability: vec![],
151        }
152        .resolved_cell()
153    }
154
155    /// The availability the async loader of `module` was created with by this result's chunk
156    /// groups, so that a loader for `module` with exactly the chunks they load at runtime can be
157    /// created elsewhere (e.g. for a manifest). `None` when none of them created one: the loader
158    /// was then created by another chunk group (e.g. an available one, or the async chunk group of
159    /// a module they load), or the caller's module graph and this result are momentarily out of
160    /// sync during recomputation.
161    ///
162    /// The first chunk group, in load order, that created an async loader for `module` wins.
163    /// Usually only one did: a chunk group doesn't create an async loader that an available chunk
164    /// group already created. But a later chunk group doesn't always see an earlier one as
165    /// available, so several can create one. All of these loaders share one module id, and the
166    /// runtime keeps the first module factory registered for an id, so the loader of the first
167    /// chunk group loaded is the one used.
168    pub async fn find_async_loader_availability_info(
169        &self,
170        module: ResolvedVc<Box<dyn ChunkableModule>>,
171    ) -> Result<Option<AvailabilityInfo>> {
172        for chunk_group in &self.async_loader_availability {
173            if let Some(availability_info) = chunk_group.get(&module).await? {
174                return Ok(Some(*availability_info));
175            }
176        }
177        Ok(None)
178    }
179}
180
181#[turbo_tasks::value(transparent)]
182pub struct OptionChunkGroupResult(Option<ResolvedVc<ChunkGroupResult>>);
183
184#[turbo_tasks::value_impl]
185impl ChunkGroupResult {
186    #[turbo_tasks::function]
187    pub fn output_assets_with_referenced(&self) -> Vc<OutputAssetsWithReferenced> {
188        OutputAssetsWithReferenced {
189            assets: self.assets,
190            referenced_assets: self.referenced_assets,
191            references: self.references,
192        }
193        .cell()
194    }
195
196    #[turbo_tasks::function]
197    pub async fn concatenate(&self, next: Vc<Self>) -> Result<Vc<Self>> {
198        let next = next.await?;
199        Ok(ChunkGroupResult {
200            assets: self.assets.concatenate(*next.assets).to_resolved().await?,
201            referenced_assets: self
202                .referenced_assets
203                .concatenate(*next.referenced_assets)
204                .to_resolved()
205                .await?,
206            references: self
207                .references
208                .concatenate(*next.references)
209                .to_resolved()
210                .await?,
211            availability_info: next.availability_info,
212            chunk_group_bootstrap_params: next.chunk_group_bootstrap_params.clone(),
213            async_loader_availability: self
214                .async_loader_availability
215                .iter()
216                .chain(&next.async_loader_availability)
217                .copied()
218                .collect(),
219        }
220        .cell())
221    }
222
223    #[turbo_tasks::function]
224    pub async fn all_assets(&self) -> Result<Vc<OutputAssets>> {
225        Ok(Vc::cell(
226            expand_output_assets(
227                self.assets
228                    .await?
229                    .into_iter()
230                    .chain(self.referenced_assets.await?)
231                    .map(ExpandOutputAssetsInput::Asset)
232                    .chain(
233                        self.references
234                            .await?
235                            .into_iter()
236                            .map(ExpandOutputAssetsInput::Reference),
237                    ),
238                false,
239            )
240            .await?,
241        ))
242    }
243
244    /// Returns only primary asset entries. Doesn't expand OutputAssets. Doesn't return referenced
245    /// assets.
246    #[turbo_tasks::function]
247    pub fn primary_assets(&self) -> Vc<OutputAssets> {
248        *self.assets
249    }
250
251    #[turbo_tasks::function]
252    pub async fn referenced_assets(&self) -> Result<Vc<OutputAssets>> {
253        Ok(Vc::cell(
254            expand_output_assets(
255                self.referenced_assets
256                    .await?
257                    .into_iter()
258                    .map(ExpandOutputAssetsInput::Asset)
259                    .chain(
260                        self.references
261                            .await?
262                            .into_iter()
263                            .map(ExpandOutputAssetsInput::Reference),
264                    ),
265                false,
266            )
267            .await?,
268        ))
269    }
270}
271
272#[turbo_tasks::value(shared)]
273pub struct EntryChunkGroupResult {
274    pub asset: ResolvedVc<Box<dyn OutputAsset>>,
275    pub availability_info: AvailabilityInfo,
276}
277
278#[turbo_tasks::task_input]
279#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)]
280pub struct ChunkingConfig {
281    /// Try to avoid creating more than 1 chunk smaller than this size.
282    /// It merges multiple small chunks into bigger ones to avoid that.
283    pub min_chunk_size: usize,
284
285    /// Try to avoid creating more than this number of chunks per group.
286    /// It merges multiple chunks into bigger ones to avoid that.
287    pub max_chunk_count_per_group: usize,
288
289    /// Never merges chunks bigger than this size with other chunks.
290    /// This makes sure that code in big chunks is not duplicated in multiple chunks.
291    /// `0` means no limit. When `max_chunk_size` is set, this is limited to `max_chunk_size` (see
292    /// [`ChunkingConfig::normalized`]).
293    pub max_merge_chunk_size: usize,
294
295    /// Best-effort upper bound on the estimated size of a chunk. `0` disables the limit. Not used
296    /// for style chunk types.
297    ///
298    /// Merging never creates chunks bigger than this size, and chunks bigger than this size are
299    /// never merged. Chunks that are too big on their own are split deterministically (by sorting
300    /// their chunk items by module identifier) into chunks that are not bigger than this size,
301    /// preferring chunks of at least `min_chunk_size`. To stay below the limit, chunks may be
302    /// smaller than `min_chunk_size` and there may be more chunks than
303    /// `max_chunk_count_per_group`. Only a single chunk item bigger than this size can still
304    /// produce a bigger chunk.
305    ///
306    /// This is raised to at least `3 * min_chunk_size` (see [`ChunkingConfig::normalized`]).
307    pub max_chunk_size: usize,
308
309    /// When enabled, a merged chunk also emits its constituent component chunks (referenced,
310    /// loaded on demand) so the runtime can fetch an individual component chunk instead of the
311    /// whole merged chunk when it is already cached.
312    pub generate_component_chunks: bool,
313
314    /// Minimum size for a component chunk to be emitted on its own when
315    /// `generate_component_chunks` is enabled. Component chunks smaller than this are folded
316    /// into a single remainder component chunk.
317    pub min_component_chunk_size: usize,
318
319    /// Selects the algorithm used to compute
320    /// [`crate::module_graph::style_groups::StyleGroups`]. Only consulted for the CSS chunk
321    /// type.
322    pub style_groups_algorithm: StyleGroupsAlgorithm,
323
324    /// First-page-load priority as an integer percentage (`0..=100`), or `None` to use the
325    /// default. Used by the production chunker's merge heuristics.
326    pub first_page_load_priority: Option<u32>,
327
328    /// Priority boost as an integer percentage (e.g. `150` for a 1.5x boost), or `None` to use the
329    /// default. Used by the production chunker's merge heuristics.
330    pub priority_boost_percent: Option<u32>,
331
332    /// Estimated request cost in bytes, or `None` to use the default. Used by the production
333    /// chunker's merge heuristics.
334    pub request_cost: Option<u64>,
335
336    #[allow(dead_code)]
337    pub placeholder_for_future_extensions: (),
338}
339
340#[turbo_tasks::value(transparent)]
341pub struct ChunkingConfigs(FxHashMap<ResolvedVc<Box<dyn ChunkType>>, ChunkingConfig>);
342
343impl ChunkingConfig {
344    /// Returns this config with consistent size limits. When `max_chunk_size` is set (not `0`):
345    ///
346    /// 1. `max_chunk_size` is raised to `3 * min_chunk_size` if it is smaller, so that chunks can
347    ///    be split into chunks of at least `min_chunk_size`.
348    /// 2. `max_merge_chunk_size` is lowered to `max_chunk_size` if it is bigger or `0` (no limit),
349    ///    since chunks bigger than `max_chunk_size` are never merged anyway.
350    ///
351    /// The production chunking algorithm always uses the normalized config. Compare with the
352    /// original config to find out whether anything was adjusted.
353    pub fn normalized(&self) -> Self {
354        let mut config = self.clone();
355        if config.max_chunk_size != 0 {
356            config.max_chunk_size = config
357                .max_chunk_size
358                .max(config.min_chunk_size.saturating_mul(3));
359            if config.max_merge_chunk_size == 0
360                || config.max_merge_chunk_size > config.max_chunk_size
361            {
362                config.max_merge_chunk_size = config.max_chunk_size;
363            }
364        }
365        config
366    }
367}
368
369/// turbopack-browser needs to know the original
370/// source of the hmr chunk list to properly map to a
371/// EcmascriptDevChunkListSource and provide the correct
372/// updates. This maps one to one with that.
373/// We could consider lifting EcmascriptDevChunkListSource to
374/// core instead if this grows. Or using this type in browser instead.
375#[turbo_tasks::task_input]
376#[derive(Eq, PartialEq, Debug, Clone, Copy, Hash, Serialize, Deserialize, Encode, Decode)]
377pub enum HmrChunkListSource {
378    Entry,
379    Dynamic,
380}
381
382#[turbo_tasks::value(shared)]
383#[derive(Debug, Clone, Copy, Hash, Default, Deserialize)]
384pub enum SourceMapSourceType {
385    AbsoluteFileUri,
386    RelativeUri,
387    #[default]
388    TurbopackUri,
389}
390
391#[turbo_tasks::value(transparent, cell = "keyed")]
392#[allow(clippy::type_complexity)]
393/// For each reference, the targets it resolves to that were dropped as unused. One reference can
394/// resolve to several targets, which are dropped independently.
395pub struct UnusedReferences(
396    FxHashMap<ResolvedVc<Box<dyn ModuleReference>>, FxHashSet<ResolvedVc<Box<dyn Module>>>>,
397);
398
399#[turbo_tasks::value(shared)]
400#[derive(Debug, Clone, Default)]
401pub struct WorkerConfigurationOptions {
402    /// The worker base-path override. When `Some`, takes precedence over
403    /// `chunk_base_path` for the worker entrypoint URL and the module chunks
404    /// loaded inside the worker.
405    pub asset_prefix: Option<RcStr>,
406    /// The list of global variable names to forward to workers. These globals
407    /// are read from `globalThis` at worker creation time and passed to the
408    /// worker via URL params.
409    pub forwarded_globals: Vec<RcStr>,
410}
411
412/// A context for the chunking that influences the way chunks are created
413#[turbo_tasks::value_trait]
414pub trait ChunkingContext {
415    #[turbo_tasks::function]
416    async fn source_map_generation_options(
417        self: Vc<Self>,
418    ) -> Result<Vc<SourceMapGenerationOptions>> {
419        Ok(SourceMapGenerationOptions::from_emitted(*self.emitted_source_map_type().await?).cell())
420    }
421    #[turbo_tasks::function]
422    fn emitted_source_map_type(self: Vc<Self>) -> Vc<OptionSourceMapType>;
423    #[turbo_tasks::function]
424    fn name(self: Vc<Self>) -> Vc<RcStr>;
425    #[turbo_tasks::function]
426    fn source_map_source_type(self: Vc<Self>) -> Vc<SourceMapSourceType>;
427    /// The root path of the project
428    #[turbo_tasks::function]
429    fn root_path(self: Vc<Self>) -> Vc<FileSystemPath>;
430    /// The output root path in the output filesystem
431    #[turbo_tasks::function]
432    fn output_root(self: Vc<Self>) -> Vc<FileSystemPath>;
433    /// A relative path how to reach the root path from the output root. This is used to compute
434    /// original paths at runtime relative to the output files. e. g. import.meta.url needs that.
435    #[turbo_tasks::function]
436    fn output_root_to_root_path(self: Vc<Self>) -> Vc<RcStr>;
437
438    // TODO remove this, a chunking context should not be bound to a specific
439    // environment since this can change due to transitions in the module graph
440    #[turbo_tasks::function]
441    fn environment(self: Vc<Self>) -> Vc<Environment>;
442
443    /// The path to the folder where all chunks are placed. This can be used to compute relative
444    /// paths.
445    #[turbo_tasks::function]
446    fn chunk_root_path(self: Vc<Self>) -> Vc<FileSystemPath>;
447
448    #[turbo_tasks::function]
449    fn chunk_loading(self: Vc<Self>) -> Vc<ChunkLoading> {
450        self.environment().chunk_loading()
451    }
452
453    // TODO(alexkirsz) Remove this from the chunking context. This should be at the
454    // discretion of chunking context implementors. However, we currently use this
455    // in a couple of places in `turbopack-css`, so we need to remove that
456    // dependency first.
457    #[turbo_tasks::function]
458    fn chunk_path(
459        self: Vc<Self>,
460        asset: Option<Vc<Box<dyn Asset>>>,
461        ident: Vc<AssetIdent>,
462        content_hashing_prefix: Option<RcStr>,
463        extension: RcStr,
464    ) -> Vc<FileSystemPath>;
465
466    /// Reference Source Map Assets for chunks
467    #[turbo_tasks::function]
468    fn reference_chunk_source_maps(self: Vc<Self>, chunk: Vc<Box<dyn OutputAsset>>) -> Vc<bool>;
469
470    /// Returns a URL (relative or absolute, depending on the asset prefix) to
471    /// the static asset based on its `ident`.
472    /// The `tag` is an arbitrary string that can be used to distinguish
473    /// different usages of the same asset (e.g. different base paths).
474    #[turbo_tasks::function]
475    fn asset_url(self: Vc<Self>, ident: FileSystemPath, tag: Option<RcStr>) -> Result<Vc<RcStr>>;
476
477    #[turbo_tasks::function]
478    fn service_worker_scope_base_path(self: Vc<Self>) -> Vc<RcStr> {
479        Vc::cell(RcStr::default())
480    }
481
482    #[turbo_tasks::function]
483    fn asset_path(
484        self: Vc<Self>,
485        content: Vc<AssetContent>,
486        original_asset_ident: Vc<AssetIdent>,
487        tag: Option<RcStr>,
488    ) -> Vc<FileSystemPath>;
489
490    /// Returns the URL behavior for a given tag.
491    /// This determines how asset URLs are suffixed (e.g., for deployment IDs).
492    #[turbo_tasks::function]
493    fn url_behavior(self: Vc<Self>, _tag: Option<RcStr>) -> Vc<UrlBehavior> {
494        UrlBehavior {
495            suffix: AssetSuffix::Inferred,
496            static_suffix: ResolvedVc::cell(None),
497        }
498        .cell()
499    }
500
501    #[turbo_tasks::function]
502    fn chunking_configs(self: Vc<Self>) -> Vc<ChunkingConfigs> {
503        Vc::cell(Default::default())
504    }
505
506    #[turbo_tasks::function]
507    fn batching_config(self: Vc<Self>) -> Vc<BatchingConfig> {
508        BatchingConfig::new(BatchingConfig {
509            ..Default::default()
510        })
511    }
512
513    /// Whether async modules should create an new availability boundary and therefore nested async
514    /// modules include less modules. Enabling this will lead to better optimized async chunks,
515    /// but it will require to compute all possible paths in the application, which might lead to
516    /// many combinations.
517    #[turbo_tasks::function]
518    fn is_nested_async_availability_enabled(self: Vc<Self>) -> Vc<bool> {
519        Vc::cell(false)
520    }
521
522    /// Whether to use `MergeableModule` to merge modules if possible.
523    #[turbo_tasks::function]
524    fn is_module_merging_enabled(self: Vc<Self>) -> Vc<bool> {
525        Vc::cell(false)
526    }
527
528    /// Whether to include information about the content of the chunk into the runtime, to allow
529    /// more incremental loading of individual chunk items.
530    #[turbo_tasks::function]
531    fn is_dynamic_chunk_content_loading_enabled(self: Vc<Self>) -> Vc<bool> {
532        Vc::cell(false)
533    }
534
535    /// Returns the list of emit options for this chunking context.
536    ///
537    /// Emit options allow crate-specific configuration (e.g., SWC minify options,
538    /// CSS minification settings) without requiring turbopack-core to depend on those crates.
539    /// Consumers fall back to their defaults when no option of the requested type is present.
540    #[turbo_tasks::function]
541    fn emit_options(self: Vc<Self>) -> Vc<EmitOptions>;
542
543    #[turbo_tasks::function]
544    fn should_use_absolute_url_references(self: Vc<Self>) -> Vc<bool> {
545        Vc::cell(false)
546    }
547
548    #[turbo_tasks::function]
549    fn async_loader_chunk_item(
550        &self,
551        module: Vc<Box<dyn ChunkableModule>>,
552        module_graph: Vc<ModuleGraph>,
553        availability_info: AvailabilityInfo,
554    ) -> Vc<Box<dyn ChunkItem>>;
555    #[turbo_tasks::function]
556    fn async_loader_chunk_item_ident(&self, module: Vc<Box<dyn ChunkableModule>>)
557    -> Vc<AssetIdent>;
558
559    /// Places a synthesized chunk item into a standalone output chunk without module graph
560    /// traversal.
561    #[turbo_tasks::function]
562    fn standalone_chunk(
563        self: Vc<Self>,
564        chunk_item: ResolvedVc<Box<dyn ChunkItem>>,
565    ) -> Vc<Box<dyn OutputAsset>>;
566
567    /// Chunks the chunk groups identified by `chunk_groups` together as one chunk group, in a
568    /// single task.
569    ///
570    /// The groups must be registered in `module_graph`'s
571    /// [`ChunkGroupInfo`](crate::module_graph::chunk_group_info::ChunkGroupInfo); their contents
572    /// (e.g. the entries of a merged group) are looked up there, so callers only name the groups.
573    /// The modules of all groups are collected once each and chunked together, and the resulting
574    /// availability includes every group. `chunk_groups` must not be empty.
575    #[turbo_tasks::function]
576    fn chunk_group(
577        self: Vc<Self>,
578        ident: Vc<AssetIdent>,
579        chunk_groups: SmallVec<[ChunkGroupKey; 1]>,
580        module_graph: Vc<ModuleGraph>,
581        availability_info: AvailabilityInfo,
582    ) -> Vc<ChunkGroupResult>;
583
584    /// Like [`Self::chunk_group`] for a single `chunk_group`, but additionally produces an
585    /// evaluate chunk (and, in dev, a chunk-list register chunk) that bootstraps and runs
586    /// `chunk_group`'s entries.
587    ///
588    /// `extra_chunks` are not part of this chunk group's module graph, but they
589    /// are loaded alongside the entries (and tracked in the chunk-list register
590    /// chunk for HMR) — used to extend the entry's HMR-tracked chunks with
591    /// chunks computed elsewhere (e.g. app-router client references).
592    #[turbo_tasks::function]
593    fn evaluated_chunk_group(
594        self: Vc<Self>,
595        ident: Vc<AssetIdent>,
596        chunk_group: ChunkGroupKey,
597        module_graph: Vc<ModuleGraph>,
598        extra_chunks: Vc<OutputAssets>,
599        availability_info: AvailabilityInfo,
600    ) -> Vc<ChunkGroupResult>;
601
602    /// In development, produces a standalone HMR chunk-list register chunk
603    /// that tracks `chunks` for hot-module-replacement without producing an
604    /// evaluate chunk. Returns `None` (empty vec) outside dev or when HMR is
605    /// disabled. Used to register a page-specific chunk list that covers
606    /// client-reference chunks built outside the shared module graph.
607    #[turbo_tasks::function]
608    fn hmr_chunk_list(
609        self: Vc<Self>,
610        _ident: Vc<AssetIdent>,
611        _chunks: Vc<OutputAssets>,
612        _source: HmrChunkListSource,
613    ) -> Vc<OutputAssets> {
614        OutputAssets::empty()
615    }
616
617    /// Generates an output chunk that:
618    /// * loads the given extra_chunks in addition to the generated chunks; and
619    /// * evaluates the given assets; and
620    /// * exports the result of evaluating the last module as a CommonJS default export.
621    #[turbo_tasks::function]
622    fn entry_chunk_group(
623        self: Vc<Self>,
624        path: FileSystemPath,
625        chunk_group: ChunkGroupKey,
626        module_graph: Vc<ModuleGraph>,
627        extra_chunks: Vc<OutputAssets>,
628        extra_referenced_assets: Vc<OutputAssets>,
629        availability_info: AvailabilityInfo,
630    ) -> Result<Vc<EntryChunkGroupResult>>;
631
632    #[turbo_tasks::function]
633    async fn chunk_item_id_strategy(self: Vc<Self>) -> Result<Vc<ModuleIdStrategy>>;
634
635    #[turbo_tasks::function]
636    async fn module_export_usage(
637        self: Vc<Self>,
638        module: Vc<Box<dyn Module>>,
639    ) -> Result<Vc<ModuleExportUsage>>;
640
641    #[turbo_tasks::function]
642    async fn unused_references(self: Vc<Self>) -> Result<Vc<UnusedReferences>>;
643
644    /// Returns whether debug IDs are enabled for this chunking context.
645    #[turbo_tasks::function]
646    fn debug_ids_enabled(self: Vc<Self>) -> Vc<bool>;
647
648    /// Returns the worker-related configuration: the base-path override and the
649    /// list of globals to forward to workers.
650    #[turbo_tasks::function]
651    fn worker_configuration_options(self: Vc<Self>) -> Vc<WorkerConfigurationOptions> {
652        WorkerConfigurationOptions::default().cell()
653    }
654
655    /// Returns the worker entrypoint for this chunking context.
656    #[turbo_tasks::function]
657    async fn worker_entrypoint(self: Vc<Self>) -> Result<Vc<Box<dyn OutputAsset>>> {
658        turbobail!("Worker entrypoint is not supported by {}", self.name());
659    }
660}
661pub trait ChunkingContextExt {
662    fn root_chunk_group(
663        self: Vc<Self>,
664        ident: Vc<AssetIdent>,
665        chunk_group: ChunkGroupKey,
666        module_graph: Vc<ModuleGraph>,
667    ) -> Vc<ChunkGroupResult>
668    where
669        Self: Send;
670
671    fn root_chunk_group_assets(
672        self: Vc<Self>,
673        ident: Vc<AssetIdent>,
674        chunk_group: ChunkGroupKey,
675        module_graph: Vc<ModuleGraph>,
676    ) -> Vc<OutputAssetsWithReferenced>
677    where
678        Self: Send;
679
680    fn evaluated_chunk_group_assets(
681        self: Vc<Self>,
682        ident: Vc<AssetIdent>,
683        chunk_group: ChunkGroupKey,
684        module_graph: Vc<ModuleGraph>,
685        extra_chunks: Vc<OutputAssets>,
686        availability_info: AvailabilityInfo,
687    ) -> Vc<OutputAssetsWithReferenced>
688    where
689        Self: Send;
690
691    fn entry_chunk_group_asset(
692        self: Vc<Self>,
693        path: FileSystemPath,
694        chunk_group: ChunkGroupKey,
695        module_graph: Vc<ModuleGraph>,
696        extra_chunks: Vc<OutputAssets>,
697        extra_referenced_assets: Vc<OutputAssets>,
698        availability_info: AvailabilityInfo,
699    ) -> Vc<Box<dyn OutputAsset>>
700    where
701        Self: Send;
702
703    fn root_entry_chunk_group(
704        self: Vc<Self>,
705        path: FileSystemPath,
706        chunk_group: ChunkGroupKey,
707        module_graph: Vc<ModuleGraph>,
708        extra_chunks: Vc<OutputAssets>,
709        extra_referenced_assets: Vc<OutputAssets>,
710    ) -> Vc<EntryChunkGroupResult>
711    where
712        Self: Send;
713
714    fn root_entry_chunk_group_asset(
715        self: Vc<Self>,
716        path: FileSystemPath,
717        chunk_group: ChunkGroupKey,
718        module_graph: Vc<ModuleGraph>,
719        extra_chunks: Vc<OutputAssets>,
720        extra_referenced_assets: Vc<OutputAssets>,
721    ) -> Vc<Box<dyn OutputAsset>>
722    where
723        Self: Send;
724
725    fn chunk_group_assets(
726        self: Vc<Self>,
727        ident: Vc<AssetIdent>,
728        chunk_group: ChunkGroupKey,
729        module_graph: Vc<ModuleGraph>,
730        availability_info: AvailabilityInfo,
731    ) -> Vc<OutputAssetsWithReferenced>
732    where
733        Self: Send;
734
735    /// Computes the relative path from the chunk output root to the project root.
736    ///
737    /// This is used to compute relative paths for source maps in certain configurations.
738    fn relative_path_from_chunk_root_to_project_root(self: Vc<Self>) -> Vc<RcStr>
739    where
740        Self: Send;
741}
742
743impl<T: ChunkingContext + Send + Upcast<Box<dyn ChunkingContext>>> ChunkingContextExt for T {
744    fn root_chunk_group(
745        self: Vc<Self>,
746        ident: Vc<AssetIdent>,
747        chunk_group: ChunkGroupKey,
748        module_graph: Vc<ModuleGraph>,
749    ) -> Vc<ChunkGroupResult> {
750        self.chunk_group(
751            ident,
752            smallvec![chunk_group],
753            module_graph,
754            AvailabilityInfo::root(),
755        )
756    }
757
758    fn root_chunk_group_assets(
759        self: Vc<Self>,
760        ident: Vc<AssetIdent>,
761        chunk_group: ChunkGroupKey,
762        module_graph: Vc<ModuleGraph>,
763    ) -> Vc<OutputAssetsWithReferenced> {
764        root_chunk_group_assets(
765            Vc::upcast_non_strict(self),
766            ident,
767            chunk_group,
768            module_graph,
769        )
770    }
771
772    fn evaluated_chunk_group_assets(
773        self: Vc<Self>,
774        ident: Vc<AssetIdent>,
775        chunk_group: ChunkGroupKey,
776        module_graph: Vc<ModuleGraph>,
777        extra_chunks: Vc<OutputAssets>,
778        availability_info: AvailabilityInfo,
779    ) -> Vc<OutputAssetsWithReferenced> {
780        evaluated_chunk_group_assets(
781            Vc::upcast_non_strict(self),
782            ident,
783            chunk_group,
784            module_graph,
785            extra_chunks,
786            availability_info,
787        )
788    }
789
790    fn entry_chunk_group_asset(
791        self: Vc<Self>,
792        path: FileSystemPath,
793        chunk_group: ChunkGroupKey,
794        module_graph: Vc<ModuleGraph>,
795        extra_chunks: Vc<OutputAssets>,
796        extra_referenced_assets: Vc<OutputAssets>,
797        availability_info: AvailabilityInfo,
798    ) -> Vc<Box<dyn OutputAsset>> {
799        entry_chunk_group_asset(
800            Vc::upcast_non_strict(self),
801            path,
802            chunk_group,
803            module_graph,
804            extra_chunks,
805            extra_referenced_assets,
806            availability_info,
807        )
808    }
809
810    fn root_entry_chunk_group(
811        self: Vc<Self>,
812        path: FileSystemPath,
813        chunk_group: ChunkGroupKey,
814        module_graph: Vc<ModuleGraph>,
815        extra_chunks: Vc<OutputAssets>,
816        extra_referenced_assets: Vc<OutputAssets>,
817    ) -> Vc<EntryChunkGroupResult> {
818        self.entry_chunk_group(
819            path,
820            chunk_group,
821            module_graph,
822            extra_chunks,
823            extra_referenced_assets,
824            AvailabilityInfo::root(),
825        )
826    }
827
828    fn root_entry_chunk_group_asset(
829        self: Vc<Self>,
830        path: FileSystemPath,
831        chunk_group: ChunkGroupKey,
832        module_graph: Vc<ModuleGraph>,
833        extra_chunks: Vc<OutputAssets>,
834        extra_referenced_assets: Vc<OutputAssets>,
835    ) -> Vc<Box<dyn OutputAsset>> {
836        entry_chunk_group_asset(
837            Vc::upcast_non_strict(self),
838            path,
839            chunk_group,
840            module_graph,
841            extra_chunks,
842            extra_referenced_assets,
843            AvailabilityInfo::root(),
844        )
845    }
846
847    fn chunk_group_assets(
848        self: Vc<Self>,
849        ident: Vc<AssetIdent>,
850        chunk_group: ChunkGroupKey,
851        module_graph: Vc<ModuleGraph>,
852        availability_info: AvailabilityInfo,
853    ) -> Vc<OutputAssetsWithReferenced> {
854        chunk_group_assets(
855            Vc::upcast_non_strict(self),
856            ident,
857            chunk_group,
858            module_graph,
859            availability_info,
860        )
861    }
862
863    fn relative_path_from_chunk_root_to_project_root(self: Vc<Self>) -> Vc<RcStr> {
864        relative_path_from_chunk_root_to_project_root(Vc::upcast_non_strict(self))
865    }
866}
867
868#[turbo_tasks::function]
869async fn relative_path_from_chunk_root_to_project_root(
870    chunking_context: Vc<Box<dyn ChunkingContext>>,
871) -> Result<Vc<RcStr>> {
872    // Example,
873    //   project root: /project/root
874    //   output root: /project/root/dist
875    //   chunk root path: /project/root/dist/ssr/chunks
876    //   output_root_to_chunk_root: ../
877    //
878    // Example2,
879    //   project root: /project/root
880    //   output root: /project/out
881    //   chunk root path: /project/out/ssr/chunks
882    //   output_root_to_chunk_root: ../root
883    //
884    // From that we want to return  ../../../root to get from a path in `chunks` to a path in the
885    // project root.
886
887    let chunk_root_path = chunking_context.chunk_root_path().await?;
888    let output_root = chunking_context.output_root().await?;
889    let chunk_to_output_root = chunk_root_path.get_relative_path_to(&output_root);
890    let Some(chunk_to_output_root) = chunk_to_output_root else {
891        turbobail!(
892            "expected chunk_root_path: {} to be inside of output_root: {}",
893            chunking_context.chunk_root_path(),
894            chunking_context.output_root()
895        );
896    };
897    let output_root_to_chunk_root_path = chunking_context.output_root_to_root_path().await?;
898
899    // Note we cannot use `normalize_path` here since it rejects paths that start with `../`
900    Ok(Vc::cell(
901        format!(
902            "{}/{}",
903            chunk_to_output_root, output_root_to_chunk_root_path
904        )
905        .into(),
906    ))
907}
908
909#[turbo_tasks::function]
910fn root_chunk_group_assets(
911    chunking_context: Vc<Box<dyn ChunkingContext>>,
912    ident: Vc<AssetIdent>,
913    chunk_group: ChunkGroupKey,
914    module_graph: Vc<ModuleGraph>,
915) -> Vc<OutputAssetsWithReferenced> {
916    chunking_context
917        .root_chunk_group(ident, chunk_group, module_graph)
918        .output_assets_with_referenced()
919}
920
921#[turbo_tasks::function]
922fn evaluated_chunk_group_assets(
923    chunking_context: Vc<Box<dyn ChunkingContext>>,
924    ident: Vc<AssetIdent>,
925    chunk_group: ChunkGroupKey,
926    module_graph: Vc<ModuleGraph>,
927    extra_chunks: Vc<OutputAssets>,
928    availability_info: AvailabilityInfo,
929) -> Vc<OutputAssetsWithReferenced> {
930    chunking_context
931        .evaluated_chunk_group(
932            ident,
933            chunk_group,
934            module_graph,
935            extra_chunks,
936            availability_info,
937        )
938        .output_assets_with_referenced()
939}
940
941#[turbo_tasks::function]
942async fn entry_chunk_group_asset(
943    chunking_context: Vc<Box<dyn ChunkingContext>>,
944    path: FileSystemPath,
945    chunk_group: ChunkGroupKey,
946    module_graph: Vc<ModuleGraph>,
947    extra_chunks: Vc<OutputAssets>,
948    extra_referenced_assets: Vc<OutputAssets>,
949    availability_info: AvailabilityInfo,
950) -> Result<Vc<Box<dyn OutputAsset>>> {
951    Ok(*chunking_context
952        .entry_chunk_group(
953            path,
954            chunk_group,
955            module_graph,
956            extra_chunks,
957            extra_referenced_assets,
958            availability_info,
959        )
960        .await?
961        .asset)
962}
963
964#[turbo_tasks::function]
965fn chunk_group_assets(
966    chunking_context: Vc<Box<dyn ChunkingContext>>,
967    ident: Vc<AssetIdent>,
968    chunk_group: ChunkGroupKey,
969    module_graph: Vc<ModuleGraph>,
970    availability_info: AvailabilityInfo,
971) -> Vc<OutputAssetsWithReferenced> {
972    chunking_context
973        .chunk_group(
974            ident,
975            smallvec![chunk_group],
976            module_graph,
977            availability_info,
978        )
979        .output_assets_with_referenced()
980}
981
982#[cfg(test)]
983mod tests {
984    use super::ChunkingConfig;
985
986    fn config(min: usize, merge: usize, max: usize) -> ChunkingConfig {
987        ChunkingConfig {
988            min_chunk_size: min,
989            max_merge_chunk_size: merge,
990            max_chunk_size: max,
991            ..Default::default()
992        }
993    }
994
995    fn limits(config: &ChunkingConfig) -> (usize, usize, usize) {
996        (
997            config.min_chunk_size,
998            config.max_merge_chunk_size,
999            config.max_chunk_size,
1000        )
1001    }
1002
1003    #[test]
1004    fn normalized_keeps_valid_configs() {
1005        let valid = config(50_000, 200_000, 1_000_000);
1006        assert_eq!(valid.normalized(), valid);
1007        // Exactly at the limits.
1008        let valid = config(100, 300, 300);
1009        assert_eq!(valid.normalized(), valid);
1010    }
1011
1012    #[test]
1013    fn normalized_ignores_disabled_max_chunk_size() {
1014        let disabled = config(50_000, 0, 0);
1015        assert_eq!(disabled.normalized(), disabled);
1016        let disabled = config(50_000, 200_000, 0);
1017        assert_eq!(disabled.normalized(), disabled);
1018    }
1019
1020    #[test]
1021    fn normalized_raises_max_chunk_size() {
1022        assert_eq!(limits(&config(100, 200, 200).normalized()), (100, 200, 300));
1023    }
1024
1025    #[test]
1026    fn normalized_lowers_max_merge_chunk_size() {
1027        assert_eq!(limits(&config(10, 500, 200).normalized()), (10, 200, 200));
1028        // `0` means no limit, which is bigger than any `max_chunk_size`.
1029        assert_eq!(limits(&config(10, 0, 200).normalized()), (10, 200, 200));
1030    }
1031
1032    #[test]
1033    fn normalized_lowers_max_merge_chunk_size_to_raised_max_chunk_size() {
1034        assert_eq!(
1035            limits(&config(100, 1_000, 200).normalized()),
1036            (100, 300, 300)
1037        );
1038    }
1039}