Skip to content

Commit a305f36

Browse files
fix: isolate hook state per async module.register() registration
## Problem `tsImport()` stops settling after ~5 calls on Node versions that use the async `module.register()` path (below v24.11.1 / v25.1.0): resolution work multiplies ~10x per call, so the 6th call appears to hang forever. Regression in 4.22.0. The async path registers a cache-busted copy of the hook entry (`./esm/index.mjs?<timestamp>`) per registration so that each copy gets its own state. Since 4.22.0, `esm/api/register.ts` imports the hook factories for the sync `module.registerHooks()` path, which moved the hook modules — including the mutable `data` singleton — into a bundler chunk shared by both entries. Chunks evaluate once per thread, so every registration's `initialize()` mutated the same object: all chained registrations claimed the latest namespace, and each chain entry re-applied TypeScript extension guessing to the failed candidates of the hook below it. Fixes #806 ## Changes - Hook state is now created in the hook entry module itself (`src/esm/index.ts`) — the unit the async path cache-busts — so each registration gets its own state regardless of how the bundler chunks shared modules. - `initialize` / `globalPreload` / `load` / `resolve` are constructed per entry evaluation from factories; the module-level `data` singleton is removed (`createDefaultData()` + `createInitialize()` / `createGlobalPreload()`). - Regression test: repeated `tsImport()` of a failing import must reject every call. Runs across the CI Node matrix, so Node 18/20/22 exercise the async path.
1 parent ca501a9 commit a305f36

6 files changed

Lines changed: 83 additions & 16 deletions

File tree

‎src/esm/hook/index.ts‎

Lines changed: 0 additions & 3 deletions
This file was deleted.

‎src/esm/hook/initialize.ts‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,21 @@ type Data = InitializationOptions & {
1010
parsedTsconfig: TsconfigResult | undefined;
1111
};
1212

13-
export const data: Data = {
13+
export type { Data };
14+
15+
/**
16+
* Empty hook state, filled in by `initialize()`/`globalPreload()`. Must be
17+
* instantiated by the hook entry module (`src/esm/index.ts`) rather than
18+
* shared as a module-level singleton: the async `module.register()` path
19+
* registers a cache-busted copy of the entry per registration, and only the
20+
* entry module is re-evaluated per copy. State in any other module can be
21+
* hoisted into a bundler chunk shared across all copies, making every
22+
* registration mutate the same object (#806).
23+
*/
24+
export const createDefaultData = (): Data => ({
1425
active: true,
1526
parsedTsconfig: undefined,
16-
};
17-
18-
export type { Data };
27+
});
1928

2029
export const createData = (
2130
options?: InitializationOptions & {
@@ -38,7 +47,9 @@ export const createData = (
3847
return hookData;
3948
};
4049

41-
export const initialize: InitializeHook = async (
50+
export const createInitialize = (
51+
data: Data,
52+
): InitializeHook => async (
4253
options?: InitializationOptions,
4354
) => {
4455
if (!options) {
@@ -61,7 +72,9 @@ export const initialize: InitializeHook = async (
6172
type GlobalPreloadHook = () => string;
6273

6374
// Replaced by `initialize` in Node v20.6.0, v18.19.0
64-
export const globalPreload: GlobalPreloadHook = () => {
75+
export const createGlobalPreload = (
76+
data: Data,
77+
): GlobalPreloadHook => () => {
6578
data.parsedTsconfig = loadTsconfig(process.env.TSX_TSCONFIG_PATH);
6679
return 'process.setSourceMapsEnabled(true);';
6780
};

‎src/esm/hook/load.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import {
2828
getNamespace,
2929
moduleSourceByUrl,
3030
} from './utils.js';
31-
import { data as defaultData, type Data } from './initialize.js';
31+
import type { Data } from './initialize.js';
3232

3333
const importAttributesProperty = (
3434
isFeatureSupported(importAttributes)
@@ -598,5 +598,3 @@ export const createLoadSync = (
598598
return result;
599599
};
600600
};
601-
602-
export const load = createLoad(defaultData);

‎src/esm/hook/resolve.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ import {
3232
getNamespace,
3333
parentImportsCommonJsExports,
3434
} from './utils.js';
35-
import { data as defaultData, type Data } from './initialize.js';
35+
import type { Data } from './initialize.js';
3636

3737
type NextResolve = Parameters<ResolveHook>[2];
3838
type NextResolveSync = Parameters<ResolveHookSync>[2];
@@ -850,5 +850,3 @@ export const createResolveSync = (
850850
return result;
851851
};
852852
};
853-
854-
export const resolve = createResolve(defaultData);

‎src/esm/index.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
import * as workerThreads from 'node:worker_threads';
55
import { isFeatureSupported, moduleRegister, moduleRegisterHooksCjsReload } from '../utils/node-features.js';
66
import { register } from './api/index.js';
7+
import { createDefaultData, createInitialize, createGlobalPreload } from './hook/initialize.js';
8+
import { createLoad } from './hook/load.js';
9+
import { createResolve } from './hook/resolve.js';
710

811
// Loaded via --import flag
912
if (
@@ -22,4 +25,15 @@ if (
2225
register();
2326
}
2427

25-
export * from './hook/index.js';
28+
// The async module.register() path registers a cache-busted copy of this
29+
// entry per registration (`./esm/index.mjs?<timestamp>`). Only this entry
30+
// module is re-evaluated per copy — imported modules can be hoisted into
31+
// bundler chunks that evaluate once per thread — so the per-registration
32+
// hook state must be created here for each registration to get its own
33+
// namespace and active flag (#806).
34+
const data = createDefaultData();
35+
36+
export const initialize = createInitialize(data);
37+
export const globalPreload = createGlobalPreload(data);
38+
export const load = createLoad(data);
39+
export const resolve = createResolve(data);

‎tests/specs/version-sensitive.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -922,6 +922,53 @@ export const versionSensitiveTests = (node: NodeApis) => describe('Version-sensi
922922
});
923923
});
924924

925+
// Each tsImport() registers a fresh copy of the hooks. Hook state must
926+
// be per-registration: the async module.register() path loads a
927+
// cache-busted `esm/index.mjs?<timestamp>` per call, and if the state
928+
// lands in a bundler chunk shared across those copies, every chained
929+
// registration claims the latest namespace. Each chain entry then
930+
// re-applies TS extension guessing to the failed candidates of the
931+
// hook below it, multiplying resolution work per call until imports
932+
// stop settling (issue #806).
933+
test('repeated tsImport() of a failing import rejects every call (issue #806)', async () => {
934+
if (!node.supports.moduleRegister) {
935+
return;
936+
}
937+
938+
await using fixture = await createFixture({
939+
'package.json': createPackageJson({ type: 'module' }),
940+
'fail.ts': "import './missing.js';",
941+
'main.mjs': `
942+
import { tsImport } from ${JSON.stringify(tsxEsmApiPath)};
943+
944+
for (let i = 1; i <= 7; i += 1) {
945+
const outcome = await tsImport('./fail.ts', import.meta.url).then(
946+
() => 'unexpectedly resolved',
947+
error => error.code,
948+
);
949+
console.log(i, outcome);
950+
}
951+
`,
952+
});
953+
954+
const { stdout, stderr, exitCode } = await execaNode(
955+
fixture.getPath('main.mjs'),
956+
[],
957+
{
958+
nodePath: node.path,
959+
nodeOptions: ['--no-warnings'],
960+
reject: false,
961+
timeout: 30_000,
962+
},
963+
);
964+
965+
expect(stderr).toBe('');
966+
expect(stdout).toBe(
967+
Array.from({ length: 7 }, (_, index) => `${index + 1} ERR_MODULE_NOT_FOUND`).join('\n'),
968+
);
969+
expect(exitCode).toBe(0);
970+
});
971+
925972
test('CJS namespace import shape depends on Node version', async () => {
926973
await using fixture = await createFixture({
927974
'package.json': createPackageJson({ type: 'module' }),

0 commit comments

Comments
 (0)