Unverified Commit a84bc8de authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: mangle exported names for smaller bundle sizes (#97672)

### What?

Adds export-name mangling to Turbopack, behind a new experimental option
`experimental.turbopackMangleExportNames` (default `false`). It is
independent of minification:
`--no-mangling` is a minifier flag and does not affect it.

When enabled, each ECMAScript module's *used* export names — including
`default` and
`__esModule` — are replaced by short keys in the emitted output, both
where the module registers
its exports and where every consumer reads them. Modules whose export
names could be observed by
user code keep their original names, decided per module.

This is a reland of #89060 (on top of the already-merged #89406),
originally written by Matt
Mastracci, who is credited as a co-author on the commit.

Stacked on top: #97676 flips the default to `true` on canary releases,
so Next.js's own CI
exercises the feature broadly before it is considered for stable.

### Why?

Bundle size. A module's export keys exist only to link modules together:
the producing module
emits `{ someVeryLongExportName: … }` and every consumer reads
`ns["someVeryLongExportName"]`.
Both sides are generated by us, so as long as producer and consumer
agree — and the name isn't
observable from user code — the key can be a single character. Long
export names are extremely
common in real dependency graphs (icon sets, utility packages, barrel
files), and each one is paid
for once in the module that defines it and once per importing module.

### How?

**Ported, not rebased.** `canary` is ~2500 commits past the original
stack's base, and the files it
touched were independently rewritten in the meantime (export-analysis
refactor #92781, CJS analysis
for scope hoisting #95826, the `module_fragments` subsystem #95978). A
probe rebase produced 16
conflicting files on the first commit alone, so the original branches
were used as a reference
implementation — for intent, the identifier alphabet, and test coverage
— and the feature was
rebuilt on today's infrastructure. #89561 from the original stack
(erasing the Next.js wrapper
module types) is deliberately **not** part of this change; it turned out
to be unnecessary, because
those modules already declare whole-module export usage and therefore
back off on their own.

**The name table** (`references/esm/mangle/table.rs`) hashes each name
into a table of all valid JS
identifiers of the smallest length that fits the name set — 15 exports
get single-character keys —
and resolves collisions by open addressing. Hashing rather than
assigning `a`, `b`, `c`, … is what
keeps names stable: an unrelated edit elsewhere in the module doesn't
renumber every other export,
and a collision only perturbs its own cluster. Assignment happens in two
passes: every name that is
*already* a valid identifier at the chosen length keeps itself and
reserves its bucket first, and
only then is anything hashed — so an export called `a` keeps `a`, and
nothing else can be assigned
it. Both passes iterate in sorted order, so the mapping depends only on
the set of names.

A module with exactly **one** mangleable export is special-cased to a
fixed key, `f`, rather than a
hashed one. `f` is the most common character in JS keywords (`if`,
`for`, `function`), and every
single-export module in the graph then emits the same `.f` / `.f()` byte
sequences, which gzip's
back-references pick up across the whole bundle — a bigger win than
hashing, at the cost of that one
key changing when a second export is added.

A fixed list, `RESERVED_KEYS`, is withheld from every table for two
different reasons: JS reserved
words (`if`, `in`, `do`, `for`, `let`, `new`, `try`, `var`) are legal as
quoted property keys but a
minifier will not fold `ns["if"]` into the shorter `ns.if`, so handing
one out costs bytes instead of
saving them; and `__esModule` is withheld because the runtime's `esm()`
helper defines that property
on every module's exports object regardless of what the module itself
exports, so an assigned key
landing on it would collide. (`default` needs no such protection — once
it is mangled like any other
export, nothing else emits a property under that literal name.)

**One source of truth for the mapping.** `mangled_export_names(module,
chunking_context)` is a
turbo-task that both the producing side (`EsmExports::code_generation`)
and the consuming side
(`ReferencedAssetIdent::Module`, the single place a cross-module export
access is materialized) ask
for the *target* module's map. Neither side computes a table of its own,
so they cannot disagree,
and the task derives export usage from the chunking context itself
rather than accepting it as an
argument, so a caller can't supply usage from the wrong graph. Re-export
chains need no special
handling, because the consumer side already resolves through re-exports
to the module that produces
the binding.

The mangling decision itself lives on `EsmExports` as a
`mangle_export_names: bool` field, rather
than a separate trait method every module type has to override. A module
that derives its exports
from another one (a facade, a locals module, a part, a rename) inherits
the flag with the data,
which removed seven hand-written delegations and the possibility of a
new wrapper type forgetting
one.

**A mangling decision must not cross module identities.** A few module
types hand out *another*
module's exports value as their own (the WASM loader module, the
module-fragments side-effects
wrapper, the client-reference proxy). If that borrowed value carried a
real mangling decision, the
producing and consuming sides would key their lookups on two different
modules and could compute two
different keys for the same export — this actually broke every WASM- and
`@vercel/og`-based test
once the default-on layer exercised it in CI.
`EcmascriptExports::borrowed()` is the one place this
is handled: it always returns an unmangled view, and every such
pass-through site uses it.

**Back-off is per module**, built on the export-usage information that
landed after the original PR
(`BindingUsageInfo` / `ModuleExportUsageInfo`) rather than the
original's locals/facade-split
heuristic. A module keeps its names when its usage is `All` (a namespace
import that couldn't be
lowered, a computed property access, an unresolvable `export *`, or a
chunk-group entry — which
covers client references and the Next.js wrapper modules), when it is
read through a namespace value
at all, when its exports are dynamic or not statically known ESM, or
when names aren't being mangled
in this build.

`__webpack_exports_info__` gains `canMangle` and `mangledName` per
export, which is how a running
test can observe the mapping; with the option off it emits exactly what
it emitted before.

### Testing

- `turbo-tasks-hash`/table unit tests: encode/decode round-trip,
degenerate-name rejection, table
sizing, the single-export fixed key (including its own reservation),
reserved-word withholding
(including a reserved bucket-count test that stays in sync with the
reserved list), the
preserved-name pass running before any hashing, uniqueness under heavy
collision, order
  independence, wrap-around probing, and same-tier stability.
- 13 `turbopack-tests` execution fixtures under
`tests/execution/turbopack/exports/mangle-*`,
several ported from the original PR and from webpack's
`test/configCases/mangle`: named imports,
re-export chains and default exports (including one literally named
`__esModule`), escaping
namespaces (`Object.keys`, `delete ns.missing`, `export * as`, CJS
interop), destructuring,
prototype-shadowing names (`toString`, `$1`, `__1`), a 60-export
two-character table, dynamic
`import()` with `webpackExports` / `turbopackExports`, a CommonJS
consumer of an ESM module,
dynamic re-exports, scope hoisting on and off, and a control with the
option off.
- 3 committed snapshot fixtures under `tests/snapshot/mangle-exports`,
so the emitted keys, the
  back-off, and the fixed single-export key are visible in review.
- One fixture under `__skipped__`, which the harness asserts *fails*,
recording the
  namespace-materialization gap below.
- Full suite: 546 unit + 272 execution + 125 snapshot tests pass, with
no snapshot churn across the
  several refactors this PR went through in review.
- Verified against real builds: targeted app-dir, worker, WASM, and
`@vercel/og`-based e2e suites
pass with the option forced on (the failures that remain are
external-network tests that fail
identically with it off), and a small two-page app shrank by 0.76% of
total emitted JS / 0.53%
  gzipped.

### Known limitations, each intentional

- **A module read through `import * as ns` is never mangled**, even when
every read is statically
tracked, because the analysis doesn't yet distinguish a lowered named
read from a materialized
namespace object. Namespace imports are common, so this leaves real wins
on the table; unlocking
  it is the highest-value follow-up.
- **Escaping namespaces back off entirely.** Webpack instead keeps
mangling and materializes a
namespace object keyed by the original names. That is the `__skipped__`
fixture: implementing it
  turns the suite red until the fixture is moved out.
- **CommonJS export mangling is out of scope.** The producing side is
reachable, but the consuming
accesses live in user source and nothing rewrites them today; it needs
its own design pass.

Closes PACK-435

<!-- NEXT_JS_LLM -->
Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>


<!-- fleet ecdfa248-cd54-41ac-b4a2-c9d49e2a67ee -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent 451985dc
...@@ -376,6 +376,7 @@ pub async fn get_client_module_options_context( ...@@ -376,6 +376,7 @@ pub async fn get_client_module_options_context(
source_maps, source_maps,
infer_module_side_effects: *next_config.turbopack_infer_module_side_effects().await?, infer_module_side_effects: *next_config.turbopack_infer_module_side_effects().await?,
cjs_tree_shaking: *next_config.turbopack_cjs_tree_shaking().await?, cjs_tree_shaking: *next_config.turbopack_cjs_tree_shaking().await?,
mangle_export_names: *next_config.turbopack_mangle_export_names().await?,
cjs_scope_hoisting: *next_config.turbopack_cjs_scope_hoisting().await?, cjs_scope_hoisting: *next_config.turbopack_cjs_scope_hoisting().await?,
cross_module_constants: *next_config.turbopack_cross_module_constants().await?, cross_module_constants: *next_config.turbopack_cross_module_constants().await?,
preset_env_config, preset_env_config,
......
...@@ -285,7 +285,9 @@ impl ChunkableModule for EcmascriptClientReferenceModule { ...@@ -285,7 +285,9 @@ impl ChunkableModule for EcmascriptClientReferenceModule {
impl EcmascriptChunkPlaceable for EcmascriptClientReferenceModule { impl EcmascriptChunkPlaceable for EcmascriptClientReferenceModule {
#[turbo_tasks::function] #[turbo_tasks::function]
fn get_exports(self: Vc<Self>) -> Vc<EcmascriptExports> { fn get_exports(self: Vc<Self>) -> Vc<EcmascriptExports> {
self.proxy_module().get_exports() // Borrowed from the proxy module, a separate module identity, so they must not carry a
// mangling decision — see `EcmascriptExports::borrowed`.
self.proxy_module().get_exports().borrowed()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -1446,6 +1446,8 @@ pub struct ExperimentalConfig { ...@@ -1446,6 +1446,8 @@ pub struct ExperimentalConfig {
turbopack_infer_module_side_effects: Option<bool>, turbopack_infer_module_side_effects: Option<bool>,
/// Enable tree shaking of unused exports from static CommonJS modules. Defaults to false. /// Enable tree shaking of unused exports from static CommonJS modules. Defaults to false.
turbopack_cjs_tree_shaking: Option<bool>, turbopack_cjs_tree_shaking: Option<bool>,
/// Shorten ("mangle") the export names modules expose to each other. Defaults to false.
turbopack_mangle_export_names: Option<bool>,
/// Enable scope hoisting of static CommonJS modules. Defaults to false. /// Enable scope hoisting of static CommonJS modules. Defaults to false.
turbopack_cjs_scope_hoisting: Option<bool>, turbopack_cjs_scope_hoisting: Option<bool>,
/// Enable cross-module constant inlining. Defaults to false. /// Enable cross-module constant inlining. Defaults to false.
...@@ -2587,6 +2589,15 @@ impl NextConfig { ...@@ -2587,6 +2589,15 @@ impl NextConfig {
) )
} }
#[turbo_tasks::function]
pub fn turbopack_mangle_export_names(&self) -> Vc<bool> {
Vc::cell(
self.experimental
.turbopack_mangle_export_names
.unwrap_or(false),
)
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn turbopack_cjs_scope_hoisting(&self) -> Vc<bool> { pub fn turbopack_cjs_scope_hoisting(&self) -> Vc<bool> {
Vc::cell( Vc::cell(
......
...@@ -551,6 +551,7 @@ pub async fn get_server_module_options_context( ...@@ -551,6 +551,7 @@ pub async fn get_server_module_options_context(
source_maps, source_maps,
infer_module_side_effects: *next_config.turbopack_infer_module_side_effects().await?, infer_module_side_effects: *next_config.turbopack_infer_module_side_effects().await?,
cjs_tree_shaking: *next_config.turbopack_cjs_tree_shaking().await?, cjs_tree_shaking: *next_config.turbopack_cjs_tree_shaking().await?,
mangle_export_names: *next_config.turbopack_mangle_export_names().await?,
cjs_scope_hoisting: *next_config.turbopack_cjs_scope_hoisting().await?, cjs_scope_hoisting: *next_config.turbopack_cjs_scope_hoisting().await?,
cross_module_constants: *next_config.turbopack_cross_module_constants().await?, cross_module_constants: *next_config.turbopack_cross_module_constants().await?,
..Default::default() ..Default::default()
......
...@@ -423,7 +423,7 @@ Turbopack can be configured via `next.config.js` (or `next.config.ts`) under the ...@@ -423,7 +423,7 @@ Turbopack can be configured via `next.config.js` (or `next.config.ts`) under the
Additionally, the following experimental options are available under `experimental` in `next.config.js`: Additionally, the following experimental options are available under `experimental` in `next.config.js`:
| Option | Description | Default (dev) | Default (build) | | Option | Description | Default (dev) | Default (build) |
| ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ----------------------------- | | ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ----------------------------- |
| [`turbopackFileSystemCacheForDev`](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) | Enable filesystem cache for the dev server. | `true` | N/A | | [`turbopackFileSystemCacheForDev`](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) | Enable filesystem cache for the dev server. | `true` | N/A |
| [`turbopackFileSystemCacheForBuild`](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) | Enable filesystem cache for builds. | N/A | `true`<sup>1</sup> | | [`turbopackFileSystemCacheForBuild`](/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache) | Enable filesystem cache for builds. | N/A | `true`<sup>1</sup> |
| `turbopackMinify` | Enable minification. Accepts a boolean, or `{ server, client, edge }` to configure each environment separately. | `false` | `true` | | `turbopackMinify` | Enable minification. Accepts a boolean, or `{ server, client, edge }` to configure each environment separately. | `false` | `true` |
...@@ -432,6 +432,7 @@ Additionally, the following experimental options are available under `experiment ...@@ -432,6 +432,7 @@ Additionally, the following experimental options are available under `experiment
| `turbopackModuleFragments` | Currently in active development. This splits modules into fragments and chunks only import the used fragments of the modules. | `false` | `false` | | `turbopackModuleFragments` | Currently in active development. This splits modules into fragments and chunks only import the used fragments of the modules. | `false` | `false` |
| `turbopackRemoveUnusedImports` | Enable removing unused imports. Requires `turbopackRemoveUnusedExports`. | `false` | `true` | | `turbopackRemoveUnusedImports` | Enable removing unused imports. Requires `turbopackRemoveUnusedExports`. | `false` | `true` |
| `turbopackRemoveUnusedExports` | Enable removing unused exports. | `false` | `true` | | `turbopackRemoveUnusedExports` | Enable removing unused exports. | `false` | `true` |
| `turbopackMangleExportNames` | Shorten the export names modules expose to each other, to reduce bundle size. A module whose export names can be observed (an escaping namespace object, a dynamic `import()`, a CommonJS `require()`) keeps its original names. | `false` | `false` |
| `turbopackInferModuleSideEffects` | Enable local analysis to infer side-effect-free modules for better tree shaking. | `true` | `true` | | `turbopackInferModuleSideEffects` | Enable local analysis to infer side-effect-free modules for better tree shaking. | `true` | `true` |
| `turbopackScopeHoisting` | Enable scope hoisting. Always disabled in dev mode. | `false` | `true` | | `turbopackScopeHoisting` | Enable scope hoisting. Always disabled in dev mode. | `false` | `true` |
| `turbopackClientSideNestedAsyncChunking` | Enable nested async chunking for client-side assets. | `false` | `true` | | `turbopackClientSideNestedAsyncChunking` | Enable nested async chunking for client-side assets. | `false` | `true` |
......
...@@ -423,6 +423,7 @@ export const experimentalSchema = { ...@@ -423,6 +423,7 @@ export const experimentalSchema = {
turbopackModuleIds: z.enum(['named', 'deterministic']).optional(), turbopackModuleIds: z.enum(['named', 'deterministic']).optional(),
turbopackInferModuleSideEffects: z.boolean().optional(), turbopackInferModuleSideEffects: z.boolean().optional(),
turbopackCjsTreeShaking: z.boolean().optional(), turbopackCjsTreeShaking: z.boolean().optional(),
turbopackMangleExportNames: z.boolean().optional(),
turbopackCjsScopeHoisting: z.boolean().optional(), turbopackCjsScopeHoisting: z.boolean().optional(),
turbopackCrossModuleConstants: z.boolean().optional(), turbopackCrossModuleConstants: z.boolean().optional(),
turbopackServerFastRefresh: z.boolean().optional(), turbopackServerFastRefresh: z.boolean().optional(),
......
...@@ -1011,6 +1011,16 @@ export interface ExperimentalConfig { ...@@ -1011,6 +1011,16 @@ export interface ExperimentalConfig {
*/ */
turbopackCjsTreeShaking?: boolean turbopackCjsTreeShaking?: boolean
/**
* Shorten ("mangle") the export names modules expose to each other in Turbopack, to reduce
* bundle size. Only affects the keys used to link modules together: a module whose export names
* can be observed by user code (a namespace object that escapes, a dynamic `import()`, a
* CommonJS `require()`) keeps its original names.
*
* Defaults to `false`
*/
turbopackMangleExportNames?: boolean
/** /**
* Enable scope hoisting of static CommonJS modules. * Enable scope hoisting of static CommonJS modules.
* *
......
...@@ -23,6 +23,18 @@ pub struct UsedExportsMap(FxHashMap<ResolvedVc<Box<dyn Module>>, ModuleExportUsa ...@@ -23,6 +23,18 @@ pub struct UsedExportsMap(FxHashMap<ResolvedVc<Box<dyn Module>>, ModuleExportUsa
#[turbo_tasks::value(transparent, cell = "keyed")] #[turbo_tasks::value(transparent, cell = "keyed")]
pub struct ExportCircuitBreakers(FxHashSet<ResolvedVc<Box<dyn Module>>>); pub struct ExportCircuitBreakers(FxHashSet<ResolvedVc<Box<dyn Module>>>);
/// Modules that are read through a *partial namespace object* — an
/// [`ExportUsage::PartialNamespaceObject`] edge points at them.
///
/// The used export names are still known individually (that is why the usage stays
/// [`ModuleExportUsageInfo::Exports`]), but the reads went through a namespace value: a namespace
/// binding's member reads or destructuring, or the object a dynamic `import()` resolves to. Some of
/// those reads are lowered to direct named accesses and some are not, and this set does not
/// distinguish them — so a consumer that wants to rename the module's export keys has to assume the
/// original names may still be read somewhere, and leave them alone.
#[turbo_tasks::value(transparent, cell = "keyed")]
pub struct PartialNamespaceModules(FxHashSet<ResolvedVc<Box<dyn Module>>>);
#[turbo_tasks::value] #[turbo_tasks::value]
#[derive(Clone, Default, Debug)] #[derive(Clone, Default, Debug)]
pub struct BindingUsageInfo { pub struct BindingUsageInfo {
...@@ -32,6 +44,7 @@ pub struct BindingUsageInfo { ...@@ -32,6 +44,7 @@ pub struct BindingUsageInfo {
used_exports: ResolvedVc<UsedExportsMap>, used_exports: ResolvedVc<UsedExportsMap>,
export_circuit_breakers: ResolvedVc<ExportCircuitBreakers>, export_circuit_breakers: ResolvedVc<ExportCircuitBreakers>,
partial_namespace_modules: ResolvedVc<PartialNamespaceModules>,
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
...@@ -42,6 +55,9 @@ pub struct ModuleExportUsage { ...@@ -42,6 +55,9 @@ pub struct ModuleExportUsage {
pub export_usage: ResolvedVc<ModuleExportUsageInfo>, pub export_usage: ResolvedVc<ModuleExportUsageInfo>,
// Whether this module exists in an import cycle and has been selected to break the cycle. // Whether this module exists in an import cycle and has been selected to break the cycle.
pub is_circuit_breaker: bool, pub is_circuit_breaker: bool,
/// Whether this module is read through a namespace value somewhere, which means one of those
/// reads may still use an original export name. See [`PartialNamespaceModules`].
pub namespace_object_may_escape: bool,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ModuleExportUsage { impl ModuleExportUsage {
...@@ -50,6 +66,7 @@ impl ModuleExportUsage { ...@@ -50,6 +66,7 @@ impl ModuleExportUsage {
Ok(Self { Ok(Self {
export_usage: ModuleExportUsageInfo::all().to_resolved().await?, export_usage: ModuleExportUsageInfo::all().to_resolved().await?,
is_circuit_breaker: true, is_circuit_breaker: true,
namespace_object_may_escape: true,
} }
.cell()) .cell())
} }
...@@ -78,9 +95,12 @@ impl BindingUsageInfo { ...@@ -78,9 +95,12 @@ impl BindingUsageInfo {
bail!("export usage not found for module: {ident:?}"); bail!("export usage not found for module: {ident:?}");
}; };
let namespace_object_may_escape =
self.partial_namespace_modules.contains_key(&module).await?;
Ok(ModuleExportUsage { Ok(ModuleExportUsage {
export_usage: (*exports).clone().resolved_cell(), export_usage: (*exports).clone().resolved_cell(),
is_circuit_breaker, is_circuit_breaker,
namespace_object_may_escape,
} }
.cell()) .cell())
} }
...@@ -108,6 +128,7 @@ pub async fn compute_binding_usage_info( ...@@ -108,6 +128,7 @@ pub async fn compute_binding_usage_info(
async move { async move {
let mut used_exports = FxHashMap::<_, ModuleExportUsageInfo>::default(); let mut used_exports = FxHashMap::<_, ModuleExportUsageInfo>::default();
let mut partial_namespace_modules = FxHashSet::default();
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
let mut debug_unused_references_name = FxHashSet::<( let mut debug_unused_references_name = FxHashSet::<(
ResolvedVc<Box<dyn Module>>, ResolvedVc<Box<dyn Module>>,
...@@ -246,6 +267,14 @@ pub async fn compute_binding_usage_info( ...@@ -246,6 +267,14 @@ pub async fn compute_binding_usage_info(
let entry = used_exports.entry(target); let entry = used_exports.entry(target);
let is_first_visit = matches!(entry, Entry::Vacant(_)); let is_first_visit = matches!(entry, Entry::Vacant(_));
if matches!(
&ref_data.binding_usage.export,
ExportUsage::PartialNamespaceObject(_)
) {
// `target` is read through a namespace value. We know which names are used, but
// not that every read of them was lowered to a direct named access.
partial_namespace_modules.insert(target);
}
if entry.or_default().add(&ref_data.binding_usage.export) || is_first_visit { if entry.or_default().add(&ref_data.binding_usage.export) || is_first_visit {
// First visit, or the used exports changed. This can cause more imports to get // First visit, or the used exports changed. This can cause more imports to get
// used downstream. // used downstream.
...@@ -336,6 +365,7 @@ pub async fn compute_binding_usage_info( ...@@ -336,6 +365,7 @@ pub async fn compute_binding_usage_info(
unused_references_edges, unused_references_edges,
used_exports: ResolvedVc::cell(used_exports), used_exports: ResolvedVc::cell(used_exports),
export_circuit_breakers: ResolvedVc::cell(export_circuit_breakers), export_circuit_breakers: ResolvedVc::cell(export_circuit_breakers),
partial_namespace_modules: ResolvedVc::cell(partial_namespace_modules),
} }
.cell()) .cell())
} }
......
...@@ -288,6 +288,38 @@ pub enum EcmascriptExports { ...@@ -288,6 +288,38 @@ pub enum EcmascriptExports {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl EcmascriptExports { impl EcmascriptExports {
/// A view of these exports for a module that *borrows* them from another module, i.e. whose
/// `get_exports` hands out the exports value of some other module verbatim.
///
/// Export mangling is decided per module: the producing side keys on the module whose code
/// generation emits the export object, and the consuming side on the module it imports from.
/// An exports value shared by two module identities would let those two sides compute
/// different keys for the same export, so a borrowed view is always unmangled — which both
/// sides agree on.
#[turbo_tasks::function]
pub async fn borrowed(self: Vc<Self>) -> Result<Vc<EcmascriptExports>> {
let this = self.await?;
Ok(match &*this {
EcmascriptExports::EsmExports(exports) => {
let exports = exports.await?;
if !exports.mangle_export_names {
return Ok(self);
}
EcmascriptExports::EsmExports(
EsmExports {
exports: exports.exports.clone(),
star_exports: exports.star_exports.clone(),
mangle_export_names: false,
}
.resolved_cell(),
)
.cell()
}
// Nothing else carries a mangling decision.
_ => self,
})
}
/// Returns whether this module should be split into separate locals and facade modules. /// Returns whether this module should be split into separate locals and facade modules.
/// ///
/// Splitting is enabled when the module has re-exports (star exports or imported bindings), /// Splitting is enabled when the module has re-exports (star exports or imported bindings),
......
...@@ -22,11 +22,20 @@ use crate::{ ...@@ -22,11 +22,20 @@ use crate::{
EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports, EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports,
ecmascript_chunk_item, ecmascript_chunk_item,
}, },
references::esm::{EsmExport, EsmExports, Liveness}, references::esm::{EsmExport, EsmExports, Liveness, mangle::generated_export_key},
runtime_functions::{TURBOPACK_ESM, TURBOPACK_IMPORT}, runtime_functions::{TURBOPACK_ESM, TURBOPACK_IMPORT},
utils::StringifyJs, utils::StringifyJs,
}; };
/// The single export of the generated collect module.
///
/// Both the producer below and the read side in `references::emit_collect` resolve the key this is
/// actually *emitted* under through `generated_export_key`, rather than assuming the source name,
/// so the two cannot drift apart. Today that always resolves back to this name — see
/// `get_exports` for why — but wiring it through means mangling starts applying to both sides
/// together the moment it becomes possible, with no further change here.
pub const COLLECT_LIST_EXPORT: RcStr = rcstr!("getList");
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct EcmascriptCollectModule { pub struct EcmascriptCollectModule {
parent_module: ResolvedVc<Box<dyn Module>>, parent_module: ResolvedVc<Box<dyn Module>>,
...@@ -165,11 +174,20 @@ impl EcmascriptChunkPlaceable for EcmascriptCollectModuleWithChunkGroup { ...@@ -165,11 +174,20 @@ impl EcmascriptChunkPlaceable for EcmascriptCollectModuleWithChunkGroup {
EcmascriptExports::EsmExports( EcmascriptExports::EsmExports(
EsmExports { EsmExports {
exports: [( exports: [(
"getList".into(), COLLECT_LIST_EXPORT,
EsmExport::LocalBinding(rcstr!("getList"), Liveness::Constant), EsmExport::LocalBinding(COLLECT_LIST_EXPORT, Liveness::Constant),
)] )]
.into(), .into(),
star_exports: vec![], star_exports: vec![],
// This module is code-generated but never referenced in the module graph (it is
// reached through `collected_modules`), so it has no entry in the graph's
// used-export map and `module_export_usage` cannot answer for it — the same class
// of module as the wasm loader and the client-reference proxy, which
// `BindingUsageInfo::used_exports` special-cases by ident with a `TODO fix these
// cases`. Mangling therefore cannot be computed here at all, rather than being
// merely undesirable. Keeping this `false` makes `mangled_export_names` answer
// before it consults the graph; flip it once this module is graph-tracked.
mangle_export_names: false,
} }
.resolved_cell(), .resolved_cell(),
) )
...@@ -204,15 +222,16 @@ impl EcmascriptChunkPlaceable for EcmascriptCollectModuleWithChunkGroup { ...@@ -204,15 +222,16 @@ impl EcmascriptChunkPlaceable for EcmascriptCollectModuleWithChunkGroup {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn chunk_item_content( async fn chunk_item_content(
&self, self: Vc<Self>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_graph: Vc<ModuleGraph>, module_graph: Vc<ModuleGraph>,
_async_module_info: Option<Vc<AsyncModuleInfo>>, _async_module_info: Option<Vc<AsyncModuleInfo>>,
_estimated: bool, _estimated: bool,
) -> Result<Vc<EcmascriptChunkItemContent>> { ) -> Result<Vc<EcmascriptChunkItemContent>> {
let this = self.await?;
let chunk_item_id_strategy = chunking_context.chunk_item_id_strategy().await?; let chunk_item_id_strategy = chunking_context.chunk_item_id_strategy().await?;
let entries = self let entries = this
.entry_chunk_group .entry_chunk_group
.await? .await?
.into_iter() .into_iter()
...@@ -220,7 +239,7 @@ impl EcmascriptChunkPlaceable for EcmascriptCollectModuleWithChunkGroup { ...@@ -220,7 +239,7 @@ impl EcmascriptChunkPlaceable for EcmascriptCollectModuleWithChunkGroup {
let collected_modules = module_graph.collected_modules(); let collected_modules = module_graph.collected_modules();
let items = collected_modules let items = collected_modules
.get(&ResolvedVc::upcast(self.module)) .get(&ResolvedVc::upcast(this.module))
.await?; .await?;
let items = items let items = items
.iter() .iter()
...@@ -262,11 +281,19 @@ impl EcmascriptChunkPlaceable for EcmascriptCollectModuleWithChunkGroup { ...@@ -262,11 +281,19 @@ impl EcmascriptChunkPlaceable for EcmascriptCollectModuleWithChunkGroup {
code += "]);"; code += "]);";
code += "function getList() { return data; }"; code += "function getList() { return data; }";
// The *key* this is exposed under may be mangled; the local binding keeps its own name.
// `references::emit_collect` resolves the same key for the read side, so both agree.
let export = generated_export_key(
ResolvedVc::upcast(self.to_resolved().await?),
chunking_context,
&COLLECT_LIST_EXPORT,
)
.await?;
writeln!( writeln!(
code, code,
"{TURBOPACK_ESM}([ "{TURBOPACK_ESM}([\n {}, ()=>getList\n]);",
'getList', ()=>getList StringifyJs(&export),
]);"
)?; )?;
Ok(EcmascriptChunkItemContent { Ok(EcmascriptChunkItemContent {
......
...@@ -242,6 +242,10 @@ pub struct EcmascriptOptions { ...@@ -242,6 +242,10 @@ pub struct EcmascriptOptions {
pub infer_module_side_effects: bool, pub infer_module_side_effects: bool,
/// Whether to tree shake unused exports from static CommonJS modules. Defaults to false. /// Whether to tree shake unused exports from static CommonJS modules. Defaults to false.
pub cjs_tree_shaking: bool, pub cjs_tree_shaking: bool,
/// Whether to shorten ("mangle") the export names this module exposes to other modules, to
/// reduce output size. Defaults to false. See
/// `references::esm::mangle::mangled_export_names`.
pub mangle_export_names: bool,
/// Whether to scope hoist static CommonJS modules. Defaults to false. /// Whether to scope hoist static CommonJS modules. Defaults to false.
pub cjs_scope_hoisting: bool, pub cjs_scope_hoisting: bool,
/// Whether to enable cross-module constant inlining. Defaults to false. /// Whether to enable cross-module constant inlining. Defaults to false.
......
...@@ -134,7 +134,8 @@ impl Module for SideEffectsModule { ...@@ -134,7 +134,8 @@ impl Module for SideEffectsModule {
impl EcmascriptChunkPlaceable for SideEffectsModule { impl EcmascriptChunkPlaceable for SideEffectsModule {
#[turbo_tasks::function] #[turbo_tasks::function]
fn get_exports(&self) -> Vc<EcmascriptExports> { fn get_exports(&self) -> Vc<EcmascriptExports> {
self.resolved_as.get_exports() // Borrowed from another module identity, so it must not carry a mangling decision.
self.resolved_as.get_exports().borrowed()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use bincode::{Decode, Encode}; use bincode::{Decode, Encode};
use swc_core::{ use swc_core::{
ecma::ast::{Expr, Invalid}, common::DUMMY_SP,
quote, ecma::ast::{Expr, IdentName, Invalid, MemberExpr, MemberProp},
}; };
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
...@@ -28,10 +28,11 @@ use turbopack_resolve::ecmascript::esm_resolve; ...@@ -28,10 +28,11 @@ use turbopack_resolve::ecmascript::esm_resolve;
use crate::{ use crate::{
analyzer::imports::ImportAnnotations, analyzer::imports::ImportAnnotations,
code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference}, code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference},
collect_module::EcmascriptCollectModule, collect_module::{COLLECT_LIST_EXPORT, EcmascriptCollectModule},
create_visitor, create_visitor,
references::{ references::{
AstPath, AstPath,
esm::{base::ReferencedAsset, mangle::generated_export_key},
pattern_mapping::{PatternMapping, ResolveType}, pattern_mapping::{PatternMapping, ResolveType},
removal::RemovalCodeGen, removal::RemovalCodeGen,
}, },
...@@ -253,14 +254,27 @@ impl CollectReferenceCodeGen { ...@@ -253,14 +254,27 @@ impl CollectReferenceCodeGen {
.await?; .await?;
let mut visitors = Vec::new(); let mut visitors = Vec::new();
// The collect module's own `getList` export is mangled like any other, so resolve the key
// it is actually emitted under rather than hard-coding the source name. Both sides ask the
// same module, so they always agree; when that module keeps its original names this is
// just `getList` again.
let export =
match ReferencedAsset::from_resolve_result(self.reference.resolve_reference()).await? {
ReferencedAsset::Some(module) => {
generated_export_key(module, chunking_context, &COLLECT_LIST_EXPORT).await?
}
_ => COLLECT_LIST_EXPORT,
};
visitors.push(create_visitor!( visitors.push(create_visitor!(
self.path, self.path,
visit_mut_expr, visit_mut_expr,
|expr: &mut Expr| { |expr: &mut Expr| {
*expr = quote!( *expr = Expr::Member(MemberExpr {
"$v.getList" as Expr, span: DUMMY_SP,
v: Expr = pm.create_require(Expr::Invalid(Invalid::default())) obj: Box::new(pm.create_require(Expr::Invalid(Invalid::default()))),
); prop: MemberProp::Ident(IdentName::new(export.as_str().into(), DUMMY_SP)),
});
} }
)); ));
......
...@@ -51,6 +51,7 @@ use crate::{ ...@@ -51,6 +51,7 @@ use crate::{
esm::{ esm::{
EsmExport, EsmExport,
export::{all_known_export_names, is_export_missing}, export::{all_known_export_names, is_export_missing},
mangle::generated_export_key,
}, },
util::{SpecifiedChunkingType, throw_module_not_found_expr}, util::{SpecifiedChunkingType, throw_module_not_found_expr},
}, },
...@@ -308,7 +309,16 @@ impl ReferencedAsset { ...@@ -308,7 +309,16 @@ impl ReferencedAsset {
Some(ReferencedAssetIdent::Module { Some(ReferencedAssetIdent::Module {
namespace_ident: import_source.get_namespace_ident(chunking_context).await?, namespace_ident: import_source.get_namespace_ident(chunking_context).await?,
ctxt: None, ctxt: None,
export, // The target module may emit its exports under shortened keys. This is the
// only place a cross-module export access is materialized, and it resolves
// the same map the producing module uses (see
// `EsmExports::code_generation`), so the two always agree.
export: match &export {
Some(export) => {
Some(generated_export_key(*asset, chunking_context, export).await?)
}
None => None,
},
import_source, import_source,
}) })
} }
......
...@@ -33,7 +33,7 @@ use crate::{ ...@@ -33,7 +33,7 @@ use crate::{
code_gen::{CodeGeneration, CodeGenerationHoistedStmt}, code_gen::{CodeGeneration, CodeGenerationHoistedStmt},
magic_identifier::MAGIC_IDENTIFIER_DEFAULT_EXPORT_ATOM, magic_identifier::MAGIC_IDENTIFIER_DEFAULT_EXPORT_ATOM,
module_fragments::part::module::EcmascriptModulePartAsset, module_fragments::part::module::EcmascriptModulePartAsset,
references::esm::base::ReferencedAsset, references::esm::{base::ReferencedAsset, mangle::mangled_export_names},
runtime_functions::{TURBOPACK_DYNAMIC, TURBOPACK_ESM}, runtime_functions::{TURBOPACK_DYNAMIC, TURBOPACK_ESM},
utils::module_id_to_lit, utils::module_id_to_lit,
}; };
...@@ -533,6 +533,10 @@ pub struct EsmExports { ...@@ -533,6 +533,10 @@ pub struct EsmExports {
pub exports: FrozenMap<RcStr, EsmExport>, pub exports: FrozenMap<RcStr, EsmExport>,
/// Unexpanded `export * from ...` statements (expanded in `expand_star_exports`) /// Unexpanded `export * from ...` statements (expanded in `expand_star_exports`)
pub star_exports: Vec<ResolvedVc<Box<dyn ModuleReference>>>, pub star_exports: Vec<ResolvedVc<Box<dyn ModuleReference>>>,
/// Whether the keys these exports are emitted under may be shortened. Carried with the exports
/// so a module deriving its exports from another (facade, locals, part, rename) inherits it.
/// `mangle::mangled_export_names` decides whether they actually are.
pub mangle_export_names: bool,
} }
/// The expanded version of [`EsmExports`], the `exports` field here includes all exports that could /// The expanded version of [`EsmExports`], the `exports` field here includes all exports that could
...@@ -571,6 +575,9 @@ impl EsmExports { ...@@ -571,6 +575,9 @@ impl EsmExports {
EsmExports { EsmExports {
exports: FrozenMap::from(exports), exports: FrozenMap::from(exports),
star_exports: vec![module_reference], star_exports: vec![module_reference],
// These facades exist so that a host framework can find the wrapped module's
// exports by name, so their keys have to stay as written.
mangle_export_names: false,
} }
.resolved_cell(), .resolved_cell(),
) )
...@@ -697,6 +704,9 @@ impl EsmExports { ...@@ -697,6 +704,9 @@ 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
// module (see `ReferencedAsset::get_ident_inner`), so both sides always agree.
let mangled_names = mangled_export_names(*module, chunking_context).await?;
for (exported, local) in &expanded.exports { for (exported, local) in &expanded.exports {
let exprs: ExportBinding = match local { let exprs: ExportBinding = match local {
EsmExport::Error => ExportBinding::Getter(quote!( EsmExport::Error => ExportBinding::Getter(quote!(
...@@ -839,7 +849,14 @@ impl EsmExports { ...@@ -839,7 +849,14 @@ impl EsmExports {
getters.push(Some( getters.push(Some(
Expr::Lit(Lit::Str(Str { Expr::Lit(Lit::Str(Str {
span: DUMMY_SP, span: DUMMY_SP,
value: exported.as_str().into(), // The key this export is emitted under: the mangled one when this module's
// names are shortened, otherwise the original.
value: mangled_names
.as_ref()
.and_then(|names| names.get(exported))
.unwrap_or(exported)
.as_str()
.into(),
raw: None, raw: None,
})) }))
.into(), .into(),
......
//! Shortening ("mangling") of the export names a module exposes to other modules.
//!
//! A module's export keys usually only exist to link modules together: the producing module emits
//! `{ someVeryLongExportName: () => … }` and every consumer reads
//! `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
//! observable from user code.
//!
//! [`mangled_export_names`] is the single source of truth for that mapping. Both the producer
//! ([`super::export::EsmExports::code_generation`]) and the consumer
//! ([`super::base::ReferencedAsset`]) ask it for the *target* module's map, so they cannot
//! disagree. It returns an empty map whenever the module has to keep its original names — the
//! same effect as mangling every name to itself, so callers never need to branch on "did mangling
//! even apply here", only look a name up and fall back to itself.
//!
//! Code generation that spells an export access out **as a string** — rather than going through
//! `ReferencedAssetIdent`, which handles this automatically — must resolve its key through
//! [`generated_export_key`]. A hard-coded `["someExport"]` in generated source silently misses as
//! soon as the target module's exports are mangled.
mod table;
use anyhow::Result;
use turbo_frozenmap::FrozenMap;
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc};
use turbopack_core::{
chunk::ChunkingContext, module_graph::binding_usage_info::ModuleExportUsageInfo,
};
use self::table::shorten_to_unique_names;
use crate::chunk::{EcmascriptChunkPlaceable, EcmascriptExports};
/// A module's export name mapping: original export name -> the key actually used in the output.
///
/// `None` means the module is not eligible for mangling at all and keeps every original name (see
/// [`mangled_export_names`] for the conditions). `Some` covers only the exports that were actually
/// *renamed* — an export that kept its own name because it was already short enough, or because it
/// lost every hash collision, is not a key in the map. So a missing key always means "use the
/// original name", and callers that only want the correct output key can ignore the distinction
/// entirely (see [`generated_export_key`]); the `canMangle` reporting in
/// [`crate::references::exports_info`] is the one caller that needs to tell "not eligible" from
/// "eligible but unchanged", which is exactly what the `Option` gives it.
#[turbo_tasks::value(transparent)]
pub struct MangledExportNames(pub Option<FrozenMap<RcStr, RcStr>>);
/// Computes the mangled export names of `module`, or `None` when its exports must keep their
/// original names.
///
/// Both the producing and the consuming side call this for the same `module`, which is what
/// guarantees they agree. The mapping covers the module's *used* exports: unused exports are not
/// emitted at all, so giving them names would only make the remaining names longer.
///
/// A module keeps its original names when any of these hold:
///
/// 1. mangling is disabled for the module that owns these exports,
/// 2. its export usage is [`ModuleExportUsageInfo::All`] — a namespace import, a computed property
/// access, an unresolvable `export *`, or a module referenced from outside the module graph
/// (entries, which are seeded with `All`). This is what a plain `import * as ns` reaches in
/// practice, whether or not the namespace object escapes: the reads are not enumerated, so the
/// usage widens to `All`. Note that widening propagates, so splitting such a module into a
/// facade and a locals module does not rescue the locals module,
/// 3. it is read through a namespace value whose used names *are* known — in practice a dynamic
/// `import()` with an enumerated export list (`import(/* webpackExports: [...] */ "…")`). We
/// know which names are used, but not that every read of them was lowered to a direct named
/// access, so an original name may still be read by user code,
/// 4. its exports are not statically known ECMAScript exports, or contain dynamic re-exports.
///
/// None of these depend on the individual export, so "is `e` a candidate for mangling" is exactly
/// "is this `Some`, and is `e` used" — the per-name step (hashing into a short identifier) never
/// itself excludes a name.
#[turbo_tasks::function]
pub async fn mangled_export_names(
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<MangledExportNames>> {
// (4) Only statically known ESM exports can be renamed.
let EcmascriptExports::EsmExports(exports) = *module.get_exports().await? else {
return Ok(Vc::cell(None));
};
// (1) Disabled for the module these exports belong to. Deliberately independent of whether
// this build minifies at all: mangling and minification are two separate concerns, and a
// caller may want either without the other.
if !exports.await?.mangle_export_names {
return Ok(Vc::cell(None));
}
let usage = chunking_context
.module_export_usage(*ResolvedVc::upcast(module))
.await?;
// (3) An original name may still be read through a namespace value.
if usage.namespace_object_may_escape {
return Ok(Vc::cell(None));
}
// (2) We don't know which exports are used, so we don't know that all uses are ours.
let usage_info = usage.export_usage.await?;
let ModuleExportUsageInfo::Exports(used) = &*usage_info else {
return Ok(Vc::cell(None));
};
if used.is_empty() {
return Ok(Vc::cell(None));
}
// (4) `export * from "./some-dynamic-cjs"` is resolved at runtime by property access on the
// original names, and a used set that resolves to no actual export at all leaves nothing to
// mangle.
let expanded = exports.expand_exports(*usage.export_usage).await?;
if !expanded.dynamic_exports.is_empty() || expanded.exports.is_empty() {
return Ok(Vc::cell(None));
}
// Every emitted export is mangled, `default` and `__esModule` included.
//
// Neither is a runtime contract *as an export name*. The runtime paths that look `'default'` up
// by name — the CommonJS interop in `esmNamespaceObject` and the proxy traps behind
// `ensureDynamicExports` — only apply to CommonJS targets and to modules with dynamic
// re-exports, and both already keep their original names via the checks above. `__esModule` is
// how a CommonJS module signals interop *to* ESM, so an ESM module that happens to export that
// name is just an ordinary export. `__esModule` still cannot be *assigned* to some other
// export, because the runtime defines that property itself; see `RESERVED_KEYS` in `table`.
Ok(Vc::cell(Some(shorten_to_unique_names(
expanded.exports.keys(),
))))
}
/// The key that generated code has to use to read `export` from `module` — the mangled key when
/// the module's exports are mangled, and `export` itself otherwise.
///
/// **Every** piece of code generation that materializes an export access as a string has to get its
/// key from here, or the access will miss when the module is mangled. That includes generated
/// source text (`__turbopack_require__(id)["default"](…)` and friends) as well as AST built by
/// hand. Code that goes through `ReferencedAssetIdent` (see `super::base`) is already covered.
///
/// `module` must be the module that actually *produces* the export. For a re-export, resolve to the
/// producing module first (as `ReferencedAsset::get_ident_inner` does), because each module mangles
/// its own keys independently.
pub async fn generated_export_key(
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
export: &RcStr,
) -> Result<RcStr> {
let names = mangled_export_names(*module, chunking_context).await?;
Ok(names
.as_ref()
.and_then(|names| names.get(export))
.cloned()
.unwrap_or_else(|| export.clone()))
}
...@@ -2,6 +2,7 @@ pub(crate) mod base; ...@@ -2,6 +2,7 @@ pub(crate) mod base;
pub(crate) mod binding; pub(crate) mod binding;
pub(crate) mod dynamic; pub(crate) mod dynamic;
pub(crate) mod export; pub(crate) mod export;
pub(crate) mod mangle;
pub(crate) mod meta; pub(crate) mod meta;
pub(crate) mod module_id; pub(crate) mod module_id;
pub(crate) mod module_item; pub(crate) mod module_item;
...@@ -12,6 +13,7 @@ pub use self::{ ...@@ -12,6 +13,7 @@ pub use self::{
binding::EsmBinding, binding::EsmBinding,
dynamic::EsmAsyncAssetReference, dynamic::EsmAsyncAssetReference,
export::{EsmExport, EsmExports, FoundExportType, Liveness}, export::{EsmExport, EsmExports, FoundExportType, Liveness},
mangle::generated_export_key,
meta::{ImportMetaBinding, ImportMetaRef}, meta::{ImportMetaBinding, ImportMetaRef},
module_item::EsmModuleItem, module_item::EsmModuleItem,
url::{UrlAssetReference, UrlRewriteBehavior}, url::{UrlAssetReference, UrlRewriteBehavior},
......
...@@ -179,6 +179,7 @@ pub async fn compute_ecmascript_module_exports( ...@@ -179,6 +179,7 @@ pub async fn compute_ecmascript_module_exports(
let esm_exports = EsmExports { let esm_exports = EsmExports {
exports: esm_exports, exports: esm_exports,
star_exports: esm_star_exports, star_exports: esm_star_exports,
mangle_export_names: options.mangle_export_names,
} }
.cell(); .cell();
...@@ -199,6 +200,7 @@ pub async fn compute_ecmascript_module_exports( ...@@ -199,6 +200,7 @@ pub async fn compute_ecmascript_module_exports(
EsmExports { EsmExports {
exports: Default::default(), exports: Default::default(),
star_exports: Default::default(), star_exports: Default::default(),
mangle_export_names: options.mangle_export_names,
} }
.resolved_cell(), .resolved_cell(),
) )
...@@ -210,6 +212,7 @@ pub async fn compute_ecmascript_module_exports( ...@@ -210,6 +212,7 @@ pub async fn compute_ecmascript_module_exports(
EsmExports { EsmExports {
exports: Default::default(), exports: Default::default(),
star_exports: Default::default(), star_exports: Default::default(),
mangle_export_names: options.mangle_export_names,
} }
.resolved_cell(), .resolved_cell(),
), ),
...@@ -224,6 +227,7 @@ pub async fn compute_ecmascript_module_exports( ...@@ -224,6 +227,7 @@ pub async fn compute_ecmascript_module_exports(
EsmExports { EsmExports {
exports: Default::default(), exports: Default::default(),
star_exports: Default::default(), star_exports: Default::default(),
mangle_export_names: options.mangle_export_names,
} }
.resolved_cell(), .resolved_cell(),
) )
......
...@@ -13,7 +13,7 @@ use crate::{ ...@@ -13,7 +13,7 @@ use crate::{
chunk::{EcmascriptChunkPlaceable, EcmascriptExports}, chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, magic_identifier, create_visitor, magic_identifier,
references::AstPath, references::{AstPath, esm::mangle::mangled_export_names},
}; };
/// Responsible for initializing the `ExportsInfoBinding` object binding, so that it may be /// Responsible for initializing the `ExportsInfoBinding` object binding, so that it may be
...@@ -44,18 +44,48 @@ impl ExportsInfoBinding { ...@@ -44,18 +44,48 @@ impl ExportsInfoBinding {
.module_export_usage(*ResolvedVc::upcast(module)) .module_export_usage(*ResolvedVc::upcast(module))
.await?; .await?;
let export_usage_info = export_usage_info.export_usage.await?; let export_usage_info = export_usage_info.export_usage.await?;
// The keys of `__webpack_exports_info__` stay the *original* export names — user code
// looks them up by name. The emitted key is reported as `mangledName` instead, which is
// always present alongside `canMangle` (`null` when `canMangle` is false), regardless of
// whether export mangling is enabled at all — see the `map` closure below for exactly
// what each of the three fields means.
let exports = exports.await?;
let mangled_names = mangled_export_names(*module, chunking_context).await?;
let props = if let EcmascriptExports::EsmExports(exports) = &*exports.await? { let props = if let EcmascriptExports::EsmExports(exports) = &*exports {
exports exports
.await? .await?
.exports .exports
.keys() .keys()
.map(|e| { .map(|e| {
let used: Expr = export_usage_info.is_export_used(e).into(); let is_used = export_usage_info.is_export_used(e);
let used: Expr = is_used.into();
// `canMangle` is true exactly when this export is a genuine candidate for
// mangling: the module has to be eligible at all (which is what a `Some` map
// means — see `mangled_export_names`) and the export itself has to be used, as
// an unused export is never emitted and so was never a candidate.
// `mangledName` is then always a string — the assigned key when mangling
// actually renamed it, or the export's own name when it was considered but
// kept itself (e.g. already short enough) — and only `null` when `canMangle`
// is false.
let can_mangle_names = mangled_names.as_ref().filter(|_| is_used);
let can_mangle_expr: Expr = can_mangle_names.is_some().into();
let mangled_name: Expr =
match can_mangle_names {
Some(names) => Expr::Lit(names.get(e).unwrap_or(e).as_str().into()),
None => Expr::Lit(swc_core::ecma::ast::Lit::Null(
swc_core::ecma::ast::Null { span: DUMMY_SP },
)),
};
PropOrSpread::Prop(Box::new(swc_core::ecma::ast::Prop::KeyValue( PropOrSpread::Prop(Box::new(swc_core::ecma::ast::Prop::KeyValue(
KeyValueProp { KeyValueProp {
key: PropName::Str(e.as_str().into()), key: PropName::Str(e.as_str().into()),
value: quote!("{ used: $v }" as Box<Expr>, v: Expr = used), value: quote!(
"{ used: $v, canMangle: $c, mangledName: $m }" as Box<Expr>,
v: Expr = used,
c: Expr = can_mangle_expr,
m: Expr = mangled_name
),
}, },
))) )))
}) })
......
...@@ -241,6 +241,12 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleRenameModule { ...@@ -241,6 +241,12 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleRenameModule {
let exports = EsmExports { let exports = EsmExports {
exports: FrozenMap::from_unique_sorted_box(Box::new([export])), exports: FrozenMap::from_unique_sorted_box(Box::new([export])),
star_exports: Vec::new(), star_exports: Vec::new(),
// This module only re-exports one binding of `self.module` under a different name, so
// whether its own key may be shortened follows the module it renames.
mangle_export_names: match &*self.module.get_exports().await? {
EcmascriptExports::EsmExports(exports) => exports.await?.mangle_export_names,
_ => false,
},
} }
.resolved_cell(); .resolved_cell();
Ok(EcmascriptExports::EsmExports(exports).cell()) Ok(EcmascriptExports::EsmExports(exports).cell())
......
...@@ -243,6 +243,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleFacadeModule { ...@@ -243,6 +243,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleFacadeModule {
let exports = EsmExports { let exports = EsmExports {
exports: FrozenMap::from_unique_sorted_box(exports.into_boxed_slice()), exports: FrozenMap::from_unique_sorted_box(exports.into_boxed_slice()),
star_exports: esm_exports.star_exports.clone(), star_exports: esm_exports.star_exports.clone(),
mangle_export_names: esm_exports.mangle_export_names,
} }
.resolved_cell(); .resolved_cell();
Ok(EcmascriptExports::EsmExports(exports).cell()) Ok(EcmascriptExports::EsmExports(exports).cell())
......
...@@ -184,6 +184,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleLocalsModule { ...@@ -184,6 +184,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleLocalsModule {
let exports = EsmExports { let exports = EsmExports {
exports: FrozenMap::from_unique_sorted_box(exports.into_boxed_slice()), exports: FrozenMap::from_unique_sorted_box(exports.into_boxed_slice()),
star_exports: vec![], star_exports: vec![],
mangle_export_names: esm_exports.mangle_export_names,
} }
.resolved_cell(); .resolved_cell();
Ok(EcmascriptExports::EsmExports(exports).cell()) Ok(EcmascriptExports::EsmExports(exports).cell())
......
...@@ -27,6 +27,7 @@ use crate::{ ...@@ -27,6 +27,7 @@ use crate::{
EcmascriptExports, data::EcmascriptChunkData, ecmascript_chunk_item, EcmascriptExports, data::EcmascriptChunkData, ecmascript_chunk_item,
}, },
embed_js::embed_fs, embed_js::embed_fs,
references::esm::generated_export_key,
runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_REQUIRE}, runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_REQUIRE},
utils::{StringifyJs, StringifyModuleId}, utils::{StringifyJs, StringifyModuleId},
}; };
...@@ -261,6 +262,10 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule { ...@@ -261,6 +262,10 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule {
// otherwise we will induce a turbo tasks cycle. But we only need an // otherwise we will induce a turbo tasks cycle. But we only need an
// approximate solution. We'll use the same estimate for both web // approximate solution. We'll use the same estimate for both web
// and Node.js workers. // and Node.js workers.
//
// That includes the export key: resolving the real one needs the chunking context, so
// the estimate uses the source name even when the helper's exports are mangled. It can
// only be off by a few characters.
let fake_id = ModuleId::String(rcstr!("a_fake_module")); let fake_id = ModuleId::String(rcstr!("a_fake_module"));
return Ok(EcmascriptChunkItemContent { return Ok(EcmascriptChunkItemContent {
inner_code: formatdoc! { inner_code: formatdoc! {
...@@ -277,10 +282,19 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule { ...@@ -277,10 +282,19 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule {
.cell()); .cell());
} }
let create_worker_id = self let create_worker_module = self.create_worker_module();
.create_worker_module() let create_worker_id = create_worker_module.chunk_item_id(chunking_context).await?;
.chunk_item_id(chunking_context) // The helper's `default` export is read here as a string, so it has to go through the same
.await?; // mapping the helper itself emits — a hard-coded `["default"]` misses once its exports are
// mangled.
let create_worker_export = match ResolvedVc::try_sidecast::<Box<dyn EcmascriptChunkPlaceable>>(
create_worker_module.to_resolved().await?,
) {
Some(placeable) => {
generated_export_key(placeable, chunking_context, &rcstr!("default")).await?
}
None => rcstr!("default"),
};
let code = match this.worker_type { let code = match this.worker_type {
WorkerType::WebWorker | WorkerType::SharedWebWorker => { WorkerType::WebWorker | WorkerType::SharedWebWorker => {
...@@ -306,11 +320,12 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule { ...@@ -306,11 +320,12 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule {
formatdoc! { formatdoc! {
r#" r#"
{TURBOPACK_EXPORT_VALUE}({TURBOPACK_REQUIRE}({workers_module})["default"]({entrypoint}, {chunks})); {TURBOPACK_EXPORT_VALUE}({TURBOPACK_REQUIRE}({workers_module})[{export:#}]({entrypoint}, {chunks}));
"#, "#,
entrypoint = StringifyJs(&entrypoint_path), entrypoint = StringifyJs(&entrypoint_path),
chunks = StringifyJs(&chunks_data), chunks = StringifyJs(&chunks_data),
workers_module = StringifyModuleId(&create_worker_id), workers_module = StringifyModuleId(&create_worker_id),
export = StringifyJs(&create_worker_export),
} }
} }
WorkerType::NodeWorkerThread => { WorkerType::NodeWorkerThread => {
...@@ -338,10 +353,11 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule { ...@@ -338,10 +353,11 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule {
// directory // directory
formatdoc! { formatdoc! {
r#" r#"
{TURBOPACK_EXPORT_VALUE}({TURBOPACK_REQUIRE}({workers_module})["default"](__dirname + "/" + {worker_path:#})); {TURBOPACK_EXPORT_VALUE}({TURBOPACK_REQUIRE}({workers_module})[{export:#}](__dirname + "/" + {worker_path:#}));
"#, "#,
worker_path = StringifyJs(entry_path.file_name()), worker_path = StringifyJs(entry_path.file_name()),
workers_module = StringifyModuleId(&create_worker_id), workers_module = StringifyModuleId(&create_worker_id),
export = StringifyJs(&create_worker_export),
} }
} }
}; };
......
...@@ -280,6 +280,8 @@ struct TestOptions { ...@@ -280,6 +280,8 @@ struct TestOptions {
infer_module_side_effects: bool, infer_module_side_effects: bool,
#[serde(default)] #[serde(default)]
cjs_tree_shaking: bool, cjs_tree_shaking: bool,
#[serde(default)]
mangle_export_names: bool,
#[serde(default = "default_true")] #[serde(default = "default_true")]
cross_module_constants: bool, cross_module_constants: bool,
#[serde(default)] #[serde(default)]
...@@ -312,6 +314,7 @@ impl Default for TestOptions { ...@@ -312,6 +314,7 @@ impl Default for TestOptions {
remove_unused_imports: default_true(), remove_unused_imports: default_true(),
scope_hoisting: default_true(), scope_hoisting: default_true(),
cjs_tree_shaking: false, cjs_tree_shaking: false,
mangle_export_names: false,
cjs_scope_hoisting: false, cjs_scope_hoisting: false,
cross_module_constants: true, cross_module_constants: true,
infer_module_side_effects: default_true(), infer_module_side_effects: default_true(),
...@@ -479,6 +482,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V ...@@ -479,6 +482,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
import_externals: true, import_externals: true,
enable_exports_info_inlining: true, enable_exports_info_inlining: true,
cjs_tree_shaking: options.cjs_tree_shaking, cjs_tree_shaking: options.cjs_tree_shaking,
mangle_export_names: options.mangle_export_names,
cjs_scope_hoisting: options.cjs_scope_hoisting, cjs_scope_hoisting: options.cjs_scope_hoisting,
cross_module_constants: options.cross_module_constants, cross_module_constants: options.cross_module_constants,
infer_module_side_effects: options.infer_module_side_effects, infer_module_side_effects: options.infer_module_side_effects,
......
export const ENUM_A = 'a-value'
export const ENUM_B = 'b-value'
export default 'default-value'
export const exportsInfo = {
ENUM_A: __webpack_exports_info__.ENUM_A,
ENUM_B: __webpack_exports_info__.ENUM_B,
}
// NOT IMPLEMENTED YET — this fixture is expected to fail.
//
// Turbopack currently backs off completely when a namespace object of a module escapes: the module
// keeps its original export keys. Webpack does better — it keeps mangling the internal keys and
// *materializes* a namespace object that maps the original names onto them, so one `import * as ns`
// in a dependency no longer un-mangles the whole module.
//
// See webpack's `test/configCases/mangle/mangle-escaping-namespace`, which asserts both halves:
// the raw export is not defined under its original name, and the materialized namespace object
// exposes the original name.
//
// What blocks it today is *export usage*, not module structure. When the namespace object genuinely
// escapes (`export const getEnums = () => ns`), the analysis cannot enumerate the reads, so the
// module's usage widens to `ModuleExportUsageInfo::All` and mangling backs off on that. Forcing the
// facade / locals split for mangled modules does not help: the widened usage propagates through the
// facade to the locals module, so both keep their original keys. Materialization needs the facade to
// pin the original names *while* declaring a known, named usage of the locals module.
//
// Lives under `__skipped__`, so the harness asserts it still fails. When materialization is
// implemented this fixture starts passing, the suite goes red, and it should be moved out of
// `__skipped__`.
import { getEnums } from './provider'
it('should still mangle a module whose namespace escapes', () => {
const ns = getEnums()
// The namespace object keeps the original names...
expect(ns.ENUM_A).toBe('a-value')
expect(ns.ENUM_B).toBe('b-value')
expect(ns.default).toBe('default-value')
expect(Object.keys(ns).sort()).toEqual([
'ENUM_A',
'ENUM_B',
'default',
'exportsInfo',
])
// ...while the module's own export keys are still shortened. This is the part that isn't
// implemented: today `canMangle` is false here because we back off instead.
expect(ns.exportsInfo.ENUM_A.canMangle).toBe(true)
expect(ns.exportsInfo.ENUM_A.mangledName).not.toBe('ENUM_A')
expect(ns.exportsInfo.ENUM_B.mangledName).not.toBe(
ns.exportsInfo.ENUM_A.mangledName
)
})
import * as ns from './enums'
// The namespace object escapes, so it cannot be statically tracked.
export const getEnums = () => ns
import {
a,
b,
foo,
reallyLongExportName,
anotherVeryLongExportName,
shortFn,
thisIsAVeryLongFunctionName,
exportsInfo,
} from './named-exports'
it('should keep the values of mangled exports correct', () => {
expect(a).toBe('short-a')
expect(b).toBe('short-b')
expect(foo).toBe('short-foo')
expect(reallyLongExportName).toBe('long-name-1')
expect(anotherVeryLongExportName).toBe('long-name-2')
expect(shortFn()).toBe('short-fn')
expect(thisIsAVeryLongFunctionName()).toBe('long-fn')
})
it('should actually mangle the exported names', () => {
// `__webpack_exports_info__` is keyed by the original names and reports the key the export is
// emitted under, which is how a running test can observe that mangling happened at all.
expect(exportsInfo.reallyLongExportName.canMangle).toBe(true)
expect(exportsInfo.reallyLongExportName.mangledName).toEqual(
expect.any(String)
)
expect(
exportsInfo.reallyLongExportName.mangledName.length
).toBeLessThanOrEqual(2)
expect(exportsInfo.thisIsAVeryLongFunctionName.mangledName).not.toBe(
'thisIsAVeryLongFunctionName'
)
// Distinct exports never share a key.
expect(exportsInfo.reallyLongExportName.mangledName).not.toBe(
exportsInfo.thisIsAVeryLongFunctionName.mangledName
)
})
it('should keep a name that is already short', () => {
// `a` is already a valid one-character identifier, so it reserves that bucket and keeps itself
// instead of being renamed.
expect(exportsInfo.a.mangledName).toBe('a')
})
// Every export here is imported by name, so the keys this module emits are only ever read by
// generated code and can be shortened.
export const a = 'short-a'
export const b = 'short-b'
export const foo = 'short-foo'
export const reallyLongExportName = 'long-name-1'
export const anotherVeryLongExportName = 'long-name-2'
export function shortFn() {
return 'short-fn'
}
export function thisIsAVeryLongFunctionName() {
return 'long-fn'
}
export const exportsInfo = {
a: __webpack_exports_info__.a,
reallyLongExportName: __webpack_exports_info__.reallyLongExportName,
thisIsAVeryLongFunctionName:
__webpack_exports_info__.thisIsAVeryLongFunctionName,
}
{
"mangleExportNames": true,
"minify": true,
"scopeHoisting": false
}
const esm = require('./esm')
exports.readNamed = () => esm.someLongExportName
exports.readOther = () => esm.anotherLongExportName
exports.exportsInfo = esm.exportsInfo
exports.keys = () => Object.keys(esm)
// Imported by a CommonJS module through `require()`. The property accesses on the required object
// live in user source and are not rewritten, so this module must keep its original names.
export const someLongExportName = 'esm-1'
export const anotherLongExportName = 'esm-2'
export const exportsInfo = {
someLongExportName: __webpack_exports_info__.someLongExportName,
}
import { readNamed, readOther, exportsInfo, keys } from './cjs-consumer'
import { someLongExportName } from './esm'
it('should keep a CommonJS consumer of an ESM module working', () => {
expect(readNamed()).toBe('esm-1')
expect(readOther()).toBe('esm-2')
// The ESM import of the same module resolves to the same binding.
expect(someLongExportName).toBe('esm-1')
})
it('should not mangle a module that a CommonJS module requires', () => {
// The `esm.someLongExportName` accesses in `cjs-consumer.js` are user source, so the names have
// to stay as written.
expect(exportsInfo.someLongExportName.canMangle).toBe(false)
expect(keys()).toContain('someLongExportName')
})
{
"mangleExportNames": true,
"minify": true,
"scopeHoisting": false,
"cjsTreeShaking": true
}
// `__esModule` is how a CommonJS module signals interop *to* ESM; the runtime defines it on the
// exports object itself. An ESM module that happens to export that name is just an ordinary export,
// so its key is mangled like any other — and the runtime's own `__esModule` is untouched.
export const __esModule = 'a-normal-export'
export const someLongExportName = 'named-value'
export const exportsInfo = {
__esModule: __webpack_exports_info__.__esModule,
}
import theDefault, { someLongExportName, exportsInfo } from './lib'
import throughReexport, { renamedDefault } from './reexport'
import {
__esModule as esModuleExport,
exportsInfo as esModuleExportsInfo,
} from './es-module-name'
it('should keep the default export working when it is mangled', () => {
expect(theDefault()).toBe('default-value')
expect(someLongExportName).toBe('named-value')
})
it('should mangle the default export key', () => {
expect(exportsInfo.default.canMangle).toBe(true)
expect(exportsInfo.default.mangledName).not.toBe('default')
expect(exportsInfo.default.mangledName.length).toBeLessThanOrEqual(2)
// `default` shares the table with the other exports, so it never collides with them.
expect(exportsInfo.default.mangledName).not.toBe(
exportsInfo.someLongExportName.mangledName
)
})
it('should carry a mangled default through a re-export', () => {
expect(throughReexport()).toBe('default-value')
expect(renamedDefault()).toBe('default-value')
})
it('should mangle an export literally named __esModule', () => {
// The name is only an interop marker when a CommonJS module sets it; as an ESM export name it
// carries no meaning, so its key is shortened like any other.
expect(esModuleExport).toBe('a-normal-export')
expect(esModuleExportsInfo.__esModule.canMangle).toBe(true)
expect(esModuleExportsInfo.__esModule.mangledName).not.toBe('__esModule')
})
// `default` is mangled like any other export key: every read of it in an eligible module is
// generated by us. Modules whose names can be observed (CommonJS interop, an escaping namespace,
// a dynamic import) keep `default` along with everything else — see the other `mangle-*` fixtures.
export default function theDefaultExport() {
return 'default-value'
}
export const someLongExportName = 'named-value'
export const exportsInfo = {
default: __webpack_exports_info__.default,
someLongExportName: __webpack_exports_info__.someLongExportName,
}
// A default export travelling through a re-export, in both spellings.
export { default } from './lib'
export { default as renamedDefault } from './lib'
{
"mangleExportNames": true,
"minify": true,
"scopeHoisting": false
}
import * as mod from './module'
it('should keep values correct when destructuring the namespace', () => {
const { aVeryLongExportName, anotherVeryLongExportName } = mod
expect(aVeryLongExportName).toBe('a-value')
expect(anotherVeryLongExportName).toBe('b-value')
})
it('should keep values correct when destructuring a namespace property', () => {
const { a, b } = mod.objectValuedExportName
expect(a).toBe('a')
expect(b).toBe('b')
})
it('should keep values correct with member access on the namespace', () => {
expect(mod.aVeryLongExportName).toBe('a-value')
})
it('should handle `default` when destructuring a namespace', () => {
const { default: value } = mod
expect(value).toBe('default-value')
})
it('should back off for a module read through a namespace binding', () => {
// Reads through an `import * as ns` binding are reported as a *partial namespace object*: we
// know which names are used, but not whether every read was lowered to a direct named access,
// and a read that wasn't (a destructuring pattern, say) still uses the original name. So the
// module keeps its names. Distinguishing lowered reads from a materialized namespace object is
// a follow-up; it would unlock mangling for namespace-imported modules too.
expect(mod.exportsInfo.aVeryLongExportName.canMangle).toBe(false)
expect(mod.exportsInfo.aVeryLongExportName.mangledName).toBe(null)
})
export const aVeryLongExportName = 'a-value'
export const anotherVeryLongExportName = 'b-value'
export const objectValuedExportName = { a: 'a', b: 'b' }
export default 'default-value'
export const exportsInfo = {
aVeryLongExportName: __webpack_exports_info__.aVeryLongExportName,
objectValuedExportName: __webpack_exports_info__.objectValuedExportName,
}
{
"mangleExportNames": true,
"minify": true,
"scopeHoisting": false
}
// A CommonJS module whose exports can't be determined statically, so a re-export of it has to be
// resolved at runtime by property access on the original names.
const key = 'dynamicallyNamedExport'
exports[key] = 'dynamic-value'
exports.staticallyNamedExport = 'static-value'
import { ownLongExportName, staticallyNamedExport } from './reexport'
import * as ns from './reexport'
it('should keep a re-export of dynamic exports working', () => {
expect(ownLongExportName).toBe('own-value')
expect(staticallyNamedExport).toBe('static-value')
})
it('should expose the original names of a module with dynamic re-exports', () => {
// The star re-export is resolved at runtime by property access on the original names, so the
// names this module exposes must be the ones written in the source.
expect(ns.ownLongExportName).toBe('own-value')
expect(ns.staticallyNamedExport).toBe('static-value')
expect(ns.dynamicallyNamedExport).toBe('dynamic-value')
expect(Object.keys(ns)).toContain('ownLongExportName')
})
// `export *` from a module with dynamic exports: the re-exported names are only known at runtime,
// so this module keeps its original export names.
export * from './dynamic-cjs'
export const ownLongExportName = 'own-value'
warning - [analysis] /turbopack/crates/turbopack-tests/tests/execution/turbopack/exports/mangle-dynamic-exports/input/dynamic-cjs.js unexpected export *
export * used with module [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/exports/mangle-dynamic-exports/input/dynamic-cjs.js [test] (ecmascript) which is a CommonJS module with exports only available at runtime
List all export names manually (`export { a, b, c } from "...") or rewrite the module to ESM, to avoid the additional runtime code.`
Import trace:
test:
./turbopack/crates/turbopack-tests/tests/execution/turbopack/exports/mangle-dynamic-exports/input/dynamic-cjs.js
./turbopack/crates/turbopack-tests/tests/execution/turbopack/exports/mangle-dynamic-exports/input/index.js
\ No newline at end of file
import * as ns from './cjs'
// A CommonJS namespace escaping through the interop layer. CommonJS exports are never mangled,
// and the interop object must keep working unchanged.
export const getCjs = () => ns
import * as ns from './enums'
// A statically tracked read of the same module whose namespace escapes elsewhere. It has to keep
// working, and it has to read the same (original) name the escaping namespace exposes.
export function read() {
const { ENUM_B } = ns
return ENUM_B
}
// A namespace object of this module escapes into user code (see `provider.js`), so its export
// names are observable and must not be shortened.
export const ENUM_A = 'a-value'
export const ENUM_B = 'b-value'
export const ENUM_C = 'c-value'
export const NUM = 42
export default 'default-value'
import { getEnums } from './provider'
import { enumsNs } from './reexport'
import { getCjs } from './cjs-provider'
import { read } from './destr'
import {
someLongExportName,
anotherLongExportName,
exportsInfo,
} from './mangleable'
it('should keep an escaped namespace object readable by its original names', () => {
const ns = getEnums()
expect(ns.ENUM_A).toBe('a-value')
expect(ns.ENUM_B).toBe('b-value')
expect(ns.ENUM_C).toBe('c-value')
expect(ns.NUM).toBe(42)
expect(ns.default).toBe('default-value')
})
it('should expose the original names when enumerating an escaped namespace', () => {
const keys = Object.keys(getEnums()).sort()
expect(keys).toEqual(['ENUM_A', 'ENUM_B', 'ENUM_C', 'NUM', 'default'])
})
it('should keep an escaped re-exported (export * as) namespace working', () => {
const get = () => enumsNs
const ns = get()
expect(ns.ENUM_A).toBe('a-value')
expect(ns.default).toBe('default-value')
})
it('should keep destructuring working for a module that also escapes', () => {
expect(read()).toBe('b-value')
})
it('should keep `delete ns.member` valid when the namespace escapes', () => {
// Deleting a member that does not exist returns true per spec, and must not be emitted as a
// bare `delete undefined`, which is a SyntaxError in strict mode.
const ns = getEnums()
expect(delete ns.doesNotExist).toBe(true)
expect(ns.ENUM_A).toBe('a-value')
})
it('should keep an escaped CommonJS namespace interop correct', () => {
const ns = getCjs()
expect(ns.CJS_A).toBe('cjs-a')
expect(ns.CJS_B).toBe('cjs-b')
})
it('should still mangle a sibling module that does not escape', () => {
expect(someLongExportName).toBe('mangled-1')
expect(anotherLongExportName).toBe('mangled-2')
expect(exportsInfo.someLongExportName.canMangle).toBe(true)
expect(exportsInfo.someLongExportName.mangledName).not.toBe(
'someLongExportName'
)
})
// Nothing escapes here: every export is read by name, so this module *is* mangled even though
// another module in the same graph had to back off. Back-off is per module.
export const someLongExportName = 'mangled-1'
export const anotherLongExportName = 'mangled-2'
export const exportsInfo = {
someLongExportName: __webpack_exports_info__.someLongExportName,
anotherLongExportName: __webpack_exports_info__.anotherLongExportName,
}
import * as ns from './enums'
// The whole namespace object escapes through a function return, so no static analysis can tell
// which names the caller will read.
export const getEnums = () => ns
// A re-exported namespace object that later escapes.
export * as enumsNs from './enums'
import {
someLongExportName,
anotherLongExportName,
aLongFunctionName,
} from './shared'
it('should be correct with scope hoisting enabled', () => {
expect(someLongExportName).toBe('shared-1')
expect(anotherLongExportName).toBe('shared-2')
expect(aLongFunctionName()).toBe('shared-fn')
})
it('should be correct across a chunk boundary with scope hoisting enabled', async () => {
// `lazy.js` lives in another chunk and reads the same module, so the binding has to be resolved
// through the emitted export object rather than a merged local.
const { fromLazy } = await import(
/* turbopackExports: ["fromLazy"] */ './lazy'
)
expect(fromLazy()).toBe('shared-1/shared-fn')
})
import { someLongExportName, aLongFunctionName } from './shared'
export const fromLazy = () => `${someLongExportName}/${aLongFunctionName()}`
// Statically imported by `index.js` and dynamically by `lazy.js`, so it is exposed across a chunk
// boundary and its export object is really emitted even with scope hoisting on.
export const someLongExportName = 'shared-1'
export const anotherLongExportName = 'shared-2'
export function aLongFunctionName() {
return 'shared-fn'
}
{
"mangleExportNames": true,
"minify": true,
"scopeHoisting": true
}
it('should keep the names of a module imported with webpackExports', async () => {
const { usedName, exportsInfo } = await import(
/* webpackExports: ["usedName", "exportsInfo"] */ './lazy'
)
expect(usedName).toBe('used')
// The magic comment narrows which exports are *used*, but the namespace object still exposes
// them under their original names, so the module has to back off.
expect(exportsInfo.usedName.canMangle).toBe(false)
expect(exportsInfo.usedName.mangledName).toBe(null)
})
it('should keep the names of a module imported with turbopackExports', async () => {
const ns = await import(
/* turbopackExports: ["otherUsedName", "exportsInfo"] */ './lazy'
)
expect(ns.otherUsedName).toBe('other-used')
expect(ns.exportsInfo.otherUsedName.canMangle).toBe(false)
})
it('should keep a plain dynamic import working', async () => {
const ns = await import('./lazy')
expect(ns.usedName).toBe('used')
expect(Object.keys(ns)).toContain('usedName')
})
// Reached only through `import()`. Even with a `webpackExports` / `turbopackExports` comment
// telling us which exports are used, the namespace object that `import()` resolves to is handed
// to user code and destructured by the *original* names, so this module must not be mangled.
export const usedName = 'used'
export const otherUsedName = 'other-used'
export const unusedName = 'unused'
export const exportsInfo = {
usedName: __webpack_exports_info__.usedName,
otherUsedName: __webpack_exports_info__.otherUsedName,
}
{
"mangleExportNames": true,
"minify": true,
"scopeHoisting": false
}
import {
exportNumber00,
exportNumber01,
exportNumber02,
exportNumber03,
exportNumber04,
exportNumber05,
exportNumber06,
exportNumber07,
exportNumber08,
exportNumber09,
exportNumber10,
exportNumber11,
exportNumber12,
exportNumber13,
exportNumber14,
exportNumber15,
exportNumber16,
exportNumber17,
exportNumber18,
exportNumber19,
exportNumber20,
exportNumber21,
exportNumber22,
exportNumber23,
exportNumber24,
exportNumber25,
exportNumber26,
exportNumber27,
exportNumber28,
exportNumber29,
exportNumber30,
exportNumber31,
exportNumber32,
exportNumber33,
exportNumber34,
exportNumber35,
exportNumber36,
exportNumber37,
exportNumber38,
exportNumber39,
exportNumber40,
exportNumber41,
exportNumber42,
exportNumber43,
exportNumber44,
exportNumber45,
exportNumber46,
exportNumber47,
exportNumber48,
exportNumber49,
exportNumber50,
exportNumber51,
exportNumber52,
exportNumber53,
exportNumber54,
exportNumber55,
exportNumber56,
exportNumber57,
exportNumber58,
exportNumber59,
exportsInfo,
} from './many-named'
export const values = () => [
exportNumber00,
exportNumber01,
exportNumber02,
exportNumber03,
exportNumber04,
exportNumber05,
exportNumber06,
exportNumber07,
exportNumber08,
exportNumber09,
exportNumber10,
exportNumber11,
exportNumber12,
exportNumber13,
exportNumber14,
exportNumber15,
exportNumber16,
exportNumber17,
exportNumber18,
exportNumber19,
exportNumber20,
exportNumber21,
exportNumber22,
exportNumber23,
exportNumber24,
exportNumber25,
exportNumber26,
exportNumber27,
exportNumber28,
exportNumber29,
exportNumber30,
exportNumber31,
exportNumber32,
exportNumber33,
exportNumber34,
exportNumber35,
exportNumber36,
exportNumber37,
exportNumber38,
exportNumber39,
exportNumber40,
exportNumber41,
exportNumber42,
exportNumber43,
exportNumber44,
exportNumber45,
exportNumber46,
exportNumber47,
exportNumber48,
exportNumber49,
exportNumber50,
exportNumber51,
exportNumber52,
exportNumber53,
exportNumber54,
exportNumber55,
exportNumber56,
exportNumber57,
exportNumber58,
exportNumber59,
]
export { exportsInfo }
// Not part of the test: regenerates the two 60-export modules and the consumer that imports each
// of them by name. Run from this directory:
// node generate.mjs
import { writeFileSync } from 'node:fs'
const count = 60
const names = Array.from(
{ length: count },
(_, i) => `exportNumber${String(i).padStart(2, '0')}`
)
const moduleSource = (withInfo) =>
[
...names.map((name, i) => {
const n = String(i).padStart(2, '0')
return `export const ${name} = 'value-${n}'`
}),
'',
'export const exportsInfo = {',
...names.map((name) => ` ${name}: __webpack_exports_info__.${name},`),
'}',
'',
].join('\n')
// Read through a namespace binding with a computed key, so this one has to keep its names.
writeFileSync('many.js', moduleSource())
// Imported entirely by name, so this one is mangled with a two-character table.
writeFileSync('many-named.js', moduleSource())
writeFileSync(
'consume.js',
[
'import {',
...names.map((name) => ` ${name},`),
' exportsInfo,',
"} from './many-named'",
'',
'export const values = () => [',
...names.map((name) => ` ${name},`),
']',
'',
'export { exportsInfo }',
'',
].join('\n')
)
import * as manyAsNamespace from './many'
import { values, exportsInfo as namedExportsInfo } from './consume'
// 60 used exports don't fit the 54 single-character identifiers, so the table grows to two
// characters.
it('should mangle a 60-export module into a two-character table', () => {
const entries = Object.entries(namedExportsInfo)
expect(entries.length).toBe(60)
for (const [name, info] of entries) {
expect(info.canMangle).toBe(true)
expect(info.mangledName).not.toBe(name)
expect(info.mangledName.length).toBeLessThanOrEqual(2)
}
// Every name gets a distinct key.
const keys = entries.map(([, info]) => info.mangledName)
expect(new Set(keys).size).toBe(60)
// Some names still fit in one character: the table is only as long as it has to be, and open
// addressing never pushes a name past the chosen length.
expect(keys.some((key) => key.length === 1)).toBe(true)
})
it('should keep all 60 values correct through the mangled keys', () => {
const expected = Array.from(
{ length: 60 },
(_, i) => `value-${String(i).padStart(2, '0')}`
)
expect(values()).toEqual(expected)
})
it('should keep the names of a module read with a computed key', () => {
for (let i = 0; i < 60; i++) {
const n = String(i).padStart(2, '0')
expect(manyAsNamespace[`exportNumber${n}`]).toBe(`value-${n}`)
}
expect(manyAsNamespace.exportsInfo.exportNumber00.canMangle).toBe(false)
})
export const exportNumber00 = 'value-00'
export const exportNumber01 = 'value-01'
export const exportNumber02 = 'value-02'
export const exportNumber03 = 'value-03'
export const exportNumber04 = 'value-04'
export const exportNumber05 = 'value-05'
export const exportNumber06 = 'value-06'
export const exportNumber07 = 'value-07'
export const exportNumber08 = 'value-08'
export const exportNumber09 = 'value-09'
export const exportNumber10 = 'value-10'
export const exportNumber11 = 'value-11'
export const exportNumber12 = 'value-12'
export const exportNumber13 = 'value-13'
export const exportNumber14 = 'value-14'
export const exportNumber15 = 'value-15'
export const exportNumber16 = 'value-16'
export const exportNumber17 = 'value-17'
export const exportNumber18 = 'value-18'
export const exportNumber19 = 'value-19'
export const exportNumber20 = 'value-20'
export const exportNumber21 = 'value-21'
export const exportNumber22 = 'value-22'
export const exportNumber23 = 'value-23'
export const exportNumber24 = 'value-24'
export const exportNumber25 = 'value-25'
export const exportNumber26 = 'value-26'
export const exportNumber27 = 'value-27'
export const exportNumber28 = 'value-28'
export const exportNumber29 = 'value-29'
export const exportNumber30 = 'value-30'
export const exportNumber31 = 'value-31'
export const exportNumber32 = 'value-32'
export const exportNumber33 = 'value-33'
export const exportNumber34 = 'value-34'
export const exportNumber35 = 'value-35'
export const exportNumber36 = 'value-36'
export const exportNumber37 = 'value-37'
export const exportNumber38 = 'value-38'
export const exportNumber39 = 'value-39'
export const exportNumber40 = 'value-40'
export const exportNumber41 = 'value-41'
export const exportNumber42 = 'value-42'
export const exportNumber43 = 'value-43'
export const exportNumber44 = 'value-44'
export const exportNumber45 = 'value-45'
export const exportNumber46 = 'value-46'
export const exportNumber47 = 'value-47'
export const exportNumber48 = 'value-48'
export const exportNumber49 = 'value-49'
export const exportNumber50 = 'value-50'
export const exportNumber51 = 'value-51'
export const exportNumber52 = 'value-52'
export const exportNumber53 = 'value-53'
export const exportNumber54 = 'value-54'
export const exportNumber55 = 'value-55'
export const exportNumber56 = 'value-56'
export const exportNumber57 = 'value-57'
export const exportNumber58 = 'value-58'
export const exportNumber59 = 'value-59'
export const exportsInfo = {
exportNumber00: __webpack_exports_info__.exportNumber00,
exportNumber01: __webpack_exports_info__.exportNumber01,
exportNumber02: __webpack_exports_info__.exportNumber02,
exportNumber03: __webpack_exports_info__.exportNumber03,
exportNumber04: __webpack_exports_info__.exportNumber04,
exportNumber05: __webpack_exports_info__.exportNumber05,
exportNumber06: __webpack_exports_info__.exportNumber06,
exportNumber07: __webpack_exports_info__.exportNumber07,
exportNumber08: __webpack_exports_info__.exportNumber08,
exportNumber09: __webpack_exports_info__.exportNumber09,
exportNumber10: __webpack_exports_info__.exportNumber10,
exportNumber11: __webpack_exports_info__.exportNumber11,
exportNumber12: __webpack_exports_info__.exportNumber12,
exportNumber13: __webpack_exports_info__.exportNumber13,
exportNumber14: __webpack_exports_info__.exportNumber14,
exportNumber15: __webpack_exports_info__.exportNumber15,
exportNumber16: __webpack_exports_info__.exportNumber16,
exportNumber17: __webpack_exports_info__.exportNumber17,
exportNumber18: __webpack_exports_info__.exportNumber18,
exportNumber19: __webpack_exports_info__.exportNumber19,
exportNumber20: __webpack_exports_info__.exportNumber20,
exportNumber21: __webpack_exports_info__.exportNumber21,
exportNumber22: __webpack_exports_info__.exportNumber22,
exportNumber23: __webpack_exports_info__.exportNumber23,
exportNumber24: __webpack_exports_info__.exportNumber24,
exportNumber25: __webpack_exports_info__.exportNumber25,
exportNumber26: __webpack_exports_info__.exportNumber26,
exportNumber27: __webpack_exports_info__.exportNumber27,
exportNumber28: __webpack_exports_info__.exportNumber28,
exportNumber29: __webpack_exports_info__.exportNumber29,
exportNumber30: __webpack_exports_info__.exportNumber30,
exportNumber31: __webpack_exports_info__.exportNumber31,
exportNumber32: __webpack_exports_info__.exportNumber32,
exportNumber33: __webpack_exports_info__.exportNumber33,
exportNumber34: __webpack_exports_info__.exportNumber34,
exportNumber35: __webpack_exports_info__.exportNumber35,
exportNumber36: __webpack_exports_info__.exportNumber36,
exportNumber37: __webpack_exports_info__.exportNumber37,
exportNumber38: __webpack_exports_info__.exportNumber38,
exportNumber39: __webpack_exports_info__.exportNumber39,
exportNumber40: __webpack_exports_info__.exportNumber40,
exportNumber41: __webpack_exports_info__.exportNumber41,
exportNumber42: __webpack_exports_info__.exportNumber42,
exportNumber43: __webpack_exports_info__.exportNumber43,
exportNumber44: __webpack_exports_info__.exportNumber44,
exportNumber45: __webpack_exports_info__.exportNumber45,
exportNumber46: __webpack_exports_info__.exportNumber46,
exportNumber47: __webpack_exports_info__.exportNumber47,
exportNumber48: __webpack_exports_info__.exportNumber48,
exportNumber49: __webpack_exports_info__.exportNumber49,
exportNumber50: __webpack_exports_info__.exportNumber50,
exportNumber51: __webpack_exports_info__.exportNumber51,
exportNumber52: __webpack_exports_info__.exportNumber52,
exportNumber53: __webpack_exports_info__.exportNumber53,
exportNumber54: __webpack_exports_info__.exportNumber54,
exportNumber55: __webpack_exports_info__.exportNumber55,
exportNumber56: __webpack_exports_info__.exportNumber56,
exportNumber57: __webpack_exports_info__.exportNumber57,
exportNumber58: __webpack_exports_info__.exportNumber58,
exportNumber59: __webpack_exports_info__.exportNumber59,
}
export const exportNumber00 = 'value-00'
export const exportNumber01 = 'value-01'
export const exportNumber02 = 'value-02'
export const exportNumber03 = 'value-03'
export const exportNumber04 = 'value-04'
export const exportNumber05 = 'value-05'
export const exportNumber06 = 'value-06'
export const exportNumber07 = 'value-07'
export const exportNumber08 = 'value-08'
export const exportNumber09 = 'value-09'
export const exportNumber10 = 'value-10'
export const exportNumber11 = 'value-11'
export const exportNumber12 = 'value-12'
export const exportNumber13 = 'value-13'
export const exportNumber14 = 'value-14'
export const exportNumber15 = 'value-15'
export const exportNumber16 = 'value-16'
export const exportNumber17 = 'value-17'
export const exportNumber18 = 'value-18'
export const exportNumber19 = 'value-19'
export const exportNumber20 = 'value-20'
export const exportNumber21 = 'value-21'
export const exportNumber22 = 'value-22'
export const exportNumber23 = 'value-23'
export const exportNumber24 = 'value-24'
export const exportNumber25 = 'value-25'
export const exportNumber26 = 'value-26'
export const exportNumber27 = 'value-27'
export const exportNumber28 = 'value-28'
export const exportNumber29 = 'value-29'
export const exportNumber30 = 'value-30'
export const exportNumber31 = 'value-31'
export const exportNumber32 = 'value-32'
export const exportNumber33 = 'value-33'
export const exportNumber34 = 'value-34'
export const exportNumber35 = 'value-35'
export const exportNumber36 = 'value-36'
export const exportNumber37 = 'value-37'
export const exportNumber38 = 'value-38'
export const exportNumber39 = 'value-39'
export const exportNumber40 = 'value-40'
export const exportNumber41 = 'value-41'
export const exportNumber42 = 'value-42'
export const exportNumber43 = 'value-43'
export const exportNumber44 = 'value-44'
export const exportNumber45 = 'value-45'
export const exportNumber46 = 'value-46'
export const exportNumber47 = 'value-47'
export const exportNumber48 = 'value-48'
export const exportNumber49 = 'value-49'
export const exportNumber50 = 'value-50'
export const exportNumber51 = 'value-51'
export const exportNumber52 = 'value-52'
export const exportNumber53 = 'value-53'
export const exportNumber54 = 'value-54'
export const exportNumber55 = 'value-55'
export const exportNumber56 = 'value-56'
export const exportNumber57 = 'value-57'
export const exportNumber58 = 'value-58'
export const exportNumber59 = 'value-59'
export const exportsInfo = {
exportNumber00: __webpack_exports_info__.exportNumber00,
exportNumber01: __webpack_exports_info__.exportNumber01,
exportNumber02: __webpack_exports_info__.exportNumber02,
exportNumber03: __webpack_exports_info__.exportNumber03,
exportNumber04: __webpack_exports_info__.exportNumber04,
exportNumber05: __webpack_exports_info__.exportNumber05,
exportNumber06: __webpack_exports_info__.exportNumber06,
exportNumber07: __webpack_exports_info__.exportNumber07,
exportNumber08: __webpack_exports_info__.exportNumber08,
exportNumber09: __webpack_exports_info__.exportNumber09,
exportNumber10: __webpack_exports_info__.exportNumber10,
exportNumber11: __webpack_exports_info__.exportNumber11,
exportNumber12: __webpack_exports_info__.exportNumber12,
exportNumber13: __webpack_exports_info__.exportNumber13,
exportNumber14: __webpack_exports_info__.exportNumber14,
exportNumber15: __webpack_exports_info__.exportNumber15,
exportNumber16: __webpack_exports_info__.exportNumber16,
exportNumber17: __webpack_exports_info__.exportNumber17,
exportNumber18: __webpack_exports_info__.exportNumber18,
exportNumber19: __webpack_exports_info__.exportNumber19,
exportNumber20: __webpack_exports_info__.exportNumber20,
exportNumber21: __webpack_exports_info__.exportNumber21,
exportNumber22: __webpack_exports_info__.exportNumber22,
exportNumber23: __webpack_exports_info__.exportNumber23,
exportNumber24: __webpack_exports_info__.exportNumber24,
exportNumber25: __webpack_exports_info__.exportNumber25,
exportNumber26: __webpack_exports_info__.exportNumber26,
exportNumber27: __webpack_exports_info__.exportNumber27,
exportNumber28: __webpack_exports_info__.exportNumber28,
exportNumber29: __webpack_exports_info__.exportNumber29,
exportNumber30: __webpack_exports_info__.exportNumber30,
exportNumber31: __webpack_exports_info__.exportNumber31,
exportNumber32: __webpack_exports_info__.exportNumber32,
exportNumber33: __webpack_exports_info__.exportNumber33,
exportNumber34: __webpack_exports_info__.exportNumber34,
exportNumber35: __webpack_exports_info__.exportNumber35,
exportNumber36: __webpack_exports_info__.exportNumber36,
exportNumber37: __webpack_exports_info__.exportNumber37,
exportNumber38: __webpack_exports_info__.exportNumber38,
exportNumber39: __webpack_exports_info__.exportNumber39,
exportNumber40: __webpack_exports_info__.exportNumber40,
exportNumber41: __webpack_exports_info__.exportNumber41,
exportNumber42: __webpack_exports_info__.exportNumber42,
exportNumber43: __webpack_exports_info__.exportNumber43,
exportNumber44: __webpack_exports_info__.exportNumber44,
exportNumber45: __webpack_exports_info__.exportNumber45,
exportNumber46: __webpack_exports_info__.exportNumber46,
exportNumber47: __webpack_exports_info__.exportNumber47,
exportNumber48: __webpack_exports_info__.exportNumber48,
exportNumber49: __webpack_exports_info__.exportNumber49,
exportNumber50: __webpack_exports_info__.exportNumber50,
exportNumber51: __webpack_exports_info__.exportNumber51,
exportNumber52: __webpack_exports_info__.exportNumber52,
exportNumber53: __webpack_exports_info__.exportNumber53,
exportNumber54: __webpack_exports_info__.exportNumber54,
exportNumber55: __webpack_exports_info__.exportNumber55,
exportNumber56: __webpack_exports_info__.exportNumber56,
exportNumber57: __webpack_exports_info__.exportNumber57,
exportNumber58: __webpack_exports_info__.exportNumber58,
exportNumber59: __webpack_exports_info__.exportNumber59,
}
{
"mangleExportNames": true,
"minify": true,
"scopeHoisting": true
}
// `mangleExportNames` is on, but minification is off. Mangling and minification are independent
// options — this fixture proves that mangling still happens without minification, the same way it
// would with it (see `mangle-basic`).
import {
a,
b,
foo,
reallyLongExportName,
anotherVeryLongExportName,
shortFn,
thisIsAVeryLongFunctionName,
exportsInfo,
} from './named-exports'
it('should keep the values correct with minification disabled', () => {
expect(a).toBe('short-a')
expect(b).toBe('short-b')
expect(foo).toBe('short-foo')
expect(reallyLongExportName).toBe('long-name-1')
expect(anotherVeryLongExportName).toBe('long-name-2')
expect(shortFn()).toBe('short-fn')
expect(thisIsAVeryLongFunctionName()).toBe('long-fn')
})
it('should still mangle the exported names with minification disabled', () => {
expect(exportsInfo.reallyLongExportName.canMangle).toBe(true)
expect(exportsInfo.reallyLongExportName.mangledName).toEqual(
expect.any(String)
)
expect(
exportsInfo.reallyLongExportName.mangledName.length
).toBeLessThanOrEqual(2)
expect(exportsInfo.thisIsAVeryLongFunctionName.mangledName).not.toBe(
'thisIsAVeryLongFunctionName'
)
})
// Every export here is imported by name, so the keys this module emits are only ever read by
// generated code and can be shortened.
export const a = 'short-a'
export const b = 'short-b'
export const foo = 'short-foo'
export const reallyLongExportName = 'long-name-1'
export const anotherVeryLongExportName = 'long-name-2'
export function shortFn() {
return 'short-fn'
}
export function thisIsAVeryLongFunctionName() {
return 'long-fn'
}
export const exportsInfo = {
a: __webpack_exports_info__.a,
reallyLongExportName: __webpack_exports_info__.reallyLongExportName,
thisIsAVeryLongFunctionName:
__webpack_exports_info__.thisIsAVeryLongFunctionName,
}
{
"mangleExportNames": true,
"minify": false,
"scopeHoisting": false
}
import {
toString,
valueOf,
constructor,
__proto__,
a,
$1,
__1,
aVeryLongExportNameIndeed,
exportsInfo,
} from './lib'
it('should mangle exports whose names shadow Object.prototype members', () => {
expect(toString).toBe('toString-value')
expect(valueOf).toBe('valueOf-value')
expect(constructor).toBe('constructor-value')
expect(__proto__).toBe('proto-value')
expect(aVeryLongExportNameIndeed).toBe('long')
})
it('should keep short names and mangle the rest', () => {
expect(a).toBe('single char')
expect($1).toBe('double char')
expect(__1).toBe('3 chars')
// `a` and `$` are single valid identifiers in the table's alphabet, so they keep themselves.
expect(exportsInfo.a.mangledName).toBe('a')
// `$1` and `__1` are longer than the table's identifier length, so they get hashed like any
// other name — including `__1`, which is not even representable in the encoding (trailing
// "zero" characters are rejected as degenerate).
expect(exportsInfo.$1.mangledName).not.toBe('$1')
expect(exportsInfo.__1.mangledName).not.toBe('__1')
})
it('should give every export a distinct key', () => {
const keys = Object.values(exportsInfo).map((e) => e.mangledName)
expect(new Set(keys).size).toBe(keys.length)
})
// Export names that are awkward for a mangling table: names that collide with
// `Object.prototype` members, and names that are already short enough to be kept.
export const toString = 'toString-value'
export const valueOf = 'valueOf-value'
export const constructor = 'constructor-value'
export const __proto__ = 'proto-value'
export const a = 'single char'
export const $1 = 'double char'
export const __1 = '3 chars'
export const aVeryLongExportNameIndeed = 'long'
export const exportsInfo = {
toString: __webpack_exports_info__.toString,
valueOf: __webpack_exports_info__.valueOf,
a: __webpack_exports_info__.a,
$1: __webpack_exports_info__.$1,
__1: __webpack_exports_info__.__1,
aVeryLongExportNameIndeed: __webpack_exports_info__.aVeryLongExportNameIndeed,
}
{
"mangleExportNames": true,
"minify": true,
"scopeHoisting": false
}
// The control for `mangle-basic`: identical input, `mangleExportNames` off. Same observable
// behaviour, and no export key is renamed.
import {
a,
b,
foo,
reallyLongExportName,
anotherVeryLongExportName,
shortFn,
thisIsAVeryLongFunctionName,
exportsInfo,
} from './named-exports'
it('should keep the values correct with mangling disabled', () => {
expect(a).toBe('short-a')
expect(b).toBe('short-b')
expect(foo).toBe('short-foo')
expect(reallyLongExportName).toBe('long-name-1')
expect(anotherVeryLongExportName).toBe('long-name-2')
expect(shortFn()).toBe('short-fn')
expect(thisIsAVeryLongFunctionName()).toBe('long-fn')
})
it('should report canMangle: false and mangledName: null when disabled', () => {
// With the option off, `canMangle`/`mangledName` are still present (the shape of
// `__webpack_exports_info__` no longer depends on whether mangling is enabled at all), but
// report that nothing was mangled: `canMangle` is always false, and `mangledName` is only ever
// a string when `canMangle` is true, so it's `null` here.
expect(exportsInfo.a.used).toBe(true)
expect(exportsInfo.a.canMangle).toBe(false)
expect(exportsInfo.a.mangledName).toBe(null)
expect(exportsInfo.reallyLongExportName.canMangle).toBe(false)
expect(exportsInfo.reallyLongExportName.mangledName).toBe(null)
})
// Every export here is imported by name, so the keys this module emits are only ever read by
// generated code and can be shortened.
export const a = 'short-a'
export const b = 'short-b'
export const foo = 'short-foo'
export const reallyLongExportName = 'long-name-1'
export const anotherVeryLongExportName = 'long-name-2'
export function shortFn() {
return 'short-fn'
}
export function thisIsAVeryLongFunctionName() {
return 'long-fn'
}
export const exportsInfo = {
a: __webpack_exports_info__.a,
reallyLongExportName: __webpack_exports_info__.reallyLongExportName,
thisIsAVeryLongFunctionName:
__webpack_exports_info__.thisIsAVeryLongFunctionName,
}
{
"mangleExportNames": false,
"minify": true,
"scopeHoisting": false
}
export const veryLongOriginalExportName = 'from-a'
export function anotherLongFunctionName() {
return 'func-a'
}
export default function () {
return 'default-from-a'
}
export const exportsInfo = {
veryLongOriginalExportName:
__webpack_exports_info__.veryLongOriginalExportName,
anotherLongFunctionName: __webpack_exports_info__.anotherLongFunctionName,
}
export {
veryLongOriginalExportName as renamedInMiddleLayer,
anotherLongFunctionName as middleLayerFunction,
exportsInfo,
} from './a'
export { default as defaultFromA } from './a'
export {
renamedInMiddleLayer as finalExportName,
middleLayerFunction as finalFunctionName,
defaultFromA as finalDefaultExport,
exportsInfo,
} from './b'
export const localInC = 'local-c'
export default function () {
return 'default-from-c'
}
import {
finalExportName,
finalFunctionName,
finalDefaultExport,
localInC,
exportsInfo,
} from './c'
import defaultFromC from './c'
import { renamedInMiddleLayer, middleLayerFunction } from './b'
import { veryLongOriginalExportName, anotherLongFunctionName } from './a'
it('should carry values through a re-export chain', () => {
// Each module in the chain mangles its own keys independently; every hop has to resolve to the
// key of the module that actually produces the binding.
expect(finalExportName).toBe('from-a')
expect(finalFunctionName()).toBe('func-a')
expect(localInC).toBe('local-c')
})
it('should carry default exports through a re-export chain', () => {
expect(finalDefaultExport()).toBe('default-from-a')
expect(defaultFromC()).toBe('default-from-c')
})
it('should support importing from the middle and the source of the chain', () => {
expect(renamedInMiddleLayer).toBe('from-a')
expect(middleLayerFunction()).toBe('func-a')
expect(veryLongOriginalExportName).toBe('from-a')
expect(anotherLongFunctionName()).toBe('func-a')
})
it('should mangle the source module of the chain', () => {
expect(exportsInfo.veryLongOriginalExportName.canMangle).toBe(true)
expect(exportsInfo.veryLongOriginalExportName.mangledName).not.toBe(
'veryLongOriginalExportName'
)
expect(exportsInfo.anotherLongFunctionName.mangledName).not.toBe(
exportsInfo.veryLongOriginalExportName.mangledName
)
})
{
"mangleExportNames": true,
"minify": true,
"scopeHoisting": false
}
...@@ -96,6 +96,8 @@ struct SnapshotOptions { ...@@ -96,6 +96,8 @@ struct SnapshotOptions {
#[serde(default)] #[serde(default)]
cjs_tree_shaking: bool, cjs_tree_shaking: bool,
#[serde(default)] #[serde(default)]
mangle_export_names: bool,
#[serde(default)]
cjs_scope_hoisting: bool, cjs_scope_hoisting: bool,
#[serde(default)] #[serde(default)]
cross_module_constants: bool, cross_module_constants: bool,
...@@ -145,6 +147,7 @@ impl Default for SnapshotOptions { ...@@ -145,6 +147,7 @@ impl Default for SnapshotOptions {
remove_unused_imports: false, remove_unused_imports: false,
remove_unused_exports: false, remove_unused_exports: false,
cjs_tree_shaking: false, cjs_tree_shaking: false,
mangle_export_names: false,
cjs_scope_hoisting: false, cjs_scope_hoisting: false,
cross_module_constants: false, cross_module_constants: false,
scope_hoisting: false, scope_hoisting: false,
...@@ -422,6 +425,7 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> { ...@@ -422,6 +425,7 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
ignore_dynamic_requests: true, ignore_dynamic_requests: true,
infer_module_side_effects: true, infer_module_side_effects: true,
cjs_tree_shaking: options.cjs_tree_shaking, cjs_tree_shaking: options.cjs_tree_shaking,
mangle_export_names: options.mangle_export_names,
cjs_scope_hoisting: options.cjs_scope_hoisting, cjs_scope_hoisting: options.cjs_scope_hoisting,
cross_module_constants: options.cross_module_constants, cross_module_constants: options.cross_module_constants,
enable_exports_info_inlining: true, enable_exports_info_inlining: true,
......
// A namespace object of this module escapes, so it keeps its original export names.
export const someLongExportName = 'long-1'
export const anotherLongExportName = 'long-2'
import * as escaping from './escaping.js'
import { someLongExportName, anotherLongExportName } from './mangled.js'
const leak = () => escaping
console.log(leak(), someLongExportName, anotherLongExportName)
// Nothing escapes here, so this module in the same graph is still mangled.
export const someLongExportName = 'mangled-1'
export const anotherLongExportName = 'mangled-2'
{
"runtime": "NodeJs",
"mangleExportNames": true,
"removeUnusedExports": true,
"removeUnusedImports": true,
"followReexports": true,
"minifyType": {
"Minify": {
"mangle": "optimal-size"
}
}
}
module.exports=["[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/escaping.js [test] (ecmascript)",t=>{"use strict";t.s(["anotherLongExportName",0,"long-2","someLongExportName",0,"long-1"])},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/index.js [test] (ecmascript)",t=>{"use strict";var s=t.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/escaping.js [test] (ecmascript)"),e=t.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/mangled.js [test] (ecmascript)");console.log(s,e.z,e.T),t.s([])},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/mangled.js [test] (ecmascript)",t=>{"use strict";t.s(["T",0,"mangled-2","z",0,"mangled-1"])}];
//# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_mangle-exports_escaping-namespace_input_1ysta13._.js.map
\ No newline at end of file
{"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/escaping.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/index.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/mangled.js"],"sourcesContent":["// A namespace object of this module escapes, so it keeps its original export names.\nexport const someLongExportName = 'long-1'\nexport const anotherLongExportName = 'long-2'\n","import * as escaping from './escaping.js'\nimport { someLongExportName, anotherLongExportName } from './mangled.js'\n\nconst leak = () => escaping\n\nconsole.log(leak(), someLongExportName, anotherLongExportName)\n","// Nothing escapes here, so this module in the same graph is still mangled.\nexport const someLongExportName = 'mangled-1'\nexport const anotherLongExportName = 'mangled-2'\n"],"names":["someLongExportName","anotherLongExportName","leak","imported module [project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/escaping.js [test] (ecmascript)","console","log"],"mappings":"oMAEqC,gCADH,8JCDlC,IAAA,EAAA,EAAA,CAAA,CAAA,qIACA,EAAA,EAAA,CAAA,CAAA,oIAIAI,QAAQC,GAAG,CAFQF,AAEPD,EAAQ,EAAA,CAAkB,CAAE,EAAA,CAAqB,0KCHxB,kBADH"}
\ No newline at end of file
var RUNTIME_PUBLIC_PATH = "output/[turbopack]_runtime.js";
var RELATIVE_ROOT_PATH = "../../../../../../..";
var ASSET_PREFIX = "/";
// Dummy runtime
\ No newline at end of file
var R=require("./[turbopack]_runtime.js")("output/index.entry.js")
R.c("output/0_9x_turbopack-tests_tests_snapshot_mangle-exports_escaping-namespace_input_1ysta13._.js")
R.m("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/index.js [test] (ecmascript)")
module.exports=R.m("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/index.js [test] (ecmascript)").exports
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": []
}
\ No newline at end of file
import {
a,
bb,
someLongExportName,
anotherLongExportName,
aLongFunctionName,
} from './lib.js'
console.log(
a,
bb,
someLongExportName,
anotherLongExportName,
aLongFunctionName()
)
export const a = 'a'
export const bb = 'bb'
export const someLongExportName = 'long-1'
export const anotherLongExportName = 'long-2'
export const unusedLongExportName = 'unused'
export function aLongFunctionName() {
return 'fn'
}
{
"runtime": "NodeJs",
"mangleExportNames": true,
"removeUnusedExports": true,
"removeUnusedImports": true,
"followReexports": true,
"minifyType": {
"Minify": {
"mangle": "optimal-size"
}
}
}
module.exports=["[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/index.js [test] (ecmascript)",t=>{"use strict";var s=t.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/lib.js [test] (ecmascript)");console.log(s.a,s.$,s.z,s.T,(0,s.X)()),t.s([])},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/lib.js [test] (ecmascript)",t=>{"use strict";t.s(["a",0,"a","X",0,function(){return"fn"},"T",0,"long-2","$",0,"bb","z",0,"long-1"])}];
//# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_mangle-exports_named-and-preserved_input_0pbreft._.js.map
\ 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