vitest-native 0.13.0 → 0.14.0-rc.10

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 (117) hide show
  1. package/CHANGELOG.md +746 -0
  2. package/README.md +205 -88
  3. package/dist/cli.cjs +1478 -145
  4. package/dist/cli.d.cts +2 -3
  5. package/dist/cli.d.mts +2 -3
  6. package/dist/cli.mjs +1475 -142
  7. package/dist/context.d.mts +40 -0
  8. package/dist/context.mjs +238 -0
  9. package/dist/errors.d.mts +19 -0
  10. package/dist/helpers.cjs +6 -9
  11. package/dist/helpers.d.cts +8 -9
  12. package/dist/helpers.d.mts +8 -9
  13. package/dist/helpers.mjs +6 -9
  14. package/dist/host-D3wzmsw8.cjs +1296 -0
  15. package/dist/host-DCPzgC3D.mjs +1180 -0
  16. package/dist/{index-CPGq6p95.d.cts → index-CPEAYjaQ.d.mts} +88 -19
  17. package/dist/{index-CmETArCM.d.mts → index-D5cOy_iY.d.cts} +89 -18
  18. package/dist/index.d.mts +4 -4
  19. package/dist/index.mjs +1366 -210
  20. package/dist/jest-compat/aliases.d.mts +5 -0
  21. package/dist/jest-compat/aliases.mjs +65 -0
  22. package/dist/jest-compat/caller.mjs +53 -0
  23. package/dist/jest-compat/error-equality.mjs +127 -0
  24. package/dist/jest-compat/interop.mjs +78 -4
  25. package/dist/jest-compat/jest-globals.mjs +5 -2
  26. package/dist/jest-compat/jest-object.mjs +348 -0
  27. package/dist/jest-compat/node-registry.mjs +489 -0
  28. package/dist/jest-compat/setup.mjs +167 -66
  29. package/dist/jest-compat.cjs +35 -5
  30. package/dist/jest-compat.d.cts +9 -5
  31. package/dist/jest-compat.d.mts +9 -5
  32. package/dist/jest-compat.mjs +35 -3
  33. package/dist/matchers.d.cts +9 -8
  34. package/dist/matchers.d.mts +9 -8
  35. package/dist/memory-BFxB285Z.mjs +137 -0
  36. package/dist/memory-bBnzadf6.cjs +155 -0
  37. package/dist/native/assets.d.mts +39 -0
  38. package/dist/native/assets.mjs +431 -0
  39. package/dist/native/babel-preset.d.mts +14 -0
  40. package/dist/native/babel-preset.mjs +56 -0
  41. package/dist/native/boundary.mjs +71 -8
  42. package/dist/native/bounded-process.mjs +165 -0
  43. package/dist/native/compile-cache.mjs +21 -9
  44. package/dist/native/expo-module-mocks.mjs +432 -0
  45. package/dist/native/expo-module-table-57.mjs +1925 -0
  46. package/dist/native/expo-module-table-58.mjs +2045 -0
  47. package/dist/native/expo-module-tables.mjs +6 -0
  48. package/dist/native/expo-native-modules.mjs +66 -0
  49. package/dist/native/export-condition-recovery-preload.mjs +5 -0
  50. package/dist/native/export-condition-recovery.mjs +195 -0
  51. package/dist/native/globals.mjs +289 -9
  52. package/dist/native/hooks.mjs +392 -114
  53. package/dist/native/loader.mjs +346 -75
  54. package/dist/native/match.d.mts +13 -0
  55. package/dist/native/match.mjs +127 -2
  56. package/dist/native/metro-profile-compiler.mjs +234 -0
  57. package/dist/native/metro-profile.mjs +115 -0
  58. package/dist/native/module-reset.mjs +172 -6
  59. package/dist/native/native-modules.d.mts +15 -0
  60. package/dist/native/native-modules.mjs +228 -0
  61. package/dist/native/nitro.mjs +60 -0
  62. package/dist/native/ownership.d.mts +105 -0
  63. package/dist/native/ownership.mjs +474 -0
  64. package/dist/native/registry-compiler.mjs +43 -0
  65. package/dist/native/registry-process.mjs +124 -0
  66. package/dist/native/registry.mjs +197 -39
  67. package/dist/native/reset.mjs +334 -135
  68. package/dist/native/resolve.d.mts +20 -3
  69. package/dist/native/resolve.mjs +103 -17
  70. package/dist/native/rntl-hooks.mjs +227 -0
  71. package/dist/native/rntl-text-host.mjs +64 -0
  72. package/dist/native/runner.mjs +33 -1
  73. package/dist/native/setup.mjs +284 -96
  74. package/dist/native/state-manifest.d.mts +22 -0
  75. package/dist/native/state-manifest.mjs +138 -0
  76. package/dist/native/transform.d.mts +2 -0
  77. package/dist/native/transform.mjs +270 -47
  78. package/dist/native/tsconfig-paths.d.mts +5 -0
  79. package/dist/native/tsconfig-paths.mjs +163 -0
  80. package/dist/native/worker.mjs +151 -40
  81. package/dist/pool-DUOe-n1k.mjs +125 -0
  82. package/dist/pool-DaTJRKJb.cjs +127 -0
  83. package/dist/preset-map-BlBriTA0.mjs +197 -0
  84. package/dist/preset-map-jSFsNy1Q.cjs +241 -0
  85. package/dist/preset-modules-Bt6k_Wdw.mjs +31 -0
  86. package/dist/preset-modules-C7gu3bPn.cjs +48 -0
  87. package/dist/preset-modules.d.mts +16 -0
  88. package/dist/preset-modules.mjs +92 -0
  89. package/dist/preset-ready.mjs +9 -0
  90. package/dist/{presets-CoNf4ByH.cjs → presets-DH7fC0YV.cjs} +1125 -102
  91. package/dist/{presets-DGProTaA.mjs → presets-DuXiUNAx.mjs} +1107 -103
  92. package/dist/presets.d.mts +2 -2
  93. package/dist/presets.mjs +1 -2
  94. package/dist/report-error.d.mts +20 -0
  95. package/dist/report-error.mjs +145 -0
  96. package/dist/rntl-matchers.d.ts +58 -12
  97. package/dist/rntl-support.d.mts +12 -0
  98. package/dist/rntl-support.mjs +189 -0
  99. package/dist/serializer.cjs +4 -2
  100. package/dist/serializer.d.cts +3 -4
  101. package/dist/serializer.d.mts +3 -4
  102. package/dist/serializer.mjs +4 -2
  103. package/dist/setup.mjs +463 -97
  104. package/dist/worker-vitest-BGPo0ek6.mjs +49 -0
  105. package/dist/worker-vitest-BfiQB8ND.cjs +62 -0
  106. package/docs/hot-default-design.md +181 -88
  107. package/docs/migrating-from-jest.md +74 -16
  108. package/docs/migrating-from-vitest-react-native.md +5 -5
  109. package/docs/release-readiness.md +55 -15
  110. package/docs/versioning.md +31 -22
  111. package/package.json +122 -98
  112. package/dist/ecosystem-CEIF_-jq.cjs +0 -659
  113. package/dist/ecosystem-Duw40-mO.mjs +0 -597
  114. package/dist/pool-BU-1ecIF.cjs +0 -122
  115. package/dist/pool-Bcxn9a3I.mjs +0 -118
  116. package/dist/preset-map-BoG19dLa.cjs +0 -35
  117. package/dist/preset-map-DuX0ocdn.mjs +0 -30
@@ -1,659 +0,0 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
- const require_errors = require("./errors-B3lJK46O.cjs");
3
- const require_preset_map = require("./preset-map-BoG19dLa.cjs");
4
- let node_fs = require("node:fs");
5
- node_fs = require_rolldown_runtime.__toESM(node_fs, 1);
6
- let node_path = require("node:path");
7
- node_path = require_rolldown_runtime.__toESM(node_path, 1);
8
- let node_module = require("node:module");
9
- //#region src/validate.ts
10
- const KNOWN_OPTIONS = [
11
- "platform",
12
- "presets",
13
- "mocks",
14
- "diagnostics",
15
- "assetExts",
16
- "engine",
17
- "transform",
18
- "hotRuntime"
19
- ];
20
- const KNOWN_HOT_RUNTIME_OPTIONS = [
21
- "recycleAfterFiles",
22
- "memoryLimit",
23
- "preserveGlobals",
24
- "esmGeneration"
25
- ];
26
- function assertStringArray(value, option) {
27
- if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.length === 0)) throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"${option}" must be an array of non-empty strings.`);
28
- }
29
- function assertNonNegativeInteger(value, option) {
30
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"${option}" must be a non-negative safe integer.`);
31
- }
32
- function validateOptions(options) {
33
- if (options.engine !== void 0 && options.engine !== "auto" && options.engine !== "mock" && options.engine !== "native") throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"engine" must be "auto", "mock", or "native".`);
34
- if (options.platform !== void 0 && options.platform !== "ios" && options.platform !== "android") throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"platform" must be "ios" or "android".`);
35
- if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"diagnostics" must be a boolean.`);
36
- if (options.assetExts !== void 0) assertStringArray(options.assetExts, "assetExts");
37
- if (options.transform !== void 0) if (Array.isArray(options.transform)) assertStringArray(options.transform, "transform");
38
- else if (options.transform !== null && typeof options.transform === "object") {
39
- const shape = options.transform;
40
- const unknownKeys = Object.keys(shape).filter((k) => k !== "include" && k !== "exclude");
41
- if (unknownKeys.length > 0) throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"transform" accepts only "include" and "exclude"; received ${unknownKeys.map((k) => `"${k}"`).join(", ")}.`);
42
- if (shape.include !== void 0) assertStringArray(shape.include, "transform.include");
43
- if (shape.exclude !== void 0) assertStringArray(shape.exclude, "transform.exclude");
44
- } else throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"transform" must be an array of package names, or an object with "include" and/or "exclude".`);
45
- if (options.presets !== void 0 && !Array.isArray(options.presets)) {
46
- if (!(options.presets !== null && typeof options.presets === "object" && Object.values(options.presets).every((v) => typeof v === "boolean"))) throw new require_errors.VitestNativeTypeError("INVALID_OPTION", "\"presets\" must be an array of presets, or an object of booleans to switch auto-detected presets off (for example { navigation: false }).");
47
- }
48
- if (options.mocks !== void 0 && (options.mocks === null || Array.isArray(options.mocks) || typeof options.mocks !== "object")) throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"mocks" must be a plain object.`);
49
- const hotRuntime = options.hotRuntime;
50
- if (hotRuntime === void 0 || typeof hotRuntime === "boolean") return;
51
- if (hotRuntime === null || Array.isArray(hotRuntime) || typeof hotRuntime !== "object") throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"hotRuntime" must be a boolean or an options object.`);
52
- const hotOptions = hotRuntime;
53
- for (const key of Object.keys(hotOptions)) if (!KNOWN_HOT_RUNTIME_OPTIONS.includes(key)) {
54
- const suggestion = findClosest(key, KNOWN_HOT_RUNTIME_OPTIONS);
55
- throw new require_errors.VitestNativeTypeError("UNKNOWN_OPTION", `Unknown hotRuntime option "${key}".` + (suggestion ? ` Did you mean '${suggestion}'?` : "") + ` Valid options: ${KNOWN_HOT_RUNTIME_OPTIONS.join(", ")}.`);
56
- }
57
- if (hotOptions.recycleAfterFiles !== void 0) assertNonNegativeInteger(hotOptions.recycleAfterFiles, "hotRuntime.recycleAfterFiles");
58
- if (hotOptions.memoryLimit !== void 0) assertNonNegativeInteger(hotOptions.memoryLimit, "hotRuntime.memoryLimit");
59
- if (hotOptions.preserveGlobals !== void 0) assertStringArray(hotOptions.preserveGlobals, "hotRuntime.preserveGlobals");
60
- if (hotOptions.esmGeneration !== void 0 && typeof hotOptions.esmGeneration !== "boolean") throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"hotRuntime.esmGeneration" must be a boolean.`);
61
- }
62
- function satisfiesMinimum(version, minimum) {
63
- const parse = (v) => v.replace(/^[^0-9]*/, "").split(/[-+]/)[0].split(".").map(Number);
64
- const [aMaj, aMin = 0, aPat = 0] = parse(version);
65
- const [bMaj, bMin = 0, bPat = 0] = parse(minimum);
66
- if (aMaj !== bMaj) return aMaj > bMaj;
67
- if (aMin !== bMin) return aMin > bMin;
68
- return aPat >= bPat;
69
- }
70
- function validatePeerDependency(pkgName, minimumVersion, projectRoot, maximumMajorExclusive, minimumByMajor) {
71
- const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
72
- try {
73
- const { version } = req(req.resolve(`${pkgName}/package.json`));
74
- const major = Number(version.replace(/^[^0-9]*/, "").split(".")[0]);
75
- const requiredMinimum = minimumByMajor?.[major] ?? minimumVersion;
76
- if (!satisfiesMinimum(version, requiredMinimum)) return `vitest-native requires ${pkgName} >= ${requiredMinimum} for ${major}.x, but found ${version}. Please upgrade.`;
77
- if (maximumMajorExclusive !== void 0 && major >= maximumMajorExclusive) return `vitest-native supports ${pkgName} >= ${minimumVersion} and < ${maximumMajorExclusive}, but found ${version}.`;
78
- return null;
79
- } catch {
80
- return `vitest-native requires ${pkgName} >= ${minimumVersion}, but it was not found. Please install it.`;
81
- }
82
- }
83
- function warnUnknownOptions(options) {
84
- for (const key of Object.keys(options)) if (!KNOWN_OPTIONS.includes(key)) {
85
- const suggestion = findClosest(key, KNOWN_OPTIONS);
86
- const hint = suggestion ? ` Did you mean '${suggestion}'?` : "";
87
- console.warn(`[vitest-native] Unknown option '${key}'.${hint}`);
88
- }
89
- }
90
- function findClosest(input, candidates) {
91
- let best = null;
92
- let bestDist = Infinity;
93
- for (const c of candidates) {
94
- const d = levenshtein(input.toLowerCase(), c.toLowerCase());
95
- if (d < bestDist && d <= 3) {
96
- bestDist = d;
97
- best = c;
98
- }
99
- }
100
- return best;
101
- }
102
- function levenshtein(a, b) {
103
- const m = a.length;
104
- const n = b.length;
105
- const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
106
- for (let i = 0; i <= m; i++) dp[i][0] = i;
107
- for (let j = 0; j <= n; j++) dp[0][j] = j;
108
- 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]);
109
- return dp[m][n];
110
- }
111
- //#endregion
112
- //#region src/peer-requirements.ts
113
- const PEER_REQUIREMENTS = [
114
- {
115
- name: "vitest",
116
- minimum: "4.0.0",
117
- maximumMajor: 6
118
- },
119
- {
120
- name: "vite",
121
- minimum: "6.4.2",
122
- maximumMajor: 9,
123
- minimumByMajor: {
124
- 6: "6.4.2",
125
- 7: "7.3.2",
126
- 8: "8.0.5"
127
- }
128
- },
129
- {
130
- name: "react",
131
- minimum: "18.0.0"
132
- },
133
- {
134
- name: "@testing-library/react-native",
135
- minimum: "12.0.0",
136
- maximumMajor: 15,
137
- optional: true
138
- }
139
- ];
140
- //#endregion
141
- //#region src/native/match.mjs
142
- /**
143
- * Which files belong to which package — the one place that decides it.
144
- *
145
- * The native engine splits the module graph between Vite and Node (the rule itself is
146
- * written down in the header of apply.ts). Four places used to answer "does this file
147
- * belong to a Node-owned package?" independently: the externalization patterns handed
148
- * to Vitest, auto-detection, and the transform matchers in the require hook and the
149
- * ESM loader. They agreed by construction rather than by structure, and three of the
150
- * defects in this area were one of them disagreeing with the others — a directory
151
- * anchor the transform side applied and the config side did not, a `node_modules`
152
- * rule that also matched any folder sharing a package's name, and a separator
153
- * mismatch that only appeared on Windows.
154
- *
155
- * Vitest's `server.deps.external` takes patterns rather than a predicate, so config
156
- * time and run time cannot literally call the same function. They can be generated
157
- * from the same rules, which is what `packagePatterns` is for: `buildPkgMatcher`
158
- * tests exactly the patterns that were handed to Vitest.
159
- *
160
- * Everything here is pure. apply.ts bundles a copy into the plugin entry while the
161
- * worker loads this file directly, so it must stay that way — module-level state
162
- * would exist twice.
163
- */
164
- /**
165
- * React Native's own source, including the `@react-native/*` packages. Node owns
166
- * these unconditionally: the Flow strip, the boundary mocks and the precompiled
167
- * registry are all Node loader hooks.
168
- */
169
- const REACT_NATIVE_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
170
- /** Escape a string for literal use inside a RegExp. */
171
- function escapeRe(value) {
172
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
173
- }
174
- /** Forward slashes, the form Vitest presents module ids in. */
175
- function toPosix(value) {
176
- return value.replace(/\\/g, "/");
177
- }
178
- /**
179
- * Does `dir` contain `target` (or equal it)?
180
- *
181
- * Used to recognise the package the run lives in. A package directory containing the
182
- * Vitest root is the project, not a dependency of it — externalizing it hands Vitest
183
- * its own source and test files back through Node, where they are compiled to
184
- * CommonJS.
185
- *
186
- * Compared case-insensitively on Windows: `require.resolve` reports the on-disk
187
- * casing while a working directory carries whatever the shell supplied, and a
188
- * drive-letter difference alone would silently defeat the check.
189
- */
190
- function containsPath(dir, target) {
191
- const normalize = (value) => {
192
- const resolved = node_path.default.resolve(value);
193
- return process.platform === "win32" ? resolved.toLowerCase() : resolved;
194
- };
195
- const outer = normalize(dir);
196
- const inner = normalize(target);
197
- return inner === outer || inner.startsWith(outer.endsWith(node_path.default.sep) ? outer : outer + node_path.default.sep);
198
- }
199
- /**
200
- * The on-disk directory a package resolves to, or null.
201
- *
202
- * `pkg/package.json` is tried first because it names the package root exactly; some
203
- * packages do not export it, so fall back to resolving the entry and walking up to
204
- * the manifest that names them. Symlinked and workspace packages resolve to their
205
- * real location, which is the whole point — see buildPkgMatcher.
206
- */
207
- function packageDirOf(name, projectRoot) {
208
- const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
209
- try {
210
- return node_path.default.dirname(req.resolve(`${name}/package.json`));
211
- } catch {}
212
- let dir;
213
- try {
214
- dir = node_path.default.dirname(req.resolve(name));
215
- } catch {
216
- return null;
217
- }
218
- for (;;) {
219
- try {
220
- if ((0, node_module.createRequire)(node_path.default.join(dir, "index.js"))("./package.json").name === name) return dir;
221
- } catch {}
222
- const parent = node_path.default.dirname(dir);
223
- if (parent === dir) return null;
224
- dir = parent;
225
- }
226
- }
227
- /**
228
- * The patterns identifying one package's files. THE rule; everything else composes it.
229
- *
230
- * A bare `[/\]name[/\]` test — what this used to be — also matches any DIRECTORY
231
- * that happens to share a package's name. A project folder called `expo`, or a source
232
- * directory named after the library it implements, made every file beneath it look
233
- * like third-party source to be compiled. That mis-compiled unrelated files, this
234
- * package's own runtime among them.
235
- *
236
- * Anchoring on `node_modules` alone would fix that and break linked packages: a
237
- * workspace or `file:` dependency resolves to its real path, which has no
238
- * `node_modules` segment at all. So a file matches if it is either
239
- *
240
- * - under `node_modules/<name>/` (covers additional copies of a package that a
241
- * single resolution cannot see, and projects where resolution fails), or
242
- * - inside the package's resolved directory (exact; covers workspace links, and
243
- * stores like pnpm's and bun's).
244
- *
245
- * The resolved-directory anchor is dropped when that directory CONTAINS the project
246
- * root, because then it is the project. Externalizing the project hands Vitest its
247
- * own source and test files back through Node, which compiles them to CommonJS: a
248
- * test file's `import { it } from 'vitest'` becomes `require('vitest')` and throws.
249
- *
250
- * `projectRoot` is optional; without it only the `node_modules` rule applies, since
251
- * there is nothing to resolve against.
252
- */
253
- function packagePatterns(name, projectRoot) {
254
- const patterns = [new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe(name)}[\\\\/]`)];
255
- if (!projectRoot) return patterns;
256
- const dir = packageDirOf(name, projectRoot);
257
- if (dir && !containsPath(dir, projectRoot)) patterns.push(new RegExp(`^${escapeRe(toPosix(dir).replace(/\/$/, ""))}[\\\\/]`));
258
- return patterns;
259
- }
260
- /**
261
- * The native engine's dependencies that do NOT resolve from the project root.
262
- *
263
- * react-native itself is part of the check: the Babel toolchain alone chose
264
- * native mode in a project with the preset installed but no react-native — an
265
- * incomplete install, a babel-only workspace — which then failed later at RN
266
- * resolution with nothing pointing at the cause. Resolution, not declaration:
267
- * every check walks node_modules upward from the root — so a hoisted workspace
268
- * install or Expo's transitive react-native counts, and a project does not need
269
- * react-native in its own manifest.
270
- */
271
- function missingNativeDeps(projectRoot) {
272
- const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
273
- const missing = [];
274
- if (!reactNativeInstalledNear(projectRoot)) missing.push("react-native");
275
- for (const dep of ["@react-native/babel-preset", "@babel/core"]) try {
276
- req.resolve(dep);
277
- } catch {
278
- missing.push(dep);
279
- }
280
- return missing;
281
- }
282
- /** Does node_modules/react-native exist in projectRoot or any ancestor? */
283
- function reactNativeInstalledNear(projectRoot) {
284
- let dir = node_path.default.resolve(projectRoot);
285
- for (;;) {
286
- if (node_fs.default.existsSync(node_path.default.join(dir, "node_modules", "react-native", "package.json"))) return true;
287
- const parent = node_path.default.dirname(dir);
288
- if (parent === dir) return false;
289
- dir = parent;
290
- }
291
- }
292
- /** Resolve the concrete engine for a run. Pure; never throws. */
293
- function detectEngine(requested, projectRoot, opts) {
294
- const missing = missingNativeDeps(projectRoot);
295
- const nativeAvailable = missing.length === 0;
296
- if (requested === "native") return {
297
- engine: "native",
298
- nativeAvailable,
299
- missing,
300
- notice: null
301
- };
302
- if (requested === "mock") return {
303
- engine: "mock",
304
- nativeAvailable,
305
- missing,
306
- notice: null
307
- };
308
- const prefersNative = opts?.autoPrefersNative ?? true;
309
- if (prefersNative && nativeAvailable) return {
310
- engine: "native",
311
- nativeAvailable,
312
- missing,
313
- notice: null
314
- };
315
- if (prefersNative) return {
316
- engine: "mock",
317
- nativeAvailable: false,
318
- missing,
319
- notice: `[vitest-native] ${missing.join(", ")} not found — using the mock engine. Install what's missing to run real React Native, or set engine:'mock' to silence this.`
320
- };
321
- return {
322
- engine: "mock",
323
- nativeAvailable,
324
- missing,
325
- notice: null
326
- };
327
- }
328
- //#endregion
329
- //#region src/native/ecosystem.ts
330
- /**
331
- * Packages that must never be auto-inlined even though they depend on React
332
- * Native. The test library and the renderers underneath it are infrastructure the
333
- * engine itself wires up; pulling a second copy of them into the module graph has
334
- * corrupted rendering before, in ways that surface as unrelated act() and
335
- * host-component failures.
336
- *
337
- * This list is one clause of the ownership rule; the whole of it is written down in
338
- * the header of native/apply.ts, which is the file to read before changing what ends
339
- * up in either graph.
340
- */
341
- const NEVER_INLINE = /* @__PURE__ */ new Set([
342
- "@testing-library/react-native",
343
- "react-test-renderer",
344
- "test-renderer",
345
- "react-native",
346
- "react",
347
- "react-is"
348
- ]);
349
- /** Does this manifest offer a React Native build, by legacy field or export condition? */
350
- function hasReactNativeBuild(manifest) {
351
- if (typeof manifest["react-native"] === "string") return true;
352
- const seen = /* @__PURE__ */ new Set();
353
- const search = (node) => {
354
- if (!node || typeof node !== "object" || seen.has(node)) return false;
355
- seen.add(node);
356
- for (const [key, value] of Object.entries(node)) {
357
- if (key === "react-native") return true;
358
- if (search(value)) return true;
359
- }
360
- return false;
361
- };
362
- return search(manifest.exports);
363
- }
364
- /**
365
- * A package that ships ES modules and nothing React Native.
366
- *
367
- * The closure walk is a guess: a detected package's dependencies MIGHT be untranspiled
368
- * React Native source, because the ecosystem publishes that way and the dependency's
369
- * own manifest cannot say so. `"type": "module"` is the manifest saying the opposite —
370
- * this is runnable ES modules — and with no React Native build anywhere in it, there is
371
- * nothing for the preset to do. Compiling it anyway rewrites a package that publishes
372
- * ESM into CommonJS and hands it to Node under that format, which is how a dependency
373
- * reached this way (`zod`) failed to parse and took fourteen test files down with it.
374
- *
375
- * A genuine React Native library is unaffected: declaring `react-native` by field or
376
- * export condition keeps it in the closure however it publishes.
377
- *
378
- * Only closure MEMBERS are judged this way. A package detected on its own manifest, or
379
- * named in `transform: [...]`, was asked for explicitly and is still compiled.
380
- */
381
- function publishesOnlyEsm(manifest) {
382
- return manifest.type === "module" && !hasReactNativeBuild(manifest);
383
- }
384
- /** Manifest fields that make a package part of the React Native ecosystem. */
385
- function dependsOnReactNative(manifest) {
386
- for (const field of ["dependencies", "peerDependencies"]) {
387
- const deps = manifest[field];
388
- if (deps && typeof deps === "object" && "react-native" in deps) return true;
389
- }
390
- return false;
391
- }
392
- /**
393
- * Every package manifest from the project up to the filesystem root.
394
- *
395
- * A workspace does not always declare its dependencies where the tests run: an app
396
- * package may inherit React Native libraries from the repository root, and a Vitest
397
- * `root` can point at a directory above or below the package that owns them. Reading
398
- * only the project's own manifest silently found nothing in those layouts and sent
399
- * the user back to maintaining `transform: [...]` by hand.
400
- *
401
- * Over-collecting is safe and under-collecting is not: a package that is listed but
402
- * never imported costs nothing, because inlining only applies to files that are
403
- * actually loaded.
404
- */
405
- /**
406
- * Directories of the workspace members a manifest declares, plus any listed in a
407
- * sibling pnpm-workspace.yaml.
408
- *
409
- * Needed because `manifestsFrom` only walks UP. In a workspace the run root is
410
- * frequently ABOVE the package under test — Nx invokes tasks from the workspace
411
- * root, and Vitest's root defaults to the working directory — so the app's own
412
- * dependencies are declared in a manifest that walking up never reaches. The
413
- * package then misses auto-detection and stays in Vite's graph while Node loads it
414
- * too, which is the dual-ownership failure reproducing from nothing but a different
415
- * working directory.
416
- *
417
- * Only the two glob shapes workspace fields actually use are expanded (`dir/*` and a
418
- * literal path). Over-collecting is safe here — an unimported package costs nothing —
419
- * so a shape that is not understood is skipped rather than approximated.
420
- */
421
- function workspaceMemberDirs(dir, manifest) {
422
- const patterns = [];
423
- const declared = manifest.workspaces;
424
- if (Array.isArray(declared)) patterns.push(...declared.filter((p) => typeof p === "string"));
425
- else if (declared && typeof declared === "object" && Array.isArray(declared.packages)) patterns.push(...declared.packages.filter((p) => typeof p === "string"));
426
- try {
427
- const yaml = node_fs.default.readFileSync(node_path.default.join(dir, "pnpm-workspace.yaml"), "utf8");
428
- for (const line of yaml.split(/\r?\n/)) {
429
- const entry = /^\s*-\s*["']?([^"'#]+?)["']?\s*$/.exec(line);
430
- if (entry) patterns.push(entry[1]);
431
- }
432
- } catch {}
433
- const dirs = [];
434
- for (const pattern of patterns) if (pattern.endsWith("/*")) {
435
- const parent = node_path.default.join(dir, pattern.slice(0, -2));
436
- try {
437
- for (const entry of node_fs.default.readdirSync(parent, { withFileTypes: true })) if (entry.isDirectory()) dirs.push(node_path.default.join(parent, entry.name));
438
- } catch {}
439
- } else if (!pattern.includes("*")) dirs.push(node_path.default.join(dir, pattern));
440
- return dirs;
441
- }
442
- function manifestsFrom(projectRoot) {
443
- const manifests = [];
444
- let dir = node_path.default.resolve(projectRoot);
445
- for (;;) {
446
- try {
447
- const raw = node_fs.default.readFileSync(node_path.default.join(dir, "package.json"), "utf8");
448
- const manifest = JSON.parse(raw);
449
- manifests.push({
450
- dir,
451
- manifest
452
- });
453
- for (const member of workspaceMemberDirs(dir, manifest)) try {
454
- manifests.push({
455
- dir: member,
456
- manifest: JSON.parse(node_fs.default.readFileSync(node_path.default.join(member, "package.json"), "utf8"))
457
- });
458
- } catch {}
459
- } catch {}
460
- const parent = node_path.default.dirname(dir);
461
- if (parent === dir) return manifests;
462
- dir = parent;
463
- }
464
- }
465
- /**
466
- * Packages in the project that declare React Native in their own manifest.
467
- *
468
- * These are the ones published the way the React Native ecosystem publishes:
469
- * untranspiled JSX, Flow, or TypeScript, on the assumption that Metro will compile
470
- * them. Node cannot run that source, which is why they previously had to be listed
471
- * by hand in `transform: [...]` — a list every project had to discover the hard way,
472
- * one `SyntaxError: Unexpected token '<'` at a time.
473
- *
474
- * A package's own manifest is the authority here rather than a heuristic on its
475
- * name: `react-native-*` misses `@gorhom/bottom-sheet` and would wrongly claim
476
- * `react-native` itself, while the manifest states the relationship exactly.
477
- *
478
- * Declared dependencies are read from the project and every manifest above it, so a
479
- * workspace that declares its React Native libraries at the repository root is covered
480
- * too. Resolving each name is cheap and package-manager-agnostic, where walking the
481
- * installed tree depends on the store layout. Transitive dependencies that nothing
482
- * declares stay available through `transform: [...]`.
483
- *
484
- * Excluded: packages a preset already shadows (their real source never loads), the
485
- * test infrastructure in NEVER_INLINE, and anything the consumer listed explicitly
486
- * in `transform` — that option keeps its existing meaning and takes precedence.
487
- */
488
- function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], neverTransform = []) {
489
- const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
490
- const skip = /* @__PURE__ */ new Set([
491
- ...NEVER_INLINE,
492
- ...Object.keys(require_preset_map.AUTO_DETECT_PRESETS),
493
- ...explicit,
494
- ...neverTransform
495
- ]);
496
- const candidates = /* @__PURE__ */ new Set();
497
- const found = roots.flatMap((root) => manifestsFrom(root));
498
- const requires = [...new Set(found.map((entry) => entry.dir))].map((dir) => (0, node_module.createRequire)(node_path.default.join(dir, "package.json")));
499
- for (const { manifest } of found) for (const field of [
500
- "dependencies",
501
- "devDependencies",
502
- "optionalDependencies"
503
- ]) {
504
- const deps = manifest[field];
505
- if (deps && typeof deps === "object") for (const name of Object.keys(deps)) candidates.add(name);
506
- }
507
- if (candidates.size === 0) return [];
508
- /** Resolve a package's manifest from whichever root can see it. */
509
- const manifestOf = (name) => {
510
- for (const req of requires) try {
511
- return req(`${name}/package.json`);
512
- } catch {}
513
- return null;
514
- };
515
- /**
516
- * The packages the run itself lives in — the project, in other words.
517
- *
518
- * In a workspace, the package under test is usually declared as a dependency by a
519
- * sibling or by the repository root, so it appears in the candidate set like any
520
- * third-party library — and it declares React Native, because it is React Native
521
- * code. Detecting it would claim the project's own source: its directory becomes a
522
- * `server.deps.external` pattern, so Vitest hands every file under it to Node,
523
- * where the loader compiles it to CommonJS. A test file's own
524
- * `import { it } from 'vitest'` becomes `require('vitest')`, which throws
525
- * "Vitest cannot be imported in a CommonJS module using require()" — a failure that
526
- * appears in one workspace package and not another for no visible reason.
527
- *
528
- * A package cannot be its own dependency, so a manifest whose directory contains a
529
- * run root belongs to the project. Read straight off the manifests already walked,
530
- * which is both cheaper than resolving each candidate and independent of how a
531
- * package manager happens to lay out its store — under pnpm every workspace member
532
- * is additionally linked into a hidden directory on NODE_PATH, so a package can
533
- * resolve its own name from its own directory, but nothing here depends on that.
534
- *
535
- * Workspace libraries the project merely depends on sit beside a run root rather
536
- * than above it and are unaffected — detecting those is the point of the
537
- * workspace-member walk above.
538
- */
539
- const ownerRoots = [...roots, ...testRoots];
540
- const runOwners = new Set(found.filter(({ dir }) => ownerRoots.some((root) => containsPath(dir, root))).map(({ manifest }) => manifest.name).filter((name) => typeof name === "string"));
541
- const ownsTheRun = (name) => runOwners.has(name);
542
- const detected = [];
543
- for (const name of candidates) {
544
- if (skip.has(name) || name.startsWith("@react-native/")) continue;
545
- const pkg = manifestOf(name);
546
- if (pkg && dependsOnReactNative(pkg) && !ownsTheRun(name)) detected.push(name);
547
- }
548
- const rnOwned = new Set(Object.keys(manifestOf("react-native")?.dependencies ?? {}));
549
- /** Every package reachable from `roots` through runtime dependencies. */
550
- const closureOf = (starts) => {
551
- const seen = /* @__PURE__ */ new Set();
552
- const pending = [...starts];
553
- while (pending.length > 0) {
554
- const name = pending.pop();
555
- if (seen.has(name)) continue;
556
- seen.add(name);
557
- const deps = manifestOf(name)?.dependencies;
558
- if (deps && typeof deps === "object") pending.push(...Object.keys(deps));
559
- }
560
- return seen;
561
- };
562
- const toolchain = closureOf([
563
- "@babel/core",
564
- "@react-native/babel-preset",
565
- "@babel/runtime",
566
- "metro"
567
- ]);
568
- const projectDeclared = /* @__PURE__ */ new Set();
569
- for (const { dir, manifest } of found) {
570
- if (!ownerRoots.some((root) => containsPath(dir, root))) continue;
571
- for (const field of [
572
- "dependencies",
573
- "devDependencies",
574
- "optionalDependencies"
575
- ]) {
576
- const deps = manifest[field];
577
- if (deps && typeof deps === "object") for (const name of Object.keys(deps)) projectDeclared.add(name);
578
- }
579
- }
580
- const inClosure = new Set(detected);
581
- const queue = detected.filter((name) => projectDeclared.has(name));
582
- while (queue.length > 0) {
583
- const deps = manifestOf(queue.pop())?.dependencies;
584
- if (!deps || typeof deps !== "object") continue;
585
- for (const dep of Object.keys(deps)) {
586
- if (inClosure.has(dep) || skip.has(dep) || dep.startsWith("@react-native/")) continue;
587
- if (rnOwned.has(dep)) continue;
588
- if (toolchain.has(dep)) continue;
589
- if (ownsTheRun(dep)) continue;
590
- const depManifest = manifestOf(dep);
591
- if (!depManifest) continue;
592
- if (publishesOnlyEsm(depManifest)) continue;
593
- inClosure.add(dep);
594
- queue.push(dep);
595
- }
596
- }
597
- return [...inClosure].sort();
598
- }
599
- //#endregion
600
- Object.defineProperty(exports, "PEER_REQUIREMENTS", {
601
- enumerable: true,
602
- get: function() {
603
- return PEER_REQUIREMENTS;
604
- }
605
- });
606
- Object.defineProperty(exports, "REACT_NATIVE_PATH", {
607
- enumerable: true,
608
- get: function() {
609
- return REACT_NATIVE_PATH;
610
- }
611
- });
612
- Object.defineProperty(exports, "containsPath", {
613
- enumerable: true,
614
- get: function() {
615
- return containsPath;
616
- }
617
- });
618
- Object.defineProperty(exports, "detectEcosystemPackages", {
619
- enumerable: true,
620
- get: function() {
621
- return detectEcosystemPackages;
622
- }
623
- });
624
- Object.defineProperty(exports, "detectEngine", {
625
- enumerable: true,
626
- get: function() {
627
- return detectEngine;
628
- }
629
- });
630
- Object.defineProperty(exports, "packageDirOf", {
631
- enumerable: true,
632
- get: function() {
633
- return packageDirOf;
634
- }
635
- });
636
- Object.defineProperty(exports, "packagePatterns", {
637
- enumerable: true,
638
- get: function() {
639
- return packagePatterns;
640
- }
641
- });
642
- Object.defineProperty(exports, "validateOptions", {
643
- enumerable: true,
644
- get: function() {
645
- return validateOptions;
646
- }
647
- });
648
- Object.defineProperty(exports, "validatePeerDependency", {
649
- enumerable: true,
650
- get: function() {
651
- return validatePeerDependency;
652
- }
653
- });
654
- Object.defineProperty(exports, "warnUnknownOptions", {
655
- enumerable: true,
656
- get: function() {
657
- return warnUnknownOptions;
658
- }
659
- });