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
@@ -1,69 +1,51 @@
1
- // Surgical per-file reset for the hot runtime (see worker.mjs and runner.mjs).
2
- //
3
- // Vitest's own per-file reset (run with config.isolate flipped on by worker.mjs)
4
- // already re-evaluates everything in the module-runner graph — test files, app
5
- // source, setup files. What it can NOT touch is state living in the worker's
6
- // resident Node require cache: React Native itself (externalized by design),
7
- // other externalized CJS deps, and our boundary mocks. This module covers that
8
- // gap with a boot-baseline + import-attribution model:
9
- //
10
- // THE ATTRIBUTION PROBLEM: top-level code in an app/test module re-runs for
11
- // every file and must be cleaned, while a resident externalized dependency
12
- // initializes only once and may need to retain its process-wide state. A
13
- // blanket "bless everything created during import" policy confuses the two
14
- // and leaks app globals, env mutations, and listeners across files.
15
- //
16
- // The split is observable: runner.mjs calls bless() from onBeforeRunFiles —
17
- // after the test module (and its resident deps) finished importing, before
18
- // any test runs. Listener call sites inside node_modules are treated as
19
- // resident import state; listeners created by app/test modules stay tracked
20
- // and are removed at the NEXT file's setup. Globals and process.env always
21
- // return to the worker boot baseline, with an explicit preserveGlobals escape
22
- // hatch for external libraries that intentionally publish a global registry.
23
- // If bless() never fires (consumer overrode `runner`), attribution-dependent
24
- // teardowns stay disarmed — fail-open rather than guessing.
25
- //
26
- // Covered surfaces:
27
- // 1. RN event listeners — every NativeEventEmitter (AppState, Appearance,
28
- // Keyboard, …) delegates to the RCTDeviceEventEmitter singleton, so one
29
- // wrapped addListener tracks the whole RN JS event surface. Test-phase
30
- // subscriptions are removed via their own public subscription.remove().
31
- // Only import-phase subscriptions owned by node_modules are blessed.
32
- // 2. RN module state with known mutation APIs (Dimensions, Appearance) —
33
- // restored from a boot-time snapshot (value-restore: no attribution needed).
34
- // 2b. process.env — restored to the worker boot snapshot.
35
- // 3. Vitest timers/global/env stubs — restored by setup.mjs before this reset.
36
- // 4. Boundary/preset mocks that registered callbacks in
37
- // globalThis.__vitest_native_resets (the turboStubs register one per
38
- // native-module name to clear per-file overrides; runs before the
39
- // value-restores, which route through those stubs).
40
- // 5. globalThis keys added by a file — deleted. The baseline starts at the
41
- // first per-file call (after Vitest injected its per-batch globals) and
42
- // never grows implicitly. Mutations of pre-existing keys are not restored
43
- // (documented limitation).
1
+ // Shared-realm restoration for the hot runtime. Vitest resets the Vite graph;
2
+ // this manifest covers Node/RN state, environment, listeners, descriptors,
3
+ // timers, native-boundary mocks, ErrorUtils and Expo state. runner.mjs calls
4
+ // bless() after import and before tests. Only imports whose shared ownership
5
+ // policy is worker-resident keep their listener state; ordinary dependencies and
6
+ // app/test code re-evaluate and remain resettable. Attribution-dependent cleanup
7
+ // stays disarmed if a consumer replaces the runner, rather than guessing.
44
8
  import { createRequire } from "node:module";
45
9
  import path from "node:path";
46
10
  import { fileURLToPath } from "node:url";
11
+ import { VitestNativeError } from "../errors.mjs";
12
+ import { isRuntimeResidentFile, isTestRuntimeResidentFile } from "./ownership.mjs";
13
+ import { createStateManifest } from "./state-manifest.mjs";
47
14
 
48
15
  // Keys owned by the harness or this plugin — never deleted by the globals diff.
49
16
  const HARNESS_GLOBALS = /^(__vitest_native_|__VITEST|__coverage__|__VITE)/;
17
+ // Node's bundled undici installs these non-configurable symbols lazily. Their
18
+ // lifecycle belongs to the host runtime, not to the test file that happens to
19
+ // trigger initialization, and attempting to delete them poisons every later
20
+ // file. Keep the allowlist narrow and description-based across Node releases.
21
+ const NODE_LAZY_GLOBAL_SYMBOLS = /^undici\.(?:globalDispatcher|globalOrigin)(?:\.|$)/;
50
22
  // Vitest updates these scheduler-owned values between tasks.
51
23
  const ENV_PRESERVED = new Set(["VITEST_POOL_ID", "VITEST_WORKER_ID"]);
52
24
  const RESET_FILE = fileURLToPath(import.meta.url).replaceAll("\\", "/");
53
25
  const DEFAULT_PRESERVED_GLOBALS = ["__STORYBOOK_ADDONS_PREVIEW"];
54
26
 
55
- function isResidentImportListener(stack, projectRoot) {
27
+ function stateFailure(message) {
28
+ return new VitestNativeError("HOT_STATE_RESTORE_FAILED", message);
29
+ }
30
+
31
+ export function isResidentImportListener(stack, projectRoot) {
56
32
  const root = projectRoot.replaceAll("\\", "/").replace(/\/$/, "");
57
33
  let sawExternalFrame = false;
58
34
 
59
35
  for (const rawLine of stack.split("\n").slice(1)) {
60
36
  const line = rawLine.replaceAll("\\", "/");
61
37
  if (line.includes(RESET_FILE)) continue;
62
- if (!line.includes(`${root}/`)) continue;
63
38
  if (line.includes("/node_modules/")) {
64
39
  sawExternalFrame = true;
40
+ // Most Node-owned packages reset per file. Only the identity-sensitive
41
+ // runtime/test-runtime allowlists are truly resident; blessing every
42
+ // node_modules frame duplicates listeners when an ordinary dependency
43
+ // re-evaluates in the next file. This is the same reset policy used by
44
+ // module-reset.mjs, not a second location heuristic.
45
+ if (!isRuntimeResidentFile(line) && !isTestRuntimeResidentFile(line)) return false;
65
46
  continue;
66
47
  }
48
+ if (!line.includes(`${root}/`)) continue;
67
49
  // A project-owned frame means this listener was created by app/test code,
68
50
  // even when the call passed through React Native internals.
69
51
  return false;
@@ -72,6 +54,51 @@ function isResidentImportListener(stack, projectRoot) {
72
54
  return sawExternalFrame;
73
55
  }
74
56
 
57
+ function captureDescriptors(target) {
58
+ return new Map(
59
+ Reflect.ownKeys(target).map((key) => [key, Object.getOwnPropertyDescriptor(target, key)]),
60
+ );
61
+ }
62
+
63
+ function sameDescriptor(left, right) {
64
+ if (!left || !right) return left === right;
65
+ return (
66
+ left.configurable === right.configurable &&
67
+ left.enumerable === right.enumerable &&
68
+ left.writable === right.writable &&
69
+ Object.is(left.value, right.value) &&
70
+ left.get === right.get &&
71
+ left.set === right.set
72
+ );
73
+ }
74
+
75
+ function restoreDescriptors(target, baseline, skip = () => false) {
76
+ for (const key of Reflect.ownKeys(target)) {
77
+ if (skip(key) || baseline.has(key)) continue;
78
+ if (!Reflect.deleteProperty(target, key)) {
79
+ throw stateFailure(`could not delete ${String(key)}`);
80
+ }
81
+ }
82
+ for (const [key, descriptor] of baseline) {
83
+ if (skip(key)) continue;
84
+ if (!sameDescriptor(Object.getOwnPropertyDescriptor(target, key), descriptor)) {
85
+ Object.defineProperty(target, key, descriptor);
86
+ }
87
+ }
88
+ }
89
+
90
+ function verifyDescriptors(target, baseline, skip = () => false) {
91
+ for (const key of Reflect.ownKeys(target)) {
92
+ if (!skip(key) && !baseline.has(key)) throw stateFailure(`unexpected ${String(key)}`);
93
+ }
94
+ for (const [key, descriptor] of baseline) {
95
+ if (skip(key)) continue;
96
+ if (!sameDescriptor(Object.getOwnPropertyDescriptor(target, key), descriptor)) {
97
+ throw stateFailure(`descriptor differs for ${String(key)}`);
98
+ }
99
+ }
100
+ }
101
+
75
102
  /**
76
103
  * Called once at hot-worker boot, AFTER react-native has been preloaded and its
77
104
  * stateful core modules touched (so their internal boot-time listeners register
@@ -83,6 +110,11 @@ export function installHotReset({ projectRoot, diagnostics, preserveGlobals = []
83
110
  const req = createRequire(path.join(projectRoot, "package.json"));
84
111
  const RN = req("react-native");
85
112
  const explicitlyPreserved = new Set([...DEFAULT_PRESERVED_GLOBALS, ...preserveGlobals]);
113
+ const globallyPreserved = new Set();
114
+ const manifest = createStateManifest({
115
+ diagnostics,
116
+ mutation: process.env.VITEST_NATIVE_HOT_STATE_MUTATION || null,
117
+ });
86
118
 
87
119
  // --- (1) Track listeners added to the RCTDeviceEventEmitter singleton ---
88
120
  const tracked = new Map();
@@ -96,25 +128,39 @@ export function installHotReset({ projectRoot, diagnostics, preserveGlobals = []
96
128
  return sub;
97
129
  };
98
130
 
99
- // --- (2) Boot snapshot of mutable resident RN state ---
100
- let dims = null;
101
- try {
102
- dims = {
103
- window: { ...RN.Dimensions.get("window") },
104
- screen: { ...RN.Dimensions.get("screen") },
131
+ // Track process listeners with the same attribution rule. Node's once() and
132
+ // prependOnceListener() delegate through these methods, so their wrapper listener
133
+ // is captured without replacing EventEmitter's once semantics.
134
+ const trackedProcessListeners = new Set();
135
+ const originalProcessAdd = process.addListener;
136
+ const originalProcessPrepend = process.prependListener;
137
+ const originalProcessRemove = process.removeListener;
138
+ function trackProcessAdd(original) {
139
+ return function (eventName, listener) {
140
+ const before = process.rawListeners(eventName);
141
+ const result = original.call(this, eventName, listener);
142
+ const after = process.rawListeners(eventName);
143
+ const remaining = [...before];
144
+ const added = after.filter((candidate) => {
145
+ const index = remaining.indexOf(candidate);
146
+ if (index === -1) return true;
147
+ remaining.splice(index, 1);
148
+ return false;
149
+ });
150
+ for (const rawListener of added) {
151
+ trackedProcessListeners.add({
152
+ eventName,
153
+ rawListener,
154
+ residentImport: isResidentImportListener(new Error().stack || "", projectRoot),
155
+ });
156
+ }
157
+ return result;
105
158
  };
106
- } catch {}
107
- let colorScheme = null;
108
- try {
109
- colorScheme = RN.Appearance.getColorScheme?.() ?? null;
110
- } catch {}
111
-
112
- // --- (2b) Fixed process.env worker-boot snapshot ---
113
- const envBaseline = { ...process.env };
114
-
115
- // --- (5) globalThis baseline: starts at the first per-file call and remains
116
- // fixed. Explicitly preserved keys may join it at an import boundary. ---
117
- let globalBaseline = null;
159
+ }
160
+ const trackedAdd = trackProcessAdd(originalProcessAdd);
161
+ process.addListener = trackedAdd;
162
+ process.on = trackedAdd;
163
+ process.prependListener = trackProcessAdd(originalProcessPrepend);
118
164
 
119
165
  // Attribution-dependent teardowns run only once bless() has fired at least
120
166
  // once (i.e. the hot runner is installed and working).
@@ -122,91 +168,215 @@ export function installHotReset({ projectRoot, diagnostics, preserveGlobals = []
122
168
 
123
169
  function bless() {
124
170
  armed = true;
125
- if (globalBaseline) {
126
- for (const key of explicitlyPreserved) {
127
- if (Object.hasOwn(globalThis, key)) globalBaseline.add(key);
128
- }
171
+ for (const key of explicitlyPreserved) {
172
+ if (Object.hasOwn(globalThis, key)) globallyPreserved.add(key);
129
173
  }
130
174
  // Resident external dependencies do not re-run, so retain only listeners
131
- // whose import-time call stack belongs exclusively to node_modules.
175
+ // whose import-time call stack belongs exclusively to packages the shared
176
+ // ownership policy marks worker-resident.
132
177
  for (const [sub, record] of tracked) {
133
178
  if (record.residentImport) tracked.delete(sub);
134
179
  }
180
+ for (const record of trackedProcessListeners) {
181
+ if (record.residentImport) trackedProcessListeners.delete(record);
182
+ }
183
+ globalThis.expo?.[Symbol.for("vitest-native.expo.reset")]?.bless?.((stack) =>
184
+ isResidentImportListener(stack, projectRoot),
185
+ );
135
186
  }
136
187
 
137
- function hotReset() {
138
- if (globalBaseline === null) {
139
- // First file: nothing to clean — the worker is pristine. Capture the
140
- // baseline every later file must be reset back to.
141
- globalBaseline = new Set(Reflect.ownKeys(globalThis));
142
- return;
143
- }
188
+ manifest.register({
189
+ id: "native-boundary-mocks",
190
+ // Clear per-file boundary overrides before value-based RN restores route
191
+ // through those same boundary objects.
192
+ restoreOrder: -100,
193
+ capture: () => null,
194
+ restore: () => {
195
+ const resets = globalThis.__vitest_native_resets;
196
+ if (Array.isArray(resets)) for (const reset of resets) reset();
197
+ },
198
+ verify: () => {
199
+ const resets = globalThis.__vitest_native_resets;
200
+ if (Array.isArray(resets) && resets.some((reset) => reset.verify?.() === false)) {
201
+ throw stateFailure("native boundary overrides remain");
202
+ }
203
+ },
204
+ });
144
205
 
145
- // (3) RNTL cleanup happens in setup.mjs, NOT here: it must run in the
146
- // module-runner context so it reaches the SAME RNTL instance the tests
147
- // use. Loading RNTL through Node from here created a second instance whose
148
- // act/auto-cleanup machinery corrupted rendering for every later file
149
- // when the consumer's graph inlines RNTL (found via Rocket.Chat).
150
-
151
- // (4) Boundary/preset mock reset callbacks — BEFORE the value-restore:
152
- // these clear per-file overrides on the boundary stubs (spies, direct
153
- // method assignments), and the value-restore below routes through those
154
- // very stubs (Appearance.setColorScheme → NativeAppearance). Restoring
155
- // first would send the restore through a previous file's dead override
156
- // and then clear it one step too late.
157
- const resets = globalThis.__vitest_native_resets;
158
- if (Array.isArray(resets)) {
159
- for (const fn of resets) {
160
- try {
161
- fn();
162
- } catch {}
206
+ manifest.register({
207
+ id: "react-native.dimensions",
208
+ capture: () => ({
209
+ window: { ...RN.Dimensions.get("window") },
210
+ screen: { ...RN.Dimensions.get("screen") },
211
+ }),
212
+ restore: (snapshot) => RN.Dimensions.set(snapshot),
213
+ verify: (snapshot) => {
214
+ const current = {
215
+ window: RN.Dimensions.get("window"),
216
+ screen: RN.Dimensions.get("screen"),
217
+ };
218
+ if (JSON.stringify(current) !== JSON.stringify(snapshot)) {
219
+ throw stateFailure("Dimensions differ from the worker baseline");
163
220
  }
164
- }
221
+ },
222
+ });
165
223
 
166
- // (2) Restore mutable resident RN state (value-restore, always safe).
167
- if (dims) {
168
- try {
169
- RN.Dimensions.set(dims);
170
- } catch {}
171
- }
172
- try {
173
- RN.Appearance.setColorScheme?.(colorScheme);
174
- } catch {}
224
+ manifest.register({
225
+ id: "react-native.appearance",
226
+ capture: () => RN.Appearance.getColorScheme?.() ?? null,
227
+ restore: (snapshot) => RN.Appearance.setColorScheme?.(snapshot),
228
+ verify: (snapshot) => {
229
+ if ((RN.Appearance.getColorScheme?.() ?? null) !== snapshot) {
230
+ throw stateFailure("Appearance differs from the worker baseline");
231
+ }
232
+ },
233
+ });
175
234
 
176
- if (!armed) return; // no bless yet → cannot attribute; fail open
235
+ manifest.register({
236
+ id: "react-native.event-listeners",
237
+ capture: () => null,
238
+ restore: () => {
239
+ if (!armed) return;
240
+ for (const sub of tracked.keys()) sub.remove();
241
+ tracked.clear();
242
+ },
243
+ verify: () => {
244
+ if (armed && tracked.size > 0) {
245
+ throw stateFailure(`${tracked.size} subscriptions remain`);
246
+ }
247
+ },
248
+ });
177
249
 
178
- // (1) Remove the previous file's test-phase RN event listeners.
179
- for (const sub of tracked.keys()) {
180
- try {
181
- sub.remove();
182
- } catch {}
183
- }
184
- tracked.clear();
250
+ manifest.register({
251
+ id: "process.env",
252
+ capture: () => ({ ...process.env }),
253
+ restore: (baseline) => {
254
+ for (const key of Object.keys(process.env)) {
255
+ if (ENV_PRESERVED.has(key)) continue;
256
+ if (!(key in baseline)) delete process.env[key];
257
+ else if (process.env[key] !== baseline[key]) process.env[key] = baseline[key];
258
+ }
259
+ for (const key of Object.keys(baseline)) {
260
+ if (!(key in process.env) && !ENV_PRESERVED.has(key)) process.env[key] = baseline[key];
261
+ }
262
+ },
263
+ verify: (baseline) => {
264
+ const keys = new Set([...Object.keys(process.env), ...Object.keys(baseline)]);
265
+ for (const key of keys) {
266
+ if (!ENV_PRESERVED.has(key) && process.env[key] !== baseline[key]) {
267
+ throw stateFailure(`${key} differs from the worker baseline`);
268
+ }
269
+ }
270
+ },
271
+ });
185
272
 
186
- // (2b) Restore process.env to the worker boot snapshot.
187
- for (const key of Object.keys(process.env)) {
188
- if (ENV_PRESERVED.has(key)) continue;
189
- if (!(key in envBaseline)) delete process.env[key];
190
- else if (process.env[key] !== envBaseline[key]) process.env[key] = envBaseline[key];
191
- }
192
- for (const key of Object.keys(envBaseline)) {
193
- if (!(key in process.env) && !ENV_PRESERVED.has(key)) process.env[key] = envBaseline[key];
194
- }
273
+ manifest.register({
274
+ id: "process.listeners",
275
+ capture: () => ({
276
+ addListener: process.addListener,
277
+ on: process.on,
278
+ prependListener: process.prependListener,
279
+ }),
280
+ restore: (baseline) => {
281
+ if (armed) {
282
+ for (const record of trackedProcessListeners) {
283
+ originalProcessRemove.call(process, record.eventName, record.rawListener);
284
+ }
285
+ trackedProcessListeners.clear();
286
+ }
287
+ process.addListener = baseline.addListener;
288
+ process.on = baseline.on;
289
+ process.prependListener = baseline.prependListener;
290
+ },
291
+ verify: (baseline) => {
292
+ if (armed && trackedProcessListeners.size > 0) {
293
+ throw stateFailure(`${trackedProcessListeners.size} listeners remain`);
294
+ }
295
+ if (
296
+ process.addListener !== baseline.addListener ||
297
+ process.on !== baseline.on ||
298
+ process.prependListener !== baseline.prependListener
299
+ ) {
300
+ throw stateFailure("process listener methods differ from the worker baseline");
301
+ }
302
+ },
303
+ });
195
304
 
196
- // (5) Delete globals added during the previous test phase.
197
- const deleted = [];
198
- for (const key of Reflect.ownKeys(globalThis)) {
199
- if (globalBaseline.has(key)) continue;
200
- if (typeof key === "string" && HARNESS_GLOBALS.test(key)) continue;
201
- try {
202
- delete globalThis[key];
203
- if (diagnostics) deleted.push(String(key));
204
- } catch {}
205
- }
206
- if (diagnostics && deleted.length) {
207
- console.log(`[vitest-native] hot reset: deleted test-phase globals: ${deleted.join(", ")}`);
208
- }
209
- }
305
+ manifest.register({
306
+ id: "global.descriptors",
307
+ capture: () => captureDescriptors(globalThis),
308
+ restore: (baseline) => {
309
+ const deleted = [];
310
+ const skip = (key) =>
311
+ globallyPreserved.has(key) ||
312
+ (typeof key === "string" && HARNESS_GLOBALS.test(key)) ||
313
+ (typeof key === "symbol" &&
314
+ !baseline.has(key) &&
315
+ NODE_LAZY_GLOBAL_SYMBOLS.test(key.description ?? ""));
316
+ if (diagnostics) {
317
+ for (const key of Reflect.ownKeys(globalThis)) {
318
+ if (!skip(key) && !baseline.has(key)) deleted.push(String(key));
319
+ }
320
+ }
321
+ restoreDescriptors(globalThis, baseline, skip);
322
+ if (diagnostics && deleted.length) {
323
+ console.log(`[vitest-native] hot reset: deleted test-phase globals: ${deleted.join(", ")}`);
324
+ }
325
+ },
326
+ verify: (baseline) =>
327
+ verifyDescriptors(
328
+ globalThis,
329
+ baseline,
330
+ (key) =>
331
+ globallyPreserved.has(key) ||
332
+ (typeof key === "string" && HARNESS_GLOBALS.test(key)) ||
333
+ (typeof key === "symbol" &&
334
+ !baseline.has(key) &&
335
+ NODE_LAZY_GLOBAL_SYMBOLS.test(key.description ?? "")),
336
+ ),
337
+ });
210
338
 
211
- return { hotReset, bless };
339
+ manifest.register({
340
+ id: "console.descriptors",
341
+ capture: () => captureDescriptors(console),
342
+ restore: (baseline) => restoreDescriptors(console, baseline),
343
+ verify: (baseline) => verifyDescriptors(console, baseline),
344
+ });
345
+
346
+ manifest.register({
347
+ id: "react-native.error-utils",
348
+ capture: () => globalThis.ErrorUtils?.getGlobalHandler?.(),
349
+ restore: (baseline) => {
350
+ if (baseline) globalThis.ErrorUtils?.setGlobalHandler?.(baseline);
351
+ },
352
+ verify: (baseline) => {
353
+ if (baseline && globalThis.ErrorUtils?.getGlobalHandler?.() !== baseline) {
354
+ throw stateFailure("ErrorUtils handler differs from the worker baseline");
355
+ }
356
+ },
357
+ });
358
+
359
+ manifest.register({
360
+ id: "expo.runtime",
361
+ capture: () => captureDescriptors(globalThis.expo ?? {}),
362
+ restore: (baseline) => {
363
+ globalThis.expo?.[Symbol.for("vitest-native.expo.reset")]?.();
364
+ if (globalThis.expo) restoreDescriptors(globalThis.expo, baseline);
365
+ },
366
+ verify: (baseline) => {
367
+ if (globalThis.expo) {
368
+ verifyDescriptors(globalThis.expo, baseline);
369
+ if (globalThis.expo[Symbol.for("vitest-native.expo.reset")]?.verify?.() === false) {
370
+ throw stateFailure("Expo runtime state differs from the worker baseline");
371
+ }
372
+ }
373
+ },
374
+ });
375
+
376
+ return {
377
+ hotReset: () => manifest.beginFile(),
378
+ bless,
379
+ registerState: manifest.register,
380
+ stateEntries: manifest.entries,
381
+ };
212
382
  }
@@ -7,10 +7,13 @@
7
7
  export declare const METRO_SOURCE_EXTS: string[];
8
8
 
9
9
  /**
10
- * Extensions to try for `platform`, in Metro's order: every platform-suffixed
11
- * variant, then every `.native` one, then the bare extensions.
10
+ * Extensions to try for `platform`, in Metro's extension-major order. A
11
+ * project-specific sourceExts list may replace Metro's bare React Native defaults.
12
12
  */
13
- export declare function extensionsFor(platform: "ios" | "android"): string[];
13
+ export declare function extensionsFor(
14
+ platform: "ios" | "android",
15
+ sourceExts?: readonly string[],
16
+ ): string[];
14
17
 
15
18
  /**
16
19
  * First existing platform variant of an extensionless absolute base path, or its
@@ -19,4 +22,18 @@ export declare function extensionsFor(platform: "ios" | "android"): string[];
19
22
  export declare function resolvePlatformFile(
20
23
  absBase: string,
21
24
  platform?: "ios" | "android",
25
+ sourceExts?: readonly string[],
22
26
  ): string | null;
27
+
28
+ export declare function resolveDeepPackageFile(
29
+ request: string,
30
+ fromDir: string,
31
+ platform: "ios" | "android",
32
+ sourceExts?: readonly string[],
33
+ ): string | null;
34
+
35
+ /**
36
+ * Whether `file` exists under exactly this name, which a case-insensitive disk (macOS,
37
+ * Windows) does not answer by itself.
38
+ */
39
+ export declare function existsExact(file: string): boolean;
@@ -31,16 +31,36 @@ export const METRO_SOURCE_EXTS = ["js", "jsx", "json", "ts", "tsx"];
31
31
  * ships. The order is asserted against real metro-resolver by
32
32
  * tests/metro-resolver-oracle.test.ts, not just against these literals.
33
33
  */
34
- export function extensionsFor(platform) {
34
+ export function extensionsFor(platform, sourceExts = METRO_SOURCE_EXTS) {
35
35
  const suffix = platform === "android" ? "android" : "ios";
36
36
  const exts = [];
37
- for (const e of METRO_SOURCE_EXTS) {
37
+ for (const e of sourceExts) {
38
38
  exts.push(`.${suffix}.${e}`, `.native.${e}`, `.${e}`);
39
39
  }
40
40
  return exts;
41
41
  }
42
42
 
43
- // Per-worker resolution cache: `${platform}\0${absBase}` → resolved path | null.
43
+ /**
44
+ * Whether `file` exists under exactly this name.
45
+ *
46
+ * macOS and Windows disks are case-insensitive by default, so `fs.existsSync("App.json")`
47
+ * is true when only `app.json` exists. Resolving `./App` in extension order (Metro's: js,
48
+ * jsx, json, ts, tsx) then picks the React Native template's `app.json` over its `App.tsx`,
49
+ * and the template's own test renders `{ name, displayName }`. Metro resolves from a
50
+ * case-sensitive file map, as does Linux, which is why neither Metro nor CI saw it. The
51
+ * directory listing has the real names. Checked for the file's own name: the case the
52
+ * template hits, and one `readdir` per hit, which the resolution caches absorb.
53
+ */
54
+ export function existsExact(file) {
55
+ if (!fs.existsSync(file)) return false;
56
+ try {
57
+ return fs.readdirSync(path.dirname(file)).includes(path.basename(file));
58
+ } catch {
59
+ return true; // An unreadable directory keeps the filesystem's verdict.
60
+ }
61
+ }
62
+
63
+ // Per-worker cache: platform + ordered sourceExts + absolute base → path | null.
44
64
  // Platform resolution is deterministic for a given on-disk layout, and Node's own
45
65
  // module cache already dedupes most re-resolution; this dedupes the rest (distinct
46
66
  // import edges resolving to the same base), so each base is scanned at most once per
@@ -54,23 +74,23 @@ const resolveCache = new Map();
54
74
  * first existing platform variant (".../Foo.ios.tsx", etc.) or directory index,
55
75
  * or null if none exist.
56
76
  */
57
- export function resolvePlatformFile(absBase, platform = "ios") {
58
- const key = platform + "\0" + absBase;
77
+ export function resolvePlatformFile(absBase, platform = "ios", sourceExts = METRO_SOURCE_EXTS) {
78
+ const key = platform + "\0" + sourceExts.join("\0") + "\0" + absBase;
59
79
  const cached = resolveCache.get(key);
60
80
  if (cached !== undefined) return cached;
61
- const resolved = scanPlatformFile(absBase, platform);
81
+ const resolved = scanPlatformFile(absBase, platform, sourceExts);
62
82
  resolveCache.set(key, resolved);
63
83
  return resolved;
64
84
  }
65
85
 
66
- function scanPlatformFile(absBase, platform) {
67
- const extensions = extensionsFor(platform);
86
+ function scanPlatformFile(absBase, platform, sourceExts) {
87
+ const extensions = extensionsFor(platform, sourceExts);
68
88
  for (const ext of extensions) {
69
- if (fs.existsSync(absBase + ext)) return absBase + ext;
89
+ if (existsExact(absBase + ext)) return absBase + ext;
70
90
  }
71
91
  for (const ext of extensions) {
72
92
  const idx = path.join(absBase, "index" + ext);
73
- if (fs.existsSync(idx)) return idx;
93
+ if (existsExact(idx)) return idx;
74
94
  }
75
95
  return null;
76
96
  }
@@ -91,7 +111,7 @@ function scanPlatformFile(absBase, platform) {
91
111
  * Scoped to react-native and @react-native/* — the packages whose graphs the
92
112
  * preset rewrites. Ordinary packages keep Node's exports enforcement.
93
113
  */
94
- export function resolveDeepPackageFile(request, fromDir, platform) {
114
+ export function resolveDeepPackageFile(request, fromDir, platform, sourceExts = METRO_SOURCE_EXTS) {
95
115
  const m = /^(react-native|@react-native\/[^/]+)\/(.+)$/.exec(request);
96
116
  if (!m) return null;
97
117
  const [, pkg, rest] = m;
@@ -104,7 +124,7 @@ export function resolveDeepPackageFile(request, fromDir, platform) {
104
124
  // `Foo.js` may exist only as a platform variant, and extensionless specifiers
105
125
  // need the full Metro candidate list either way.
106
126
  const stem = /\.[a-z0-9]+$/i.test(base) ? base.replace(/\.js$/, "") : base;
107
- return resolvePlatformFile(stem, platform);
127
+ return resolvePlatformFile(stem, platform, sourceExts);
108
128
  }
109
129
 
110
130
  function findPackageDir(startDir, pkg) {