Skip to content
Merged
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
4 changes: 2 additions & 2 deletions docs/reference/detail/new-module-registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -827,8 +827,8 @@ if (isolate.isUsingNewModuleRegistry()) {
The isolate-level bit is set at isolate construction from
`isNewModuleRegistryEnabled(flags)` (`io/features.h`), which returns false for
Python workers regardless of the `new_module_registry` flag. All other
flag-check sites (`worker-factory.c++` registry creation, `worker.c++` compile paths and
the nodejs_compat_v2 process/buffer warm-up, and the api-level require paths)
flag-check sites (`worker-factory.c++` registry creation, `worker.c++` compile paths,
the lazy `process` and `Buffer` getters in `global-scope.c++`, and the api-level require paths)
route through the same function, so a worker can never be split across the two
registries. Note that `Cloudflare.compatibilityFlags.new_module_registry` as
observed by user code still reflects the configured flag value; the function
Expand Down
7 changes: 5 additions & 2 deletions src/node/internal/internal_process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -434,16 +434,19 @@ export function emitWarning(

// Emit the warning event on the process object
// Use nextTick to ensure the warning is emitted asynchronously
// The process object is only set once its module has loaded, which happens on first use. Before
// that, nothing can have a 'warning' listener, so there is nothing to emit to.
queueMicrotask(() => {
(_process as typeof publicProcessType).emit('warning', err);
(_process as typeof publicProcessType | undefined)?.emit('warning', err);
});
}

// Events has a cycle with process, so to resolve that we lazily bind
// this _process for events usage only. All other internal importers should
// import 'node:process' directly rather, as _eventsProcess is only guaranteed
// to be available when that has been imported.
export let _process: typeof legacyProcessType | typeof publicProcessType;
export let _process:
typeof legacyProcessType | typeof publicProcessType | undefined;
export function _setEventsProcess(
process: typeof legacyProcessType | typeof publicProcessType
): void {
Expand Down
13 changes: 13 additions & 0 deletions src/workerd/api/global-scope.c++
Original file line number Diff line number Diff line change
Expand Up @@ -1380,6 +1380,14 @@ jsg::JsValue ServiceWorkerGlobalScope::getBuffer(jsg::Lock& js) {
return p.getHandle(js);
}
constexpr auto kSpecifier = "node:buffer"_kj;
// This loads the module on first access. With the new module registry, a require() at
// evaluation depth 0 drains the microtask queue, so a first access during a request would run
// the Worker's pending microtasks inside this getter. node:buffer is a synchronous built-in
// that settles without a drain, so it is resolved as if nested in a module evaluation.
kj::Maybe<jsg::Lock::ModuleEvaluationScope> scope;
if (isNewModuleRegistryEnabled(FeatureFlags::get(js))) {
scope.emplace(js);
}
KJ_IF_SOME(module, js.resolveModule(kSpecifier)) {
KJ_IF_SOME(p, bufferValue) {
// There's a chance that resolving the module caused side-effects
Expand Down Expand Up @@ -1448,6 +1456,11 @@ jsg::JsValue ServiceWorkerGlobalScope::getProcess(jsg::Lock& js) {
}
})();

// Resolved as if nested in a module evaluation, for the reason given in getBuffer().
kj::Maybe<jsg::Lock::ModuleEvaluationScope> scope;
if (isNewModuleRegistryEnabled(FeatureFlags::get(js))) {
scope.emplace(js);
}
KJ_IF_SOME(module, js.resolveInternalModule(specifier)) {
KJ_IF_SOME(p, processValue) {
// There's a chance that resolving the module caused side-effects
Expand Down
10 changes: 10 additions & 0 deletions src/workerd/api/tests/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -1679,6 +1679,16 @@ wd_test(
],
)

wd_test(
src = "new-module-registry-lazy-globals-test.wd-test",
args = ["--experimental"],
data = [
"new-module-registry-lazy-globals-request-test.js",
"new-module-registry-lazy-globals-top-level-test.js",
"new-module-registry-lazy-globals-warning-test.js",
],
)

wd_test(
src = "new-module-registry-startup-eval-test.wd-test",
args = ["--experimental"],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

// Nothing here touches process or Buffer, or imports a module that loads them, before the test
// runs, so the test makes the first access to both.

function check(value, message) {
if (!value) throw new Error(message);
}

export const firstAccessInRequest = {
async test() {
let ran = false;
queueMicrotask(() => {
ran = true;
});

const process = globalThis.process;
check(!ran, 'the first process access ran a pending microtask');
const Buffer = globalThis.Buffer;
check(!ran, 'the first Buffer access ran a pending microtask');

await Promise.resolve();
check(ran, 'the microtask did not run');

check(process === (await import('node:process')).default, 'wrong process');
check(Buffer === (await import('node:buffer')).Buffer, 'wrong Buffer');
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using Workerd = import "/workerd/workerd.capnp";

# The process and Buffer globals load their modules on first access. A first access must not run
# the Worker's pending microtasks, whether it happens in a request or during top-level evaluation,
# and a built-in that emits a process warning before then must not fail.
const unitTests :Workerd.Config = (
services = [
( name = "new-module-registry-lazy-globals-request-test",
worker = (
modules = [
(name = "worker", esModule = embed "new-module-registry-lazy-globals-request-test.js"),
],
compatibilityFlags = ["nodejs_compat_v2", "new_module_registry"],
),
),
( name = "new-module-registry-lazy-globals-top-level-test",
worker = (
modules = [
(name = "worker", esModule = embed "new-module-registry-lazy-globals-top-level-test.js"),
],
compatibilityFlags = ["nodejs_compat_v2", "new_module_registry"],
),
),
( name = "new-module-registry-lazy-globals-warning-test",
worker = (
modules = [
(name = "worker", esModule = embed "new-module-registry-lazy-globals-warning-test.js"),
],
compatibilityFlags = ["nodejs_compat_v2", "enable_nodejs_process_v2", "new_module_registry"],
),
),
( name = "legacy-module-registry-lazy-globals-warning-test",
worker = (
modules = [
(name = "worker", esModule = embed "new-module-registry-lazy-globals-warning-test.js"),
],
compatibilityFlags = ["nodejs_compat_v2", "enable_nodejs_process_v2", "legacy_module_registry"],
),
),
],
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

// The first access to process and Buffer happens here, during top-level evaluation.

let ran = false;
queueMicrotask(() => {
ran = true;
});
const process = globalThis.process;
const ranAfterProcess = ran;
const Buffer = globalThis.Buffer;
const ranAfterBuffer = ran;

function check(value, message) {
if (!value) throw new Error(message);
}

export const firstAccessAtTopLevel = {
async test() {
check(!ranAfterProcess, 'the first process access ran a pending microtask');
check(!ranAfterBuffer, 'the first Buffer access ran a pending microtask');
check(ran, 'the microtask did not run');
check(process === (await import('node:process')).default, 'wrong process');
check(Buffer === (await import('node:buffer')).Buffer, 'wrong Buffer');
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

// node:events emits a MaxListenersExceededWarning through process.emitWarning(), which emits on the
// process object from a microtask. Nothing here loads the process module, so the warning comes
// before the process object exists.
import { EventEmitter } from 'node:events';

const errors = [];
const queueMicrotask = globalThis.queueMicrotask;
globalThis.queueMicrotask = (callback) =>
queueMicrotask(() => {
try {
callback();
} catch (error) {
errors.push(error);
}
});

export const warningBeforeProcessLoads = {
async test() {
const emitter = new EventEmitter();
for (let i = 0; i <= EventEmitter.defaultMaxListeners; i++) {
emitter.on('event', () => {});
}
await new Promise((resolve) => setTimeout(resolve, 0));
if (errors.length > 0) throw errors[0];
},
};
21 changes: 0 additions & 21 deletions src/workerd/io/worker.c++
Original file line number Diff line number Diff line change
Expand Up @@ -2323,28 +2323,7 @@ kj::Maybe<jsg::JsObject> tryResolveMainModule(jsg::Lock& js,
}
});

// Before resolving the main module, if both nodejs_compat_v2 and the new
// module registry are enabled, let's pre-resolve the process and buffer modules.
// Why? Great question! Resolving these modules synchronously causes the microtask
// queue to be pumped, which we don't actually want to do while resolving the main
// module until we are ready. Both process and buffer are exposed via globalThis
// when the nodejs_compat_v2 flag is used, and if the top-level scope is accessing
// either globalThis.process or globalThis.buffer, then we need to make sure that
// the modules are already resolved so we don't pump the microtask queue while
// synchronously accessing those globals. Resolving them here ensures that they are
// ready to go before we begin evaluating the main module.
//
// The process global reads the process object's own module, not node:process, whose
// named exports include the stdio streams and so force them to be built.
auto featureFlags = FeatureFlags::get(js);
if (featureFlags.getNodeJsCompatV2() && isNewModuleRegistryEnabled(featureFlags)) {
auto processSpec = featureFlags.getEnableNodeJsProcessV2() ? "node-internal:public_process"_kj
: "node-internal:legacy_process"_kj;
JSG_REQUIRE_NONNULL(js.resolveInternalModule(processSpec), Error, "Failed to initialize ",
processSpec, " module");
JSG_REQUIRE_NONNULL(js.resolveModule("node:buffer", jsg::RequireEsm::YES), Error,
"Failed to initialize node:buffer module");
}

// When enable_nodejs_global_timers is enabled, load the module that makes all 6 timer
// functions (setTimeout, setInterval, clearTimeout, clearInterval, setImmediate,
Expand Down
Loading