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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/ast/e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,8 @@ pub enum Special {
/// Prints the resolved specifier string for an import record
/// (an `ImportRecord` index).
ResolvedSpecifierString(u32),
/// `import.meta.require` in a bundle whose output cannot evaluate it. The printer spells it as the `require` of that output.
ImportMetaRequire,
}

pub struct Call {
Expand Down
43 changes: 31 additions & 12 deletions src/bundler/ParseTask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1110,7 +1110,7 @@ pub mod parse_worker {

// This injects the following code:
//
// import.meta.require(unique_key).db
// import.meta.require(unique_key, { type: "sqlite" }).db
//
let import_path = Expr::init(
E::String {
Expand All @@ -1120,16 +1120,24 @@ pub mod parse_worker {
Loc { start: 0 },
);

let import_meta = Expr::init(E::ImportMeta {}, Loc { start: 0 });
let require_property = Expr::init(
E::Dot {
target: import_meta,
name_loc: Loc::EMPTY,
name: b"require".into(),
..Default::default()
},
Loc { start: 0 },
);
// `import.meta` is a SyntaxError inside the cjs `@bun-cjs` wrapper.
let require_target = if opts.output_format == js_parser::options::Format::Cjs {
Expr {
data: ast::ExprData::ERequireCallTarget,
loc: Loc { start: 0 },
}
} else {
let import_meta = Expr::init(E::ImportMeta {}, Loc { start: 0 });
Expr::init(
E::Dot {
target: import_meta,
name_loc: Loc::EMPTY,
name: b"require".into(),
..Default::default()
},
Loc { start: 0 },
)
};
let require_args = bump.alloc_slice_fill_default::<Expr>(2);
require_args[0] = import_path;
let object_properties = bump.alloc_slice_fill_default::<G::Property>(1);
Expand Down Expand Up @@ -1161,7 +1169,7 @@ pub mod parse_worker {
);
let require_call = Expr::init(
E::Call {
target: require_property,
target: require_target,
// SAFETY: bump-owned slice; never grown via this Vec.
args: unsafe { bun_ast::ExprNodeList::from_bump_slice(require_args) },
..Default::default()
Expand Down Expand Up @@ -2690,6 +2698,17 @@ pub mod parse_worker {
opts.lower_import_meta_main_for_node_js = true;
}

// In CommonJS output a file for Bun or node has `require`. In an ES module only a build for node has a `__require` to take its place: `createRequire(import.meta.url)`. The dev server has `hmr.require` on both sides. A file for the browser can end in a module script, which has none.
opts.lower_import_meta_require = match output_format {
options::Format::InternalBakeDev => true,
options::Format::Iife => false,
options::Format::Cjs => target.is_server_side(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟣 pre-existing, not blocking: pre-existing: users of bun build --format=cjs with no --target still get CommonJS output that contains import.meta.require, which is a SyntaxError in every CommonJS loader (node, webpack). The gate at src/bundler/ParseTask.rs:2705 is target.is_server_side(), so a browser-target CJS build is left unlowered. The stated reason for excluding the browser (a module script has no require) only holds for ESM output; a CJS module always has require and never has import.meta. Fix: lower import.meta.require to require for every CJS output regardless of target (Format::Cjs => true), keeping the HTML client files of a server build untouched, which already come through an ESM transpiler.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

A library or a dependency it bundles contains typeof Bun !== "undefined" ? import.meta.require("x") : null, or is a file that bun build --target=bun wrote (var __require = import.meta.require;). The user runs bun build --format=cjs entry.js with no --target, so target at src/bundler/ParseTask.rs:2479 is Target::Browser. The match at src/bundler/ParseTask.rs:2705 gives lower_import_meta_require = false, so the E::Dot arm at src/js_parser/fold.rs:616 does not fire and the output keeps import.meta.require. Loading that CommonJS file in node or any bundler throws SyntaxError: Cannot use 'import.meta' outside a module. The base branch produces the same broken output, so this is pre-existing; the PR lowers the same spelling for --target=bun and --target=node CJS output at the same line, and the printer path at src/js_printer/lib.rs:3559 already prints the bare global require for Format::Cjs, so the same lowering would be correct for browser-target CJS too.

Verification: bun build --format=cjs entry.js with no --target defaults to Target::Browser. src/bundler/ParseTask.rs:2702-2710 sets options::Format::Cjs => target.is_server_side(), which is false for Target::Browser, so the fold at src/js_parser/fold.rs:616-630 does not fire. Node's CommonJS loader rejects import.meta with a SyntaxError, so the CJS output fails to load at all.

options::Format::Esm => {
target.is_server_side()
&& worker_ctx.transpiler().options.target == options::Target::Node
}
};

opts.tree_shaking = if task.source_index.is_runtime() {
true
} else {
Expand Down
1 change: 1 addition & 0 deletions src/bundler/transpiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1484,6 +1484,7 @@ impl<'a> Transpiler<'a> {
transform_only: self.options.transform_only,
import_meta_main_value: None,
lower_import_meta_main_for_node_js: false,
lower_import_meta_require: false,
framework: None,
repl_mode: self.options.repl_mode,
lower_toml_datetimes: false,
Expand Down
17 changes: 17 additions & 0 deletions src/js_parser/fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,23 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
});
}

// The printer spells this node as the `require` of the output. `--drop` of it needs the `E::Dot`. A revisit cannot record the use of the runtime's `__require`.
if name == b"require"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟣 pre-existing, not blocking: Users who build import.meta["require"](...) for node or as cjs get a bundle that works unminified and crashes with --minify-syntax. The new arm at src/js_parser/fold.rs:616 only runs from the EDot visit; with minify the EIndex path at src/js_parser/visit/visit_expr.rs:995-1016 rewrites the index to a dot and returns without running the fold, so the minified output keeps import.meta.require (undefined under node, SyntaxError in the @ bun-cjs wrapper) while the unminified output prints __require/require. Fix: lower every spelling that the lowering claims, e.g. run the import.meta fold (or re-visit the new EDot) after the EIndex->EDot shortcut so import.meta["require"], ["main"] and ["hot"] match the dotted form in both minify states.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

Trigger: source containing import.meta["require"] bundled with --target=node (esm or cjs) or --format=cjs --target=bun, with --minify-syntax or --minify. In visit_expr.rs:995-1016 the EIndex is turned into an E::Dot and the visitor returns at line 1016 without calling the property-access fold, so fold.rs:616-629 never sees it and no ESpecial::ImportMetaRequire is produced; record_usage_of_runtime_require is also not called. The same source without minify goes through visit_expr.rs:1023 onward and is lowered. Result: unminified node output runs, minified node output throws TypeError: import.meta.require is not a function, and minified cjs output is a SyntaxError inside the wrapper. On base both minify states were identical (both left as written), so the PR introduces a minify/non-minify divergence, the semantics-changing-minify bug class. Remedy: make the EIndex->EDot shortcut fall through into the same property-access fold the EDot path uses.

Verification: With minify, src/js_parser/visit/visit_expr.rs:995-1016 builds an E::Dot, assigns *e = dot; and returns; maybe_rewrite_property_access is never reached, so no ImportMetaRequire node is produced. Without minify, visit_expr.rs:1023-1039 reaches the fold at src/js_parser/fold.rs:597-630 and prints __require/require. No test uses import.meta["require"].

&& p.options.lower_import_meta_require
&& !p.method_call_must_be_replaced_with_undefined

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 (optional) Node-target builds of code that reads an import.meta.hot method without calling it leave the next import.meta.require unlowered, so it is undefined under node while the same expression a line earlier is a function. The guard at src/js_parser/fold.rs:618 reads method_call_must_be_replaced_with_undefined, which src/js_parser/fold.rs:782 and :816 set for every non-HMR import.meta.hot.<method> access and which only the next call visit clears (src/js_parser/visit/visit_expr.rs:2127). Fix: the --drop check must look at the current expression (e.g. compare the define hit or check the dot is the call target) instead of the sticky parser flag, so a stale flag from a sibling expression cannot suppress lowering.

Why this was flagged

A production (non-HMR) build for node contains, e.g., const dispose = import.meta.hot.dispose; const load = import.meta.require; (Vite-style modules read import.meta.hot methods as values). At src/js_parser/fold.rs:816 the hot method access sets p.method_call_must_be_replaced_with_undefined = true and returns undefined; the flag is only reset inside the next ECall visit at src/js_parser/visit/visit_expr.rs:2124-2127. The import.meta.require read that follows is not a call, so when it reaches the arm at src/js_parser/fold.rs:618 the flag is still set, the guard skips lowering and the dot is printed as import.meta.require, which is undefined under node. The dismissal only checked that drop cannot be defeated; it did not check that the guard's own action, suppressing the lowering, is the user-visible failure when the flag is stale. The author acknowledges this window in the PR notes but ships no test for it and bun/ImportMetaRequireAfterImportMetaHot only covers the call form. Remedy: gate on a per-expression drop decision rather than the sticky flag.

Verification: src/js_parser/fold.rs:782 and :816 set p.method_call_must_be_replaced_with_undefined = true unconditionally. src/js_parser/fold.rs:616-622 requires the flag clear, so an import.meta.require read after a non-call hot-method read is printed as written, undefined under node. On the base branch import.meta.require is never lowered for node, so this input already yields undefined there.

&& !p.is_revisit_for_substitution

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟣 pre-existing, not blocking: Users bundling for node with --minify-syntax get undefined for import.meta.require reached through a local alias of import.meta, while the direct spelling in the same file prints __require. The guard !p.is_revisit_for_substitution at src/js_parser/fold.rs:619 skips the lowering when const m = import.meta; m.require || null is re-visited after inlining (src/js_parser/p.rs:2748-2754), and substitutions whose result is a call never re-run the fold at all (src/js_parser/p.rs:2755-2757), so import.meta.require(...) is emitted verbatim and throws under node. Fix: lower the alias form consistently with the direct form, and record the __require runtime usage at substitution time instead of relying on the revisit.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

Trigger: const m = import.meta; return m.require("x") or m.require || null in a file bundled with --target=node (esm or cjs) and --minify-syntax. The single-use-symbol substitution at p.rs:2735 replaces m with import.meta; when the result is EBinary/EUnary/EIf the revisit runs with is_revisit_for_substitution = true (p.rs:2749) and fold.rs:619 bails; when the result is an ECall no revisit happens (p.rs:2755-2757), so the fold never sees the new import.meta.require E::Dot. The printed output is import.meta.require(...), which is undefined under node (TypeError) and a SyntaxError inside the cjs wrapper, while a sibling direct import.meta.require("x") in the same file is lowered to __require("x"). Remedy: lower at substitution time or block the substitution for .require so both forms agree.

Verification: The new arm at src/js_parser/fold.rs:616-630 bails on !p.is_revisit_for_substitution (line 619); when the result is an ECall there is no revisit at all (p.rs:2755-2757), so the fold never sees the new import.meta.require. The aliased access prints import.meta.require while the direct spelling in the same file prints __require.

&& identifier_opts.assign_target() == js_ast::AssignTarget::None
&& !identifier_opts.is_delete_target()
{
if p.options.features.allow_runtime {
p.record_usage_of_runtime_require();
}
return Some(Expr {
data: js_ast::ExprData::ESpecial(E::Special::ImportMetaRequire),
loc: target.loc,
});
}
Comment on lines +616 to +630

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 Users who bundle for node code that detects Bun by testing import.meta.require now get a startup crash instead of the non-Bun branch. The arm at src/js_parser/fold.rs:616 lowers every non-assigned read, so import.meta.require ? import.meta.require("bun:sqlite") : null or typeof import.meta.require === "function" becomes a test of __require, which is always truthy in node output, and the guarded call then throws. Fix: keep the value undefined where the base did in positions that only test it (typeof, !, ? :, ??, ||, &&, == null) while still lowering calls, .resolve and plain value reads so const r = import.meta.require; r("x") keeps working. [also at: src/bundler/ParseTask.rs:2710 - Node-target bundles of code that feature-detects Bun with import.meta.require now take the Bun branch under node and throw, where on the base they fell back.]

Why this was flagged

A dependency or source file contains const sqlite = import.meta.require ? import.meta.require("bun:sqlite") : null; or if (typeof import.meta.require === "function") { ... Bun-only path ... } and is bundled with bun build --target=node (ESM or CJS) or --target=bun --format=cjs. src/bundler/ParseTask.rs:2702-2710 sets lower_import_meta_require for those outputs; src/js_parser/fold.rs:616-630 then replaces the read with E::Special::ImportMetaRequire for every position except assignment and delete targets, and src/js_printer/lib.rs:3423 prints it as __require or require. Under node the test is now true and the guarded __require("bun:sqlite") throws Cannot find module 'bun:sqlite' at module load. On the base branch the same output printed import.meta.require unchanged, which is undefined under node, so the test was false and the non-Bun branch ran. The PR's own test at test/bundler/bundler_bun.test.ts:443 (tested() expects "has require") records this change for an ordinary input.

Verification: src/js_parser/fold.rs:616-630 replaces every non-assigned, non-deleted read of import.meta.require with E::Special::ImportMetaRequire when lower_import_meta_require is set. On the base commit the EImportMeta arm left the access as written, so node evaluated import.meta.require to undefined and took the non-Bun branch; this is a regression that works on the base.


// Inline import.meta properties for Bake
if p.options.framework.is_some()
|| (p.options.bundle
Expand Down
3 changes: 3 additions & 0 deletions src/js_parser/p.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6177,6 +6177,9 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
| js_ast::ExprData::EArrow(_)
| js_ast::ExprData::EImportMeta(_) => return true,

// No side effects, like the `import.meta.require` that it replaces.
js_ast::ExprData::ESpecial(E::Special::ImportMetaRequire) => return true,

js_ast::ExprData::EInlinedEnum(e) => {
return self.expr_can_be_removed_if_unused_without_dce_check(&e.value);
}
Expand Down
5 changes: 5 additions & 0 deletions src/js_parser/parse/parse_entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,8 @@ pub struct Options<'a> {
/// Used for inlining the state of import.meta.main during visiting
pub import_meta_main_value: Option<bool>,
pub lower_import_meta_main_for_node_js: bool,
/// The output of this file has a `require` and cannot evaluate `import.meta.require`: the printer spells the one as the other.
pub lower_import_meta_require: bool,

/// When using react fast refresh or server components, the framework is
/// able to customize what import sources are used.
Expand Down Expand Up @@ -227,6 +229,7 @@ impl<'a> Default for Options<'a> {
transform_only: false,
import_meta_main_value: None,
lower_import_meta_main_for_node_js: false,
lower_import_meta_require: false,
framework: None,
repl_mode: false,
lower_toml_datetimes: false,
Expand Down Expand Up @@ -315,6 +318,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,
lower_import_meta_require: self.lower_import_meta_require,
framework: self.framework,
repl_mode: self.repl_mode,
lower_toml_datetimes: self.lower_toml_datetimes,
Expand Down Expand Up @@ -390,6 +394,7 @@ impl<'a> Options<'a> {
transform_only: false,
import_meta_main_value: None,
lower_import_meta_main_for_node_js: false,
lower_import_meta_require: false,
framework: None,
repl_mode: false,
lower_toml_datetimes: loader == options::Loader::Toml,
Expand Down
1 change: 1 addition & 0 deletions src/js_parser/scan/scan_side_effects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -985,6 +985,7 @@ impl SideEffects {
ExprData::ESpecial(special) => match special {
E::Special::ModuleExports
| E::Special::ResolvedSpecifierString(_)
| E::Special::ImportMetaRequire
| E::Special::HotData => None,
E::Special::HotAccept | E::Special::HotAcceptVisited | E::Special::HotEnabled => {
Some(Known {
Expand Down
10 changes: 10 additions & 0 deletions src/js_printer/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3420,6 +3420,16 @@ pub(crate) mod __gated_printer {
true,
);
}
E::Special::ImportMetaRequire => {
self.print_expr(
Expr {
data: ExprData::ERequireCallTarget,
loc: expr.loc,
},
level,
Comment on lines 3420 to +3429

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 (optional) Dev-server client code that stores import.meta.require in a variable before calling it loses HMR dependency tracking, so edits to the required file now force a full page reload. The node prints as hmr.require (src/js_printer/lib.rs:3565), a prototype method whose this is the importer; called unbound, loadModuleSync gets importer === undefined and never records the edge (src/runtime/bake/hmr-module.ts:147, 307). On the base the client printed hmr.importMeta.require, which is this.require.bind(this) (hmr-module.ts:179). Fix: make the value safe to call detached for both require and import.meta.require, e.g. bind require per instance in the HMRModule constructor or print hmr.require.bind(hmr) when ERequireCallTarget is not the call target.

Why this was flagged

A dev-server client module contains const load = import.meta.require; const dep = load("./dep.js");. With output format InternalBakeDev, src/js_parser/fold.rs:616-629 returns E::Special::ImportMetaRequire, and src/js_printer/lib.rs:3420-3429 prints it through ERequireCallTarget, which for InternalBakeDev emits hmr.require (src/js_printer/lib.rs:3565-3567). HMRModule.prototype.require (src/runtime/bake/hmr-module.ts:145-147) calls loadModuleSync(id, true, this); invoked detached from load, this is undefined, so if (importer) mod.importers.add(importer) at hmr-module.ts:307-308 and 330-331 is skipped. When ./dep.js is edited, the hot-update walk at hmr-module.ts:676-679 sees importers.size === 0 without a self-accept, records a failure and does a full reload with the "root module that does not self-accept" message instead of propagating to the importer's import.meta.hot.accept. On the base branch the same source printed hmr.importMeta.require (src/js_printer/lib.rs:3282-3285), which is this.require.bind(this) at hmr-module.ts:179, so the importer edge was recorded.

Verification: HMRModule.prototype.require (hmr-module.ts:145-148) calls loadModuleSync(id, true, this); as a class method it runs in strict mode, so an unbound call passes importer === undefined. Every mod.importers.add(importer) site is guarded by if (importer) (hmr-module.ts:307, 330, 369, 418, 444, 481), so the call succeeds silently but records no edge.

in_flags,
);
}
},
ExprData::ECommonjsExportIdentifier(id) => {
self.print_commonjs_export_identifier(*id, expr.loc, false);
Expand Down
7 changes: 6 additions & 1 deletion src/react_compiler/hir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1457,7 +1457,12 @@ impl NonLocalBinding {
Tag::ERequireMain => b"require.main",
Tag::EImportMetaMain => b"import.meta.main",
Tag::EBranchBoolean => b"feature()",
Tag::ESpecial => b"module.exports",
Tag::ESpecial => match e.data {
bun_ast::ExprData::ESpecial(bun_ast::E::Special::ImportMetaRequire) => {
b"import.meta.require"
}
_ => b"module.exports",
},
_ => b"<bun-opaque>",
}
}
Expand Down
18 changes: 9 additions & 9 deletions src/react_compiler/lowering/build_hir/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,15 +331,15 @@ pub(crate) fn lower_expression(
loc,
}),
Data::ESpecial(special) => match special {
E::Special::ModuleExports | E::Special::ResolvedSpecifierString(_) => {
Ok(InstructionValue::LoadGlobal {
binding: NonLocalBinding {
ref_: Ref::NONE,
kind: NonLocalKind::BunOpaque(*expr),
},
loc,
})
}
E::Special::ModuleExports
| E::Special::ResolvedSpecifierString(_)
| E::Special::ImportMetaRequire => Ok(InstructionValue::LoadGlobal {
binding: NonLocalBinding {
ref_: Ref::NONE,
kind: NonLocalKind::BunOpaque(*expr),
},
loc,
}),
E::Special::HotEnabled
| E::Special::HotDisabled
| E::Special::HotData
Expand Down
21 changes: 18 additions & 3 deletions test/bake/dev-and-prod.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Tests which apply to both dev and prod. They are run twice.
import { writeFileSync } from "node:fs";
import { devAndProductionTest, devTest, emptyHtmlFile, WAIT_MULTIPLIER } from "./bake-harness";
import { devAndProductionTest, devTest, emptyHtmlFile, minimalFramework, WAIT_MULTIPLIER } from "./bake-harness";

const hmrSelfAcceptingModule = (label: string) => `
console.log(${JSON.stringify(label)});
Expand Down Expand Up @@ -193,15 +193,30 @@ devTest("using runtime import", {
// TODO: all of these should be `hmr.require`
"()=>hmr.require",
"()=>module.require", // not being visited
"()=>hmr.importMeta.require", // not being visited
"()=>hmr.require",
true,
false,
false,
true,
]
: []),
);
},
});
// The server side of the dev server gets the same node as the browser side.
devTest("import.meta.require in a route is hmr.require", {
framework: minimalFramework,
files: {
"routes/index.ts": `
const load = () => import.meta.require;
export default function (req, meta) {
return new Response(load.toString().replaceAll(" ", "").replaceAll("\\n", "") + " " + (load() === eval("hmr.require")));
}
`,
},
async test(dev) {
await dev.fetch("/").equals("()=>hmr.require true");
},
});
devTest("hmr handles rapid consecutive edits", {
files: {
"index.html": emptyHtmlFile({
Expand Down
Loading
Loading