vitest-native 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as VitestNativeError } from "./errors-CxoBUfVJ.mjs";
2
- import { a as packageDirOf, c as validateOptions, i as containsPath, l as validatePeerDependency, n as detectEngine, o as packagePatterns, r as REACT_NATIVE_PATH, s as PEER_REQUIREMENTS, t as detectEcosystemPackages, u as warnUnknownOptions } from "./ecosystem-DJMGR2YY.mjs";
2
+ import { a as packageDirOf, c as validateOptions, i as containsPath, l as validatePeerDependency, n as detectEngine, o as packagePatterns, r as REACT_NATIVE_PATH, s as PEER_REQUIREMENTS, t as detectEcosystemPackages, u as warnUnknownOptions } from "./ecosystem-Duw40-mO.mjs";
3
3
  import { t as AUTO_DETECT_PRESETS } from "./preset-map-DuX0ocdn.mjs";
4
4
  import { t as presets_exports } from "./presets-IStcJEOa.mjs";
5
5
  import { createRequire } from "node:module";
@@ -27,16 +27,24 @@ const METRO_SOURCE_EXTS = [
27
27
  "tsx"
28
28
  ];
29
29
  /**
30
- * Metro tries every platform-suffixed variant first, then every `.native` one,
31
- * then the bare extensions — not extension-major.
30
+ * Extension-MAJOR, exactly as Metro resolves: for each source extension in order,
31
+ * try the platform variant, then `.native`, then bare — `.ios.js`, `.native.js`,
32
+ * `.js`, `.ios.jsx`, … (metro-resolver's `resolveSourceFile` loops `sourceExts`
33
+ * in the outer loop and the platform variants inside it).
34
+ *
35
+ * This order previously interleaved the other way — every `.ios.*` before any
36
+ * `.native.*` before any bare extension — and the difference is not stylistic:
37
+ * a module shipping `Foo.native.js` beside `Foo.ios.tsx` resolves to
38
+ * `.native.js` under Metro (the `js` round wins before `tsx` is ever tried) but
39
+ * resolved to `.ios.tsx` here, so the test ran a different file than the app
40
+ * ships. The order is asserted against real metro-resolver by
41
+ * tests/metro-resolver-oracle.test.ts, not just against these literals.
32
42
  */
33
43
  function extensionsFor(platform) {
34
44
  const suffix = platform === "android" ? "android" : "ios";
35
- return [
36
- ...METRO_SOURCE_EXTS.map((e) => `.${suffix}.${e}`),
37
- ...METRO_SOURCE_EXTS.map((e) => `.native.${e}`),
38
- ...METRO_SOURCE_EXTS.map((e) => `.${e}`)
39
- ];
45
+ const exts = [];
46
+ for (const e of METRO_SOURCE_EXTS) exts.push(`.${suffix}.${e}`, `.native.${e}`, `.${e}`);
47
+ return exts;
40
48
  }
41
49
  //#endregion
42
50
  //#region src/resolve.ts
@@ -213,6 +221,34 @@ function nearestPackageDir(from) {
213
221
  dir = parent;
214
222
  }
215
223
  }
224
+ /**
225
+ * The `transform` option in either shape: an array of packages to compile, or an
226
+ * object naming those and the ones to leave alone.
227
+ *
228
+ * `exclude` overrides everything — auto-detection, the closure walk, and the engine's
229
+ * built-in toolchain and infrastructure lists. Those built-in lists are names the
230
+ * engine learned from packages that broke, which means they are only ever as current
231
+ * as the last release; `exclude` is the same decision, handed to the project.
232
+ */
233
+ function normalizeTransformOption(option) {
234
+ const names = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string" && v !== "") : [];
235
+ if (Array.isArray(option)) return {
236
+ include: names(option),
237
+ exclude: []
238
+ };
239
+ if (option && typeof option === "object") {
240
+ const shape = option;
241
+ const exclude = names(shape.exclude);
242
+ return {
243
+ include: names(shape.include).filter((n) => !exclude.includes(n)),
244
+ exclude
245
+ };
246
+ }
247
+ return {
248
+ include: [],
249
+ exclude: []
250
+ };
251
+ }
216
252
  function resolvePackageVersion(packageName, projectRoot) {
217
253
  const req = createRequire(path.join(projectRoot, "package.json"));
218
254
  try {
@@ -682,7 +718,7 @@ function reactNative(options) {
682
718
  const platform = options?.platform ?? "ios";
683
719
  const diagnostics = options?.diagnostics ?? false;
684
720
  const requestedEngine = options?.engine ?? "auto";
685
- const transformPkgs = (options?.transform ?? []).filter((p) => typeof p === "string" && p.length > 0);
721
+ const { include: transformPkgs, exclude: neverTransform } = normalizeTransformOption(options?.transform);
686
722
  const hotRuntimeOpt = options?.hotRuntime ?? false;
687
723
  const hotRuntime = hotRuntimeOpt !== false;
688
724
  const hotRecycle = typeof hotRuntimeOpt === "object" ? hotRuntimeOpt : {};
@@ -704,7 +740,7 @@ function reactNative(options) {
704
740
  const jsxTransform = getJsxTransformConfig(resolvedRoot);
705
741
  const decision = detectEngine(requestedEngine, resolvedRoot);
706
742
  engine = decision.engine;
707
- if (engine === "native" && !decision.nativeAvailable) throw new VitestNativeError("ENGINE_REQUIRES_BABEL", `engine:'native' requires '@react-native/babel-preset' and '@babel/core' to resolve from ${resolvedRoot}. Install them as devDependencies (React Native projects ship them by default):\n\n npm install -D @react-native/babel-preset @babel/core\n\nOr set engine:'mock' to run without a React Native install.`);
743
+ if (engine === "native" && !decision.nativeAvailable) throw new VitestNativeError("ENGINE_REQUIRES_BABEL", `engine:'native' requires react-native, '@react-native/babel-preset', and '@babel/core' to resolve from ${resolvedRoot} — missing: ${decision.missing.join(", ")}. React Native projects ship all three by default. Install what's missing (react-native as a dependency, the toolchain as devDependencies), or set engine:'mock' to run without a React Native install.`);
708
744
  if (decision.notice) console.warn(decision.notice);
709
745
  printEngineBanner(engine, platform, resolvedRoot);
710
746
  const env = {
@@ -717,6 +753,7 @@ function reactNative(options) {
717
753
  const assetExtList = [...DEFAULT_ASSET_EXTS, ...(options?.assetExts ?? []).map((e) => e.replace(/^\./, ""))];
718
754
  env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify(assetExtList);
719
755
  if (hotRuntime && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
756
+ if (hotRuntime && hotRecycle.esmGeneration === false) env.VITEST_NATIVE_HOT_ESM_GEN = "0";
720
757
  if (engine === "native") {
721
758
  if (options?.mocks && Object.keys(options.mocks).length > 0) throw new VitestNativeError("MOCKS_REQUIRE_MOCK_ENGINE", "The \"mocks\" option is only supported by engine:'mock'. The native engine runs the real react-native module and cannot safely merge arbitrary exports into it. Use vi.mock() in a setup file, mockNativeModule() for native modules, or set engine:'mock'.");
722
759
  const disabledNative = disabledPresetNames(options?.presets);
@@ -728,7 +765,7 @@ function reactNative(options) {
728
765
  if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
729
766
  }
730
767
  const includeRoots = testIncludeRoots(userConfig.test?.include, resolvedRoot);
731
- const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots);
768
+ const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots, neverTransform);
732
769
  const linkedDetectedDirs = ecosystem.map((name) => packageDirOf(name, resolvedRoot)).filter((dir) => dir !== null && !/[\\/]node_modules[\\/]/.test(dir));
733
770
  const projectDirs = [...new Set([resolvedRoot, ...includeRoots].map((dir) => nearestPackageDir(dir)).filter((dir) => dir !== null))].filter((dir) => !linkedDetectedDirs.some((detected) => containsPath(dir, detected)));
734
771
  if (projectDirs.length > 0) env.VITEST_NATIVE_PROJECT_DIRS = JSON.stringify(projectDirs);
@@ -44,21 +44,42 @@ export function decorateTransformError(err, file, platform) {
44
44
  const UNTRANSPILED_SYNTAX =
45
45
  /Unexpected token '?<'?|Unexpected identifier|Unexpected reserved word|Missing initializer in const|Unexpected token ':'/;
46
46
 
47
+ // Node's ReferenceError when a MIXED-SYNTAX file runs: top-level `import` makes the
48
+ // CJS parse fail, Node retries the file as an ES module (require(esm)), and the
49
+ // CommonJS half then dereferences a wrapper variable that ESM scope never defines.
50
+ // Metro compiles both halves, so packages ship this shape — react-native-worklets'
51
+ // lib/module/mock.js ends in `module.exports = ...` under a header of `import`s.
52
+ // It is the runtime sibling of the SyntaxError class above: same cause, same fix,
53
+ // but it parses cleanly and so fails AFTER compilation, as a ReferenceError.
54
+ const ESM_SCOPE_REFERENCE =
55
+ /\b(?:module|exports|require|__dirname|__filename) is not defined in ES module scope/;
56
+
47
57
  /**
48
- * When Node throws a SyntaxError compiling a node_modules file that vitest-native
49
- * did NOT transform, explain the (very common) real cause: the package ships
50
- * untranspiled JSX/Flow/TS and needs to be added to `transform: [...]`.
58
+ * When Node throws compiling or running a node_modules file that vitest-native did
59
+ * NOT transform, explain the (very common) real cause: the package ships source
60
+ * only Metro can run — untranspiled JSX/Flow/TS (a SyntaxError), or mixed
61
+ * ESM-import/CommonJS-exports (a ReferenceError from the require(esm) retry) —
62
+ * and needs to be added to `transform: [...]`.
51
63
  * Returns a decorated error, or null when the failure doesn't match the pattern.
52
64
  */
53
65
  export function explainUntransformedSyntaxError(err, file) {
54
- if (!err || err.name !== "SyntaxError") return null;
55
- if (!UNTRANSPILED_SYNTAX.test(String(err.message))) return null;
66
+ if (!err) return null;
67
+ const matches =
68
+ (err.name === "SyntaxError" && UNTRANSPILED_SYNTAX.test(String(err.message))) ||
69
+ (err.name === "ReferenceError" && ESM_SCOPE_REFERENCE.test(String(err.message)));
70
+ if (!matches) return null;
56
71
  const pkg = packageNameFromPath(file);
57
72
  if (!pkg) return null;
58
- const wrapped = new SyntaxError(
73
+ const cause =
74
+ err.name === "ReferenceError"
75
+ ? `This usually means the package publishes mixed ES-module/CommonJS source ` +
76
+ `that only a bundler like Metro can run.`
77
+ : `This usually means the package publishes untranspiled JSX, Flow, or TypeScript.`;
78
+ const Ctor = err.name === "ReferenceError" ? ReferenceError : SyntaxError;
79
+ const wrapped = new Ctor(
59
80
  `[vitest-native] '${pkg}' shipped source Node can't run directly ` +
60
81
  `(${err.message} in ${file}).\n` +
61
- `This usually means the package publishes untranspiled JSX, Flow, or TypeScript. ` +
82
+ `${cause} ` +
62
83
  `Ask vitest-native to transform it:\n\n` +
63
84
  ` reactNative({ transform: ['${pkg}'] })\n\n` +
64
85
  `in your vitest config. See https://github.com/danfry1/vitest-native` +
@@ -3,7 +3,7 @@
3
3
  import Module from "node:module";
4
4
  import path from "node:path";
5
5
  import fs from "node:fs";
6
- import { transformRN, isFlow } from "./transform.mjs";
6
+ import { transformRN, isFlow, needsTransform } from "./transform.mjs";
7
7
  import { boundarySourceFor } from "./boundary.mjs";
8
8
  import { resolvePlatformFile } from "./resolve.mjs";
9
9
  import {
@@ -163,7 +163,17 @@ export function installRequireHooks(
163
163
  reactNativeVersion = "0.0.0",
164
164
  assetExts = [],
165
165
  ) {
166
- if (globalThis.__vitest_native_require_hooks_installed) return;
166
+ if (globalThis.__vitest_native_require_hooks_installed) {
167
+ // Install once per worker — but not with a frozen transform list. The hot
168
+ // worker installs the hooks at BOOT, before the setup file has built the
169
+ // preset mocks and can extend the list with preset-shadowed packages (their
170
+ // pass-through entries are compiled only if named here); a pure no-op would
171
+ // pin the boot-time env list forever, and the divergence is hot-only because
172
+ // under stock the setup file IS the first caller. Rebuild the matcher when
173
+ // a later caller brings a different list; hook layers are never stacked.
174
+ globalThis.__vitest_native_require_hooks_update?.(transformPkgs);
175
+ return;
176
+ }
167
177
  globalThis.__vitest_native_require_hooks_installed = true;
168
178
 
169
179
  // Asset requires (`require('./logo.png')`, `require('./Icon.ttf')`) reaching
@@ -186,7 +196,16 @@ export function installRequireHooks(
186
196
  }
187
197
 
188
198
  // Configured third-party packages to also transform (Flow/TS/JSX stripped).
189
- const isExtra = buildPkgMatcher(transformPkgs, projectRoot);
199
+ // `let` + the updater below: the hot worker installs the hooks at boot with the
200
+ // raw env list, and the setup file re-calls with the preset-extended one.
201
+ let isExtra = buildPkgMatcher(transformPkgs, projectRoot);
202
+ let isExtraKey = JSON.stringify(transformPkgs);
203
+ globalThis.__vitest_native_require_hooks_update = (pkgs) => {
204
+ const key = JSON.stringify(pkgs);
205
+ if (key === isExtraKey) return;
206
+ isExtraKey = key;
207
+ isExtra = buildPkgMatcher(pkgs, projectRoot);
208
+ };
190
209
 
191
210
  // Preset redirect (CJS): when an externalized third-party module require()s a
192
211
  // preset package by its bare name (e.g. @gorhom/bottom-sheet → require(
@@ -289,10 +308,15 @@ export function installRequireHooks(
289
308
  if (isFlow(src))
290
309
  return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
291
310
  } else if (isExtra(norm)) {
292
- // Configured third-party packages: transform unconditionally — TS `import
293
- // type`/JSX aren't caught by isFlow, and babel passes plain JS through.
311
+ // Selected for compiling — but only compile what Node cannot run as published.
312
+ // `isFlow` is not enough here (TS `import type` and JSX slip past it), and
313
+ // compiling everything is what handed Babel its own toolchain. See
314
+ // needsTransform: V8 answers the question Node is about to ask.
294
315
  const src = fs.readFileSync(filename, "utf8");
295
- return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
316
+ if (needsTransform(filename, src)) {
317
+ return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
318
+ }
319
+ return origJs(mod, filename);
296
320
  }
297
321
  if (NODE_MODULES_PATH.test(norm)) {
298
322
  // A node_modules package we did NOT transform: when Node's compile throws a
@@ -3,7 +3,7 @@
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
4
  import path from "node:path";
5
5
  import fs from "node:fs";
6
- import { transformRN, isFlow, cjsExportNames } from "./transform.mjs";
6
+ import { transformRN, isFlow, cjsExportNames, needsTransform } from "./transform.mjs";
7
7
  import { boundarySourceFor } from "./boundary.mjs";
8
8
  import { resolvePlatformFile } from "./resolve.mjs";
9
9
  import {
@@ -55,6 +55,59 @@ let presetExports = {};
55
55
  // Asset file extensions (without leading dot, lower-cased) the loader should stub.
56
56
  let assetExtSet = new Set();
57
57
 
58
+ /**
59
+ * Hot-runtime ESM generation (experimental, `VITEST_NATIVE_HOT_ESM_GEN=1`).
60
+ *
61
+ * Node's ESM registry has no invalidation API, so a package a TEST FILE reaches
62
+ * through `import` keeps its module state for the whole run — the per-file reset
63
+ * can only clear the CommonJS cache. That is the hot runtime's one measured
64
+ * correctness hole at scale (see validation/idiomatic/scale, `extstore`).
65
+ *
66
+ * The registry is keyed by full URL, query included, so stamping a generation onto
67
+ * the URL makes the next file's import a different module and Node evaluates it
68
+ * again. The counter lives in a SharedArrayBuffer because loader hooks run on their
69
+ * own thread; the worker bumps it in the per-file reset.
70
+ *
71
+ * Cost is bounded by ownership: a CommonJS package re-enters through Module._cache,
72
+ * which the reset already drops, so only a thin namespace wrapper is retained per
73
+ * generation. A true-ESM package retains its whole instance — which is why this is
74
+ * measured before it is trusted.
75
+ */
76
+ let genView = null;
77
+ const generationOf = () => (genView ? Atomics.load(genView, 0) : 0);
78
+ // Modules whose identity must be stable across files: dropping them makes a twin
79
+ // rather than a fresh copy. Mirrors KEEP_RESIDENT in module-reset.mjs.
80
+ const KEEP_RESIDENT =
81
+ /[\\/]node_modules[\\/](react|react-is|react-dom|scheduler|react-reconciler|react-test-renderer|test-renderer|@testing-library[\\/]react-native)[\\/]/;
82
+ // The test stack itself: Vitest's runtime, the chai it asserts through, and this
83
+ // engine. The worker's runtime holds instances of these from boot — the runner's
84
+ // SnapshotClient, chai's extended Assertion, the engine's registry and hooks — and a
85
+ // test file reaches the SAME packages through Node's ESM path. Stamping those
86
+ // resolutions hands the file a twin runtime: `toMatchSnapshot` then asks a
87
+ // SnapshotClient no one set up, `vi.useFakeTimers` flips a copy of the timer state
88
+ // the runner never reads, and matchers extend a chai the expect chain doesn't use.
89
+ //
90
+ // The workspace gates cannot catch a miss here: in-repo, this package and the
91
+ // validation suites resolve OUTSIDE node_modules, so the NODE_MODULES_PATH guard
92
+ // below exempts the engine by accident of layout. Only a packed install — the
93
+ // bake-off apps — puts the whole test stack under node_modules where stamping can
94
+ // reach it. That is how this list was earned: react-native-paper under the hot
95
+ // runtime, 603/678 -> 473/648, every extra failure a twin-runtime symptom.
96
+ const TEST_RUNTIME_RESIDENT =
97
+ /[\\/]node_modules[\\/](vitest|@vitest[\\/][^\\/]+|chai|vitest-native)[\\/]/;
98
+
99
+ /** Should this resolved file carry a generation stamp? */
100
+ function versionable(url) {
101
+ if (!genView || !url.startsWith("file:")) return false;
102
+ const norm = fileURLToPath(url).replace(/\\/g, "/");
103
+ if (!NODE_MODULES_PATH.test(norm)) return false;
104
+ // React Native itself is preloaded once per worker and shared deliberately —
105
+ // re-instantiating it per file would undo the reason the worker stays warm.
106
+ if (REACT_NATIVE_PATH.test(norm) || KEEP_RESIDENT.test(norm)) return false;
107
+ if (TEST_RUNTIME_RESIDENT.test(norm)) return false;
108
+ return true;
109
+ }
110
+
58
111
  export async function initialize(data) {
59
112
  if (data && data.projectRoot) PROJECT_ROOT = data.projectRoot;
60
113
  if (data && data.platform === "android") PLATFORM = "android";
@@ -63,6 +116,7 @@ export async function initialize(data) {
63
116
  if (data && data.presetExports) presetExports = data.presetExports;
64
117
  if (data && data.assetExts)
65
118
  assetExtSet = new Set(data.assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
119
+ if (data && data.hotGenerationBuffer) genView = new Int32Array(data.hotGenerationBuffer);
66
120
  }
67
121
 
68
122
  export async function resolve(specifier, context, nextResolve) {
@@ -133,6 +187,16 @@ export async function resolve(specifier, context, nextResolve) {
133
187
  shortCircuit: true,
134
188
  };
135
189
  }
190
+
191
+ // Stamp the hot generation so the next test file re-evaluates this module rather
192
+ // than reusing the ESM registry's copy. `fileURLToPath` ignores the query, so
193
+ // `load` and every on-disk read below are unaffected.
194
+ if (versionable(resolved.url)) {
195
+ const gen = generationOf();
196
+ if (gen > 0 && !resolved.url.includes("vnhot=")) {
197
+ return { ...resolved, url: `${resolved.url}?vnhot=${gen}`, shortCircuit: true };
198
+ }
199
+ }
136
200
  return resolved;
137
201
  }
138
202
 
@@ -248,6 +312,10 @@ export async function load(url, context, nextLoad) {
248
312
  // JSX are not installed, so a require here fails with "Unexpected token '<'".
249
313
  if (TRANSFORMABLE.test(norm)) {
250
314
  const src = fs.readFileSync(file, "utf8");
315
+ // Only compile what Node cannot run as published — see needsTransform. A file V8
316
+ // accepts is handed straight back to Node, which is how the toolchain packages a
317
+ // closure walk drags in stop reaching the Babel preset at all.
318
+ if (!needsTransform(file, src)) return nextLoad(url, context);
251
319
  const code = transformRN(file, src, PROJECT_ROOT, PLATFORM);
252
320
  const names = cjsExportNames(code);
253
321
  return {
@@ -19,11 +19,16 @@ const UNRESETTABLE = /\.node$/;
19
19
  * rather than a fresh one.
20
20
  *
21
21
  * Test files reach these through ESM `import`, which caches them in Node's ESM
22
- * registry — and that registry has no invalidation API, so the copy a test holds
23
- * survives any reset. Dropping the CJS entry therefore does not replace the module;
24
- * it adds a twin, and the two halves of the test stack stop recognising each other.
25
- * The symptom is not an error about modules: it is RNTL's matchers failing to see
26
- * elements that a resident renderer produced.
22
+ * registry. Dropping the CJS entry therefore does not replace the module; it adds a
23
+ * twin, and the two halves of the test stack stop recognising each other. The symptom
24
+ * is not an error about modules: it is RNTL's matchers failing to see elements that a
25
+ * resident renderer produced.
26
+ *
27
+ * The ESM registry is not reachable from here — it has no invalidation API — but it
28
+ * IS keyed by full URL, and the engine owns the resolve hook, so the loader gives
29
+ * every other externalized package a per-file generation stamp instead (see
30
+ * `versionable` in loader.mjs). The entries below are exempt from that on purpose:
31
+ * for them a fresh instance is the bug, not the fix.
27
32
  *
28
33
  * Which entries carry weight depends on the RNTL version, so the list is bisected
29
34
  * rather than assumed. Measured one entry at a time:
@@ -18,16 +18,26 @@ import path from "node:path";
18
18
  export const METRO_SOURCE_EXTS = ["js", "jsx", "json", "ts", "tsx"];
19
19
 
20
20
  /**
21
- * Metro tries every platform-suffixed variant first, then every `.native` one,
22
- * then the bare extensions — not extension-major.
21
+ * Extension-MAJOR, exactly as Metro resolves: for each source extension in order,
22
+ * try the platform variant, then `.native`, then bare — `.ios.js`, `.native.js`,
23
+ * `.js`, `.ios.jsx`, … (metro-resolver's `resolveSourceFile` loops `sourceExts`
24
+ * in the outer loop and the platform variants inside it).
25
+ *
26
+ * This order previously interleaved the other way — every `.ios.*` before any
27
+ * `.native.*` before any bare extension — and the difference is not stylistic:
28
+ * a module shipping `Foo.native.js` beside `Foo.ios.tsx` resolves to
29
+ * `.native.js` under Metro (the `js` round wins before `tsx` is ever tried) but
30
+ * resolved to `.ios.tsx` here, so the test ran a different file than the app
31
+ * ships. The order is asserted against real metro-resolver by
32
+ * tests/metro-resolver-oracle.test.ts, not just against these literals.
23
33
  */
24
34
  export function extensionsFor(platform) {
25
35
  const suffix = platform === "android" ? "android" : "ios";
26
- return [
27
- ...METRO_SOURCE_EXTS.map((e) => `.${suffix}.${e}`),
28
- ...METRO_SOURCE_EXTS.map((e) => `.native.${e}`),
29
- ...METRO_SOURCE_EXTS.map((e) => `.${e}`),
30
- ];
36
+ const exts = [];
37
+ for (const e of METRO_SOURCE_EXTS) {
38
+ exts.push(`.${suffix}.${e}`, `.native.${e}`, `.${e}`);
39
+ }
40
+ return exts;
31
41
  }
32
42
 
33
43
  // Per-worker resolution cache: `${platform}\0${absBase}` → resolved path | null.
@@ -98,6 +98,21 @@ for (const name of presetNames) {
98
98
  }
99
99
  }
100
100
 
101
+ // Preset-shadowed packages join the Node-side transform set. Their bare and
102
+ // subpath imports are redirected to the preset mock before any file loads, so the
103
+ // only real files reachable from them are the deliberately exempted pass-throughs
104
+ // (package.json subpaths, assets, and Node-safe utility entries such as `mock`,
105
+ // `plugin`, `jest-utils`). Some of those ship Metro-only source —
106
+ // react-native-worklets' lib/module/mock.js mixes ESM `import` with
107
+ // `module.exports`, which served as published throws "module is not defined in
108
+ // ES module scope" or, on Node 24 (whose global `module` is the Module
109
+ // constructor), loads SILENTLY with empty exports —
110
+ // and the preset shadow is exactly what keeps such packages OUT of the detected
111
+ // ecosystem list, so nothing else will ever compile them. Membership here only
112
+ // makes their files eligible: needsTransform still gates every compile, so a
113
+ // pass-through Node can already run is served untouched.
114
+ const nodeTransformPkgs = [...new Set([...transformPkgs, ...Object.keys(presetExports)])];
115
+
101
116
  // Enable the V8 compile cache before RN is compiled (it loads when the test file
102
117
  // imports react-native, after this setup runs) so its bytecode is cached to disk
103
118
  // and reused on the next file/worker/run. Covers the stock (non-hot) path.
@@ -119,8 +134,28 @@ if (typeof globalThis.expect === "undefined") {
119
134
  // installRequireHooks are internally guarded the same way.)
120
135
  if (!globalThis.__vitest_native_loader_registered) {
121
136
  globalThis.__vitest_native_loader_registered = true;
137
+ // Hot ESM generation (see loader.mjs): closes the hot runtime's one measured
138
+ // correctness hole, where a package a test file `import`s keeps its module state
139
+ // for the whole run because Node's ESM registry cannot be invalidated. Only
140
+ // meaningful under the hot runtime — `__vitest_native_hot_reset` is installed by
141
+ // the hot worker before this setup file runs, and nothing bumps the counter
142
+ // otherwise. Shared rather than passed by value because loader hooks run on their
143
+ // own thread. Set VITEST_NATIVE_HOT_ESM_GEN=0 to opt out (and to mutation-test the
144
+ // isolation gate that covers this).
145
+ if (globalThis.__vitest_native_hot_reset && process.env.VITEST_NATIVE_HOT_ESM_GEN !== "0") {
146
+ globalThis.__vitest_native_hot_generation = new Int32Array(new SharedArrayBuffer(4));
147
+ globalThis.__vitest_native_hot_generation[0] = 1;
148
+ }
122
149
  register("./loader.mjs", import.meta.url, {
123
- data: { projectRoot, platform, reactNativeVersion, transformPkgs, presetExports, assetExts },
150
+ data: {
151
+ projectRoot,
152
+ platform,
153
+ reactNativeVersion,
154
+ transformPkgs: nodeTransformPkgs,
155
+ presetExports,
156
+ assetExts,
157
+ hotGenerationBuffer: globalThis.__vitest_native_hot_generation?.buffer,
158
+ },
124
159
  });
125
160
  }
126
161
  // Serve React Native from the precompiled registry when the plugin produced one
@@ -136,7 +171,7 @@ if (process.env.VITEST_NATIVE_RN_REGISTRY) {
136
171
  );
137
172
  }
138
173
  }
139
- installRequireHooks(projectRoot, transformPkgs, platform, reactNativeVersion, assetExts);
174
+ installRequireHooks(projectRoot, nodeTransformPkgs, platform, reactNativeVersion, assetExts);
140
175
 
141
176
  // Build the mock objects now that the require hooks are installed (preset
142
177
  // factories may lazily resolve react-native at render time).