Unverified Commit 3e024743 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[turbopack] Optimize `export const` to bind readonly values not getters (#82760)

## Optimize ESM Exports

### What

This builds on the work from #82214

For an esm module like

```
export const foo = 2;
```

turbopack will generate a factory function like

```
__turbopack_context__ => {
  __turbopack_context__.s(['foo', ()=>foo]);
  const foo = 2;
}
```

- we expose the exports early to enable circular imports  between modules
- we expose as 'getter functions' to enable live bindings

These behaviors are necessary to uphold the ESM specification, however, we can optimize it by avoiding getter functions most of the time

```

  const foo = 2;
__turbopack_context__ => {
  __turbopack_context__.s(['foo', 0, foo]);
}
```

If we can statically detect that the module is not part of an import cycle then we can delay registering its exports until the end of evaluation.  Then if we also determine that a given export is never mutated (after module evaluation) then we can export it as a value instead of a getter.

We use a small numeric discriminator flag this to the runtime (otherwise exporting a function is ambiguous).

This approach will save code size (2 bytes per const binding), memory (no functions to allocate), and improve parsing and execution performance.

Currently we use `export const` as a hint and `export default <expr>` to decide that a binding is not 'live'.  Future PRs will enhance this to cover more cases.

# Performance

the module-cost benchmark just uses `export const` so that is enough to prove the effectiveness of avoiding getters.

## Benchmark Results: CHANGE vs HEAD (Median Values)

| Scenario | Metric | HEAD (ms) | CHANGE (ms) | Speedup | % Improvement |
| --- | --- | --- | --- | --- | --- |
| **Client CommonJS** | Load Duration | 19\.80 | 19\.60 | 1\.01x | \+1.0% ✅ |
|  | Execute Duration | 19\.30 | 19\.00 | 1\.02x | \+1.6% ✅ |
| **Client ESM** | Load Duration | 18\.15 | 17\.70 | 1\.03x | \+2.5% ✅ |
|  | Execute Duration | 46\.85 | 27\.95 | 1\.68x | \+40.3% ✅ |
| **Pages API CommonJS** | Load Duration | 19\.41 | 19\.52 | 0\.99x | \-0.6% ❌ |
|  | Execute Duration | 25\.34 | 25\.15 | 1\.01x | \+0.7% ✅ |
| **Pages API ESM** | Load Duration | 26\.02 | 22\.08 | 1\.18x | \+15.1% ✅ |
|  | Execute Duration | 56\.30 | 35\.12 | 1\.60x | \+37.6% ✅ |

As expected this is a substantial improvement to ESM.  The CJS results are just noise and should provide an idea of the variance of the run.

Load time improves due to smaller and simpler code
Execution time improves since there are fewer function objects to construct
parent 074638be
...@@ -100,9 +100,10 @@ impl EcmascriptChunkPlaceable for NextServerComponentModule { ...@@ -100,9 +100,10 @@ impl EcmascriptChunkPlaceable for NextServerComponentModule {
); );
let mut exports = BTreeMap::new(); let mut exports = BTreeMap::new();
let default = rcstr!("default");
exports.insert( exports.insert(
rcstr!("default"), default.clone(),
EsmExport::ImportedBinding(module_reference, rcstr!("default"), false), EsmExport::ImportedBinding(module_reference, default, false),
); );
Ok(EcmascriptExports::EsmExports( Ok(EcmascriptExports::EsmExports(
......
...@@ -100,9 +100,10 @@ impl EcmascriptChunkPlaceable for NextServerUtilityModule { ...@@ -100,9 +100,10 @@ impl EcmascriptChunkPlaceable for NextServerUtilityModule {
); );
let mut exports = BTreeMap::new(); let mut exports = BTreeMap::new();
let default = rcstr!("default");
exports.insert( exports.insert(
rcstr!("default"), default.clone(),
EsmExport::ImportedBinding(module_reference, rcstr!("default"), false), EsmExport::ImportedBinding(module_reference, default, false),
); );
Ok(EcmascriptExports::EsmExports( Ok(EcmascriptExports::EsmExports(
......
...@@ -24,7 +24,7 @@ use turbopack_core::{ ...@@ -24,7 +24,7 @@ use turbopack_core::{
module_graph::{ module_graph::{
ModuleGraph, ModuleGraph,
chunk_group_info::ChunkGroup, chunk_group_info::ChunkGroup,
export_usage::{ExportUsageInfo, ModuleExportUsageInfo}, export_usage::{ExportUsageInfo, ModuleExportUsage},
}, },
output::{OutputAsset, OutputAssets}, output::{OutputAsset, OutputAssets},
}; };
...@@ -756,11 +756,13 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -756,11 +756,13 @@ impl ChunkingContext for BrowserChunkingContext {
async fn module_export_usage( async fn module_export_usage(
self: Vc<Self>, self: Vc<Self>,
module: ResolvedVc<Box<dyn Module>>, module: ResolvedVc<Box<dyn Module>>,
) -> Result<Vc<ModuleExportUsageInfo>> { ) -> Result<Vc<ModuleExportUsage>> {
if let Some(export_usage) = self.await?.export_usage { if let Some(export_usage) = self.await?.export_usage {
Ok(export_usage.await?.used_exports(module)) Ok(export_usage.await?.used_exports(module).await?)
} else { } else {
Ok(ModuleExportUsageInfo::all()) // In development mode, we don't have export usage info, so we assume all exports are
// used.
Ok(ModuleExportUsage::all())
} }
} }
} }
...@@ -14,7 +14,7 @@ use crate::{ ...@@ -14,7 +14,7 @@ use crate::{
ident::AssetIdent, ident::AssetIdent,
module::Module, module::Module,
module_graph::{ module_graph::{
ModuleGraph, chunk_group_info::ChunkGroup, export_usage::ModuleExportUsageInfo, ModuleGraph, chunk_group_info::ChunkGroup, export_usage::ModuleExportUsage,
module_batches::BatchingConfig, module_batches::BatchingConfig,
}, },
output::{OutputAsset, OutputAssets}, output::{OutputAsset, OutputAssets},
...@@ -295,7 +295,7 @@ pub trait ChunkingContext { ...@@ -295,7 +295,7 @@ pub trait ChunkingContext {
async fn module_export_usage( async fn module_export_usage(
self: Vc<Self>, self: Vc<Self>,
module: Vc<Box<dyn Module>>, module: Vc<Box<dyn Module>>,
) -> Result<Vc<ModuleExportUsageInfo>>; ) -> Result<Vc<ModuleExportUsage>>;
} }
pub trait ChunkingContextExt { pub trait ChunkingContextExt {
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
use anyhow::Result; use anyhow::Result;
use auto_hash_map::AutoSet; use auto_hash_map::AutoSet;
use rustc_hash::FxHashMap; use rustc_hash::{FxHashMap, FxHashSet};
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
...@@ -13,22 +13,45 @@ pub async fn compute_export_usage_info( ...@@ -13,22 +13,45 @@ pub async fn compute_export_usage_info(
graph: ResolvedVc<ModuleGraph>, graph: ResolvedVc<ModuleGraph>,
) -> Result<Vc<ExportUsageInfo>> { ) -> Result<Vc<ExportUsageInfo>> {
let mut used_exports = FxHashMap::<_, ModuleExportUsageInfo>::default(); let mut used_exports = FxHashMap::<_, ModuleExportUsageInfo>::default();
let graph = graph.await?;
graph graph
.await?
.traverse_all_edges_unordered(|(_, ref_data), target| { .traverse_all_edges_unordered(|(_, ref_data), target| {
if let Some(target_module) = ResolvedVc::try_downcast::<Box<dyn Module>>(target.module) let e = used_exports.entry(target.module).or_default();
{
let e = used_exports.entry(target_module).or_default();
e.add(&ref_data.export); e.add(&ref_data.export);
}
Ok(()) Ok(())
}) })
.await?; .await?;
// Compute cycles and select modules to be 'circuit breakers'
// A circuit breaker module will need to eagerly export lazy getters for its exports to break an
// evaluation cycle all other modules can export values after defining them
let mut circuit_breakers = FxHashSet::default();
graph
.traverse_cycles(
|e| e.chunking_type.is_parallel(),
|cycle| {
// To break cycles we need to ensure that no importing module can observe a
// partially populated exports object.
// We could compute this based on the module graph via a DFS from each entry point
// to the cycle. Whatever node is hit first is an entry point to the cycle.
// (scope hoisting does something similar) and then we would only need to
// mark 'entry' modules (basically the targets of back edges in the export graph) as
// circuit breakers. For now we just mark everything on the theory that cycles are
// rare. For vercel-site on 8/22/2025 there were 106 cycles covering 800 modules
// (or 1.2% of all modules). So with this analysis we could potentially drop 80% of
// the cycle breaker modules.
circuit_breakers.extend(cycle.iter().map(|n| n.module));
},
)
.await?;
Ok(ExportUsageInfo { used_exports }.cell()) Ok(ExportUsageInfo {
used_exports,
circuit_breakers,
}
.cell())
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
...@@ -37,17 +60,46 @@ pub struct OptionExportUsageInfo(Option<ResolvedVc<ExportUsageInfo>>); ...@@ -37,17 +60,46 @@ pub struct OptionExportUsageInfo(Option<ResolvedVc<ExportUsageInfo>>);
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct ExportUsageInfo { pub struct ExportUsageInfo {
used_exports: FxHashMap<ResolvedVc<Box<dyn Module>>, ModuleExportUsageInfo>, used_exports: FxHashMap<ResolvedVc<Box<dyn Module>>, ModuleExportUsageInfo>,
circuit_breakers: FxHashSet<ResolvedVc<Box<dyn Module>>>,
}
#[turbo_tasks::value(shared)]
pub struct ModuleExportUsage {
pub export_usage: ResolvedVc<ModuleExportUsageInfo>,
// Whether this module exists in an import cycle and has been selected to break the cycle.
pub is_circuit_breaker: bool,
}
#[turbo_tasks::value_impl]
impl ModuleExportUsage {
#[turbo_tasks::function]
pub async fn all() -> Result<Vc<Self>> {
Ok(Self {
export_usage: ModuleExportUsageInfo::all().to_resolved().await?,
is_circuit_breaker: true,
}
.cell())
}
} }
impl ExportUsageInfo { impl ExportUsageInfo {
pub fn used_exports(&self, module: ResolvedVc<Box<dyn Module>>) -> Vc<ModuleExportUsageInfo> { pub async fn used_exports(
if let Some(exports) = self.used_exports.get(&module) { &self,
exports.clone().cell() module: ResolvedVc<Box<dyn Module>>,
) -> Result<Vc<ModuleExportUsage>> {
let is_circuit_breaker = self.circuit_breakers.contains(&module);
let export_usage = if let Some(exports) = self.used_exports.get(&module) {
exports.clone().resolved_cell()
} else { } else {
// We exclude template files from tree shaking because they are entrypoints to the // We exclude template files from tree shaking because they are entrypoints to the
// module graph. // module graph.
ModuleExportUsageInfo::all() ModuleExportUsageInfo::all().to_resolved().await?
};
Ok(ModuleExportUsage {
export_usage,
is_circuit_breaker,
} }
.cell())
} }
} }
......
...@@ -105,29 +105,52 @@ function createModuleObject(id: ModuleId): Module { ...@@ -105,29 +105,52 @@ function createModuleObject(id: ModuleId): Module {
} }
} }
type BindingTag = 0
const BindingTag_Value = 0 as BindingTag
// an arbitrary sequence of bindings as
// - a prop name
// - BindingTag_Value, a value to be bound directly, or
// - 1 or 2 functions to bind as getters and sdetters
type EsmBindings = Array<
string | BindingTag | (() => unknown) | ((v: unknown) => void) | unknown
>
/** /**
* Adds the getters to the exports object. * Adds the getters to the exports object.
*/ */
function esm( function esm(exports: Exports, bindings: EsmBindings) {
exports: Exports,
getters: Array<string | (() => unknown) | ((v: unknown) => void)>
) {
defineProp(exports, '__esModule', { value: true }) defineProp(exports, '__esModule', { value: true })
if (toStringTag) defineProp(exports, toStringTag, { value: 'Module' }) if (toStringTag) defineProp(exports, toStringTag, { value: 'Module' })
let i = 0 let i = 0
while (i < getters.length) { while (i < bindings.length) {
const propName = getters[i++] as string const propName = bindings[i++] as string
// TODO(luke.sandberg): we could support raw values here, but would need a discriminator beyond 'not a function' const tagOrFunction = bindings[i++]
const getter = getters[i++] as () => unknown if (typeof tagOrFunction === 'number') {
if (typeof getters[i] === 'function') { if (tagOrFunction === BindingTag_Value) {
// a setter defineProp(exports, propName, {
defineProp(exports, propName, { value: bindings[i++],
get: getter, enumerable: true,
set: getters[i++] as (v: unknown) => void, writable: false,
enumerable: true, })
}) } else {
throw new Error(`unexpected tag: ${tagOrFunction}`)
}
} else { } else {
defineProp(exports, propName, { get: getter, enumerable: true }) const getterFn = tagOrFunction as () => unknown
if (typeof bindings[i] === 'function') {
const setterFn = bindings[i++] as (v: unknown) => void
defineProp(exports, propName, {
get: getterFn,
set: setterFn,
enumerable: true,
})
} else {
defineProp(exports, propName, {
get: getterFn,
enumerable: true,
})
}
} }
} }
Object.seal(exports) Object.seal(exports)
...@@ -138,7 +161,7 @@ function esm( ...@@ -138,7 +161,7 @@ function esm(
*/ */
function esmExport( function esmExport(
this: TurbopackBaseContext<Module>, this: TurbopackBaseContext<Module>,
getters: Array<string | (() => unknown) | ((v: unknown) => void)>, bindings: EsmBindings,
id: ModuleId | undefined id: ModuleId | undefined
) { ) {
let module: Module let module: Module
...@@ -151,7 +174,7 @@ function esmExport( ...@@ -151,7 +174,7 @@ function esmExport(
exports = this.e exports = this.e
} }
module.namespaceObject = exports module.namespaceObject = exports
esm(exports, getters) esm(exports, bindings)
} }
contextPrototype.s = esmExport contextPrototype.s = esmExport
...@@ -203,7 +226,7 @@ function dynamicExport( ...@@ -203,7 +226,7 @@ function dynamicExport(
id: ModuleId | undefined id: ModuleId | undefined
) { ) {
let module: Module let module: Module
let exports: Module['exports'] let exports: Exports
if (id != null) { if (id != null) {
module = getOverwrittenModule(this.c, id) module = getOverwrittenModule(this.c, id)
exports = module.exports exports = module.exports
...@@ -275,8 +298,7 @@ function interopEsm( ...@@ -275,8 +298,7 @@ function interopEsm(
ns: EsmNamespaceObject, ns: EsmNamespaceObject,
allowExportDefault?: boolean allowExportDefault?: boolean
) { ) {
const getters: Array<string | (() => unknown) | ((v: unknown) => void)> = [] const bindings: EsmBindings = []
// The index of the `default` export if any
let defaultLocation = -1 let defaultLocation = -1
for ( for (
let current = raw; let current = raw;
...@@ -285,9 +307,9 @@ function interopEsm( ...@@ -285,9 +307,9 @@ function interopEsm(
current = getProto(current) current = getProto(current)
) { ) {
for (const key of Object.getOwnPropertyNames(current)) { for (const key of Object.getOwnPropertyNames(current)) {
getters.push(key, createGetter(raw, key)) bindings.push(key, createGetter(raw, key))
if (defaultLocation === -1 && key === 'default') { if (defaultLocation === -1 && key === 'default') {
defaultLocation = getters.length - 1 defaultLocation = bindings.length - 1
} }
} }
} }
...@@ -297,13 +319,14 @@ function interopEsm( ...@@ -297,13 +319,14 @@ function interopEsm(
if (!(allowExportDefault && defaultLocation >= 0)) { if (!(allowExportDefault && defaultLocation >= 0)) {
// Replace the binding with one for the namespace itself in order to preserve iteration order. // Replace the binding with one for the namespace itself in order to preserve iteration order.
if (defaultLocation >= 0) { if (defaultLocation >= 0) {
getters[defaultLocation] = () => raw // Replace the getter with the value
bindings.splice(defaultLocation, 1, BindingTag_Value, raw)
} else { } else {
getters.push('default', () => raw) bindings.push('default', BindingTag_Value, raw)
} }
} }
esm(ns, getters) esm(ns, bindings)
return ns return ns
} }
...@@ -343,7 +366,7 @@ function asyncLoader( ...@@ -343,7 +366,7 @@ function asyncLoader(
const loader = this.r(moduleId) as ( const loader = this.r(moduleId) as (
importFunction: EsmImport importFunction: EsmImport
) => Promise<Exports> ) => Promise<Exports>
return loader(this.i.bind(this)) return loader(esmImport.bind(this))
} }
contextPrototype.A = asyncLoader contextPrototype.A = asyncLoader
......
...@@ -45,6 +45,8 @@ pub struct CodeGeneration { ...@@ -45,6 +45,8 @@ pub struct CodeGeneration {
pub visitors: Vec<(Vec<AstParentKind>, Box<dyn AstModifier>)>, pub visitors: Vec<(Vec<AstParentKind>, Box<dyn AstModifier>)>,
pub hoisted_stmts: Vec<CodeGenerationHoistedStmt>, pub hoisted_stmts: Vec<CodeGenerationHoistedStmt>,
pub early_hoisted_stmts: Vec<CodeGenerationHoistedStmt>, pub early_hoisted_stmts: Vec<CodeGenerationHoistedStmt>,
pub late_stmts: Vec<CodeGenerationHoistedStmt>,
pub early_late_stmts: Vec<CodeGenerationHoistedStmt>,
pub comments: Option<SwcComments>, pub comments: Option<SwcComments>,
} }
...@@ -59,11 +61,15 @@ impl CodeGeneration { ...@@ -59,11 +61,15 @@ impl CodeGeneration {
visitors: Vec<(Vec<AstParentKind>, Box<dyn AstModifier>)>, visitors: Vec<(Vec<AstParentKind>, Box<dyn AstModifier>)>,
hoisted_stmts: Vec<CodeGenerationHoistedStmt>, hoisted_stmts: Vec<CodeGenerationHoistedStmt>,
early_hoisted_stmts: Vec<CodeGenerationHoistedStmt>, early_hoisted_stmts: Vec<CodeGenerationHoistedStmt>,
late_stmts: Vec<CodeGenerationHoistedStmt>,
early_late_stmts: Vec<CodeGenerationHoistedStmt>,
) -> Self { ) -> Self {
CodeGeneration { CodeGeneration {
visitors, visitors,
hoisted_stmts, hoisted_stmts,
early_hoisted_stmts, early_hoisted_stmts,
late_stmts,
early_late_stmts,
..Default::default() ..Default::default()
} }
} }
......
...@@ -2015,6 +2015,8 @@ fn process_content_with_code_gens( ...@@ -2015,6 +2015,8 @@ fn process_content_with_code_gens(
let mut root_visitors = Vec::new(); let mut root_visitors = Vec::new();
let mut early_hoisted_stmts = FxIndexMap::default(); let mut early_hoisted_stmts = FxIndexMap::default();
let mut hoisted_stmts = FxIndexMap::default(); let mut hoisted_stmts = FxIndexMap::default();
let mut early_late_stmts = FxIndexMap::default();
let mut late_stmts = FxIndexMap::default();
for code_gen in code_gens { for code_gen in code_gens {
for CodeGenerationHoistedStmt { key, stmt } in code_gen.hoisted_stmts.drain(..) { for CodeGenerationHoistedStmt { key, stmt } in code_gen.hoisted_stmts.drain(..) {
hoisted_stmts.entry(key).or_insert(stmt); hoisted_stmts.entry(key).or_insert(stmt);
...@@ -2022,7 +2024,12 @@ fn process_content_with_code_gens( ...@@ -2022,7 +2024,12 @@ fn process_content_with_code_gens(
for CodeGenerationHoistedStmt { key, stmt } in code_gen.early_hoisted_stmts.drain(..) { for CodeGenerationHoistedStmt { key, stmt } in code_gen.early_hoisted_stmts.drain(..) {
early_hoisted_stmts.insert(key.clone(), stmt); early_hoisted_stmts.insert(key.clone(), stmt);
} }
for CodeGenerationHoistedStmt { key, stmt } in code_gen.late_stmts.drain(..) {
late_stmts.insert(key.clone(), stmt);
}
for CodeGenerationHoistedStmt { key, stmt } in code_gen.early_late_stmts.drain(..) {
early_late_stmts.insert(key.clone(), stmt);
}
for (path, visitor) in &code_gen.visitors { for (path, visitor) in &code_gen.visitors {
if path.is_empty() { if path.is_empty() {
root_visitors.push(&**visitor); root_visitors.push(&**visitor);
...@@ -2053,6 +2060,12 @@ fn process_content_with_code_gens( ...@@ -2053,6 +2060,12 @@ fn process_content_with_code_gens(
.chain(hoisted_stmts.into_values()) .chain(hoisted_stmts.into_values())
.map(ModuleItem::Stmt), .map(ModuleItem::Stmt),
); );
body.extend(
early_late_stmts
.into_values()
.chain(late_stmts.into_values())
.map(ModuleItem::Stmt),
);
} }
Program::Script(Script { body, .. }) => { Program::Script(Script { body, .. }) => {
body.splice( body.splice(
...@@ -2061,6 +2074,11 @@ fn process_content_with_code_gens( ...@@ -2061,6 +2074,11 @@ fn process_content_with_code_gens(
.into_values() .into_values()
.chain(hoisted_stmts.into_values()), .chain(hoisted_stmts.into_values()),
); );
body.extend(
early_late_stmts
.into_values()
.chain(late_stmts.into_values()),
);
} }
}; };
} }
......
...@@ -41,6 +41,7 @@ use crate::{ ...@@ -41,6 +41,7 @@ use crate::{
analyzer::imports::ImportAnnotations, analyzer::imports::ImportAnnotations,
chunk::{EcmascriptChunkPlaceable, EcmascriptExports}, chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
code_gen::{CodeGeneration, CodeGenerationHoistedStmt}, code_gen::{CodeGeneration, CodeGenerationHoistedStmt},
export::Liveness,
magic_identifier, magic_identifier,
references::{ references::{
esm::EsmExport, esm::EsmExport,
...@@ -62,7 +63,11 @@ pub enum ReferencedAsset { ...@@ -62,7 +63,11 @@ pub enum ReferencedAsset {
#[derive(Debug)] #[derive(Debug)]
pub enum ReferencedAssetIdent { pub enum ReferencedAssetIdent {
/// The given export (or namespace) is a local binding in the current scope hoisting group. /// The given export (or namespace) is a local binding in the current scope hoisting group.
LocalBinding { ident: RcStr, ctxt: SyntaxContext }, LocalBinding {
ident: RcStr,
ctxt: SyntaxContext,
liveness: Liveness,
},
/// The given export (or namespace) should be imported and will be assigned to a new variable. /// The given export (or namespace) should be imported and will be assigned to a new variable.
Module { Module {
namespace_ident: String, namespace_ident: String,
...@@ -85,9 +90,11 @@ impl ReferencedAssetIdent { ...@@ -85,9 +90,11 @@ impl ReferencedAssetIdent {
pub fn as_expr_individual(&self, span: Span) -> Either<Ident, MemberExpr> { pub fn as_expr_individual(&self, span: Span) -> Either<Ident, MemberExpr> {
match self { match self {
ReferencedAssetIdent::LocalBinding { ident, ctxt } => { ReferencedAssetIdent::LocalBinding {
Either::Left(Ident::new(ident.as_str().into(), span, *ctxt)) ident,
} ctxt,
liveness: _,
} => Either::Left(Ident::new(ident.as_str().into(), span, *ctxt)),
ReferencedAssetIdent::Module { ReferencedAssetIdent::Module {
namespace_ident, namespace_ident,
ctxt, ctxt,
...@@ -172,13 +179,14 @@ impl ReferencedAsset { ...@@ -172,13 +179,14 @@ impl ReferencedAsset {
let exports = exports.expand_exports(ModuleExportUsageInfo::all()).await?; let exports = exports.expand_exports(ModuleExportUsageInfo::all()).await?;
let esm_export = exports.exports.get(export); let esm_export = exports.exports.get(export);
match esm_export { match esm_export {
Some(EsmExport::LocalBinding(_, _)) => { Some(EsmExport::LocalBinding(_name, liveness)) => {
// 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(Some(ReferencedAssetIdent::LocalBinding { return Ok(Some(ReferencedAssetIdent::LocalBinding {
ident: export.clone(), ident: export.clone(),
ctxt, ctxt,
liveness: *liveness,
})); }));
} }
Some(b @ EsmExport::ImportedBinding(esm_ref, _, _)) Some(b @ EsmExport::ImportedBinding(esm_ref, _, _))
......
...@@ -11,7 +11,7 @@ pub use self::{ ...@@ -11,7 +11,7 @@ pub use self::{
base::EsmAssetReference, base::EsmAssetReference,
binding::EsmBinding, binding::EsmBinding,
dynamic::EsmAsyncAssetReference, dynamic::EsmAsyncAssetReference,
export::{EsmExport, EsmExports, FoundExportType}, export::{EsmExport, EsmExports, FoundExportType, Liveness},
meta::{ImportMetaBinding, ImportMetaRef}, meta::{ImportMetaBinding, ImportMetaRef},
module_item::EsmModuleItem, module_item::EsmModuleItem,
url::{UrlAssetReference, UrlRewriteBehavior}, url::{UrlAssetReference, UrlRewriteBehavior},
......
...@@ -141,6 +141,7 @@ use crate::{ ...@@ -141,6 +141,7 @@ use crate::{
}, },
chunk::EcmascriptExports, chunk::EcmascriptExports,
code_gen::{CodeGen, CodeGens, IntoCodeGenReference}, code_gen::{CodeGen, CodeGens, IntoCodeGenReference},
export::Liveness,
magic_identifier, magic_identifier,
parse::parse, parse::parse,
references::{ references::{
...@@ -3219,28 +3220,6 @@ fn as_parent_path(ast_path: &AstNodePath<AstParentNodeRef<'_>>) -> Vec<AstParent ...@@ -3219,28 +3220,6 @@ fn as_parent_path(ast_path: &AstNodePath<AstParentNodeRef<'_>>) -> Vec<AstParent
ast_path.iter().map(|n| n.kind()).collect() ast_path.iter().map(|n| n.kind()).collect()
} }
fn for_each_ident_in_decl(decl: &Decl, f: &mut impl FnMut(RcStr)) {
match decl {
Decl::Class(ClassDecl { ident, .. }) | Decl::Fn(FnDecl { ident, .. }) => {
f(ident.sym.as_str().into());
}
Decl::Var(var_decl) => {
let decls = &*var_decl.decls;
decls
.iter()
.for_each(|VarDeclarator { name, .. }| for_each_ident_in_pat(name, f));
}
Decl::Using(using_decl) => {
let decls = &*using_decl.decls;
decls
.iter()
.for_each(|VarDeclarator { name, .. }| for_each_ident_in_pat(name, f));
}
Decl::TsInterface(_) | Decl::TsTypeAlias(_) | Decl::TsEnum(_) | Decl::TsModule(_) => {
// ignore typescript for code generation
}
}
}
fn for_each_ident_in_pat(pat: &Pat, f: &mut impl FnMut(RcStr)) { fn for_each_ident_in_pat(pat: &Pat, f: &mut impl FnMut(RcStr)) {
match pat { match pat {
Pat::Ident(BindingIdent { id, .. }) => { Pat::Ident(BindingIdent { id, .. }) => {
...@@ -3301,8 +3280,8 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> { ...@@ -3301,8 +3280,8 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> {
if export.src.is_none() { if export.src.is_none() {
for spec in export.specifiers.iter() { for spec in export.specifiers.iter() {
fn to_string(name: &ModuleExportName) -> &Atom { fn to_rcstr(name: &ModuleExportName) -> RcStr {
name.atom() name.atom().as_str().into()
} }
match spec { match spec {
ExportSpecifier::Namespace(_) => { ExportSpecifier::Namespace(_) => {
...@@ -3318,8 +3297,8 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> { ...@@ -3318,8 +3297,8 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> {
); );
} }
ExportSpecifier::Named(ExportNamedSpecifier { orig, exported, .. }) => { ExportSpecifier::Named(ExportNamedSpecifier { orig, exported, .. }) => {
let key = to_string(exported.as_ref().unwrap_or(orig)).as_str().into(); let key = to_rcstr(exported.as_ref().unwrap_or(orig));
let binding_name = to_string(orig).as_str().into(); let binding_name = to_rcstr(orig);
let export = { let export = {
let imported_binding = if let ModuleExportName::Ident(ident) = orig { let imported_binding = if let ModuleExportName::Ident(ident) = orig {
self.eval_context.imports.get_binding(&ident.to_id()) self.eval_context.imports.get_binding(&ident.to_id())
...@@ -3339,7 +3318,16 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> { ...@@ -3339,7 +3318,16 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> {
EsmExport::ImportedNamespace(ResolvedVc::upcast(esm_ref)) EsmExport::ImportedNamespace(ResolvedVc::upcast(esm_ref))
} }
} else { } else {
EsmExport::LocalBinding(binding_name, is_fake_esm) EsmExport::LocalBinding(
binding_name,
if is_fake_esm {
Liveness::Mutable
} else {
// If this is `export {foo} from 'mod'` and `foo` is a const
// in mod then we could export as Const here.
Liveness::Live
},
)
} }
}; };
self.esm_exports.insert(key, export); self.esm_exports.insert(key, export);
...@@ -3358,10 +3346,45 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> { ...@@ -3358,10 +3346,45 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> {
export: &'ast ExportDecl, export: &'ast ExportDecl,
ast_path: &mut AstNodePath<AstParentNodeRef<'r>>, ast_path: &mut AstNodePath<AstParentNodeRef<'r>>,
) { ) {
for_each_ident_in_decl(&export.decl, &mut |name| { {
self.esm_exports let decl: &Decl = &export.decl;
.insert(name.clone(), EsmExport::LocalBinding(name, false)); let insert_export_binding = &mut |name: RcStr, liveness: Liveness| {
}); self.esm_exports
.insert(name.clone(), EsmExport::LocalBinding(name, liveness));
};
match decl {
Decl::Class(ClassDecl { ident, .. }) | Decl::Fn(FnDecl { ident, .. }) => {
// TODO: examine whether the value is ever mutated rather than just checking
// 'const'
insert_export_binding(ident.sym.as_str().into(), Liveness::Live);
}
Decl::Var(var_decl) => {
// TODO: examine whether the value is ever mutated rather than just checking
// 'const'
let liveness = match var_decl.kind {
VarDeclKind::Var => Liveness::Live,
VarDeclKind::Let => Liveness::Live,
VarDeclKind::Const => Liveness::Constant,
};
let decls = &*var_decl.decls;
decls.iter().for_each(|VarDeclarator { name, .. }| {
for_each_ident_in_pat(name, &mut |name| {
insert_export_binding(name, liveness)
})
});
}
Decl::Using(_) => {
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export#:~:text=You%20cannot%20use%20export%20on%20a%20using%20or%20await%20using%20declaration
unreachable!("using declarations can not be exported");
}
Decl::TsInterface(_)
| Decl::TsTypeAlias(_)
| Decl::TsEnum(_)
| Decl::TsModule(_) => {
// ignore typescript for code generation
}
}
};
self.analysis self.analysis
.add_code_gen(EsmModuleItem::new(as_parent_path(ast_path).into())); .add_code_gen(EsmModuleItem::new(as_parent_path(ast_path).into()));
export.visit_children_with_ast_path(self, ast_path); export.visit_children_with_ast_path(self, ast_path);
...@@ -3374,7 +3397,11 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> { ...@@ -3374,7 +3397,11 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> {
) { ) {
self.esm_exports.insert( self.esm_exports.insert(
rcstr!("default"), rcstr!("default"),
EsmExport::LocalBinding(magic_identifier::mangle("default export").into(), false), EsmExport::LocalBinding(
magic_identifier::mangle("default export").into(),
// The expression passed to `export default` cannot be mutated
Liveness::Constant,
),
); );
self.analysis self.analysis
.add_code_gen(EsmModuleItem::new(as_parent_path(ast_path).into())); .add_code_gen(EsmModuleItem::new(as_parent_path(ast_path).into()));
...@@ -3395,7 +3422,12 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> { ...@@ -3395,7 +3422,12 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> {
.as_ref() .as_ref()
.map(|i| i.sym.as_str().into()) .map(|i| i.sym.as_str().into())
.unwrap_or_else(|| magic_identifier::mangle("default export").into()), .unwrap_or_else(|| magic_identifier::mangle("default export").into()),
false, // Default export declarations can only be mutated if they have a name.
if ident.is_some() {
Liveness::Live
} else {
Liveness::Constant
},
), ),
); );
} }
......
...@@ -22,6 +22,7 @@ use crate::{ ...@@ -22,6 +22,7 @@ use crate::{
EcmascriptModuleContentOptions, EcmascriptOptions, MergedEcmascriptModule, SpecifiedModuleType, EcmascriptModuleContentOptions, EcmascriptOptions, MergedEcmascriptModule, SpecifiedModuleType,
chunk::{EcmascriptChunkPlaceable, EcmascriptExports}, chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
code_gen::CodeGens, code_gen::CodeGens,
export::Liveness,
parse::ParseResult, parse::ParseResult,
references::{ references::{
async_module::{AsyncModule, OptionAsyncModule}, async_module::{AsyncModule, OptionAsyncModule},
...@@ -251,7 +252,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleFacadeModule { ...@@ -251,7 +252,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleFacadeModule {
for (name, export) in &esm_exports.exports { for (name, export) in &esm_exports.exports {
let name = name.clone(); let name = name.clone();
match export { match export {
EsmExport::LocalBinding(_, mutable) => { EsmExport::LocalBinding(_, liveness) => {
exports.insert( exports.insert(
name.clone(), name.clone(),
EsmExport::ImportedBinding( EsmExport::ImportedBinding(
...@@ -265,7 +266,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleFacadeModule { ...@@ -265,7 +266,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleFacadeModule {
.await?, .await?,
), ),
name, name,
*mutable, *liveness == Liveness::Mutable,
), ),
); );
} }
......
...@@ -19,7 +19,7 @@ use turbopack_core::{ ...@@ -19,7 +19,7 @@ use turbopack_core::{
module_graph::{ module_graph::{
ModuleGraph, ModuleGraph,
chunk_group_info::ChunkGroup, chunk_group_info::ChunkGroup,
export_usage::{ExportUsageInfo, ModuleExportUsageInfo}, export_usage::{ExportUsageInfo, ModuleExportUsage},
}, },
output::{OutputAsset, OutputAssets}, output::{OutputAsset, OutputAssets},
}; };
...@@ -529,11 +529,13 @@ impl ChunkingContext for NodeJsChunkingContext { ...@@ -529,11 +529,13 @@ impl ChunkingContext for NodeJsChunkingContext {
async fn module_export_usage( async fn module_export_usage(
self: Vc<Self>, self: Vc<Self>,
module: ResolvedVc<Box<dyn Module>>, module: ResolvedVc<Box<dyn Module>>,
) -> Result<Vc<ModuleExportUsageInfo>> { ) -> Result<Vc<ModuleExportUsage>> {
if let Some(export_usage) = self.await?.export_usage { if let Some(export_usage) = self.await?.export_usage {
Ok(export_usage.await?.used_exports(module)) Ok(export_usage.await?.used_exports(module).await?)
} else { } else {
Ok(ModuleExportUsageInfo::all()) // In development mode, we don't have export usage info, so we assume all exports are
// used.
Ok(ModuleExportUsage::all())
} }
} }
} }
import * as liveExports from './live_exports.js'
import {
default as liveDefaultClass,
setDefaultClass,
} from './live_default_class.js'
import * as constDefaultExportFunction from './const_default_export_function.js'
it('hoisted declarations are live', () => {
expect(liveExports.bar()).toBe('bar')
liveExports.setBar(() => 'patched')
expect(liveExports.bar()).toBe('patched')
})
it('default class export declarations are live', () => {
expect(liveDefaultClass.default()).toBe('defaultClass')
setDefaultClass(
class {
static default() {
return 'patched'
}
}
)
expect(liveDefaultClass.default()).toBe('patched')
})
it('default function export declarations are live', () => {
expect(liveExports.default()).toBe('defaultFunction')
liveExports.setDefaultFunction(() => 'patched')
expect(liveExports.default()).toBe('patched')
})
it('exported lets are live', () => {
expect(liveExports.foo).toBe('foo')
liveExports.setFoo('new')
expect(liveExports.foo).toBe('new')
})
it('exported bindings that are not mutated are not live', () => {
// These should be bound to values, but we don't have the analysis yet
expectGetter(liveExports, 'obviouslyneverMutated')
expectGetter(liveExports, 'neverMutated')
expectGetter(constDefaultExportFunction, 'default')
})
it('exported bindings that are free vars are live', () => {
expectGetter(liveExports, 'g')
})
function expectGetter(ns, propName) {
const gDesc = Object.getOwnPropertyDescriptor(ns, propName)
expect(gDesc).toEqual(
expect.objectContaining({
enumerable: true,
configurable: false,
set: undefined,
})
)
expect(gDesc).toHaveProperty('get')
}
export default class DefaultClass {
static default() {
return 'defaultClass'
}
}
export function setDefaultClass(c) {
DefaultClass = c
}
let foo = 'foo'
function setFoo(n) {
foo = n
}
let neverMutated = 'neverMutated'
const obviouslyneverMutated = 'obviouslyneverMutated'
export { foo, setFoo, neverMutated, obviouslyneverMutated }
// biome-ignore lint/suspicious/noFunctionAssign: testing crimes
export function bar() {
return 'bar'
}
export function setBar(b) {
bar = b
}
export { globalThis as g }
export default function defaultFunction() {
return 'defaultFunction'
}
export function setDefaultFunction(f) {
defaultFunction = f
}
...@@ -2,30 +2,26 @@ ...@@ -2,30 +2,26 @@
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict"; "use strict";
__turbopack_context__.s([]);
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$reexport$2d$with$2d$locals$2f$input$2f$node_modules$2f$lib$2f$index$2e$js__$5b$test$5d$__$28$ecmascript$29$__$3c$locals$3e$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/index.js [test] (ecmascript) <locals>"); var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$reexport$2d$with$2d$locals$2f$input$2f$node_modules$2f$lib$2f$index$2e$js__$5b$test$5d$__$28$ecmascript$29$__$3c$locals$3e$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/index.js [test] (ecmascript) <locals>");
; ;
(0, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$reexport$2d$with$2d$locals$2f$input$2f$node_modules$2f$lib$2f$index$2e$js__$5b$test$5d$__$28$ecmascript$29$__$3c$locals$3e$__["local"])(); (0, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$reexport$2d$with$2d$locals$2f$input$2f$node_modules$2f$lib$2f$index$2e$js__$5b$test$5d$__$28$ecmascript$29$__$3c$locals$3e$__["local"])();
__turbopack_context__.s([]);
}), }),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/unused.js [test] (ecmascript)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/unused.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict"; "use strict";
__turbopack_context__.s([]);
function unusedStar() {} function unusedStar() {}
__turbopack_context__.s([]);
}), }),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/unused-star.js [test] (ecmascript)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/unused-star.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict"; "use strict";
__turbopack_context__.s([]);
function unused() {} function unused() {}
__turbopack_context__.s([]);
}), }),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/index.js [test] (ecmascript) <locals>", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/index.js [test] (ecmascript) <locals>", ((__turbopack_context__) => {
"use strict"; "use strict";
__turbopack_context__.s([
"local",
()=>local
]);
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$reexport$2d$with$2d$locals$2f$input$2f$node_modules$2f$lib$2f$unused$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/unused.js [test] (ecmascript)"); var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$reexport$2d$with$2d$locals$2f$input$2f$node_modules$2f$lib$2f$unused$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/unused.js [test] (ecmascript)");
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$reexport$2d$with$2d$locals$2f$input$2f$node_modules$2f$lib$2f$unused$2d$star$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/unused-star.js [test] (ecmascript)"); var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$reexport$2d$with$2d$locals$2f$input$2f$node_modules$2f$lib$2f$unused$2d$star$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/unused-star.js [test] (ecmascript)");
; ;
...@@ -37,6 +33,10 @@ function localUnused() { ...@@ -37,6 +33,10 @@ function localUnused() {
console.log('This is a local unused function'); console.log('This is a local unused function');
} }
; ;
__turbopack_context__.s([
"local",
()=>local
]);
}), }),
]); ]);
......
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
"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/intermediate-tree-shake/reexport-with-locals/input/index.js"],"sourcesContent":["import { local } from 'lib'\n\nlocal()\n"],"names":[],"mappings":";AAAA;;AAEA,IAAA,yRAAK"}}, {"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/index.js"],"sourcesContent":["import { local } from 'lib'\n\nlocal()\n"],"names":[],"mappings":"AAAA;;AAEA,IAAA,yRAAK"}},
{"offset": {"line": 12, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/unused.js"],"sourcesContent":["export function unusedStar() {}\n"],"names":[],"mappings":";AAAO,SAAS,cAAc","ignoreList":[0]}}, {"offset": {"line": 12, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/unused.js"],"sourcesContent":["export function unusedStar() {}\n"],"names":[],"mappings":"AAAO,SAAS,cAAc","ignoreList":[0]}},
{"offset": {"line": 18, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/unused-star.js"],"sourcesContent":["export function unused() {}\n"],"names":[],"mappings":";AAAO,SAAS,UAAU","ignoreList":[0]}}, {"offset": {"line": 18, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/unused-star.js"],"sourcesContent":["export function unused() {}\n"],"names":[],"mappings":"AAAO,SAAS,UAAU","ignoreList":[0]}},
{"offset": {"line": 24, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/index.js"],"sourcesContent":["export { unused } from './unused.js'\nexport * from './unused-star.js'\n\nfunction local() {\n console.log('This is a local function')\n}\nfunction localUnused() {\n console.log('This is a local unused function')\n}\n\nexport { local, localUnused }\n"],"names":[],"mappings":";;;;AAAA;AACA;;;AAEA,SAAS;IACP,QAAQ,GAAG,CAAC;AACd;AACA,SAAS;IACP,QAAQ,GAAG,CAAC;AACd","ignoreList":[0]}}] {"offset": {"line": 24, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/reexport-with-locals/input/node_modules/lib/index.js"],"sourcesContent":["export { unused } from './unused.js'\nexport * from './unused-star.js'\n\nfunction local() {\n console.log('This is a local function')\n}\nfunction localUnused() {\n console.log('This is a local unused function')\n}\n\nexport { local, localUnused }\n"],"names":[],"mappings":"AAAA;AACA;;;AAEA,SAAS;IACP,QAAQ,GAAG,CAAC;AACd;AACA,SAAS;IACP,QAAQ,GAAG,CAAC;AACd","ignoreList":[0]}}]
} }
\ No newline at end of file
...@@ -2,29 +2,30 @@ ...@@ -2,29 +2,30 @@
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/rename-side-effect-free-facade/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/rename-side-effect-free-facade/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict"; "use strict";
__turbopack_context__.s([]);
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$rename$2d$side$2d$effect$2d$free$2d$facade$2f$input$2f$node_modules$2f$lib$2f$a$2e$js__$5b$test$5d$__$28$ecmascript$29$__$3c$export__a__as__a0$3e$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/rename-side-effect-free-facade/input/node_modules/lib/a.js [test] (ecmascript) <export a as a0>"); var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$rename$2d$side$2d$effect$2d$free$2d$facade$2f$input$2f$node_modules$2f$lib$2f$a$2e$js__$5b$test$5d$__$28$ecmascript$29$__$3c$export__a__as__a0$3e$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/rename-side-effect-free-facade/input/node_modules/lib/a.js [test] (ecmascript) <export a as a0>");
; ;
console.log(__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$rename$2d$side$2d$effect$2d$free$2d$facade$2f$input$2f$node_modules$2f$lib$2f$a$2e$js__$5b$test$5d$__$28$ecmascript$29$__$3c$export__a__as__a0$3e$__["a0"]); console.log(__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$rename$2d$side$2d$effect$2d$free$2d$facade$2f$input$2f$node_modules$2f$lib$2f$a$2e$js__$5b$test$5d$__$28$ecmascript$29$__$3c$export__a__as__a0$3e$__["a0"]);
__turbopack_context__.s([]);
}), }),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/rename-side-effect-free-facade/input/node_modules/lib/a.js [test] (ecmascript)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/rename-side-effect-free-facade/input/node_modules/lib/a.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict"; "use strict";
const a = 'a';
const a_unused = 'a_unused';
__turbopack_context__.s([ __turbopack_context__.s([
"a", "a",
()=>a 0,
a
]); ]);
const a = 'a';
const a_unused = 'a_unused';
}), }),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/rename-side-effect-free-facade/input/node_modules/lib/a.js [test] (ecmascript) <export a as a0>", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/rename-side-effect-free-facade/input/node_modules/lib/a.js [test] (ecmascript) <export a as a0>", ((__turbopack_context__) => {
"use strict"; "use strict";
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$rename$2d$side$2d$effect$2d$free$2d$facade$2f$input$2f$node_modules$2f$lib$2f$a$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/rename-side-effect-free-facade/input/node_modules/lib/a.js [test] (ecmascript)");
__turbopack_context__.s([ __turbopack_context__.s([
"a0", "a0",
()=>__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$rename$2d$side$2d$effect$2d$free$2d$facade$2f$input$2f$node_modules$2f$lib$2f$a$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$intermediate$2d$tree$2d$shake$2f$rename$2d$side$2d$effect$2d$free$2d$facade$2f$input$2f$node_modules$2f$lib$2f$a$2e$js__$5b$test$5d$__$28$ecmascript$29$__["a"]
]); ]);
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$rename$2d$side$2d$effect$2d$free$2d$facade$2f$input$2f$node_modules$2f$lib$2f$a$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/rename-side-effect-free-facade/input/node_modules/lib/a.js [test] (ecmascript)");
}), }),
]); ]);
......
...@@ -2,6 +2,6 @@ ...@@ -2,6 +2,6 @@
"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/intermediate-tree-shake/rename-side-effect-free-facade/input/index.js"],"sourcesContent":["import { a0 } from 'lib'\n\nconsole.log(a0)\n"],"names":[],"mappings":";AAAA;;AAEA,QAAQ,GAAG,CAAC,6SAAE"}}, {"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/rename-side-effect-free-facade/input/index.js"],"sourcesContent":["import { a0 } from 'lib'\n\nconsole.log(a0)\n"],"names":[],"mappings":"AAAA;;AAEA,QAAQ,GAAG,CAAC,6SAAE"}},
{"offset": {"line": 12, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/rename-side-effect-free-facade/input/node_modules/lib/a.js"],"sourcesContent":["export const a = 'a'\nexport const a_unused = 'a_unused'\n"],"names":[],"mappings":";;;;AAAO,MAAM,IAAI;AACV,MAAM,WAAW","ignoreList":[0]}}] {"offset": {"line": 12, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/rename-side-effect-free-facade/input/node_modules/lib/a.js"],"sourcesContent":["export const a = 'a'\nexport const a_unused = 'a_unused'\n"],"names":[],"mappings":"AAAO,MAAM,IAAI;AACV,MAAM,WAAW","ignoreList":[0]}}]
} }
\ No newline at end of file
...@@ -2,18 +2,14 @@ ...@@ -2,18 +2,14 @@
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/tree-shake-test-1/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/tree-shake-test-1/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict"; "use strict";
__turbopack_context__.s([]);
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$tree$2d$shake$2d$test$2d$1$2f$input$2f$node_modules$2f$lib$2f$index$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/tree-shake-test-1/input/node_modules/lib/index.js [test] (ecmascript)"); var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$tree$2d$shake$2d$test$2d$1$2f$input$2f$node_modules$2f$lib$2f$index$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/tree-shake-test-1/input/node_modules/lib/index.js [test] (ecmascript)");
; ;
console.log(`I like ${(0, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$tree$2d$shake$2d$test$2d$1$2f$input$2f$node_modules$2f$lib$2f$index$2e$js__$5b$test$5d$__$28$ecmascript$29$__["getCat"])()}`); console.log(`I like ${(0, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$intermediate$2d$tree$2d$shake$2f$tree$2d$shake$2d$test$2d$1$2f$input$2f$node_modules$2f$lib$2f$index$2e$js__$5b$test$5d$__$28$ecmascript$29$__["getCat"])()}`);
__turbopack_context__.s([]);
}), }),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/tree-shake-test-1/input/node_modules/lib/index.js [test] (ecmascript)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/tree-shake-test-1/input/node_modules/lib/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict"; "use strict";
__turbopack_context__.s([
"getCat",
()=>getCat
]);
let cat = "cat"; let cat = "cat";
let dog = "dog"; let dog = "dog";
function getChimera() { function getChimera() {
...@@ -25,6 +21,10 @@ function getCat() { ...@@ -25,6 +21,10 @@ function getCat() {
function getDog() { function getDog() {
return dog; return dog;
} }
__turbopack_context__.s([
"getCat",
()=>getCat
]);
}), }),
]); ]);
......
...@@ -2,6 +2,6 @@ ...@@ -2,6 +2,6 @@
"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/intermediate-tree-shake/tree-shake-test-1/input/index.js"],"sourcesContent":["import { getCat } from 'lib'\n\nconsole.log(`I like ${getCat()}`)\n"],"names":[],"mappings":";AAAA;;AAEA,QAAQ,GAAG,CAAC,CAAC,OAAO,EAAE,IAAA,0QAAM,KAAI"}}, {"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/tree-shake-test-1/input/index.js"],"sourcesContent":["import { getCat } from 'lib'\n\nconsole.log(`I like ${getCat()}`)\n"],"names":[],"mappings":"AAAA;;AAEA,QAAQ,GAAG,CAAC,CAAC,OAAO,EAAE,IAAA,0QAAM,KAAI"}},
{"offset": {"line": 12, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/tree-shake-test-1/input/node_modules/lib/index.js"],"sourcesContent":["\nlet cat = \"cat\";\nlet dog = \"dog\";\n\nexport function getChimera() {\n return cat + dog;\n}\n\nexport function getCat() {\n return cat;\n}\n\nexport function getDog() {\n return dog;\n}\n\n"],"names":[],"mappings":";;;;AACA,IAAI,MAAM;AACV,IAAI,MAAM;AAEH,SAAS;IACd,OAAO,MAAM;AACf;AAEO,SAAS;IACd,OAAO;AACT;AAEO,SAAS;IACd,OAAO;AACT","ignoreList":[0]}}] {"offset": {"line": 12, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/intermediate-tree-shake/tree-shake-test-1/input/node_modules/lib/index.js"],"sourcesContent":["\nlet cat = \"cat\";\nlet dog = \"dog\";\n\nexport function getChimera() {\n return cat + dog;\n}\n\nexport function getCat() {\n return cat;\n}\n\nexport function getDog() {\n return dog;\n}\n\n"],"names":[],"mappings":"AACA,IAAI,MAAM;AACV,IAAI,MAAM;AAEH,SAAS;IACd,OAAO,MAAM;AACf;AAEO,SAAS;IACd,OAAO;AACT;AAEO,SAAS;IACd,OAAO;AACT","ignoreList":[0]}}]
} }
\ No newline at end of file
...@@ -47,9 +47,10 @@ function getOverwrittenModule(moduleCache, id) { ...@@ -47,9 +47,10 @@ function getOverwrittenModule(moduleCache, id) {
namespaceObject: undefined namespaceObject: undefined
}; };
} }
const BindingTag_Value = 0;
/** /**
* Adds the getters to the exports object. * Adds the getters to the exports object.
*/ function esm(exports, getters) { */ function esm(exports, bindings) {
defineProp(exports, '__esModule', { defineProp(exports, '__esModule', {
value: true value: true
}); });
...@@ -57,29 +58,41 @@ function getOverwrittenModule(moduleCache, id) { ...@@ -57,29 +58,41 @@ function getOverwrittenModule(moduleCache, id) {
value: 'Module' value: 'Module'
}); });
let i = 0; let i = 0;
while(i < getters.length){ while(i < bindings.length){
const propName = getters[i++]; const propName = bindings[i++];
// TODO(luke.sandberg): we could support raw values here, but would need a discriminator beyond 'not a function' const tagOrFunction = bindings[i++];
const getter = getters[i++]; if (typeof tagOrFunction === 'number') {
if (typeof getters[i] === 'function') { if (tagOrFunction === BindingTag_Value) {
// a setter defineProp(exports, propName, {
defineProp(exports, propName, { value: bindings[i++],
get: getter, enumerable: true,
set: getters[i++], writable: false
enumerable: true });
}); } else {
throw new Error(`unexpected tag: ${tagOrFunction}`);
}
} else { } else {
defineProp(exports, propName, { const getterFn = tagOrFunction;
get: getter, if (typeof bindings[i] === 'function') {
enumerable: true const setterFn = bindings[i++];
}); defineProp(exports, propName, {
get: getterFn,
set: setterFn,
enumerable: true
});
} else {
defineProp(exports, propName, {
get: getterFn,
enumerable: true
});
}
} }
} }
Object.seal(exports); Object.seal(exports);
} }
/** /**
* Makes the module an ESM with exports * Makes the module an ESM with exports
*/ function esmExport(getters, id) { */ function esmExport(bindings, id) {
let module; let module;
let exports; let exports;
if (id != null) { if (id != null) {
...@@ -90,7 +103,7 @@ function getOverwrittenModule(moduleCache, id) { ...@@ -90,7 +103,7 @@ function getOverwrittenModule(moduleCache, id) {
exports = this.e; exports = this.e;
} }
module.namespaceObject = exports; module.namespaceObject = exports;
esm(exports, getters); esm(exports, bindings);
} }
contextPrototype.s = esmExport; contextPrototype.s = esmExport;
function ensureDynamicExports(module, exports) { function ensureDynamicExports(module, exports) {
...@@ -178,14 +191,13 @@ function createGetter(obj, key) { ...@@ -178,14 +191,13 @@ function createGetter(obj, key) {
* * `false`: will have the raw module as default export * * `false`: will have the raw module as default export
* * `true`: will have the default property as default export * * `true`: will have the default property as default export
*/ function interopEsm(raw, ns, allowExportDefault) { */ function interopEsm(raw, ns, allowExportDefault) {
const getters = []; const bindings = [];
// The index of the `default` export if any
let defaultLocation = -1; let defaultLocation = -1;
for(let current = raw; (typeof current === 'object' || typeof current === 'function') && !LEAF_PROTOTYPES.includes(current); current = getProto(current)){ for(let current = raw; (typeof current === 'object' || typeof current === 'function') && !LEAF_PROTOTYPES.includes(current); current = getProto(current)){
for (const key of Object.getOwnPropertyNames(current)){ for (const key of Object.getOwnPropertyNames(current)){
getters.push(key, createGetter(raw, key)); bindings.push(key, createGetter(raw, key));
if (defaultLocation === -1 && key === 'default') { if (defaultLocation === -1 && key === 'default') {
defaultLocation = getters.length - 1; defaultLocation = bindings.length - 1;
} }
} }
} }
...@@ -194,12 +206,13 @@ function createGetter(obj, key) { ...@@ -194,12 +206,13 @@ function createGetter(obj, key) {
if (!(allowExportDefault && defaultLocation >= 0)) { if (!(allowExportDefault && defaultLocation >= 0)) {
// Replace the binding with one for the namespace itself in order to preserve iteration order. // Replace the binding with one for the namespace itself in order to preserve iteration order.
if (defaultLocation >= 0) { if (defaultLocation >= 0) {
getters[defaultLocation] = ()=>raw; // Replace the getter with the value
bindings.splice(defaultLocation, 1, BindingTag_Value, raw);
} else { } else {
getters.push('default', ()=>raw); bindings.push('default', BindingTag_Value, raw);
} }
} }
esm(ns, getters); esm(ns, bindings);
return ns; return ns;
} }
function createNS(raw) { function createNS(raw) {
...@@ -222,7 +235,7 @@ function esmImport(id) { ...@@ -222,7 +235,7 @@ function esmImport(id) {
contextPrototype.i = esmImport; contextPrototype.i = esmImport;
function asyncLoader(moduleId) { function asyncLoader(moduleId) {
const loader = this.r(moduleId); const loader = this.r(moduleId);
return loader(this.i.bind(this)); return loader(esmImport.bind(this));
} }
contextPrototype.A = asyncLoader; contextPrototype.A = asyncLoader;
// Add a simple runtime require so that environments without one can still pass // Add a simple runtime require so that environments without one can still pass
......
...@@ -57,9 +57,10 @@ function getOverwrittenModule(moduleCache, id) { ...@@ -57,9 +57,10 @@ function getOverwrittenModule(moduleCache, id) {
namespaceObject: undefined namespaceObject: undefined
}; };
} }
const BindingTag_Value = 0;
/** /**
* Adds the getters to the exports object. * Adds the getters to the exports object.
*/ function esm(exports, getters) { */ function esm(exports, bindings) {
defineProp(exports, '__esModule', { defineProp(exports, '__esModule', {
value: true value: true
}); });
...@@ -67,29 +68,41 @@ function getOverwrittenModule(moduleCache, id) { ...@@ -67,29 +68,41 @@ function getOverwrittenModule(moduleCache, id) {
value: 'Module' value: 'Module'
}); });
let i = 0; let i = 0;
while(i < getters.length){ while(i < bindings.length){
const propName = getters[i++]; const propName = bindings[i++];
// TODO(luke.sandberg): we could support raw values here, but would need a discriminator beyond 'not a function' const tagOrFunction = bindings[i++];
const getter = getters[i++]; if (typeof tagOrFunction === 'number') {
if (typeof getters[i] === 'function') { if (tagOrFunction === BindingTag_Value) {
// a setter defineProp(exports, propName, {
defineProp(exports, propName, { value: bindings[i++],
get: getter, enumerable: true,
set: getters[i++], writable: false
enumerable: true });
}); } else {
throw new Error(`unexpected tag: ${tagOrFunction}`);
}
} else { } else {
defineProp(exports, propName, { const getterFn = tagOrFunction;
get: getter, if (typeof bindings[i] === 'function') {
enumerable: true const setterFn = bindings[i++];
}); defineProp(exports, propName, {
get: getterFn,
set: setterFn,
enumerable: true
});
} else {
defineProp(exports, propName, {
get: getterFn,
enumerable: true
});
}
} }
} }
Object.seal(exports); Object.seal(exports);
} }
/** /**
* Makes the module an ESM with exports * Makes the module an ESM with exports
*/ function esmExport(getters, id) { */ function esmExport(bindings, id) {
let module; let module;
let exports; let exports;
if (id != null) { if (id != null) {
...@@ -100,7 +113,7 @@ function getOverwrittenModule(moduleCache, id) { ...@@ -100,7 +113,7 @@ function getOverwrittenModule(moduleCache, id) {
exports = this.e; exports = this.e;
} }
module.namespaceObject = exports; module.namespaceObject = exports;
esm(exports, getters); esm(exports, bindings);
} }
contextPrototype.s = esmExport; contextPrototype.s = esmExport;
function ensureDynamicExports(module, exports) { function ensureDynamicExports(module, exports) {
...@@ -188,14 +201,13 @@ function createGetter(obj, key) { ...@@ -188,14 +201,13 @@ function createGetter(obj, key) {
* * `false`: will have the raw module as default export * * `false`: will have the raw module as default export
* * `true`: will have the default property as default export * * `true`: will have the default property as default export
*/ function interopEsm(raw, ns, allowExportDefault) { */ function interopEsm(raw, ns, allowExportDefault) {
const getters = []; const bindings = [];
// The index of the `default` export if any
let defaultLocation = -1; let defaultLocation = -1;
for(let current = raw; (typeof current === 'object' || typeof current === 'function') && !LEAF_PROTOTYPES.includes(current); current = getProto(current)){ for(let current = raw; (typeof current === 'object' || typeof current === 'function') && !LEAF_PROTOTYPES.includes(current); current = getProto(current)){
for (const key of Object.getOwnPropertyNames(current)){ for (const key of Object.getOwnPropertyNames(current)){
getters.push(key, createGetter(raw, key)); bindings.push(key, createGetter(raw, key));
if (defaultLocation === -1 && key === 'default') { if (defaultLocation === -1 && key === 'default') {
defaultLocation = getters.length - 1; defaultLocation = bindings.length - 1;
} }
} }
} }
...@@ -204,12 +216,13 @@ function createGetter(obj, key) { ...@@ -204,12 +216,13 @@ function createGetter(obj, key) {
if (!(allowExportDefault && defaultLocation >= 0)) { if (!(allowExportDefault && defaultLocation >= 0)) {
// Replace the binding with one for the namespace itself in order to preserve iteration order. // Replace the binding with one for the namespace itself in order to preserve iteration order.
if (defaultLocation >= 0) { if (defaultLocation >= 0) {
getters[defaultLocation] = ()=>raw; // Replace the getter with the value
bindings.splice(defaultLocation, 1, BindingTag_Value, raw);
} else { } else {
getters.push('default', ()=>raw); bindings.push('default', BindingTag_Value, raw);
} }
} }
esm(ns, getters); esm(ns, bindings);
return ns; return ns;
} }
function createNS(raw) { function createNS(raw) {
...@@ -232,7 +245,7 @@ function esmImport(id) { ...@@ -232,7 +245,7 @@ function esmImport(id) {
contextPrototype.i = esmImport; contextPrototype.i = esmImport;
function asyncLoader(moduleId) { function asyncLoader(moduleId) {
const loader = this.r(moduleId); const loader = this.r(moduleId);
return loader(this.i.bind(this)); return loader(esmImport.bind(this));
} }
contextPrototype.A = asyncLoader; contextPrototype.A = asyncLoader;
// Add a simple runtime require so that environments without one can still pass // Add a simple runtime require so that environments without one can still pass
......
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