Unverified Commit b0d33e9a authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Add support for single-entry chunks (#94727)

This PR adds support for generating single-entry chunks, based on this
plan: https://gist.github.com/bgw/356344ea6fb0e897647c478d01c096d3 up
until Step 6.

Also adds a basic snapshot test to capture this behaviour.

---------
Co-authored-by: 's avatarBenjamin Woodruff <benjamin.woodruff@vercel.com>
parent b132f1dc
use anyhow::{Context, Result, bail};
use async_trait::async_trait;
use tracing::Instrument;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, FxIndexSet, ResolvedVc, TryJoinIterExt, Upcast, ValueToString, Vc};
use turbo_tasks::{
FxIndexMap, FxIndexSet, ResolvedVc, TryJoinIterExt, Upcast, ValueToString, ValueToStringRef, Vc,
};
use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_hash::HashAlgorithm;
use turbopack_core::{
......@@ -16,8 +19,9 @@ use turbopack_core::{
chunk_group::{MakeChunkGroupResult, make_chunk_group},
chunk_id_strategy::ModuleIdStrategy,
},
environment::Environment,
environment::{ChunkLoading, Environment},
ident::AssetIdent,
issue::{Issue, IssueExt, IssueSeverity, IssueStage, StyledString},
module::Module,
module_graph::{
ModuleGraph,
......@@ -28,14 +32,17 @@ use turbopack_core::{
};
use turbopack_ecmascript::{
async_chunk::module::AsyncLoaderModule,
chunk::EcmascriptChunk,
chunk::{EcmascriptChunk, EcmascriptChunkContent, EcmascriptChunkType},
manifest::{chunk_asset::ManifestAsyncModule, loader_module::ManifestLoaderModule},
};
use turbopack_ecmascript_runtime::RuntimeType;
use crate::ecmascript::{
chunk::EcmascriptBrowserChunk,
evaluate::chunk::EcmascriptBrowserEvaluateChunk,
evaluate::{
chunk::EcmascriptBrowserEvaluateChunk,
single_entry_chunk::EcmascriptBrowserSingleEntryChunk,
},
list::asset::{EcmascriptDevChunkList, EcmascriptDevChunkListSource},
worker::EcmascriptBrowserWorkerEntrypoint,
};
......@@ -235,6 +242,23 @@ impl BrowserChunkingContextBuilder {
self
}
pub async fn single_chunk(mut self) -> Result<Self> {
self.chunking_context.single_chunk = true;
// Force every ECMAScript chunk item into a single output chunk.
let ecmascript_ty: ResolvedVc<Box<dyn ChunkType>> =
ResolvedVc::upcast(Vc::<EcmascriptChunkType>::default().to_resolved().await?);
self.chunking_context.chunking_configs.push((
ecmascript_ty,
ChunkingConfig {
min_chunk_size: usize::MAX,
max_chunk_count_per_group: 1,
max_merge_chunk_size: usize::MAX,
..Default::default()
},
));
Ok(self)
}
pub fn build(self) -> Vc<BrowserChunkingContext> {
BrowserChunkingContext::cell(self.chunking_context)
}
......@@ -343,6 +367,9 @@ pub struct BrowserChunkingContext {
cross_origin: CrossOrigin,
/// The retry policy for transient chunk load failures in the browser runtime.
chunk_load_retry: ChunkLoadRetry,
/// When enabled, module closure is inlined into a single output chunk
/// (no runtime chunk loading).
single_chunk: bool,
}
impl BrowserChunkingContext {
......@@ -398,6 +425,7 @@ impl BrowserChunkingContext {
hash_salt: ResolvedVc::cell(RcStr::default()),
cross_origin: Default::default(),
chunk_load_retry: Default::default(),
single_chunk: false,
},
}
}
......@@ -717,8 +745,8 @@ impl ChunkingContext for BrowserChunkingContext {
}
#[turbo_tasks::function]
fn chunking_configs(&self) -> Result<Vc<ChunkingConfigs>> {
Ok(Vc::cell(self.chunking_configs.iter().cloned().collect()))
fn chunking_configs(&self) -> Vc<ChunkingConfigs> {
Vc::cell(self.chunking_configs.iter().cloned().collect())
}
#[turbo_tasks::function]
......@@ -939,16 +967,103 @@ impl ChunkingContext for BrowserChunkingContext {
}
#[turbo_tasks::function]
fn entry_chunk_group(
self: Vc<Self>,
_path: FileSystemPath,
_chunk_group: ChunkGroup,
_module_graph: Vc<ModuleGraph>,
_extra_chunks: Vc<OutputAssets>,
_extra_referenced_assets: Vc<OutputAssets>,
_availability_info: AvailabilityInfo,
async fn entry_chunk_group(
self: ResolvedVc<Self>,
path: FileSystemPath,
chunk_group: ChunkGroup,
module_graph: ResolvedVc<ModuleGraph>,
extra_chunks: Vc<OutputAssets>,
extra_referenced_assets: Vc<OutputAssets>,
availability_info: AvailabilityInfo,
) -> Result<Vc<EntryChunkGroupResult>> {
bail!("Browser chunking context does not support entry chunk groups")
if !self.await?.single_chunk {
bail!("Browser chunking context only supports entry chunk groups in single-chunk mode");
}
if !extra_chunks.await?.is_empty() {
bail!("single-chunk entry does not support extra chunks");
}
let span = tracing::info_span!(
"chunking",
name = display(path.to_string_ref().await?),
chunking_type = "single-chunk entry",
);
async move {
let MakeChunkGroupResult {
chunks,
references,
availability_info,
} = make_chunk_group(
chunk_group.clone(),
module_graph,
ResolvedVc::upcast(self),
availability_info,
)
.await?;
let chunks = chunks.await?;
let ecmascript_chunk = chunks
.iter()
.find_map(|chunk| ResolvedVc::try_downcast_type::<EcmascriptChunk>(*chunk));
if chunks.len() != 1 || ecmascript_chunk.is_none() {
SingleChunkProducedMultipleChunksIssue {
path: path.clone(),
chunk_count: chunks.len(),
}
.resolved_cell()
.emit();
}
// use a stub if chunks == 0, we already emitted an issue
let ecmascript_chunk = match ecmascript_chunk {
Some(ecmascript_chunk) => ecmascript_chunk,
None => {
EcmascriptChunk::new(
Vc::upcast(*self),
EcmascriptChunkContent {
chunk_items: Vec::new(),
batch_groups: Vec::new(),
}
.cell(),
)
.to_resolved()
.await?
}
};
let evaluatable_assets = chunk_group
.entries()
.map(|entry| {
ResolvedVc::try_sidecast::<Box<dyn EvaluatableAsset>>(entry)
.context("entry_chunk_group entries must be evaluatable assets")
})
.collect::<Result<Vec<_>>>()?;
let asset = ResolvedVc::upcast(
EcmascriptBrowserSingleEntryChunk::new(
*self,
path,
*ecmascript_chunk,
Vc::cell(evaluatable_assets),
extra_referenced_assets,
Vc::cell(references),
*module_graph,
)
.to_resolved()
.await?,
);
Ok(EntryChunkGroupResult {
asset,
availability_info,
}
.cell())
}
.instrument(span)
.await
}
#[turbo_tasks::function]
......@@ -966,6 +1081,16 @@ impl ChunkingContext for BrowserChunkingContext {
availability_info: AvailabilityInfo,
) -> Result<Vc<Box<dyn ChunkItem>>> {
let chunking_context = ResolvedVc::upcast::<Box<dyn ChunkingContext>>(self);
if self.await?.single_chunk {
// Single-chunk (eg. service-workers) entries cannot split a
// separate async chunk.
SingleChunkAsyncLoaderIssue {
path: module.ident().await?.path.clone(),
}
.resolved_cell()
.emit();
return Ok(module.as_chunk_item(module_graph, *chunking_context));
}
Ok(if self.await?.manifest_chunks {
let manifest_asset = ManifestAsyncModule::new(
module,
......@@ -1036,6 +1161,15 @@ impl ChunkingContext for BrowserChunkingContext {
let entrypoint = EcmascriptBrowserWorkerEntrypoint::new(*resolved, forwarded_globals);
Ok(Vc::upcast(entrypoint))
}
#[turbo_tasks::function]
fn chunk_loading(&self) -> Vc<ChunkLoading> {
if self.single_chunk {
ChunkLoading::SingleChunk.cell()
} else {
self.environment.chunk_loading()
}
}
}
#[turbo_tasks::value]
......@@ -1044,3 +1178,83 @@ struct ChunkPathInfo {
chunk_root_path: FileSystemPath,
chunk_content_hashing: Option<ContentHashing>,
}
#[turbo_tasks::value(shared)]
struct SingleChunkProducedMultipleChunksIssue {
path: FileSystemPath,
chunk_count: usize,
}
#[async_trait]
#[turbo_tasks::value_impl]
impl Issue for SingleChunkProducedMultipleChunksIssue {
fn severity(&self) -> IssueSeverity {
IssueSeverity::Error
}
async fn file_path(&self) -> Result<FileSystemPath> {
Ok(self.path.clone())
}
fn stage(&self) -> IssueStage {
IssueStage::CodeGen
}
async fn title(&self) -> Result<StyledString> {
Ok(StyledString::Text(rcstr!(
"Single-chunk entry could not be reduced to a single ECMAScript chunk"
)))
}
async fn description(&self) -> Result<Option<StyledString>> {
Ok(Some(StyledString::Stack(vec![
StyledString::Line(vec![
StyledString::Text(rcstr!(
"A single-chunk entry must produce exactly one ECMAScript chunk, but it \
produced "
)),
StyledString::Strong(RcStr::from(format!("{}", self.chunk_count))),
StyledString::Text(rcstr!(" chunk(s).")),
]),
StyledString::Text(rcstr!(
"This usually means the module graph contains non-ECMAScript chunkable items \
(e.g. CSS, image or font imports), which cannot be inlined into a single chunk."
)),
])))
}
}
#[turbo_tasks::value(shared)]
struct SingleChunkAsyncLoaderIssue {
path: FileSystemPath,
}
#[async_trait]
#[turbo_tasks::value_impl]
impl Issue for SingleChunkAsyncLoaderIssue {
fn severity(&self) -> IssueSeverity {
IssueSeverity::Error
}
async fn file_path(&self) -> Result<FileSystemPath> {
Ok(self.path.clone())
}
fn stage(&self) -> IssueStage {
IssueStage::CodeGen
}
async fn title(&self) -> Result<StyledString> {
Ok(StyledString::Text(rcstr!(
"Async loaders are not supported in single-chunk mode"
)))
}
async fn description(&self) -> Result<Option<StyledString>> {
Ok(Some(StyledString::Stack(vec![StyledString::Text(rcstr!(
"The dynamically imported module is inlined into the single chunk and cannot be \
code-split. Remove the dynamic import (import the module statically) if separate \
loading is not required."
))])))
}
}
......@@ -77,7 +77,7 @@ impl OutputChunk for EcmascriptBrowserChunk {
#[turbo_tasks::value_impl]
impl EcmascriptBrowserChunk {
#[turbo_tasks::function]
async fn own_content(self: Vc<Self>) -> Result<Vc<EcmascriptBrowserChunkContent>> {
pub(crate) async fn own_content(self: Vc<Self>) -> Result<Vc<EcmascriptBrowserChunkContent>> {
let this = self.await?;
Ok(EcmascriptBrowserChunkContent::new(
*this.chunking_context,
......
......@@ -72,7 +72,7 @@ impl EcmascriptBrowserChunkContent {
}
#[turbo_tasks::function]
async fn code(self: Vc<Self>) -> Result<Vc<Code>> {
pub(crate) async fn code(self: Vc<Self>) -> Result<Vc<Code>> {
let this = self.await?;
let source_maps = *this
.chunking_context
......
......@@ -78,7 +78,7 @@ impl EcmascriptBrowserEvaluateChunk {
}
#[turbo_tasks::function]
async fn code(self: Vc<Self>) -> Result<Vc<Code>> {
pub(crate) async fn code(self: Vc<Self>) -> Result<Vc<Code>> {
let this = self.await?;
let environment = this.chunking_context.environment();
......@@ -194,6 +194,7 @@ impl EcmascriptBrowserEvaluateChunk {
this.chunking_context.cross_origin(),
this.chunking_context.chunk_load_retry(),
has_async_modules,
this.chunking_context.chunk_loading(),
);
code.push_code(&*runtime_code.await?);
}
......
use anyhow::Result;
use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::{File, FileContent, FileSystemPath};
use turbopack_core::{
asset::{Asset, AssetContent},
chunk::{Chunk, ChunkingContext, EvaluatableAssets},
code_builder::{Code, CodeBuilder},
module_graph::ModuleGraph,
output::{
OutputAsset, OutputAssets, OutputAssetsReference, OutputAssetsReferences,
OutputAssetsWithReferenced,
},
source_map::{GenerateSourceMap, SourceMapAsset},
};
use turbopack_ecmascript::chunk::EcmascriptChunk;
use crate::{
BrowserChunkingContext,
ecmascript::{chunk::EcmascriptBrowserChunk, evaluate::chunk::EcmascriptBrowserEvaluateChunk},
};
/// A self-contained chunk that inlines the entire module together with
/// the Turbopack browser runtime and the evaluation of the entry modules.
///
/// Unlike the regular evaluate chunk, this emits everything into one file at a
/// fixed path and never loads additional chunks at runtime.
#[turbo_tasks::value(shared)]
#[derive(ValueToString)]
#[value_to_string("Ecmascript Browser Single Entry Chunk")]
pub(crate) struct EcmascriptBrowserSingleEntryChunk {
chunking_context: ResolvedVc<BrowserChunkingContext>,
path: FileSystemPath,
chunk: ResolvedVc<EcmascriptChunk>,
evaluatable_assets: ResolvedVc<EvaluatableAssets>,
referenced_output_assets: ResolvedVc<OutputAssets>,
references: ResolvedVc<OutputAssetsReferences>,
module_graph: ResolvedVc<ModuleGraph>,
}
#[turbo_tasks::value_impl]
impl EcmascriptBrowserSingleEntryChunk {
#[turbo_tasks::function]
pub fn new(
chunking_context: ResolvedVc<BrowserChunkingContext>,
path: FileSystemPath,
chunk: ResolvedVc<EcmascriptChunk>,
evaluatable_assets: ResolvedVc<EvaluatableAssets>,
referenced_output_assets: ResolvedVc<OutputAssets>,
references: ResolvedVc<OutputAssetsReferences>,
module_graph: ResolvedVc<ModuleGraph>,
) -> Vc<Self> {
EcmascriptBrowserSingleEntryChunk {
chunking_context,
path,
chunk,
evaluatable_assets,
referenced_output_assets,
references,
module_graph,
}
.cell()
}
#[turbo_tasks::function]
async fn code(self: Vc<Self>) -> Result<Vc<Code>> {
let this = self.await?;
let source_maps = *this
.chunking_context
.reference_chunk_source_maps(Vc::upcast(self))
.await?;
let mut code = CodeBuilder::new(
source_maps,
*this.chunking_context.debug_ids_enabled().await?,
);
let module_chunk = EcmascriptBrowserChunk::new(*this.chunking_context, *this.chunk);
code.push_code(&*module_chunk.own_content().code().await?);
let evaluate_chunk = EcmascriptBrowserEvaluateChunk::new(
*this.chunking_context,
this.chunk.ident(),
OutputAssets::empty(),
*this.evaluatable_assets,
*this.module_graph,
);
code.push_code(&*evaluate_chunk.code().await?);
Ok(Code::cell(code.build()))
}
#[turbo_tasks::function]
async fn source_map(self: Vc<Self>) -> Result<Vc<SourceMapAsset>> {
let this = self.await?;
Ok(SourceMapAsset::new_fixed(
this.path.clone(),
Vc::upcast(self),
))
}
}
#[turbo_tasks::value_impl]
impl OutputAssetsReference for EcmascriptBrowserSingleEntryChunk {
#[turbo_tasks::function]
async fn references(self: Vc<Self>) -> Result<Vc<OutputAssetsWithReferenced>> {
let this = self.await?;
let mut assets = Vec::new();
if *this
.chunking_context
.reference_chunk_source_maps(Vc::upcast(self))
.await?
{
assets.push(ResolvedVc::upcast(self.source_map().to_resolved().await?));
}
Ok(OutputAssetsWithReferenced {
assets: ResolvedVc::cell(assets),
referenced_assets: this.referenced_output_assets,
references: this.references,
}
.cell())
}
}
#[turbo_tasks::value_impl]
impl OutputAsset for EcmascriptBrowserSingleEntryChunk {
#[turbo_tasks::function]
fn path(&self) -> Vc<FileSystemPath> {
self.path.clone().cell()
}
}
#[turbo_tasks::value_impl]
impl Asset for EcmascriptBrowserSingleEntryChunk {
#[turbo_tasks::function]
async fn content(self: Vc<Self>) -> Result<Vc<AssetContent>> {
Ok(AssetContent::file(
FileContent::Content(File::from(
self.code()
.to_rope_with_magic_comments(|| self.source_map())
.await?,
))
.cell(),
))
}
}
#[turbo_tasks::value_impl]
impl GenerateSourceMap for EcmascriptBrowserSingleEntryChunk {
#[turbo_tasks::function]
fn generate_source_map(self: Vc<Self>) -> Vc<FileContent> {
self.code().generate_source_map()
}
}
......@@ -19,7 +19,6 @@ use crate::{
available_modules::{AvailableModuleItem, AvailableModulesSet},
chunk_item_batch::{ChunkItemBatchGroup, ChunkItemOrBatchWithAsyncModuleInfo},
},
environment::ChunkLoading,
module_graph::{
GraphTraversalAction, ModuleGraph,
chunk_group_info::ChunkGroup,
......@@ -46,10 +45,7 @@ pub async fn make_chunk_group(
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
availability_info: AvailabilityInfo,
) -> Result<MakeChunkGroupResult> {
let can_split_async = !matches!(
*chunking_context.environment().chunk_loading().await?,
ChunkLoading::Edge
);
let can_split_async = chunking_context.chunk_loading().await?.can_split_async();
let is_nested_async_availability_enabled = *chunking_context
.is_nested_async_availability_enabled()
.await?;
......
......@@ -13,7 +13,7 @@ use crate::{
ChunkItem, ChunkType, ChunkableModule, availability_info::AvailabilityInfo,
chunk_id_strategy::ModuleIdStrategy,
},
environment::Environment,
environment::{ChunkLoading, Environment},
ident::AssetIdent,
module::Module,
module_graph::{
......@@ -320,6 +320,11 @@ pub trait ChunkingContext {
#[turbo_tasks::function]
fn chunk_root_path(self: Vc<Self>) -> Vc<FileSystemPath>;
#[turbo_tasks::function]
fn chunk_loading(self: Vc<Self>) -> Vc<ChunkLoading> {
self.environment().chunk_loading()
}
// TODO(alexkirsz) Remove this from the chunking context. This should be at the
// discretion of chunking context implementors. However, we currently use this
// in a couple of places in `turbopack-css`, so we need to remove that
......
......@@ -30,13 +30,21 @@ impl Rendering {
}
}
#[turbo_tasks::value]
#[turbo_tasks::value(shared)]
pub enum ChunkLoading {
Edge,
/// CommonJS in Node.js
NodeJs,
/// `<script>` and `<link>` tags in the browser
Dom,
/// Everything inlined into one entry chunk
SingleChunk,
}
impl ChunkLoading {
pub fn can_split_async(&self) -> bool {
matches!(self, ChunkLoading::NodeJs | ChunkLoading::Dom)
}
}
#[turbo_tasks::value]
......
......@@ -27,6 +27,7 @@ pub async fn get_browser_runtime_code(
cross_origin: Vc<CrossOrigin>,
chunk_load_retry: Vc<ChunkLoadRetry>,
has_async_modules: bool,
chunk_loading: Vc<ChunkLoading>,
) -> Result<Vc<Code>> {
let asset_context = *asset_context;
let environment = asset_context.compile_time_info().environment();
......@@ -50,21 +51,19 @@ pub async fn get_browser_runtime_code(
}
}
let chunk_loading = &*asset_context
.compile_time_info()
.environment()
.chunk_loading()
.await?;
let chunk_loading = &*chunk_loading.await?;
let mut runtime_backend_code = vec![];
match (chunk_loading, runtime_type) {
(ChunkLoading::Edge, RuntimeType::Development) => {
// The self-contained backend performs no runtime chunk loading and registers chunks only
// via `globalThis`/`self` (no DOM).
(ChunkLoading::Edge | ChunkLoading::SingleChunk, RuntimeType::Development) => {
runtime_backend_code
.push("browser/runtime/self-contained/runtime-backend-self-contained.ts");
runtime_backend_code
.push("browser/runtime/self-contained/dev-backend-self-contained.ts");
}
(ChunkLoading::Edge, RuntimeType::Production) => {
(ChunkLoading::Edge | ChunkLoading::SingleChunk, RuntimeType::Production) => {
runtime_backend_code
.push("browser/runtime/self-contained/runtime-backend-self-contained.ts");
}
......@@ -141,8 +140,11 @@ pub async fn get_browser_runtime_code(
)?;
}
AssetSuffix::Inferred => {
if chunk_loading == &ChunkLoading::Edge {
panic!("AssetSuffix::Inferred is not supported in Edge runtimes");
if matches!(
chunk_loading,
ChunkLoading::Edge | ChunkLoading::SingleChunk
) {
panic!("AssetSuffix::Inferred is not supported in Edge or single-chunk runtimes");
}
writedoc!(
code,
......
......@@ -10,7 +10,6 @@ use turbo_tasks::{
};
use turbopack_core::{
chunk::{ChunkingContext, ChunkingType},
environment::ChunkLoading,
issue::IssueSource,
module::Module,
reference::ModuleReference,
......@@ -154,13 +153,10 @@ impl EsmAsyncAssetReferenceCodeGen {
*reference.origin,
chunking_context,
self.reference.resolve_reference(),
if matches!(
*chunking_context.environment().chunk_loading().await?,
ChunkLoading::Edge
) {
ResolveType::ChunkItem
} else {
if chunking_context.chunk_loading().await?.can_split_async() {
ResolveType::AsyncChunkLoader
} else {
ResolveType::ChunkItem
},
)
.await?;
......
......@@ -97,6 +97,8 @@ struct SnapshotOptions {
#[serde(default)]
production_chunking: bool,
#[serde(default)]
single_chunk: bool,
#[serde(default)]
enable_debug_ids: bool,
#[serde(default)]
source_map_source_type: SourceMapSourceType,
......@@ -134,6 +136,7 @@ impl Default for SnapshotOptions {
remove_unused_exports: false,
scope_hoisting: false,
production_chunking: false,
single_chunk: false,
enable_debug_ids: false,
source_map_source_type: SourceMapSourceType::default(),
chunk_loading_global: default_chunk_loading_global(),
......@@ -518,6 +521,10 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
.source_map_source_type(options.source_map_source_type)
.chunk_loading_global(options.chunk_loading_global.into());
if options.single_chunk {
builder = builder.single_chunk().await?;
}
if options.remove_unused_imports {
builder = builder.unused_references(
binding_usage
......@@ -595,6 +602,27 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
// TODO: Load runtime entries from snapshots
let chunks = match options.runtime {
Runtime::Browser if options.single_chunk => OutputAssetsWithReferenced {
assets: ResolvedVc::cell(vec![
chunking_context
.entry_chunk_group(
// `expected` expects a completely flat output directory.
chunk_root_path
.join(entry_module.ident().await?.path.file_stem().unwrap())?
.with_extension("entry.js"),
ChunkGroup::Entry(entry_modules),
module_graph,
OutputAssets::empty(),
OutputAssets::empty(),
AvailabilityInfo::root(),
)
.await?
.asset,
]),
referenced_assets: ResolvedVc::cell(vec![]),
references: ResolvedVc::cell(vec![]),
}
.cell(),
Runtime::Browser => chunking_context.evaluated_chunk_group_assets(
entry_module.ident(),
ChunkGroup::Entry(entry_modules.into_iter().collect()),
......
// `dep1` is reached via `import('./dep1')` and itself dynamically imports
// `dep2` — exercising a nested dynamic-import boundary that must also inline.
export function dep1() {
console.log('dep1')
import('./dep2').then(({ dep2 }) => {
dep2()
})
}
// Leaf module reached via the nested `import('./dep2')`.
export function dep2() {
console.log('dep2')
}
// Service-worker-style entry: the whole transitive closure (including the
// dynamic `import()` targets) must be inlined into a single output file.
console.log('service worker entry')
import('./dep1').then(({ dep1 }) => {
dep1()
})
{
"minifyType": "NoMinify",
"runtime": "Browser",
"singleChunk": true
}
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_single-chunk-entry_input_0085tus._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/single-chunk-entry/input/dep1.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
// `dep1` is reached via `import('./dep1')` and itself dynamically imports
// `dep2` — exercising a nested dynamic-import boundary that must also inline.
__turbopack_context__.s([
"dep1",
()=>dep1
]);
function dep1() {
console.log('dep1');
Promise.resolve().then(()=>__turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/single-chunk-entry/input/dep2.js [test] (ecmascript)")).then(({ dep2 })=>{
dep2();
});
}
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/single-chunk-entry/input/dep2.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
// Leaf module reached via the nested `import('./dep2')`.
__turbopack_context__.s([
"dep2",
()=>dep2
]);
function dep2() {
console.log('dep2');
}
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/single-chunk-entry/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
// Service-worker-style entry: the whole transitive closure (including the
// dynamic `import()` targets) must be inlined into a single output file.
console.log('service worker entry');
Promise.resolve().then(()=>__turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/single-chunk-entry/input/dep1.js [test] (ecmascript)")).then(({ dep1 })=>{
dep1();
});
}),
]);(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1i9t_crates_turbopack-tests_tests_snapshot_basic_single-chunk-entry_input_1gjyv-z._.js",
{"otherChunks":[],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/single-chunk-entry/input/index.js [test] (ecmascript)"]}
]);
// Dummy runtime
//# sourceMappingURL=index.entry.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/single-chunk-entry/input/dep1.js"],"sourcesContent":["// `dep1` is reached via `import('./dep1')` and itself dynamically imports\n// `dep2` — exercising a nested dynamic-import boundary that must also inline.\nexport function dep1() {\n console.log('dep1')\n import('./dep2').then(({ dep2 }) => {\n dep2()\n })\n}\n"],"names":["dep1","console","log","then","dep2"],"mappings":"AAAA,0EAA0E;AAC1E,8EAA8E;;;;;AACvE,SAASA;IACdC,QAAQC,GAAG,CAAC;IACZ,4KAAiBC,IAAI,CAAC,CAAC,EAAEC,IAAI,EAAE;QAC7BA;IACF;AACF"}},
{"offset": {"line": 20, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/single-chunk-entry/input/dep2.js"],"sourcesContent":["// Leaf module reached via the nested `import('./dep2')`.\nexport function dep2() {\n console.log('dep2')\n}\n"],"names":["dep2","console","log"],"mappings":"AAAA,yDAAyD;;;;;AAClD,SAASA;IACdC,QAAQC,GAAG,CAAC;AACd"}},
{"offset": {"line": 31, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/single-chunk-entry/input/index.js"],"sourcesContent":["// Service-worker-style entry: the whole transitive closure (including the\n// dynamic `import()` targets) must be inlined into a single output file.\nconsole.log('service worker entry')\n\nimport('./dep1').then(({ dep1 }) => {\n dep1()\n})\n"],"names":["console","log","then","dep1"],"mappings":"AAAA,0EAA0E;AAC1E,yEAAyE;AACzEA,QAAQC,GAAG,CAAC;AAEZ,4KAAiBC,IAAI,CAAC,CAAC,EAAEC,IAAI,EAAE;IAC7BA;AACF"}}]
}
\ No newline at end of file
......@@ -72,6 +72,7 @@ impl WebAssemblyModuleAsset {
.environment()
.chunk_loading()
.await?;
let is_edge = matches!(*chunk_loading, ChunkLoading::Edge);
let loader_source = if query == "?module" {
......@@ -84,6 +85,10 @@ impl WebAssemblyModuleAsset {
ChunkLoading::Edge => rcstr!("edge/loadWasm.ts"),
ChunkLoading::NodeJs => rcstr!("node/loadWasm.ts"),
ChunkLoading::Dom => rcstr!("browser/loadWasm.ts"),
ChunkLoading::SingleChunk => unreachable!(
"Environment::chunk_loading never returns SingleChunk; single-chunk WASM is \
rejected in chunk_item_content"
),
};
let helper = self
......@@ -223,6 +228,16 @@ impl EcmascriptChunkPlaceable for WebAssemblyModuleAsset {
async_module_info: Option<Vc<AsyncModuleInfo>>,
estimated: bool,
) -> Result<Vc<EcmascriptChunkItemContent>> {
if matches!(
*chunking_context.chunk_loading().await?,
ChunkLoading::SingleChunk
) {
bail!(
"WebAssembly imports are not supported in single-chunk (service-worker) \
entrypoints"
);
}
// Delegate to the loader's chunk item content
Ok(self.loader().chunk_item_content(
chunking_context,
......
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