Skip to content

Commit 6e730fe

Browse files
fix: hand Node.js' null source back as null and keep commonjs-typescript off the deferral
Node.js' `addon` translator asserts `source === null` for a `.node` file under node_modules, but `transform_output` dropped the `Option` and the result reached JavaScript as `undefined`, on both the asynchronous and the synchronous hooks. The `startsWith("commonjs")` deferral also caught `commonjs-typescript`, whose translator needs the source, turning Node's own type-stripping error into one blaming the hook. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent 5125e3c commit 6e730fe

3 files changed

Lines changed: 70 additions & 7 deletions

File tree

‎packages/core/register.mjs‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,11 @@ function load(url, context, nextLoad) {
103103
// `.cts` entry gets reported at the transformed position rather than the original one.
104104
// Asking `oxcLoad` first is what keeps a CommonJS-reported file that actually contains
105105
// ESM syntax running as an ES module. `commonjs-typescript` — Node.js' own format for a
106-
// `.ts` file it strips types from — belongs on that same path, hence the prefix test.
107-
if (result.format.startsWith("commonjs")) {
106+
// `.ts` file it strips types from — is not deferred, because that translator needs the
107+
// source and rejects `null`; it is passed through untouched so Node.js reports its own
108+
// error (`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`) for a `.ts` dependency instead
109+
// of one blaming the hook.
110+
if (result.format === "commonjs") {
108111
// A null source is what `module.register()`'s asynchronous default load returned for
109112
// every CommonJS module, and it is the one shape that keeps `require()` inside such a
110113
// module working on every runtime: a source-bearing result made Node.js short-circuit

‎packages/integrate-vitest/__tests__/register-hooks.spec.ts‎

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ function fixture(files: Record<string, string | Uint8Array>): string {
5858
return root;
5959
}
6060

61-
function run(root: string, args: string[]): string {
61+
function spawn(root: string, args: string[]): { status: number | null; output: string } {
6262
const result = spawnSync(
6363
process.execPath,
6464
// A bare specifier resolves through the symlinked node_modules on every platform,
@@ -79,7 +79,12 @@ function run(root: string, args: string[]): string {
7979
);
8080
const output = `${result.stdout}${result.stderr}`;
8181
expect(result.error, result.error?.message).toBeFalsy();
82-
expect(result.status, output).toBe(0);
82+
return { status: result.status, output };
83+
}
84+
85+
function run(root: string, args: string[]): string {
86+
const { status, output } = spawn(root, args);
87+
expect(status, output).toBe(0);
8388
return output;
8489
}
8590

@@ -122,6 +127,53 @@ describe("a source that is not UTF-8", () => {
122127
});
123128
});
124129

130+
describe("a source Node.js hands over without bytes", () => {
131+
// Not specific to the synchronous hooks — the asynchronous default load returned the
132+
// same `null` — but it lives here for the fixture helpers. A `.node` addon under
133+
// node_modules resolves without a format, so Node.js decides `addon` and hands the load
134+
// hook `source: null`. Its `addon` translator asserts exactly `null` on the way back:
135+
// an `undefined`, which is what a dropped `Option` serialised to, fails with
136+
// ERR_INVALID_RETURN_PROPERTY_VALUE.
137+
const addon = readdirSync(CORE).find((name) => name.endsWith(".node"));
138+
139+
test.skipIf(addon === undefined)("an addon imported from a dependency still loads", () => {
140+
const root = fixture({
141+
"package.json": COMMONJS,
142+
"node_modules/addon-dep/package.json": JSON.stringify({
143+
name: "addon-dep",
144+
main: "addon.node",
145+
}),
146+
"node_modules/addon-dep/addon.node": readFileSync(join(CORE, addon!)),
147+
"entry.mts": [
148+
'import addon from "addon-dep";',
149+
'console.log("addon:", typeof addon.transform);',
150+
].join("\n"),
151+
});
152+
// Unflagged on v26; v22 and v24 need the flag, and v26 still accepts it.
153+
expect(run(root, ["--experimental-addon-modules", "./entry.mts"])).toContain("addon: function");
154+
});
155+
156+
test("a TypeScript dependency gets Node.js' own error, not one blaming the hook", () => {
157+
// `.cts` under node_modules is `commonjs-typescript` to Node.js, a format whose
158+
// translator needs the source: deferring it with `source: null` like plain `commonjs`
159+
// is an invalid return shape. Node.js refuses type stripping in node_modules on every
160+
// path, so what has to hold is that *its* error is the one reported.
161+
const root = fixture({
162+
"package.json": COMMONJS,
163+
"node_modules/ts-dep/package.json": JSON.stringify({
164+
name: "ts-dep",
165+
exports: "./index.cts",
166+
}),
167+
"node_modules/ts-dep/index.cts": "const c: number = 3;\nexport { c };\n",
168+
"entry.mts": ['import { c } from "ts-dep";', 'console.log("cts:", c);'].join("\n"),
169+
});
170+
const { status, output } = spawn(root, ["./entry.mts"]);
171+
expect(status, output).not.toBe(0);
172+
expect(output).toContain("ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING");
173+
expect(output).not.toContain("ERR_INVALID_RETURN_PROPERTY_VALUE");
174+
});
175+
});
176+
125177
// `--conditions` adds to the condition set of every request, so neither `require` nor
126178
// `import` says anything about which loader asked. Both directions have to keep working
127179
// with either one of them injected.

‎src/lib.rs‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1194,7 +1194,13 @@ fn transform_output(
11941194
return Ok(loaded);
11951195
}
11961196
tracing::debug!("No source code to transform {}", url);
1197-
Ok(LoadFnOutput { format: output.format, source: None, response_url: Some(url) })
1197+
// The `null` Node.js handed over is handed back as-is: its `addon`
1198+
// translator asserts `source === null`, and an `undefined` fails it.
1199+
Ok(LoadFnOutput {
1200+
format: output.format,
1201+
source: Some(Either4::D(Null)),
1202+
response_url: Some(url),
1203+
})
11981204
}
11991205
Some(Either4::A(_) | Either4::B(_) | Either4::C(_)) => {
12001206
// `url` is a URL, so a `?query` or `#fragment` has to be stripped before it can
@@ -1210,14 +1216,16 @@ fn transform_output(
12101216
// and lets the CommonJS machinery read the file — but the synchronous
12111217
// `defaultLoadSync` behind `module.registerHooks()` always reads it. Drop the
12121218
// bytes and defer the same way instead of failing to decode them.
1219+
// `commonjs-typescript` is not deferred: Node.js' type-stripping translator
1220+
// needs the source, and handing it `null` is an invalid return shape.
12131221
if !is_json
1214-
&& output.format.starts_with("commonjs")
1222+
&& output.format == "commonjs"
12151223
&& output.source.as_ref().unwrap().try_as_str().is_err()
12161224
{
12171225
tracing::debug!("Not UTF-8, deferring to the CommonJS loader {}", url);
12181226
return Ok(LoadFnOutput {
12191227
format: output.format,
1220-
source: None,
1228+
source: Some(Either4::D(Null)),
12211229
response_url: Some(url),
12221230
});
12231231
}

0 commit comments

Comments
 (0)