From a0943953e0cffe0951318e1b4b246bbe485abe5d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 15 Aug 2026 23:32:03 +0000 Subject: [PATCH 1/2] bundler: keep exported and using declarations initialized by an unwrapped require() visit_decls replaces `const x = require("pkg")` with the import the require() becomes when pkg is on the CommonJS unwrap list, dropping the declaration. That lost the `export` keyword of exported declarations (including TypeScript `export import x = require()` and exports inside a namespace) and the disposal of `using` declarations. The bool that asked transpose_require for the replaceable-declaration marker becomes a three-state RequireUnwrap, chosen by visit_decls from the statement's kind and export flag: exported declarations bind the import namespace like any other expression and survive, `using` and `await using` declarations keep an ordinary require() so the value they dispose is the module's own exports, and everything else folds into the import as before. --- src/js_parser/p.rs | 12 +-- src/js_parser/parser.rs | 21 +++-- src/js_parser/visit/mod.rs | 17 +++- src/js_parser/visit/visit_expr.rs | 12 ++- src/js_parser/visit/visit_stmt.rs | 5 +- test/bundler/bundler_cjs2esm.test.ts | 118 +++++++++++++++++++++++++++ 6 files changed, 165 insertions(+), 20 deletions(-) diff --git a/src/js_parser/p.rs b/src/js_parser/p.rs index 6db4b4882930..06612df9c713 100644 --- a/src/js_parser/p.rs +++ b/src/js_parser/p.rs @@ -24,9 +24,10 @@ use crate::{ FindLabelSymbolResult, FnOnlyDataVisit, FnOrArrowDataParse, FnOrArrowDataVisit, FunctionKind, IdentifierOpts, ImportItemForNamespaceMap, InvalidLoc, JSXImport, JSXTransformType, Jest, LOC_MODULE_SCOPE as loc_module_scope, LocList, MacroState, ParseStatementOptions, ParsedPath, - PrependTempRefsOpts, ReactRefresh, Ref, RefMap, RefRefMap, RuntimeImports, ScopeOrder, - ScopeOrderList, StrictModeFeature, StringBoolMap, Substitution, TempRef, ThenCatchChain, - TransposeState, WrapMode, fs, is_eval_or_arguments, options, statement_cares_about_scope, + PrependTempRefsOpts, ReactRefresh, Ref, RefMap, RefRefMap, RequireUnwrap, RuntimeImports, + ScopeOrder, ScopeOrderList, StrictModeFeature, StringBoolMap, Substitution, TempRef, + ThenCatchChain, TransposeState, WrapMode, fs, is_eval_or_arguments, options, + statement_cares_about_scope, }; use bun_ast as js_ast; use bun_ast::DeclaredSymbol; @@ -1147,7 +1148,8 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O // We cannot unwrap a require wrapped in a try/catch because // import statements cannot be wrapped in a try/catch and // require cannot return a promise. - && !handles_import_errors; + && !handles_import_errors + && state.require_unwrap != RequireUnwrap::Disabled; if should_unwrap_require { let import_record_index = self.add_import_record_by_range_and_path( @@ -1190,7 +1192,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O .insert(namespace_ref, ImportItemForNamespaceMap::default()); self.record_usage(namespace_ref); - if !state.is_require_immediately_assigned_to_decl { + if state.require_unwrap != RequireUnwrap::IntoDecl { return self.new_expr( E::Identifier { ref_: namespace_ref, diff --git a/src/js_parser/parser.rs b/src/js_parser/parser.rs index 8be190092052..8a879c34fda4 100644 --- a/src/js_parser/parser.rs +++ b/src/js_parser/parser.rs @@ -691,11 +691,23 @@ pub struct VisitDeclOpts { pub(crate) could_be_macro: bool, } +/// What a `require()` of a package on the CommonJS unwrap list becomes at the visited position. +#[derive(Clone, Copy, PartialEq, Eq, Default)] +pub(crate) enum RequireUnwrap { + /// A reference to the namespace of the `import * as ns` it becomes. + #[default] + Namespace, + /// `const x = require("pkg")`: the import takes over `x` and `visit_decls` drops the declarator. + IntoDecl, + /// Stays a plain `require()`, as inside a try/catch: `using` disposes the required value itself. + Disabled, +} + #[derive(Clone, Copy)] pub struct TransposeState { pub(crate) is_await_target: bool, pub(crate) is_then_catch_target: bool, - pub(crate) is_require_immediately_assigned_to_decl: bool, + pub(crate) require_unwrap: RequireUnwrap, pub(crate) loc: bun_ast::Loc, pub(crate) import_record_tag: Option, pub(crate) import_loader: Option, @@ -707,7 +719,7 @@ impl Default for TransposeState { Self { is_await_target: false, is_then_catch_target: false, - is_require_immediately_assigned_to_decl: false, + require_unwrap: RequireUnwrap::Namespace, loc: bun_ast::Loc::EMPTY, import_record_tag: None, import_loader: None, @@ -1011,9 +1023,8 @@ pub struct ExprIn { /// tests. pub(crate) assign_target: js_ast::AssignTarget, - /// Currently this is only used when unwrapping a call to `require()` - /// with `__toESM()`. - pub(crate) is_immediately_assigned_to_decl: bool, + /// Set by `visit_decls` when the expression initializes a declarator. + pub(crate) require_unwrap: RequireUnwrap, pub(crate) property_access_for_method_call_maybe_should_replace_with_undefined: bool, } diff --git a/src/js_parser/visit/mod.rs b/src/js_parser/visit/mod.rs index 685d5e1ef7a5..7f93b9525e3c 100644 --- a/src/js_parser/visit/mod.rs +++ b/src/js_parser/visit/mod.rs @@ -10,8 +10,8 @@ use crate::lexer as js_lexer; use crate::p::{LowerUsingDeclarationsContext, P}; use crate::parser::{ ExprIn, FnOnlyDataVisit, FnOrArrowDataVisit, ImportItemForNamespaceMap, PrependTempRefsOpts, - Ref, RelocateVarsMode, ScopeOrder, StmtsKind, StrictModeFeature, StringVoidMap, VisitArgsOpts, - VisitDeclOpts, is_eval_or_arguments, + Ref, RelocateVarsMode, RequireUnwrap, ScopeOrder, StmtsKind, StrictModeFeature, StringVoidMap, + VisitArgsOpts, VisitDeclOpts, is_eval_or_arguments, }; use bun_alloc::{ArenaVec as BumpVec, ArenaVecExt as _}; use bun_ast as js_ast; @@ -242,8 +242,17 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O pub(crate) fn visit_decls( &mut self, decls: &mut [G::Decl], - was_const: bool, + kind: LocalKind, + is_export: bool, ) -> usize { + let was_const = kind == LocalKind::KConst; + let require_unwrap = if kind.is_using() { + RequireUnwrap::Disabled + } else if is_export { + RequireUnwrap::Namespace + } else { + RequireUnwrap::IntoDecl + }; let mut j: usize = 0; // Iterate by index so kept entries can be written back through `decls[j]` // while scanning ahead. @@ -320,7 +329,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O self.visit_expr_in_out( &mut val, ExprIn { - is_immediately_assigned_to_decl: true, + require_unwrap, ..Default::default() }, ); diff --git a/src/js_parser/visit/visit_expr.rs b/src/js_parser/visit/visit_expr.rs index 260a937e154b..768a0ecd3fd9 100644 --- a/src/js_parser/visit/visit_expr.rs +++ b/src/js_parser/visit/visit_expr.rs @@ -9,7 +9,8 @@ use crate::lexer as js_lexer; use crate::p::P; use crate::parser::{ ExprIn, FnOrArrowDataVisit, IdentifierOpts, PrependTempRefsOpts, ReactRefresh, Ref, - StrictModeFeature, ThenCatchChain, TransposeState, VisitArgsOpts, float_to_int32, prefill, + RequireUnwrap, StrictModeFeature, ThenCatchChain, TransposeState, VisitArgsOpts, + float_to_int32, prefill, }; use crate::scan::scan_side_effects::SideEffects; use bun_alloc::ArenaVecExt as _; @@ -2019,8 +2020,13 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O if e_.args.len_u32() == 1 { let first = e_.args.slice()[0]; let state = TransposeState { - is_require_immediately_assigned_to_decl: in_.is_immediately_assigned_to_decl - && matches!(first.data, Data::EString(..)), + require_unwrap: match in_.require_unwrap { + // Only a string literal can take over the declaration. + RequireUnwrap::IntoDecl if !matches!(first.data, Data::EString(..)) => { + RequireUnwrap::Namespace + } + mode => mode, + }, ..Default::default() }; match &first.data { diff --git a/src/js_parser/visit/visit_stmt.rs b/src/js_parser/visit/visit_stmt.rs index dfce8bec1923..6a9f4c2dda8b 100644 --- a/src/js_parser/visit/visit_stmt.rs +++ b/src/js_parser/visit/visit_stmt.rs @@ -1132,11 +1132,10 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O p.cur_scope().is_after_const_local_prefix = was_after_after_const_local_prefix; // visit_decls returns the surviving decl count; truncate `data.decls.len` to it. - let was_const = data.kind == S::Kind::KConst; let new_len = if !(data.is_export && p.options.features.replace_exports.entries.len() > 0) { - p.visit_decls::(data.decls.slice_mut(), was_const) + p.visit_decls::(data.decls.slice_mut(), data.kind, data.is_export) } else { - p.visit_decls::(data.decls.slice_mut(), was_const) + p.visit_decls::(data.decls.slice_mut(), data.kind, data.is_export) }; // Drop the whole statement when every decl was // eliminated; otherwise we'd emit an empty `var;`/`let;`/`const;`. diff --git a/test/bundler/bundler_cjs2esm.test.ts b/test/bundler/bundler_cjs2esm.test.ts index 2ab2c8769c22..75fc634f9c24 100644 --- a/test/bundler/bundler_cjs2esm.test.ts +++ b/test/bundler/bundler_cjs2esm.test.ts @@ -320,6 +320,124 @@ describe("bundler", () => { stdout: "react\nreact", }, }); + // `const x = require("react")` is normally replaced by the import it becomes. + // An exported declaration has to survive as a declaration, or the export is + // dropped with it. + itBundled("cjs2esm/UnwrappedModuleRequireExported", { + files: { + "/entry.js": /* js */ ` + import { constReact, varReact, letReact, first, second, third } from "./lib.js"; + import { importEquals, NS } from "./lib-ts.ts"; + console.log(constReact.react, varReact.react, letReact.react); + console.log(first.react, second, third.react); + console.log(importEquals.react, NS.react.react); + `, + "/lib.js": /* js */ ` + export const constReact = require("react"); + export var varReact = require("react"); + export let letReact = require("react"); + export const first = require("react"), + second = "second", + third = require("react"); + `, + "/lib-ts.ts": /* ts */ ` + export import importEquals = require("react"); + export namespace NS { + export const react = require("react"); + } + `, + ...fakeReactNodeModules, + }, + run: { + stdout: "react react react\nreact second react\nreact react", + }, + }); + // Same against a package that converts to ESM. The unexported declaration is + // still folded into the import; the exported one stays a declaration. + itBundled("cjs2esm/UnwrappedModuleRequireExportedConverted", { + files: { + "/entry.js": /* js */ ` + import { exported } from "./lib.js"; + console.log(exported.react); + `, + "/lib.js": /* js */ ` + export const exported = require("react"); + const unexported = require("react"); + console.log(unexported.react); + `, + "/node_modules/react/index.js": /* js */ ` + exports.react = "react"; + `, + "/node_modules/react/package.json": /* json */ ` + { + "name": "react", + "version": "2.0.0", + "main": "index.js" + } + `, + }, + onAfterBundle: api => { + const code = api.readFile("out.js"); + expect(code).toMatch(/var exported = \(?exports_react\)?;/); + expect(code).not.toContain("unexported"); + }, + run: { + stdout: "react\nreact", + }, + }); + // A `using` declaration disposes the required value itself, so its require() + // is not unwrapped at all: the import namespace __toESM() builds has no + // symbol-keyed properties and only getters. The expected output is what the + // entry prints unbundled. + itBundled("cjs2esm/UnwrappedModuleRequireUsing", { + files: { + "/entry.js": /* js */ ` + import reactExports from "react"; + import schedulerExports from "scheduler"; + { + using react = require("react"); + await using scheduler = require("scheduler"); + using conditional = require(Math.random() < 2 ? "react" : "scheduler"); + console.log(react.react, scheduler.scheduler, conditional.react); + console.log(react === reactExports, scheduler === schedulerExports, conditional === reactExports); + } + console.log("after", reactExports.disposed, schedulerExports.disposed); + `, + "/node_modules/react/index.js": /* js */ ` + module.exports = { + react: "react", + [Symbol.dispose]() { + this.disposed = true; + console.log("dispose react"); + }, + }; + `, + "/node_modules/react/package.json": /* json */ ` + { + "name": "react", + "version": "2.0.0", + "main": "index.js" + } + `, + "/node_modules/scheduler/index.js": /* js */ ` + exports.scheduler = "scheduler"; + exports[Symbol.asyncDispose] = async function () { + this.disposed = true; + console.log("dispose scheduler"); + }; + `, + "/node_modules/scheduler/package.json": /* json */ ` + { + "name": "scheduler", + "version": "1.0.0", + "main": "index.js" + } + `, + }, + run: { + stdout: "react scheduler react\ntrue true true\ndispose react\ndispose scheduler\ndispose react\nafter true true", + }, + }); itBundled("cjs2esm/ReactSpecificUnwrapping", { files: { "/entry.js": /* js */ ` From 4afe33b259d72dd7f295bbb6a8a8460be9d327a5 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 16 Aug 2026 04:52:38 +0000 Subject: [PATCH 2/2] ci: retrigger