vitest-native 0.13.0 → 0.14.0-rc.2

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.
Files changed (77) hide show
  1. package/CHANGELOG.md +339 -0
  2. package/README.md +138 -48
  3. package/dist/cli.cjs +70 -5
  4. package/dist/cli.d.cts +2 -3
  5. package/dist/cli.d.mts +2 -3
  6. package/dist/cli.mjs +70 -5
  7. package/dist/{ecosystem-Duw40-mO.mjs → ecosystem-DFbU_MPe.mjs} +389 -18
  8. package/dist/{ecosystem-CEIF_-jq.cjs → ecosystem-DI1AhK_k.cjs} +408 -25
  9. package/dist/errors.d.mts +12 -0
  10. package/dist/helpers.cjs +6 -3
  11. package/dist/helpers.d.cts +8 -9
  12. package/dist/helpers.d.mts +8 -9
  13. package/dist/helpers.mjs +6 -3
  14. package/dist/{index-CPGq6p95.d.cts → index-BxzW2D7K.d.cts} +33 -9
  15. package/dist/{index-CmETArCM.d.mts → index-CEbwa4QU.d.mts} +33 -9
  16. package/dist/index.d.mts +4 -4
  17. package/dist/index.mjs +537 -118
  18. package/dist/jest-compat/aliases.d.mts +5 -0
  19. package/dist/jest-compat/aliases.mjs +65 -0
  20. package/dist/jest-compat/caller.mjs +53 -0
  21. package/dist/jest-compat/setup.mjs +72 -36
  22. package/dist/jest-compat.cjs +1 -3
  23. package/dist/jest-compat.d.cts +4 -5
  24. package/dist/jest-compat.d.mts +4 -5
  25. package/dist/jest-compat.mjs +1 -1
  26. package/dist/matchers.d.cts +9 -9
  27. package/dist/matchers.d.mts +9 -9
  28. package/dist/memory-6EPHrJA1.cjs +144 -0
  29. package/dist/memory-FYbP0_gg.mjs +126 -0
  30. package/dist/native/boundary.mjs +13 -2
  31. package/dist/native/bounded-process.mjs +165 -0
  32. package/dist/native/export-condition-recovery-preload.mjs +5 -0
  33. package/dist/native/export-condition-recovery.mjs +195 -0
  34. package/dist/native/globals.mjs +133 -5
  35. package/dist/native/hooks.mjs +131 -71
  36. package/dist/native/loader.mjs +41 -28
  37. package/dist/native/match.d.mts +3 -0
  38. package/dist/native/match.mjs +38 -2
  39. package/dist/native/metro-profile-compiler.mjs +234 -0
  40. package/dist/native/metro-profile.mjs +115 -0
  41. package/dist/native/module-reset.mjs +111 -6
  42. package/dist/native/ownership.d.mts +105 -0
  43. package/dist/native/ownership.mjs +474 -0
  44. package/dist/native/registry-compiler.mjs +43 -0
  45. package/dist/native/registry-process.mjs +124 -0
  46. package/dist/native/registry.mjs +139 -32
  47. package/dist/native/reset.mjs +305 -135
  48. package/dist/native/resolve.d.mts +20 -3
  49. package/dist/native/resolve.mjs +32 -12
  50. package/dist/native/rntl-hooks.mjs +76 -0
  51. package/dist/native/setup.mjs +81 -32
  52. package/dist/native/state-manifest.d.mts +22 -0
  53. package/dist/native/state-manifest.mjs +136 -0
  54. package/dist/native/transform.mjs +29 -8
  55. package/dist/native/worker.mjs +52 -4
  56. package/dist/pool-B4yesGhI.cjs +121 -0
  57. package/dist/pool-DjpOjOf3.mjs +119 -0
  58. package/dist/{presets-CoNf4ByH.cjs → presets-BYHmi7-W.cjs} +117 -18
  59. package/dist/{presets-DGProTaA.mjs → presets-DC-eM5IA.mjs} +117 -18
  60. package/dist/presets.d.mts +1 -1
  61. package/dist/presets.mjs +1 -1
  62. package/dist/rntl-matchers.d.ts +58 -12
  63. package/dist/serializer.cjs +4 -2
  64. package/dist/serializer.d.cts +3 -4
  65. package/dist/serializer.d.mts +3 -4
  66. package/dist/serializer.mjs +4 -2
  67. package/dist/setup.mjs +61 -50
  68. package/dist/worker-vitest-BGPo0ek6.mjs +49 -0
  69. package/dist/worker-vitest-BfiQB8ND.cjs +62 -0
  70. package/docs/hot-default-design.md +175 -88
  71. package/docs/migrating-from-jest.md +12 -5
  72. package/docs/migrating-from-vitest-react-native.md +4 -4
  73. package/docs/release-readiness.md +39 -13
  74. package/docs/versioning.md +19 -18
  75. package/package.json +42 -31
  76. package/dist/pool-BU-1ecIF.cjs +0 -122
  77. package/dist/pool-Bcxn9a3I.mjs +0 -118
@@ -0,0 +1,76 @@
1
+ // React Native Testing Library's per-file hooks under the hot runtime.
2
+ //
3
+ // RNTL's entry module registers its test hooks as a side effect of being evaluated:
4
+ // `afterEach` cleanup (unmount every rendered tree, reset `screen`) and the
5
+ // `beforeAll`/`afterAll` pair that turns React's act environment on for the file.
6
+ // Under per-file isolation a file that imports RNTL evaluates it, so it gets them, and
7
+ // a file that does not import RNTL does not. The hot runtime keeps RNTL resident — a
8
+ // fresh instance per file breaks its matchers against the resident renderer (see
9
+ // RUNTIME_RESIDENT_PACKAGES) — so the entry ran once, in the first file that imported
10
+ // it, and later files had no cleanup: `screen` still returned the previous file's
11
+ // tree, and its components stayed mounted with their effects.
12
+ //
13
+ // So the hooks are registered where RNTL would register them: when the file's graph
14
+ // imports RNTL's main entry. Vitest evaluates that externalized import through the
15
+ // module evaluator's runExternalModule once per file (the per-file reset clears the
16
+ // runner's evaluated flags). If the entry was already in Node's module cache before the
17
+ // import, it is resident and did not run, so its code is evaluated again outside the
18
+ // cache, against the resident instances it requires. Otherwise the import evaluated it
19
+ // and RNTL registered its own hooks. Consequences, each matching per-file isolation:
20
+ // - a file that never imports RNTL gets no RNTL hooks and no act environment;
21
+ // - `@testing-library/react-native/pure` never registers hooks;
22
+ // - whichever copy of RNTL the file imports is the one re-run (monorepos, duplicates);
23
+ // - an RNTL that Vite inlines registers itself and never passes through here.
24
+ // Two limits, both narrower than the leak this closes. An RNTL reached only through
25
+ // another Node-owned package, never imported by the file's own (Vite-owned) graph, is
26
+ // not seen here. And if such a package first loads RNTL during a file that also imports
27
+ // it directly, RNTL registers itself and the entry then re-runs, registering its hooks a
28
+ // second time in that one file — harmless, as cleanup is idempotent and the act
29
+ // environment pair restores in order.
30
+ //
31
+ // runExternalModule is Vitest's module-evaluator method in Vitest 4 and 5; if it goes
32
+ // away, nothing is wrapped and tests-native/hot-jest-compat fails on the RNTL surface.
33
+ import fs from "node:fs";
34
+ import Module from "node:module";
35
+ import { fileURLToPath } from "node:url";
36
+
37
+ const RNTL_ENTRY =
38
+ /[\\/]node_modules[\\/]@testing-library[\\/]react-native[\\/](?:build|dist)[\\/]index\.js$/;
39
+ const WRAPPED = Symbol.for("vitest-native.rntl-hooks");
40
+
41
+ function residentEntry(id) {
42
+ let file;
43
+ try {
44
+ file = id.startsWith("file://") ? fileURLToPath(id) : id.replace(/[?#].*$/, "");
45
+ } catch {
46
+ return null;
47
+ }
48
+ if (!RNTL_ENTRY.test(file)) return null;
49
+ if (Module._cache[file]) return file;
50
+ try {
51
+ const real = fs.realpathSync(file);
52
+ return Module._cache[real] ? real : null;
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Make `evaluator` re-register RNTL's per-file hooks whenever a file imports a
60
+ * resident RNTL entry. Idempotent.
61
+ */
62
+ export function registerRntlHooksOnImport(evaluator) {
63
+ const run = evaluator?.runExternalModule;
64
+ if (typeof run !== "function" || run[WRAPPED]) return;
65
+ const wrapped = async function (id) {
66
+ // Read before the import: afterwards the entry is always cached. A stubbed id
67
+ // never loads the file, so it never re-runs it either.
68
+ const stubbed = this?.stubs != null && typeof id === "string" && id in this.stubs;
69
+ const resident = typeof id === "string" && !stubbed ? residentEntry(id) : null;
70
+ const namespace = await run.call(this, id);
71
+ if (resident) new Module(resident, null).load(resident);
72
+ return namespace;
73
+ };
74
+ wrapped[WRAPPED] = true;
75
+ evaluator.runExternalModule = wrapped;
76
+ }
@@ -4,7 +4,7 @@
4
4
  import { createRequire, register } from "node:module";
5
5
  import path from "node:path";
6
6
  import { expect, vi } from "vitest";
7
- import { installGlobals } from "./globals.mjs";
7
+ import { installGlobals, installErrorUtils } from "./globals.mjs";
8
8
  import { installRequireHooks } from "./hooks.mjs";
9
9
  import { installRegistry } from "./registry.mjs";
10
10
  import { enableV8CompileCache } from "./compile-cache.mjs";
@@ -13,29 +13,39 @@ import { animatedMatchers } from "../matchers.mjs";
13
13
  import { serializer as rnSerializer } from "../serializer.mjs";
14
14
  import { VitestNativeError } from "../errors.mjs";
15
15
 
16
- // Hot runtime: surgical reset of state left by the PREVIOUS file. Setup files
17
- // are force-inlined by Vitest, so this body re-runs per test file even when the
18
- // rest of this package is externalized — making it the per-file hook. Installed
19
- // by worker.mjs (hot runtime only); a no-op everywhere else.
16
+ // Non-enumerable key on the preset container: the mocks built so far in this file.
17
+ const PRESETS_BUILT = Symbol.for("vitest-native.presets-built");
18
+
19
+ // Hot runtime: the worker resets state left by the PREVIOUS file at the file
20
+ // boundary (runner onBeforeCollect), before any setup file — including the user's,
21
+ // which Vitest runs ahead of this one. This file only contributes the Vitest-owned
22
+ // manifest entry, which needs this module's `vi`. A no-op outside the hot runtime.
20
23
  if (globalThis.__vitest_native_hot_reset) {
21
- // Vitest-level state first: in a fresh-worker-per-file world these die with
22
- // the worker, but Vitest's own per-file loop never undoes them. Fake timers
23
- // are the big one — jest suites enable them per file and rely on teardown;
24
- // leaked into the next file they break React rendering entirely ("Can't
25
- // access .root on unmounted test renderer" via RNTL).
26
- vi.useRealTimers();
27
- vi.unstubAllGlobals();
28
- vi.unstubAllEnvs();
29
- // NOTE on RNTL trees: when RNTL is inlined in the consumer graph it
30
- // re-evaluates per file (fresh registry + fresh auto-cleanup) and needs no
31
- // help. When RNTL is externalized/resident, trees from earlier files can
32
- // stay mounted (auto-cleanup's afterEach only registers in the first file) —
33
- // a memory accumulation, bounded by worker recycling, NOT a correctness
34
- // leak (each file renders into fresh roots; cross-file listeners are removed
35
- // by the reset below). Do NOT "fix" this by importing RNTL here or via Node
36
- // require — both create instance/evaluation-order hazards that corrupt
37
- // rendering (found via Rocket.Chat).
38
- globalThis.__vitest_native_hot_reset();
24
+ // Setup re-evaluates per file, but registration is idempotent: the first
25
+ // closure owns the worker-lifetime baseline and the manifest names any
26
+ // restoration failure. Fake timers are the critical case — leaking them into
27
+ // the next file breaks React rendering before an app assertion can explain it.
28
+ globalThis.__vitest_native_register_state?.({
29
+ id: "vitest-runtime",
30
+ // Vitest must uninstall fake timers before descriptor restoration: its
31
+ // uninstall owns Date and deletes it if another entry restores Date first.
32
+ restoreOrder: -200,
33
+ capture: () => null,
34
+ restore: () => {
35
+ vi.useRealTimers();
36
+ vi.unstubAllGlobals();
37
+ vi.unstubAllEnvs();
38
+ },
39
+ verify: () => {
40
+ if (vi.isFakeTimers()) {
41
+ throw new VitestNativeError("HOT_STATE_RESTORE_FAILED", "fake timers remain enabled");
42
+ }
43
+ },
44
+ });
45
+ // RNTL's per-file hooks (cleanup, act environment) for a resident RNTL are
46
+ // registered by the worker when a file imports it: see native/rntl-hooks.mjs. Do
47
+ // NOT import or require RNTL here instead — a load from setup in the first file
48
+ // creates the evaluation-order hazard that corrupted rendering (Rocket.Chat).
39
49
  }
40
50
 
41
51
  const projectRoot = process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd();
@@ -50,10 +60,15 @@ try {
50
60
  } catch {}
51
61
  // Asset extensions the Node require-hook should stub (matches the Vite graph).
52
62
  let assetExts = [];
63
+ let sourceExts = ["js", "jsx", "json", "ts", "tsx"];
53
64
  try {
54
65
  if (process.env.VITEST_NATIVE_ASSET_EXTS)
55
66
  assetExts = JSON.parse(process.env.VITEST_NATIVE_ASSET_EXTS);
56
67
  } catch {}
68
+ try {
69
+ if (process.env.VITEST_NATIVE_SOURCE_EXTS)
70
+ sourceExts = JSON.parse(process.env.VITEST_NATIVE_SOURCE_EXTS);
71
+ } catch {}
57
72
 
58
73
  // --- Third-party preset mocks ---
59
74
  //
@@ -154,6 +169,7 @@ if (!globalThis.__vitest_native_loader_registered) {
154
169
  transformPkgs: nodeTransformPkgs,
155
170
  presetExports,
156
171
  assetExts,
172
+ sourceExts: process.env.VITEST_NATIVE_SOURCE_EXTS ? sourceExts : undefined,
157
173
  hotGenerationBuffer: globalThis.__vitest_native_hot_generation?.buffer,
158
174
  },
159
175
  });
@@ -164,24 +180,56 @@ if (!globalThis.__vitest_native_loader_registered) {
164
180
  // serve — a computed require, a package in `transform` — falls through to the
165
181
  // hooks below, so this is purely a faster path to the same modules.
166
182
  if (process.env.VITEST_NATIVE_RN_REGISTRY) {
167
- const installed = installRegistry(process.env.VITEST_NATIVE_RN_REGISTRY, projectRoot);
183
+ const installed = installRegistry(process.env.VITEST_NATIVE_RN_REGISTRY, projectRoot, sourceExts);
168
184
  if (diagnostics) {
169
185
  console.log(
170
186
  `[vitest-native] (native) precompiled RN registry ${installed ? "installed" : "unavailable; using per-file module loading"}`,
171
187
  );
172
188
  }
173
189
  }
174
- installRequireHooks(projectRoot, nodeTransformPkgs, platform, reactNativeVersion, assetExts);
190
+ installRequireHooks(
191
+ projectRoot,
192
+ nodeTransformPkgs,
193
+ platform,
194
+ reactNativeVersion,
195
+ assetExts,
196
+ sourceExts,
197
+ );
198
+ // After the hooks: the polyfill is Flow-typed and compiled by them (see globals.mjs).
199
+ installErrorUtils(projectRoot);
175
200
 
176
- // Build the mock objects now that the require hooks are installed (preset
177
- // factories may lazily resolve react-native at render time).
201
+ // Preset mocks are built on first use in each file, not up front. A project with
202
+ // twenty auto-detected presets otherwise builds ~900 vi.fn() mocks for every test
203
+ // file, most of which never import those packages — and Vitest keeps every vi.fn()
204
+ // it has ever created (for clearAllMocks), so under worker reuse each file's unused
205
+ // mocks stayed reachable for the rest of the run. Accessors are redefined for every
206
+ // file, so each file still gets its own fresh mock the moment it needs one.
178
207
  const g = globalThis;
179
208
  g.__vitest_native_preset_mocks = g.__vitest_native_preset_mocks || Object.create(null);
209
+ const builtPresetMocks = new Map();
210
+ Object.defineProperty(g.__vitest_native_preset_mocks, PRESETS_BUILT, {
211
+ configurable: true,
212
+ enumerable: false,
213
+ writable: true,
214
+ value: builtPresetMocks,
215
+ });
180
216
  for (const { pkg, mod, presetName } of presetDefs) {
181
- g.__vitest_native_preset_mocks[pkg] = mod.factory();
182
- if (diagnostics) {
183
- console.log(`[vitest-native] (native) registered preset mock: ${pkg} (${presetName})`);
184
- }
217
+ Object.defineProperty(g.__vitest_native_preset_mocks, pkg, {
218
+ configurable: true,
219
+ enumerable: true,
220
+ get() {
221
+ if (!builtPresetMocks.has(pkg)) {
222
+ builtPresetMocks.set(pkg, mod.factory());
223
+ if (diagnostics) {
224
+ console.log(`[vitest-native] (native) built preset mock: ${pkg} (${presetName})`);
225
+ }
226
+ }
227
+ return builtPresetMocks.get(pkg);
228
+ },
229
+ set(value) {
230
+ builtPresetMocks.set(pkg, value);
231
+ },
232
+ });
185
233
  }
186
234
 
187
235
  // --- Shared test-helper control surface ---
@@ -232,7 +280,8 @@ g.__vitest_native_control = {
232
280
  for (const name of Object.keys(g.__vitest_native_module_mocks)) {
233
281
  delete g.__vitest_native_module_mocks[name];
234
282
  }
235
- for (const presetMock of Object.values(g.__vitest_native_preset_mocks || {})) {
283
+ // Only mocks this file actually built; resetting must not build the rest.
284
+ for (const presetMock of builtPresetMocks.values()) {
236
285
  presetMock?._reset?.();
237
286
  presetMock?._resetStore?.();
238
287
  }
@@ -0,0 +1,22 @@
1
+ export interface StateManifestEntry<Snapshot = unknown> {
2
+ id: string;
3
+ /** Lower values restore first. Equal values preserve registration order. */
4
+ restoreOrder?: number;
5
+ capture(): Snapshot;
6
+ restore(snapshot: Snapshot): void;
7
+ verify?(snapshot: Snapshot): void;
8
+ }
9
+
10
+ export interface StateManifest {
11
+ register(entry: StateManifestEntry): boolean;
12
+ beginFile(): void;
13
+ restore(): void;
14
+ entries(): string[];
15
+ }
16
+
17
+ export declare function createStateManifest(options?: {
18
+ diagnostics?: boolean;
19
+ mutation?: string | null;
20
+ }): StateManifest;
21
+
22
+ export declare const HOT_STATE_MANIFEST_ENTRIES: readonly string[];
@@ -0,0 +1,136 @@
1
+ // Declarative shared-realm state restoration for the hot runtime.
2
+ //
3
+ // Module isolation resets code. This manifest resets the mutable realm around that
4
+ // code: globals, environment, listeners, native boundary state and runtime-specific
5
+ // singletons. Every entry is named, captured once at the first file boundary, then
6
+ // restored and verified before the next file. A failure names the responsible entry
7
+ // instead of being swallowed and turning into an order-dependent later assertion.
8
+ import { VitestNativeError, VitestNativeTypeError } from "../errors.mjs";
9
+
10
+ const NOT_CAPTURED = Symbol("vitest-native.state.not-captured");
11
+
12
+ function messageOf(error) {
13
+ const message = error instanceof Error ? error.message : String(error);
14
+ return message.replace(/^\[vitest-native\] /, "");
15
+ }
16
+
17
+ export function createStateManifest({ diagnostics = false, mutation = null } = {}) {
18
+ const records = [];
19
+ const ids = new Set();
20
+ let initialized = false;
21
+ let dirty = false;
22
+
23
+ function capture(record) {
24
+ try {
25
+ record.snapshot = record.entry.capture();
26
+ } catch (error) {
27
+ throw new VitestNativeError(
28
+ "HOT_STATE_CAPTURE_FAILED",
29
+ `hotRuntime could not capture state manifest entry '${record.entry.id}': ${messageOf(error)}`,
30
+ { cause: error },
31
+ );
32
+ }
33
+ }
34
+
35
+ function register(entry) {
36
+ if (!entry || typeof entry.id !== "string" || entry.id.length === 0) {
37
+ throw new VitestNativeTypeError(
38
+ "INVALID_OPTION",
39
+ "state manifest entries require a non-empty string id",
40
+ );
41
+ }
42
+ if (typeof entry.capture !== "function" || typeof entry.restore !== "function") {
43
+ throw new VitestNativeTypeError(
44
+ "INVALID_OPTION",
45
+ `state manifest entry '${entry.id}' requires capture() and restore()`,
46
+ );
47
+ }
48
+ // Setup files re-evaluate per file. Their registration is intentionally
49
+ // idempotent so the first closure owns the worker-lifetime snapshot.
50
+ if (ids.has(entry.id)) return false;
51
+ ids.add(entry.id);
52
+ const record = { entry, snapshot: NOT_CAPTURED, registrationIndex: records.length };
53
+ records.push(record);
54
+ if (initialized) capture(record);
55
+ return true;
56
+ }
57
+
58
+ function captureAll() {
59
+ if (initialized) return;
60
+ for (const record of records) capture(record);
61
+ initialized = true;
62
+ if (diagnostics) {
63
+ console.log(
64
+ `[vitest-native] state manifest: ${records.map(({ entry }) => entry.id).join(", ")}`,
65
+ );
66
+ }
67
+ }
68
+
69
+ function restoreAll() {
70
+ captureAll();
71
+ if (!dirty) return;
72
+ const failures = [];
73
+ const ordered = [...records].sort(
74
+ (left, right) =>
75
+ (left.entry.restoreOrder ?? 0) - (right.entry.restoreOrder ?? 0) ||
76
+ left.registrationIndex - right.registrationIndex,
77
+ );
78
+ for (const record of ordered) {
79
+ const { entry, snapshot } = record;
80
+ try {
81
+ // Validation can disable one action while leaving verification armed. This
82
+ // is a mutation oracle, not a supported user option.
83
+ if (mutation !== entry.id) entry.restore(snapshot);
84
+ } catch (error) {
85
+ failures.push(`${entry.id} restore: ${messageOf(error)}`);
86
+ }
87
+ }
88
+ // Verify only after every restore has run. Restore domains can interact
89
+ // (for example fake timers own the global Date descriptor), so validating
90
+ // inline would miss damage caused by a later entry.
91
+ for (const record of ordered) {
92
+ const { entry, snapshot } = record;
93
+ if (typeof entry.verify === "function") {
94
+ try {
95
+ entry.verify(snapshot);
96
+ } catch (error) {
97
+ failures.push(`${entry.id} verify: ${messageOf(error)}`);
98
+ }
99
+ }
100
+ }
101
+ if (failures.length > 0) {
102
+ throw new VitestNativeError(
103
+ "HOT_STATE_RESTORE_FAILED",
104
+ `hotRuntime state restoration failed:\n- ${failures.join("\n- ")}`,
105
+ );
106
+ }
107
+ dirty = false;
108
+ }
109
+
110
+ function beginFile() {
111
+ captureAll();
112
+ restoreAll();
113
+ dirty = true;
114
+ }
115
+
116
+ return Object.freeze({
117
+ register,
118
+ beginFile,
119
+ restore: restoreAll,
120
+ entries: () => records.map(({ entry }) => entry.id),
121
+ });
122
+ }
123
+
124
+ export const HOT_STATE_MANIFEST_ENTRIES = Object.freeze([
125
+ "vitest-runtime",
126
+ "native-boundary-mocks",
127
+ "react-native.dimensions",
128
+ "react-native.appearance",
129
+ "react-native.event-listeners",
130
+ "process.env",
131
+ "process.listeners",
132
+ "global.descriptors",
133
+ "console.descriptors",
134
+ "react-native.error-utils",
135
+ "expo.runtime",
136
+ ]);
@@ -69,15 +69,28 @@ export const TRANSFORM_CACHE_VERSION = 4;
69
69
  * node_modules is absent or unwritable.
70
70
  */
71
71
  export function cacheRootFor(projectRoot) {
72
- const nm = path.join(projectRoot, "node_modules");
73
- if (fs.existsSync(nm)) {
74
- try {
75
- const dir = path.join(nm, ".cache", "vitest-native");
76
- fs.mkdirSync(dir, { recursive: true });
77
- return dir;
78
- } catch {
79
- // Read-only node_modules (some CI sandboxes) — fall through to tmpdir.
72
+ // The project's own node_modules, else the nearest one above it that holds React
73
+ // Native: a project in a monorepo, or a Vitest project rooted in a subdirectory,
74
+ // often has none of its own — its dependencies are hoisted — and its cache belongs
75
+ // with the install it uses, not with an unrelated node_modules further up.
76
+ const start = path.resolve(projectRoot);
77
+ for (let dir = start; ; dir = path.dirname(dir)) {
78
+ const nm = path.join(dir, "node_modules");
79
+ const owns =
80
+ dir === start
81
+ ? fs.existsSync(nm)
82
+ : fs.existsSync(path.join(nm, "react-native", "package.json"));
83
+ if (owns) {
84
+ try {
85
+ const cache = path.join(nm, ".cache", "vitest-native");
86
+ fs.mkdirSync(cache, { recursive: true });
87
+ return cache;
88
+ } catch {
89
+ // Read-only node_modules (some CI sandboxes) — fall through to tmpdir.
90
+ }
91
+ break;
80
92
  }
93
+ if (path.dirname(dir) === dir) break;
81
94
  }
82
95
  const dir = path.join(os.tmpdir(), "vitest-native-cache");
83
96
  fs.mkdirSync(dir, { recursive: true });
@@ -265,8 +278,16 @@ export function isFlow(src) {
265
278
  * hands those to Node as CommonJS today, and changing that is an interop question
266
279
  * about named exports and live bindings that this check does not answer.
267
280
  */
281
+ const TYPESCRIPT_FILE = /\.[cm]?tsx?$/;
282
+
268
283
  export function needsTransform(file, src) {
269
284
  if (file.endsWith(".mjs") || moduleGoal(file)) return true; // Not this check's business.
285
+ // Node refuses TypeScript under node_modules by extension, whatever the content
286
+ // ("Stripping types is currently unsupported for files under node_modules"). Expo
287
+ // packages publish their TypeScript source (expo-modules-core's `main` is
288
+ // src/index.ts), and a file with no type syntax — its src/polyfill/index.ts is a
289
+ // bare `// noop` — parses as a script, so the check below would hand it to Node.
290
+ if (TYPESCRIPT_FILE.test(file)) return true;
270
291
  try {
271
292
  // Parsed for the verdict only; the compiled script is never run.
272
293
  const parsed = new vm.Script(src, { filename: file });
@@ -13,11 +13,12 @@ import { createRequire } from "node:module";
13
13
  import path from "node:path";
14
14
  import { isMainThread, parentPort, threadId } from "node:worker_threads";
15
15
  import { init, runBaseTests, setupEnvironment } from "vitest/worker";
16
- import { installGlobals } from "./globals.mjs";
16
+ import { installGlobals, installErrorUtils } from "./globals.mjs";
17
17
  import { installRequireHooks } from "./hooks.mjs";
18
18
  import { installHotReset } from "./reset.mjs";
19
19
  import { installRegistry } from "./registry.mjs";
20
20
  import { captureModuleBaseline } from "./module-reset.mjs";
21
+ import { registerRntlHooksOnImport } from "./rntl-hooks.mjs";
21
22
  import { enableV8CompileCache } from "./compile-cache.mjs";
22
23
  import { VitestNativeError } from "../errors.mjs";
23
24
 
@@ -32,10 +33,15 @@ const reactNativeVersion = process.env.VITEST_NATIVE_RN_VERSION || "0.0.0";
32
33
  let transformPkgs = [];
33
34
  let preserveGlobals = [];
34
35
  let assetExts = [];
36
+ let sourceExts = ["js", "jsx", "json", "ts", "tsx"];
35
37
  try {
36
38
  if (process.env.VITEST_NATIVE_TRANSFORM)
37
39
  transformPkgs = JSON.parse(process.env.VITEST_NATIVE_TRANSFORM);
38
40
  } catch {}
41
+ try {
42
+ if (process.env.VITEST_NATIVE_SOURCE_EXTS)
43
+ sourceExts = JSON.parse(process.env.VITEST_NATIVE_SOURCE_EXTS);
44
+ } catch {}
39
45
  try {
40
46
  if (process.env.VITEST_NATIVE_ASSET_EXTS)
41
47
  assetExts = JSON.parse(process.env.VITEST_NATIVE_ASSET_EXTS);
@@ -66,9 +72,18 @@ installGlobals();
66
72
  // worker holding a second, separate copy of RN's singletons from the one every
67
73
  // test file sees.
68
74
  if (process.env.VITEST_NATIVE_RN_REGISTRY) {
69
- installRegistry(process.env.VITEST_NATIVE_RN_REGISTRY, projectRoot);
75
+ installRegistry(process.env.VITEST_NATIVE_RN_REGISTRY, projectRoot, sourceExts);
70
76
  }
71
- installRequireHooks(projectRoot, transformPkgs, platform, reactNativeVersion, assetExts);
77
+ installRequireHooks(
78
+ projectRoot,
79
+ transformPkgs,
80
+ platform,
81
+ reactNativeVersion,
82
+ assetExts,
83
+ sourceExts,
84
+ );
85
+ // After the hooks: the polyfill is Flow-typed and compiled by them (see globals.mjs).
86
+ installErrorUtils(projectRoot);
72
87
  try {
73
88
  const req = createRequire(path.join(projectRoot, "package.json"));
74
89
  const RN = req("react-native");
@@ -104,7 +119,13 @@ try {
104
119
  );
105
120
  }
106
121
  const resetModules = captureModuleBaseline();
107
- const { hotReset, bless } = installHotReset({ projectRoot, diagnostics, preserveGlobals });
122
+ const { hotReset, bless, registerState, stateEntries } = installHotReset({
123
+ projectRoot,
124
+ diagnostics,
125
+ preserveGlobals,
126
+ });
127
+ globalThis.__vitest_native_register_state = registerState;
128
+ globalThis.__vitest_native_state_entries = stateEntries;
108
129
  globalThis.__vitest_native_hot_reset = () => {
109
130
  globalThis.__vitest_native_registry_reset?.();
110
131
  // Advance the ESM generation so externalized packages a test file `import`s are
@@ -147,9 +168,35 @@ let moduleRunner = null;
147
168
  // module nodes, and re-evaluating Vitest itself, for nothing.
148
169
  const VITEST_RUNTIME = [/\/vitest\/dist\//, /vitest-virtual-\w+\/dist/, /@vitest\/dist/];
149
170
 
171
+ /**
172
+ * Drop mocks queued but not yet resolved.
173
+ *
174
+ * `vi.mock`/`vi.doMock` push onto a static queue on Vitest's mocker class, which is
175
+ * resolved on the next import. `mocker.reset()` clears the registries but not that
176
+ * queue, so a `vi.doMock` issued after a file's last import was resolved during the
177
+ * NEXT file's first import and mocked it there. Per-file isolation never sees this —
178
+ * the worker, and its queue, go away. The queue is internal (Vitest 4 and 5 both keep
179
+ * it as `static pendingIds` on BareModuleMocker); if it moves, this is a no-op and
180
+ * tests-native/hot-jest-compat fails by name on the runtime-mock surface.
181
+ */
182
+ function clearPendingMocks(mocker) {
183
+ for (let C = mocker?.constructor; C && C !== Function.prototype; C = Object.getPrototypeOf(C)) {
184
+ if (Object.hasOwn(C, "pendingIds") && Array.isArray(C.pendingIds)) {
185
+ C.pendingIds = [];
186
+ return;
187
+ }
188
+ }
189
+ }
190
+
150
191
  globalThis.__vitest_native_reset_module_runner = () => {
192
+ // The previous file's realm state (fake timers, stubbed globals, listeners) must be
193
+ // gone before ANY setup file of the next one runs. It used to be reset from this
194
+ // package's setup file, which Vitest runs after the user's own: a user setup that
195
+ // installs fake timers then found the previous file's still installed.
196
+ globalThis.__vitest_native_hot_reset?.();
151
197
  if (!moduleRunner) return;
152
198
  moduleRunner.mocker?.reset();
199
+ clearPendingMocks(moduleRunner.mocker);
153
200
  for (const [id, node] of moduleRunner.evaluatedModules.idToModuleMap) {
154
201
  if (VITEST_RUNTIME.some((re) => re.test(id))) continue;
155
202
  node.promise = undefined;
@@ -169,6 +216,7 @@ init({
169
216
  collectTests: (state, traces) => runBaseTests("collect", state, traces),
170
217
  onModuleRunner: (runner) => {
171
218
  moduleRunner = runner;
219
+ registerRntlHooksOnImport(runner.evaluator);
172
220
  },
173
221
  setup: setupEnvironment,
174
222
  });