Skip to content
21 changes: 21 additions & 0 deletions src/jsc/NodeModuleModule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,21 +228,42 @@
Ok(())
}

/// Keys that `JSCommonJSExtensions::finishCreation` installs on the
/// `Module._extensions` object. Used by [`find_longest_registered_extension`]
/// to decide whether an unmatched extension should fall back to `.js`.
Comment thread
robobun marked this conversation as resolved.
Resolved
const EXTENSIONS_DEFAULT_KEYS: &[&[u8]] =
&[b".js", b".json", b".node", b".ts", b".cts", b".mjs", b".mts"];

pub fn find_longest_registered_extension<'a>(
vm: &'a VirtualMachine,
filename: &[u8],
) -> Option<&'a CustomLoader> {
let basename = bun_paths::basename(filename);
let mut next: usize = 0;
let mut last_ext: &[u8] = b"";
while let Some(i) = strings::index_of_char_pos(basename, b'.', next) {
next = i + 1;
if i == 0 {
continue;
}
let ext = &basename[i..];
last_ext = ext;
if let Some(value) = vm.commonjs_custom_extensions.get(ext) {
return Some(value);
}
if EXTENSIONS_DEFAULT_KEYS.iter().any(|k| *k == ext) {

Check failure on line 254 in src/jsc/NodeModuleModule.rs

View workflow job for this annotation

GitHub Actions / cargo clippy

using `contains()` instead of `iter().any()` is more efficient
// A default `_extensions` key matched but wasn't overridden; use
// Bun's native loader for it.
Comment thread
robobun marked this conversation as resolved.
Resolved
return None;
}
}
// Node's `findLongestRegisteredExtension` returns `.js` when no key
// matched, so `.cjs` (and any unrecognised extension) is loaded via the
// `.js` handler. Mirror that only when `.js` itself has been overridden,
// and only for extensions Bun does not already handle natively so hooking
// `.js` does not hijack `.jsx`/`.tsx`/`.toml` etc.
Comment thread
robobun marked this conversation as resolved.
Resolved
if !last_ext.is_empty() && (last_ext == b".cjs" || DEFAULT_LOADERS.get(last_ext).is_none()) {
return vm.commonjs_custom_extensions.get(b".js".as_slice());
}
Comment thread
robobun marked this conversation as resolved.
Resolved
None
}
Expand Down
76 changes: 70 additions & 6 deletions src/jsc/bindings/JSCommonJSModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1189,6 +1189,7 @@
visitor.appendHidden(thisObject->m_paths);
visitor.appendHidden(thisObject->m_overriddenParent);
visitor.appendHidden(thisObject->m_overriddenCompile);
visitor.appendHidden(thisObject->m_pendingCustomExtension);
visitor.appendHidden(thisObject->m_childrenValue);
{
WTF::Locker locker { thisObject->cellLock() };
Expand Down Expand Up @@ -1551,12 +1552,23 @@
if (entry) {
if (auto* moduleObject = dynamicDowncast<JSCommonJSModule>(entry)) {
if (!moduleObject->hasEvaluated) {
evaluateCommonJSModuleOnce(
vm,
globalObject,
moduleObject,
moduleObject->m_dirname.get(),
moduleObject->m_filename.get());
if (JSValue extension = moduleObject->m_pendingCustomExtension.get()) {
moduleObject->m_pendingCustomExtension.clear();
evaluateCommonJSCustomExtension(
globalObject,
moduleObject,
moduleKey.string(),
moduleObject->m_filename.get(),
extension);
moduleObject->hasEvaluated = true;
} else {
evaluateCommonJSModuleOnce(
vm,
globalObject,
moduleObject,
moduleObject->m_dirname.get(),
moduleObject->m_filename.get());
}
if (auto exception = scope.exception()) {
(void)scope.tryClearException();

Expand Down Expand Up @@ -1633,6 +1645,58 @@
return commonJSModuleSyntheticSourceCode(sourceOrigin, sourceURL);
}

std::optional<JSC::SourceCode> createCommonJSModuleForCustomExtension(
Zig::GlobalObject* globalObject,
JSC::JSString* requireMapKey,
JSC::JSValue extension)
{
auto& vm = JSC::getVM(globalObject);
auto scope = DECLARE_THROW_SCOPE(vm);
JSCommonJSModule* moduleObject = nullptr;
WTF::String sourceURL = requireMapKey->value(globalObject);
RETURN_IF_EXCEPTION(scope, {});
SourceOrigin sourceOrigin = Zig::toSourceOrigin(sourceURL, false);

JSValue entry = globalObject->requireMap()->get(globalObject, requireMapKey);
RETURN_IF_EXCEPTION(scope, {});

if (entry) {
moduleObject = dynamicDowncast<JSCommonJSModule>(entry);
}

if (!moduleObject) {
size_t index = sourceURL.reverseFind(PLATFORM_SEP, sourceURL.length());
JSString* dirname;
JSString* filename = requireMapKey;
if (index != WTF::notFound) {
dirname = JSC::jsSubstring(globalObject, requireMapKey, 0, index);
RETURN_IF_EXCEPTION(scope, {});
} else {
dirname = jsEmptyString(vm);
}
auto requireMap = globalObject->requireMap();
if (requireMap->size() == 0) {
requireMapKey = JSC::jsString(vm, WTF::String("."_s));
}

moduleObject = JSCommonJSModule::create(
vm,
globalObject->CommonJSModuleObjectStructure(),
requireMapKey, filename, dirname, JSC::SourceCode());

moduleObject->putDirect(vm,
WebCore::clientData(vm)->builtinNames().exportsPublicName(),
JSC::constructEmptyObject(globalObject, globalObject->objectPrototype()), 0);

requireMap->set(globalObject, filename, moduleObject);
RETURN_IF_EXCEPTION(scope, {});
}

Check warning on line 1693 in src/jsc/bindings/JSCommonJSModule.cpp

View check run for this annotation

Claude / Claude Code Review

createCommonJSModuleForCustomExtension is a third near-verbatim copy of the get-or-create block

Nit: this is now the third near-verbatim copy of the same ~30-line get-or-create block (requireMap lookup → dynamicDowncast → `reverseFind(PLATFORM_SEP)` dirname → `size()==0` '.' id rewrite → `JSCommonJSModule::create` → `putDirect(exportsPublicName, constructEmptyObject)` → `requireMap->set`) alongside the two existing `createCommonJSModule` overloads in this file. A shared static `getOrCreateCommonJSModule(globalObject, requireMapKey, sourceURL, sourceCode)` helper that all three call would k
Comment thread
robobun marked this conversation as resolved.
Resolved

moduleObject->m_pendingCustomExtension.set(vm, moduleObject, extension);

Check failure on line 1695 in src/jsc/bindings/JSCommonJSModule.cpp

View check run for this annotation

Claude / Claude Code Review

load() ignores m_pendingCustomExtension: cross-require between ESM-imported CJS siblings returns empty {}

`JSCommonJSModule::load()` short-circuits on `sourceCode.isNull()` without checking `m_pendingCustomExtension`, so when an ESM entry statically imports two CJS siblings and the first one's body does `require('./b.js')`, `overridableRequire` finds b already in `$requireMap`, `load()` no-ops, and `require()` returns the pristine empty `{}` — b.js's extension handler never runs. Before this PR the same import stored real transpiled `sourceCode` so `load()` evaluated it on demand; `load()` (or `jsFu
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved

return commonJSModuleSyntheticSourceCode(sourceOrigin, sourceURL);
}

JSObject* JSCommonJSModule::createBoundRequireFunction(VM& vm, JSGlobalObject* lexicalGlobalObject, const WTF::String& pathString)
{
ASSERT(!pathString.startsWith("file://"_s));
Expand Down
10 changes: 10 additions & 0 deletions src/jsc/bindings/JSCommonJSModule.h
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ class JSCommonJSModule final : public JSC::JSDestructibleObject {
// If compile is overridden, it is assigned to this field. The default
// compile function is not stored here, but in
mutable JSC::WriteBarrier<Unknown> m_overriddenCompile;
// When a CJS module is reached via the ESM loader (entrypoint or
// `import` of CJS) and a `Module._extensions` handler applies, the
// handler is stashed here so the deferred synthetic-module evaluation
// can invoke it instead of evaluating pre-transpiled source.
Comment thread
robobun marked this conversation as resolved.
Resolved
mutable JSC::WriteBarrier<Unknown> m_pendingCustomExtension;

bool ignoreESModuleAnnotation { false };
JSC::SourceCode sourceCode = JSC::SourceCode();
Expand Down Expand Up @@ -184,6 +189,11 @@ inline std::optional<JSC::SourceCode> createCommonJSModule(
return createCommonJSModule(globalObject, specifierValue, source, false);
}

std::optional<JSC::SourceCode> createCommonJSModuleForCustomExtension(
Zig::GlobalObject* globalObject,
JSC::JSString* specifierValue,
JSC::JSValue extension);

class RequireResolveFunctionPrototype final : public JSC::JSNonFinalObject {
public:
using Base = JSC::JSNonFinalObject;
Expand Down
18 changes: 18 additions & 0 deletions src/jsc/bindings/ModuleLoader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1114,6 +1114,24 @@ static JSValue fetchESMSourceCode(
RELEASE_AND_RETURN(scope, reject(exception));
}

if (res->result.value.tag == SyntheticModuleType::CommonJSCustomExtension) {
auto created = Bun::createCommonJSModuleForCustomExtension(
globalObject, specifierJS, JSC::JSValue::decode(res->result.value.cjsCustomExtension));
EXCEPTION_ASSERT(created.has_value() == !scope.exception());
if (created.has_value()) {
RELEASE_AND_RETURN(scope, rejectOrResolve(JSSourceCode::create(vm, WTF::move(created.value()))));
}

if constexpr (allowPromise) {
auto* exception = scope.exception();
(void)scope.tryClearException();
RELEASE_AND_RETURN(scope, rejectedInternalPromise(globalObject, exception));
} else {
scope.release();
return {};
}
}

// The JSONForObjectLoader tag is source code returned from Bun that needs
// to go through the JSON parser in JSC.
//
Expand Down
7 changes: 7 additions & 0 deletions src/jsc/bindings/ModuleLoader.h
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,11 @@ JSValue fetchBuiltinModuleWithoutResolution(
BunString* specifier,
ErrorableResolvedSource* res);

void evaluateCommonJSCustomExtension(
Zig::GlobalObject* globalObject,
JSCommonJSModule* target,
String filename,
JSValue filenameValue,
JSValue extension);

} // namespace Bun
69 changes: 38 additions & 31 deletions src/runtime/jsc_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4229,15 +4229,52 @@ unsafe fn transpile_file(
}
});

// ── module_type sniff from extension / package.json ─────────────────────
let module_type: ModuleType = 'brk: {
let ext = lr.path.name().ext;
// regex /\.[cm][jt]s$/
if ext.len() == b".cjs".len() {
if ext == b".cjs" {
break 'brk ModuleType::Cjs;
}
if ext == b".mjs" {
break 'brk ModuleType::Esm;
}
if ext == b".cts" {
break 'brk ModuleType::Cjs;
}
if ext == b".mts" {
break 'brk ModuleType::Esm;
}
}
// regex /\.[jt]s$/
if ext.len() == b".ts".len() && (ext == b".js" || ext == b".ts") {
// Use the package.json module type if it exists.
break 'brk lr
.package_json
.map(|pkg| pkg.module_type)
.unwrap_or(ModuleType::Unknown);
}
// For JSX/TSX and other extensions, let the file contents decide.
ModuleType::Unknown
};

// ── force_loader / require.extensions override ──────────────────────────
if let Some(loader_type) = force_loader_type {
// Note: `@branchHint(.unlikely)` dropped (no stable Rust equiv).
debug_assert!(!is_commonjs_require);
lr.loader = Some(loader_type);
} else if is_commonjs_require
} else if (is_commonjs_require || module_type != ModuleType::Esm)
&& lr.virtual_source.is_none()
Comment thread
robobun marked this conversation as resolved.
Resolved
// SAFETY: per fn contract.
&& unsafe { &*jsc_vm }.has_mutated_built_in_extensions > 0
{
// Node.js routes every CJS-loader load (the entrypoint, nested
// require(), and a CJS module reached from ESM import) through
// `Module._extensions[ext]`. `is_commonjs_require` alone covers only
// nested require(); gating on `module_type != Esm` adds the entrypoint
// and ESM-imports-CJS paths while still skipping `.mjs`/`.mts` and
// `.js` under `"type": "module"`.
Comment thread
robobun marked this conversation as resolved.
Resolved
use bun_jsc::node_module_module::{CustomLoader, find_longest_registered_extension};
if let Some(entry) =
// SAFETY: per fn contract.
Expand All @@ -4262,36 +4299,6 @@ unsafe fn transpile_file(
}
}
}

// ── module_type sniff from extension / package.json ─────────────────────
let module_type: ModuleType = 'brk: {
let ext = lr.path.name().ext;
// regex /\.[cm][jt]s$/
if ext.len() == b".cjs".len() {
if ext == b".cjs" {
break 'brk ModuleType::Cjs;
}
if ext == b".mjs" {
break 'brk ModuleType::Esm;
}
if ext == b".cts" {
break 'brk ModuleType::Cjs;
}
if ext == b".mts" {
break 'brk ModuleType::Esm;
}
}
// regex /\.[jt]s$/
if ext.len() == b".ts".len() && (ext == b".js" || ext == b".ts") {
// Use the package.json module type if it exists.
break 'brk lr
.package_json
.map(|pkg| pkg.module_type)
.unwrap_or(ModuleType::Unknown);
}
// For JSX/TSX and other extensions, let the file contents decide.
ModuleType::Unknown
};
let pkg_name: Option<&[u8]> = lr
.package_json
.and_then(|pkg| (!pkg.name.is_empty()).then_some(&*pkg.name));
Expand Down
Loading
Loading