Skip to content

resolver: read package.json "type" from the nearest package.json, named or not - #41232

Merged
Jarred-Sumner merged 1 commit into
mainfrom
robobun/17bd4806/nearest-package-json-type
Sep 3, 2026
Merged

Jarred-Sumner merged 1 commit into
mainfrom
robobun/17bd4806/nearest-package-json-type

Conversation

@robobun

@robobun robobun commented Sep 3, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • Regression on main from bundler: pick the __toESM interop from the importer's module type #41150. No release has it. bun build reads "type" from the wrong package.json, so it misses a { "type": "module" } that has no "name". Two common places: a project root, and a dual package's dist/esm/package.json.
  • A .js or .ts file there gets exports.default for the default import of a CommonJS module with __esModule. Node, esbuild and bun 1.4.0 give the whole module.exports. The bundle has __toESM(require_tsdep()), without , 1.
  • Cause: finalize_result (src/resolver/resolver.rs:1669) read "type" from the package root, or else from enclosing_package_json. dir_info_uncached (src/resolver/resolver.rs:6357) sets that field only for a named package.json (Support running package.json scripts from package.json without a name #229).

Fix

  • DirInfo gets package_json_for_module_type: the nearest package.json in the directory or above it, named or not. finalize_result reads "type" from it for the primary path. The extension still wins.
  • Correct because esbuild uses this rule, and Node ignores "name" too.
  • Only the bundler reads Result.module_type. enclosing_package_json does not change. The four runtime lookups in src/runtime/jsc_hooks.rs are out of scope.
  • Verified: test/bundler/bundler_cjs.test.ts, 10 new cases, 9 fail on main. Self-reviewed: 3 concerns raised, 3 addressed. Other suites in Notes.

Background

Notes

Found by comparing bun build on main with bun 1.4.0, Node 26 and esbuild 0.25. No issue is open for it.

Repro for the dual-package face:

D=$(mktemp -d); cd $D; mkdir -p node_modules/pkg/dist/esm node_modules/tsdep
echo '{"name":"tsdep","version":"1.0.0","main":"index.js"}' > node_modules/tsdep/package.json
echo 'Object.defineProperty(exports,"__esModule",{value:true}); exports.default=function styled(){}; exports.css="css";' > node_modules/tsdep/index.js
echo '{"name":"pkg","version":"1.0.0","main":"./dist/esm/index.js"}' > node_modules/pkg/package.json
echo '{"type":"module"}' > node_modules/pkg/dist/esm/package.json
echo 'import styled from "tsdep"; export const seen = typeof styled + "/" + typeof styled.default;' > node_modules/pkg/dist/esm/index.js
echo 'import { seen } from "pkg"; console.log(seen);' > app.mjs
node app.mjs                                                              # object/function
bun build ./app.mjs --target=node --outfile=out.mjs && node out.mjs       # main: function/undefined, this PR: object/function

For the project-root face, put { "type": "module" } (no "name") in the project's package.json and bundle a .js file that imports tsdep.

Faces of the bug on main. Each has a test:

  • A project package.json with "type" and no "name" (case 58).
  • The nested marker reached through "main", "module" or a relative path (cases 53, 55, 56). Through an exports map it worked, because handle_esm_resolution reads the file's own directory.
  • A nested package.json with a "name", reached through "main" (case 54). result.package_json was the package root, so the nested file was not read at all.
  • A file in a subdirectory of the marker (case 57).

Why a new field instead of widening enclosing_package_json: that field also names the package for sideEffects, the auto-install version gate and bun run script discovery. #33883 widens it for every consumer and had to rework the sideEffects loop in finalize_result to keep the DCE tests passing.

Four cases pin the lookup rule. Each result matches esbuild 0.25.1:

  • Case 59: a nameless { "type": "commonjs" } below a "type": "module" package wins, because it is the nearest.
  • Case 60: a nearest package.json without "type" is the scope. The lookup does not continue to a typed package root, so the importer is not ESM by type. Main read the root's "type" here. Node prints object/function for this shape, but only because it detects ESM syntax in a file with no "type". bundler: pick the __toESM interop from the importer's module type #41150 chose the esbuild rule for such files.
  • Case 61: the lookup does not stop at a node_modules directory. A package without a package.json of its own takes the "type" above it. Node prints the same result.
  • Case 62: only the primary path decides. With the default target, "module" is the primary path and "main" is the fallback for require(). The fallback's package.json does not count. esbuild has the same check. The case fails when the check is removed.

Overlap with #40940: it adds a field with the same name, but its lookup stops at node_modules, and the runtime reads it too. If #40940 lands after this PR, it must choose one rule for the field. Case 61 pins the crossing for the bundler. Node's stop can still apply at the runtime read sites. #40940 also calls the lookup for the fallback path, which case 62 rejects.

Out of scope: the runtime's four lookups (src/runtime/jsc_hooks.rs lines 1474, 2972, 3220 and 4071) keep package_json().or(enclosing_package_json). So bun run still skips a nameless package.json above the file's own directory. That gap predates #41150. For this import, bun run 1.4.1 gives exports.default for every importer, even .mjs.

Self-review, the three concerns and what changed:

  • Document the node_modules rule on the field. Done in src/resolver/dir_info.rs.
  • Add a default-target case with both "main" and "module". That is case 62.
  • Say in this body that no release has the bug, lead with the project-root face, and name the runtime lookups that stay.

Suites run with the fix on a debug ASAN build, after a rebase on main: bundler_cjs (62), esbuild/packagejson, esbuild/dce, esbuild/default, bundler_cjs2esm, bundler_npm, bundler_edgecase, bundler_regressions, bundler_splitting, bundler_barrel, cli/run/run-cjs, test/js/bun/resolve. All pass except the second case of test/js/bun/resolve/load-same-js-file-a-lot.test.ts. It times out at 5 s on this build with and without this change (back-to-back runs on the same machine).


[human-review] gate passed · iteration 0 · 4 files touched

fails on main (without fix)
ASAN without fix: 9 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/bundler_cjs.test.ts
bun test v1.4.1 (a6c4cc276)

test/bundler/bundler_cjs.test.ts:
(pass) bundler > cjs/__toESM_import_syntax_with_esModule [945.38ms]
(pass) bundler > cjs/__toESM_import_syntax_without_esModule [445.45ms]
(pass) bundler > cjs/__toESM_import_syntax_function [371.94ms]
(pass) bundler > cjs/__toESM_import_syntax_primitive [387.72ms]
(pass) bundler > cjs/__toESM_import_syntax_named_and_default [361.78ms]
(pass) bundler > cjs/__toESM_import_syntax_namespace [367.76ms]
(pass) bundler > cjs/__toESM_target_node [455.64ms]
(pass) bundler > cjs/__toESM_target_browser [413.38ms]
(pass) bundler > cjs/__toESM_target_bun [455.22ms]
(pass) bundler > cjs/__toESM_format_esm [462.40ms]
(pass) bundler > cjs/__toESM_format_cjs_with_import [377.93ms]
(pass) bundler > cjs/__toESM_mjs_reexport [431.60ms]
(pass) bundler > cjs/__toESM_mjs_reexport_with_esModule [432.63ms]
(pass) bundler > cjs/__toESM_deep_reexport_chain [368.70ms]
(pass) bundler > cjs/__toESM_reexport_with_rename [443.84ms]
(pass) bundler > cjs/__toESM_default_prop
... (truncated)

release without fix: 20 FAILED
bun test v1.4.1-canary.1 (a6c4cc276)

test/bundler/bundler_cjs.test.ts:
runtime failed file: /tmp/bun-build-tests/bun-4t1lr0/cjs/__toESM_import_syntax_with_esModule/out.js
stdout output:
{"__esModule":true,"default":{"value":"default export"},"named":"named export"}
---
expected stdout:
{"value":"default export"}
---
1913 |               console.log(`---`);
1914 |               console.log(`expected ${name}:`);
1915 |               console.log(expected);
1916 |               console.log(`---`);
1917 |             }
1918 |             expect(result).toBe(expected);
                                  ^
error: expect(received).toBe(expected)

Expected: "{"value":"default export"}"
Received: "{"__esModule":true,"default":{"value":"default export"},"named":"named export"}"

      at <anonymous> (/workspace/bun/test/bundler/expectBundled.ts:1918:28)
(fail) bundler > cjs/__toESM_import_syntax_with_esModule [29.17ms]
(pass) bundler > cjs/__toESM_import_syntax_without_esModule [11.71ms]
(pass) bundler > cjs/__toESM_import_syntax_function [9.90ms]
(pass) bundler > cjs/__toESM_import_syntax_primitive [9.43ms]
(pass) bundler > cjs/__toESM_import_syntax_named_and_default [9.97ms]
... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/bundler_cjs.test.ts
bun test v1.4.1 (a6c4cc276)

test/bundler/bundler_cjs.test.ts:
(pass) bundler > cjs/__toESM_import_syntax_with_esModule [1024.06ms]
(pass) bundler > cjs/__toESM_import_syntax_without_esModule [473.45ms]
(pass) bundler > cjs/__toESM_import_syntax_function [489.71ms]
(pass) bundler > cjs/__toESM_import_syntax_primitive [494.25ms]
(pass) bundler > cjs/__toESM_import_syntax_named_and_default [388.89ms]
(pass) bundler > cjs/__toESM_import_syntax_namespace [381.97ms]
(pass) bundler > cjs/__toESM_target_node [389.92ms]
(pass) bundler > cjs/__toESM_target_browser [453.17ms]
(pass) bundler > cjs/__toESM_target_bun [481.14ms]
(pass) bundler > cjs/__toESM_format_esm [415.53ms]
(pass) bundler > cjs/__toESM_format_cjs_with_import [376.77ms]
(pass) bundler > cjs/__toESM_mjs_reexport [451.67ms]
(pass) bundler > cjs/__toESM_mjs_reexport_with_esModule [380.06ms]
(pass) bundler > cjs/__toESM_deep_reexport_chain [453.02ms]
(pass) bundler > cjs/__toESM_reexport_with_rename [430.08ms]
(pass) bundler > cjs/__toESM_default_pro
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     822e3b27f1
  features     baseline

23 deps, 131 codegen, 1172 objects in 647ms

ninja: Entering directory `/workspace/bun/build/release'
[1/1244] install /workspace/bun
bun install v1.4.1-canary.1 (a6c4cc276)

Checked 25 installs across 62 packages (no changes) [10.00ms]
[2/1244] gen bindgenv2
[3/1244] gen ErrorCode+*.h
[4/1244] install /workspace/bun/packages/bun-error
bun install v1.4.1-canary.1 (a6c4cc276)

Checked 1 install across 2 packages (no changes) [3.00ms]
[5/1244] fetch libjpeg-turbo
[libjpeg-turbo] up to date
[6/1217] gen ProcessBindingConstants.lut.h
Generating /workspace/bun/build/release/codegen/ProcessBindingConstants.lut.h from /workspace/bun/src/jsc/bindings/ProcessBindingConstants.cpp
[7/1217] gen bake.{client,server,error}.js
-> bake.client.js, bake.server.js, bake.error.js
[8/1217] fetch tinycc
[tinycc] up to date
[9/1216] install /workspace/bun/src/node-fallbacks
bun install v1.4.1-canary.1 (a6c4cc276)

Checked 111 installs across 104 packages (no changes) [15.00
... (truncated)
diff hotspot
src/resolver/dir_info.rs         |   9 ++
 src/resolver/resolver.rs         |  20 +++--
 src/resolver/result.rs           |  15 +---
 test/bundler/bundler_cjs.test.ts | 182 ++++++++++++++++++++++++++++++++++++++-
 4 files changed, 207 insertions(+), 19 deletions(-)

gate history · 1 passed · 0 rejected · iteration 0

evidence per changed file
file                              reads  edits  tests
src/resolver/dir_info.rs              3      4     33
src/resolver/resolver.rs              8      5     34
src/resolver/result.rs                1      1     33
test/bundler/bundler_cjs.test.ts      3     11     33

…ed or not

The bundler picks the __toESM interop from the importer's module type.
The resolver took that type from the package.json that the resolution
recorded, or else from enclosing_package_json, which skips a
package.json without a "name". So it missed a { "type": "module" }
with no "name", in a project root or in a dual package's
dist/esm/package.json. A default import of a CommonJS module with
__esModule then got exports.default instead of the whole
module.exports that Node gives.

DirInfo now carries package_json_for_module_type: the nearest
package.json in the directory or above it, with or without a "name".
finalize_result reads "type" from it for the primary path. esbuild
uses the same rule.
@robobun

robobun commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

Reproduced on main at 1b315c2 with the script in the Notes. bun build gives function/undefined. Node 26 and esbuild 0.25 give object/function.

Fail-before: 9 of the 10 new cases in test/bundler/bundler_cjs.test.ts fail with the src/ of main. Case 62 passes on both. It fails when the primary-path check in finalize_result is removed.

@coderabbitai

coderabbitai Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

  • Run on-demand review

On-demand reviews are free for the next 18 days. After that, they cost $0.25 per reviewed file.

Or wait 7 minutes for your next included review.

Check out review usage here.

View limit details

Limit details: You’ve used all 10 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Essentials

Run ID: 6d7dfc20-f552-4abf-86cd-3abfcf88eaa3

📥 Commits

Reviewing files that changed from the base of the PR and between b0cf0f4 and 822e3b2.

📒 Files selected for processing (4)
  • src/resolver/dir_info.rs
  • src/resolver/resolver.rs
  • src/resolver/result.rs
  • test/bundler/bundler_cjs.test.ts

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added the claude label Sep 3, 2026

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed this and didn't find any bugs. Because it changes core resolver semantics for module-type inference and the author flags a naming/semantics collision with open PR #40940 (same package_json_for_module_type field, different node_modules-boundary rule), a human should confirm the chosen rule and the coordination story before merge.

What was reviewed:

  • finalize_result: is_primary is taken before the read_dir_info let-else, so a failed primary dir read correctly prevents the secondary from setting module_type; extension override still runs afterward on path_pair.primary.
  • PathPair::iter skips is_disabled entries, so a disabled primary would tag the secondary as primary — same effective behavior as the old post-loop result.package_json read, not a regression.
  • dir_info_uncached: new field falls back to parent's value regardless of is_node_modules/name, matching the doc comment; enclosing_package_json untouched.
  • package_json_ref has no remaining callers; tests 53–62 follow the file's existing itBundled fixtures and cover the nearest/nameless/no-type/above-node_modules/fallback-path matrix.
Extended reasoning...

Overview

The PR adds DirInfo::package_json_for_module_type — the nearest package.json (named or not, not stopping at node_modules) — populated in dir_info_uncached by info.package_json().or(parent.package_json_for_module_type). finalize_result now reads module_type from this field for the primary path inside the path-pair loop (guarded by a core::mem::take-based is_primary flag), replacing the post-loop read of result.package_json. The now-orphaned Result::package_json_ref helper is deleted (grep confirms no other callers). Ten itBundled cases (53–62) are added to test/bundler/bundler_cjs.test.ts covering nameless nested markers via main/module/relative/subdir, nameless project root, nested commonjs under module root, nearest-without-type as scope boundary, lookup crossing node_modules, and the primary-only rule for the main fallback.

Security risks

None. This is bundler module-resolution metadata (which package.json's "type" applies to a .js file). No untrusted input parsing, no auth/crypto/permissions, no new syscalls or FFI. The new field is an Option<&'static PackageJSON> following the exact pattern of the neighboring enclosing_package_json.

Level of scrutiny

Medium-high. The code change is small and mechanically simple — one new inherited field, one relocated conditional — but it alters how the bundler classifies every .js/.ts file's module type, which feeds __toESM's Node-mode flag and thus the shape of default imports across the entire bundle. Resolver semantics are subtle, historically regression-prone, and this PR itself is fixing a regression from #41150. The author explicitly notes four open PRs in this area, including #40940 which adds a field with the same name but a node_modules-stopping rule and runtime consumers; test 61 pins the crossing behavior for the bundler, but a maintainer should decide whether one field can serve both or the runtime read sites need their own. That coordination is a human call.

Other factors

The is_primary flag is taken before the read_dir_info let-else continue, so a primary whose directory can't be read won't let the secondary set module_type — intentional per test 62. PathPairIter::next() skips is_disabled paths, so a disabled primary would make the secondary the first yielded path and it would see primary == true; this mirrors the old behavior (which read result.package_json set by whichever path ran through the loop) and is not a new defect. Test coverage is thorough and follows the file's existing conventions (itBundled, shared cjsDepFiles/logDefaultAndNamed fixtures, onAfterBundle bundle-text assertion on case 53). No CODEOWNERS entries match the changed paths. The exit reason was dry_streak, so the hunt ran to exhaustion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants