Unverified Commit 33e50fa7 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Simplify hoisted export lookup and preserve per-member namespaces

Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent edd910c0
...@@ -604,7 +604,6 @@ pub async fn get_client_chunking_context( ...@@ -604,7 +604,6 @@ pub async fn get_client_chunking_context(
.chunk_load_retry(NEXT_CHUNK_LOAD_RETRY) .chunk_load_retry(NEXT_CHUNK_LOAD_RETRY)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?) .unused_references(unused_references.to_resolved().await?)
.merged_modules(merged_modules.to_resolved().await?)
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.debug_ids(*debug_ids.await?) .debug_ids(*debug_ids.await?)
.worker_asset_prefix(worker_asset_prefix.owned().await?) .worker_asset_prefix(worker_asset_prefix.owned().await?)
...@@ -659,8 +658,10 @@ pub async fn get_client_chunking_context( ...@@ -659,8 +658,10 @@ pub async fn get_client_chunking_context(
}, },
) )
.chunk_content_hashing(ContentHashing::Direct { length: 13 }) .chunk_content_hashing(ContentHashing::Direct { length: 13 })
.module_merging(*scope_hoisting.await?)
.shared_runtime(*shared_runtime.await?); .shared_runtime(*shared_runtime.await?);
if *scope_hoisting.await? {
builder = builder.merged_modules(merged_modules.to_resolved().await?);
}
} }
Ok(Vc::upcast(builder.build())) Ok(Vc::upcast(builder.build()))
......
...@@ -267,7 +267,6 @@ pub async fn get_edge_chunking_context_with_client_assets( ...@@ -267,7 +267,6 @@ pub async fn get_edge_chunking_context_with_client_assets(
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?) .unused_references(unused_references.to_resolved().await?)
.merged_modules(merged_modules.to_resolved().await?)
.hash_salt(hash_salt) .hash_salt(hash_salt)
.nested_async_availability(*nested_async_chunking.await?) .nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(worker_forwarded_globals()); .worker_forwarded_globals(worker_forwarded_globals());
...@@ -288,8 +287,10 @@ pub async fn get_edge_chunking_context_with_client_assets( ...@@ -288,8 +287,10 @@ pub async fn get_edge_chunking_context_with_client_assets(
style_groups_algorithm: style_groups_algorithm.clone(), style_groups_algorithm: style_groups_algorithm.clone(),
..Default::default() ..Default::default()
}, },
) );
.module_merging(*scope_hoisting.await?); if *scope_hoisting.await? {
builder = builder.merged_modules(merged_modules.to_resolved().await?);
}
} }
Ok(Vc::upcast(builder.build())) Ok(Vc::upcast(builder.build()))
...@@ -382,7 +383,6 @@ pub async fn get_edge_chunking_context( ...@@ -382,7 +383,6 @@ pub async fn get_edge_chunking_context(
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?) .unused_references(unused_references.to_resolved().await?)
.merged_modules(merged_modules.to_resolved().await?)
.hash_salt(hash_salt) .hash_salt(hash_salt)
.nested_async_availability(*nested_async_chunking.await?) .nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(worker_forwarded_globals()); .worker_forwarded_globals(worker_forwarded_globals());
...@@ -403,8 +403,10 @@ pub async fn get_edge_chunking_context( ...@@ -403,8 +403,10 @@ pub async fn get_edge_chunking_context(
style_groups_algorithm: style_groups_algorithm.clone(), style_groups_algorithm: style_groups_algorithm.clone(),
..Default::default() ..Default::default()
}, },
) );
.module_merging(*scope_hoisting.await?); if *scope_hoisting.await? {
builder = builder.merged_modules(merged_modules.to_resolved().await?);
}
} }
Ok(Vc::upcast(builder.build())) Ok(Vc::upcast(builder.build()))
......
...@@ -1111,7 +1111,6 @@ pub async fn get_server_chunking_context_with_client_assets( ...@@ -1111,7 +1111,6 @@ pub async fn get_server_chunking_context_with_client_assets(
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?) .unused_references(unused_references.to_resolved().await?)
.merged_modules(merged_modules.to_resolved().await?)
.debug_ids(*debug_ids.await?) .debug_ids(*debug_ids.await?)
.hash_salt(hash_salt) .hash_salt(hash_salt)
.nested_async_availability(*nested_async_chunking.await?) .nested_async_availability(*nested_async_chunking.await?)
...@@ -1146,8 +1145,10 @@ pub async fn get_server_chunking_context_with_client_assets( ...@@ -1146,8 +1145,10 @@ pub async fn get_server_chunking_context_with_client_assets(
style_groups_algorithm: style_groups_algorithm.clone(), style_groups_algorithm: style_groups_algorithm.clone(),
..Default::default() ..Default::default()
}, },
) );
.module_merging(*scope_hoisting.await?); if *scope_hoisting.await? {
builder = builder.merged_modules(merged_modules.to_resolved().await?);
}
} }
Ok(builder.build()) Ok(builder.build())
...@@ -1228,7 +1229,6 @@ pub async fn get_server_chunking_context( ...@@ -1228,7 +1229,6 @@ pub async fn get_server_chunking_context(
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?) .unused_references(unused_references.to_resolved().await?)
.merged_modules(merged_modules.to_resolved().await?)
.debug_ids(*debug_ids.await?) .debug_ids(*debug_ids.await?)
.hash_salt(hash_salt) .hash_salt(hash_salt)
.nested_async_availability(*nested_async_chunking.await?) .nested_async_availability(*nested_async_chunking.await?)
...@@ -1261,8 +1261,10 @@ pub async fn get_server_chunking_context( ...@@ -1261,8 +1261,10 @@ pub async fn get_server_chunking_context(
style_groups_algorithm: style_groups_algorithm.clone(), style_groups_algorithm: style_groups_algorithm.clone(),
..Default::default() ..Default::default()
}, },
) );
.module_merging(*scope_hoisting.await?); if *scope_hoisting.await? {
builder = builder.merged_modules(merged_modules.to_resolved().await?);
}
} }
Ok(builder.build()) Ok(builder.build())
......
...@@ -86,11 +86,6 @@ impl BrowserChunkingContextBuilder { ...@@ -86,11 +86,6 @@ impl BrowserChunkingContextBuilder {
self 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( pub fn dynamic_chunk_content_loading(
mut self, mut self,
enable_dynamic_chunk_content_loading: bool, enable_dynamic_chunk_content_loading: bool,
...@@ -361,8 +356,6 @@ pub struct BrowserChunkingContext { ...@@ -361,8 +356,6 @@ pub struct BrowserChunkingContext {
enable_hot_module_replacement: bool, enable_hot_module_replacement: bool,
/// Enable nested async availability for this chunking /// Enable nested async availability for this chunking
enable_nested_async_availability: bool, enable_nested_async_availability: bool,
/// Enable module merging
enable_module_merging: bool,
/// Enable dynamic chunk content loading. /// Enable dynamic chunk content loading.
enable_dynamic_chunk_content_loading: bool, enable_dynamic_chunk_content_loading: bool,
/// Enable debug IDs for chunks and source maps. /// Enable debug IDs for chunks and source maps.
...@@ -450,7 +443,6 @@ impl BrowserChunkingContext { ...@@ -450,7 +443,6 @@ impl BrowserChunkingContext {
default_url_behavior: None, default_url_behavior: None,
enable_hot_module_replacement: false, enable_hot_module_replacement: false,
enable_nested_async_availability: false, enable_nested_async_availability: false,
enable_module_merging: false,
enable_dynamic_chunk_content_loading: false, enable_dynamic_chunk_content_loading: false,
debug_ids: false, debug_ids: false,
shared_runtime: false, shared_runtime: false,
...@@ -864,7 +856,7 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -864,7 +856,7 @@ impl ChunkingContext for BrowserChunkingContext {
#[turbo_tasks::function] #[turbo_tasks::function]
fn is_module_merging_enabled(&self) -> Vc<bool> { fn is_module_merging_enabled(&self) -> Vc<bool> {
Vc::cell(self.enable_module_merging) Vc::cell(self.merged_modules.is_some())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -1343,9 +1335,7 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -1343,9 +1335,7 @@ impl ChunkingContext for BrowserChunkingContext {
#[turbo_tasks::function] #[turbo_tasks::function]
fn merged_modules(&self) -> Vc<MergedModuleGroups> { fn merged_modules(&self) -> Vc<MergedModuleGroups> {
if self.enable_module_merging if let Some(merged_modules) = self.merged_modules {
&& let Some(merged_modules) = self.merged_modules
{
*merged_modules *merged_modules
} else { } else {
Vc::cell(Default::default()) Vc::cell(Default::default())
......
...@@ -383,8 +383,7 @@ async fn build_internal( ...@@ -383,8 +383,7 @@ async fn build_internal(
) )
.chunk_content_hashing(ContentHashing::Direct { length: 13 }) .chunk_content_hashing(ContentHashing::Direct { length: 13 })
.asset_content_hashing(ContentHashing::Direct { length: 13 }) .asset_content_hashing(ContentHashing::Direct { length: 13 })
.nested_async_availability(true) .nested_async_availability(true);
.module_merging(scope_hoist);
if scope_hoist { if scope_hoist {
builder = builder =
builder.merged_modules(module_graph.merged_modules().await?.groups); builder.merged_modules(module_graph.merged_modules().await?.groups);
...@@ -434,8 +433,7 @@ async fn build_internal( ...@@ -434,8 +433,7 @@ async fn build_internal(
max_merge_chunk_size: 100_000, max_merge_chunk_size: 100_000,
..Default::default() ..Default::default()
}, },
) );
.module_merging(scope_hoist);
if scope_hoist { if scope_hoist {
builder = builder =
builder.merged_modules(module_graph.merged_modules().await?.groups); builder.merged_modules(module_graph.merged_modules().await?.groups);
......
...@@ -132,6 +132,7 @@ use crate::{ ...@@ -132,6 +132,7 @@ use crate::{
side_effect_optimization::reference::EcmascriptModulePartReference, side_effect_optimization::reference::EcmascriptModulePartReference,
swc_comments::{CowComments, ImmutableComments}, swc_comments::{CowComments, ImmutableComments},
transform::{remove_directives, remove_shebang}, transform::{remove_directives, remove_shebang},
utils::module_id_to_lit,
}; };
pub use crate::{ pub use crate::{
references::{AnalyzeEcmascriptModuleResult, TURBOPACK_HELPER}, references::{AnalyzeEcmascriptModuleResult, TURBOPACK_HELPER},
...@@ -1349,14 +1350,43 @@ impl EcmascriptModuleContent { ...@@ -1349,14 +1350,43 @@ impl EcmascriptModuleContent {
// Use the options from an arbitrary module, since they should all be the same with // Use the options from an arbitrary module, since they should all be the same with
// regards to minify_type and chunking_context. // regards to minify_type and chunking_context.
let options = module_options.last().unwrap().await?; let options = module_options.last().unwrap().await?;
let flat_group = *references::esm::mangle::flat_export_group( let first_entry = entry_points.first().unwrap().0;
*entry_points[0].0, let flat_group = if let Some(group) = options
*options.chunking_context, .chunking_context
) .merged_modules()
.await?; .get(&ResolvedVc::upcast(first_entry))
let flat_exports = flat_group.is_some(); .await?
.as_deref()
{
if let Some(flat_group) =
*references::esm::mangle::flat_group_exports(**group, *options.chunking_context)
.await?
{
Some(flat_group.await?)
} else {
None
}
} else {
None
};
// A deoptimized factory entry keeps its own namespace. Register the shared table
// under an eligible member instead, without changing the factory's identity.
let flat_export_id = if let Some(group) = &flat_group
&& group.entry != first_entry
{
Some(group.entry.chunk_item_id(*options.chunking_context).await?)
} else {
None
};
let (merged_ast, comments, source_maps, original_source_maps, lookup_table) = let (merged_ast, comments, source_maps, original_source_maps, lookup_table) =
merge_modules(contents, &entry_points, &globals_merged, flat_exports).await?; merge_modules(
contents,
&entry_points,
&globals_merged,
flat_group.is_some(),
flat_export_id.as_ref(),
)
.await?;
let modules_header_width = modules.len().next_power_of_two().trailing_zeros(); let modules_header_width = modules.len().next_power_of_two().trailing_zeros();
let content = CodeGenResult { let content = CodeGenResult {
...@@ -1380,29 +1410,21 @@ impl EcmascriptModuleContent { ...@@ -1380,29 +1410,21 @@ impl EcmascriptModuleContent {
scope_hoisting_syntax_contexts: None, scope_hoisting_syntax_contexts: None,
}; };
let first_entry = entry_points.first().unwrap().0; let additional_ids = modules
let additional_ids = if flat_exports { .keys()
// All imports of a flat group use its canonical entry, which is also the chunk // Flat members share one namespace ID. Only its target and independently
// item's ID. The other exposed members do not need factory aliases. // exposed namespaces need aliases for imports that instantiate this factory.
SmallVec::new() .filter(|module| {
} else { **module != first_entry
modules && *modules.get(*module).unwrap() == MergeableModuleExposure::External
.keys() && flat_group.as_ref().is_none_or(|group| {
// Additionally set this module factory for all modules that are exposed. The **module == group.entry || !group.names.contains_key(*module)
// whole group might be imported via a different entry import in different })
// chunks (we only ensure that the modules are in the same order, not that they })
// form a subgraph that is always imported from the same root module). .map(|module| module.chunk_item_id(*options.chunking_context))
// .try_join()
// Also skip the first entry, which is the name of the chunk item. .await?
.filter(|m| { .into();
**m != first_entry
&& *modules.get(*m).unwrap() == MergeableModuleExposure::External
})
.map(|m| m.chunk_item_id(*options.chunking_context))
.try_join()
.await?
.into()
};
emit_content(content, additional_ids) emit_content(content, additional_ids)
.instrument(tracing::info_span!("emit code")) .instrument(tracing::info_span!("emit code"))
...@@ -1466,6 +1488,7 @@ async fn merge_modules( ...@@ -1466,6 +1488,7 @@ async fn merge_modules(
entry_points: &Vec<(ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, usize)>, entry_points: &Vec<(ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, usize)>,
globals_merged: &'_ Globals, globals_merged: &'_ Globals,
flat_exports: bool, flat_exports: bool,
flat_export_id: Option<&ModuleId>,
) -> Result<( ) -> Result<(
Program, Program,
Vec<CodeGenResultComments>, Vec<CodeGenResultComments>,
...@@ -1807,17 +1830,31 @@ async fn merge_modules( ...@@ -1807,17 +1830,31 @@ async fn merge_modules(
&& let Callee::Expr(callee) = &call.callee && let Callee::Expr(callee) = &call.callee
&& callee.is_ident_ref_to("__turbopack_flat_esm__") && callee.is_ident_ref_to("__turbopack_flat_esm__")
{ {
let Expr::Array(array) = &mut *call.args[0].expr else { unreachable!() }; let Expr::Array(array) = &mut *call.args[0].expr else {
unreachable!()
};
getters.append(&mut array.elems); getters.append(&mut array.elems);
return false; return false;
} }
true true
}); });
if !getters.is_empty() { if !getters.is_empty() || flat_export_id.is_some() {
let stmt = ModuleItem::Stmt(quote!("$esm($getters);" as Stmt, let getters = Expr::from(swc_core::ecma::ast::ArrayLit {
esm: Expr = runtime_functions::TURBOPACK_ESM.into(), span: DUMMY_SP,
getters: Expr = swc_core::ecma::ast::ArrayLit { span: DUMMY_SP, elems: getters }.into(), elems: getters,
)); });
let stmt = ModuleItem::Stmt(if let Some(id) = flat_export_id {
quote!("$esm($getters, $id);" as Stmt,
esm: Expr = runtime_functions::TURBOPACK_ESM.into(),
getters: Expr = getters,
id: Expr = module_id_to_lit(id),
)
} else {
quote!("$esm($getters);" as Stmt,
esm: Expr = runtime_functions::TURBOPACK_ESM.into(),
getters: Expr = getters,
)
});
merged_prelude.insert(0, stmt); merged_prelude.insert(0, stmt);
} }
} }
......
...@@ -125,9 +125,7 @@ impl AsyncModule { ...@@ -125,9 +125,7 @@ impl AsyncModule {
ReferencedAsset::External(_, ExternalType::EcmaScriptModule) => { ReferencedAsset::External(_, ExternalType::EcmaScriptModule) => {
if self.import_externals { if self.import_externals {
referenced_asset referenced_asset
.prepare_binding(chunking_context, None, ScopeHoistingContext::None) .get_ident(chunking_context, None, ScopeHoistingContext::None)
.await?
.get_ident(chunking_context)
.await? .await?
.map(|i| i.into_module_namespace_ident().unwrap()) .map(|i| i.into_module_namespace_ident().unwrap())
.map(|(i, ctx)| (i, ctx.unwrap_or_default().into())) .map(|(i, ctx)| (i, ctx.unwrap_or_default().into()))
...@@ -141,9 +139,7 @@ impl AsyncModule { ...@@ -141,9 +139,7 @@ impl AsyncModule {
.contains(&ResolvedVc::upcast(*placeable)) .contains(&ResolvedVc::upcast(*placeable))
{ {
referenced_asset referenced_asset
.prepare_binding(chunking_context, None, ScopeHoistingContext::None) .get_ident(chunking_context, None, ScopeHoistingContext::None)
.await?
.get_ident(chunking_context)
.await? .await?
.map(|i| i.into_module_namespace_ident().unwrap()) .map(|i| i.into_module_namespace_ident().unwrap())
.map(|(i, ctx)| (i, ctx.unwrap_or_default().into())) .map(|(i, ctx)| (i, ctx.unwrap_or_default().into()))
......
...@@ -205,71 +205,24 @@ impl ReferencedAssetIdent { ...@@ -205,71 +205,24 @@ impl ReferencedAssetIdent {
} }
} }
/// A binding prepared for code generation. Target selection and re-export traversal happen
/// before identifier formatting, while the original module is still available for local
/// binding resolution and export-name allocation.
pub enum PreparedBinding {
LocalBinding {
ident: RcStr,
ctxt: SyntaxContext,
liveness: Liveness,
},
Module {
import_source: ImportSource,
ctxt: Option<SyntaxContext>,
export: Option<RcStr>,
},
None,
}
impl PreparedBinding {
pub async fn get_ident(
self,
chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Option<ReferencedAssetIdent>> {
Ok(match self {
Self::LocalBinding {
ident,
ctxt,
liveness,
} => Some(ReferencedAssetIdent::LocalBinding {
ident,
ctxt,
liveness,
}),
Self::Module {
import_source,
ctxt,
export,
} => Some(ReferencedAssetIdent::Module {
namespace_ident: import_source.get_namespace_ident(chunking_context).await?,
ctxt,
export,
import_source,
}),
Self::None => None,
})
}
}
impl ReferencedAsset { impl ReferencedAsset {
pub async fn prepare_binding( pub async fn get_ident(
&self, &self,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
export: Option<RcStr>, export: Option<RcStr>,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
) -> Result<PreparedBinding> { ) -> Result<Option<ReferencedAssetIdent>> {
self.prepare_binding_inner(chunking_context, export, scope_hoisting_context, None) self.get_ident_inner(chunking_context, export, scope_hoisting_context, None)
.await .await
} }
async fn prepare_binding_inner( async fn get_ident_inner(
&self, &self,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
export: Option<RcStr>, export: Option<RcStr>,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
initial: Option<&ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>>, initial: Option<&ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>>,
) -> Result<PreparedBinding> { ) -> Result<Option<ReferencedAssetIdent>> {
Ok(match self { Ok(match self {
ReferencedAsset::Some(asset) => { ReferencedAsset::Some(asset) => {
if let Some(ctxt) = scope_hoisting_context.get_module_syntax_context(*asset) if let Some(ctxt) = scope_hoisting_context.get_module_syntax_context(*asset)
...@@ -283,11 +236,11 @@ impl ReferencedAsset { ...@@ -283,11 +236,11 @@ impl ReferencedAsset {
// A local binding in a module that is merged in the same group. Use the // A local binding in a module that is merged in the same group. Use the
// export name as identifier, it will be replaced with the actual // export name as identifier, it will be replaced with the actual
// variable name during AST merging. // variable name during AST merging.
return Ok(PreparedBinding::LocalBinding { return Ok(Some(ReferencedAssetIdent::LocalBinding {
ident: export.clone(), ident: export.clone(),
ctxt, ctxt,
liveness: *liveness, liveness: *liveness,
}); }));
} }
Some(b @ EsmExport::ImportedBinding(esm_ref, _, _)) Some(b @ EsmExport::ImportedBinding(esm_ref, _, _))
| Some(b @ EsmExport::ImportedNamespace(esm_ref)) => { | Some(b @ EsmExport::ImportedNamespace(esm_ref)) => {
...@@ -314,13 +267,13 @@ impl ReferencedAsset { ...@@ -314,13 +267,13 @@ impl ReferencedAsset {
} }
.resolved_cell() .resolved_cell()
.emit(); .emit();
return Ok(PreparedBinding::None); return Ok(None);
} }
// If the target module is still in the same group, we can // If the target module is still in the same group, we can
// refer it locally, otherwise it will be imported // refer it locally, otherwise it will be imported
return Ok( return Ok(
match Box::pin(referenced_asset.prepare_binding_inner( match Box::pin(referenced_asset.get_ident_inner(
chunking_context, chunking_context,
imported, imported,
scope_hoisting_context, scope_hoisting_context,
...@@ -328,17 +281,19 @@ impl ReferencedAsset { ...@@ -328,17 +281,19 @@ impl ReferencedAsset {
)) ))
.await? .await?
{ {
PreparedBinding::Module { Some(ReferencedAssetIdent::Module {
// This import is inserted in the module containing the // This import is inserted in the module containing the
// reexport, not the module using the import. // reexport, not the module using the import.
ctxt: None, ctxt: None,
namespace_ident,
export, export,
import_source, import_source,
} => PreparedBinding::Module { }) => Some(ReferencedAssetIdent::Module {
ctxt: Some(ctxt), ctxt: Some(ctxt),
namespace_ident,
export, export,
import_source, import_source,
}, }),
ident => ident, ident => ident,
}, },
); );
...@@ -357,29 +312,32 @@ impl ReferencedAsset { ...@@ -357,29 +312,32 @@ impl ReferencedAsset {
*asset *asset
}; };
let import_source = ImportSource::Module { asset: target }; let import_source = ImportSource::Module { asset: target };
PreparedBinding::Module { // Allocate against the original module, not the shared factory target,
// using the same mapping as the producing module.
let export = match &export {
Some(export) => {
Some(generated_export_key(*asset, chunking_context, export).await?)
}
None => None,
};
Some(ReferencedAssetIdent::Module {
namespace_ident: import_source.get_namespace_ident(chunking_context).await?,
ctxt: None, ctxt: None,
// Allocate against the original module, not the shared factory target, export,
// using the same mapping as the producing module.
export: match &export {
Some(export) => {
Some(generated_export_key(*asset, chunking_context, export).await?)
}
None => None,
},
import_source, import_source,
} })
} }
ReferencedAsset::External(request, ty) => { ReferencedAsset::External(request, ty) => {
let import_source = ImportSource::External { let import_source = ImportSource::External {
request: request.clone(), request: request.clone(),
ty: *ty, ty: *ty,
}; };
PreparedBinding::Module { Some(ReferencedAssetIdent::Module {
namespace_ident: import_source.get_namespace_ident(chunking_context).await?,
ctxt: None, ctxt: None,
export, export,
import_source, import_source,
} })
} }
ReferencedAsset::NonPlaceable(module) => { ReferencedAsset::NonPlaceable(module) => {
// The module exists but has no ECMAScript bindings, so there is // The module exists but has no ECMAScript bindings, so there is
...@@ -407,11 +365,9 @@ impl ReferencedAsset { ...@@ -407,11 +365,9 @@ impl ReferencedAsset {
} }
.resolved_cell() .resolved_cell()
.emit(); .emit();
PreparedBinding::None None
}
ReferencedAsset::None | ReferencedAsset::Empty | ReferencedAsset::Unresolvable => {
PreparedBinding::None
} }
ReferencedAsset::None | ReferencedAsset::Empty | ReferencedAsset::Unresolvable => None,
}) })
} }
...@@ -926,7 +882,7 @@ impl EsmAssetReference { ...@@ -926,7 +882,7 @@ impl EsmAssetReference {
} else { } else {
'import: { 'import: {
let ident = referenced_asset let ident = referenced_asset
.prepare_binding( .get_ident(
chunking_context, chunking_context,
this.export_name this.export_name
.as_ref() .as_ref()
...@@ -934,8 +890,6 @@ impl EsmAssetReference { ...@@ -934,8 +890,6 @@ impl EsmAssetReference {
.cloned(), .cloned(),
scope_hoisting_context, scope_hoisting_context,
) )
.await?
.get_ident(chunking_context)
.await?; .await?;
// `referenced_asset` must not be used past this point: the ident // `referenced_asset` must not be used past this point: the ident
// carries everything about the import // carries everything about the import
......
...@@ -136,13 +136,7 @@ impl EsmBindings { ...@@ -136,13 +136,7 @@ impl EsmBindings {
imported_module => match exports_cache.entry(export.clone()) { imported_module => match exports_cache.entry(export.clone()) {
std::collections::hash_map::Entry::Vacant(entry) => { std::collections::hash_map::Entry::Vacant(entry) => {
let ident: ImportedIdent = imported_module let ident: ImportedIdent = imported_module
.prepare_binding( .get_ident(chunking_context, export.clone(), scope_hoisting_context)
chunking_context,
export.clone(),
scope_hoisting_context,
)
.await?
.get_ident(chunking_context)
.await? .await?
.map_or(ImportedIdent::Unresolvable, ImportedIdent::Module); .map_or(ImportedIdent::Unresolvable, ImportedIdent::Module);
entry.insert(ident.clone()); entry.insert(ident.clone());
......
...@@ -659,9 +659,7 @@ async fn compact_reference_target( ...@@ -659,9 +659,7 @@ async fn compact_reference_target(
import_source: ImportSource::Module { asset }, import_source: ImportSource::Module { asset },
.. ..
}) = referenced_asset }) = referenced_asset
.prepare_binding(chunking_context, None, scope_hoisting_context) .get_ident(chunking_context, None, scope_hoisting_context)
.await?
.get_ident(chunking_context)
.await? .await?
else { else {
return Ok(None); return Ok(None);
...@@ -781,14 +779,12 @@ async fn build_compact_reexports( ...@@ -781,14 +779,12 @@ async fn build_compact_reexports(
export: Some(imported_key), export: Some(imported_key),
import_source: ImportSource::Module { asset }, import_source: ImportSource::Module { asset },
}) = referenced_asset }) = referenced_asset
.prepare_binding( .get_ident(
chunking_context, chunking_context,
Some(imported_name.clone()), Some(imported_name.clone()),
scope_hoisting_context, scope_hoisting_context,
) )
.await? .await?
.get_ident(chunking_context)
.await?
else { else {
// Scope-hoisted into a local binding, an external, or a namespace re-export: none of // Scope-hoisted into a local binding, an external, or a namespace re-export: none of
// these are a property read off an imported namespace. // these are a property read off an imported namespace.
...@@ -1071,7 +1067,7 @@ impl EsmExports { ...@@ -1071,7 +1067,7 @@ impl EsmExports {
let mut getters = Vec::new(); let mut getters = Vec::new();
// The keys this module's exports are emitted under. Consumers resolve the same map for this // The keys this module's exports are emitted under. Consumers resolve the same map for this
// module (see `ReferencedAsset::prepare_binding`), so both sides always agree. // module (see `ReferencedAsset::get_ident`), so both sides always agree.
let mangled_names = mangled_export_names(*module, chunking_context).await?; let mangled_names = mangled_export_names(*module, chunking_context).await?;
let flat_group = if scope_hoisting_context.module().is_some() { let flat_group = if scope_hoisting_context.module().is_some() {
*flat_export_group(*module, chunking_context).await? *flat_export_group(*module, chunking_context).await?
...@@ -1177,9 +1173,7 @@ impl EsmExports { ...@@ -1177,9 +1173,7 @@ impl EsmExports {
let referenced_asset = let referenced_asset =
ReferencedAsset::from_resolve_result(esm_ref.resolve_reference()).await?; ReferencedAsset::from_resolve_result(esm_ref.resolve_reference()).await?;
referenced_asset referenced_asset
.prepare_binding(chunking_context, Some(name.clone()), scope_hoisting_context) .get_ident(chunking_context, Some(name.clone()), scope_hoisting_context)
.await?
.get_ident(chunking_context)
.await? .await?
.map(|ident| { .map(|ident| {
let expr = ident.as_expr_individual(DUMMY_SP); let expr = ident.as_expr_individual(DUMMY_SP);
...@@ -1244,9 +1238,7 @@ impl EsmExports { ...@@ -1244,9 +1238,7 @@ impl EsmExports {
let referenced_asset = let referenced_asset =
ReferencedAsset::from_resolve_result(esm_ref.resolve_reference()).await?; ReferencedAsset::from_resolve_result(esm_ref.resolve_reference()).await?;
referenced_asset referenced_asset
.prepare_binding(chunking_context, None, scope_hoisting_context) .get_ident(chunking_context, None, scope_hoisting_context)
.await?
.get_ident(chunking_context)
.await? .await?
.map(|ident| { .map(|ident| {
let imported = ident.as_expr(DUMMY_SP, false); let imported = ident.as_expr(DUMMY_SP, false);
......
...@@ -4,8 +4,9 @@ ...@@ -4,8 +4,9 @@
//! `{ someVeryLongExportName: () => … }` and every consumer reads //! `{ someVeryLongExportName: () => … }` and every consumer reads
//! `ns["someVeryLongExportName"]`. Both sides are generated by us, so the key can be replaced by a //! `ns["someVeryLongExportName"]`. Both sides are generated by us, so the key can be replaced by a
//! much shorter one — as long as producer and consumer agree, and as long as the name is not //! much shorter one — as long as producer and consumer agree, and as long as the name is not
//! observable from user code. Scope-hoisted groups with no observable source-module namespaces //! observable from user code. Eligible members of scope-hoisted groups share a single allocation
//! share a single allocation domain, with distinct keys for each `(module, export)` binding. //! domain, with distinct keys for each `(module, export)` binding. Other members keep their own
//! source-module namespaces.
//! //!
//! [`mangled_export_names`] is the single source of truth for that mapping. Both the producer //! [`mangled_export_names`] is the single source of truth for that mapping. Both the producer
//! ([`super::export::EsmExports::code_generation`]) and the consumer //! ([`super::export::EsmExports::code_generation`]) and the consumer
...@@ -50,6 +51,8 @@ pub struct MangledExportNames(pub Option<FrozenMap<RcStr, RcStr>>); ...@@ -50,6 +51,8 @@ pub struct MangledExportNames(pub Option<FrozenMap<RcStr, RcStr>>);
/// so two source modules exporting the same name still get distinct output properties. /// so two source modules exporting the same name still get distinct output properties.
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct FlatExportGroup { pub struct FlatExportGroup {
/// The source-module identity used for the shared namespace. In mixed groups this may
/// differ from the merged factory's original entry, which needs its own namespace.
pub entry: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, pub entry: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
pub names: rustc_hash::FxHashMap< pub names: rustc_hash::FxHashMap<
ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
...@@ -71,32 +74,41 @@ pub async fn flat_export_group( ...@@ -71,32 +74,41 @@ pub async fn flat_export_group(
.await? .await?
.as_deref() .as_deref()
{ {
return Ok(flat_group_exports(**group, chunking_context)); if let Some(flat_group) = *flat_group_exports(**group, chunking_context).await?
&& flat_group.await?.names.contains_key(&module)
{
return Ok(Vc::cell(Some(flat_group)));
}
} }
Ok(Vc::cell(None)) Ok(Vc::cell(None))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
async fn flat_group_exports( pub(crate) async fn flat_group_exports(
group: Vc<MergedModuleGroup>, group: Vc<MergedModuleGroup>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<OptionFlatExportGroup>> { ) -> Result<Vc<OptionFlatExportGroup>> {
let group = group.await?; let group = group.await?;
let mut exports_to_name = Vec::new(); let mut exports_to_name = Vec::new();
let mut flat_modules = Vec::new();
for (index, (module, exposure)) in group.modules.await?.iter().enumerate() { for (index, (module, exposure)) in group.modules.await?.iter().enumerate() {
// A shared export table can only be emitted for ECMAScript modules with statically // Only externally read members contribute to the shared table. Internal namespaces
// known ESM exports; other module types need their existing runtime representation. // keep their source identity; unexposed members only use local bindings.
if *exposure != MergeableModuleExposure::External {
continue;
}
// Non-static export shapes keep their existing namespace without excluding peers.
let Some(module) = ResolvedVc::try_sidecast::<Box<dyn EcmascriptChunkPlaceable>>(*module) let Some(module) = ResolvedVc::try_sidecast::<Box<dyn EcmascriptChunkPlaceable>>(*module)
else { else {
return Ok(Vc::cell(None)); continue;
}; };
let EcmascriptExports::EsmExports(exports) = *module.get_exports().await? else { let EcmascriptExports::EsmExports(exports) = *module.get_exports().await? else {
return Ok(Vc::cell(None)); continue;
}; };
// Every member must allow renaming. An internal namespace use still needs a distinct // An observable namespace needs original names and a distinct object, not the
// source-module namespace, which the shared flat table cannot represent. // shared table. Its peers can still flatten independently.
if !exports.await?.mangle_export_names || *exposure == MergeableModuleExposure::Internal { if !exports.await?.mangle_export_names {
return Ok(Vc::cell(None)); continue;
} }
let usage = chunking_context let usage = chunking_context
.module_export_usage(*ResolvedVc::upcast(module)) .module_export_usage(*ResolvedVc::upcast(module))
...@@ -106,35 +118,40 @@ async fn flat_group_exports( ...@@ -106,35 +118,40 @@ async fn flat_group_exports(
if usage.namespace_object_may_escape if usage.namespace_object_may_escape
|| matches!(*usage.export_usage.await?, ModuleExportUsageInfo::All) || matches!(*usage.export_usage.await?, ModuleExportUsageInfo::All)
{ {
return Ok(Vc::cell(None)); continue;
} }
let expanded = exports.expand_exports(*usage.export_usage).await?; let expanded = exports.expand_exports(*usage.export_usage).await?;
// Runtime re-exports discover their names dynamically, so we cannot allocate collision-free // Runtime re-exports discover their names dynamically, so we cannot allocate collision-free
// keys for them or rewrite every access to the shared table ahead of time. // keys for them or rewrite every access to the shared table ahead of time.
if !expanded.dynamic_exports.is_empty() { if !expanded.dynamic_exports.is_empty() {
return Ok(Vc::cell(None)); continue;
} }
// Only bindings read from outside the group need table entries. Unexposed members use // Preserve even an eligible member with no used exports, since imports must still
// direct local bindings within the merged factory and require no runtime registration. // target the shared factory and agree with its empty registration.
if *exposure == MergeableModuleExposure::External { flat_modules.push(module);
for name in expanded.exports.keys() { for name in expanded.exports.keys() {
exports_to_name.push(( exports_to_name.push((module, name.clone(), RcStr::from(format!("{index}:{name}"))));
module,
name.clone(),
RcStr::from(format!("{index}:{name}")),
));
}
} }
} }
let Some(entry) = flat_modules
.iter()
.find(|module| ResolvedVc::upcast(**module) == group.entry)
.or_else(|| flat_modules.first())
.copied()
else {
return Ok(Vc::cell(None));
};
let allocated = shorten_to_unique_names(exports_to_name.iter().map(|(_, _, key)| key)); let allocated = shorten_to_unique_names(exports_to_name.iter().map(|(_, _, key)| key));
let mut names = rustc_hash::FxHashMap::<_, Vec<_>>::default(); let mut names = flat_modules
.into_iter()
.map(|module| (module, Vec::new()))
.collect::<rustc_hash::FxHashMap<_, _>>();
for (module, name, key) in exports_to_name { for (module, name, key) in exports_to_name {
names names
.entry(module) .entry(module)
.or_default() .or_default()
.push((name, allocated.get(&key).unwrap().clone())); .push((name, allocated.get(&key).unwrap().clone()));
} }
let entry = ResolvedVc::try_downcast::<Box<dyn EcmascriptChunkPlaceable>>(group.entry).unwrap();
Ok(Vc::cell(Some( Ok(Vc::cell(Some(
FlatExportGroup { FlatExportGroup {
entry, entry,
......
...@@ -162,9 +162,7 @@ impl ModuleHotReferenceCodeGen { ...@@ -162,9 +162,7 @@ impl ModuleHotReferenceCodeGen {
match &referenced_asset { match &referenced_asset {
ReferencedAsset::Some(asset) => { ReferencedAsset::Some(asset) => {
let ident = referenced_asset let ident = referenced_asset
.prepare_binding(chunking_context, None, scope_hoisting_context) .get_ident(chunking_context, None, scope_hoisting_context)
.await?
.get_ident(chunking_context)
.await?; .await?;
if let Some((namespace_ident, ctxt)) = if let Some((namespace_ident, ctxt)) =
ident.and_then(|i| i.into_module_namespace_ident()) ident.and_then(|i| i.into_module_namespace_ident())
......
...@@ -204,7 +204,7 @@ impl EcmascriptModulePartReference { ...@@ -204,7 +204,7 @@ impl EcmascriptModulePartReference {
// hoisting group (unless it's a namespace import) // hoisting group (unless it's a namespace import)
} else { } else {
let ident = referenced_asset let ident = referenced_asset
.prepare_binding( .get_ident(
chunking_context, chunking_context,
match export_usage { match export_usage {
ExportUsage::Named(export) => Some(export.clone()), ExportUsage::Named(export) => Some(export.clone()),
...@@ -216,8 +216,6 @@ impl EcmascriptModulePartReference { ...@@ -216,8 +216,6 @@ impl EcmascriptModulePartReference {
scope_hoisting_context, scope_hoisting_context,
) )
.await? .await?
.get_ident(chunking_context)
.await?
.context("part module reference should have an ident")?; .context("part module reference should have an ident")?;
match ident { match ident {
......
...@@ -93,11 +93,6 @@ impl NodeJsChunkingContextBuilder { ...@@ -93,11 +93,6 @@ impl NodeJsChunkingContextBuilder {
self 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( pub fn dynamic_chunk_content_loading(
mut self, mut self,
enable_dynamic_chunk_content_loading: bool, enable_dynamic_chunk_content_loading: bool,
...@@ -230,8 +225,6 @@ pub struct NodeJsChunkingContext { ...@@ -230,8 +225,6 @@ pub struct NodeJsChunkingContext {
runtime_type: RuntimeType, runtime_type: RuntimeType,
/// Enable nested async availability for this chunking /// Enable nested async availability for this chunking
enable_nested_async_availability: bool, enable_nested_async_availability: bool,
/// Enable module merging
enable_module_merging: bool,
/// Enable dynamic chunk content loading. /// Enable dynamic chunk content loading.
enable_dynamic_chunk_content_loading: bool, enable_dynamic_chunk_content_loading: bool,
/// Whether to minify resulting chunks /// Whether to minify resulting chunks
...@@ -291,7 +284,6 @@ impl NodeJsChunkingContext { ...@@ -291,7 +284,6 @@ impl NodeJsChunkingContext {
url_behaviors: Default::default(), url_behaviors: Default::default(),
default_url_behavior: None, default_url_behavior: None,
enable_nested_async_availability: false, enable_nested_async_availability: false,
enable_module_merging: false,
enable_dynamic_chunk_content_loading: false, enable_dynamic_chunk_content_loading: false,
environment, environment,
runtime_type, runtime_type,
...@@ -433,7 +425,7 @@ impl ChunkingContext for NodeJsChunkingContext { ...@@ -433,7 +425,7 @@ impl ChunkingContext for NodeJsChunkingContext {
#[turbo_tasks::function] #[turbo_tasks::function]
fn is_module_merging_enabled(&self) -> Vc<bool> { fn is_module_merging_enabled(&self) -> Vc<bool> {
Vc::cell(self.enable_module_merging) Vc::cell(self.merged_modules.is_some())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -832,9 +824,7 @@ impl ChunkingContext for NodeJsChunkingContext { ...@@ -832,9 +824,7 @@ impl ChunkingContext for NodeJsChunkingContext {
#[turbo_tasks::function] #[turbo_tasks::function]
fn merged_modules(&self) -> Vc<MergedModuleGroups> { fn merged_modules(&self) -> Vc<MergedModuleGroups> {
if self.enable_module_merging if let Some(merged_modules) = self.merged_modules {
&& let Some(merged_modules) = self.merged_modules
{
*merged_modules *merged_modules
} else { } else {
Vc::cell(Default::default()) Vc::cell(Default::default())
......
...@@ -620,7 +620,6 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V ...@@ -620,7 +620,6 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
RuntimeType::Development, RuntimeType::Development,
) )
.source_map_source_type(turbopack_core::chunk::SourceMapSourceType::RelativeUri) .source_map_source_type(turbopack_core::chunk::SourceMapSourceType::RelativeUri)
.module_merging(options.scope_hoisting)
.minify_type(if options.minify { .minify_type(if options.minify {
MinifyType::Minify { MinifyType::Minify {
mangle: Some(MangleType::OptimalSize), mangle: Some(MangleType::OptimalSize),
......
import { Worker } from 'node:worker_threads' import { Worker } from 'node:worker_threads'
import * as preserved from './mixed-preserved'
import {
someLongExportName as mixedFirst,
a as mixedFirstShort,
liveValue as mixedLiveValue,
} from './mixed-first'
import {
someLongExportName as mixedSecond,
a as mixedSecondShort,
} from './mixed-second'
import { import {
someLongExportName, someLongExportName,
anotherLongExportName, anotherLongExportName,
...@@ -12,6 +22,50 @@ import { ...@@ -12,6 +22,50 @@ import {
increment, increment,
} from './second' } from './second'
it('should keep one observable namespace without deoptimizing its flat peers', async () => {
const lazy = await import(
/* turbopackExports: ["namespace", "read", "update"] */ './mixed-lazy'
)
expect(lazy.namespace()).toBe(preserved)
expect(Object.keys(preserved).sort()).toEqual([
'increment',
'liveValue',
'someLongExportName',
])
expect([mixedFirst, mixedSecond, mixedFirstShort, mixedSecondShort]).toEqual([
'first',
'second',
'first-short',
'second-short',
])
expect(lazy.read()).toEqual([
'preserved',
'first',
'second',
'first-short',
'second-short',
0,
0,
])
lazy.update()
expect(preserved.liveValue).toBe(1)
expect(mixedLiveValue).toBe(1)
expect(lazy.read()).toEqual([
'preserved',
'first',
'second',
'first-short',
'second-short',
1,
1,
])
const again = await import(
/* turbopackExports: ["namespace", "read", "update"] */ './mixed-lazy'
)
expect(again.namespace()).toBe(preserved)
expect(preserved).not.toHaveProperty('a')
})
it('should be correct with scope hoisting enabled', () => { it('should be correct with scope hoisting enabled', () => {
expect(someLongExportName).toBe('shared-1') expect(someLongExportName).toBe('shared-1')
expect(anotherLongExportName).toBe('shared-2') expect(anotherLongExportName).toBe('shared-2')
......
export const someLongExportName = 'first'
export const a = 'first-short'
export let liveValue = 0
export function increment() {
liveValue++
}
import * as preserved from './mixed-preserved'
import {
someLongExportName as first,
a as firstShort,
liveValue,
increment,
} from './mixed-first'
import { someLongExportName as second, a as secondShort } from './mixed-second'
export const namespace = () => preserved
export const read = () => [
preserved.someLongExportName,
first,
second,
firstShort,
secondShort,
preserved.liveValue,
liveValue,
]
export const update = () => {
preserved.increment()
increment()
}
// Keep this first in both import lists so the factory entry needs a distinct namespace.
export const someLongExportName = 'preserved'
export let liveValue = 0
export function increment() {
liveValue++
}
export const someLongExportName = 'second'
export const a = 'second-short'
...@@ -541,7 +541,6 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> { ...@@ -541,7 +541,6 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
options.runtime_type, options.runtime_type,
) )
.minify_type(options.minify_type) .minify_type(options.minify_type)
.module_merging(options.scope_hoisting)
.shared_runtime(options.shared_runtime) .shared_runtime(options.shared_runtime)
.export_usage(if options.remove_unused_exports { .export_usage(if options.remove_unused_exports {
Some(binding_usage.unwrap().connect().to_resolved().await?) Some(binding_usage.unwrap().connect().to_resolved().await?)
...@@ -598,7 +597,6 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> { ...@@ -598,7 +597,6 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
options.runtime_type, options.runtime_type,
) )
.minify_type(options.minify_type) .minify_type(options.minify_type)
.module_merging(options.scope_hoisting)
.export_usage(if options.remove_unused_exports { .export_usage(if options.remove_unused_exports {
Some(binding_usage.unwrap().connect().to_resolved().await?) Some(binding_usage.unwrap().connect().to_resolved().await?)
} else { } else {
......
import { sameLongExportName as first, a as firstShort } from './first' import * as first from './first'
import * as second from './second' import { sameLongExportName as second, a as secondShort } from './second'
import { sameLongExportName as third, a as thirdShort } from './third'
console.log(first, firstShort, Object.keys(second), second) // The factory entry keeps its namespace; the other two members share a flat table.
console.log(Object.keys(first), first, second, third, secondShort, thirdShort)
import('./lazy').then(({ read }) => console.log(read())) import('./lazy').then(({ read }) => console.log(read()))
import { sameLongExportName as first, a as firstShort } from './first' import { sameLongExportName as first, a as firstShort } from './first'
import { sameLongExportName as second, a as secondShort } from './second' import { sameLongExportName as second, a as secondShort } from './second'
import { sameLongExportName as third, a as thirdShort } from './third'
export const read = () => [first, second, firstShort, secondShort] export const read = () => [
first,
second,
third,
firstShort,
secondShort,
thirdShort,
]
export const sameLongExportName = 'third'
export const a = 'third-short'
...@@ -3,6 +3,16 @@ ...@@ -3,6 +3,16 @@
((__turbopack_context__) => { ((__turbopack_context__) => {
"use strict"; "use strict";
__turbopack_context__.s([
"t",
()=>a2,
"r",
()=>sameLongExportName2,
"_",
()=>a1,
"g",
()=>sameLongExportName1
], "[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/second.js [test] (ecmascript)");
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/first.js [test] (ecmascript) // MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/first.js [test] (ecmascript)
; ;
const sameLongExportName = 'first'; const sameLongExportName = 'first';
...@@ -11,7 +21,7 @@ __turbopack_context__.s([ ...@@ -11,7 +21,7 @@ __turbopack_context__.s([
"a", "a",
0, 0,
a, a,
"k", "sameLongExportName",
0, 0,
sameLongExportName sameLongExportName
], "[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/first.js [test] (ecmascript)"); ], "[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/first.js [test] (ecmascript)");
...@@ -19,14 +29,10 @@ __turbopack_context__.s([ ...@@ -19,14 +29,10 @@ __turbopack_context__.s([
; ;
const sameLongExportName1 = 'second'; const sameLongExportName1 = 'second';
const a1 = 'second-short'; const a1 = 'second-short';
__turbopack_context__.s([ // MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/third.js [test] (ecmascript)
"a", ;
0, const sameLongExportName2 = 'third';
a1, const a2 = 'third-short';
"sameLongExportName",
0,
sameLongExportName1
], "[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/second.js [test] (ecmascript)");
}), }),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict"; "use strict";
...@@ -35,7 +41,9 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo ...@@ -35,7 +41,9 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/second.js [test] (ecmascript)"); var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/second.js [test] (ecmascript)");
; ;
; ;
console.log(__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$first$2e$js__$5b$test$5d$__$28$ecmascript$29$__["k"], __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$first$2e$js__$5b$test$5d$__$28$ecmascript$29$__["a"], Object.keys(__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__), __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__); ;
// The factory entry keeps its namespace; the other two members share a flat table.
console.log(Object.keys(__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$first$2e$js__$5b$test$5d$__$28$ecmascript$29$__), __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$first$2e$js__$5b$test$5d$__$28$ecmascript$29$__, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__["g"], __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__["r"], __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__["_"], __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__["t"]);
__turbopack_context__.A("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/lazy.js [test] (ecmascript, async loader)").then(({ read })=>console.log(read())); __turbopack_context__.A("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/lazy.js [test] (ecmascript, async loader)").then(({ read })=>console.log(read()));
__turbopack_context__.s([]); __turbopack_context__.s([]);
}), }),
......
...@@ -2,6 +2,6 @@ ...@@ -2,6 +2,6 @@
"version": 3, "version": 3,
"sources": [], "sources": [],
"sections": [ "sections": [
{"offset": {"line": 5, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/first.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/second.js"],"sourcesContent":["export const sameLongExportName = 'first'\nexport const a = 'first-short'\n","export const sameLongExportName = 'second'\nexport const a = 'second-short'\n"],"names":["sameLongExportName","a"],"mappings":";;AAAO,MAAMA,qBAAqB;AAC3B,MAAMC,IAAI;;;;;;;;;;;ACDV,MAAMD,sBAAqB;AAC3B,MAAM,KAAI"}}, {"offset": {"line": 5, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/first.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/second.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/third.js"],"sourcesContent":["export const sameLongExportName = 'first'\nexport const a = 'first-short'\n","export const sameLongExportName = 'second'\nexport const a = 'second-short'\n","export const sameLongExportName = 'third'\nexport const a = 'third-short'\n"],"names":["sameLongExportName","a"],"mappings":";;;;;;;;;;;;AAAO,MAAMA,qBAAqB;AAC3B,MAAMC,IAAI;;;;;;;;;;;ACDV,MAAMD,sBAAqB;AAC3B,MAAM,KAAI;;;ACDV,MAAMA,sBAAqB;AAC3B,MAAMC,KAAI"}},
{"offset": {"line": 33, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/index.js"],"sourcesContent":["import { sameLongExportName as first, a as firstShort } from './first'\nimport * as second from './second'\n\nconsole.log(first, firstShort, Object.keys(second), second)\nimport('./lazy').then(({ read }) => console.log(read()))\n"],"names":["console","log","Object","keys","imported module [project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/second.js [test] (ecmascript)","then","read"],"mappings":"AAAA;AACA;;;AAEAA,QAAQC,GAAG,CAAC,oOAAK,EAAE,oOAAU,EAAEC,OAAOC,IAAI,CAACC,mOAASA;AACpD,2KAAiBC,IAAI,CAAC,CAAC,EAAEC,IAAI,EAAE,GAAKN,QAAQC,GAAG,CAACK"}}] {"offset": {"line": 39, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/index.js"],"sourcesContent":["import * as first from './first'\nimport { sameLongExportName as second, a as secondShort } from './second'\nimport { sameLongExportName as third, a as thirdShort } from './third'\n\n// The factory entry keeps its namespace; the other two members share a flat table.\nconsole.log(Object.keys(first), first, second, third, secondShort, thirdShort)\nimport('./lazy').then(({ read }) => console.log(read()))\n"],"names":["console","log","Object","keys","imported module [project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/first.js [test] (ecmascript)","then","read"],"mappings":"AAAA;AACA;;;;AAGA,mFAAmF;AACnFA,QAAQC,GAAG,CAACC,OAAOC,IAAI,CAACC,kOAAQA,iOAAO,qOAAM,EAAE,qOAAK,EAAE,qOAAW,EAAE,qOAAU;AAC7E,2KAAiBC,IAAI,CAAC,CAAC,EAAEC,IAAI,EAAE,GAAKN,QAAQC,GAAG,CAACK"}}]
} }
\ No newline at end of file
...@@ -6,11 +6,14 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo ...@@ -6,11 +6,14 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/second.js [test] (ecmascript)"); var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/second.js [test] (ecmascript)");
; ;
; ;
;
const read = ()=>[ const read = ()=>[
__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$first$2e$js__$5b$test$5d$__$28$ecmascript$29$__["k"], __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$first$2e$js__$5b$test$5d$__$28$ecmascript$29$__["sameLongExportName"],
__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__["sameLongExportName"], __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__["g"],
__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__["r"],
__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$first$2e$js__$5b$test$5d$__$28$ecmascript$29$__["a"], __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$first$2e$js__$5b$test$5d$__$28$ecmascript$29$__["a"],
__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__["a"] __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__["_"],
__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$mangle$2d$exports$2f$flat$2d$hoisted$2d$namespace$2f$input$2f$second$2e$js__$5b$test$5d$__$28$ecmascript$29$__["t"]
]; ];
__turbopack_context__.s([ __turbopack_context__.s([
"read", "read",
......
...@@ -2,5 +2,5 @@ ...@@ -2,5 +2,5 @@
"version": 3, "version": 3,
"sources": [], "sources": [],
"sections": [ "sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/lazy.js"],"sourcesContent":["import { sameLongExportName as first, a as firstShort } from './first'\nimport { sameLongExportName as second, a as secondShort } from './second'\n\nexport const read = () => [first, second, firstShort, secondShort]\n"],"names":["read"],"mappings":"AAAA;AACA;;;AAEO,MAAMA,OAAO,IAAM;QAAC,oOAAK;QAAE,sPAAM;QAAE,oOAAU;QAAE,qOAAW;KAAC"}}] {"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/flat-hoisted-namespace/input/lazy.js"],"sourcesContent":["import { sameLongExportName as first, a as firstShort } from './first'\nimport { sameLongExportName as second, a as secondShort } from './second'\nimport { sameLongExportName as third, a as thirdShort } from './third'\n\nexport const read = () => [\n first,\n second,\n third,\n firstShort,\n secondShort,\n thirdShort,\n]\n"],"names":["read"],"mappings":"AAAA;AACA;;;;AAGO,MAAMA,OAAO,IAAM;QACxB,qPAAK;QACL,qOAAM;QACN,qOAAK;QACL,oOAAU;QACV,qOAAW;QACX,qOAAU;KACX"}}]
} }
\ No newline at end of file
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