vitest-native 0.8.0 → 0.10.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 (65) hide show
  1. package/CHANGELOG.md +1063 -0
  2. package/README.md +47 -2
  3. package/dist/cli.cjs +642 -0
  4. package/dist/cli.d.cts +4 -0
  5. package/dist/cli.d.mts +4 -0
  6. package/dist/cli.mjs +638 -0
  7. package/dist/ecosystem-CO5vqExO.mjs +318 -0
  8. package/dist/ecosystem-IuZ-Gv0R.cjs +356 -0
  9. package/dist/errors-Dm5yLNTF.mjs +64 -0
  10. package/dist/errors-flXDIeWk.cjs +75 -0
  11. package/dist/errors.d.mts +46 -0
  12. package/dist/errors.mjs +78 -0
  13. package/dist/helpers.cjs +6 -23
  14. package/dist/helpers.d.cts +0 -6
  15. package/dist/helpers.d.mts +0 -6
  16. package/dist/helpers.mjs +6 -23
  17. package/dist/{index-vlK4zxuK.d.mts → index-BJL4cQ-l.d.cts} +22 -7
  18. package/dist/{index-YjjYELG7.d.cts → index-CvCU0cLl.d.mts} +20 -9
  19. package/dist/index.d.mts +8 -6
  20. package/dist/index.mjs +563 -232
  21. package/dist/jest-compat/interop.mjs +15 -0
  22. package/dist/jest-compat/setup.mjs +164 -5
  23. package/dist/matchers.cjs +16 -7
  24. package/dist/matchers.mjs +16 -7
  25. package/dist/native/boundary.mjs +108 -30
  26. package/dist/native/compile-cache.mjs +10 -5
  27. package/dist/native/explain.mjs +69 -0
  28. package/dist/native/hooks.mjs +151 -4
  29. package/dist/native/loader.mjs +61 -12
  30. package/dist/native/match.mjs +107 -8
  31. package/dist/native/module-reset.mjs +63 -0
  32. package/dist/native/registry.mjs +540 -0
  33. package/dist/native/reset.mjs +18 -12
  34. package/dist/native/resolve.d.mts +22 -0
  35. package/dist/native/resolve.mjs +21 -13
  36. package/dist/native/runner.mjs +34 -7
  37. package/dist/native/setup.mjs +19 -3
  38. package/dist/native/transform.mjs +195 -21
  39. package/dist/native/worker.mjs +69 -17
  40. package/dist/pool-Bcxp4Qrg.mjs +118 -0
  41. package/dist/pool-CFND7plG.cjs +122 -0
  42. package/dist/{preset-map-DCWaM08s.mjs → preset-map-BpDG_D5m.mjs} +1 -1
  43. package/dist/{preset-map-BY9zk9Pj.cjs → preset-map-DxilQ4pI.cjs} +1 -1
  44. package/dist/{presets-7eMfp7o2.cjs → presets-BGTqVH6C.cjs} +227 -52
  45. package/dist/{presets-23FJ76O4.mjs → presets-CK85x8ey.mjs} +222 -53
  46. package/dist/presets.d.mts +2 -2
  47. package/dist/presets.mjs +2 -2
  48. package/dist/rntl-matchers.d.ts +35 -0
  49. package/dist/serializer.cjs +33 -3
  50. package/dist/serializer.mjs +33 -3
  51. package/dist/setup.mjs +544 -193
  52. package/docs/hot-default-design.md +129 -0
  53. package/docs/migrating-from-jest.md +43 -7
  54. package/docs/migrating-from-vitest-react-native.md +1 -1
  55. package/docs/release-readiness.md +24 -6
  56. package/docs/versioning.md +133 -0
  57. package/package.json +40 -38
  58. package/dist/index.cjs +0 -643
  59. package/dist/index.d.cts +0 -14
  60. package/dist/pool-B7LBfcMQ.mjs +0 -67
  61. package/dist/pool-p54QV1dQ.cjs +0 -69
  62. package/dist/presets.cjs +0 -17
  63. package/dist/presets.d.cts +0 -2
  64. package/dist/setup.cjs +0 -2514
  65. package/dist/setup.d.cts +0 -1
package/dist/index.mjs CHANGED
@@ -1,130 +1,56 @@
1
- import { t as AUTO_DETECT_PRESETS } from "./preset-map-DCWaM08s.mjs";
2
- import { t as presets_exports } from "./presets-23FJ76O4.mjs";
1
+ import { t as VitestNativeError } from "./errors-Dm5yLNTF.mjs";
2
+ import { a as validatePeerDependency, i as validateOptions, n as detectEngine, o as warnUnknownOptions, r as PEER_REQUIREMENTS, t as detectEcosystemPackages } from "./ecosystem-CO5vqExO.mjs";
3
+ import { t as AUTO_DETECT_PRESETS } from "./preset-map-BpDG_D5m.mjs";
4
+ import { t as presets_exports } from "./presets-CK85x8ey.mjs";
3
5
  import { createRequire } from "node:module";
4
- import { fileURLToPath } from "node:url";
5
- import path from "node:path";
6
6
  import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
9
  import flowRemoveTypes from "flow-remove-types";
8
- //#region src/resolve.ts
9
- const PLATFORM_EXTENSIONS_IOS = [
10
- ".ios.tsx",
11
- ".ios.ts",
12
- ".ios.jsx",
13
- ".ios.js",
14
- ".native.tsx",
15
- ".native.ts",
16
- ".native.jsx",
17
- ".native.js",
18
- ".tsx",
19
- ".ts",
20
- ".jsx",
21
- ".js"
22
- ];
23
- const PLATFORM_EXTENSIONS_ANDROID = [
24
- ".android.tsx",
25
- ".android.ts",
26
- ".android.jsx",
27
- ".android.js",
28
- ".native.tsx",
29
- ".native.ts",
30
- ".native.jsx",
31
- ".native.js",
32
- ".tsx",
33
- ".ts",
34
- ".jsx",
35
- ".js"
10
+ //#region src/native/resolve.mjs
11
+ /**
12
+ * Metro's default `sourceExts`, in its order. Kept as data rather than spelled out
13
+ * per platform so the Vite graph and the Node graph cannot drift apart — both build
14
+ * their list from this one array (see `getPlatformExtensions` in ../resolve.ts).
15
+ *
16
+ * The order is load-bearing where a module has more than one variant on disk:
17
+ * Metro picks `Foo.js` over `Foo.tsx`, so this list must too, or a project with a
18
+ * compiled file beside its source tests a different file than it ships. `json` is
19
+ * a source extension to Metro, which is why `import config from './config'`
20
+ * resolves `config.json` in an app.
21
+ */
22
+ const METRO_SOURCE_EXTS = [
23
+ "js",
24
+ "jsx",
25
+ "json",
26
+ "ts",
27
+ "tsx"
36
28
  ];
37
- function getPlatformExtensions(platform) {
38
- return platform === "ios" ? PLATFORM_EXTENSIONS_IOS : PLATFORM_EXTENSIONS_ANDROID;
29
+ /**
30
+ * Metro tries every platform-suffixed variant first, then every `.native` one,
31
+ * then the bare extensions — not extension-major.
32
+ */
33
+ function extensionsFor(platform) {
34
+ const suffix = platform === "android" ? "android" : "ios";
35
+ return [
36
+ ...METRO_SOURCE_EXTS.map((e) => `.${suffix}.${e}`),
37
+ ...METRO_SOURCE_EXTS.map((e) => `.native.${e}`),
38
+ ...METRO_SOURCE_EXTS.map((e) => `.${e}`)
39
+ ];
39
40
  }
40
41
  //#endregion
41
- //#region src/validate.ts
42
- const KNOWN_OPTIONS = [
43
- "platform",
44
- "presets",
45
- "mocks",
46
- "diagnostics",
47
- "assetExts",
48
- "engine",
49
- "transform",
50
- "hotRuntime"
51
- ];
52
- const KNOWN_HOT_RUNTIME_OPTIONS = [
53
- "recycleAfterFiles",
54
- "memoryLimit",
55
- "preserveGlobals"
56
- ];
57
- function assertStringArray(value, option) {
58
- if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.length === 0)) throw new TypeError(`[vitest-native] "${option}" must be an array of non-empty strings.`);
59
- }
60
- function assertNonNegativeInteger(value, option) {
61
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new TypeError(`[vitest-native] "${option}" must be a non-negative safe integer.`);
62
- }
63
- function validateOptions(options) {
64
- if (options.engine !== void 0 && options.engine !== "auto" && options.engine !== "mock" && options.engine !== "native") throw new TypeError(`[vitest-native] "engine" must be "auto", "mock", or "native".`);
65
- if (options.platform !== void 0 && options.platform !== "ios" && options.platform !== "android") throw new TypeError(`[vitest-native] "platform" must be "ios" or "android".`);
66
- if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") throw new TypeError(`[vitest-native] "diagnostics" must be a boolean.`);
67
- if (options.assetExts !== void 0) assertStringArray(options.assetExts, "assetExts");
68
- if (options.transform !== void 0) assertStringArray(options.transform, "transform");
69
- if (options.presets !== void 0 && !Array.isArray(options.presets)) throw new TypeError(`[vitest-native] "presets" must be an array.`);
70
- if (options.mocks !== void 0 && (options.mocks === null || Array.isArray(options.mocks) || typeof options.mocks !== "object")) throw new TypeError(`[vitest-native] "mocks" must be a plain object.`);
71
- const hotRuntime = options.hotRuntime;
72
- if (hotRuntime === void 0 || typeof hotRuntime === "boolean") return;
73
- if (hotRuntime === null || Array.isArray(hotRuntime) || typeof hotRuntime !== "object") throw new TypeError(`[vitest-native] "hotRuntime" must be a boolean or an options object.`);
74
- const hotOptions = hotRuntime;
75
- for (const key of Object.keys(hotOptions)) if (!KNOWN_HOT_RUNTIME_OPTIONS.includes(key)) throw new TypeError(`[vitest-native] Unknown hotRuntime option "${key}".`);
76
- if (hotOptions.recycleAfterFiles !== void 0) assertNonNegativeInteger(hotOptions.recycleAfterFiles, "hotRuntime.recycleAfterFiles");
77
- if (hotOptions.memoryLimit !== void 0) assertNonNegativeInteger(hotOptions.memoryLimit, "hotRuntime.memoryLimit");
78
- if (hotOptions.preserveGlobals !== void 0) assertStringArray(hotOptions.preserveGlobals, "hotRuntime.preserveGlobals");
79
- }
80
- function satisfiesMinimum(version, minimum) {
81
- const parse = (v) => v.replace(/^[^0-9]*/, "").split(".").map(Number);
82
- const [aMaj, aMin = 0, aPat = 0] = parse(version);
83
- const [bMaj, bMin = 0, bPat = 0] = parse(minimum);
84
- if (aMaj !== bMaj) return aMaj > bMaj;
85
- if (aMin !== bMin) return aMin > bMin;
86
- return aPat >= bPat;
87
- }
88
- function validatePeerDependency(pkgName, minimumVersion, projectRoot, maximumMajorExclusive, minimumByMajor) {
89
- const req = createRequire(path.join(projectRoot, "package.json"));
90
- try {
91
- const { version } = req(req.resolve(`${pkgName}/package.json`));
92
- const major = Number(version.replace(/^[^0-9]*/, "").split(".")[0]);
93
- const requiredMinimum = minimumByMajor?.[major] ?? minimumVersion;
94
- if (!satisfiesMinimum(version, requiredMinimum)) return `vitest-native requires ${pkgName} >= ${requiredMinimum} for ${major}.x, but found ${version}. Please upgrade.`;
95
- if (maximumMajorExclusive !== void 0 && major >= maximumMajorExclusive) return `vitest-native supports ${pkgName} >= ${minimumVersion} and < ${maximumMajorExclusive}, but found ${version}.`;
96
- return null;
97
- } catch {
98
- return `vitest-native requires ${pkgName} >= ${minimumVersion}, but it was not found. Please install it.`;
99
- }
100
- }
101
- function warnUnknownOptions(options) {
102
- for (const key of Object.keys(options)) if (!KNOWN_OPTIONS.includes(key)) {
103
- const suggestion = findClosest(key, KNOWN_OPTIONS);
104
- const hint = suggestion ? ` Did you mean '${suggestion}'?` : "";
105
- console.warn(`[vitest-native] Unknown option '${key}'.${hint}`);
106
- }
107
- }
108
- function findClosest(input, candidates) {
109
- let best = null;
110
- let bestDist = Infinity;
111
- for (const c of candidates) {
112
- const d = levenshtein(input.toLowerCase(), c.toLowerCase());
113
- if (d < bestDist && d <= 3) {
114
- bestDist = d;
115
- best = c;
116
- }
117
- }
118
- return best;
119
- }
120
- function levenshtein(a, b) {
121
- const m = a.length;
122
- const n = b.length;
123
- const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
124
- for (let i = 0; i <= m; i++) dp[i][0] = i;
125
- for (let j = 0; j <= n; j++) dp[0][j] = j;
126
- for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
127
- return dp[m][n];
42
+ //#region src/resolve.ts
43
+ /**
44
+ * Extension search order for the Vite graph, taken from the same definition the
45
+ * Node graph uses. Vite's default list is replaced wholesale by whatever is set
46
+ * here, so anything Metro treats as a source extension has to appear — `.json`
47
+ * included, or `import config from './config'` resolves in the app and fails in
48
+ * the test.
49
+ */
50
+ const PLATFORM_EXTENSIONS_IOS = extensionsFor("ios");
51
+ const PLATFORM_EXTENSIONS_ANDROID = extensionsFor("android");
52
+ function getPlatformExtensions(platform) {
53
+ return platform === "ios" ? PLATFORM_EXTENSIONS_IOS : PLATFORM_EXTENSIONS_ANDROID;
128
54
  }
129
55
  //#endregion
130
56
  //#region src/native/apply.ts
@@ -137,14 +63,54 @@ function levenshtein(a, b) {
137
63
  function escapeRe(s) {
138
64
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
139
65
  }
140
- function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }) {
141
- const extraExternal = transformPkgs.map((p) => new RegExp(`[\\\\/]${escapeRe(p)}[\\\\/]`));
66
+ /**
67
+ * The on-disk directory a package resolves to, or null. Used alongside the
68
+ * node_modules-anchored patterns so workspace and `file:` dependencies — which
69
+ * resolve to a real path with no node_modules segment — are matched too.
70
+ */
71
+ function resolvePackageDir(name, projectRoot) {
72
+ try {
73
+ const req = createRequire(path.join(projectRoot, "package.json"));
74
+ return path.dirname(req.resolve(`${name}/package.json`));
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }, userPool, inlinePkgs = [], projectRoot = process.cwd()) {
80
+ const extraExternal = transformPkgs.flatMap((p) => {
81
+ const patterns = [new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe(p)}[\\\\/]`)];
82
+ const dir = resolvePackageDir(p, projectRoot);
83
+ if (dir) patterns.push(new RegExp(`^${escapeRe(dir.replace(/\\/g, "/"))}[\\\\/]`));
84
+ return patterns;
85
+ });
86
+ const ecosystemExternal = inlinePkgs.flatMap((p) => {
87
+ const patterns = [new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe(p)}[\\\\/]`)];
88
+ const dir = resolvePackageDir(p, projectRoot);
89
+ if (dir) patterns.push(new RegExp(`^${escapeRe(dir.replace(/\\/g, "/"))}[\\\\/]`));
90
+ return patterns;
91
+ });
92
+ const nodeTransformed = [...new Set([...transformPkgs, ...inlinePkgs])];
142
93
  const fullEnv = { ...env };
143
- if (transformPkgs.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(transformPkgs);
94
+ if (nodeTransformed.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(nodeTransformed);
144
95
  return {
145
96
  ...jsxTransform,
97
+ ssr: { resolve: {
98
+ conditions: ["react-native"],
99
+ mainFields: [
100
+ "react-native",
101
+ "module",
102
+ "jsnext:main",
103
+ "jsnext"
104
+ ]
105
+ } },
146
106
  resolve: {
147
107
  conditions: ["react-native"],
108
+ mainFields: [
109
+ "react-native",
110
+ "module",
111
+ "jsnext:main",
112
+ "jsnext"
113
+ ],
148
114
  extensions,
149
115
  dedupe: [
150
116
  "react",
@@ -160,56 +126,16 @@ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [],
160
126
  pool: hot.pool,
161
127
  isolate: false,
162
128
  runner: hot.runnerPath
163
- } : { pool: "threads" },
129
+ } : { pool: userPool ?? "threads" },
164
130
  server: { deps: { external: [
165
131
  /[\\/]node_modules[\\/]react-native[\\/]/,
166
132
  /[\\/]node_modules[\\/]@react-native[\\/]/,
167
- ...extraExternal
133
+ ...extraExternal,
134
+ ...ecosystemExternal
168
135
  ] } }
169
136
  }
170
137
  };
171
138
  }
172
- /** Can this project run the native engine? (Both transform deps resolvable.) */
173
- function isNativeCapable(projectRoot) {
174
- try {
175
- const req = createRequire(path.join(projectRoot, "package.json"));
176
- req.resolve("@react-native/babel-preset");
177
- req.resolve("@babel/core");
178
- return true;
179
- } catch {
180
- return false;
181
- }
182
- }
183
- /** Resolve the concrete engine for a run. Pure; never throws. */
184
- function detectEngine(requested, projectRoot, opts) {
185
- const nativeAvailable = isNativeCapable(projectRoot);
186
- if (requested === "native") return {
187
- engine: "native",
188
- nativeAvailable,
189
- notice: null
190
- };
191
- if (requested === "mock") return {
192
- engine: "mock",
193
- nativeAvailable,
194
- notice: null
195
- };
196
- const prefersNative = opts?.autoPrefersNative ?? true;
197
- if (prefersNative && nativeAvailable) return {
198
- engine: "native",
199
- nativeAvailable,
200
- notice: null
201
- };
202
- if (prefersNative) return {
203
- engine: "mock",
204
- nativeAvailable: false,
205
- notice: "[vitest-native] @react-native/babel-preset not found — using the mock engine. Install it (and @babel/core) to run real React Native, or set engine:'mock' to silence this."
206
- };
207
- return {
208
- engine: "mock",
209
- nativeAvailable,
210
- notice: null
211
- };
212
- }
213
139
  //#endregion
214
140
  //#region src/plugin.ts
215
141
  const DEFAULT_ASSET_EXTS = [
@@ -270,11 +196,91 @@ function resolvePackageVersion(packageName, projectRoot) {
270
196
  return null;
271
197
  }
272
198
  }
199
+ /**
200
+ * One line, once per process, stating which engine this run actually uses.
201
+ * Tests pass either way; a team that believes it's exercising real React Native
202
+ * while running the mock (or vice versa) must be able to see it in every log.
203
+ * Guarded via globalThis (like the require-hook install) so workspace setups
204
+ * that call config() per project print it once.
205
+ *
206
+ * Written to stderr: this is the plugin's only unconditional output, and stdout
207
+ * must stay parseable for pipelines like `vitest --reporter=json > results.json`.
208
+ */
209
+ function printEngineBanner(engine, platform, projectRoot) {
210
+ const g = globalThis;
211
+ if (g.__vitest_native_banner_printed) return;
212
+ g.__vitest_native_banner_printed = true;
213
+ if (engine === "native") {
214
+ const rn = resolvePackageVersion("react-native", projectRoot);
215
+ console.error(`[vitest-native] engine: native — real react-native${rn ? `@${rn}` : ""} (platform ${platform})`);
216
+ } else console.error(`[vitest-native] engine: mock — React Native reimplementation, cross-checked against real RN (platform ${platform})`);
217
+ }
273
218
  function getJsxTransformConfig(projectRoot) {
274
219
  const viteVersion = resolvePackageVersion("vite", projectRoot);
275
220
  return Number(viteVersion?.split(".")[0]) >= 8 ? { oxc: { jsx: { runtime: "automatic" } } } : { esbuild: { jsx: "automatic" } };
276
221
  }
277
222
  /**
223
+ * The names React Native's index exports.
224
+ *
225
+ * They cannot be read with a normal import: the index is Flow source, and its
226
+ * exports are lazy getters that neither a bundler nor cjs-module-lexer can see.
227
+ * They also cannot be read by requiring the module here — that would execute React
228
+ * Native inside the Vite process, before any of the engine's globals exist.
229
+ *
230
+ * So they are parsed out of the `module.exports = { … }` object literal, whose
231
+ * members sit at one indentation level. React Native uses three member shapes
232
+ * there: lazy getters (`get View() {`), method shorthand
233
+ * (`unstable_batchedUpdates<T>(fn) {`), and plain properties (`Systrace: …`).
234
+ * A name missed here surfaces immediately as "does not provide an export named X"
235
+ * rather than silently, and the facade's export surface is asserted against the
236
+ * real module in the native suite, across every React Native version in CI.
237
+ */
238
+ function parseReactNativeExports(indexSource) {
239
+ const start = indexSource.indexOf("module.exports = {");
240
+ if (start === -1) return [];
241
+ const body = indexSource.slice(start);
242
+ const names = /* @__PURE__ */ new Set();
243
+ for (const match of body.matchAll(/^ {2}(?:get\s+)?([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*[(:,]/gm)) {
244
+ const name = match[1];
245
+ if (name !== "default" && name !== "__esModule" && name !== "get") names.add(name);
246
+ }
247
+ return [...names];
248
+ }
249
+ /**
250
+ * Build (or reuse) the precompiled React Native registry for a project.
251
+ *
252
+ * The builder ships as runtime `.mjs` next to this file (it is also imported by the
253
+ * native setup file, which Node loads directly), so it is reached through a computed
254
+ * dynamic import rather than a static one — a static specifier would bundle a second
255
+ * copy into the plugin entry. Returns the registry path, or null when one could not
256
+ * be produced, in which case the engine keeps loading RN file by file.
257
+ */
258
+ async function buildRegistryFor(options) {
259
+ try {
260
+ const dir = path.dirname(fileURLToPath(import.meta.url));
261
+ return (await import(pathToFileURL(path.resolve(dir, "native/registry.mjs")).href)).buildRegistry(options);
262
+ } catch (error) {
263
+ if (options.diagnostics) console.warn(`[vitest-native] could not precompile the React Native registry (${error?.message}); using per-file module loading.`);
264
+ return null;
265
+ }
266
+ }
267
+ /**
268
+ * Compile one inlined ecosystem file with the project's React Native Babel preset.
269
+ *
270
+ * The transformer ships as runtime `.mjs` (Node's loader hooks use it too), so it is
271
+ * loaded through a computed path rather than a static import, and synchronously —
272
+ * Vite's transform hook may be sync and the module is already resident by the time
273
+ * any file reaches this point.
274
+ */
275
+ let ecosystemTransformer = null;
276
+ function transformEcosystem(file, code, projectRoot, platform) {
277
+ if (!ecosystemTransformer) {
278
+ const dir = path.dirname(fileURLToPath(import.meta.url));
279
+ ecosystemTransformer = createRequire(import.meta.url)(path.resolve(dir, "native/transform.mjs")).transformRN;
280
+ }
281
+ return ecosystemTransformer(file, code, projectRoot, platform);
282
+ }
283
+ /**
278
284
  * Vite 6/7 and Vite 8 expose mutually exclusive JSX config types:
279
285
  * `esbuild.jsx` before Vite 8 and `oxc.jsx` from Vite 8 onward. The runtime
280
286
  * version check above guarantees that only the matching shape is returned,
@@ -308,8 +314,12 @@ async function resolveOptions(options = {}, projectRoot) {
308
314
  const engine = options.engine === "native" ? "native" : "mock";
309
315
  const userExts = (options.assetExts ?? []).map((e) => e.replace(/^\./, ""));
310
316
  let presets;
311
- if (options.presets) presets = options.presets;
312
- else presets = await autoDetectPresets(diagnostics, projectRoot ?? process.cwd());
317
+ if (Array.isArray(options.presets)) presets = options.presets;
318
+ else {
319
+ const detected = await autoDetectPresets(diagnostics, projectRoot ?? process.cwd());
320
+ const disabled = disabledPresetNames(options.presets);
321
+ presets = disabled.size > 0 ? detected.filter((p) => !disabled.has(p.name)) : detected;
322
+ }
313
323
  return {
314
324
  platform,
315
325
  engine,
@@ -411,6 +421,82 @@ const RN_EXPORT_NAMES = [
411
421
  "NativeDialogManagerAndroid",
412
422
  "usePressability"
413
423
  ];
424
+ /**
425
+ * A file inside a React Native ecosystem package under node_modules — one whose
426
+ * package NAME begins with `react-native` (with or without a scope, so
427
+ * `@shopify/react-native-skia` counts), or whose scope begins with `@react-native`.
428
+ *
429
+ * The name must BEGIN with it, which is what separates this from the substring test
430
+ * it replaced: `eslint-plugin-react-native` and a project directory called
431
+ * `react-native-app` both contain the words without being React Native packages.
432
+ */
433
+ /**
434
+ * Two copies of React in one test process produce a null hooks dispatcher, which
435
+ * surfaces as `Cannot read properties of null (reading 'use')` — usually wrapped by
436
+ * React Native Testing Library as "Trying to detect host component names triggered the
437
+ * following error", whose own advice is only that something is wrong with the
438
+ * configuration. `resolve.dedupe` prevents it in the normal case; this reports the
439
+ * cases dedupe cannot reach, such as a nested install, so the cause is named rather
440
+ * than discovered.
441
+ *
442
+ * Pure and exported for testing: `resolve` is the resolver, so the check can be
443
+ * exercised without building a broken node_modules tree.
444
+ */
445
+ function findDuplicateReact(resolve, projectRoot, consumers) {
446
+ const projectCopy = resolve("react/package.json", projectRoot);
447
+ if (!projectCopy) return null;
448
+ for (const consumer of consumers) {
449
+ const consumerRoot = resolve(`${consumer}/package.json`, projectRoot);
450
+ if (!consumerRoot) continue;
451
+ const otherCopy = resolve("react/package.json", consumerRoot);
452
+ if (otherCopy && otherCopy !== projectCopy) return {
453
+ projectCopy,
454
+ otherCopy,
455
+ consumer
456
+ };
457
+ }
458
+ return null;
459
+ }
460
+ const HAS_JEST_MOCK_CALL = /\bjest\s*\.\s*(?:mock|unmock|doMock|doUnmock)\s*\(/;
461
+ const RN_ECOSYSTEM_PATH = /[\\/]node_modules[\\/](?:@react-native[^\\/]*[\\/][^\\/]+|(?:@[^\\/]+[\\/])?react-native[^\\/]*)[\\/]/;
462
+ /** Fast membership check for leaf-name lookups on subpath imports. */
463
+ const RN_EXPORT_NAME_SET = new Set(RN_EXPORT_NAMES);
464
+ /**
465
+ * The bare package name of an import specifier ("@scope/pkg/sub" → "@scope/pkg",
466
+ * "pkg/sub" → "pkg"). Mirrors native/match.mjs for the Vite-graph side.
467
+ */
468
+ function packageNameOf(specifier) {
469
+ if (specifier.startsWith("@")) {
470
+ const [scope, name] = specifier.split("/");
471
+ return name ? `${scope}/${name}` : specifier;
472
+ }
473
+ return specifier.split("/")[0];
474
+ }
475
+ /**
476
+ * The leaf module name a subpath import points at ("pkg/lib/Swipeable" or
477
+ * "react-native/Libraries/Utilities/Platform.ios.js" → "Platform"), used to pick
478
+ * the matching export off the mock. Mirrors native/match.mjs.
479
+ */
480
+ function subpathLeafOf(specifier) {
481
+ const base = specifier.split("/").pop();
482
+ if (!base) return null;
483
+ return base.split(".")[0] || null;
484
+ }
485
+ /**
486
+ * Deep entries of preset packages that are deliberately Node-safe and must NOT
487
+ * be shadowed (test utilities and tooling entry points). Mirrors
488
+ * native/match.mjs.
489
+ */
490
+ const UTILITY_SUBPATH_LEAVES = new Set([
491
+ "jest-utils",
492
+ "jestSetup",
493
+ "mock",
494
+ "plugin"
495
+ ]);
496
+ function isUtilitySubpath(specifier) {
497
+ const leaf = subpathLeafOf(specifier);
498
+ return leaf !== null && UTILITY_SUBPATH_LEAVES.has(leaf);
499
+ }
414
500
  /** Check if a value (or any nested value) contains functions. */
415
501
  function containsFunctions(value, visited = /* @__PURE__ */ new WeakSet()) {
416
502
  if (typeof value === "function") return true;
@@ -427,16 +513,136 @@ function containsFunctions(value, visited = /* @__PURE__ */ new WeakSet()) {
427
513
  * modules, and automatic setup-file injection so tests can run against
428
514
  * React Native code in a Node/JSDOM environment.
429
515
  */
516
+ /**
517
+ * Fields that select a different FORMAT of the same code — an ESM build beside a CJS
518
+ * one. Vite prefers them, Node reads `main`, and the two builds are interchangeable,
519
+ * so pointing Vite at `main` costs nothing and collapses the pair into one instance.
520
+ *
521
+ * `react-native` is deliberately NOT here. That field selects a different
522
+ * IMPLEMENTATION — the native build rather than the web one — and Metro resolves it
523
+ * ahead of `main`, so the engine must too (see tests-native/export-conditions.test.ts).
524
+ * Aligning it downward would quietly load the web build, which is a fidelity
525
+ * regression, not a deduplication. Packages using it stay split and are reported by
526
+ * the duplicate-instance warning instead; fixing those means teaching Node to load
527
+ * the native build, which needs the transform pipeline and is a separate change.
528
+ */
529
+ const FORMAT_ONLY_FIELDS = [
530
+ "module",
531
+ "jsnext:main",
532
+ "jsnext"
533
+ ];
534
+ /**
535
+ * Make Vite resolve a package to the same file Node will.
536
+ *
537
+ * The native engine runs two module systems. Vitest already forwards
538
+ * `resolve.conditions` to the worker's Node (`--conditions react-native ...`), so a
539
+ * package using an `exports` map resolves identically on both sides. Legacy
540
+ * top-level fields have no such bridge: Vite reads `react-native`/`module`, Node
541
+ * reads `main`, and a package publishing both ends up loaded twice with separate
542
+ * module-level state. A store written through one copy reads back unset through the
543
+ * other — silently, since nothing fails.
544
+ *
545
+ * Aligning downward, onto the file Node picks, is the direction that cannot break a
546
+ * working suite: the `main` build is by definition something Node can execute,
547
+ * whereas the `react-native` field usually points at untranspiled source that Node
548
+ * cannot parse at all. Aligning upward would turn a wrong-value bug into a crash for
549
+ * any package the engine does not also transform.
550
+ *
551
+ * Packages the engine inlines and transforms are left alone: Vite is meant to own
552
+ * their source, and rewriting them to `main` would undo the reason they are inlined.
553
+ *
554
+ * @returns the absolute file to use, or null to leave resolution alone
555
+ */
556
+ function alignLegacyFieldsWithNode(source, packageDirFor, readManifest, resolveAsNodeWould, isEngineOwned) {
557
+ if (!source || source.startsWith(".") || source.startsWith("/") || source.startsWith("\0")) return null;
558
+ const segments = source.split("/");
559
+ const name = source.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
560
+ if (!name || segments.length > (source.startsWith("@") ? 2 : 1)) return null;
561
+ if (isEngineOwned(name)) return null;
562
+ const dir = packageDirFor(name);
563
+ if (!dir) return null;
564
+ const manifest = readManifest(dir);
565
+ if (!manifest) return null;
566
+ if (manifest.exports !== void 0) return null;
567
+ if (typeof manifest["react-native"] === "string") return null;
568
+ const legacy = FORMAT_ONLY_FIELDS.map((f) => manifest[f]).find((v) => typeof v === "string");
569
+ if (typeof legacy !== "string") return null;
570
+ const nodeFile = resolveAsNodeWould(name);
571
+ if (!nodeFile) return null;
572
+ if (path.resolve(dir, legacy) === nodeFile) return null;
573
+ return nodeFile;
574
+ }
575
+ /**
576
+ * Preset names switched off by the object form of the `presets` option.
577
+ *
578
+ * The array form replaces auto-detection wholesale, which meant that turning ONE
579
+ * preset off required listing every other detected preset by hand — tedious, and a
580
+ * list that silently rots as dependencies change. The object form keeps detection
581
+ * and names only what to drop.
582
+ */
583
+ function disabledPresetNames(presets) {
584
+ if (!presets || Array.isArray(presets) || typeof presets !== "object") return /* @__PURE__ */ new Set();
585
+ return new Set(Object.entries(presets).filter(([, enabled]) => enabled === false).map(([name]) => name));
586
+ }
430
587
  function reactNative(options) {
588
+ let jestMockTransformPresent = true;
589
+ let warnedMissingJestMockTransform = false;
590
+ const warnIfJestMockUnhoisted = (code, id) => {
591
+ if (jestMockTransformPresent || warnedMissingJestMockTransform) return;
592
+ if (!HAS_JEST_MOCK_CALL.test(code)) return;
593
+ warnedMissingJestMockTransform = true;
594
+ console.warn(`[vitest-native] ${id} calls jest.mock(), but jestMockTransform() is not in your plugins. Vitest only hoists mocks written on the vi/vitest identifier, so this call runs after the imports it should intercept and the mock will not apply.\nAdd it AFTER reactNative():\n\n import { jestMockTransform } from 'vitest-native/jest-compat'\n plugins: [reactNative(), jestMockTransform()]`);
595
+ };
431
596
  if (options) {
432
597
  validateOptions(options);
433
598
  warnUnknownOptions(options);
434
599
  }
435
- if (options?.mocks && containsFunctions(options.mocks)) throw new Error("[vitest-native] The \"mocks\" option contains function values, which cannot be transferred to Vitest worker processes. Only JSON-serializable values (strings, numbers, booleans, plain objects, arrays) are supported.\n\nFor function-based mock overrides, use vi.mock() in a setup file:\n\n // vitest.setup.ts\n import { vi } from 'vitest';\n vi.mock('react-native', async (importOriginal) => {\n const actual = await importOriginal();\n return { ...actual, Alert: { alert: vi.fn() } };\n });");
600
+ if (options?.mocks && containsFunctions(options.mocks)) throw new VitestNativeError("INVALID_OPTION", "The \"mocks\" option contains function values, which cannot be transferred to Vitest worker processes. Only JSON-serializable values (strings, numbers, booleans, plain objects, arrays) are supported.\n\nFor function-based mock overrides, use vi.mock() in a setup file:\n\n // vitest.setup.ts\n import { vi } from 'vitest';\n vi.mock('react-native', async (importOriginal) => {\n const actual = await importOriginal();\n return { ...actual, Alert: { alert: vi.fn() } };\n });");
436
601
  let resolved;
437
602
  const presetModules = /* @__PURE__ */ new Map();
438
603
  const presetExportNames = /* @__PURE__ */ new Map();
439
604
  let assetPattern;
605
+ let realRnPackageJson;
606
+ let rnFacadeExports = null;
607
+ let rnFacadeRoot = "";
608
+ let ecosystemPattern = null;
609
+ let alignRoot = "";
610
+ let ecosystemRoot = "";
611
+ const alignedCache = /* @__PURE__ */ new Map();
612
+ const alignedResolution = (source, importer) => {
613
+ if (engine !== "native") return void 0;
614
+ const from = importer && path.isAbsolute(importer) && !importer.startsWith("\0") ? importer : path.join(alignRoot || process.cwd(), "package.json");
615
+ const key = `${from}\u0000${source}`;
616
+ const cached = alignedCache.get(key);
617
+ if (cached !== void 0) return cached ?? void 0;
618
+ let result = null;
619
+ try {
620
+ const req = createRequire(from);
621
+ result = alignLegacyFieldsWithNode(source, (name) => {
622
+ try {
623
+ return path.dirname(req.resolve(`${name}/package.json`));
624
+ } catch {
625
+ return null;
626
+ }
627
+ }, (dir) => {
628
+ try {
629
+ return JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
630
+ } catch {
631
+ return null;
632
+ }
633
+ }, (name) => {
634
+ try {
635
+ return req.resolve(name);
636
+ } catch {
637
+ return null;
638
+ }
639
+ }, (name) => name === "react-native" || name.startsWith("@react-native"));
640
+ } catch {
641
+ result = null;
642
+ }
643
+ alignedCache.set(key, result);
644
+ return result ?? void 0;
645
+ };
440
646
  const resolveCache = /* @__PURE__ */ new Map();
441
647
  const virtualCodeCache = /* @__PURE__ */ new Map();
442
648
  const thisDir = path.dirname(fileURLToPath(import.meta.url));
@@ -457,15 +663,25 @@ function reactNative(options) {
457
663
  const hotRecycle = typeof hotRuntimeOpt === "object" ? hotRuntimeOpt : {};
458
664
  let engine = requestedEngine === "native" ? "native" : "mock";
459
665
  const extensions = getPlatformExtensions(platform);
666
+ const resolvePresetId = (source) => {
667
+ if (presetModules.has(source)) return `\0virtual:preset:${source}`;
668
+ if (!assetPattern) return void 0;
669
+ if (source.endsWith(".json") || assetPattern.test(source) || isUtilitySubpath(source)) return;
670
+ const pkg = packageNameOf(source);
671
+ if (pkg !== source && presetModules.has(pkg)) return `\0virtual:preset:${source}`;
672
+ };
460
673
  return {
461
674
  name: "vitest-native",
462
675
  enforce: "pre",
463
676
  async config(userConfig, _env) {
464
677
  const resolvedRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
678
+ alignRoot = resolvedRoot;
465
679
  const jsxTransform = getJsxTransformConfig(resolvedRoot);
466
680
  const decision = detectEngine(requestedEngine, resolvedRoot);
467
681
  engine = decision.engine;
468
- if (decision.notice) console.log(decision.notice);
682
+ if (engine === "native" && !decision.nativeAvailable) throw new VitestNativeError("ENGINE_REQUIRES_BABEL", `engine:'native' requires '@react-native/babel-preset' and '@babel/core' to resolve from ${resolvedRoot}. Install them as devDependencies (React Native projects ship them by default):\n\n npm install -D @react-native/babel-preset @babel/core\n\nOr set engine:'mock' to run without a React Native install.`);
683
+ if (decision.notice) console.warn(decision.notice);
684
+ printEngineBanner(engine, platform, resolvedRoot);
469
685
  const env = {
470
686
  VITEST_NATIVE_PLATFORM: platform,
471
687
  VITEST_NATIVE_DIAGNOSTICS: String(diagnostics),
@@ -473,35 +689,80 @@ function reactNative(options) {
473
689
  };
474
690
  const reactNativeVersion = resolvePackageVersion("react-native", resolvedRoot);
475
691
  if (reactNativeVersion) env.VITEST_NATIVE_RN_VERSION = reactNativeVersion;
476
- env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify([...DEFAULT_ASSET_EXTS, ...(options?.assetExts ?? []).map((e) => e.replace(/^\./, ""))]);
692
+ const assetExtList = [...DEFAULT_ASSET_EXTS, ...(options?.assetExts ?? []).map((e) => e.replace(/^\./, ""))];
693
+ env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify(assetExtList);
477
694
  if (hotRuntime && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
478
695
  if (engine === "native") {
479
- if (options?.mocks && Object.keys(options.mocks).length > 0) throw new Error("[vitest-native] The \"mocks\" option is only supported by engine:'mock'. The native engine runs the real react-native module and cannot safely merge arbitrary exports into it. Use vi.mock() in a setup file, mockNativeModule() for native modules, or set engine:'mock'.");
480
- const nativePresetNames = options?.presets ? options.presets.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics);
696
+ if (options?.mocks && Object.keys(options.mocks).length > 0) throw new VitestNativeError("MOCKS_REQUIRE_MOCK_ENGINE", "The \"mocks\" option is only supported by engine:'mock'. The native engine runs the real react-native module and cannot safely merge arbitrary exports into it. Use vi.mock() in a setup file, mockNativeModule() for native modules, or set engine:'mock'.");
697
+ const disabledNative = disabledPresetNames(options?.presets);
698
+ const nativePresetNames = Array.isArray(options?.presets) ? options.presets.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics).filter((n) => !disabledNative.has(n));
481
699
  if (nativePresetNames.length > 0) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames);
482
- if (options?.presets) {
700
+ if (Array.isArray(options?.presets)) {
483
701
  const presetConfig = {};
484
702
  for (const p of options.presets) if (p.config && Object.keys(p.config).length > 0) presetConfig[p.name] = p.config;
485
703
  if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
486
704
  }
487
- return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hotRuntime ? {
488
- pool: (await import("./pool-B7LBfcMQ.mjs")).nativePool({
489
- workerEntry: nativeWorkerPath,
490
- recycleAfterFiles: hotRecycle.recycleAfterFiles,
491
- memoryLimit: hotRecycle.memoryLimit,
492
- diagnostics
493
- }),
494
- runnerPath: nativeRunnerPath
495
- } : void 0, jsxTransform));
705
+ const ecosystem = detectEcosystemPackages(resolvedRoot, transformPkgs);
706
+ if (ecosystem.length > 0) {
707
+ ecosystemRoot = resolvedRoot;
708
+ ecosystemPattern = new RegExp(`[\\\\/]node_modules[\\\\/](?:${ecosystem.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})[\\\\/]`);
709
+ if (diagnostics) console.log(`[vitest-native] inlining React Native packages: ${ecosystem.join(", ")}`);
710
+ }
711
+ const registryFile = await buildRegistryFor({
712
+ projectRoot: resolvedRoot,
713
+ platform,
714
+ reactNativeVersion: reactNativeVersion ?? "0.0.0",
715
+ assetExts: assetExtList,
716
+ diagnostics
717
+ });
718
+ if (registryFile) env.VITEST_NATIVE_RN_REGISTRY = registryFile;
719
+ let hot;
720
+ if (hotRuntime) {
721
+ const { nativePool, defaultHotMemoryLimit } = await import("./pool-Bcxp4Qrg.mjs");
722
+ const memoryLimit = hotRecycle.memoryLimit ?? (hotRecycle.recycleAfterFiles == null ? defaultHotMemoryLimit() : void 0);
723
+ hot = {
724
+ pool: nativePool({
725
+ workerEntry: nativeWorkerPath,
726
+ projectRoot: resolvedRoot,
727
+ recycleAfterFiles: hotRecycle.recycleAfterFiles,
728
+ memoryLimit,
729
+ diagnostics
730
+ }),
731
+ runnerPath: nativeRunnerPath
732
+ };
733
+ }
734
+ const userPool = userConfig.test?.pool;
735
+ if (userPool === "vmThreads" || userPool === "vmForks") throw new VitestNativeError("UNSUPPORTED_POOL", `engine:'native' cannot run on the '${userPool}' pool. React Native is loaded through Node's module hooks, which a VM pool's context does not use — React Native fails to resolve its platform files there. Use 'threads' (the default) or 'forks', or switch to engine:'mock', which needs no hooks.`);
736
+ if (hot && userPool) console.warn(`[vitest-native] 'hotRuntime' supplies its own pool, overriding the configured pool '${typeof userPool === "string" ? userPool : "(custom)"}'.`);
737
+ return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hot, jsxTransform, userPool, ecosystem, resolvedRoot));
496
738
  }
497
739
  if (hotRuntime) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
498
740
  if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
499
- if (options?.presets) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
741
+ if (Array.isArray(options?.presets)) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
742
+ else {
743
+ const disabled = disabledPresetNames(options?.presets);
744
+ if (disabled.size > 0) env.VITEST_NATIVE_PRESET_DISABLED = JSON.stringify([...disabled]);
745
+ }
500
746
  return asCompatibleViteConfig({
501
747
  ...jsxTransform,
748
+ ssr: { resolve: {
749
+ conditions: ["react-native"],
750
+ mainFields: [
751
+ "react-native",
752
+ "module",
753
+ "jsnext:main",
754
+ "jsnext"
755
+ ]
756
+ } },
502
757
  resolve: {
503
758
  extensions,
504
759
  conditions: ["react-native"],
760
+ mainFields: [
761
+ "react-native",
762
+ "module",
763
+ "jsnext:main",
764
+ "jsnext"
765
+ ],
505
766
  dedupe: [
506
767
  "react",
507
768
  "react-test-renderer",
@@ -516,51 +777,67 @@ function reactNative(options) {
516
777
  });
517
778
  },
518
779
  async configResolved(config) {
519
- const peers = [
520
- {
521
- name: "vitest",
522
- minimum: "4.0.0",
523
- maximumMajor: 5
524
- },
525
- {
526
- name: "vite",
527
- minimum: "6.4.2",
528
- maximumMajor: 9,
529
- minimumByMajor: {
530
- 6: "6.4.2",
531
- 7: "7.3.2",
532
- 8: "8.0.5"
533
- }
534
- },
535
- {
536
- name: "react",
537
- minimum: "18.0.0"
780
+ jestMockTransformPresent = (config.plugins ?? []).some((plugin) => plugin?.name === "vitest-native:jest-mock-hoist");
781
+ const duplicateReact = findDuplicateReact((specifier, from) => {
782
+ try {
783
+ return createRequire(path.join(from, "package.json")).resolve(specifier);
784
+ } catch {
785
+ return null;
538
786
  }
539
- ];
787
+ }, config.root, [
788
+ "@testing-library/react-native",
789
+ "react-test-renderer",
790
+ "react-native"
791
+ ]);
792
+ if (duplicateReact) console.warn(`[vitest-native] Two copies of React are resolvable: your project loads one, and '${duplicateReact.consumer}' loads another.\n project: ${duplicateReact.projectCopy}\n ${duplicateReact.consumer}: ${duplicateReact.otherCopy}\nReact throws "Cannot read properties of null (reading 'use')" when hooks run through a second copy, which React Native Testing Library reports as a failure to detect host component names. Install a single React version at the project root (npm dedupe, or match the version '${duplicateReact.consumer}' expects).`);
540
793
  const peerErrors = [];
541
- for (const { name, minimum, maximumMajor, minimumByMajor } of peers) {
794
+ for (const { name, minimum, maximumMajor, minimumByMajor, optional } of PEER_REQUIREMENTS) {
795
+ if (optional) continue;
542
796
  const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
543
797
  if (error) peerErrors.push(error);
544
798
  }
545
- if (peerErrors.length > 0) throw new Error(`[vitest-native] Unsupported peer dependencies:\n- ${peerErrors.join("\n- ")}`);
546
- const rntlError = validatePeerDependency("@testing-library/react-native", "12.0.0", config.root, 15);
547
- if (rntlError && !rntlError.includes("not found")) console.warn(`[vitest-native] ${rntlError}`);
799
+ if (peerErrors.length > 0) throw new VitestNativeError("UNSUPPORTED_PEER", `Unsupported peer dependencies:\n- ${peerErrors.join("\n- ")}`);
800
+ for (const { name, minimum, maximumMajor, minimumByMajor, optional } of PEER_REQUIREMENTS) {
801
+ if (!optional) continue;
802
+ const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
803
+ if (error && !error.includes("not found")) console.warn(`[vitest-native] ${error}`);
804
+ }
548
805
  resolved = await resolveOptions(options, config.root);
806
+ try {
807
+ realRnPackageJson = createRequire(path.join(config.root, "package.json")).resolve("react-native/package.json");
808
+ } catch {}
549
809
  resolved.engine = engine;
550
810
  for (const preset of resolved.presets) for (const [moduleName, presetModule] of Object.entries(preset.modules)) {
551
811
  presetModules.set(moduleName, presetModule.factory);
552
812
  presetExportNames.set(moduleName, presetModule.exports);
553
813
  }
554
- assetPattern = new RegExp(`\\.(${resolved.assetExts.join("|")})$`);
814
+ if (engine === "native") {
815
+ rnFacadeRoot = config.root;
816
+ try {
817
+ const indexPath = createRequire(path.join(config.root, "package.json")).resolve("react-native");
818
+ const names = parseReactNativeExports(fs.readFileSync(indexPath, "utf8"));
819
+ rnFacadeExports = names.length > 0 ? names : null;
820
+ } catch {
821
+ rnFacadeExports = null;
822
+ }
823
+ }
824
+ const escaped = resolved.assetExts.map((e) => e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
825
+ assetPattern = new RegExp(`\\.(${escaped.join("|")})$`, "i");
555
826
  },
556
827
  resolveId(source, importer) {
557
828
  if (engine === "native") {
558
- if (presetModules.has(source)) return `\0virtual:preset:${source}`;
559
- return;
829
+ if (source === "react-native" && rnFacadeExports !== null) return "\0virtual:rn-facade";
830
+ const presetHit = resolvePresetId(source);
831
+ if (presetHit) return presetHit;
832
+ return alignedResolution(source, importer);
560
833
  }
561
834
  if (source === "react-native") return "\0virtual:react-native";
562
- if (source.startsWith("react-native/")) return `\0virtual:rn-subpath:${source}`;
563
- if (presetModules.has(source)) return `\0virtual:preset:${source}`;
835
+ if (source.startsWith("react-native/")) {
836
+ if (source === "react-native/package.json" && realRnPackageJson) return realRnPackageJson;
837
+ return `\0virtual:rn-subpath:${source}`;
838
+ }
839
+ const presetId = resolvePresetId(source);
840
+ if (presetId) return presetId;
564
841
  if (importer && importer.includes("node_modules") && source.startsWith(".") && !path.extname(source)) {
565
842
  const cacheKey = `${importer}\0${source}`;
566
843
  const cached = resolveCache.get(cacheKey);
@@ -585,48 +862,102 @@ function reactNative(options) {
585
862
  }
586
863
  },
587
864
  load(id) {
865
+ if (id === "\0virtual:rn-facade" && rnFacadeExports !== null) {
866
+ const cached = virtualCodeCache.get(id);
867
+ if (cached) return cached;
868
+ const code = [
869
+ `import { createRequire } from "node:module";`,
870
+ `const _rn = createRequire(${JSON.stringify(path.join(rnFacadeRoot, "package.json"))})("react-native");`,
871
+ ...rnFacadeExports.map((n) => `export const ${n} = _rn[${JSON.stringify(n)}];`),
872
+ `export default _rn;`
873
+ ].join("\n");
874
+ virtualCodeCache.set(id, code);
875
+ return code;
876
+ }
588
877
  if (id.startsWith("\0virtual:preset:")) {
589
878
  const cached = virtualCodeCache.get(id);
590
879
  if (cached) return cached;
591
- const moduleName = id.slice(16);
592
- const exportNames = presetExportNames.get(moduleName) || [];
880
+ const specifier = id.slice(16);
881
+ const pkg = packageNameOf(specifier);
882
+ const exportNames = presetExportNames.get(pkg) || [];
883
+ const leaf = specifier === pkg ? null : subpathLeafOf(specifier);
884
+ const fallback = `('default' in _m ? _m['default'] : _m)`;
593
885
  const code = [
594
- `const _m = (globalThis.__vitest_native_preset_mocks || {})['${moduleName}'] || {};`,
886
+ `const _m = (globalThis.__vitest_native_preset_mocks || {})[${JSON.stringify(pkg)}] || {};`,
595
887
  ...exportNames.map((n) => `export const ${n} = _m['${n}'];`),
596
- `export default ('default' in _m ? _m['default'] : _m);`
888
+ ...leaf ? [
889
+ `const _hit = ${JSON.stringify(leaf)} in _m;`,
890
+ `if (!_hit && process.env.VITEST_NATIVE_DIAGNOSTICS === "true") console.warn(${JSON.stringify(`[vitest-native] '${specifier}' has no matching export on the '${pkg}' preset mock; serving the root mock namespace.`)});`,
891
+ `export default (_hit ? _m[${JSON.stringify(leaf)}] : ${fallback});`
892
+ ] : [`export default ${fallback};`]
597
893
  ].join("\n");
598
894
  virtualCodeCache.set(id, code);
599
895
  return code;
600
896
  }
601
897
  const fsPath = stripFsPrefix(id);
602
- if (assetPattern.test(fsPath)) return `export default "${fsPath.split("/").pop() ?? fsPath}";`;
898
+ if (assetPattern.test(fsPath)) {
899
+ const basename = fsPath.split("/").pop() ?? fsPath;
900
+ return `export default ${JSON.stringify(basename)};`;
901
+ }
603
902
  if (engine === "native") return void 0;
604
- if (id === "\0virtual:react-native") return "export default {};";
605
- if (id.startsWith("\0virtual:rn-subpath:")) {
606
- let code = virtualCodeCache.get("\0rn-subpath");
903
+ if (id === "\0virtual:react-native") {
904
+ const cacheKey = "\0rn-root";
905
+ let code = virtualCodeCache.get(cacheKey);
607
906
  if (!code) {
608
907
  code = [
609
908
  `const _rn = globalThis.__vitest_native_mock || {};`,
610
909
  ...RN_EXPORT_NAMES.map((n) => `export const ${n} = _rn['${n}'];`),
611
910
  `export default _rn;`
612
911
  ].join("\n");
613
- virtualCodeCache.set("\0rn-subpath", code);
912
+ virtualCodeCache.set(cacheKey, code);
913
+ }
914
+ return code;
915
+ }
916
+ if (id.startsWith("\0virtual:rn-subpath:")) {
917
+ const leaf = subpathLeafOf(id.slice(20));
918
+ const known = leaf && RN_EXPORT_NAME_SET.has(leaf) ? leaf : null;
919
+ const cacheKey = `\0rn-subpath:${known ?? ""}`;
920
+ let code = virtualCodeCache.get(cacheKey);
921
+ if (!code) {
922
+ code = [
923
+ `const _rn = globalThis.__vitest_native_mock || {};`,
924
+ ...RN_EXPORT_NAMES.map((n) => `export const ${n} = _rn['${n}'];`),
925
+ known ? `export default _rn[${JSON.stringify(known)}];` : `export default _rn;`
926
+ ].join("\n");
927
+ virtualCodeCache.set(cacheKey, code);
614
928
  }
615
929
  return code;
616
930
  }
617
931
  },
618
932
  transform(code, id) {
619
- if (engine === "native") return void 0;
620
- if (!id.includes("node_modules")) return void 0;
621
- if (!id.includes("react-native") || !id.endsWith(".js")) return void 0;
933
+ warnIfJestMockUnhoisted(code, id);
934
+ if (engine === "native") {
935
+ if (!ecosystemPattern || !ecosystemPattern.test(id)) return void 0;
936
+ if (!/\.[cm]?[jt]sx?$/.test(id.split("?")[0])) return void 0;
937
+ try {
938
+ return {
939
+ code: transformEcosystem(id, code, ecosystemRoot, platform),
940
+ map: null
941
+ };
942
+ } catch (error) {
943
+ if (diagnostics) console.warn(`[vitest-native] could not compile inlined ${id} (${error?.message}); serving it untouched.`);
944
+ return;
945
+ }
946
+ }
947
+ if (!RN_ECOSYSTEM_PATH.test(id) || !id.endsWith(".js")) return void 0;
622
948
  if (!code.includes("@flow")) return void 0;
623
- const stripped = flowRemoveTypes(code, { all: true });
624
- return {
625
- code: stripped.toString(),
626
- map: stripped.generateMap()
627
- };
949
+ try {
950
+ const stripped = flowRemoveTypes(code, { all: true });
951
+ return {
952
+ code: stripped.toString(),
953
+ map: stripped.generateMap()
954
+ };
955
+ } catch (e) {
956
+ console.warn(`[vitest-native] Flow strip skipped for ${id} (parse failed: ${e?.message}); serving the file untouched.`);
957
+ return;
958
+ }
628
959
  }
629
960
  };
630
961
  }
631
962
  //#endregion
632
- export { presets_exports as presets, reactNative };
963
+ export { disabledPresetNames, presets_exports as presets, reactNative };