From b2f664c57d48156771c475af4fc13924cecaf04b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 24 Jul 2026 22:55:30 +0000 Subject: [PATCH 01/11] bundler: resolve __dirname/__filename at runtime for --target=bun/node Bundling a file that references __dirname or __filename with --target=bun (or --target=node) previously inlined the build machine's absolute source path as a string literal: var __dirname = "/home/user/project/src"; This leaked the build environment into the output, broke the bundle as soon as it was run from any other location, and made builds non-reproducible. The bundler now threads the target through to the parser and, for ESM output, emits `var __dirname = import.meta.dir` / `import.meta.path` (Bun) or `import.meta.dirname` / `import.meta.filename` (Node) so the values resolve to the output file's location at runtime. For CJS output on those targets the declaration is dropped entirely, letting references fall through to the module wrapper's __dirname/__filename parameters. Browser and IIFE output are unchanged (no runtime equivalent exists). Since --compile implies --target=bun this also gives compiled executables the virtual $bunfs path for __dirname/__filename, matching import.meta.dir. Fixes #4216. --- src/bundler/ParseTask.rs | 2 + src/bundler/transpiler.rs | 1 + src/js_parser/parse/parse_entry.rs | 201 +++++++++++++++++++--------- test/bundler/cli.test.ts | 22 ++- test/regression/issue/04216.test.ts | 169 +++++++++++++++++++++++ 5 files changed, 328 insertions(+), 67 deletions(-) create mode 100644 test/regression/issue/04216.test.ts diff --git a/src/bundler/ParseTask.rs b/src/bundler/ParseTask.rs index 86fc7ff7c7e4..06278a75a9e4 100644 --- a/src/bundler/ParseTask.rs +++ b/src/bundler/ParseTask.rs @@ -2557,6 +2557,8 @@ pub mod parse_worker { opts.ignore_dce_annotations = topts.ignore_dce_annotations && !task.source_index.is_runtime(); + opts.target = target; + // For files that are not user-specified entrypoints, set `import.meta.main` to `false`. // Entrypoints will have `import.meta.main` set as "unknown", unless we use `--compile`, // in which we inline `true`. diff --git a/src/bundler/transpiler.rs b/src/bundler/transpiler.rs index 8fb72a09715a..edafdf48cd6b 100644 --- a/src/bundler/transpiler.rs +++ b/src/bundler/transpiler.rs @@ -1555,6 +1555,7 @@ impl<'a> Transpiler<'a> { transform_only: self.options.transform_only, import_meta_main_value: None, lower_import_meta_main_for_node_js: false, + target, framework: None, repl_mode: self.options.repl_mode, }; diff --git a/src/js_parser/parse/parse_entry.rs b/src/js_parser/parse/parse_entry.rs index 9227cd63a118..935b8ef89d83 100644 --- a/src/js_parser/parse/parse_entry.rs +++ b/src/js_parser/parse/parse_entry.rs @@ -93,6 +93,12 @@ pub struct Options<'a> { pub import_meta_main_value: Option, pub lower_import_meta_main_for_node_js: bool, + /// The bundle target. Controls whether `__dirname` / `__filename` are + /// inlined as build-time string literals (browser) or lowered to + /// `import.meta.dir` / `import.meta.path` so they resolve at runtime + /// (Bun / Node ESM output). Only consulted when `bundle` is set. + pub target: js_ast::Target, + /// When using react fast refresh or server components, the framework is /// able to customize what import sources are used. pub framework: Option<&'a options::Framework>, // TYPE_ONLY: was bun_runtime::bake::Framework @@ -132,6 +138,7 @@ impl<'a> Default for Options<'a> { transform_only: false, import_meta_main_value: None, lower_import_meta_main_for_node_js: false, + target: js_ast::Target::Browser, framework: None, repl_mode: false, } @@ -215,6 +222,7 @@ impl<'a> Options<'a> { transform_only: self.transform_only, import_meta_main_value: self.import_meta_main_value, lower_import_meta_main_for_node_js: self.lower_import_meta_main_for_node_js, + target: self.target, framework: self.framework, repl_mode: self.repl_mode, } @@ -282,6 +290,7 @@ impl<'a> Options<'a> { transform_only: false, import_meta_main_value: None, lower_import_meta_main_for_node_js: false, + target: js_ast::Target::Browser, framework: None, repl_mode: false, }; @@ -1013,79 +1022,141 @@ impl<'a> Parser<'a> { // var __dirname = "foo/bar" // var __filename = "foo/bar/baz.js" // + // When bundling for Bun or Node, the build machine's absolute source + // path is the wrong value: the bundle will typically run from a + // different location (and on a different machine). For ESM output we + // instead emit `var __dirname = import.meta.dir` (Bun) or + // `import.meta.dirname` (Node), so it resolves to the output file's + // directory at runtime. For CJS output on those targets the runtime + // already provides `__dirname`/`__filename` via the module wrapper, so + // we emit nothing and let references fall through. + // + // https://github.com/oven-sh/bun/issues/4216 if p.options.bundle || !p.options.features.commonjs_at_runtime { if uses_dirname || uses_filename { - let count = (uses_dirname as usize) + (uses_filename as usize); - let mut declared_symbols = - bun_ast::DeclaredSymbolList::init_capacity(count).expect("unreachable"); - let decls = p - .arena - .alloc_slice_fill_with::(count, |_| G::Decl::default()); - if uses_dirname { - decls[0] = G::Decl { - binding: p.b( - B::Identifier { - r#ref: p.dirname_ref, - }, - bun_ast::Loc::EMPTY, - ), - value: Some(p.new_expr( - E::String { - data: p.source.path.name().dir.into(), - ..Default::default() - }, - bun_ast::Loc::EMPTY, - )), + // `(dir_property, path_property)` — `Some` when the target + // runtime exposes these on `import.meta`, `None` to fall back + // to the build-time string literal. + let import_meta_names: Option<(&'static [u8], &'static [u8])> = + if p.options.bundle && p.options.output_format == options::Format::Esm { + if p.options.target.is_bun() { + Some((b"dir", b"path")) + } else if p.options.target.is_node() { + Some((b"dirname", b"filename")) + } else { + None + } + } else { + None }; - declared_symbols.append_assume_capacity(DeclaredSymbol { - ref_: p.dirname_ref, - is_top_level: true, - }); - } - if uses_filename { - decls[uses_dirname as usize] = G::Decl { - binding: p.b( - B::Identifier { - r#ref: p.filename_ref, - }, - bun_ast::Loc::EMPTY, - ), - value: Some(p.new_expr( - E::String { - data: p.source.path.text.into(), + + let defer_to_cjs_wrapper = p.options.bundle + && p.options.output_format == options::Format::Cjs + && (p.options.target.is_bun() || p.options.target.is_node()); + + if !defer_to_cjs_wrapper { + let count = (uses_dirname as usize) + (uses_filename as usize); + let mut declared_symbols = + bun_ast::DeclaredSymbolList::init_capacity(count).expect("unreachable"); + let decls = p + .arena + .alloc_slice_fill_with::(count, |_| G::Decl::default()); + if uses_dirname { + let value = if let Some((dir_name, _)) = import_meta_names { + let import_meta = p.new_expr(E::ImportMeta {}, bun_ast::Loc::EMPTY); + p.new_expr( + E::Dot { + name: dir_name.into(), + name_loc: bun_ast::Loc::EMPTY, + target: import_meta, + can_be_removed_if_unused: true, + ..Default::default() + }, + bun_ast::Loc::EMPTY, + ) + } else { + p.new_expr( + E::String { + data: p.source.path.name().dir.into(), + ..Default::default() + }, + bun_ast::Loc::EMPTY, + ) + }; + decls[0] = G::Decl { + binding: p.b( + B::Identifier { + r#ref: p.dirname_ref, + }, + bun_ast::Loc::EMPTY, + ), + value: Some(value), + }; + declared_symbols.append_assume_capacity(DeclaredSymbol { + ref_: p.dirname_ref, + is_top_level: true, + }); + } + if uses_filename { + let value = if let Some((_, path_name)) = import_meta_names { + let import_meta = p.new_expr(E::ImportMeta {}, bun_ast::Loc::EMPTY); + p.new_expr( + E::Dot { + name: path_name.into(), + name_loc: bun_ast::Loc::EMPTY, + target: import_meta, + can_be_removed_if_unused: true, + ..Default::default() + }, + bun_ast::Loc::EMPTY, + ) + } else { + p.new_expr( + E::String { + data: p.source.path.text.into(), + ..Default::default() + }, + bun_ast::Loc::EMPTY, + ) + }; + decls[uses_dirname as usize] = G::Decl { + binding: p.b( + B::Identifier { + r#ref: p.filename_ref, + }, + bun_ast::Loc::EMPTY, + ), + value: Some(value), + }; + declared_symbols.append_assume_capacity(DeclaredSymbol { + ref_: p.filename_ref, + is_top_level: true, + }); + } + + let part_stmts = p.arena.alloc_slice_fill_with(1, |_| { + p.s( + S::Local { + kind: js_ast::LocalKind::KVar, + decls: { + let mut dl = G::DeclList::init_capacity(decls.len()); + for d in decls.iter_mut() { + dl.append_assume_capacity(core::mem::take(d)); + } + dl + }, ..Default::default() }, bun_ast::Loc::EMPTY, - )), - }; - declared_symbols.append_assume_capacity(DeclaredSymbol { - ref_: p.filename_ref, - is_top_level: true, + ) + }); + before.push(js_ast::Part { + stmts: part_stmts.into(), + declared_symbols, + tag: bun_ast::PartTag::DirnameFilename, + ..Default::default() }); } - - let part_stmts = p.arena.alloc_slice_fill_with(1, |_| { - p.s( - S::Local { - kind: js_ast::LocalKind::KVar, - decls: { - let mut dl = G::DeclList::init_capacity(decls.len()); - for d in decls.iter_mut() { - dl.append_assume_capacity(core::mem::take(d)); - } - dl - }, - ..Default::default() - }, - bun_ast::Loc::EMPTY, - ) - }); - before.push(js_ast::Part { - stmts: part_stmts.into(), - declared_symbols, - tag: bun_ast::PartTag::DirnameFilename, - ..Default::default() - }); uses_dirname = false; uses_filename = false; } diff --git a/test/bundler/cli.test.ts b/test/bundler/cli.test.ts index 350841445132..d068b15dbed7 100644 --- a/test/bundler/cli.test.ts +++ b/test/bundler/cli.test.ts @@ -186,6 +186,9 @@ console.log(utils());`, }); const baseDir = baseDirPath + ""; + // `--compile` bundles for Bun's runtime, so `__dirname`/`__filename` + // resolve to the compiled executable's virtual `$bunfs` path at runtime + // instead of the build machine's source path (#4216). const { exited } = Bun.spawn({ cmd: [ bunExe(), @@ -211,8 +214,23 @@ console.log(utils());`, const text = await proc.stdout.text(); await proc.exited; - expect(text).toContain(path.join(baseDir, "我") + "\n"); - expect(text).toContain(path.join(baseDir, "我", "我.ts") + "\n"); + const bunfsRoot = isWindows ? "B:\\~BUN\\root" : "/$bunfs/root"; + expect(text).toBe(bunfsRoot + "\n" + path.join(bunfsRoot, "exe.exe") + "\n"); + + // The browser target has no runtime source for `__dirname`, so it still + // inlines the source path as a string literal. Exercise the UTF-8 path + // round-trip this test originally covered there. + await using browserBuild = Bun.spawn({ + cmd: [bunExe(), "build", path.join(baseDir, "我/我.ts"), "--target=browser"], + env: bunEnv, + cwd: baseDir, + stdout: "pipe", + stderr: "pipe", + }); + const [browserOut, browserExit] = await Promise.all([browserBuild.stdout.text(), browserBuild.exited]); + expect(browserOut).toContain(JSON.stringify(path.join(baseDir, "我"))); + expect(browserOut).toContain(JSON.stringify(path.join(baseDir, "我", "我.ts"))); + expect(browserExit).toBe(0); }); test.skipIf(!isWindows)("should be able to handle pretty path when using pnpm + #14685", async () => { diff --git a/test/regression/issue/04216.test.ts b/test/regression/issue/04216.test.ts new file mode 100644 index 000000000000..19b06e21e381 --- /dev/null +++ b/test/regression/issue/04216.test.ts @@ -0,0 +1,169 @@ +// https://github.com/oven-sh/bun/issues/4216 +// `bun build --target=bun` used to inline __dirname/__filename as string +// literals containing the build machine's absolute source path. The bundle +// would then only work from the exact location it was built in. +import { describe, expect, test } from "bun:test"; +import { bunEnv, bunExe, tempDir } from "harness"; +import { cpSync } from "node:fs"; +import { join } from "node:path"; + +describe("__dirname/__filename resolve at runtime in bundled output", () => { + for (const target of ["bun", "node"] as const) { + test.concurrent(`--target=${target}`, async () => { + using src = tempDir("issue-4216-src", { + "nested/entry.js": ` + const dep = require("./dep.cjs"); + console.log(JSON.stringify({ + dirname: __dirname, + filename: __filename, + depDirname: dep.dir, + depFilename: dep.file, + })); + `, + "nested/dep.cjs": ` + module.exports = { dir: __dirname, file: __filename }; + `, + }); + const srcDir = String(src); + + // Build into a subdirectory of the source dir. + await using build = Bun.spawn({ + cmd: [ + bunExe(), + "build", + join(srcDir, "nested/entry.js"), + "--target", + target, + "--outfile", + join(srcDir, "build/bundle.mjs"), + ], + env: bunEnv, + cwd: srcDir, + stdout: "pipe", + stderr: "pipe", + }); + const [buildStderr, buildExit] = await Promise.all([build.stderr.text(), build.exited]); + expect(buildStderr).not.toContain("error:"); + expect(buildExit).toBe(0); + + const bundleSource = await Bun.file(join(srcDir, "build/bundle.mjs")).text(); + // The build machine's absolute source path must not appear in the output. + expect(bundleSource).not.toContain(join(srcDir, "nested")); + + // Copy the bundle somewhere unrelated to the build directory and run it + // from there, so a hardcoded build-time path cannot accidentally resolve. + using runDir = tempDir("issue-4216-run", {}); + const runPath = join(String(runDir), "moved.mjs"); + cpSync(join(srcDir, "build/bundle.mjs"), runPath); + + await using proc = Bun.spawn({ + cmd: [bunExe(), runPath], + env: bunEnv, + cwd: String(runDir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([ + proc.stdout.text(), + proc.stderr.text(), + proc.exited, + ]); + expect(stderr).toBe(""); + const out = JSON.parse(stdout.trim()); + // All four should point at the *runtime* bundle location, not the source + // tree. The wrapped CJS dep sees the same chunk-level `import.meta` as the + // entry, so its __dirname/__filename match. + expect(out).toEqual({ + dirname: String(runDir), + filename: runPath, + depDirname: String(runDir), + depFilename: runPath, + }); + expect(exitCode).toBe(0); + }); + + test.concurrent(`--target=${target} --format=cjs`, async () => { + using src = tempDir("issue-4216-cjs", { + "entry.js": ` + console.log(JSON.stringify({ dirname: __dirname, filename: __filename })); + `, + }); + const srcDir = String(src); + + await using build = Bun.spawn({ + cmd: [ + bunExe(), + "build", + join(srcDir, "entry.js"), + "--target", + target, + "--format=cjs", + "--outfile", + join(srcDir, "bundle.cjs"), + ], + env: bunEnv, + cwd: srcDir, + stdout: "pipe", + stderr: "pipe", + }); + const [buildStderr, buildExit] = await Promise.all([build.stderr.text(), build.exited]); + expect(buildStderr).not.toContain("error:"); + expect(buildExit).toBe(0); + + // The output must not re-declare __dirname/__filename with the build path; + // the CJS wrapper (Bun's `@bun-cjs` or Node's native module wrapper) + // already provides them. + const bundleSource = await Bun.file(join(srcDir, "bundle.cjs")).text(); + expect(bundleSource).not.toContain(srcDir); + + using runDir = tempDir("issue-4216-cjs-run", {}); + const runPath = join(String(runDir), "moved.cjs"); + cpSync(join(srcDir, "bundle.cjs"), runPath); + + await using proc = Bun.spawn({ + cmd: [bunExe(), runPath], + env: bunEnv, + cwd: String(runDir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([ + proc.stdout.text(), + proc.stderr.text(), + proc.exited, + ]); + expect(stderr).toBe(""); + expect(JSON.parse(stdout.trim())).toEqual({ + dirname: String(runDir), + filename: runPath, + }); + expect(exitCode).toBe(0); + }); + } + + // --target=browser has no runtime `import.meta.dir` equivalent, so it keeps + // the legacy behavior of inlining the build-time path as a string literal. + test.concurrent("--target=browser still inlines a string literal", async () => { + using src = tempDir("issue-4216-browser", { + "entry.js": `console.log(__dirname, __filename);`, + }); + const srcDir = String(src); + + await using build = Bun.spawn({ + cmd: [bunExe(), "build", join(srcDir, "entry.js"), "--target", "browser"], + env: bunEnv, + cwd: srcDir, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([ + build.stdout.text(), + build.stderr.text(), + build.exited, + ]); + expect(stderr).not.toContain("error:"); + expect(stdout).toContain("var __dirname ="); + expect(stdout).not.toContain("import.meta"); + expect(exitCode).toBe(0); + }); +}); From fc608f39a46b7b06be8bf26d93ff2e8830e6a943 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Fri, 24 Jul 2026 22:58:15 +0000 Subject: [PATCH 02/11] [autofix.ci] apply automated fixes --- test/regression/issue/04216.test.ts | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/test/regression/issue/04216.test.ts b/test/regression/issue/04216.test.ts index 19b06e21e381..6098a5a0b12e 100644 --- a/test/regression/issue/04216.test.ts +++ b/test/regression/issue/04216.test.ts @@ -63,11 +63,7 @@ describe("__dirname/__filename resolve at runtime in bundled output", () => { stdout: "pipe", stderr: "pipe", }); - const [stdout, stderr, exitCode] = await Promise.all([ - proc.stdout.text(), - proc.stderr.text(), - proc.exited, - ]); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); expect(stderr).toBe(""); const out = JSON.parse(stdout.trim()); // All four should point at the *runtime* bundle location, not the source @@ -127,11 +123,7 @@ describe("__dirname/__filename resolve at runtime in bundled output", () => { stdout: "pipe", stderr: "pipe", }); - const [stdout, stderr, exitCode] = await Promise.all([ - proc.stdout.text(), - proc.stderr.text(), - proc.exited, - ]); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); expect(stderr).toBe(""); expect(JSON.parse(stdout.trim())).toEqual({ dirname: String(runDir), @@ -156,11 +148,7 @@ describe("__dirname/__filename resolve at runtime in bundled output", () => { stdout: "pipe", stderr: "pipe", }); - const [stdout, stderr, exitCode] = await Promise.all([ - build.stdout.text(), - build.stderr.text(), - build.exited, - ]); + const [stdout, stderr, exitCode] = await Promise.all([build.stdout.text(), build.stderr.text(), build.exited]); expect(stderr).not.toContain("error:"); expect(stdout).toContain("var __dirname ="); expect(stdout).not.toContain("import.meta"); From f4f4621936dacc93bbc8a8b7f4499abec189f4a3 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 24 Jul 2026 22:59:19 +0000 Subject: [PATCH 03/11] set has_import_meta when emitting import.meta.dir for __dirname The bytecode module-info path in postProcessJSChunk derives contains_import_meta from the AST flag rather than the printer, so set it when the post-visit __dirname/__filename lowering introduces an import.meta reference. --- src/js_parser/parse/parse_entry.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/js_parser/parse/parse_entry.rs b/src/js_parser/parse/parse_entry.rs index 935b8ef89d83..fa52799493c0 100644 --- a/src/js_parser/parse/parse_entry.rs +++ b/src/js_parser/parse/parse_entry.rs @@ -1054,6 +1054,10 @@ impl<'a> Parser<'a> { && p.options.output_format == options::Format::Cjs && (p.options.target.is_bun() || p.options.target.is_node()); + if import_meta_names.is_some() { + p.has_import_meta = true; + } + if !defer_to_cjs_wrapper { let count = (uses_dirname as usize) + (uses_filename as usize); let mut declared_symbols = From 6cc8318c2d4d3d32605b9ef93275dd722be155a1 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 24 Jul 2026 23:22:58 +0000 Subject: [PATCH 04/11] address review: dedupe dirname/filename injection, move tests out of regression dir - Extract import_meta_dot and inject_dirname_filename_part helpers shared by the bundle-time and runtime lowering paths so declaration metadata stays identical in both - Move the issue 4216 suite into test/bundler/cli.test.ts: the hardcoded path behavior was never correct, so it is not a regression - Run --target=node bundles under a real node binary (skip if absent) - Drain stdout/stderr on every build spawn --- src/js_parser/parse/parse_entry.rs | 297 +++++++++++----------------- test/bundler/cli.test.ts | 174 +++++++++++++++- test/regression/issue/04216.test.ts | 157 --------------- 3 files changed, 291 insertions(+), 337 deletions(-) delete mode 100644 test/regression/issue/04216.test.ts diff --git a/src/js_parser/parse/parse_entry.rs b/src/js_parser/parse/parse_entry.rs index fa52799493c0..82fba16e7d68 100644 --- a/src/js_parser/parse/parse_entry.rs +++ b/src/js_parser/parse/parse_entry.rs @@ -1059,107 +1059,33 @@ impl<'a> Parser<'a> { } if !defer_to_cjs_wrapper { - let count = (uses_dirname as usize) + (uses_filename as usize); - let mut declared_symbols = - bun_ast::DeclaredSymbolList::init_capacity(count).expect("unreachable"); - let decls = p - .arena - .alloc_slice_fill_with::(count, |_| G::Decl::default()); - if uses_dirname { - let value = if let Some((dir_name, _)) = import_meta_names { - let import_meta = p.new_expr(E::ImportMeta {}, bun_ast::Loc::EMPTY); - p.new_expr( - E::Dot { - name: dir_name.into(), - name_loc: bun_ast::Loc::EMPTY, - target: import_meta, - can_be_removed_if_unused: true, - ..Default::default() - }, - bun_ast::Loc::EMPTY, - ) - } else { - p.new_expr( - E::String { - data: p.source.path.name().dir.into(), - ..Default::default() - }, - bun_ast::Loc::EMPTY, - ) - }; - decls[0] = G::Decl { - binding: p.b( - B::Identifier { - r#ref: p.dirname_ref, - }, - bun_ast::Loc::EMPTY, - ), - value: Some(value), - }; - declared_symbols.append_assume_capacity(DeclaredSymbol { - ref_: p.dirname_ref, - is_top_level: true, - }); - } - if uses_filename { - let value = if let Some((_, path_name)) = import_meta_names { - let import_meta = p.new_expr(E::ImportMeta {}, bun_ast::Loc::EMPTY); - p.new_expr( - E::Dot { - name: path_name.into(), - name_loc: bun_ast::Loc::EMPTY, - target: import_meta, - can_be_removed_if_unused: true, - ..Default::default() - }, - bun_ast::Loc::EMPTY, - ) - } else { - p.new_expr( - E::String { - data: p.source.path.text.into(), - ..Default::default() - }, - bun_ast::Loc::EMPTY, - ) - }; - decls[uses_dirname as usize] = G::Decl { - binding: p.b( - B::Identifier { - r#ref: p.filename_ref, - }, - bun_ast::Loc::EMPTY, - ), - value: Some(value), - }; - declared_symbols.append_assume_capacity(DeclaredSymbol { - ref_: p.filename_ref, - is_top_level: true, - }); - } - - let part_stmts = p.arena.alloc_slice_fill_with(1, |_| { - p.s( - S::Local { - kind: js_ast::LocalKind::KVar, - decls: { - let mut dl = G::DeclList::init_capacity(decls.len()); - for d in decls.iter_mut() { - dl.append_assume_capacity(core::mem::take(d)); - } - dl - }, + let dirname_value = if !uses_dirname { + None + } else if let Some((dir_name, _)) = import_meta_names { + Some(import_meta_dot(p, dir_name)) + } else { + Some(p.new_expr( + E::String { + data: p.source.path.name().dir.into(), ..Default::default() }, bun_ast::Loc::EMPTY, - ) - }); - before.push(js_ast::Part { - stmts: part_stmts.into(), - declared_symbols, - tag: bun_ast::PartTag::DirnameFilename, - ..Default::default() - }); + )) + }; + let filename_value = if !uses_filename { + None + } else if let Some((_, path_name)) = import_meta_names { + Some(import_meta_dot(p, path_name)) + } else { + Some(p.new_expr( + E::String { + data: p.source.path.text.into(), + ..Default::default() + }, + bun_ast::Loc::EMPTY, + )) + }; + inject_dirname_filename_part(p, &mut before, dirname_value, filename_value); } uses_dirname = false; uses_filename = false; @@ -1755,85 +1681,10 @@ impl<'a> Parser<'a> { // if exports_kind == js_ast::ExportsKind::Esm && (uses_dirname || uses_filename) { debug_assert!(!p.options.bundle); - let count = (uses_dirname as usize) + (uses_filename as usize); - let mut declared_symbols = - bun_ast::DeclaredSymbolList::init_capacity(count).expect("unreachable"); - let decls = p - .arena - .alloc_slice_fill_with::(count, |_| G::Decl::default()); - if uses_dirname { - // var __dirname = import.meta - let import_meta = p.new_expr(E::ImportMeta {}, bun_ast::Loc::EMPTY); - decls[0] = G::Decl { - binding: p.b( - B::Identifier { - r#ref: p.dirname_ref, - }, - bun_ast::Loc::EMPTY, - ), - value: Some(p.new_expr( - E::Dot { - name: b"dir".into(), - name_loc: bun_ast::Loc::EMPTY, - target: import_meta, - ..Default::default() - }, - bun_ast::Loc::EMPTY, - )), - }; - declared_symbols.append_assume_capacity(DeclaredSymbol { - ref_: p.dirname_ref, - is_top_level: true, - }); - } - if uses_filename { - // var __filename = import.meta.path - let import_meta = p.new_expr(E::ImportMeta {}, bun_ast::Loc::EMPTY); - decls[uses_dirname as usize] = G::Decl { - binding: p.b( - B::Identifier { - r#ref: p.filename_ref, - }, - bun_ast::Loc::EMPTY, - ), - value: Some(p.new_expr( - E::Dot { - name: b"path".into(), - name_loc: bun_ast::Loc::EMPTY, - target: import_meta, - ..Default::default() - }, - bun_ast::Loc::EMPTY, - )), - }; - declared_symbols.append_assume_capacity(DeclaredSymbol { - ref_: p.filename_ref, - is_top_level: true, - }); - } - - let part_stmts = p.arena.alloc_slice_fill_with(1, |_| { - p.s( - S::Local { - kind: js_ast::LocalKind::KVar, - decls: { - let mut dl = G::DeclList::init_capacity(decls.len()); - for d in decls.iter_mut() { - dl.append_assume_capacity(core::mem::take(d)); - } - dl - }, - ..Default::default() - }, - bun_ast::Loc::EMPTY, - ) - }); - before.push(js_ast::Part { - stmts: part_stmts.into(), - declared_symbols, - tag: bun_ast::PartTag::DirnameFilename, - ..Default::default() - }); + // var __dirname = import.meta.dir, __filename = import.meta.path + let dirname_value = uses_dirname.then(|| import_meta_dot(p, b"dir")); + let filename_value = uses_filename.then(|| import_meta_dot(p, b"path")); + inject_dirname_filename_part(p, &mut before, dirname_value, filename_value); } if exports_kind == js_ast::ExportsKind::Esm @@ -2342,6 +2193,98 @@ struct PragmaState { seen_bytecode: bool, } +/// `import.meta.`, marked side-effect-free so the declaration it +/// initializes can be dropped if the symbol ends up unused. +fn import_meta_dot( + p: &mut P<'_, TS, SCAN_ONLY>, + name: &'static [u8], +) -> Expr { + let import_meta = p.new_expr(E::ImportMeta {}, bun_ast::Loc::EMPTY); + p.new_expr( + E::Dot { + name: name.into(), + name_loc: bun_ast::Loc::EMPTY, + target: import_meta, + can_be_removed_if_unused: true, + ..Default::default() + }, + bun_ast::Loc::EMPTY, + ) +} + +/// Injects `var __dirname = ..., __filename = ...` as its own +/// `PartTag::DirnameFilename` part. Shared by the bundle-time and runtime +/// lowering paths so their declaration metadata cannot drift; each caller +/// supplies only the value expressions (`None` = symbol unused, no decl). +fn inject_dirname_filename_part<'a, const TS: bool, const SCAN_ONLY: bool>( + p: &mut P<'a, TS, SCAN_ONLY>, + before: &mut BumpVec<'a, js_ast::Part>, + dirname_value: Option, + filename_value: Option, +) { + let count = (dirname_value.is_some() as usize) + (filename_value.is_some() as usize); + let mut declared_symbols = + bun_ast::DeclaredSymbolList::init_capacity(count).expect("unreachable"); + let decls = p + .arena + .alloc_slice_fill_with::(count, |_| G::Decl::default()); + let mut decl_i = 0; + if let Some(value) = dirname_value { + decls[decl_i] = G::Decl { + binding: p.b( + B::Identifier { + r#ref: p.dirname_ref, + }, + bun_ast::Loc::EMPTY, + ), + value: Some(value), + }; + declared_symbols.append_assume_capacity(DeclaredSymbol { + ref_: p.dirname_ref, + is_top_level: true, + }); + decl_i += 1; + } + if let Some(value) = filename_value { + decls[decl_i] = G::Decl { + binding: p.b( + B::Identifier { + r#ref: p.filename_ref, + }, + bun_ast::Loc::EMPTY, + ), + value: Some(value), + }; + declared_symbols.append_assume_capacity(DeclaredSymbol { + ref_: p.filename_ref, + is_top_level: true, + }); + } + + let part_stmts = p.arena.alloc_slice_fill_with(1, |_| { + p.s( + S::Local { + kind: js_ast::LocalKind::KVar, + decls: { + let mut dl = G::DeclList::init_capacity(decls.len()); + for d in decls.iter_mut() { + dl.append_assume_capacity(core::mem::take(d)); + } + dl + }, + ..Default::default() + }, + bun_ast::Loc::EMPTY, + ) + }); + before.push(js_ast::Part { + stmts: part_stmts.into(), + declared_symbols, + tag: bun_ast::PartTag::DirnameFilename, + ..Default::default() + }); +} + #[cfg(target_arch = "wasm32")] pub type MacroContext = Option<*mut c_void>; #[cfg(not(target_arch = "wasm32"))] diff --git a/test/bundler/cli.test.ts b/test/bundler/cli.test.ts index d068b15dbed7..fdc3a53c7012 100644 --- a/test/bundler/cli.test.ts +++ b/test/bundler/cli.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe, isWindows, tempDir, tmpdirSync } from "harness"; -import fs, { mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { bunEnv, bunExe, isWindows, nodeExe, tempDir, tmpdirSync } from "harness"; +import fs, { cpSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import path, { join } from "node:path"; describe.concurrent( @@ -227,7 +227,12 @@ console.log(utils());`, stdout: "pipe", stderr: "pipe", }); - const [browserOut, browserExit] = await Promise.all([browserBuild.stdout.text(), browserBuild.exited]); + const [browserOut, browserErr, browserExit] = await Promise.all([ + browserBuild.stdout.text(), + browserBuild.stderr.text(), + browserBuild.exited, + ]); + expect(browserErr).not.toContain("error:"); expect(browserOut).toContain(JSON.stringify(path.join(baseDir, "我"))); expect(browserOut).toContain(JSON.stringify(path.join(baseDir, "我", "我.ts"))); expect(browserExit).toBe(0); @@ -535,3 +540,166 @@ describe("CLI argument error messages", () => { expect(exitCode).toBe(1); }); }); + +// https://github.com/oven-sh/bun/issues/4216 +describe.concurrent("__dirname/__filename resolve at runtime in bundled output", () => { + for (const target of ["bun", "node"] as const) { + // Node-target bundles run under a real `node` so the emitted + // `import.meta.dirname`/`filename` are exercised on the runtime they + // target, not just on Bun's implementation of them. + const missingNode = target === "node" && !nodeExe(); + + test.skipIf(missingNode)(`--target=${target}`, async () => { + using src = tempDir("dirname-4216-src", { + "nested/entry.js": ` + const dep = require("./dep.cjs"); + console.log(JSON.stringify({ + dirname: __dirname, + filename: __filename, + depDirname: dep.dir, + depFilename: dep.file, + })); + `, + "nested/dep.cjs": ` + module.exports = { dir: __dirname, file: __filename }; + `, + }); + const srcDir = String(src); + + // Build into a subdirectory of the source dir. + await using build = Bun.spawn({ + cmd: [ + bunExe(), + "build", + join(srcDir, "nested/entry.js"), + "--target", + target, + "--outfile", + join(srcDir, "build/bundle.mjs"), + ], + env: bunEnv, + cwd: srcDir, + stdout: "pipe", + stderr: "pipe", + }); + const [, buildStderr, buildExit] = await Promise.all([ + build.stdout.text(), + build.stderr.text(), + build.exited, + ]); + expect(buildStderr).not.toContain("error:"); + expect(buildExit).toBe(0); + + const bundleSource = await Bun.file(join(srcDir, "build/bundle.mjs")).text(); + // The build machine's absolute source path must not appear in the output. + expect(bundleSource).not.toContain(join(srcDir, "nested")); + + // Copy the bundle somewhere unrelated to the build directory and run it + // from there, so a hardcoded build-time path cannot accidentally resolve. + using runDir = tempDir("dirname-4216-run", {}); + const runPath = join(String(runDir), "moved.mjs"); + cpSync(join(srcDir, "build/bundle.mjs"), runPath); + + await using proc = Bun.spawn({ + cmd: [target === "node" ? nodeExe()! : bunExe(), runPath], + env: bunEnv, + cwd: String(runDir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + const out = JSON.parse(stdout.trim()); + // All four should point at the *runtime* bundle location, not the source + // tree. The wrapped CJS dep sees the same chunk-level `import.meta` as the + // entry, so its __dirname/__filename match. + expect(out).toEqual({ + dirname: String(runDir), + filename: runPath, + depDirname: String(runDir), + depFilename: runPath, + }); + expect(exitCode).toBe(0); + }); + + test.skipIf(missingNode)(`--target=${target} --format=cjs`, async () => { + using src = tempDir("dirname-4216-cjs", { + "entry.js": ` + console.log(JSON.stringify({ dirname: __dirname, filename: __filename })); + `, + }); + const srcDir = String(src); + + await using build = Bun.spawn({ + cmd: [ + bunExe(), + "build", + join(srcDir, "entry.js"), + "--target", + target, + "--format=cjs", + "--outfile", + join(srcDir, "bundle.cjs"), + ], + env: bunEnv, + cwd: srcDir, + stdout: "pipe", + stderr: "pipe", + }); + const [, buildStderr, buildExit] = await Promise.all([ + build.stdout.text(), + build.stderr.text(), + build.exited, + ]); + expect(buildStderr).not.toContain("error:"); + expect(buildExit).toBe(0); + + // The output must not re-declare __dirname/__filename with the build path; + // the CJS wrapper (Bun's `@bun-cjs` or Node's native module wrapper) + // already provides them. + const bundleSource = await Bun.file(join(srcDir, "bundle.cjs")).text(); + expect(bundleSource).not.toContain(srcDir); + + using runDir = tempDir("dirname-4216-cjs-run", {}); + const runPath = join(String(runDir), "moved.cjs"); + cpSync(join(srcDir, "bundle.cjs"), runPath); + + await using proc = Bun.spawn({ + cmd: [target === "node" ? nodeExe()! : bunExe(), runPath], + env: bunEnv, + cwd: String(runDir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(JSON.parse(stdout.trim())).toEqual({ + dirname: String(runDir), + filename: runPath, + }); + expect(exitCode).toBe(0); + }); + } + + // --target=browser has no runtime `import.meta.dir` equivalent, so it keeps + // the legacy behavior of inlining the build-time path as a string literal. + test.concurrent("--target=browser still inlines a string literal", async () => { + using src = tempDir("dirname-4216-browser", { + "entry.js": `console.log(__dirname, __filename);`, + }); + const srcDir = String(src); + + await using build = Bun.spawn({ + cmd: [bunExe(), "build", join(srcDir, "entry.js"), "--target", "browser"], + env: bunEnv, + cwd: srcDir, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([build.stdout.text(), build.stderr.text(), build.exited]); + expect(stderr).not.toContain("error:"); + expect(stdout).toContain("var __dirname ="); + expect(stdout).not.toContain("import.meta"); + expect(exitCode).toBe(0); + }); +}); diff --git a/test/regression/issue/04216.test.ts b/test/regression/issue/04216.test.ts deleted file mode 100644 index 6098a5a0b12e..000000000000 --- a/test/regression/issue/04216.test.ts +++ /dev/null @@ -1,157 +0,0 @@ -// https://github.com/oven-sh/bun/issues/4216 -// `bun build --target=bun` used to inline __dirname/__filename as string -// literals containing the build machine's absolute source path. The bundle -// would then only work from the exact location it was built in. -import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe, tempDir } from "harness"; -import { cpSync } from "node:fs"; -import { join } from "node:path"; - -describe("__dirname/__filename resolve at runtime in bundled output", () => { - for (const target of ["bun", "node"] as const) { - test.concurrent(`--target=${target}`, async () => { - using src = tempDir("issue-4216-src", { - "nested/entry.js": ` - const dep = require("./dep.cjs"); - console.log(JSON.stringify({ - dirname: __dirname, - filename: __filename, - depDirname: dep.dir, - depFilename: dep.file, - })); - `, - "nested/dep.cjs": ` - module.exports = { dir: __dirname, file: __filename }; - `, - }); - const srcDir = String(src); - - // Build into a subdirectory of the source dir. - await using build = Bun.spawn({ - cmd: [ - bunExe(), - "build", - join(srcDir, "nested/entry.js"), - "--target", - target, - "--outfile", - join(srcDir, "build/bundle.mjs"), - ], - env: bunEnv, - cwd: srcDir, - stdout: "pipe", - stderr: "pipe", - }); - const [buildStderr, buildExit] = await Promise.all([build.stderr.text(), build.exited]); - expect(buildStderr).not.toContain("error:"); - expect(buildExit).toBe(0); - - const bundleSource = await Bun.file(join(srcDir, "build/bundle.mjs")).text(); - // The build machine's absolute source path must not appear in the output. - expect(bundleSource).not.toContain(join(srcDir, "nested")); - - // Copy the bundle somewhere unrelated to the build directory and run it - // from there, so a hardcoded build-time path cannot accidentally resolve. - using runDir = tempDir("issue-4216-run", {}); - const runPath = join(String(runDir), "moved.mjs"); - cpSync(join(srcDir, "build/bundle.mjs"), runPath); - - await using proc = Bun.spawn({ - cmd: [bunExe(), runPath], - env: bunEnv, - cwd: String(runDir), - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect(stderr).toBe(""); - const out = JSON.parse(stdout.trim()); - // All four should point at the *runtime* bundle location, not the source - // tree. The wrapped CJS dep sees the same chunk-level `import.meta` as the - // entry, so its __dirname/__filename match. - expect(out).toEqual({ - dirname: String(runDir), - filename: runPath, - depDirname: String(runDir), - depFilename: runPath, - }); - expect(exitCode).toBe(0); - }); - - test.concurrent(`--target=${target} --format=cjs`, async () => { - using src = tempDir("issue-4216-cjs", { - "entry.js": ` - console.log(JSON.stringify({ dirname: __dirname, filename: __filename })); - `, - }); - const srcDir = String(src); - - await using build = Bun.spawn({ - cmd: [ - bunExe(), - "build", - join(srcDir, "entry.js"), - "--target", - target, - "--format=cjs", - "--outfile", - join(srcDir, "bundle.cjs"), - ], - env: bunEnv, - cwd: srcDir, - stdout: "pipe", - stderr: "pipe", - }); - const [buildStderr, buildExit] = await Promise.all([build.stderr.text(), build.exited]); - expect(buildStderr).not.toContain("error:"); - expect(buildExit).toBe(0); - - // The output must not re-declare __dirname/__filename with the build path; - // the CJS wrapper (Bun's `@bun-cjs` or Node's native module wrapper) - // already provides them. - const bundleSource = await Bun.file(join(srcDir, "bundle.cjs")).text(); - expect(bundleSource).not.toContain(srcDir); - - using runDir = tempDir("issue-4216-cjs-run", {}); - const runPath = join(String(runDir), "moved.cjs"); - cpSync(join(srcDir, "bundle.cjs"), runPath); - - await using proc = Bun.spawn({ - cmd: [bunExe(), runPath], - env: bunEnv, - cwd: String(runDir), - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect(stderr).toBe(""); - expect(JSON.parse(stdout.trim())).toEqual({ - dirname: String(runDir), - filename: runPath, - }); - expect(exitCode).toBe(0); - }); - } - - // --target=browser has no runtime `import.meta.dir` equivalent, so it keeps - // the legacy behavior of inlining the build-time path as a string literal. - test.concurrent("--target=browser still inlines a string literal", async () => { - using src = tempDir("issue-4216-browser", { - "entry.js": `console.log(__dirname, __filename);`, - }); - const srcDir = String(src); - - await using build = Bun.spawn({ - cmd: [bunExe(), "build", join(srcDir, "entry.js"), "--target", "browser"], - env: bunEnv, - cwd: srcDir, - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([build.stdout.text(), build.stderr.text(), build.exited]); - expect(stderr).not.toContain("error:"); - expect(stdout).toContain("var __dirname ="); - expect(stdout).not.toContain("import.meta"); - expect(exitCode).toBe(0); - }); -}); From 420ea6546100077a70f189164b8066c5c552bd6a Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Fri, 24 Jul 2026 23:25:09 +0000 Subject: [PATCH 05/11] [autofix.ci] apply automated fixes --- test/bundler/cli.test.ts | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/test/bundler/cli.test.ts b/test/bundler/cli.test.ts index fdc3a53c7012..5df2bbe47349 100644 --- a/test/bundler/cli.test.ts +++ b/test/bundler/cli.test.ts @@ -582,11 +582,7 @@ describe.concurrent("__dirname/__filename resolve at runtime in bundled output", stdout: "pipe", stderr: "pipe", }); - const [, buildStderr, buildExit] = await Promise.all([ - build.stdout.text(), - build.stderr.text(), - build.exited, - ]); + const [, buildStderr, buildExit] = await Promise.all([build.stdout.text(), build.stderr.text(), build.exited]); expect(buildStderr).not.toContain("error:"); expect(buildExit).toBe(0); @@ -646,11 +642,7 @@ describe.concurrent("__dirname/__filename resolve at runtime in bundled output", stdout: "pipe", stderr: "pipe", }); - const [, buildStderr, buildExit] = await Promise.all([ - build.stdout.text(), - build.stderr.text(), - build.exited, - ]); + const [, buildStderr, buildExit] = await Promise.all([build.stdout.text(), build.stderr.text(), build.exited]); expect(buildStderr).not.toContain("error:"); expect(buildExit).toBe(0); From 4cedb5255bd0aacf4ba1420b53e951f5ab79c04e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 24 Jul 2026 23:34:47 +0000 Subject: [PATCH 06/11] cover bytecode import.meta flag in the compile dirname test --- test/bundler/cli.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/bundler/cli.test.ts b/test/bundler/cli.test.ts index 5df2bbe47349..9a20832a1c07 100644 --- a/test/bundler/cli.test.ts +++ b/test/bundler/cli.test.ts @@ -188,13 +188,17 @@ console.log(utils());`, // `--compile` bundles for Bun's runtime, so `__dirname`/`__filename` // resolve to the compiled executable's virtual `$bunfs` path at runtime - // instead of the build machine's source path (#4216). + // instead of the build machine's source path (#4216). `--bytecode` + // additionally covers the module-record import.meta flag: the injected + // `import.meta.dir` is the only import.meta reference here, and cached + // bytecode only links it when the parser marks the module accordingly. const { exited } = Bun.spawn({ cmd: [ bunExe(), "build", path.join(baseDir, "我/我.ts"), "--compile", + "--bytecode", "--outfile", path.join(baseDir, "exe.exe"), ], From 0c1ae984b9effbca0adae12b7622b771791f1d29 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 24 Jul 2026 23:54:47 +0000 Subject: [PATCH 07/11] address review: Bake/fold.rs consistency, itBundled output-shape tests - Gate the import.meta.dir lowering on framework.is_none() so Bake production (which inlines import.meta.dir as a per-source string) keeps __dirname consistent with it. - fold.rs: for --format=cjs on Bun/Node targets (outside Bake), rewrite import.meta.dir/.dirname/.path/.filename to the wrapper's __dirname/__filename params instead of inlining the build-time path, so they agree with __dirname now that it falls through to the wrapper. - Add itBundled output-shape tests next to ImportMetaMain that pin the per-target property names, and extend the cjs move-and-run test to cover import.meta.dir === __dirname. --- src/js_parser/fold.rs | 33 +++++++++++++++++++- src/js_parser/parse/parse_entry.rs | 27 ++++++++++------- test/bundler/bundler_edgecase.test.ts | 43 +++++++++++++++++++++++++++ test/bundler/cli.test.ts | 11 ++++++- 4 files changed, 101 insertions(+), 13 deletions(-) diff --git a/src/js_parser/fold.rs b/src/js_parser/fold.rs index 08e2f4378ae0..23c4485cf6e4 100644 --- a/src/js_parser/fold.rs +++ b/src/js_parser/fold.rs @@ -509,11 +509,42 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O }); } - // Inline import.meta properties for Bake + // CJS output has no syntactic `import.meta`; Bake wants + // per-source-file paths in either format. Both need the + // `import.meta` property access replaced here. if p.options.framework.is_some() || (p.options.bundle && p.options.output_format == js_parser::options::Format::Cjs) { + // For `--format=cjs --target=bun|node` (and not Bake), + // `__dirname`/`__filename` fall through to the CJS + // wrapper at runtime. Keep `import.meta.dir`/`.path` + // consistent by rewriting them to those wrapper params + // instead of inlining the build-time path. (#4216) + if p.options.framework.is_none() + && (p.options.target.is_bun() || p.options.target.is_node()) + { + if name == b"dir" || name == b"dirname" { + p.record_usage(p.dirname_ref); + return Some(p.new_expr( + E::Identifier { + ref_: p.dirname_ref, + ..Default::default() + }, + name_loc, + )); + } else if name == b"path" || name == b"filename" { + p.record_usage(p.filename_ref); + return Some(p.new_expr( + E::Identifier { + ref_: p.filename_ref, + ..Default::default() + }, + name_loc, + )); + } + } + if name == b"dir" || name == b"dirname" { // Inline import.meta.dir return Some( diff --git a/src/js_parser/parse/parse_entry.rs b/src/js_parser/parse/parse_entry.rs index 82fba16e7d68..b6c5b001c20b 100644 --- a/src/js_parser/parse/parse_entry.rs +++ b/src/js_parser/parse/parse_entry.rs @@ -1036,22 +1036,27 @@ impl<'a> Parser<'a> { if uses_dirname || uses_filename { // `(dir_property, path_property)` — `Some` when the target // runtime exposes these on `import.meta`, `None` to fall back - // to the build-time string literal. - let import_meta_names: Option<(&'static [u8], &'static [u8])> = - if p.options.bundle && p.options.output_format == options::Format::Esm { - if p.options.target.is_bun() { - Some((b"dir", b"path")) - } else if p.options.target.is_node() { - Some((b"dirname", b"filename")) - } else { - None - } + // to the build-time string literal. Bake (`framework.is_some()`) + // inlines user-written `import.meta.dir` as a source-path string + // during visitation, so keep `__dirname` consistent with that. + let import_meta_names: Option<(&'static [u8], &'static [u8])> = if p.options.bundle + && p.options.output_format == options::Format::Esm + && p.options.framework.is_none() + { + if p.options.target.is_bun() { + Some((b"dir", b"path")) + } else if p.options.target.is_node() { + Some((b"dirname", b"filename")) } else { None - }; + } + } else { + None + }; let defer_to_cjs_wrapper = p.options.bundle && p.options.output_format == options::Format::Cjs + && p.options.framework.is_none() && (p.options.target.is_bun() || p.options.target.is_node()); if import_meta_names.is_some() { diff --git a/test/bundler/bundler_edgecase.test.ts b/test/bundler/bundler_edgecase.test.ts index 45021b293479..fabf82ecb68d 100644 --- a/test/bundler/bundler_edgecase.test.ts +++ b/test/bundler/bundler_edgecase.test.ts @@ -2146,6 +2146,49 @@ describe("bundler", () => { api.expectFile("/out.js").toMatch(/[^\.:]module/); // `.module` and `node:module` are not ok. }, }); + // __dirname/__filename lowering is target-sensitive; lock the per-target + // output shape so a property-name mixup can't silently pass when both + // targets are run under Bun (which aliases import.meta.dir/.dirname). #4216 + itBundled("edgecase/DirnameFilenameTargetBun#4216", { + target: "bun", + files: { + "/entry.ts": `console.log(capture(__dirname), capture(__filename));`, + }, + capture: ["__dirname", "__filename"], + onAfterBundle(api) { + api.expectFile("/out.js").toContain("import.meta.dir"); + api.expectFile("/out.js").toContain("import.meta.path"); + api.expectFile("/out.js").not.toContain('"/entry.ts"'); + }, + }); + itBundled("edgecase/DirnameFilenameTargetNode#4216", { + target: "node", + files: { + "/entry.ts": `console.log(capture(__dirname), capture(__filename));`, + }, + capture: ["__dirname", "__filename"], + onAfterBundle(api) { + api.expectFile("/out.js").toContain("import.meta.dirname"); + api.expectFile("/out.js").toContain("import.meta.filename"); + // Make sure we emit the Node spellings, not Bun's. + api.expectFile("/out.js").not.toMatch(/import\.meta\.dir\b/); + api.expectFile("/out.js").not.toMatch(/import\.meta\.path\b/); + }, + }); + itBundled("edgecase/DirnameFilenameTargetNodeCjs#4216", { + target: "node", + format: "cjs", + files: { + "/entry.ts": `console.log(capture(__dirname), capture(__filename), capture(import.meta.dir), capture(import.meta.path));`, + }, + capture: ["__dirname", "__filename", "__dirname", "__filename"], + onAfterBundle(api) { + // No declaration; references fall through to the host module wrapper. + api.expectFile("/out.js").not.toMatch(/var __dirname\b/); + api.expectFile("/out.js").not.toMatch(/var __filename\b/); + api.expectFile("/out.js").not.toContain("import.meta"); + }, + }); itBundled("edgecase/IdentifierInEnum#13081", { files: { "/entry.ts": ` diff --git a/test/bundler/cli.test.ts b/test/bundler/cli.test.ts index 9a20832a1c07..f368f5ccbae9 100644 --- a/test/bundler/cli.test.ts +++ b/test/bundler/cli.test.ts @@ -623,9 +623,16 @@ describe.concurrent("__dirname/__filename resolve at runtime in bundled output", }); test.skipIf(missingNode)(`--target=${target} --format=cjs`, async () => { + // Also reference `import.meta.dir`/`.path` so the test catches any + // divergence between them and `__dirname`/`__filename` in CJS output. using src = tempDir("dirname-4216-cjs", { "entry.js": ` - console.log(JSON.stringify({ dirname: __dirname, filename: __filename })); + console.log(JSON.stringify({ + dirname: __dirname, + filename: __filename, + metaDir: import.meta.dir, + metaPath: import.meta.path, + })); `, }); const srcDir = String(src); @@ -672,6 +679,8 @@ describe.concurrent("__dirname/__filename resolve at runtime in bundled output", expect(JSON.parse(stdout.trim())).toEqual({ dirname: String(runDir), filename: runPath, + metaDir: String(runDir), + metaPath: runPath, }); expect(exitCode).toBe(0); }); From 798730847efd631a162b427531440bbac6aff8cb Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 25 Jul 2026 00:48:41 +0000 Subject: [PATCH 08/11] tighten bun-target dirname assertions to word boundaries --- test/bundler/bundler_edgecase.test.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/test/bundler/bundler_edgecase.test.ts b/test/bundler/bundler_edgecase.test.ts index fabf82ecb68d..299370398682 100644 --- a/test/bundler/bundler_edgecase.test.ts +++ b/test/bundler/bundler_edgecase.test.ts @@ -2156,8 +2156,13 @@ describe("bundler", () => { }, capture: ["__dirname", "__filename"], onAfterBundle(api) { - api.expectFile("/out.js").toContain("import.meta.dir"); - api.expectFile("/out.js").toContain("import.meta.path"); + // Word-boundary match: `import.meta.dir` is a prefix of the Node + // spelling `import.meta.dirname`, so a bare toContain can't tell + // them apart. + api.expectFile("/out.js").toMatch(/import\.meta\.dir\b/); + api.expectFile("/out.js").toMatch(/import\.meta\.path\b/); + api.expectFile("/out.js").not.toContain("import.meta.dirname"); + api.expectFile("/out.js").not.toContain("import.meta.filename"); api.expectFile("/out.js").not.toContain('"/entry.ts"'); }, }); From 1c59fbe1228d3da85bed695abaae089f88030d55 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 25 Jul 2026 02:22:57 +0000 Subject: [PATCH 09/11] fix Windows __dirname from the CJS wrapper for standalone executables Standalone graph keys are forward-slashed (B:/~BUN/root/app.js), but the CJS wrapper computed __dirname by splitting on backslash only, yielding an empty string in compiled executables on Windows. Split on either separator via lastPathSeparatorIndex. Also split the compile test: --bytecode alone implies CJS output, so the previous test never exercised the ESM bytecode import.meta flag. The existing test now passes --format=esm explicitly, and a new test covers the implied-CJS wrapper values with the forward-slashed graph key. --- src/jsc/bindings/JSCommonJSModule.cpp | 8 ++--- src/jsc/bindings/PathInlines.h | 18 ++++++++++ test/bundler/cli.test.ts | 52 ++++++++++++++++++++++++--- 3 files changed, 70 insertions(+), 8 deletions(-) diff --git a/src/jsc/bindings/JSCommonJSModule.cpp b/src/jsc/bindings/JSCommonJSModule.cpp index e18cc0c15b55..79ba7f308dc6 100644 --- a/src/jsc/bindings/JSCommonJSModule.cpp +++ b/src/jsc/bindings/JSCommonJSModule.cpp @@ -895,7 +895,7 @@ JSCommonJSModule* JSCommonJSModule::create( { auto& vm = JSC::getVM(globalObject); auto key = requireMapKey->value(globalObject); - auto index = key->reverseFind(PLATFORM_SEP, key->length()); + auto index = lastPathSeparatorIndex(key.data); JSString* dirname; if (index != WTF::notFound) { @@ -1484,7 +1484,7 @@ std::optional createCommonJSModule( } if (!moduleObject) { - size_t index = sourceURL.reverseFind(PLATFORM_SEP, sourceURL.length()); + size_t index = lastPathSeparatorIndex(sourceURL); JSString* dirname; JSString* filename = requireMapKey; if (index != WTF::notFound) { @@ -1601,7 +1601,7 @@ std::optional createCommonJSModule( } if (!moduleObject) { - size_t index = sourceURL.reverseFind(PLATFORM_SEP, sourceURL.length()); + size_t index = lastPathSeparatorIndex(sourceURL); JSString* dirname; JSString* filename = requireMapKey; if (index != WTF::notFound) { @@ -1641,7 +1641,7 @@ JSObject* JSCommonJSModule::createBoundRequireFunction(VM& vm, JSGlobalObject* l auto scope = DECLARE_THROW_SCOPE(vm); JSString* filename = JSC::jsStringWithCache(vm, pathString); - auto index = pathString.reverseFind(PLATFORM_SEP, pathString.length()); + auto index = lastPathSeparatorIndex(pathString); JSString* dirname; if (index != WTF::notFound) { dirname = JSC::jsSubstring(globalObject, filename, 0, index); diff --git a/src/jsc/bindings/PathInlines.h b/src/jsc/bindings/PathInlines.h index dc39d5a58939..fcacc51de3b6 100644 --- a/src/jsc/bindings/PathInlines.h +++ b/src/jsc/bindings/PathInlines.h @@ -55,6 +55,24 @@ ALWAYS_INLINE bool isAbsolutePath(WTF::String input) #undef IS_LETTER #undef IS_SLASH +/// Index of the last path separator, or WTF::notFound. On Windows both `\` and +/// `/` count: standalone-executable module keys are forward-slashed +/// (e.g. "B:/~BUN/root/app.js"), and mixed-separator paths are legal. +ALWAYS_INLINE size_t lastPathSeparatorIndex(const WTF::String& path) +{ +#if OS(WINDOWS) + size_t slash = path.reverseFind(POSIX_PATH_SEP, path.length()); + size_t backslash = path.reverseFind(WINDOWS_PATH_SEP, path.length()); + if (slash == WTF::notFound) + return backslash; + if (backslash == WTF::notFound) + return slash; + return std::max(slash, backslash); +#else + return path.reverseFind(POSIX_PATH_SEP, path.length()); +#endif +} + extern "C" BunString ResolvePath__joinAbsStringBufCurrentPlatformBunString(JSC::JSGlobalObject*, BunString); /// CWD is determined by the global object's current cwd. diff --git a/test/bundler/cli.test.ts b/test/bundler/cli.test.ts index f368f5ccbae9..861a66ad6eea 100644 --- a/test/bundler/cli.test.ts +++ b/test/bundler/cli.test.ts @@ -188,10 +188,11 @@ console.log(utils());`, // `--compile` bundles for Bun's runtime, so `__dirname`/`__filename` // resolve to the compiled executable's virtual `$bunfs` path at runtime - // instead of the build machine's source path (#4216). `--bytecode` - // additionally covers the module-record import.meta flag: the injected - // `import.meta.dir` is the only import.meta reference here, and cached - // bytecode only links it when the parser marks the module accordingly. + // instead of the build machine's source path (#4216). `--bytecode + // --format=esm` additionally covers the module-record import.meta flag: + // the injected `import.meta.dir` is the only import.meta reference here, + // and cached bytecode only links it when the parser marks the module + // accordingly. (`--bytecode` alone would imply CJS and skip that path.) const { exited } = Bun.spawn({ cmd: [ bunExe(), @@ -199,6 +200,7 @@ console.log(utils());`, path.join(baseDir, "我/我.ts"), "--compile", "--bytecode", + "--format=esm", "--outfile", path.join(baseDir, "exe.exe"), ], @@ -242,6 +244,48 @@ console.log(utils());`, expect(browserExit).toBe(0); }); + test("__dirname and __filename from the CJS wrapper in compiled executables", async () => { + using dir = tempDir("bun-build-dirname-cjs", { + "entry.ts": "console.log(__dirname); console.log(__filename);", + }); + const base = String(dir); + + // `--bytecode` without `--format` implies CJS output: no declaration is + // injected, so `__dirname`/`__filename` come from the module wrapper. + await using build = Bun.spawn({ + cmd: [ + bunExe(), + "build", + path.join(base, "entry.ts"), + "--compile", + "--bytecode", + "--outfile", + path.join(base, "exe.exe"), + ], + env: bunEnv, + cwd: base, + stdout: "pipe", + stderr: "pipe", + }); + const [, buildErr, buildExit] = await Promise.all([build.stdout.text(), build.stderr.text(), build.exited]); + expect(buildErr).not.toContain("error:"); + expect(buildExit).toBe(0); + + await using proc = Bun.spawn({ + cmd: [path.join(base, "exe.exe")], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + // The wrapper params equal the standalone graph key, which is + // forward-slashed on every platform (`B:/~BUN/root`, not `B:\~BUN\root`). + const bunfsRoot = isWindows ? "B:/~BUN/root" : "/$bunfs/root"; + expect(stdout).toBe(bunfsRoot + "\n" + bunfsRoot + "/exe.exe\n"); + expect(exitCode).toBe(0); + }); + test.skipIf(!isWindows)("should be able to handle pretty path when using pnpm + #14685", async () => { // this test code follows the same structure as and // is based on the code for testing issue 4893 From a360c7794cba655af602c30475dc7ca37bfca27a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 25 Jul 2026 03:27:39 +0000 Subject: [PATCH 10/11] ci: retrigger From b412c36c3f76f9b83d8676d6153dd0ca6735236e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 25 Jul 2026 03:31:19 +0000 Subject: [PATCH 11/11] remove review-bot-flagged comments --- src/js_parser/fold.rs | 9 +-------- src/js_parser/parse/parse_entry.rs | 25 ------------------------- src/jsc/bindings/PathInlines.h | 3 --- 3 files changed, 1 insertion(+), 36 deletions(-) diff --git a/src/js_parser/fold.rs b/src/js_parser/fold.rs index 23c4485cf6e4..f4df381d3253 100644 --- a/src/js_parser/fold.rs +++ b/src/js_parser/fold.rs @@ -509,18 +509,11 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O }); } - // CJS output has no syntactic `import.meta`; Bake wants - // per-source-file paths in either format. Both need the - // `import.meta` property access replaced here. + // Inline import.meta properties for Bake if p.options.framework.is_some() || (p.options.bundle && p.options.output_format == js_parser::options::Format::Cjs) { - // For `--format=cjs --target=bun|node` (and not Bake), - // `__dirname`/`__filename` fall through to the CJS - // wrapper at runtime. Keep `import.meta.dir`/`.path` - // consistent by rewriting them to those wrapper params - // instead of inlining the build-time path. (#4216) if p.options.framework.is_none() && (p.options.target.is_bun() || p.options.target.is_node()) { diff --git a/src/js_parser/parse/parse_entry.rs b/src/js_parser/parse/parse_entry.rs index b6c5b001c20b..a276cab544ef 100644 --- a/src/js_parser/parse/parse_entry.rs +++ b/src/js_parser/parse/parse_entry.rs @@ -93,10 +93,6 @@ pub struct Options<'a> { pub import_meta_main_value: Option, pub lower_import_meta_main_for_node_js: bool, - /// The bundle target. Controls whether `__dirname` / `__filename` are - /// inlined as build-time string literals (browser) or lowered to - /// `import.meta.dir` / `import.meta.path` so they resolve at runtime - /// (Bun / Node ESM output). Only consulted when `bundle` is set. pub target: js_ast::Target, /// When using react fast refresh or server components, the framework is @@ -1022,23 +1018,8 @@ impl<'a> Parser<'a> { // var __dirname = "foo/bar" // var __filename = "foo/bar/baz.js" // - // When bundling for Bun or Node, the build machine's absolute source - // path is the wrong value: the bundle will typically run from a - // different location (and on a different machine). For ESM output we - // instead emit `var __dirname = import.meta.dir` (Bun) or - // `import.meta.dirname` (Node), so it resolves to the output file's - // directory at runtime. For CJS output on those targets the runtime - // already provides `__dirname`/`__filename` via the module wrapper, so - // we emit nothing and let references fall through. - // - // https://github.com/oven-sh/bun/issues/4216 if p.options.bundle || !p.options.features.commonjs_at_runtime { if uses_dirname || uses_filename { - // `(dir_property, path_property)` — `Some` when the target - // runtime exposes these on `import.meta`, `None` to fall back - // to the build-time string literal. Bake (`framework.is_some()`) - // inlines user-written `import.meta.dir` as a source-path string - // during visitation, so keep `__dirname` consistent with that. let import_meta_names: Option<(&'static [u8], &'static [u8])> = if p.options.bundle && p.options.output_format == options::Format::Esm && p.options.framework.is_none() @@ -2198,8 +2179,6 @@ struct PragmaState { seen_bytecode: bool, } -/// `import.meta.`, marked side-effect-free so the declaration it -/// initializes can be dropped if the symbol ends up unused. fn import_meta_dot( p: &mut P<'_, TS, SCAN_ONLY>, name: &'static [u8], @@ -2217,10 +2196,6 @@ fn import_meta_dot( ) } -/// Injects `var __dirname = ..., __filename = ...` as its own -/// `PartTag::DirnameFilename` part. Shared by the bundle-time and runtime -/// lowering paths so their declaration metadata cannot drift; each caller -/// supplies only the value expressions (`None` = symbol unused, no decl). fn inject_dirname_filename_part<'a, const TS: bool, const SCAN_ONLY: bool>( p: &mut P<'a, TS, SCAN_ONLY>, before: &mut BumpVec<'a, js_ast::Part>, diff --git a/src/jsc/bindings/PathInlines.h b/src/jsc/bindings/PathInlines.h index fcacc51de3b6..1d6271b0249b 100644 --- a/src/jsc/bindings/PathInlines.h +++ b/src/jsc/bindings/PathInlines.h @@ -55,9 +55,6 @@ ALWAYS_INLINE bool isAbsolutePath(WTF::String input) #undef IS_LETTER #undef IS_SLASH -/// Index of the last path separator, or WTF::notFound. On Windows both `\` and -/// `/` count: standalone-executable module keys are forward-slashed -/// (e.g. "B:/~BUN/root/app.js"), and mixed-separator paths are legal. ALWAYS_INLINE size_t lastPathSeparatorIndex(const WTF::String& path) { #if OS(WINDOWS)