From 1322898443587a36e8e53875d1c622f0c08632b5 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 14 Aug 2026 16:48:36 +0000 Subject: [PATCH 1/6] bundler: default the build target to bun from entry point hashbangs When no target is given, `bun build` and `Bun.build()` now check every entry point (in-memory `files` first, then disk) for a `#!/usr/bin/env bun` first line, accepting LF, CRLF and EOF terminators, and default the whole build to target bun. An explicit target is left alone. This replaces the per-file override in ParseTask, which only looked at the first entry point, missed CRLF files, and retargeted that one file while its dependencies were still built for the configured target. --- docs/bundler/index.mdx | 2 +- packages/bun-types/bun.d.ts | 5 ++ src/bundler/ParseTask.rs | 35 ++++---- src/bundler/bundle_v2.rs | 87 +++++++++----------- src/bundler/lib.rs | 2 +- src/bundler/options.rs | 33 ++++++++ src/runtime/api/JSBundler.rs | 10 +++ src/runtime/cli/build_command.rs | 6 ++ test/bundler/bundler_bun.test.ts | 132 ++++++++++++++++++++++++++++++- 9 files changed, 240 insertions(+), 72 deletions(-) diff --git a/docs/bundler/index.mdx b/docs/bundler/index.mdx index d59d6e77e973..09af21532065 100644 --- a/docs/bundler/index.mdx +++ b/docs/bundler/index.mdx @@ -366,7 +366,7 @@ For bundles that run in the Bun runtime. In many cases, it isn't necessary to bu All bundles generated with `target: "bun"` are marked with a `// @bun` pragma, which tells the Bun runtime that there's no need to re-transpile the file before execution. -If any entrypoint contains a Bun shebang (`#!/usr/bin/env bun`), the bundler defaults to `target: "bun"` instead of `"browser"`. +If `target` is not set and any entrypoint starts with a Bun shebang (`#!/usr/bin/env bun`), the bundler defaults to `target: "bun"` instead of `"browser"`. An explicit `target` is always used as given. When using `target: "bun"` and `format: "cjs"` together, the `// @bun @bun-cjs` pragma is added and the CommonJS wrapper function is not compatible with Node.js. diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index 175f4b6f4b4e..cdf2d18ca431 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -2800,6 +2800,11 @@ declare module "bun" { entrypoints: string[]; /** + * The environment the bundle will run in. + * + * When not set, defaults to `"bun"` if any entrypoint starts with a + * `#!/usr/bin/env bun` shebang, and to `"browser"` otherwise. + * * @default "browser" */ target?: Target; // default: "browser" diff --git a/src/bundler/ParseTask.rs b/src/bundler/ParseTask.rs index d9020c420c3a..02a350346f5b 100644 --- a/src/bundler/ParseTask.rs +++ b/src/bundler/ParseTask.rs @@ -35,7 +35,7 @@ use crate::cache::{Entry as CacheEntry, ExternalFreeFunction}; use crate::html_scanner::HTMLScanner; use crate::options::{self, Loader}; use crate::transpiler::Transpiler; -use crate::{ContentHasher, UseDirective, perf, target_from_hashbang}; +use crate::{ContentHasher, UseDirective, perf}; use bun_resolver::fs::PathResolverExt as _; use bun_resolver::{self as _resolver, Resolver}; @@ -2400,27 +2400,20 @@ pub mod parse_worker { ..Default::default() }); - let target = (if task.source_index.get() == 1 { - target_from_hashbang(entry_contents) + let target = if task.known_target == options::Target::ServerComponentsSsr + && topts + .framework + .as_ref() + .unwrap() + .server_components + .as_ref() + .unwrap() + .separate_ssr_graph + { + options::Target::ServerComponentsSsr } else { - None - }) - .unwrap_or_else(|| { - if task.known_target == options::Target::ServerComponentsSsr - && topts - .framework - .as_ref() - .unwrap() - .server_components - .as_ref() - .unwrap() - .separate_ssr_graph - { - options::Target::ServerComponentsSsr - } else { - topts.target - } - }); + topts.target + }; let output_format = topts.output_format; diff --git a/src/bundler/bundle_v2.rs b/src/bundler/bundle_v2.rs index f9be9d28d01a..bbc13daabc96 100644 --- a/src/bundler/bundle_v2.rs +++ b/src/bundler/bundle_v2.rs @@ -18,7 +18,6 @@ pub use bv2_impl::dispatch; pub use bv2_impl::{ CompileResult, CompileResultForSourceMap, CompileResultForSourceMapColumns, ContentHasher, EventLoop, ImportTracker, PartRange, StableRef, WrapKind, generic_path_with_pretty_initialized, - target_from_hashbang, }; pub use bv2_impl::{DevServerInput, DevServerOutput, ImportTrackerIterator, ImportTrackerStatus}; // Flatten the impl-body module into this file's namespace so external callers @@ -913,9 +912,7 @@ pub mod bv2_impl { } } /// Returns a `resolver::Result` for a file in the map, or `None` if - /// not found. Handles direct key matches and relative specifiers - /// joined against `dirname(source_file)` (with Windows - /// drive-letter / separator normalization). + /// not found (see [`Self::lookup`] for what matches). /// /// `arena` is the build's bump arena (`BundleV2::arena()`); /// the matched key is copied into it so the returned @@ -928,33 +925,50 @@ pub mod bv2_impl { source_file: &[u8], specifier: &[u8], ) -> Option { - if self.map.is_empty() { - return None; - } - + let (key, _) = self.lookup(source_file, specifier)?; // SAFETY: ARENA — `arena` is the build-pass bump arena // (never freed before the `Result` is consumed); detaching the // borrow lifetime matches the established `Path<'static>` // convention used throughout `bun_resolver` (PORTING.md // §Lifetimes: ARENA → `&'bump T`). - let dupe = |key: &[u8]| -> &'static [u8] { - // SAFETY: see ARENA note above — bytes live in the build-pass arena. - unsafe { bun_ptr::detach_lifetime(arena.alloc_slice_copy(key)) } - }; + let key: &'static [u8] = + unsafe { bun_ptr::detach_lifetime(arena.alloc_slice_copy(key)) }; + Some(bun_resolver::Result { + path_pair: bun_resolver::PathPair { + primary: crate::bun_fs::Path::init_with_namespace(key, b"file"), + ..Default::default() + }, + module_type: crate::options::ModuleType::Unknown, + ..Default::default() + }) + } - // Direct key match (must use `getKey` to return the map-owned - // key, not the parameter). + /// Finds the file `specifier` denotes when imported from + /// `source_file` (`b""` for an entry point): a direct key match, or a + /// relative specifier joined against `dirname(source_file)` (with + /// Windows drive-letter / separator normalization). Returns the + /// map-owned key and the file's contents. + pub(crate) fn lookup( + &self, + source_file: &[u8], + specifier: &[u8], + ) -> Option<(&[u8], &[u8])> { + if self.map.is_empty() { + return None; + } + + // Direct key match. #[cfg(not(windows))] - if let Some((key, _)) = self.map.get_key_value(specifier) { - return Some(Self::result_for_key(dupe(key.as_ref()))); + if let Some(found) = self.entry(specifier) { + return Some(found); } #[cfg(windows)] { let mut buf = bun_paths::path_buffer_pool::get(); let normalized = bun_paths::resolve_path::path_to_posix_buf(specifier, &mut **buf); - if let Some((key, _)) = self.map.get_key_value(normalized) { - return Some(Self::result_for_key(dupe(key.as_ref()))); + if let Some(found) = self.entry(normalized) { + return Some(found); } } @@ -1015,30 +1029,18 @@ pub mod bv2_impl { &mut buf[0..joined_len], ); } - let joined = &buf[0..joined_len]; - if let Some((key, _)) = self.map.get_key_value(joined) { - return Some(Self::result_for_key(dupe(key.as_ref()))); - } + return self.entry(&buf[0..joined_len]); } None } - /// Build a `bun_resolver::Result` for a matched key. `key` must - /// already satisfy `'static` — see [`resolve`], which copies the - /// map-owned key into the build's bump arena before calling here so - /// the resulting `Path<'static>` borrows arena memory rather than - /// forging a `'static` from a map borrow. - #[inline] - fn result_for_key(key: &'static [u8]) -> bun_resolver::Result { - bun_resolver::Result { - path_pair: bun_resolver::PathPair { - primary: crate::bun_fs::Path::init_with_namespace(key, b"file"), - ..Default::default() - }, - module_type: crate::options::ModuleType::Unknown, - ..Default::default() - } + /// `get_key_value` rather than `get`: callers need the map-owned + /// key (it outlives the specifier they looked up). + fn entry(&self, key: &[u8]) -> Option<(&[u8], &[u8])> { + self.map + .get_key_value(key) + .map(|(key, contents)| (key.as_ref(), &contents[..])) } } @@ -7584,17 +7586,6 @@ pub mod bv2_impl { Esm, } - pub fn target_from_hashbang(buffer: &[u8]) -> Option { - const HB: &[u8] = b"#!/usr/bin/env bun"; - if buffer.len() > HB.len() && buffer.starts_with(HB) { - match buffer[HB.len()] { - b'\n' | b' ' => return Some(options::Target::Bun), - _ => {} - } - } - None - } - pub fn generic_path_with_pretty_initialized( path: &bun_paths::fs::Path<'static>, target: options::Target, diff --git a/src/bundler/lib.rs b/src/bundler/lib.rs index 20338efed2b8..131ab0786ca2 100644 --- a/src/bundler/lib.rs +++ b/src/bundler/lib.rs @@ -47,7 +47,7 @@ pub use HTMLImportManifest::html_import_manifest; pub use bun_core::cheap_prefix_normalizer; pub use bundle_v2::{ CompileResult, CompileResultForSourceMap, ContentHasher, EventLoop, ImportTracker, PartRange, - StableRef, WrapKind, generic_path_with_pretty_initialized, target_from_hashbang, + StableRef, WrapKind, generic_path_with_pretty_initialized, }; pub use chunk::{ CrossChunkImport, CrossChunkImportItem, CrossChunkImportItemList, bun_renamer, diff --git a/src/bundler/options.rs b/src/bundler/options.rs index 66e0c833cd85..2912861cf629 100644 --- a/src/bundler/options.rs +++ b/src/bundler/options.rs @@ -324,6 +324,39 @@ impl TargetExt for Target { } } +const BUN_HASHBANG: &[u8] = b"#!/usr/bin/env bun"; + +/// `bun build` / `Bun.build()` without an explicit `target` default to +/// `Target::Bun` when an entry point starts with `#!/usr/bin/env bun` +/// (docs/bundler/index.mdx, "target"). Entry points are looked up in +/// `file_map` first, then read from disk relative to the working directory; +/// anything that is not a readable file (a bare specifier, a path only a +/// plugin resolves) does not count. +pub fn any_entry_point_has_bun_hashbang( + entry_points: &[Box<[u8]>], + file_map: Option<&crate::bundle_v2::FileMap>, +) -> bool { + entry_points.iter().any(|entry_point| { + if let Some((_, contents)) = file_map.and_then(|files| files.lookup(b"", entry_point)) { + return has_bun_hashbang(contents); + } + let mut first_bytes = [0u8; BUN_HASHBANG.len() + 1]; + bun_sys::File::openat(bun_sys::Fd::cwd(), entry_point, bun_sys::O::RDONLY, 0) + .and_then(|file| file.read_all(&mut first_bytes)) + .is_ok_and(|len| has_bun_hashbang(&first_bytes[..len])) + }) +} + +/// `contents` need only hold one byte past the hashbang: that byte tells +/// `bun` (line ends at LF / CRLF / EOF, or arguments follow) apart from `bunx`. +fn has_bun_hashbang(contents: &[u8]) -> bool { + contents.starts_with(BUN_HASHBANG) + && matches!( + contents.get(BUN_HASHBANG.len()), + None | Some(b'\n' | b'\r' | b' ' | b'\t') + ) +} + pub use bun_options_types::Format; pub use bun_options_types::WindowsOptions; diff --git a/src/runtime/api/JSBundler.rs b/src/runtime/api/JSBundler.rs index 53326b259f43..1276589214f4 100644 --- a/src/runtime/api/JSBundler.rs +++ b/src/runtime/api/JSBundler.rs @@ -830,6 +830,16 @@ pub mod js_bundler { this.files = file_map_from_js(global_this, JSValue::from_cell(files_obj))?; } + if !did_set_target + && this.target != Target::Bun + && options::any_entry_point_has_bun_hashbang( + this.entry_points.keys(), + Some(&this.files), + ) + { + this.target = Target::Bun; + } + if let Some(flag) = config.get_boolean_loose(global_this, "emitDCEAnnotations")? { this.emit_dce_annotations = Some(flag); } diff --git a/src/runtime/cli/build_command.rs b/src/runtime/cli/build_command.rs index 92003b6f7c64..e2a1bdbbfe4f 100644 --- a/src/runtime/cli/build_command.rs +++ b/src/runtime/cli/build_command.rs @@ -77,6 +77,12 @@ impl BuildCommand { return crate::bake::production::build_command(ctx); } + if ctx.args.target.is_none() + && options::any_entry_point_has_bun_hashbang(&ctx.args.entry_points, None) + { + ctx.args.target = Some(api::Target::Bun); + } + if fetcher.is_some() { ctx.args.packages = Some(api::PackagesMode::External); ctx.bundler_options.compile = false; diff --git a/test/bundler/bundler_bun.test.ts b/test/bundler/bundler_bun.test.ts index 674da11059bb..3227357763be 100644 --- a/test/bundler/bundler_bun.test.ts +++ b/test/bundler/bundler_bun.test.ts @@ -1,5 +1,7 @@ import { Database } from "bun:sqlite"; -import { describe, expect } from "bun:test"; +import { describe, expect, test } from "bun:test"; +import { bunEnv, bunExe, bunRun, tempDir } from "harness"; +import { join } from "path"; import { itBundled } from "./expectBundled"; describe("bundler", () => { @@ -184,3 +186,131 @@ error: Hello World`, } } }); + +// docs/bundler/index.mdx ("target"): a build with no explicit target defaults to +// target "bun" when an entry point starts with `#!/usr/bin/env bun`. +describe.concurrent("bundler hashbang target default", () => { + const hashbang = "#!/usr/bin/env bun"; + const backends = ["api", "cli"] as const; + + // Imports node:fs so the selected target is observable at runtime: the bun + // target keeps the import, the browser target replaces it with an empty stub. + const usesNodeFs = (firstLine: string) => + `${firstLine}import { readFileSync } from "node:fs";\nconsole.log(typeof readFileSync);\n`; + + /** Builds `entries` (relative to `dir`) into `dir/out` and returns each entry's output text. */ + async function build( + backend: (typeof backends)[number], + dir: string, + entries: string[], + target?: "node" | "browser", + ): Promise { + if (backend === "api") { + const result = await Bun.build({ + entrypoints: entries.map(entry => join(dir, entry)), + outdir: join(dir, "out"), + ...(target ? { target } : {}), + }); + expect(result.success).toBe(true); + } else { + await using proc = Bun.spawn({ + cmd: [bunExe(), "build", ...entries, "--outdir", "out", ...(target ? [`--target=${target}`] : [])], + cwd: dir, + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited, proc.stdout.text()]); + expect({ stderr, exitCode }).toEqual({ stderr: "", exitCode: 0 }); + } + return Promise.all(entries.map(entry => Bun.file(join(dir, "out", entry)).text())); + } + + const firstLines = [ + { name: "LF", source: `${hashbang}\n`, bun: true }, + { name: "CRLF", source: `${hashbang}\r\n`, bun: true }, + { name: "flags", source: `${hashbang} --smol\n`, bun: true }, + { name: "node", source: `#!/usr/bin/env node\n`, bun: false }, + { name: "bunx", source: `${hashbang}x\n`, bun: false }, + ]; + + for (const backend of backends) { + test.each(firstLines)(`${backend}: $name hashbang`, async ({ source, bun }) => { + using dir = tempDir("hashbang-target", { "cli.js": usesNodeFs(source) }); + const [output] = await build(backend, String(dir), ["cli.js"]); + const hashbangLine = source.split(/\r?\n/)[0]; + if (bun) { + expect(output).toStartWith(`${hashbangLine}\n// @bun\n`); + } else { + expect(output).toStartWith(`${hashbangLine}\n`); + expect(output).not.toContain("// @bun"); + } + expect(await bunRun(join(String(dir), "out", "cli.js"))).toSpawn(bun ? "function" : "undefined"); + }); + + test(`${backend}: a file containing only the hashbang`, async () => { + using dir = tempDir("hashbang-target", { "cli.js": hashbang }); + const [output] = await build(backend, String(dir), ["cli.js"]); + expect(output).toStartWith(`${hashbang}\n// @bun\n`); + }); + + test(`${backend}: dependencies of the hashbang entry are built for bun too`, async () => { + using dir = tempDir("hashbang-target", { + "cli.js": `${hashbang}\nimport { depHasFs } from "./dep.js";\nconsole.log(depHasFs);\n`, + "dep.js": `import { readFileSync } from "node:fs";\nexport const depHasFs = typeof readFileSync;\n`, + }); + const [output] = await build(backend, String(dir), ["cli.js"]); + expect(output).toStartWith(`${hashbang}\n// @bun\n`); + expect(await bunRun(join(String(dir), "out", "cli.js"))).toSpawn("function"); + }); + + test(`${backend}: a hashbang on a later entry point applies to the whole build`, async () => { + using dir = tempDir("hashbang-target", { + "lib.js": usesNodeFs(""), + "cli.js": usesNodeFs(`${hashbang}\n`), + }); + const [lib, cli] = await build(backend, String(dir), ["lib.js", "cli.js"]); + expect(lib).toStartWith("// @bun\n"); + expect(cli).toStartWith(`${hashbang}\n// @bun\n`); + expect(await bunRun(join(String(dir), "out", "lib.js"))).toSpawn("function"); + }); + + test.each(["node", "browser"] as const)( + `${backend}: an explicit --target=%s wins over the hashbang`, + async target => { + using dir = tempDir("hashbang-target", { + "cli.js": `${hashbang}\nimport { Shared } from "./shared.js";\nimport { ReExported } from "./reexport.js";\nconsole.log(Shared === ReExported);\n`, + "shared.js": `export class Shared {}\n`, + "reexport.js": `import { Shared } from "./shared.js";\nexport const ReExported = Shared;\n`, + }); + const [output] = await build(backend, String(dir), ["cli.js"], target); + expect(output).toStartWith(`${hashbang}\n`); + expect(output).not.toContain("// @bun"); + // The whole build shares one target, so shared.js is bundled exactly once. + expect(output.split("class Shared").length - 1).toBe(1); + expect(await bunRun(join(String(dir), "out", "cli.js"))).toSpawn("true"); + }, + ); + } + + test("api: an in-memory `files` entry is checked instead of the file on disk", async () => { + using dir = tempDir("hashbang-target", { + "plain.js": usesNodeFs(""), + "cli.js": usesNodeFs(`${hashbang}\n`), + }); + const plain = join(String(dir), "plain.js"); + const cli = join(String(dir), "cli.js"); + + const inMemoryHashbang = await Bun.build({ + entrypoints: [plain], + files: { [plain]: usesNodeFs(`${hashbang}\n`) }, + }); + expect(await inMemoryHashbang.outputs[0].text()).toStartWith(`${hashbang}\n// @bun\n`); + + const inMemoryPlain = await Bun.build({ + entrypoints: [cli], + files: { [cli]: usesNodeFs("") }, + }); + expect(await inMemoryPlain.outputs[0].text()).not.toContain("// @bun"); + }); +}); From 76bdd6a045a873c2d817d3e466b524b1611cbea4 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 14 Aug 2026 17:22:44 +0000 Subject: [PATCH 2/6] test: pin that format cjs alone does not disable the hashbang target default --- test/bundler/bundler_bun.test.ts | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/test/bundler/bundler_bun.test.ts b/test/bundler/bundler_bun.test.ts index 3227357763be..7f95dd439d43 100644 --- a/test/bundler/bundler_bun.test.ts +++ b/test/bundler/bundler_bun.test.ts @@ -203,18 +203,27 @@ describe.concurrent("bundler hashbang target default", () => { backend: (typeof backends)[number], dir: string, entries: string[], - target?: "node" | "browser", + { target, format }: { target?: "node" | "browser"; format?: "cjs" } = {}, ): Promise { if (backend === "api") { const result = await Bun.build({ entrypoints: entries.map(entry => join(dir, entry)), outdir: join(dir, "out"), ...(target ? { target } : {}), + ...(format ? { format } : {}), }); expect(result.success).toBe(true); } else { await using proc = Bun.spawn({ - cmd: [bunExe(), "build", ...entries, "--outdir", "out", ...(target ? [`--target=${target}`] : [])], + cmd: [ + bunExe(), + "build", + ...entries, + "--outdir", + "out", + ...(target ? [`--target=${target}`] : []), + ...(format ? [`--format=${format}`] : []), + ], cwd: dir, env: bunEnv, stdout: "pipe", @@ -283,7 +292,7 @@ describe.concurrent("bundler hashbang target default", () => { "shared.js": `export class Shared {}\n`, "reexport.js": `import { Shared } from "./shared.js";\nexport const ReExported = Shared;\n`, }); - const [output] = await build(backend, String(dir), ["cli.js"], target); + const [output] = await build(backend, String(dir), ["cli.js"], { target }); expect(output).toStartWith(`${hashbang}\n`); expect(output).not.toContain("// @bun"); // The whole build shares one target, so shared.js is bundled exactly once. @@ -291,6 +300,14 @@ describe.concurrent("bundler hashbang target default", () => { expect(await bunRun(join(String(dir), "out", "cli.js"))).toSpawn("true"); }, ); + + // Only an explicit target disables the default; format: "cjs" alone does not. + test(`${backend}: the hashbang still selects bun with format cjs`, async () => { + using dir = tempDir("hashbang-target", { "cli.js": `${hashbang}\nconsole.log("cjs");\n` }); + const [output] = await build(backend, String(dir), ["cli.js"], { format: "cjs" }); + expect(output).toStartWith(`${hashbang}\n// @bun @bun-cjs\n`); + expect(await bunRun(join(String(dir), "out", "cli.js"))).toSpawn("cjs"); + }); } test("api: an in-memory `files` entry is checked instead of the file on disk", async () => { From 6a28b96e9c8530437037e549b62b044e2ada3f89 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 14 Aug 2026 17:28:20 +0000 Subject: [PATCH 3/6] bundler: trim doc comments on the hashbang helpers --- src/bundler/bundle_v2.rs | 10 ++-------- src/bundler/options.rs | 10 ++-------- 2 files changed, 4 insertions(+), 16 deletions(-) diff --git a/src/bundler/bundle_v2.rs b/src/bundler/bundle_v2.rs index bbc13daabc96..6a688f51a29c 100644 --- a/src/bundler/bundle_v2.rs +++ b/src/bundler/bundle_v2.rs @@ -943,11 +943,8 @@ pub mod bv2_impl { }) } - /// Finds the file `specifier` denotes when imported from - /// `source_file` (`b""` for an entry point): a direct key match, or a - /// relative specifier joined against `dirname(source_file)` (with - /// Windows drive-letter / separator normalization). Returns the - /// map-owned key and the file's contents. + /// Returns the map-owned key and contents of `specifier` as imported + /// from `source_file` (`b""` for an entry point). pub(crate) fn lookup( &self, source_file: &[u8], @@ -957,7 +954,6 @@ pub mod bv2_impl { return None; } - // Direct key match. #[cfg(not(windows))] if let Some(found) = self.entry(specifier) { return Some(found); @@ -1035,8 +1031,6 @@ pub mod bv2_impl { None } - /// `get_key_value` rather than `get`: callers need the map-owned - /// key (it outlives the specifier they looked up). fn entry(&self, key: &[u8]) -> Option<(&[u8], &[u8])> { self.map .get_key_value(key) diff --git a/src/bundler/options.rs b/src/bundler/options.rs index 2912861cf629..077ecfb0f040 100644 --- a/src/bundler/options.rs +++ b/src/bundler/options.rs @@ -326,12 +326,8 @@ impl TargetExt for Target { const BUN_HASHBANG: &[u8] = b"#!/usr/bin/env bun"; -/// `bun build` / `Bun.build()` without an explicit `target` default to -/// `Target::Bun` when an entry point starts with `#!/usr/bin/env bun` -/// (docs/bundler/index.mdx, "target"). Entry points are looked up in -/// `file_map` first, then read from disk relative to the working directory; -/// anything that is not a readable file (a bare specifier, a path only a -/// plugin resolves) does not count. +/// Decides the documented `target` default (docs/bundler/index.mdx): a build +/// without an explicit target is built for Bun when an entry point has this hashbang. pub fn any_entry_point_has_bun_hashbang( entry_points: &[Box<[u8]>], file_map: Option<&crate::bundle_v2::FileMap>, @@ -347,8 +343,6 @@ pub fn any_entry_point_has_bun_hashbang( }) } -/// `contents` need only hold one byte past the hashbang: that byte tells -/// `bun` (line ends at LF / CRLF / EOF, or arguments follow) apart from `bunx`. fn has_bun_hashbang(contents: &[u8]) -> bool { contents.starts_with(BUN_HASHBANG) && matches!( From 4897b1dbccbb42263508c8ce8439686958e2802b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 14 Aug 2026 17:29:57 +0000 Subject: [PATCH 4/6] bundler: single-line docs on the hashbang helpers --- src/bundler/bundle_v2.rs | 3 +-- src/bundler/options.rs | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/bundler/bundle_v2.rs b/src/bundler/bundle_v2.rs index 6a688f51a29c..bb1aa4720b90 100644 --- a/src/bundler/bundle_v2.rs +++ b/src/bundler/bundle_v2.rs @@ -943,8 +943,7 @@ pub mod bv2_impl { }) } - /// Returns the map-owned key and contents of `specifier` as imported - /// from `source_file` (`b""` for an entry point). + /// Map-owned key and contents; `source_file` is `b""` for an entry point. pub(crate) fn lookup( &self, source_file: &[u8], diff --git a/src/bundler/options.rs b/src/bundler/options.rs index 077ecfb0f040..77196bc69e77 100644 --- a/src/bundler/options.rs +++ b/src/bundler/options.rs @@ -326,8 +326,7 @@ impl TargetExt for Target { const BUN_HASHBANG: &[u8] = b"#!/usr/bin/env bun"; -/// Decides the documented `target` default (docs/bundler/index.mdx): a build -/// without an explicit target is built for Bun when an entry point has this hashbang. +/// The `target` default documented in docs/bundler/index.mdx; callers apply it only when no target was given. pub fn any_entry_point_has_bun_hashbang( entry_points: &[Box<[u8]>], file_map: Option<&crate::bundle_v2::FileMap>, From 8ad0d3096314bbe0e8a1c4cfca85ec355415d077 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 14 Aug 2026 20:10:37 +0000 Subject: [PATCH 5/6] ci: retrigger From 9ec8d898f84387a673efb7e1e516e0f5102b66d5 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 21 Oct 2026 04:09:22 +0000 Subject: [PATCH 6/6] bundler: an explicit target applies to a hashbang entry point With no target, the first entry point is still parsed for bun when it starts with `#!/usr/bin/env bun`. A target that is given now holds for that file too. --- src/bundler/ParseTask.rs | 2 +- src/bundler/options.rs | 5 + src/options_types/context.rs | 3 + src/runtime/api/JSBundler.rs | 4 + src/runtime/api/js_bundle_completion_task.rs | 1 + src/runtime/cli/Arguments.rs | 1 + src/runtime/cli/build_command.rs | 2 + test/bundler/bundler_bun.test.ts | 105 ++++++++++++++++++- 8 files changed, 121 insertions(+), 2 deletions(-) diff --git a/src/bundler/ParseTask.rs b/src/bundler/ParseTask.rs index 1c20cf221d97..a5fa35ba2ef2 100644 --- a/src/bundler/ParseTask.rs +++ b/src/bundler/ParseTask.rs @@ -2468,7 +2468,7 @@ pub mod parse_worker { ..Default::default() }); - let target = (if task.source_index.get() == 1 { + let target = (if task.source_index.get() == 1 && topts.target_defaults_from_hashbang { target_from_hashbang(entry_contents) } else { None diff --git a/src/bundler/options.rs b/src/bundler/options.rs index 60b2c4fd0058..503fbee590d1 100644 --- a/src/bundler/options.rs +++ b/src/bundler/options.rs @@ -1248,6 +1248,9 @@ pub struct BundleOptions<'a> { pub(crate) tsconfig_override: Option>, pub target: Target, + /// No target was given (`--target`, `Bun.build({ target })`). The first entry point is then + /// parsed for bun when it starts with `#!/usr/bin/env bun`. + pub target_defaults_from_hashbang: bool, pub(crate) main_fields: Box<[Box<[u8]>]>, /// TODO: remove this in favor accessing bundler.log /// raw `*mut` (not `&'a mut`) — the same `*Log` is aliased @@ -1500,6 +1503,7 @@ impl<'a> BundleOptions<'a> { output_format: self.output_format, tsconfig_override: self.tsconfig_override.clone(), target: self.target, + target_defaults_from_hashbang: self.target_defaults_from_hashbang, main_fields: self.main_fields.clone(), log: self.log, external: self.external.clone(), @@ -1727,6 +1731,7 @@ impl<'a> BundleOptions<'a> { loaders, output_dir: Box::from(transform.output_dir.as_deref().unwrap_or(b"out")), target, + target_defaults_from_hashbang: false, write: transform.write.unwrap_or(false), external: ExternalModules::default(), // filled below entry_points: transform.entry_points.clone().into_boxed_slice(), diff --git a/src/options_types/context.rs b/src/options_types/context.rs index d7dd2d282fa9..217a70f13b68 100644 --- a/src/options_types/context.rs +++ b/src/options_types/context.rs @@ -209,6 +209,8 @@ pub struct BundlerOptions { pub emit_dce_annotations: bool, pub deprecated_namespace_object_setters: bool, pub output_format: bundle_enums::Format, + /// `--target` was given. + pub has_explicit_target: bool, pub bytecode: bool, pub bytecode_depth: u32, pub optimize_bytecode: bool, @@ -274,6 +276,7 @@ impl Default for BundlerOptions { emit_dce_annotations: true, deprecated_namespace_object_setters: true, output_format: bundle_enums::Format::Esm, + has_explicit_target: false, bytecode: false, bytecode_depth: u32::MAX, optimize_bytecode: true, diff --git a/src/runtime/api/JSBundler.rs b/src/runtime/api/JSBundler.rs index 5044e93e35f9..907eb322b78d 100644 --- a/src/runtime/api/JSBundler.rs +++ b/src/runtime/api/JSBundler.rs @@ -106,6 +106,8 @@ pub(crate) mod js_bundler { pub(crate) struct Config { pub(crate) target: Target, + /// `target` was not given: see `BundleOptions::target_defaults_from_hashbang`. + pub(crate) target_defaults_from_hashbang: bool, pub(crate) entry_points: StringSet, pub(crate) react_fast_refresh: bool, pub(crate) react_compiler: bun_ast::runtime::ReactCompilerMode, @@ -173,6 +175,7 @@ pub(crate) mod js_bundler { fn default() -> Self { Self { target: Target::Browser, + target_defaults_from_hashbang: false, entry_points: StringSet::default(), react_fast_refresh: false, react_compiler: bun_ast::runtime::ReactCompilerMode::Disabled, @@ -558,6 +561,7 @@ pub(crate) mod js_bundler { } drop(slice); } + this.target_defaults_from_hashbang = !did_set_target; // Plugins must be resolved first as they are allowed to mutate the config JSValue if let Some(array) = config.get_array(global_this, "plugins")? { diff --git a/src/runtime/api/js_bundle_completion_task.rs b/src/runtime/api/js_bundle_completion_task.rs index 339e444a43e8..5617c57cb916 100644 --- a/src/runtime/api/js_bundle_completion_task.rs +++ b/src/runtime/api/js_bundle_completion_task.rs @@ -1023,6 +1023,7 @@ impl CompletionStruct for JSBundleCompletionTask { }, }; transpiler.options.no_macros = config.no_macros; + transpiler.options.target_defaults_from_hashbang = config.target_defaults_from_hashbang; transpiler.options.loaders = options::loaders_from_transform_options(config.loaders.as_ref(), config.target)?; transpiler diff --git a/src/runtime/cli/Arguments.rs b/src/runtime/cli/Arguments.rs index d2a105468ec6..2bf61f81655e 100644 --- a/src/runtime/cli/Arguments.rs +++ b/src/runtime/cli/Arguments.rs @@ -2159,6 +2159,7 @@ fn parse_build_command_options( } if let Some(target) = args.option(b"--target") { + ctx.bundler_options.has_explicit_target = true; 'brk: { if cmd == CommandTag::BuildCommand { if args.flag(b"--compile") { diff --git a/src/runtime/cli/build_command.rs b/src/runtime/cli/build_command.rs index 02697be05537..d6f4585eda28 100644 --- a/src/runtime/cli/build_command.rs +++ b/src/runtime/cli/build_command.rs @@ -126,6 +126,8 @@ impl BuildCommand { let this_transpiler: &mut transpiler::Transpiler<'static> = arena.alloc( transpiler::Transpiler::init(arena, log, ctx.args.clone(), None)?, ); + this_transpiler.options.target_defaults_from_hashbang = + !ctx.bundler_options.has_explicit_target; bun_core::asan::register_root_region( std::ptr::from_ref::(this_transpiler).cast(), core::mem::size_of::(), diff --git a/test/bundler/bundler_bun.test.ts b/test/bundler/bundler_bun.test.ts index 1d283ae545f7..3ce01b4ec5cc 100644 --- a/test/bundler/bundler_bun.test.ts +++ b/test/bundler/bundler_bun.test.ts @@ -1,5 +1,7 @@ import { Database } from "bun:sqlite"; -import { describe, expect } from "bun:test"; +import { describe, expect, test } from "bun:test"; +import { bunEnv, bunExe, tempDir } from "harness"; +import { join } from "path"; import { itBundled } from "./expectBundled"; const nestedFunctions = /* js */ ` @@ -223,3 +225,104 @@ error: Hello World`, } } }); + +// With no target, a `#!/usr/bin/env bun` entry point is built for bun. A target that is given +// holds for every file, the entry point included. +describe.concurrent("bundler hashbang entry with an explicit target", () => { + const hashbang = "#!/usr/bin/env bun"; + const backends = ["api", "cli"] as const; + const targets = ["node", "browser"] as const; + + /** Builds `cli.js` in `dir` into `dir/out/cli.js` and returns the build's errors and the output path. */ + async function build( + backend: (typeof backends)[number], + dir: string, + target: (typeof targets)[number], + format: "esm" | "cjs" = "esm", + ): Promise<{ errors: string; output: string }> { + const output = join(dir, "out", "cli.js"); + if (backend === "api") { + const result = await Bun.build({ + entrypoints: [join(dir, "cli.js")], + outdir: join(dir, "out"), + target, + format, + throw: false, + }); + return { errors: result.logs.map(log => log.message).join("\n"), output }; + } + await using proc = Bun.spawn({ + cmd: [bunExe(), "build", "cli.js", "--outdir", "out", `--target=${target}`, `--format=${format}`], + cwd: dir, + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stderr] = await Promise.all([proc.stderr.text(), proc.stdout.text(), proc.exited]); + return { errors: stderr, output }; + } + + for (const backend of backends) { + // `bun build` is one process per test. One at a time keeps each of them far from the + // default timeout in a debug build. + const it = backend === "cli" ? test.serial : test; + + for (const target of targets) { + // #25767: `// @bun` tells Bun that every file in the bundle was printed for it. + it(`${backend}: every file is built for target ${target}`, async () => { + using dir = tempDir("hashbang-explicit-target", { + "cli.js": `${hashbang} +import { Shared } from "./shared.js"; +import { ReExported, symbols } from "./reexport.js"; +export const result = { oneClass: Shared === ReExported, symbols }; +`, + "shared.js": `export class Shared {}\n`, + "reexport.js": `import { Shared } from "./shared.js"; +export const ReExported = Shared; +export const symbols = "✓ ✗ ⚠"; +`, + }); + const { errors, output } = await build(backend, String(dir), target); + expect(errors).toBe(""); + const text = await Bun.file(output).text(); + expect(text).toStartWith(`${hashbang}\n`); + expect(text).not.toContain("// @bun"); + expect(text.split("class Shared").length - 1).toBe(1); + expect((await import(output)).result).toEqual({ oneClass: true, symbols: "✓ ✗ ⚠" }); + }); + + it(`${backend}: format cjs with target ${target} has no wrapper that only Bun calls`, async () => { + using dir = tempDir("hashbang-explicit-target", { + "cli.js": `${hashbang}\nmodule.exports = require("./dep.js");\n`, + "dep.js": `module.exports = "loaded";\n`, + }); + const { errors, output } = await build(backend, String(dir), target, "cjs"); + expect(errors).toBe(""); + const text = await Bun.file(output).text(); + expect(text).toStartWith(`${hashbang}\n`); + expect(text).not.toContain("@bun-cjs"); + expect(text).not.toContain("(function(exports, require, module, __filename, __dirname)"); + expect(require(output)).toBe("loaded"); + }); + + it(`${backend}: with target ${target} a hashbang entry cannot import "bun"`, async () => { + using dir = tempDir("hashbang-explicit-target", { + "cli.js": `${hashbang}\nimport { semver } from "bun";\nconsole.log(typeof semver);\n`, + }); + const { errors, output } = await build(backend, String(dir), target); + expect(errors).toContain('build cannot import Bun builtin: "bun"'); + expect(await Bun.file(output).exists()).toBe(false); + }); + } + + // For node, `import.meta.main` becomes a use of a `require` that the bundle has to define. + it(`${backend}: a hashbang entry that reads import.meta.main loads with target node`, async () => { + using dir = tempDir("hashbang-explicit-target", { + "cli.js": `${hashbang}\nexport const isMain = import.meta.main;\n`, + }); + const { errors, output } = await build(backend, String(dir), "node"); + expect(errors).toBe(""); + expect(typeof (await import(output)).isMain).toBe("boolean"); + }); + } +});