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 2fe2aff4ccc3..9a2f155953ff 100644 --- a/src/bundler/options.rs +++ b/src/bundler/options.rs @@ -1245,6 +1245,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 @@ -1497,6 +1500,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(), @@ -1724,6 +1728,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"); + }); + } +});