Repository navigation
fix(external): keep __toESM when the importing module is tree-shaken - #10516
Conversation
✅ Deploy Preview for rolldown-rs canceled.
|
How to use the Graphite Merge QueueAdd the label graphite: merge-when-ready to this PR to add it to the merge queue. You must have a Graphite account in order to use the merge queue. Sign up using this link. An organization admin has enabled the Graphite Merge Queue in this repository. Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue. This stack of pull requests is managed by Graphite. Learn more about stacking. |
Merging this PR will not alter performance
Comparing Footnotes
|
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
hyfdev
left a comment
There was a problem hiding this comment.
The new observer and mode bookkeeping still loses external interop semantics in four reachable cases: entry facades can miss wrapping after advanced chunking, union-find compression can misidentify the import writer, mixed-mode entry exports discard the Node-mode binding, and a synthetic Node binding can be captured by a nested local. Each case changes the value of a default or namespace import for CommonJS exports that declare __esModule, so they need to be covered before this merges.
— Review by @hyfdev, assisted by GPT-5
7cc530a to
9aa3d91
Compare
|
Thanks for digging into this — all four were real, and I reproduced every one with an executable fixture before touching anything. I've fixed the union-find one here. You were right that The other three I've split out into #10519 rather than fixing here, because they all reproduce on My reasoning for splitting: this PR is already five commits of interop rework, and folding in three unrelated pre-existing bugs would make it considerably harder to review — and would put them in the history as if this change caused them. #10519 has full runnable fixtures for all three plus the emitted output, so nothing is lost. One thing your review surfaced that I think is the real story: findings 1 and 2 are the same gap. Happy to pull any of the three back in here if you'd rather see them together — just say so. |
`import d from 'external'; export { d }` links the shim's symbol to a
`NamespaceAlias`, so tree-shaking follows that alias straight to the external
namespace and never enqueues the shim's declaring statement. With a
side-effect-free external the shim is dropped entirely, and two things break:
- `RuntimeHelper::ToEsm` is registered against the now-dead import statement and
discarded with it.
- `render_cjs_chunk_imports` derives `needs_interop` from
`chunk.direct_imports_from_external_modules`, which is built only from modules
present in the chunk, so the external lands in the indirect bucket and is not
wrapped.
The finalizer still renders `<external_ns>.default`, so the output reads
`.default` off the raw CommonJS exports and yields `undefined`.
Record the interop in the inclusion pass instead — the one place that walks the
reference after linking resolved it — and have the cjs renderer, the iife/umd
renderer and the chunk deconflicter OR that record into their existing
`named_imports`-derived answer. `patch_module_dependencies` derives the runtime
edge from the reference rather than the importer, so arbitrary-length re-export
chains keep the helper reachable; references that exist only as entry exports
are covered too, otherwise a chunk emits a helper it never imported and
finalization panics. Node-mode provenance is recovered by walking the symbol
link chain back to the module that wrote the import, since linking collapses the
chain onto the external's namespace symbol.
The record is per-bundle, not per-chunk (inclusion runs before chunking), so a
default import in one chunk wraps the external in all of them. Named access
still reads through the wrapper's forwarding getters; the trade-off and why
narrowing it is not a simple chunk-membership test are documented on
`recorded_external_interop`.
`issues/4585` regains its `__toESM` call, restoring the output it had before
#6751 — that fixture sets `expectExecuted: false`, which is how it kept
snapshotting the broken form.
Closes #10069
Claude-Session: https://claude.ai/code/session_01NsgZ6r2G3wbVm4ZfJNJbVn
The interop record was keyed by external namespace alone, so a default import anywhere in the bundle wrapped that external in *every* chunk emitting it — including chunks holding only a named import. That is not just larger output: `__toESM` returns a fresh object (`__create(__getProtoOf(mod))`) and `__copyProps` eagerly walks `__getOwnPropertyNames`/`__getOwnPropertyDescriptor`, so a named-only chunk observes a different namespace identity, accessor-shaped descriptors instead of data properties, and — for a CommonJS export implemented as a Proxy — extra `ownKeys`/`getOwnPropertyDescriptor` traps at require time. Record the observing module alongside the use. The observer is the module holding the surviving reference, not the importer that wrote `import ... from 'external'`; the latter is routinely the re-export shim that tree-shaking drops, while the former by construction has included code and so gets a chunk. Rendering then wraps only the chunks the observers landed in. Observers that end up without a live chunk cannot be attributed and fall back to the previous bundle-wide behaviour. That fallback is load-bearing: narrowing it away would under-approximate, which is what produced #10069 in the first place. `patch_module_dependencies` deliberately stays bundle-wide. It runs before chunking and so cannot know which chunks will wrap; over-supplying a runtime edge is harmless, whereas under-supplying panics in helper finalization. The visible cost is a bindings-less `require("./rolldown-runtime.js")` in a chunk that no longer wraps — dead weight, not incorrect. Claude-Session: https://claude.ai/code/session_01NsgZ6r2G3wbVm4ZfJNJbVn
Observer attribution made *which* chunks wrap chunk-local, but `node_esm` and
`non_node_esm` stayed bundle-wide. A `.mjs` entry and a `.js` entry importing the
same external into separate chunks therefore both looked mixed-mode, and each
emitted `__toESM(mod, 1)` *and* `__toESM(mod)` where only one binding is live —
running `__copyProps`' eager `__getOwnPropertyNames`/`__getOwnPropertyDescriptor`
walk twice, which is observable for a Proxy-based CommonJS export.
Key the record by observer, so each carries its own mode:
FxHashMap<SymbolRef, FxHashMap<ModuleIdx, ExternalInteropUse>>
`chunk_recorded_external_interop` filters to the observers it selects and only
then reduces with `ExternalInteropUse::union`. Selection and mode aggregation now
run over the same set, so they cannot drift apart again — previously selection was
per-chunk while modes were per-bundle, which is exactly the mismatch above.
The unattributable fallback is preserved and becomes mode-aware too: an observer
with no live chunk is honoured by every chunk, contributing only its own mode
rather than the bundle union.
`interop_use` survives as the bundle-wide aggregate for
`patch_module_dependencies`, which runs before chunking and legitimately needs
the union; its docs now say so, to stop renderers reaching for it again.
Also refresh the docs that still described the pre-narrowing behaviour: the
`__toESM` section of internal-docs/runtime-helpers, both fixture comments that
claimed named-only chunks get wrapped, and four stale references to the removed
`recorded_external_interop`. The `external_interop_only_reachable_via_entry_export`
comment is rewritten rather than reworded — observer attribution stops `entry-b`
wrapping at all, so it no longer reaches the panic it was written to guard and
now pins the attribution instead.
Claude-Session: https://claude.ai/code/session_01NsgZ6r2G3wbVm4ZfJNJbVn
Deconflicting decided mixed-mode binding names by filtering `named_imports` on `specifier_needs_interop`; the renderers derived the same modes without that filter. A chunk holding a non-Node *default* import plus a Node-mode *named-only* import was therefore planned single-mode and then rendered `__toESM(mod, 1)` — the named-only importer, which needs no wrapper at all, decided the mode for someone else. For a CommonJS export declaring `__esModule` and owning a `default`, that changes the value the default import sees. Predates this branch (#8987), but the derivation now lives in one place: `chunk_external_interop_modes` folds the recorded observations attributable to a chunk together with that chunk's own default/namespace imports, and deconflicting, cjs and iife/umd all consume it. Deriving it separately is how the two drifted apart, so the fix is to stop deriving it twice rather than to repeat the filter. Also drop the bundle-wide mode aggregate. Its only caller checked `.is_some()`, while the call itself folded every observer's flags — quadratic for `patch_module_dependencies`, which asks once per external reference in the bundle. Replaced by `has_interop_use_for`, an O(1) presence check. Two tests are added. `node_mode_named_only_import_...` covers the case above. `dual_provenance_through_shims_of_different_formats` is a characterization test, not a guarantee: one consumer reaching an external through both a `.mjs` and a `.js` shim has both references collapsed onto the external's namespace symbol by linking, so they are the same canonical symbol and cannot select different bindings. Finalization picks by the consumer's format (`module_finalizers/mod.rs`), so one reference reads a wrapper that does not match the shim it came through. Fixing that needs reference-level provenance carried through finalization — out of scope here, and only observable for a CommonJS export that both sets `__esModule` and owns a `default`. Claude-Session: https://claude.ai/code/session_01NsgZ6r2G3wbVm4ZfJNJbVn
Modes are recorded from the import writer's format, but the finalizer selects
between the two mixed-mode bindings using the *rendering* module's format. The
two disagree once an ESM shim is dropped and only a non-ESM consumer survives:
both flags end up set, the chunk is planned mixed-mode, and nothing ever reads
the node binding. DCE then removes the unused `let` and keeps the call, so the
output carries a bare
__toESM(node_https, 1);
running `__copyProps`' eager `__getOwnPropertyNames`/`__getOwnPropertyDescriptor`
walk — extra Proxy traps at require time — for a value that is discarded.
Gate the mixed-mode plan on `chunk_has_node_esm_reader`, mirroring the
finalizer's rule, so the binding is only planned when it can be read.
Suppressing it moves the chunk onto the single-binding path, where reading
`node_esm` alone would flip the surviving wrapper into Node mode and change what
the non-ESM consumer sees — trading a wasted call for a wrong value. Both flags
being set now means exactly "suppressed because no ESM reader", so the renderers
use `node_esm && !non_node_esm` and the survivor keeps matching its readers. The
values are byte-identical to before; only the discarded call goes away.
Also scope the indirect external list to Cjs when planning mixed-mode names. That
list is not format-gated (`compute_cross_chunk_links`, which only skips Esm), but
`render_chunk_external_imports` walks the direct list alone, so a name planned
from an indirect external under iife/umd would have no `let` to bind it. Latent
rather than live — iife/umd do not split and their import-writing shims stay
included — but the two sides should not disagree.
`note_external_interop` gets a monotonic-flag early return; it runs for every
referenced symbol of every module and has nothing left to learn once set.
`dual_provenance_through_shims_of_different_formats` tightens from a shape check
to asserting one non-Node wrapper, pinning both the removed dangling call and the
mode of the survivor. The provenance mismatch it documents is still unfixed and
still needs per-reference provenance in the finalizer.
Claude-Session: https://claude.ai/code/session_01NsgZ6r2G3wbVm4ZfJNJbVn
Node mode is decided by the format of the module that wrote `import ... from 'external'`, and that writer was recovered by walking `SymbolRefDb::link`. The walk assumed an ordered chain (consumer -> shim -> external), but `link` is a union-find parent: it resolves both endpoints through `find_mut`, which path-compresses, and it assigns to the *target root* rather than the target. Once the shim's own link exists, linking a consumer points it straight at the external namespace and the shim is no longer on the path at all. The walk then reports the consumer as the writer. For a `.mjs` shim feeding a `.js` consumer, that drops Node mode and renders `__toESM(mod)`, so `ns.default` becomes an `__esModule` external's declared `default` instead of the raw `module.exports`. Whether it happens depends on module discovery order, which is why the existing fixtures did not catch it. Only the namespace path was affected. For a default import the alias holder is where the `namespace_alias` lives, which makes it the union-find root — its owner really is the writing module and compression cannot move it. The namespace path now asks the import records who imported this external, since linking leaves those untouched. Results are cached per external on `IncludeContext`. Reported by @hyfdev while reviewing this PR. Three further findings from the same review reproduce on main and are tracked separately in #10519; they are not touched here. Claude-Session: https://claude.ai/code/session_01NsgZ6r2G3wbVm4ZfJNJbVn
9aa3d91 to
9e5b1d3
Compare
Dismissing: this review targets commit 7cc530a, which is no longer part of the PR — the branch was rewritten afterwards and the four points were addressed in the current commits (64961fd attributes external interop to the chunk that observes it, 9e5b1d3 takes external import provenance from import records instead of union-find links, 8f57034 keeps Node mode with the observer that saw it, 437e3d9 plans the node-mode binding only when something reads it). @shulaoda has approved the current head 9e5b1d3. @hyfdev — please re-review if any of these still stand.
## [1.2.1] - 2026-07-29 ### 🚀 Features - dev: support `hotUpdate` hook (#10305) by @h-a-n-a - dev: expose `disableWatcher` through the dev engine bindings (#10474) by @shulaoda - plugin: surface output-option callbacks in [PLUGIN_TIMINGS] (#10411) by @IWANABETHATGUY - `import.meta.ROLLDOWN_FILE_URL_<referenceId>_<urlId>` support to pass context to `resolveFileUrl` hook (#10297) by @sapphi-red - dev: skip the HMR update when a module's rebuilt output is unchanged (#10333) by @h-a-n-a - code-splitting: wrap strict execution order modules on demand (#10104) by @hyfdev - support `import.meta.ROLLDOWN_FILE_URL_*` (#10296) by @sapphi-red - implement `resolveFileUrl` plugin hook (#10291) by @sapphi-red - magic-string: support storeName on overwrite/update (#10312) by @IWANABETHATGUY ### 🐛 Bug Fixes - external: keep `__toESM` when the importing module is tree-shaken (#10516) by @IWANABETHATGUY - dev: resolve re-exports from externals through a real import (#10489) by @tbvjaos510 - code-splitting: route CJS barrel initialization per consumer (#10488) by @hyfdev - error: align filename-pattern diagnostics with Rollup's wording (#10501) by @IWANABETHATGUY - plugin: validate emitted prebuilt-chunk file names (#10399) by @IWANABETHATGUY - code-splitting: point a two-argument dynamic import at the chunk that holds the module (#10479) by @hyfdev - common: align is_path_fragment with Rollup's isPathFragment (#10398) by @IWANABETHATGUY - code-splitting: never name an internal chunk export `then` (#10480) by @hyfdev - code-splitting: avoid creating call-site-triggered entry facades (#10485) by @hyfdev - code-splitting: collect top-level eager order reasons in every strict build (#10463) by @hyfdev - code-splitting: let a cross-chunk dynamic importer carry the order trigger (#10456) by @hyfdev - code-splitting: avoid the dynamic-entry facade when the same-chunk collapse carries the trigger (#10433) by @hyfdev - binding: forward resolveId options.kind to callable builtin plugins (#10440) by @martijnwalraven - dev: keep the export name of `export * as ns from` (#10476) by @tbvjaos510 - code-splitting: only split an entry facade when something else can load its chunk (#10441) by @hyfdev - code-splitting: fold the runtime chunk back after order lowering (#10414) by @hyfdev - runtime: don't leave default undefined for cjs that fakes __esModule (#10453) by @IWANABETHATGUY - import-glob: escape generated string literals (#10438) by @shantanuraj - preserve-modules: don't assume every chunk mirrors a module (#10442) by @hyfdev - filter: treat missing hook inputs as non-matches, not panics (#10443) by @IWANABETHATGUY - code-splitting: keep CommonJS modules wrapped under strict execution order (#10405) by @hyfdev - code-splitting: align dynamicImports metadata with the rewritten import() specifier (#10430) by @hyfdev - dev: skip user plugin hooks for ?rolldown-lazy proxy modules (#10426) by @unknownjedi - treeshake: preserve side-effect-free spread arguments in manual-pure chains (#10432) by @IWANABETHATGUY - treeshake: preserve eagerly evaluated child effects of manual pure chains (#10427) by @Nic-Polumeyv - code-splitting: initialize pure definers behind star re-export barrels under strict execution order (#10409) by @hyfdev - resolveId: reject string `id` filters (must be a RegExp) (#10412) by @IWANABETHATGUY - code-splitting: collect eager order reasons for on-demand wrapping (#10387) by @hyfdev - rolldown: apply output.paths to CJS export-star of external modules (#10406) by @IWANABETHATGUY - dev: sourcemaps of lazily compiled chunks (#10386) by @tbvjaos510 - plugin: validate emitted file names at emitFile time (#10377) by @Nic-Polumeyv - guarantee tokio runtime release when close rejects (#10381) by @shulaoda - code-splitting: make strict transitive init registration deterministic and constant-time (#10320) by @hyfdev - pair tokio runtime acquire and release on wasm to prevent premature shutdown (#10363) by @shulaoda - don't body-demand modules from simulated facade chunk includes (#10351) by @IWANABETHATGUY - tracing: invalid RD_LOG filter and RD_LOG_OUTPUT=json no longer panic (#10343) by @Brooooooklyn - code-splitting: treat class definition-time global reads as order-sensitive (#10322) by @hyfdev - code-splitting: deconflict force-included runtime helper statements (#10336) by @hyfdev - binding: forward all missing parallel JS plugin hooks (#10345) by @Brooooooklyn - code-splitting: re-derive chunk exec order after the runtime sweep (#10334) by @hyfdev - types: add undefined to ExistingRawSourceMap optional properties (#10355) by @ocavue - magic-string: validate relocate ranges before rewiring (#10327) by @IWANABETHATGUY - add EMPTY_IMPORT_META warning for non-node CJS output (#10222) by @sapphi-red - call `resolveFileUrl` in a deterministic order (#10330) by @sapphi-red - magic-string: refuse repeated sendMagicString on a consumed instance (#10331) by @IWANABETHATGUY - magic-string: refuse to use a MagicString after sendMagicString consumed it (#10326) by @IWANABETHATGUY - magic-string: reject non-contiguous moves before rewiring the chunk list (#10311) by @IWANABETHATGUY - handle `./foo/bar` glob pattern the same as `foo/bar` (#10313) by @sapphi-red - magic-string: throw instead of panicking when append/prepend splits an edited chunk (#10301) by @IWANABETHATGUY - output: skip separator for empty hoisted functions (#10310) by @hyfdev - magic-string: don't report a change when edits cancel out (#10299) by @IWANABETHATGUY - sourcemap: map wrapped imported callees (#10288) by @hyfdev - magic-string: count positional inserts at index 0 on an empty source (#10306) by @IWANABETHATGUY - magic-string: return UTF-16 code units from length() (#10295) by @IWANABETHATGUY - output: skip separator for empty import prelude (#10289) by @hyfdev ### 🚜 Refactor - dev: make it easier to customize the runtime (#10338) by @sapphi-red - code-splitting: declare CJS carrier namespaces initializer-free (#10513) by @hyfdev - rollup-tests: avoid relying on `NODE_PATH` env var resolution (#10496) by @sapphi-red - code-splitting: derive symbol chunk ownership as pass-local link data (#10449) by @hyfdev - plugin: share asset emission helpers between copy_module and asset_module (#10450) by @Nic-Polumeyv - plugin: dedupe hook binding boilerplate (#10428) by @Nic-Polumeyv - plugin: share the oxc parse preamble between import-glob and dynamic-import-vars (#10452) by @Nic-Polumeyv - implement `GetAstBuilder` on visitor/pass types (#10424) by @overlookmotel - pass arrays to AST builder methods (#10419) by @overlookmotel - shorten AST builder code (#10418) by @overlookmotel - centralize final ESM init metadata (#10376) by @hyfdev - descriptor-based parallel-plugin detection (getParallelPluginInfo) (#10349) by @Brooooooklyn - remove AstFactory in favor of new_* construction traits (#10353) by @Boshen - enable oxc_ast's `disable_old_builder` feature (#10316) by @Boshen ### 📚 Documentation - development-guide: update config.json link line reference (#10523) by @dogledogle - clarify slash normalization for id hook filter (#10511) by @sapphi-red - code-splitting: record the thenable-namespace rule (#10502) by @hyfdev - clarify that `esmExternalRequirePlugin` must own its externals (#10439) by @TheAlexLichter - add troubleshooting entry for the @rolldown/binding-... resolution error (#10390) by @Nic-Polumeyv - add Code Splitting API reference category (#10382) by @vittorioexp ### ⚡ Performance - use VisitJsMut in JavaScript-only AST passes (#10507) by @Boshen - cache the resolved glob matcher for Id/ImporterId filters (#10410) by @IWANABETHATGUY - scope_hoisting: remove `alloc` field from `ScopeHoistingFinalizer` (#10425) by @overlookmotel - reduce string allocations (#10423) by @overlookmotel - hmr: remove unnecessary string allocations (#10422) by @overlookmotel - avoid allocating static strings via custom builder methods (#10421) by @overlookmotel - pass string literals to AST builder methods (#10420) by @overlookmotel - use VisitJs in JavaScript-only AST passes (#10396) by @Boshen - plugin: shrink erased plugin debug vtables (#10370) by @Boshen - reuse normalized path buffers (#10315) by @hyfdev ### 🧪 Testing - code-splitting: pin CJS barrel fallback triggers and flag-off equivalence (#10514) by @hyfdev - plugin: cover chunk fileName, absolute chunk name, and Windows drive names (#10400) by @IWANABETHATGUY - code-splitting: cover a single-chunk dynamic import of a wrapped module (#10505) by @hyfdev - file: remove the unused .dynamic_import fixture (#10481) by @hyfdev - treeshake: reduce manual-pure fixture to a minimal smoke test, move matrix to unit tests (#10436) by @IWANABETHATGUY - dev: run vite playgrounds under bundled dev (test-serve-bundled) (#10434) by @h-a-n-a - stop snapshots from silently hiding user code inside the runtime region (#10431) by @hyfdev - wasi: add tokio runtime lifecycle regression test (#10379) by @shulaoda - dev: expect preserved hot.data in hmr-whole-chain-dispose (#10380) by @h-a-n-a - code-splitting: pin flag-off wrapped-esm init emission (#10324) by @hyfdev - sourcemap: fix Windows-only failures in composition fixtures (#10368) by @shulaoda - generated-code: mark assert external in symbols_ns2 for deterministic output (#10339) by @hyfdev - code-splitting: cover entries-aware strict init cycle (#10307) by @hyfdev - make `just setup-vite` the only entry point that touches `vite/` (#10332) by @shulaoda - vite-tests: reuse the shared root vite checkout (#10325) by @shulaoda - test-dev-server: drop the vite submodule, track rolldown-canary (#10319) by @shulaoda - vite-tests: track the latest rolldown-canary rebased onto vite main (#10318) by @shulaoda - unify Vite in vite-test and test-dev-server (#10293) by @h-a-n-a ### ⚙️ Miscellaneous Tasks - scope the binding artifact download to `bindings-*` (#10525) by @shulaoda - deps: update napi (#10506) by @renovate[bot] - deps: update rollup submodule for tests to v4.62.3 (#10494) by @rolldown-guard[bot] - deps: upgrade oxc to 0.142.0 (#10497) by @shulaoda - deps: update test262 submodule for tests (#10495) by @rolldown-guard[bot] - deps: update github actions (#10460) by @renovate[bot] - deps: update rust crates (#10462) by @renovate[bot] - deps: update npm packages (#10461) by @renovate[bot] - metric: alert Discord when the metric workflow fails (#10447) by @IWANABETHATGUY - metric: mint a short-lived GitHub App token instead of a PAT (#10446) by @IWANABETHATGUY - repo: repair dangling CLAUDE.md symlink (#10451) by @hanayashiki - publint/package-metadata fixes and small correctness fixes (#10344) by @Brooooooklyn - deps: update dependency vite-plus to v0.2.6 (#10404) by @renovate[bot] - add Semgrep scan workflow (#10395) by @Boshen - enable Windows CI with a PR label (#10375) by @hyfdev - deps: upgrade oxc to 0.141.0 (#10373) by @camc314 - deps: update napi (#10369) by @renovate[bot] - deps: update test262 submodule for tests (#10367) by @rolldown-guard[bot] - deps: update taiki-e/install-action action to v2.83.3 (#10358) by @renovate[bot] - deps: update rust crates (#10357) by @renovate[bot] - deps: update npm packages (#10359) by @renovate[bot] - deps: update rust crate syn to v3 (#10362) by @renovate[bot] - deps: update rust crate oxc_sourcemap to v8.1.2 (#10356) by @renovate[bot] - deps: update dependency vite-plus to v0.2.5 (#10329) by @renovate[bot] - docs: migrate Netlify redirects to Void config (#10282) by @tux-tn - deps: update dependency rust to v1.97.1 (#10317) by @renovate[bot] - runtime: remove unused `runtime/index.js` (#10302) by @IWANABETHATGUY ### ❤️ New Contributors * @dogledogle made their first contribution in [#10523](#10523) * @tbvjaos510 made their first contribution in [#10489](#10489) * @martijnwalraven made their first contribution in [#10440](#10440) * @shantanuraj made their first contribution in [#10438](#10438) * @Nic-Polumeyv made their first contribution in [#10450](#10450) * @hanayashiki made their first contribution in [#10451](#10451) * @unknownjedi made their first contribution in [#10426](#10426) * @vittorioexp made their first contribution in [#10382](#10382) * @tux-tn made their first contribution in [#10282](#10282) Co-authored-by: shulaoda <[email protected]>
…10517) Stacked on #10516 — review that one first. A chunk that does not wrap an external still emitted a useless import of the runtime chunk: ```js Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); require("./rolldown-runtime.js"); // nothing is used from it let node_https = require("node:https"); exports.foo = node_https.request; ``` ## Why it happened Not an empty cross-chunk import. The chunk really did import `__toESM`, so it rendered `const require_rolldown_runtime = require(...)`; DCE then dropped the unused binding and kept the side-effectful call. The import existed because `patch_module_dependencies` set `reads_external_as_esm` from the bundle-wide record, so a module reading only a *name* off the external still demanded the helper and put it in its chunk's depended symbols. ## The fix Derive that edge from the same observer set the renderers use, so a module demands `__toESM` only when it is an observer. Both decisions now come from one source, which is what makes narrowing safe: the chunk that wraps is exactly the chunk that depends on the runtime. Under-supplying is the dangerous direction — a chunk that wraps without the edge references a helper it never imported and finalization panics — so an observer that is not included keeps the previous bundle-wide behaviour, matching rendering's own unattributable fallback. Chunks do not exist yet at that point, so `is_included` stands in for "will have a chunk". This only became safe once #10516 made rendering observer-attributed. Narrowing this edge before that reintroduces the panic, which is why it is a separate commit rather than part of the fix below it. ## Result `external_interop_only_reachable_via_entry_export` shows the payoff — with only `entry-a` demanding the helper, the runtime stops being shared and folds into `entry-a`, so the separate runtime chunk disappears entirely: ```js // entry-a.js let node_https = require("node:https"); node_https = __toESM(node_https); // entry-b.js let node_https = require("node:https"); exports.foo = node_https.request; ``` `named-user` in `reexport_default_import_of_external_multi_chunk` loses its bare `require` the same way; that fixture's `_test.mjs` still asserts the values executably. Those two snapshots are the only output changes. The fixture comment and internal doc previously stated this edge had to stay bundle-wide with the bare `require` as an accepted cost — true when written, so both are updated. --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>

Fixes #10069.
Default-importing a CJS external, re-exporting it, then reading it back produced
Cannot read properties of undefinedin CJS output.The bug
import d from 'external'; export { d }links the shim's symbol to aNamespaceAlias, so tree-shaking follows that alias straight to the external namespace and never enqueues the shim's declaring statement. With a side-effect-free external the shim is dropped entirely, and two things break:RuntimeHelper::ToEsmis registered against the now-dead import statement and discarded with it.render_cjs_chunk_importsderivedneeds_interopfromchunk.direct_imports_from_external_modules, which is built only from modules present in the chunk, so the external landed in the indirect bucket unwrapped.The finalizer still rendered
<external_ns>.default, so the output read.defaultoff the raw CommonJS exports and gotundefined.Introduced by #6751 ("skip
__toESMwhen not needed to reduce output size"), first shipped broken in 1.0.0-beta.46 — verified by bisecting published npm builds.The fix
The question "is this external read as an ES module?" can only be answered after linking resolves the reference, so the inclusion pass records it — the one pass that walks the reference at that point. The record is keyed by observer: the module holding the surviving reference, not the importer that wrote the
import, since the importer is routinely the shim that gets dropped while an observer has included code by construction and therefore lands in a chunk.Rendering then resolves observers to chunks, which decides both questions per chunk:
ownKeystraps on a Proxy-based export..mjsand.jschunks both look mixed-mode and emit__toESM(mod, 1)and__toESM(mod)for one live binding.An observer that ends up without a live chunk cannot be attributed, so every chunk emitting that external honours it. This fallback is load-bearing: narrowing it away under-approximates, which is what produced the bug.
Deconflicting and the cjs/iife/umd renderers share one mode derivation (
chunk_external_interop_modes). Deriving it in two places is how they drifted apart — deconflicting filtered out named-only specifiers and the renderers did not, so a chunk could be planned single-mode then rendered__toESM(mod, 1)because an unrelated named-only importer happened to be ESM.Notes for review
issues/4585regains its__toESMcall, restoring the output it had before feat: skip__toESMwhen not needed to reduce output size #6751. That fixture setsexpectExecuted: false, which is how it kept snapshotting the broken form for months. The new fixtures assert executably against realnode:https..mjsand a.jsshim collapses to a single canonical symbol, so one reference reads a wrapper that does not match its shim's format. A real fix needs per-reference provenance in the finalizer. Observable only for an external declaring__esModuleand owning adefault;dual_provenance_through_shims_of_different_formatscharacterizes it.Design rationale is in
internal-docs/runtime-helpers/implementation.md.