vitest-native 0.7.0 → 0.9.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +373 -0
  2. package/README.md +32 -14
  3. package/dist/cli.cjs +506 -0
  4. package/dist/cli.d.cts +4 -0
  5. package/dist/cli.d.mts +4 -0
  6. package/dist/cli.mjs +502 -0
  7. package/dist/ecosystem-BIWaVwYL.cjs +294 -0
  8. package/dist/ecosystem-EFtHnKS9.mjs +256 -0
  9. package/dist/{index-DbfKy_bm.d.mts → index-CEgRDdhd.d.cts} +22 -3
  10. package/dist/{index-BgzErxHj.d.cts → index-j-0tueBr.d.mts} +20 -5
  11. package/dist/index.cjs +345 -200
  12. package/dist/index.d.cts +1 -1
  13. package/dist/index.d.mts +1 -1
  14. package/dist/index.mjs +341 -196
  15. package/dist/jest-compat/setup.mjs +65 -1
  16. package/dist/native/boundary.mjs +108 -30
  17. package/dist/native/compile-cache.mjs +45 -0
  18. package/dist/native/explain.mjs +69 -0
  19. package/dist/native/hooks.mjs +77 -4
  20. package/dist/native/loader.mjs +36 -7
  21. package/dist/native/match.mjs +107 -8
  22. package/dist/native/registry.mjs +471 -0
  23. package/dist/native/reset.mjs +18 -12
  24. package/dist/native/runner.mjs +13 -7
  25. package/dist/native/setup.mjs +44 -0
  26. package/dist/native/transform.mjs +88 -19
  27. package/dist/native/worker.mjs +13 -0
  28. package/dist/pool-CJmjRgsB.mjs +117 -0
  29. package/dist/pool-DzsEo9vv.cjs +121 -0
  30. package/dist/{preset-map-CNBOeqAu.cjs → preset-map-CG4FMtsl.cjs} +5 -1
  31. package/dist/{preset-map-C1UwEald.mjs → preset-map-CNsZKfvu.mjs} +5 -1
  32. package/dist/{presets-BTG8fiNF.cjs → presets-C4faM3ds.cjs} +838 -2
  33. package/dist/{presets-BFuAMwYQ.mjs → presets-CuDrNA_W.mjs} +761 -3
  34. package/dist/presets.cjs +5 -1
  35. package/dist/presets.d.cts +2 -2
  36. package/dist/presets.d.mts +2 -2
  37. package/dist/presets.mjs +2 -2
  38. package/dist/setup.cjs +327 -347
  39. package/dist/setup.mjs +318 -338
  40. package/docs/hot-default-design.md +129 -0
  41. package/docs/migrating-from-jest.md +43 -7
  42. package/docs/migrating-from-vitest-react-native.md +1 -1
  43. package/docs/release-readiness.md +2 -1
  44. package/package.json +23 -7
  45. package/dist/pool-B7LBfcMQ.mjs +0 -67
  46. package/dist/pool-p54QV1dQ.cjs +0 -69
@@ -21,7 +21,30 @@ import { jestMockInterop } from "./interop.mjs";
21
21
  const projectRoot = process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd();
22
22
  const require = createRequire(path.join(projectRoot, "package.json"));
23
23
 
24
- if (typeof vi.requireActual !== "function") vi.requireActual = (m) => require(m);
24
+ // Real Jest suites commonly clone-and-override React Native:
25
+ // const RN = jest.requireActual('react-native'); RN.Platform = {...}; return RN
26
+ // Under the native engine RN's index is a CJS facade of lazy getters with no
27
+ // setters (see loader.mjs), so assigning to it throws "Cannot set property … which
28
+ // has only a getter" and takes the whole test file down at load. Jest's module is
29
+ // mutable, so match that: wrap the RN facade in a write-through proxy — reads fall
30
+ // through (keeping the getters lazy), writes are captured in an overlay so the
31
+ // override wins on later reads. Only `react-native` needs this; its submodules and
32
+ // other packages are ordinary mutable CJS.
33
+ function writableModuleFacade(mod) {
34
+ if (mod == null || typeof mod !== "object") return mod;
35
+ const overrides = new Map();
36
+ return new Proxy(mod, {
37
+ get: (target, prop) => (overrides.has(prop) ? overrides.get(prop) : Reflect.get(target, prop)),
38
+ set: (_target, prop, value) => {
39
+ overrides.set(prop, value);
40
+ return true;
41
+ },
42
+ has: (target, prop) => overrides.has(prop) || Reflect.has(target, prop),
43
+ });
44
+ }
45
+
46
+ if (typeof vi.requireActual !== "function")
47
+ vi.requireActual = (m) => (m === "react-native" ? writableModuleFacade(require(m)) : require(m));
25
48
  if (typeof vi.requireMock !== "function") vi.requireMock = (m) => require(m);
26
49
  // `jest.setTimeout(ms)` has no global `vi` equivalent — no-op so suites that call
27
50
  // it at top level don't crash.
@@ -42,6 +65,47 @@ vi.advanceTimersByTime = (...args) =>
42
65
  vi.advanceTimersByTimeAsync = async (...args) =>
43
66
  vi.isFakeTimers() ? advanceTimersByTimeAsync(...args) : undefined;
44
67
 
68
+ // Jest APIs with NO Vitest equivalent would otherwise surface as bare
69
+ // "jest.isolateModules is not a function" TypeErrors deep in a migrated suite.
70
+ // Give each one an error that names the API and states the closest migration,
71
+ // so the failure is a signpost instead of a mystery.
72
+ const MIGRATION_GUIDE =
73
+ "https://github.com/danfry1/vitest-native/blob/main/packages/vitest-native/docs/migrating-from-jest.md";
74
+ function unsupported(name, guidance) {
75
+ if (typeof vi[name] === "function") return;
76
+ vi[name] = () => {
77
+ throw new Error(
78
+ `[vitest-native] jest.${name}() has no Vitest equivalent. ${guidance} See ${MIGRATION_GUIDE}`,
79
+ );
80
+ };
81
+ }
82
+ unsupported(
83
+ "isolateModules",
84
+ "Use vi.resetModules() plus a dynamic import() to get a fresh module copy.",
85
+ );
86
+ unsupported(
87
+ "createMockFromModule",
88
+ "Build the mock explicitly with vi.fn()/vi.mock(), or import the real module and override members.",
89
+ );
90
+ unsupported(
91
+ "genMockFromModule",
92
+ "Build the mock explicitly with vi.fn()/vi.mock(), or import the real module and override members.",
93
+ );
94
+ unsupported("deepUnmock", "Use vi.unmock()/vi.doUnmock() per module.");
95
+ // jest.retryTimes configures retries at runtime; Vitest configures them statically.
96
+ // Warn once and continue — crashing a suite over retry policy helps nobody.
97
+ if (typeof vi.retryTimes !== "function") {
98
+ let warned = false;
99
+ vi.retryTimes = () => {
100
+ if (!warned) {
101
+ warned = true;
102
+ console.warn(
103
+ `[vitest-native] jest.retryTimes() is ignored under Vitest — set test.retry in your vitest config (or per-test: test('name', { retry: N }, fn)).`,
104
+ );
105
+ }
106
+ };
107
+ }
108
+
45
109
  globalThis.jest = vi;
46
110
 
47
111
  // jest.mock factories are wrapped by jestMockTransform to route their return
@@ -47,6 +47,23 @@ function deviceConstants(platform, reactNativeVersion) {
47
47
  doLeftAndRightSwapInRTL: true,
48
48
  localeIdentifier: "en_US",
49
49
  },
50
+ // RN's getDevServer (Libraries/Core/Devtools/getDevServer.js) reads
51
+ // SourceCode.getConstants().scriptURL and calls .match() on it — undefined
52
+ // there throws and takes the whole file down. Expo's async-require
53
+ // (messageSocket) pulls this in on any Expo-core-importing test. Provide a
54
+ // defined string so the lookup resolves instead of crashing.
55
+ //
56
+ // Deliberately a file:// (bundled/release) URL, NOT http(s): getDevServer only
57
+ // treats http(s) scriptURLs as a live server, so a file:// value keeps
58
+ // `bundleLoadedFromServer` false — tests run as if loaded from a bundle, not a
59
+ // Metro dev server. That stops RN internals (AssetSourceResolver,
60
+ // symbolicateStackTrace, DevTools) and third-party SDKs from believing they're
61
+ // connected to a packager and attempting real network I/O against localhost:8081.
62
+ // Mirrors RN's own jest mock, which keeps this flag off (scriptURL: null there,
63
+ // but null would re-introduce the .match crash, so we use a bundled URL).
64
+ SourceCode: {
65
+ scriptURL: "file:///index.bundle",
66
+ },
50
67
  };
51
68
  }
52
69
 
@@ -126,36 +143,73 @@ function turboStubSource(platform, version) {
126
143
  // (e.g. showShareActionSheetWithOptions(options, error, success)). For the latter,
127
144
  // the success callback is the LAST function arg.
128
145
  const __SUCCESS_LAST = new Set(["showShareActionSheetWithOptions"]);
129
- const turboStub = (name) => new Proxy({}, {
130
- get: (_t, p) => {
131
- if (p === "getConstants") return () => (__C[name] || {});
132
- if (p === "getColorScheme") {
133
- return () => getBoundaryState(name).colorScheme ?? "light";
134
- }
135
- if (p === "setColorScheme") {
136
- return (colorScheme) => {
137
- getBoundaryState(name).colorScheme =
138
- colorScheme === "unspecified" || colorScheme == null ? "light" : colorScheme;
139
- };
140
- }
141
- if (p === "addListener") return () => ({ remove: () => {} });
142
- if (p === "removeListeners") return () => {};
143
- return (...args) => {
144
- // Callback-style native methods resolve via a callback argument. Invoke the
145
- // success callback so JS Promises that wrap these settle instead of hanging.
146
- const fns = args.filter((a) => typeof a === "function");
147
- if (fns.length) {
148
- const cb = typeof p === "string" && __SUCCESS_LAST.has(p) ? fns[fns.length - 1] : fns[0];
149
- return cb(false);
150
- }
151
- // Promise-returning native methods must yield a Promise, not undefined.
152
- if (typeof p === "string" && Object.prototype.hasOwnProperty.call(__ASYNC, p)) {
153
- return Promise.resolve(__ASYNC[p]);
146
+ // Stubs are memoized per module name in the shared boundary state, so
147
+ // NativeModules.Foo === NativeModules.Foo === TurboModuleRegistry.get('Foo')
148
+ // (matching bridgeless RN, where NativeModules proxies TurboModuleRegistry).
149
+ // Methods are memoized as own properties of the proxy target on first read —
150
+ // identity-stable across reads, and explicit writes win, so
151
+ // vi.spyOn(NativeModules.Foo, 'method') records calls instead of silently
152
+ // landing on a throwaway object.
153
+ const turboStub = (name) => {
154
+ const state = getBoundaryState(name);
155
+ if (state.__stub) return state.__stub;
156
+ const target = {};
157
+ state.__stub = new Proxy(target, {
158
+ get: (t, p) => {
159
+ // Explicitly-set properties win (spies, manual overrides, memoized methods).
160
+ if (Object.prototype.hasOwnProperty.call(t, p)) return t[p];
161
+ let v;
162
+ if (p === "getConstants") v = () => (__C[name] || {});
163
+ else if (p === "getColorScheme") {
164
+ v = () => getBoundaryState(name).colorScheme ?? "light";
165
+ } else if (p === "setColorScheme") {
166
+ v = (colorScheme) => {
167
+ getBoundaryState(name).colorScheme =
168
+ colorScheme === "unspecified" || colorScheme == null ? "light" : colorScheme;
169
+ };
170
+ } else if (p === "addListener") v = () => ({ remove: () => {} });
171
+ else if (p === "removeListeners") v = () => {};
172
+ else {
173
+ v = (...args) => {
174
+ // Callback-style native methods resolve via a callback argument. Invoke the
175
+ // success callback so JS Promises that wrap these settle instead of hanging.
176
+ const fns = args.filter((a) => typeof a === "function");
177
+ if (fns.length) {
178
+ const cb = typeof p === "string" && __SUCCESS_LAST.has(p) ? fns[fns.length - 1] : fns[0];
179
+ return cb(false);
180
+ }
181
+ // Promise-returning native methods must yield a Promise, not undefined.
182
+ if (typeof p === "string" && Object.prototype.hasOwnProperty.call(__ASYNC, p)) {
183
+ return Promise.resolve(__ASYNC[p]);
184
+ }
185
+ return undefined;
186
+ };
154
187
  }
155
- return undefined;
156
- };
157
- },
158
- });
188
+ // defineProperty, not assignment: sloppy-mode \`t["__proto__"] = fn\`
189
+ // would invoke the inherited __proto__ SETTER and silently swap the
190
+ // target's prototype instead of memoizing.
191
+ Object.defineProperty(t, p, {
192
+ value: v,
193
+ writable: true,
194
+ enumerable: true,
195
+ configurable: true,
196
+ });
197
+ return v;
198
+ },
199
+ // Every property reads as a callable stub, so report them all as present —
200
+ // vi.spyOn refuses to spy on a property its \`in\` check can't see.
201
+ has: () => true,
202
+ });
203
+ // Hot runtime: clear per-file state (spies, memoized methods) between files
204
+ // via the surgical-reset registry, while keeping the stub's identity for
205
+ // resident libraries that captured a reference at import time. Under the
206
+ // default engine each file gets a fresh process, so this never fires.
207
+ const resets = globalThis.__vitest_native_resets || (globalThis.__vitest_native_resets = []);
208
+ resets.push(() => {
209
+ for (const k of Reflect.ownKeys(target)) delete target[k];
210
+ });
211
+ return state.__stub;
212
+ };
159
213
  `;
160
214
  }
161
215
 
@@ -258,9 +312,30 @@ export const BOUNDARY_SOURCES = {
258
312
 
259
313
  const SUFFIXES = Object.keys(BOUNDARY_SOURCES);
260
314
 
315
+ /**
316
+ * Expo modules whose only job is talking to a live dev server — an environment
317
+ * that doesn't exist under Node. `expo`'s Expo.fx requires messageSocket whenever
318
+ * `__DEV__ && globalThis.expo`, and the module throws at load time when the
319
+ * bundle wasn't served over HTTP ("Cannot create devtools websocket connections
320
+ * in embedded environments"), taking down any suite that imports an expo-*
321
+ * package. Stub it to a no-op, like Jest's dev-server layer mocks do. Matched
322
+ * for both the published build/ output and the src/ TS sources (some resolution
323
+ * paths reach src/), in plain and .native platform variants.
324
+ */
325
+ const EXPO_DEV_STUBS = {
326
+ "src/async-require/messageSocket.native.ts": "module.exports = {};",
327
+ "src/async-require/messageSocket.ts": "module.exports = {};",
328
+ "build/async-require/messageSocket.native.js": "module.exports = {};",
329
+ "build/async-require/messageSocket.js": "module.exports = {};",
330
+ };
331
+ const EXPO_SUFFIXES = Object.keys(EXPO_DEV_STUBS);
332
+
261
333
  /** Normalised-path test: is this a native-boundary module? */
262
334
  export function isBoundary(normPath) {
263
- return SUFFIXES.some((s) => normPath.endsWith("/react-native/" + s));
335
+ return (
336
+ SUFFIXES.some((s) => normPath.endsWith("/react-native/" + s)) ||
337
+ EXPO_SUFFIXES.some((s) => normPath.endsWith("/expo/" + s))
338
+ );
264
339
  }
265
340
 
266
341
  /** Returns the CJS source for a boundary module, or null if not a boundary. */
@@ -271,5 +346,8 @@ export function boundarySourceFor(normPath, platform = "ios", version = "0.0.0")
271
346
  return typeof source === "function" ? source(platform, version) : source;
272
347
  }
273
348
  }
349
+ for (const s of EXPO_SUFFIXES) {
350
+ if (normPath.endsWith("/expo/" + s)) return EXPO_DEV_STUBS[s];
351
+ }
274
352
  return null;
275
353
  }
@@ -0,0 +1,45 @@
1
+ // V8 compile-cache for the externalized React Native graph.
2
+ //
3
+ // RN is loaded through Node (externalized), and our require/loader hooks compile
4
+ // each RN module's Flow-stripped source with `mod._compile` / a synthetic module
5
+ // source. The transform disk cache (transform.mjs) means Babel runs once per RN
6
+ // version — but V8 still re-parses and re-compiles that source to bytecode on
7
+ // every fresh module graph. Under `engine:'native'` (isolate:true) RN's ~240-file
8
+ // graph is re-instantiated per test FILE, so that V8 compile is paid over and
9
+ // over. Node's on-disk compile cache (Node 22.8+) keys bytecode by source content
10
+ // + Node version and is shared process-wide, so the second compile of any RN
11
+ // module — the next file, the next worker, the next run — loads bytecode instead
12
+ // of recompiling. Verified to apply to `mod._compile`, which is how the hooks load
13
+ // RN. No-op on Node < 22.8 (the API is absent) and harmless when caching is off.
14
+ import nodeModule from "node:module";
15
+ import os from "node:os";
16
+ import path from "node:path";
17
+ import { cacheRootFor } from "./transform.mjs";
18
+
19
+ let _enabled = false;
20
+
21
+ /**
22
+ * Enable Node's persistent V8 compile cache for this worker/thread. Idempotent and
23
+ * guarded per realm. Colocated with the transform disk cache (the project's
24
+ * node_modules/.cache/vitest-native when available — persistent and CI-restorable —
25
+ * else tmpdir) so both caches share a lifecycle. Must be called before RN's modules
26
+ * are first compiled.
27
+ */
28
+ export function enableV8CompileCache(projectRoot) {
29
+ if (_enabled) return;
30
+ _enabled = true;
31
+ const enable = nodeModule.enableCompileCache;
32
+ if (typeof enable !== "function") return; // Node < 22.8: feature absent
33
+ try {
34
+ const root = projectRoot
35
+ ? cacheRootFor(projectRoot)
36
+ : path.join(os.tmpdir(), "vitest-native-cache");
37
+ enable.call(nodeModule, path.join(root, "v8"));
38
+ // No atomic-write handling needed (unlike the transform cache, which writes
39
+ // executable source): Node CRC32-validates each compile-cache entry on read,
40
+ // so a torn or raced write from concurrent workers is a cache miss and a
41
+ // recompile, never a corruption-induced failure.
42
+ } catch {
43
+ // Read-only tmp, unsupported platform, etc. — caching is a pure optimization.
44
+ }
45
+ }
@@ -0,0 +1,69 @@
1
+ // Turns the native engine's two worst failure moments — a Babel crash while
2
+ // transforming a file, and Node choking on untranspiled JSX/Flow from an
3
+ // externalized package — into errors that name the package and say what to do.
4
+ // Pure functions; used by transform.mjs and hooks.mjs, unit-tested directly.
5
+
6
+ /** The npm package name owning `file`, from its deepest node_modules segment, or null. */
7
+ export function packageNameFromPath(file) {
8
+ const norm = String(file).replace(/\\/g, "/");
9
+ const idx = norm.lastIndexOf("/node_modules/");
10
+ if (idx === -1) return null;
11
+ const rest = norm.slice(idx + "/node_modules/".length);
12
+ const segs = rest.split("/");
13
+ if (!segs[0]) return null;
14
+ if (segs[0].startsWith("@")) return segs[1] ? `${segs[0]}/${segs[1]}` : segs[0];
15
+ return segs[0];
16
+ }
17
+
18
+ /**
19
+ * Decorate a Babel failure from transformRN with the file, platform, and owning
20
+ * package, preserving the original message (Babel's includes a code frame) and
21
+ * chaining the original error as `cause`.
22
+ */
23
+ export function decorateTransformError(err, file, platform) {
24
+ const pkg = packageNameFromPath(file);
25
+ const subject = pkg ? `'${pkg}' (${file})` : `${file}`;
26
+ const hint = pkg
27
+ ? `The React Native Babel preset could not parse this file from ${pkg}. ` +
28
+ `If this happens on a package you added to transform: [...], the package may ` +
29
+ `ship syntax the preset can't handle — please report it at ` +
30
+ `https://github.com/danfry1/vitest-native/issues with the error below.`
31
+ : `The React Native Babel preset could not parse this file.`;
32
+ const wrapped = new Error(
33
+ `[vitest-native] Failed to transform ${subject} for platform '${platform}'.\n` +
34
+ `${hint}\n\n${err && err.message ? err.message : String(err)}`,
35
+ { cause: err },
36
+ );
37
+ wrapped.name = err && err.name ? err.name : "Error";
38
+ return wrapped;
39
+ }
40
+
41
+ // Node's SyntaxError messages when it compiles untranspiled JSX / Flow / TS.
42
+ // "Unexpected token '<'" = JSX; "Unexpected identifier" / "Unexpected reserved
43
+ // word" commonly = type annotations or `import type`.
44
+ const UNTRANSPILED_SYNTAX =
45
+ /Unexpected token '?<'?|Unexpected identifier|Unexpected reserved word|Missing initializer in const|Unexpected token ':'/;
46
+
47
+ /**
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: [...]`.
51
+ * Returns a decorated error, or null when the failure doesn't match the pattern.
52
+ */
53
+ export function explainUntransformedSyntaxError(err, file) {
54
+ if (!err || err.name !== "SyntaxError") return null;
55
+ if (!UNTRANSPILED_SYNTAX.test(String(err.message))) return null;
56
+ const pkg = packageNameFromPath(file);
57
+ if (!pkg) return null;
58
+ const wrapped = new SyntaxError(
59
+ `[vitest-native] '${pkg}' shipped source Node can't run directly ` +
60
+ `(${err.message} in ${file}).\n` +
61
+ `This usually means the package publishes untranspiled JSX, Flow, or TypeScript. ` +
62
+ `Ask vitest-native to transform it:\n\n` +
63
+ ` reactNative({ transform: ['${pkg}'] })\n\n` +
64
+ `in your vitest config. See https://github.com/danfry1/vitest-native` +
65
+ `/blob/main/packages/vitest-native/docs/migrating-from-jest.md`,
66
+ { cause: err },
67
+ );
68
+ return wrapped;
69
+ }
@@ -6,9 +6,10 @@ import fs from "node:fs";
6
6
  import { transformRN, isFlow } from "./transform.mjs";
7
7
  import { boundarySourceFor } from "./boundary.mjs";
8
8
  import { resolvePlatformFile } from "./resolve.mjs";
9
- import { buildPkgMatcher } from "./match.mjs";
9
+ import { buildPkgMatcher, packageNameOf, subpathLeafOf, isUtilitySubpath } from "./match.mjs";
10
+ import { explainUntransformedSyntaxError } from "./explain.mjs";
10
11
 
11
- const RN_PATH = /[\\/](react-native|@react-native)[\\/]/;
12
+ const RN_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
12
13
  // Any file under a node_modules directory. Platform-extension resolution
13
14
  // (`.native.js` etc.) applies to every node_modules package, not just RN — matching
14
15
  // Metro, which resolves platform variants project-wide. See loader.mjs for the
@@ -38,6 +39,7 @@ export function installRequireHooks(
38
39
  // @react-native-vector-icons are shadowed by their preset, so they never inspect
39
40
  // the stubbed font require.)
40
41
  const NON_ASSET = new Set([".js", ".cjs", ".mjs", ".ts", ".tsx", ".json", ".node"]);
42
+ const assetExtSet = new Set(assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
41
43
  for (const raw of assetExts) {
42
44
  const ext = "." + String(raw).replace(/^\./, "");
43
45
  if (NON_ASSET.has(ext) || Module._extensions[ext]) continue;
@@ -48,7 +50,7 @@ export function installRequireHooks(
48
50
  }
49
51
 
50
52
  // Configured third-party packages to also transform (Flow/TS/JSX stripped).
51
- const isExtra = buildPkgMatcher(transformPkgs);
53
+ const isExtra = buildPkgMatcher(transformPkgs, projectRoot);
52
54
 
53
55
  // Preset redirect (CJS): when an externalized third-party module require()s a
54
56
  // preset package by its bare name (e.g. @gorhom/bottom-sheet → require(
@@ -59,10 +61,62 @@ export function installRequireHooks(
59
61
  // the real package's native runtime. The lookup is dynamic (no preset-name list
60
62
  // captured at install time) so the hooks can install at hot-worker boot, before
61
63
  // the setup file has built the preset mocks.
64
+ // Subpath requires of a preset package (pkg/Swipeable) get the mock export
65
+ // matching the leaf name, wrapped in Babel-CJS interop shape ({ __esModule,
66
+ // default }) like the real compiled deep entry — served via a live Proxy so
67
+ // direct-property consumers (`require('pkg/Sub').X`) work too. Memoized per
68
+ // request for identity stability. The memo is keyed by the PER-PACKAGE mock
69
+ // object, not the __vitest_native_preset_mocks container: the hot runtime
70
+ // rebuilds each package's mock per test file while reusing the container, so
71
+ // keying by the container would serve file 1's mocks to every later file in
72
+ // the worker.
73
+ const subpathMemo = new WeakMap();
74
+ function presetSubpathExports(mocks, pkg, request) {
75
+ const mock = mocks[pkg];
76
+ if (mock === null || (typeof mock !== "object" && typeof mock !== "function")) return mock;
77
+ let memo = subpathMemo.get(mock);
78
+ if (!memo) subpathMemo.set(mock, (memo = new Map()));
79
+ if (memo.has(request)) return memo.get(request);
80
+ const leaf = subpathLeafOf(request);
81
+ let exportsValue = mock;
82
+ if (leaf && Object.prototype.hasOwnProperty.call(mock, leaf)) {
83
+ const value = mock[leaf];
84
+ exportsValue =
85
+ value !== null && (typeof value === "object" || typeof value === "function")
86
+ ? new Proxy(value, {
87
+ get: (t, p, r) =>
88
+ p === "default" ? t : p === "__esModule" ? true : Reflect.get(t, p, r),
89
+ has: (t, p) => p === "default" || p === "__esModule" || Reflect.has(t, p),
90
+ })
91
+ : { __esModule: true, default: value };
92
+ } else if (process.env.VITEST_NATIVE_DIAGNOSTICS === "true") {
93
+ console.warn(
94
+ `[vitest-native] '${request}' has no matching export on the '${pkg}' preset mock; serving the root mock namespace.`,
95
+ );
96
+ }
97
+ memo.set(request, exportsValue);
98
+ return exportsValue;
99
+ }
100
+
62
101
  const origLoad = Module._load;
63
102
  Module._load = function (request, parent, ...rest) {
64
103
  const mocks = globalThis.__vitest_native_preset_mocks;
65
- if (mocks && Object.prototype.hasOwnProperty.call(mocks, request)) return mocks[request];
104
+ if (mocks) {
105
+ if (Object.prototype.hasOwnProperty.call(mocks, request)) return mocks[request];
106
+ // Subpath require of a preset package — the real deep entry would load the
107
+ // package's native runtime. Exempt: JSON subpaths (package.json version
108
+ // gates), asset subpaths (fonts/images, stubbed from their real files by
109
+ // the Module._extensions handlers above), and Node-safe utility entries
110
+ // (jest-utils, mock, plugin) — those fall through to the real file.
111
+ const reqExtMatch = /\.([a-z0-9]+)$/i.exec(request);
112
+ const reqExt = reqExtMatch ? reqExtMatch[1].toLowerCase() : "";
113
+ if (reqExt !== "json" && !assetExtSet.has(reqExt) && !isUtilitySubpath(request)) {
114
+ const pkg = packageNameOf(request);
115
+ if (pkg !== request && Object.prototype.hasOwnProperty.call(mocks, pkg)) {
116
+ return presetSubpathExports(mocks, pkg, request);
117
+ }
118
+ }
119
+ }
66
120
  return origLoad.call(this, request, parent, ...rest);
67
121
  };
68
122
 
@@ -101,6 +155,17 @@ export function installRequireHooks(
101
155
  const src = fs.readFileSync(filename, "utf8");
102
156
  return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
103
157
  }
158
+ if (NODE_MODULES.test(norm)) {
159
+ // A node_modules package we did NOT transform: when Node's compile throws a
160
+ // SyntaxError that fingerprints as untranspiled JSX/Flow/TS, explain the
161
+ // real fix (add the package to `transform: [...]`) instead of leaving a
162
+ // bare "Unexpected token '<'" — the single most common migration blocker.
163
+ try {
164
+ return origJs(mod, filename);
165
+ } catch (err) {
166
+ throw explainUntransformedSyntaxError(err, filename) ?? err;
167
+ }
168
+ }
104
169
  return origJs(mod, filename);
105
170
  };
106
171
 
@@ -113,6 +178,14 @@ export function installRequireHooks(
113
178
  for (const ext of [".ts", ".tsx"]) {
114
179
  if (Module._extensions[ext]) continue;
115
180
  Module._extensions[ext] = function (mod, filename) {
181
+ // Boundary stubs can live in TS sources too (expo publishes src/ alongside
182
+ // build/, and some resolution paths reach the .ts files directly).
183
+ const boundary = boundarySourceFor(
184
+ filename.replace(/\\/g, "/"),
185
+ platform,
186
+ reactNativeVersion,
187
+ );
188
+ if (boundary != null) return mod._compile(boundary, filename);
116
189
  const src = fs.readFileSync(filename, "utf8");
117
190
  return mod._compile(transformRN(filename, src, projectRoot, platform), filename);
118
191
  };
@@ -6,9 +6,9 @@ import fs from "node:fs";
6
6
  import { transformRN, isFlow } from "./transform.mjs";
7
7
  import { boundarySourceFor } from "./boundary.mjs";
8
8
  import { resolvePlatformFile } from "./resolve.mjs";
9
- import { buildPkgMatcher } from "./match.mjs";
9
+ import { buildPkgMatcher, packageNameOf, subpathLeafOf, isUtilitySubpath } from "./match.mjs";
10
10
 
11
- const RN_PATH = /[\\/](react-native|@react-native)[\\/]/;
11
+ const RN_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
12
12
  // Any file living under a node_modules directory. Platform-extension resolution
13
13
  // (`.native.js` etc.) applies to every node_modules package, not just RN, matching
14
14
  // Metro — which resolves platform variants project-wide. (Without this, e.g.
@@ -54,7 +54,7 @@ export async function initialize(data) {
54
54
  if (data && data.projectRoot) PROJECT_ROOT = data.projectRoot;
55
55
  if (data && data.platform === "android") PLATFORM = "android";
56
56
  if (data && data.reactNativeVersion) REACT_NATIVE_VERSION = data.reactNativeVersion;
57
- if (data && data.transformPkgs) isExtra = buildPkgMatcher(data.transformPkgs);
57
+ if (data && data.transformPkgs) isExtra = buildPkgMatcher(data.transformPkgs, PROJECT_ROOT);
58
58
  if (data && data.presetExports) presetExports = data.presetExports;
59
59
  if (data && data.assetExts)
60
60
  assetExtSet = new Set(data.assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
@@ -65,9 +65,23 @@ export async function resolve(specifier, context, nextResolve) {
65
65
  // test graph or, crucially, nested inside an externalized third-party lib — is
66
66
  // redirected to a synthetic module that re-exports the runtime preset mock. This
67
67
  // mirrors the Vite plugin's virtual:preset modules for the Node ESM path.
68
+ // Subpath imports (e.g. react-native-gesture-handler/Swipeable) are redirected
69
+ // too — the real deep entry would pull in the package's native runtime.
70
+ // Exempt: JSON subpaths (package.json version gates), asset subpaths, and
71
+ // Node-safe utility entries (jest-utils, mock, plugin) — those pass through
72
+ // to the real file.
68
73
  if (Object.prototype.hasOwnProperty.call(presetExports, specifier)) {
69
74
  return { url: PRESET_SCHEME + specifier, shortCircuit: true };
70
75
  }
76
+ if (!specifier.endsWith(".json") && !isUtilitySubpath(specifier)) {
77
+ const specExt = /\.([a-z0-9]+)$/i.exec(specifier);
78
+ if (!specExt || !assetExtSet.has(specExt[1].toLowerCase())) {
79
+ const pkg = packageNameOf(specifier);
80
+ if (pkg !== specifier && Object.prototype.hasOwnProperty.call(presetExports, pkg)) {
81
+ return { url: PRESET_SCHEME + specifier, shortCircuit: true };
82
+ }
83
+ }
84
+ }
71
85
 
72
86
  const parent =
73
87
  context.parentURL && context.parentURL.startsWith("file:")
@@ -120,14 +134,29 @@ export async function load(url, context, nextLoad) {
120
134
  // by the native setup file from globalThis (this source executes in the main
121
135
  // realm, so globalThis is the populated one), mirroring the Vite virtual:preset.
122
136
  if (url.startsWith(PRESET_SCHEME)) {
123
- const pkg = url.slice(PRESET_SCHEME.length);
137
+ const specifier = url.slice(PRESET_SCHEME.length);
138
+ const pkg = packageNameOf(specifier);
124
139
  const names = presetExports[pkg] || [];
140
+ // For a subpath import, prefer the mock export matching the leaf module name
141
+ // (pkg/lib/Swipeable → mock.Swipeable) — real deep entries export that one
142
+ // thing as their default. Root imports (and unknown leaves) keep the
143
+ // factory-default-then-namespace behavior; unknown leaves warn under
144
+ // diagnostics since the namespace default is usually not what the importer
145
+ // wanted.
146
+ const leaf = specifier === pkg ? null : subpathLeafOf(specifier);
147
+ const fallback = `("default" in _m ? _m["default"] : _m)`;
125
148
  const source = [
126
149
  `const _m = (globalThis.__vitest_native_preset_mocks || {})[${JSON.stringify(pkg)}] || {};`,
127
150
  ...names.map((n) => `export const ${n} = _m[${JSON.stringify(n)}];`),
128
- // Honor a factory-provided default (e.g. svg's default Svg component);
129
- // only fall back to the namespace object when the mock has none.
130
- `export default ("default" in _m ? _m["default"] : _m);`,
151
+ ...(leaf
152
+ ? [
153
+ `const _hit = ${JSON.stringify(leaf)} in _m;`,
154
+ `if (!_hit && process.env.VITEST_NATIVE_DIAGNOSTICS === "true") console.warn(${JSON.stringify(
155
+ `[vitest-native] '${specifier}' has no matching export on the '${pkg}' preset mock; serving the root mock namespace.`,
156
+ )});`,
157
+ `export default (_hit ? _m[${JSON.stringify(leaf)}] : ${fallback});`,
158
+ ]
159
+ : [`export default ${fallback};`]),
131
160
  ].join("\n");
132
161
  return { format: "module", source, shortCircuit: true };
133
162
  }