Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/resolver/dir_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,11 @@ pub struct DirInfo {
// ergonomics. If a write is ever added, retype to `Option<NonNull<_>>`.
pub enclosing_package_json: Option<&'static PackageJSON>,

/// Nearest `package.json` walking up from this directory, regardless of
/// whether it has a `"name"` or parsed successfully. This is Node's
/// package-scope boundary for module-type (`"type"` field) resolution.
pub nearest_package_json: Option<&'static PackageJSON>,

// `NonNull` (not `&'static`) so `enqueue_dependency_to_resolve` can write
// `package_manager_package_id` back through it without a const→mut
// provenance cast. Read via `.package_json_for_dependencies()`.
Expand Down Expand Up @@ -157,6 +162,7 @@ impl Default for DirInfo {
package_json_for_browser_field: None,
enclosing_tsconfig_json: None,
enclosing_package_json: None,
nearest_package_json: None,
package_json_for_dependencies: None,
abs_path: b"",
entries: Index::default(),
Expand Down
44 changes: 35 additions & 9 deletions src/resolver/package_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@ pub struct PackageJSON {

pub exports: Option<ExportsMap>,
pub imports: Option<ExportsMap>,

/// Set when the file is malformed JSON, a non-object, or has a non-string
/// `"type"`. Node throws `ERR_INVALID_PACKAGE_CONFIG` for `.js` files under
/// such a scope; the runtime loader surfaces this.
pub invalid: bool,
}

// hand-rolled `Default` because `#[derive(Default)]` would zero
Expand Down Expand Up @@ -165,6 +170,7 @@ impl Default for PackageJSON {
browser_map: BrowserMap::default(),
exports: None,
imports: None,
invalid: false,
}
}
}
Expand Down Expand Up @@ -335,6 +341,14 @@ impl FileSystemPackageJsonExt for crate::fs::FileSystem {
}

impl PackageJSON {
/// Poisoned (unparseable / non-object) placeholder returned by `parse()`.
/// Distinct from a parseable object whose `"type"` is not a string, which
/// also sets `invalid` but retains `source_contents`.
#[inline]
pub fn is_poisoned(&self) -> bool {
self.invalid && self.source_contents.is_empty()
}

pub fn parse_macros_json(
macros: js_ast::Expr,
log: &mut bun_ast::Log,
Expand Down Expand Up @@ -500,15 +514,27 @@ impl PackageJSON {
// On the success path it is *moved* (not leaked) into
// `package_json.source_contents` at the bottom of this fn, so the heap
// allocation lives for the life of the returned `PackageJSON`. On every
// early `return None` below `entry_contents` drops and frees normally, after
// `json_source` is already dead. `Box<[u8]>` heap address is stable
// across the move.
// early return below (the `invalid(...)` paths) `entry_contents` drops and
// frees normally after `json_source` is already dead; the poisoned entry's
// `source` uses `b""` and does not reference these bytes. `Box<[u8]>` heap
// address is stable across the move.
let contents_static: &'static [u8] = unsafe { bun_ptr::detach_lifetime(&entry_contents) };
let json_source = bun_ast::Source::init_path_string(package_json_path, contents_static);

// An unparseable package.json is still a package scope boundary in
// Node (`ERR_INVALID_PACKAGE_CONFIG`); return a poisoned entry so
// `nearest_package_json` stops here instead of inheriting the parent.
let invalid = |path: &'static [u8]| {
Some(PackageJSON {
source: bun_ast::Source::init_path_string(path, b""),
invalid: true,
..PackageJSON::default()
})
};
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved

let parsed_json = match r.caches.json.parse_package_json(r_log, &json_source) {
Ok(Some(v)) => v,
Ok(None) => return None,
Ok(None) => return invalid(package_json_path),
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
Err(err) => {
if cfg!(debug_assertions) {
Output::print_error(format_args!(
Expand All @@ -517,16 +543,13 @@ impl PackageJSON {
bstr::BStr::new(err.name())
));
}
return None;
return invalid(package_json_path);
}
};
let json: js_ast::Expr = parsed_json.root;

if !json.is_object() {
// Invalid package.json in node_modules is noisy.
// Let's just ignore it.
// (allocator.free dropped — entry.contents owned by `entry`)
return None;
return invalid(package_json_path);
}

let mut package_json = PackageJSON {
Expand All @@ -550,6 +573,7 @@ impl PackageJSON {
side_effects: SideEffects::Unspecified,
exports: None,
imports: None,
invalid: false,
};
// shadow as `&Source`; the owned value is reconstructed at the bottom
// (Source isn't `Clone`).
Expand Down Expand Up @@ -602,6 +626,8 @@ impl PackageJSON {
}
}
} else {
// Non-string `"type"` is `ERR_INVALID_PACKAGE_CONFIG` in Node.
package_json.invalid = true;
r_log.add_warning(
Some(json_source),
type_json.loc,
Expand Down
5 changes: 5 additions & 0 deletions src/resolver/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6217,6 +6217,7 @@ impl<'a> Resolver<'a> {
info.enclosing_package_json = info
.enclosing_package_json
.or(parent_.enclosing_package_json);
info.nearest_package_json = parent_.package_json().or(parent_.nearest_package_json);
info.package_json_for_dependencies = info
.package_json_for_dependencies
.or(parent_.package_json_for_dependencies);
Expand Down Expand Up @@ -6337,6 +6338,10 @@ impl<'a> Resolver<'a> {
};

if let Some(pkg) = info.package_json() {
// Any package.json (named, nameless, or invalid) is
// Node's module-type scope boundary.
info.nearest_package_json = Some(pkg);

if pkg.browser_map.count() > 0 {
info.enclosing_browser_scope = result.index;
info.package_json_for_browser_field = Some(pkg);
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/cli/filter_run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -764,7 +764,8 @@ pub(crate) fn run_scripts_with_filter(
bun_sys::Fd::invalid(),
None,
IncludeScripts::IncludeScripts,
) else {
)
.filter(|p| !p.is_poisoned()) else {
bun_core::warn!(
"Failed to read {}, skipping this workspace package\n",
bun_core::fmt::quote(&*package_json_path),
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/cli/multi_run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -891,7 +891,8 @@ pub(crate) fn run(ctx: &mut Command::ContextData) -> Result<core::convert::Infal
bun_sys::Fd::INVALID,
None,
IncludeScripts::IncludeScripts,
) else {
)
.filter(|p| !p.is_poisoned()) else {
continue;
};

Expand Down
36 changes: 27 additions & 9 deletions src/runtime/jsc_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1351,7 +1351,7 @@
Ok(Some(dir_info)) => {
dir_info
.package_json()
.or(dir_info.enclosing_package_json)
.or(dir_info.nearest_package_json)
.map(core::ptr::from_ref::<PackageJSON>)
}
_ => None,
Expand Down Expand Up @@ -2754,7 +2754,7 @@
.read_dir_info(source.path.name().dir)
} {
Ok(Some(dir_info)) => {
dir_info.package_json().or(dir_info.enclosing_package_json)
dir_info.package_json().or(dir_info.nearest_package_json)
}
_ => None,
}
Expand Down Expand Up @@ -3028,7 +3028,7 @@
match unsafe { (*jsc_vm).transpiler.resolver.read_dir_info(dir) } {
Ok(Some(dir_info)) => dir_info
.package_json()
.or(dir_info.enclosing_package_json)
.or(dir_info.nearest_package_json)
.map(|p| p.module_type),
_ => None,
}
Expand Down Expand Up @@ -3922,7 +3922,7 @@
// SAFETY: per fn contract — `transpiler.resolver` is a value field of
// the VM; `read_dir_info` is re-entrant on the JS thread.
match unsafe { (*jsc_vm).transpiler.resolver.read_dir_info(dir) } {
Ok(Some(dir_info)) => dir_info.package_json().or(dir_info.enclosing_package_json),
Ok(Some(dir_info)) => dir_info.package_json().or(dir_info.nearest_package_json),

Check warning on line 3925 in src/runtime/jsc_hooks.rs

View check run for this annotation

Claude / Claude Code Review

nearest_package_json at :3925 also feeds pkg_name for ALWAYS_SYNC_MODULES, not just module_type

Nit / for the record: `lr.package_json` populated here also feeds `pkg_name` at :4185-4187 → the `ALWAYS_SYNC_MODULES` check at :4217, not just `module_type` — so with `nearest_package_json`, a nameless intermediate (e.g. `dist/package.json`=`{"type":"commonjs"}`) between the file and the named package root now yields `pkg_name = None` for files in subdirectories beneath it. No observable effect today (only entry is `reflect-metadata`, whose layout is flat), and arguably this makes `pkg_name` *m
Comment thread
robobun marked this conversation as resolved.
Resolved
_ => None,
}
} else {
Expand Down Expand Up @@ -4155,11 +4155,29 @@
}
// regex /\.[jt]s$/
if ext.len() == b".ts".len() && (ext == b".js" || ext == b".ts") {
// Use the package.json module type if it exists.
break 'brk lr
.package_json
.map(|pkg| pkg.module_type)
.unwrap_or(ModuleType::Unknown);
// Node refuses `.js` under a malformed/non-string-`"type"`
// package.json; falling back to content-sniffing here would
// silently change module semantics vs Node.
if let Some(pkg) = lr.package_json {
if pkg.invalid {
let js = global_ref
.err(
bun_jsc::ErrCode::ERR_INVALID_PACKAGE_CONFIG,
format_args!(
"Invalid package config {}.",
bstr::BStr::new(pkg.source.path.text)
),
)
.to_js();
// SAFETY: per fn contract — `ret` is a valid out-param.
unsafe {
*ret = ErrorableResolvedSource::err(bun_core::err!("JSErrorObject"), js);
}
return ptr::null_mut();
}
break 'brk pkg.module_type;
}
break 'brk ModuleType::Unknown;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
// For JSX/TSX and other extensions, let the file contents decide.
ModuleType::Unknown
Expand Down
26 changes: 26 additions & 0 deletions test/cli/run/filter-workspace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -661,4 +661,30 @@ describe("bun", () => {
expect(stderr).toContain("skipping this workspace package");
expect(exitCode).toBe(0);
});

test('non-string "type" does not stop --filter from running scripts', async () => {
// "type" is a module-loader concern; a non-string value must not make
// `bun run --filter` skip the package (npm/pnpm/yarn all run it).
const dir = tempDirWithFiles("filter-bad-type", {
packages: {
foo: {
"package.json": `{"name":"foo","type":42,"scripts":{"go":"echo built-foo"}}`,
},
},
"package.json": JSON.stringify({ name: "ws", workspaces: ["packages/*"] }),
});

await using proc = Bun.spawn({
cmd: [bunExe(), "run", "--filter", "*", "go"],
cwd: dir,
env: { ...bunEnv, NO_COLOR: "1" },
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stdout).toContain("built-foo");
expect(stderr).not.toContain("Failed to read");
expect(stderr).not.toContain("skipping this workspace package");
expect(exitCode).toBe(0);
});
});
18 changes: 18 additions & 0 deletions test/cli/run/run_command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,24 @@ describe("bun", () => {
expect(exitCode).toBe(1);
});

test('non-string "type" does not hide scripts from bun run', () => {
// "type" is a module-loader concern; a non-string value must not make
// `bun run <script>` miss the package.json (npm/pnpm/yarn all run it).
using dir = tempDir("bad-type-scripts", {
"package.json": `{"name":"foo","type":42,"scripts":{"build":"echo built-ok"}}`,
});
const { exitCode, stdout, stderr } = spawnSync({
cwd: String(dir),
cmd: [bunExe(), "run", "build"],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
expect(stdout.toString()).toContain("built-ok");
expect(stderr.toString()).not.toMatch(/Script not found/);
expect(exitCode).toBe(0);
});

test("an empty-string script value is not a runnable script", () => {
using dir = tempDir("empty-script", {
"package.json": JSON.stringify({ scripts: { build: "" } }),
Expand Down
Loading
Loading