vitest-native 0.14.0-rc.9 → 0.14.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 (97) hide show
  1. package/README.md +76 -60
  2. package/dist/cli.d.mts +1 -3
  3. package/dist/cli.mjs +175 -63
  4. package/dist/context.d.mts +45 -0
  5. package/dist/context.mjs +243 -0
  6. package/dist/errors.d.mts +3 -0
  7. package/dist/helpers.cjs +53 -4
  8. package/dist/helpers.d.cts +1 -3
  9. package/dist/helpers.d.mts +1 -3
  10. package/dist/helpers.mjs +2 -3
  11. package/dist/host-5o48Ujzs.mjs +939 -0
  12. package/dist/{index-CzQazgp9.d.cts → index-DqU4YO3D.d.mts} +27 -49
  13. package/dist/index.d.mts +1 -3
  14. package/dist/index.mjs +463 -595
  15. package/dist/jest-compat/error-equality.mjs +127 -0
  16. package/dist/jest-compat/jest-object.mjs +149 -4
  17. package/dist/jest-compat/node-registry.mjs +233 -58
  18. package/dist/jest-compat/setup.mjs +28 -4
  19. package/dist/jest-compat.cjs +227 -52
  20. package/dist/jest-compat.d.cts +5 -6
  21. package/dist/jest-compat.d.mts +5 -6
  22. package/dist/jest-compat.mjs +204 -52
  23. package/dist/matchers.cjs +1 -2
  24. package/dist/matchers.d.cts +0 -2
  25. package/dist/matchers.d.mts +0 -2
  26. package/dist/matchers.mjs +1 -2
  27. package/dist/{memory-FYbP0_gg.mjs → memory-Couw0Esx.mjs} +31 -6
  28. package/dist/native/assets.d.mts +2 -0
  29. package/dist/native/assets.mjs +34 -0
  30. package/dist/native/babel-toolchain.mjs +190 -0
  31. package/dist/native/babel-worker.mjs +47 -0
  32. package/dist/native/boundary.mjs +23 -8
  33. package/dist/native/compile-cache.mjs +21 -9
  34. package/dist/native/coverage-v8.mjs +287 -0
  35. package/dist/native/esm-interop.mjs +216 -0
  36. package/dist/native/expo-native-modules.mjs +7 -1
  37. package/dist/native/globals.mjs +104 -6
  38. package/dist/native/hooks.mjs +271 -60
  39. package/dist/native/loader.mjs +378 -20
  40. package/dist/native/match.d.mts +24 -2
  41. package/dist/native/match.mjs +117 -12
  42. package/dist/native/metro-profile-compiler.mjs +2 -31
  43. package/dist/native/module-reset.mjs +37 -5
  44. package/dist/native/native-modules.d.mts +2 -3
  45. package/dist/native/native-modules.mjs +22 -21
  46. package/dist/native/ownership.d.mts +10 -0
  47. package/dist/native/ownership.mjs +96 -9
  48. package/dist/native/registry-compiler.mjs +6 -0
  49. package/dist/native/registry.mjs +138 -119
  50. package/dist/native/resident-health.mjs +133 -0
  51. package/dist/native/resolve.d.mts +6 -0
  52. package/dist/native/resolve.mjs +100 -9
  53. package/dist/native/rntl-hooks.mjs +157 -6
  54. package/dist/native/rntl-text-host.mjs +64 -0
  55. package/dist/native/runner.mjs +73 -0
  56. package/dist/native/setup.mjs +96 -70
  57. package/dist/native/state-manifest.mjs +14 -8
  58. package/dist/native/transform.d.mts +2 -0
  59. package/dist/native/transform.mjs +476 -59
  60. package/dist/native/worker.mjs +65 -36
  61. package/dist/{pool-DjpOjOf3.mjs → pool-CFSpNfyw.mjs} +37 -11
  62. package/dist/{preset-map-BlBriTA0.mjs → preset-map-CogjYmSw.mjs} +4 -19
  63. package/dist/preset-modules.mjs +2 -11
  64. package/dist/{presets--zrEWQC2.mjs → presets-CXDyg51l.mjs} +65 -82
  65. package/dist/presets.d.mts +1 -1
  66. package/dist/presets.mjs +1 -1
  67. package/dist/report-error.d.mts +20 -0
  68. package/dist/report-error.mjs +145 -0
  69. package/dist/rntl-support.d.mts +12 -0
  70. package/dist/rntl-support.mjs +189 -0
  71. package/dist/{rolldown-runtime-BhDjJH2R.mjs → rolldown-runtime-D70C1uOS.mjs} +1 -2
  72. package/dist/serializer.cjs +1 -2
  73. package/dist/serializer.d.cts +1 -3
  74. package/dist/serializer.d.mts +1 -3
  75. package/dist/serializer.mjs +1 -2
  76. package/dist/setup.mjs +95 -156
  77. package/dist/{worker-vitest-BGPo0ek6.mjs → worker-vitest-CILPFeRX.mjs} +2 -3
  78. package/docs/migrating-from-jest.md +76 -12
  79. package/docs/release-readiness.md +1 -1
  80. package/package.json +119 -102
  81. package/CHANGELOG.md +0 -2491
  82. package/dist/cli.cjs +0 -1951
  83. package/dist/cli.d.cts +0 -3
  84. package/dist/ecosystem-D6e1OVOg.mjs +0 -1019
  85. package/dist/ecosystem-MFwkbnaC.cjs +0 -1099
  86. package/dist/errors-B3lJK46O.cjs +0 -75
  87. package/dist/errors-CxoBUfVJ.mjs +0 -64
  88. package/dist/index-xw43lBlv.d.mts +0 -481
  89. package/dist/memory-6EPHrJA1.cjs +0 -144
  90. package/dist/pool-B4yesGhI.cjs +0 -121
  91. package/dist/preset-map-jSFsNy1Q.cjs +0 -241
  92. package/dist/preset-modules-BoLkaeEN.cjs +0 -53
  93. package/dist/preset-modules-CG8-G82P.mjs +0 -36
  94. package/dist/presets-9f83H0WW.cjs +0 -3939
  95. package/dist/rolldown-runtime-C0BPl7ul.cjs +0 -43
  96. package/dist/worker-vitest-BfiQB8ND.cjs +0 -62
  97. package/docs/hot-default-design.md +0 -216
@@ -1,1019 +0,0 @@
1
- import { n as VitestNativeTypeError } from "./errors-CxoBUfVJ.mjs";
2
- import { t as AUTO_DETECT_PRESETS } from "./preset-map-BlBriTA0.mjs";
3
- import { createRequire } from "node:module";
4
- import fs from "node:fs";
5
- import path from "node:path";
6
- //#region src/validate.ts
7
- const KNOWN_OPTIONS = [
8
- "platform",
9
- "presets",
10
- "mocks",
11
- "diagnostics",
12
- "assetExts",
13
- "metroConfig",
14
- "engine",
15
- "transform",
16
- "hotRuntime",
17
- "nativeModules"
18
- ];
19
- const KNOWN_HOT_RUNTIME_OPTIONS = [
20
- "recycleAfterFiles",
21
- "memoryLimit",
22
- "allowUnboundedMemory",
23
- "preserveGlobals",
24
- "esmGeneration"
25
- ];
26
- const KNOWN_METRO_CONFIG_OPTIONS = ["configFile"];
27
- function assertStringArray(value, option) {
28
- if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.length === 0)) throw new VitestNativeTypeError("INVALID_OPTION", `"${option}" must be an array of non-empty strings.`);
29
- }
30
- function assertNonNegativeInteger(value, option) {
31
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new VitestNativeTypeError("INVALID_OPTION", `"${option}" must be a non-negative safe integer.`);
32
- }
33
- function validateOptions(options) {
34
- if (options.engine !== void 0 && options.engine !== "auto" && options.engine !== "mock" && options.engine !== "native") throw new VitestNativeTypeError("INVALID_OPTION", `"engine" must be "auto", "mock", or "native".`);
35
- if (options.platform !== void 0 && options.platform !== "ios" && options.platform !== "android") throw new VitestNativeTypeError("INVALID_OPTION", `"platform" must be "ios" or "android".`);
36
- if (options.nativeModules !== void 0 && options.nativeModules !== "device" && options.nativeModules !== "permissive") throw new VitestNativeTypeError("INVALID_OPTION", `"nativeModules" must be "device" or "permissive".`);
37
- if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"diagnostics" must be a boolean.`);
38
- if (options.assetExts !== void 0) assertStringArray(options.assetExts, "assetExts");
39
- if (options.metroConfig !== void 0 && typeof options.metroConfig !== "boolean") {
40
- if (options.metroConfig === null || Array.isArray(options.metroConfig) || typeof options.metroConfig !== "object") throw new VitestNativeTypeError("INVALID_OPTION", `"metroConfig" must be a boolean or an options object.`);
41
- const metro = options.metroConfig;
42
- const unknown = Object.keys(metro).filter((key) => !KNOWN_METRO_CONFIG_OPTIONS.includes(key));
43
- if (unknown.length > 0) throw new VitestNativeTypeError("UNKNOWN_OPTION", `Unknown metroConfig option "${unknown[0]}". Valid options: ${KNOWN_METRO_CONFIG_OPTIONS.join(", ")}.`);
44
- if (metro.configFile !== void 0 && (typeof metro.configFile !== "string" || !metro.configFile.trim())) throw new VitestNativeTypeError("INVALID_OPTION", `"metroConfig.configFile" must be a non-empty string.`);
45
- }
46
- if (options.transform !== void 0) {
47
- if (Array.isArray(options.transform)) assertStringArray(options.transform, "transform");
48
- else if (options.transform !== null && typeof options.transform === "object") {
49
- const shape = options.transform;
50
- const unknownKeys = Object.keys(shape).filter((k) => k !== "include" && k !== "exclude");
51
- if (unknownKeys.length > 0) throw new VitestNativeTypeError("INVALID_OPTION", `"transform" accepts only "include" and "exclude"; received ${unknownKeys.map((k) => `"${k}"`).join(", ")}.`);
52
- if (shape.include !== void 0) assertStringArray(shape.include, "transform.include");
53
- if (shape.exclude !== void 0) assertStringArray(shape.exclude, "transform.exclude");
54
- } else throw new VitestNativeTypeError("INVALID_OPTION", `"transform" must be an array of package names, or an object with "include" and/or "exclude".`);
55
- }
56
- if (options.presets !== void 0 && !Array.isArray(options.presets)) {
57
- if (!(options.presets !== null && typeof options.presets === "object" && Object.values(options.presets).every((v) => typeof v === "boolean"))) throw new 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 }).");
58
- }
59
- if (options.mocks !== void 0 && (options.mocks === null || Array.isArray(options.mocks) || typeof options.mocks !== "object")) throw new VitestNativeTypeError("INVALID_OPTION", `"mocks" must be a plain object.`);
60
- const hotRuntime = options.hotRuntime;
61
- if (hotRuntime === void 0 || typeof hotRuntime === "boolean" || hotRuntime === "auto") return;
62
- if (hotRuntime === null || Array.isArray(hotRuntime) || typeof hotRuntime !== "object") throw new VitestNativeTypeError("INVALID_OPTION", `"hotRuntime" must be a boolean, "auto", or an options object.`);
63
- const hotOptions = hotRuntime;
64
- for (const key of Object.keys(hotOptions)) if (!KNOWN_HOT_RUNTIME_OPTIONS.includes(key)) {
65
- const suggestion = findClosest(key, KNOWN_HOT_RUNTIME_OPTIONS);
66
- throw new VitestNativeTypeError("UNKNOWN_OPTION", `Unknown hotRuntime option "${key}".` + (suggestion ? ` Did you mean '${suggestion}'?` : "") + ` Valid options: ${KNOWN_HOT_RUNTIME_OPTIONS.join(", ")}.`);
67
- }
68
- if (hotOptions.recycleAfterFiles !== void 0) assertNonNegativeInteger(hotOptions.recycleAfterFiles, "hotRuntime.recycleAfterFiles");
69
- if (hotOptions.memoryLimit !== void 0) assertNonNegativeInteger(hotOptions.memoryLimit, "hotRuntime.memoryLimit");
70
- if (hotOptions.allowUnboundedMemory !== void 0 && typeof hotOptions.allowUnboundedMemory !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"hotRuntime.allowUnboundedMemory" must be a boolean.`);
71
- if (hotOptions.preserveGlobals !== void 0) assertStringArray(hotOptions.preserveGlobals, "hotRuntime.preserveGlobals");
72
- if (hotOptions.esmGeneration !== void 0 && typeof hotOptions.esmGeneration !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"hotRuntime.esmGeneration" must be a boolean.`);
73
- }
74
- function satisfiesMinimum(version, minimum) {
75
- const parse = (v) => v.replace(/^[^0-9]*/, "").split(/[-+]/)[0].split(".").map(Number);
76
- const [aMaj, aMin = 0, aPat = 0] = parse(version);
77
- const [bMaj, bMin = 0, bPat = 0] = parse(minimum);
78
- if (aMaj !== bMaj) return aMaj > bMaj;
79
- if (aMin !== bMin) return aMin > bMin;
80
- return aPat >= bPat;
81
- }
82
- function validatePeerDependency(pkgName, minimumVersion, projectRoot, maximumMajorExclusive, minimumByMajor) {
83
- const req = createRequire(path.join(projectRoot, "package.json"));
84
- try {
85
- const { version } = req(req.resolve(`${pkgName}/package.json`));
86
- const major = Number(version.replace(/^[^0-9]*/, "").split(".")[0]);
87
- const requiredMinimum = minimumByMajor?.[major] ?? minimumVersion;
88
- if (!satisfiesMinimum(version, requiredMinimum)) return `vitest-native requires ${pkgName} >= ${requiredMinimum} for ${major}.x, but found ${version}. Please upgrade.`;
89
- if (maximumMajorExclusive !== void 0 && major >= maximumMajorExclusive) return `vitest-native supports ${pkgName} >= ${minimumVersion} and < ${maximumMajorExclusive}, but found ${version}.`;
90
- return null;
91
- } catch {
92
- return `vitest-native requires ${pkgName} >= ${minimumVersion}, but it was not found. Please install it.`;
93
- }
94
- }
95
- function warnUnknownOptions(options) {
96
- for (const key of Object.keys(options)) if (!KNOWN_OPTIONS.includes(key)) {
97
- const suggestion = findClosest(key, KNOWN_OPTIONS);
98
- const hint = suggestion ? ` Did you mean '${suggestion}'?` : "";
99
- console.warn(`[vitest-native] Unknown option '${key}'.${hint}`);
100
- }
101
- }
102
- function findClosest(input, candidates) {
103
- let best = null;
104
- let bestDist = Infinity;
105
- for (const c of candidates) {
106
- const d = levenshtein(input.toLowerCase(), c.toLowerCase());
107
- if (d < bestDist && d <= 3) {
108
- bestDist = d;
109
- best = c;
110
- }
111
- }
112
- return best;
113
- }
114
- function levenshtein(a, b) {
115
- const m = a.length;
116
- const n = b.length;
117
- const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
118
- for (let i = 0; i <= m; i++) dp[i][0] = i;
119
- for (let j = 0; j <= n; j++) dp[0][j] = j;
120
- 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]);
121
- return dp[m][n];
122
- }
123
- //#endregion
124
- //#region src/peer-requirements.ts
125
- const PEER_REQUIREMENTS = [
126
- {
127
- name: "vitest",
128
- minimum: "4.0.0",
129
- maximumMajor: 6
130
- },
131
- {
132
- name: "vite",
133
- minimum: "6.4.2",
134
- maximumMajor: 9,
135
- minimumByMajor: {
136
- 6: "6.4.2",
137
- 7: "7.3.2",
138
- 8: "8.0.5"
139
- }
140
- },
141
- {
142
- name: "react",
143
- minimum: "18.0.0"
144
- },
145
- {
146
- name: "@testing-library/react-native",
147
- minimum: "12.0.0",
148
- maximumMajor: 15,
149
- optional: true
150
- }
151
- ];
152
- //#endregion
153
- //#region src/native/match.mjs
154
- /**
155
- * Which files belong to which package — the one place that decides it.
156
- *
157
- * The native engine splits the module graph between Vite and Node (the rule itself is
158
- * written down in the header of apply.ts). Four places used to answer "does this file
159
- * belong to a Node-owned package?" independently: the externalization patterns handed
160
- * to Vitest, auto-detection, and the transform matchers in the require hook and the
161
- * ESM loader. They agreed by construction rather than by structure, and three of the
162
- * defects in this area were one of them disagreeing with the others — a directory
163
- * anchor the transform side applied and the config side did not, a `node_modules`
164
- * rule that also matched any folder sharing a package's name, and a separator
165
- * mismatch that only appeared on Windows.
166
- *
167
- * Vitest's `server.deps.external` takes patterns rather than a predicate, so config
168
- * time and run time cannot literally call the same function. They can be generated
169
- * from the same rules, which is what `packagePatterns` is for: `buildPkgMatcher`
170
- * tests exactly the patterns that were handed to Vitest.
171
- *
172
- * Everything here is pure. apply.ts bundles a copy into the plugin entry while the
173
- * worker loads this file directly, so it must stay that way — module-level state
174
- * would exist twice.
175
- */
176
- /** Any file under a node_modules directory. */
177
- const NODE_MODULES_PATH = /[\\/]node_modules[\\/]/;
178
- /**
179
- * React Native's own source, including the `@react-native/*` packages. Node owns
180
- * these unconditionally: the Flow strip, the boundary mocks and the precompiled
181
- * registry are all Node loader hooks.
182
- */
183
- const REACT_NATIVE_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
184
- /**
185
- * A directory in the form Node's module loader reports paths: fs.realpathSync, not
186
- * realpathSync.native. The native call expands Windows 8.3 short names (RUNNER~1) and
187
- * rewrites letter case on case-insensitive disks, so a directory it returns can fail
188
- * to contain the module ids Node hands the matchers.
189
- */
190
- function canonicalDir(dir) {
191
- try {
192
- return fs.realpathSync(dir);
193
- } catch {
194
- return dir;
195
- }
196
- }
197
- /**
198
- * Resolve only from a physical node_modules directory at/above the project.
199
- *
200
- * Unlike createRequire.resolve(), this deliberately ignores NODE_PATH and loader
201
- * hooks. It is for dependencies whose presence must be consumer-visible rather than
202
- * borrowed from the test runner's own install.
203
- */
204
- function installedPackageDirOf(name, projectRoot) {
205
- const packagePath = name.split("/");
206
- let dir = path.resolve(projectRoot);
207
- for (;;) {
208
- const candidate = path.join(dir, "node_modules", ...packagePath);
209
- if (fs.existsSync(path.join(candidate, "package.json"))) return canonicalDir(candidate);
210
- const parent = path.dirname(dir);
211
- if (parent === dir) return null;
212
- dir = parent;
213
- }
214
- }
215
- /** Escape a string for literal use inside a RegExp. */
216
- function escapeRe$1(value) {
217
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
218
- }
219
- /** Forward slashes, the form Vitest presents module ids in. */
220
- function toPosix(value) {
221
- return value.replace(/\\/g, "/");
222
- }
223
- /**
224
- * Does `dir` contain `target` (or equal it)?
225
- *
226
- * Used to recognise the package the run lives in. A package directory containing the
227
- * Vitest root is the project, not a dependency of it — externalizing it hands Vitest
228
- * its own source and test files back through Node, where they are compiled to
229
- * CommonJS.
230
- *
231
- * Compared case-insensitively on Windows: `require.resolve` reports the on-disk
232
- * casing while a working directory carries whatever the shell supplied, and a
233
- * drive-letter difference alone would silently defeat the check.
234
- */
235
- function containsPath(dir, target) {
236
- const normalize = (value) => {
237
- const resolved = path.resolve(value);
238
- return process.platform === "win32" ? resolved.toLowerCase() : resolved;
239
- };
240
- const outer = normalize(dir);
241
- const inner = normalize(target);
242
- return inner === outer || inner.startsWith(outer.endsWith(path.sep) ? outer : outer + path.sep);
243
- }
244
- /**
245
- * The on-disk directory a package resolves to, or null.
246
- *
247
- * `pkg/package.json` is tried first because it names the package root exactly; some
248
- * packages do not export it, so fall back to resolving the entry and walking up to
249
- * the manifest that names them. Symlinked and workspace packages resolve to their
250
- * real location, which is the whole point — see buildPkgMatcher.
251
- */
252
- function packageDirOf(name, projectRoot) {
253
- const req = createRequire(path.join(projectRoot, "package.json"));
254
- try {
255
- return canonicalDir(path.dirname(req.resolve(`${name}/package.json`)));
256
- } catch {}
257
- let dir;
258
- try {
259
- dir = path.dirname(req.resolve(name));
260
- } catch {
261
- return null;
262
- }
263
- for (;;) {
264
- try {
265
- if (createRequire(path.join(dir, "index.js"))("./package.json").name === name) return canonicalDir(dir);
266
- } catch {}
267
- const parent = path.dirname(dir);
268
- if (parent === dir) return null;
269
- dir = parent;
270
- }
271
- }
272
- /**
273
- * The patterns identifying one package's files. THE rule; everything else composes it.
274
- *
275
- * A bare `[/\]name[/\]` test — what this used to be — also matches any DIRECTORY
276
- * that happens to share a package's name. A project folder called `expo`, or a source
277
- * directory named after the library it implements, made every file beneath it look
278
- * like third-party source to be compiled. That mis-compiled unrelated files, this
279
- * package's own runtime among them.
280
- *
281
- * Anchoring on `node_modules` alone would fix that and break linked packages: a
282
- * workspace or `file:` dependency resolves to its real path, which has no
283
- * `node_modules` segment at all. So a file matches if it is either
284
- *
285
- * - under `node_modules/<name>/` (covers additional copies of a package that a
286
- * single resolution cannot see, and projects where resolution fails), or
287
- * - inside the package's resolved directory (exact; covers workspace links, and
288
- * stores like pnpm's and bun's).
289
- *
290
- * The resolved-directory anchor is dropped when that directory CONTAINS the project
291
- * root, because then it is the project. Externalizing the project hands Vitest its
292
- * own source and test files back through Node, which compiles them to CommonJS: a
293
- * test file's `import { it } from 'vitest'` becomes `require('vitest')` and throws.
294
- *
295
- * `projectRoot` is optional; without it only the `node_modules` rule applies, since
296
- * there is nothing to resolve against.
297
- */
298
- function packagePatterns(name, projectRoot) {
299
- const patterns = [new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe$1(name)}[\\\\/]`)];
300
- if (!projectRoot) return patterns;
301
- const dir = packageDirOf(name, projectRoot);
302
- if (dir && !containsPath(dir, projectRoot)) patterns.push(new RegExp(`^${escapeRe$1(toPosix(dir).replace(/\/$/, ""))}[\\\\/]`));
303
- return patterns;
304
- }
305
- /**
306
- * A predicate over the same patterns Vitest is given, so what the loader transforms
307
- * and what Vitest externalizes cannot drift apart.
308
- *
309
- * Paths are normalised before testing: the directory anchor is written with forward
310
- * slashes (the form Vitest presents module ids in) while callers here pass whatever
311
- * Node handed them, which on Windows is backslashes.
312
- */
313
- function buildPkgMatcher(pkgs, projectRoot) {
314
- const patterns = (pkgs || []).flatMap((name) => packagePatterns(name, projectRoot));
315
- return (file) => {
316
- const norm = toPosix(file);
317
- return patterns.some((re) => re.test(norm));
318
- };
319
- }
320
- //#endregion
321
- //#region src/native/ownership.mjs
322
- /**
323
- * Project-scoped module ownership policy for the native engine.
324
- *
325
- * This module does not resolve or load anything. It turns already-established
326
- * project facts into the patterns and predicates consumed by Vitest config, the
327
- * CommonJS hook, the ESM loader, hot reset, and diagnostics. Keeping it pure lets
328
- * the Vite main process and every worker reconstruct the same decision.
329
- */
330
- const OUTSIDE_NODE_MODULES = String.raw`^(?!.*[\\/]node_modules[\\/])`;
331
- /** Files Vitest may execute as entries. They always belong to Vite. */
332
- const TEST_ENTRY_PATTERNS = Object.freeze([new RegExp(String.raw`${OUTSIDE_NODE_MODULES}.*\.(?:test|spec)\.[cm]?[jt]sx?$`), new RegExp(String.raw`${OUTSIDE_NODE_MODULES}.*[\\/]__tests__[\\/].*\.[cm]?[jt]sx?$`)]);
333
- /**
334
- * Identity-sensitive runtime packages whose CJS entries cannot be dropped while
335
- * their ESM entries remain resident. Shared by ESM generation and hot CJS reset.
336
- */
337
- const RUNTIME_RESIDENT_PACKAGES = Object.freeze([
338
- "react",
339
- "react-is",
340
- "react-dom",
341
- "scheduler",
342
- "react-reconciler",
343
- "react-test-renderer",
344
- "test-renderer",
345
- "@testing-library/react-native"
346
- ]);
347
- const RUNTIME_RESIDENT_PATH = /[\\/]node_modules[\\/](react|react-is|react-dom|scheduler|react-reconciler|react-test-renderer|test-renderer|@testing-library[\\/]react-native)[\\/]/;
348
- /** The test runner/runtime must never receive per-file ESM generation stamps. */
349
- const TEST_RUNTIME_RESIDENT_PACKAGES = Object.freeze([
350
- "vitest",
351
- "@vitest/*",
352
- "chai",
353
- "vitest-native"
354
- ]);
355
- const TEST_RUNTIME_RESIDENT_PATH = /[\\/]node_modules[\\/](vitest|@vitest[\\/][^\\/]+|chai|vitest-native)[\\/]/;
356
- const normalizeFile = (file) => file.replace(/\\/g, "/");
357
- const cleanRawFileId = (file) => file.replace(/[?#].*$/, "");
358
- const cleanFileId = (file) => normalizeFile(cleanRawFileId(file));
359
- const unique = (values) => [...new Set((values || []).filter(Boolean))];
360
- const escapeRe = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
361
- function isRuntimeResidentFile(file) {
362
- return RUNTIME_RESIDENT_PATH.test(normalizeFile(file));
363
- }
364
- function isTestRuntimeResidentFile(file) {
365
- return TEST_RUNTIME_RESIDENT_PATH.test(normalizeFile(file));
366
- }
367
- function decision(owner, format, transform, reset, reasons, evidence) {
368
- return Object.freeze({
369
- owner,
370
- format,
371
- transform,
372
- reset,
373
- reason: reasons[0],
374
- reasons: Object.freeze(reasons),
375
- evidence: Object.freeze(evidence)
376
- });
377
- }
378
- /**
379
- * Build one immutable policy for a Vitest project.
380
- *
381
- * `explicitTransforms` is the public `transform` include list.
382
- * `ecosystemPackages` is the detected RN dependency closure.
383
- * `runtimeTransforms` is for workers reconstructing the already-combined list from
384
- * serialized setup data; config-time callers normally leave it empty.
385
- */
386
- function createNativeOwnershipPolicy({ projectRoot = process.cwd(), explicitTransforms = [], ecosystemPackages = [], runtimeTransforms = [], runtimeTransformAugmentations = [], projectDirs = [], reactNativeRoots = [], serverDepsInlineAll = false } = {}) {
387
- const enforcement = serverDepsInlineAll ? "overridden-by-inline-all" : "enforced";
388
- const root = path.resolve(projectRoot);
389
- const explicit = unique(explicitTransforms);
390
- const explicitSet = new Set(explicit);
391
- const ecosystem = unique(ecosystemPackages).filter((name) => !explicitSet.has(name));
392
- const runtime = unique(runtimeTransforms).filter((name) => !explicitSet.has(name) && !ecosystem.includes(name));
393
- const runtimeAugmentations = Object.freeze(unique(runtimeTransformAugmentations));
394
- const nodeTransformPackages = Object.freeze([
395
- ...explicit,
396
- ...ecosystem,
397
- ...runtime
398
- ]);
399
- const inferredReactNativeRoot = installedPackageDirOf("react-native", root);
400
- const normalizedReactNativeRoots = Object.freeze(unique([inferredReactNativeRoot, ...reactNativeRoots]).map((dir) => path.resolve(dir)));
401
- const reactNativeRootPatterns = normalizedReactNativeRoots.map((dir) => new RegExp(`^${normalizeFile(dir).replace(/\/$/, "").split("/").map(escapeRe).join("[\\\\/]")}[\\\\/]`));
402
- const isReactNativeCore = (file, rawFile) => REACT_NATIVE_PATH.test(file) || normalizedReactNativeRoots.some((dir) => containsPath(dir, cleanRawFileId(rawFile)));
403
- const reactNativePathFor = (rawFile) => {
404
- const clean = cleanRawFileId(rawFile);
405
- const file = normalizeFile(clean);
406
- if (REACT_NATIVE_PATH.test(file)) return file;
407
- const packageRoot = normalizedReactNativeRoots.find((dir) => containsPath(dir, clean));
408
- if (!packageRoot) return null;
409
- return `/react-native/${normalizeFile(path.relative(packageRoot, clean))}`;
410
- };
411
- const externalPatterns = [
412
- REACT_NATIVE_PATH,
413
- ...reactNativeRootPatterns,
414
- ...nodeTransformPackages.flatMap((name) => packagePatterns(name, root))
415
- ];
416
- const matchesNodeTransformedFile = buildPkgMatcher(nodeTransformPackages, root);
417
- const explicitMatcher = buildPkgMatcher(explicit, root);
418
- const ecosystemMatcher = buildPkgMatcher(ecosystem, root);
419
- const runtimeMatcher = buildPkgMatcher(runtime, root);
420
- const normalizedProjectDirs = Object.freeze(unique(projectDirs).map((dir) => path.resolve(dir)));
421
- const decideFile = (rawFile) => {
422
- const file = cleanFileId(rawFile);
423
- if (TEST_ENTRY_PATTERNS.some((pattern) => pattern.test(file))) return decision("vite", "source", "vite", "per-file", ["test-entry"], [file]);
424
- const runtimeResident = isRuntimeResidentFile(file);
425
- const testRuntimeResident = isTestRuntimeResidentFile(file);
426
- if (isReactNativeCore(file, rawFile)) return decision("node", "cjs", "registry", "worker-resident", ["react-native-core"], [normalizedReactNativeRoots.find((dir) => containsPath(dir, cleanRawFileId(rawFile))) ?? "react-native/@react-native path", "preloaded before the hot reset baseline"]);
427
- if (!NODE_MODULES_PATH.test(file)) {
428
- const projectDir = normalizedProjectDirs.find((dir) => containsPath(dir, cleanRawFileId(rawFile)));
429
- if (projectDir) return decision("vite", "source", "vite", "per-file", ["project-source"], [projectDir]);
430
- }
431
- if (explicitMatcher(file)) return decision("node", "package", "native-babel", runtimeResident ? "worker-resident" : "per-file", runtimeResident ? ["explicit-transform", "identity-sensitive-runtime"] : ["explicit-transform"], runtimeResident ? ["reactNative.transform.include", "CJS/ESM identity must remain stable"] : ["reactNative.transform.include"]);
432
- if (ecosystemMatcher(file)) return decision("node", "package", "native-babel", runtimeResident ? "worker-resident" : "per-file", runtimeResident ? ["ecosystem-detected", "identity-sensitive-runtime"] : ["ecosystem-detected"], runtimeResident ? ["React Native dependency closure", "CJS/ESM identity must remain stable"] : ["React Native dependency closure"]);
433
- if (runtimeMatcher(file)) return decision("node", "package", "native-babel", runtimeResident ? "worker-resident" : "per-file", runtimeResident ? ["runtime-transform", "identity-sensitive-runtime"] : ["runtime-transform"], runtimeResident ? ["serialized worker transform set", "CJS/ESM identity must remain stable"] : ["serialized worker transform set"]);
434
- if (runtimeResident) return decision("vitest-default", "package", "default", "worker-resident-if-external", ["identity-sensitive-runtime"], ["Vitest decides whether this package is inlined or external", "if external, CJS/ESM identity must remain stable"]);
435
- if (testRuntimeResident) return decision("vitest-default", "package", "default", "worker-resident-if-external", ["test-runtime"], ["Vitest decides whether this package is inlined or external", "if external, runner identity must remain stable"]);
436
- return decision("vitest-default", "unknown", "default", "vitest-default", ["delegated"], ["not governed by native ownership policy"]);
437
- };
438
- const manifest = () => Object.freeze({
439
- version: 1,
440
- enforcement,
441
- projectRoot: root,
442
- projectDirs: normalizedProjectDirs,
443
- reactNativeRoots: normalizedReactNativeRoots,
444
- nodeTransformPackages,
445
- runtimeTransformAugmentations: runtimeAugmentations,
446
- identityResidentPackages: RUNTIME_RESIDENT_PACKAGES,
447
- testRuntimeResidentPackages: TEST_RUNTIME_RESIDENT_PACKAGES,
448
- rules: Object.freeze([
449
- Object.freeze({
450
- effect: "owner-transform-reset",
451
- owner: "node",
452
- transform: "registry",
453
- reset: "worker-resident",
454
- reason: "react-native-core",
455
- packages: Object.freeze(["react-native", "@react-native/*"]),
456
- roots: normalizedReactNativeRoots
457
- }),
458
- Object.freeze({
459
- effect: "owner-transform",
460
- owner: "node",
461
- transform: "native-babel",
462
- reason: "explicit-transform",
463
- packages: Object.freeze(explicit)
464
- }),
465
- Object.freeze({
466
- effect: "owner-transform",
467
- owner: "node",
468
- transform: "native-babel",
469
- reason: "ecosystem-detected",
470
- packages: Object.freeze(ecosystem)
471
- }),
472
- Object.freeze({
473
- effect: "owner-transform",
474
- owner: "node",
475
- transform: "native-babel",
476
- reason: "runtime-transform",
477
- packages: Object.freeze(runtime)
478
- }),
479
- Object.freeze({
480
- effect: "owner-transform-reset",
481
- owner: "vite",
482
- transform: "vite",
483
- reset: "per-file",
484
- reason: "project-source",
485
- roots: normalizedProjectDirs
486
- }),
487
- Object.freeze({
488
- effect: "owner-transform-reset",
489
- owner: "vite",
490
- transform: "vite",
491
- reset: "per-file",
492
- reason: "test-entry",
493
- patterns: Object.freeze(TEST_ENTRY_PATTERNS.map(String))
494
- }),
495
- Object.freeze({
496
- effect: "reset-if-external",
497
- reset: "worker-resident",
498
- reason: "identity-sensitive-runtime",
499
- packages: RUNTIME_RESIDENT_PACKAGES
500
- }),
501
- Object.freeze({
502
- effect: "reset-if-external",
503
- reset: "worker-resident",
504
- reason: "test-runtime",
505
- packages: TEST_RUNTIME_RESIDENT_PACKAGES
506
- })
507
- ])
508
- });
509
- return Object.freeze({
510
- enforcement,
511
- projectRoot: root,
512
- nodeTransformPackages,
513
- externalPatterns,
514
- testEntryPatterns: [...TEST_ENTRY_PATTERNS],
515
- matchesNodeTransformedFile,
516
- isReactNativeFile: (file) => isReactNativeCore(cleanFileId(file), file),
517
- reactNativePathFor,
518
- decideFile,
519
- manifest
520
- });
521
- }
522
- /**
523
- * Compare an actual graph observation with the owner assigned by the project.
524
- * Delegated packages are intentionally inconclusive: Vitest is allowed to inline or
525
- * externalize them. Likewise an inline-all override disables enforcement because it
526
- * has explicitly taken precedence over the engine's externalization rules.
527
- */
528
- function findNativeOwnershipConflict(policy, file, observedOwner) {
529
- if (!policy || policy.enforcement !== "enforced") return null;
530
- if (observedOwner !== "vite" && observedOwner !== "node") return null;
531
- const expected = policy.decideFile(file);
532
- if (expected.owner === "vitest-default" || expected.owner === observedOwner) return null;
533
- return Object.freeze({
534
- code: "NATIVE_MODULE_OWNER_CONFLICT",
535
- file,
536
- observedOwner,
537
- expectedOwner: expected.owner,
538
- decision: expected
539
- });
540
- }
541
- /**
542
- * Node-owned packages a Vitest inline rule would claim before externalization.
543
- * Matching mirrors Vitest's `matchPattern`: strings are fragments below a module
544
- * directory and regular expressions test the normalized resolved id.
545
- */
546
- function findNativeInlineConflicts(policy, inline) {
547
- if (!policy || inline == null) return [];
548
- if (inline === true) return ["*"];
549
- const patterns = Array.isArray(inline) ? inline : [inline];
550
- const packages = [
551
- "react-native",
552
- "@react-native/*",
553
- ...policy.nodeTransformPackages
554
- ];
555
- const conflicts = [];
556
- for (const name of packages) {
557
- const concrete = name === "@react-native/*" ? "@react-native/assets-registry" : name;
558
- const probes = [`/project/node_modules/${concrete}/index.js`, `C:\\project\\node_modules\\${concrete.replaceAll("/", "\\")}\\index.js`];
559
- const dir = name.includes("*") ? null : packageDirOf(name, policy.projectRoot);
560
- if (dir) probes.push(`${normalizeFile(dir).replace(/\/$/, "")}/index.js`);
561
- if (patterns.some((pattern) => {
562
- if (typeof pattern === "string") {
563
- const fragment = `/node_modules/${pattern.replace(/^[/\\]+/, "")}`;
564
- return probes.some((probe) => normalizeFile(probe).includes(fragment));
565
- }
566
- if (!pattern || typeof pattern.test !== "function") return false;
567
- return probes.some((probe) => {
568
- pattern.lastIndex = 0;
569
- const matched = pattern.test(normalizeFile(probe));
570
- pattern.lastIndex = 0;
571
- return matched;
572
- });
573
- })) conflicts.push(name);
574
- }
575
- return [...new Set(conflicts)];
576
- }
577
- /**
578
- * Parse the project policy passed across the Vitest worker boundary.
579
- *
580
- * Treat environment data as untrusted even though the plugin produced it: users can
581
- * set `test.env`, and a malformed diagnostic must never stop a test run. Unknown
582
- * manifest versions deliberately return null rather than being guessed at.
583
- */
584
- function parseNativeOwnershipManifest(raw) {
585
- try {
586
- const value = typeof raw === "string" ? JSON.parse(raw) : raw;
587
- if (!value || typeof value !== "object" || value.version !== 1) return null;
588
- if (value.enforcement !== "enforced" && value.enforcement !== "overridden-by-inline-all") return null;
589
- if (typeof value.projectRoot !== "string") return null;
590
- for (const key of [
591
- "projectDirs",
592
- "reactNativeRoots",
593
- "nodeTransformPackages",
594
- "runtimeTransformAugmentations",
595
- "identityResidentPackages",
596
- "testRuntimeResidentPackages",
597
- "rules"
598
- ]) if (!Array.isArray(value[key])) return null;
599
- if (![
600
- ...value.projectDirs,
601
- ...value.reactNativeRoots,
602
- ...value.nodeTransformPackages,
603
- ...value.runtimeTransformAugmentations,
604
- ...value.identityResidentPackages,
605
- ...value.testRuntimeResidentPackages
606
- ].every((entry) => typeof entry === "string")) return null;
607
- return value;
608
- } catch {
609
- return null;
610
- }
611
- }
612
- /** Human-readable lines for diagnostics and `doctor`; generated from the manifest. */
613
- function formatNativeOwnershipManifest(input) {
614
- const manifest = parseNativeOwnershipManifest(input);
615
- if (!manifest) return ["ownership manifest unavailable or invalid"];
616
- const list = (values) => values.length > 0 ? values.join(", ") : "(none)";
617
- const lines = [
618
- `project: ${manifest.projectRoot}`,
619
- `Vite / reset per file: ${list(manifest.projectDirs)} plus test entries`,
620
- `Node / worker resident: react-native, @react-native/* (${list(manifest.reactNativeRoots)})`,
621
- `Node / native transform / reset per file: ${list(manifest.nodeTransformPackages)}`,
622
- `worker-time transform augmentations: ${list(manifest.runtimeTransformAugmentations)}`,
623
- `resident if Vitest externalizes them: ${list(manifest.identityResidentPackages)}`,
624
- `test runtime resident if external: ${list(manifest.testRuntimeResidentPackages)}`
625
- ];
626
- if (manifest.enforcement === "overridden-by-inline-all") lines.push("WARNING: server.deps.inline=true takes precedence over Node ownership; graph uniqueness is not guaranteed");
627
- return lines;
628
- }
629
- //#endregion
630
- //#region src/native/babel-preset.mjs
631
- /**
632
- * The Babel preset the native engine compiles React Native and node_modules with,
633
- * resolved from the project: the preset the project's Metro applies when the project
634
- * has no Babel config of its own.
635
- *
636
- * - `@react-native/babel-preset`: React Native CLI projects, and Expo before SDK 56,
637
- * whose babel-preset-expo depends on it.
638
- * - `expo/internal/babel-preset` (babel-preset-expo): Expo from SDK 56. Its
639
- * babel-preset-expo carries React Native's plugins itself and no longer depends on
640
- * @react-native/babel-preset, so a project created from an SDK 56+ template has none
641
- * installed. Expo's Metro (@expo/metro-config, loadBabelConfig) and jest-expo
642
- * (src/resolveBabelOptions.js) load this preset in a project without a Babel config.
643
- *
644
- * The React Native preset is tried first, so a project that has it keeps compiling
645
- * exactly as before. Null when neither resolves.
646
- *
647
- * @param {string} projectRoot
648
- * @returns {{ name: string, file: string, version: string, packageDir: string } | null}
649
- */
650
- function resolveTransformPreset(projectRoot) {
651
- const req = createRequire(path.join(projectRoot, "package.json"));
652
- try {
653
- const manifest = req.resolve("@react-native/babel-preset/package.json");
654
- return {
655
- name: "@react-native/babel-preset",
656
- file: path.dirname(manifest),
657
- version: readVersion(manifest),
658
- packageDir: path.dirname(manifest)
659
- };
660
- } catch {}
661
- try {
662
- const file = req.resolve("expo/internal/babel-preset");
663
- const manifest = createRequire(file).resolve("babel-preset-expo/package.json");
664
- return {
665
- name: "babel-preset-expo",
666
- file,
667
- version: readVersion(manifest),
668
- packageDir: path.dirname(manifest)
669
- };
670
- } catch {
671
- return null;
672
- }
673
- }
674
- function readVersion(manifest) {
675
- return JSON.parse(fs.readFileSync(manifest, "utf8")).version;
676
- }
677
- /**
678
- * The native engine's dependencies that do NOT resolve from the project root.
679
- *
680
- * react-native itself is part of the check: the Babel toolchain alone chose
681
- * native mode in a project with the preset installed but no react-native — an
682
- * incomplete install, a babel-only workspace — which then failed later at RN
683
- * resolution with nothing pointing at the cause. Resolution, not declaration:
684
- * every check walks node_modules upward from the root — so a hoisted workspace
685
- * install or Expo's transitive react-native counts, and a project does not need
686
- * react-native in its own manifest.
687
- */
688
- function missingNativeDeps(projectRoot) {
689
- const req = createRequire(path.join(projectRoot, "package.json"));
690
- const missing = [];
691
- if (!reactNativeInstalledNear(projectRoot)) missing.push("react-native");
692
- if (resolveTransformPreset(projectRoot) === null) missing.push("@react-native/babel-preset");
693
- try {
694
- req.resolve("@babel/core");
695
- } catch {
696
- missing.push("@babel/core");
697
- }
698
- return missing;
699
- }
700
- /** Does node_modules/react-native exist in projectRoot or any ancestor? */
701
- function reactNativeInstalledNear(projectRoot) {
702
- let dir = path.resolve(projectRoot);
703
- for (;;) {
704
- if (fs.existsSync(path.join(dir, "node_modules", "react-native", "package.json"))) return true;
705
- const parent = path.dirname(dir);
706
- if (parent === dir) return false;
707
- dir = parent;
708
- }
709
- }
710
- /** Resolve the concrete engine for a run. Pure; never throws. */
711
- function detectEngine(requested, projectRoot, opts) {
712
- const missing = missingNativeDeps(projectRoot);
713
- const nativeAvailable = missing.length === 0;
714
- if (requested === "native") return {
715
- engine: "native",
716
- nativeAvailable,
717
- missing,
718
- notice: null
719
- };
720
- if (requested === "mock") return {
721
- engine: "mock",
722
- nativeAvailable,
723
- missing,
724
- notice: null
725
- };
726
- const prefersNative = opts?.autoPrefersNative ?? true;
727
- if (prefersNative && nativeAvailable) return {
728
- engine: "native",
729
- nativeAvailable,
730
- missing,
731
- notice: null
732
- };
733
- if (prefersNative) return {
734
- engine: "mock",
735
- nativeAvailable: false,
736
- missing,
737
- 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.`
738
- };
739
- return {
740
- engine: "mock",
741
- nativeAvailable,
742
- missing,
743
- notice: null
744
- };
745
- }
746
- //#endregion
747
- //#region src/native/ecosystem.ts
748
- /**
749
- * Packages that must never be auto-inlined even though they depend on React
750
- * Native. The test library and the renderers underneath it are infrastructure the
751
- * engine itself wires up; pulling a second copy of them into the module graph has
752
- * corrupted rendering before, in ways that surface as unrelated act() and
753
- * host-component failures.
754
- *
755
- * This list is one clause of the ownership rule; the whole of it is written down in
756
- * the header of native/apply.ts, which is the file to read before changing what ends
757
- * up in either graph.
758
- */
759
- const NEVER_INLINE = /* @__PURE__ */ new Set([
760
- "@testing-library/react-native",
761
- "react-test-renderer",
762
- "test-renderer",
763
- "react-native",
764
- "react",
765
- "react-is"
766
- ]);
767
- /** Does this manifest offer a React Native build, by legacy field or export condition? */
768
- function hasReactNativeBuild(manifest) {
769
- if (typeof manifest["react-native"] === "string") return true;
770
- const seen = /* @__PURE__ */ new Set();
771
- const search = (node) => {
772
- if (!node || typeof node !== "object" || seen.has(node)) return false;
773
- seen.add(node);
774
- for (const [key, value] of Object.entries(node)) {
775
- if (key === "react-native") return true;
776
- if (search(value)) return true;
777
- }
778
- return false;
779
- };
780
- return search(manifest.exports);
781
- }
782
- /**
783
- * A package that ships ES modules and nothing React Native.
784
- *
785
- * The closure walk is a guess: a detected package's dependencies MIGHT be untranspiled
786
- * React Native source, because the ecosystem publishes that way and the dependency's
787
- * own manifest cannot say so. `"type": "module"` is the manifest saying the opposite —
788
- * this is runnable ES modules — and with no React Native build anywhere in it, there is
789
- * nothing for the preset to do. Compiling it anyway rewrites a package that publishes
790
- * ESM into CommonJS and hands it to Node under that format, which is how a dependency
791
- * reached this way (`zod`) failed to parse and took fourteen test files down with it.
792
- *
793
- * A genuine React Native library is unaffected: declaring `react-native` by field or
794
- * export condition keeps it in the closure however it publishes.
795
- *
796
- * Only closure MEMBERS are judged this way. A package detected on its own manifest, or
797
- * named in `transform: [...]`, was asked for explicitly and is still compiled.
798
- */
799
- function publishesOnlyEsm(manifest) {
800
- return manifest.type === "module" && !hasReactNativeBuild(manifest);
801
- }
802
- /** Manifest fields that make a package part of the React Native ecosystem. */
803
- function dependsOnReactNative(manifest) {
804
- for (const field of ["dependencies", "peerDependencies"]) {
805
- const deps = manifest[field];
806
- if (deps && typeof deps === "object" && "react-native" in deps) return true;
807
- }
808
- return false;
809
- }
810
- /**
811
- * Every package manifest from the project up to the filesystem root.
812
- *
813
- * A workspace does not always declare its dependencies where the tests run: an app
814
- * package may inherit React Native libraries from the repository root, and a Vitest
815
- * `root` can point at a directory above or below the package that owns them. Reading
816
- * only the project's own manifest silently found nothing in those layouts and sent
817
- * the user back to maintaining `transform: [...]` by hand.
818
- *
819
- * Over-collecting is safe and under-collecting is not: a package that is listed but
820
- * never imported costs nothing, because inlining only applies to files that are
821
- * actually loaded.
822
- */
823
- /**
824
- * Directories of the workspace members a manifest declares, plus any listed in a
825
- * sibling pnpm-workspace.yaml.
826
- *
827
- * Needed because `manifestsFrom` only walks UP. In a workspace the run root is
828
- * frequently ABOVE the package under test — Nx invokes tasks from the workspace
829
- * root, and Vitest's root defaults to the working directory — so the app's own
830
- * dependencies are declared in a manifest that walking up never reaches. The
831
- * package then misses auto-detection and stays in Vite's graph while Node loads it
832
- * too, which is the dual-ownership failure reproducing from nothing but a different
833
- * working directory.
834
- *
835
- * Only the two glob shapes workspace fields actually use are expanded (`dir/*` and a
836
- * literal path). Over-collecting is safe here — an unimported package costs nothing —
837
- * so a shape that is not understood is skipped rather than approximated.
838
- */
839
- function workspaceMemberDirs(dir, manifest) {
840
- const patterns = [];
841
- const declared = manifest.workspaces;
842
- if (Array.isArray(declared)) patterns.push(...declared.filter((p) => typeof p === "string"));
843
- else if (declared && typeof declared === "object" && Array.isArray(declared.packages)) patterns.push(...declared.packages.filter((p) => typeof p === "string"));
844
- try {
845
- const yaml = fs.readFileSync(path.join(dir, "pnpm-workspace.yaml"), "utf8");
846
- for (const line of yaml.split(/\r?\n/)) {
847
- const entry = /^\s*-\s*["']?([^"'#]+?)["']?\s*$/.exec(line);
848
- if (entry) patterns.push(entry[1]);
849
- }
850
- } catch {}
851
- const dirs = [];
852
- for (const pattern of patterns) if (pattern.endsWith("/*")) {
853
- const parent = path.join(dir, pattern.slice(0, -2));
854
- try {
855
- for (const entry of fs.readdirSync(parent, { withFileTypes: true })) if (entry.isDirectory()) dirs.push(path.join(parent, entry.name));
856
- } catch {}
857
- } else if (!pattern.includes("*")) dirs.push(path.join(dir, pattern));
858
- return dirs;
859
- }
860
- function manifestsFrom(projectRoot) {
861
- const manifests = [];
862
- let dir = path.resolve(projectRoot);
863
- for (;;) {
864
- try {
865
- const raw = fs.readFileSync(path.join(dir, "package.json"), "utf8");
866
- const manifest = JSON.parse(raw);
867
- manifests.push({
868
- dir,
869
- manifest
870
- });
871
- for (const member of workspaceMemberDirs(dir, manifest)) try {
872
- manifests.push({
873
- dir: member,
874
- manifest: JSON.parse(fs.readFileSync(path.join(member, "package.json"), "utf8"))
875
- });
876
- } catch {}
877
- } catch {}
878
- const parent = path.dirname(dir);
879
- if (parent === dir) return manifests;
880
- dir = parent;
881
- }
882
- }
883
- /**
884
- * Packages in the project that declare React Native in their own manifest.
885
- *
886
- * These are the ones published the way the React Native ecosystem publishes:
887
- * untranspiled JSX, Flow, or TypeScript, on the assumption that Metro will compile
888
- * them. Node cannot run that source, which is why they previously had to be listed
889
- * by hand in `transform: [...]` — a list every project had to discover the hard way,
890
- * one `SyntaxError: Unexpected token '<'` at a time.
891
- *
892
- * A package's own manifest is the authority here rather than a heuristic on its
893
- * name: `react-native-*` misses `@gorhom/bottom-sheet` and would wrongly claim
894
- * `react-native` itself, while the manifest states the relationship exactly.
895
- *
896
- * Declared dependencies are read from the project and every manifest above it, so a
897
- * workspace that declares its React Native libraries at the repository root is covered
898
- * too. Resolving each name is cheap and package-manager-agnostic, where walking the
899
- * installed tree depends on the store layout. Transitive dependencies that nothing
900
- * declares stay available through `transform: [...]`.
901
- *
902
- * Excluded: packages a preset already shadows (their real source never loads), the
903
- * test infrastructure in NEVER_INLINE, and anything the consumer listed explicitly
904
- * in `transform` — that option keeps its existing meaning and takes precedence.
905
- */
906
- function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], neverTransform = [], activePresets) {
907
- const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
908
- const shadowed = Object.entries(AUTO_DETECT_PRESETS).filter(([, presetName]) => activePresets === void 0 || activePresets.includes(presetName)).map(([pkg]) => pkg);
909
- const skip = /* @__PURE__ */ new Set([
910
- ...NEVER_INLINE,
911
- ...shadowed,
912
- ...explicit,
913
- ...neverTransform
914
- ]);
915
- const candidates = /* @__PURE__ */ new Set();
916
- const found = roots.flatMap((root) => manifestsFrom(root));
917
- const requires = [...new Set(found.map((entry) => entry.dir))].map((dir) => createRequire(path.join(dir, "package.json")));
918
- for (const { manifest } of found) for (const field of [
919
- "dependencies",
920
- "devDependencies",
921
- "optionalDependencies"
922
- ]) {
923
- const deps = manifest[field];
924
- if (deps && typeof deps === "object") for (const name of Object.keys(deps)) candidates.add(name);
925
- }
926
- if (candidates.size === 0) return [];
927
- /** Resolve a package's manifest from whichever root can see it. */
928
- const manifestOf = (name) => {
929
- for (const req of requires) try {
930
- return req(`${name}/package.json`);
931
- } catch {}
932
- return null;
933
- };
934
- /**
935
- * The packages the run itself lives in — the project, in other words.
936
- *
937
- * In a workspace, the package under test is usually declared as a dependency by a
938
- * sibling or by the repository root, so it appears in the candidate set like any
939
- * third-party library — and it declares React Native, because it is React Native
940
- * code. Detecting it would claim the project's own source: its directory becomes a
941
- * `server.deps.external` pattern, so Vitest hands every file under it to Node,
942
- * where the loader compiles it to CommonJS. A test file's own
943
- * `import { it } from 'vitest'` becomes `require('vitest')`, which throws
944
- * "Vitest cannot be imported in a CommonJS module using require()" — a failure that
945
- * appears in one workspace package and not another for no visible reason.
946
- *
947
- * A package cannot be its own dependency, so a manifest whose directory contains a
948
- * run root belongs to the project. Read straight off the manifests already walked,
949
- * which is both cheaper than resolving each candidate and independent of how a
950
- * package manager happens to lay out its store — under pnpm every workspace member
951
- * is additionally linked into a hidden directory on NODE_PATH, so a package can
952
- * resolve its own name from its own directory, but nothing here depends on that.
953
- *
954
- * Workspace libraries the project merely depends on sit beside a run root rather
955
- * than above it and are unaffected — detecting those is the point of the
956
- * workspace-member walk above.
957
- */
958
- const ownerRoots = [...roots, ...testRoots];
959
- const runOwners = new Set(found.filter(({ dir }) => ownerRoots.some((root) => containsPath(dir, root))).map(({ manifest }) => manifest.name).filter((name) => typeof name === "string"));
960
- const ownsTheRun = (name) => runOwners.has(name);
961
- const detected = [];
962
- for (const name of candidates) {
963
- if (skip.has(name) || name.startsWith("@react-native/")) continue;
964
- const pkg = manifestOf(name);
965
- if (pkg && dependsOnReactNative(pkg) && !ownsTheRun(name)) detected.push(name);
966
- }
967
- const rnOwned = new Set(Object.keys(manifestOf("react-native")?.dependencies ?? {}));
968
- /** Every package reachable from `roots` through runtime dependencies. */
969
- const closureOf = (starts) => {
970
- const seen = /* @__PURE__ */ new Set();
971
- const pending = [...starts];
972
- while (pending.length > 0) {
973
- const name = pending.pop();
974
- if (seen.has(name)) continue;
975
- seen.add(name);
976
- const deps = manifestOf(name)?.dependencies;
977
- if (deps && typeof deps === "object") pending.push(...Object.keys(deps));
978
- }
979
- return seen;
980
- };
981
- const toolchain = closureOf([
982
- "@babel/core",
983
- "@react-native/babel-preset",
984
- "@babel/runtime",
985
- "metro"
986
- ]);
987
- const projectDeclared = /* @__PURE__ */ new Set();
988
- for (const { dir, manifest } of found) {
989
- if (!ownerRoots.some((root) => containsPath(dir, root))) continue;
990
- for (const field of [
991
- "dependencies",
992
- "devDependencies",
993
- "optionalDependencies"
994
- ]) {
995
- const deps = manifest[field];
996
- if (deps && typeof deps === "object") for (const name of Object.keys(deps)) projectDeclared.add(name);
997
- }
998
- }
999
- const inClosure = new Set(detected);
1000
- const queue = detected.filter((name) => projectDeclared.has(name));
1001
- while (queue.length > 0) {
1002
- const deps = manifestOf(queue.pop())?.dependencies;
1003
- if (!deps || typeof deps !== "object") continue;
1004
- for (const dep of Object.keys(deps)) {
1005
- if (inClosure.has(dep) || skip.has(dep) || dep.startsWith("@react-native/")) continue;
1006
- if (rnOwned.has(dep)) continue;
1007
- if (toolchain.has(dep)) continue;
1008
- if (ownsTheRun(dep)) continue;
1009
- const depManifest = manifestOf(dep);
1010
- if (!depManifest) continue;
1011
- if (publishesOnlyEsm(depManifest)) continue;
1012
- inClosure.add(dep);
1013
- queue.push(dep);
1014
- }
1015
- }
1016
- return [...inClosure].sort();
1017
- }
1018
- //#endregion
1019
- export { findNativeInlineConflicts as a, containsPath as c, validateOptions as d, validatePeerDependency as f, createNativeOwnershipPolicy as i, packageDirOf as l, detectEngine as n, findNativeOwnershipConflict as o, warnUnknownOptions as p, resolveTransformPreset as r, formatNativeOwnershipManifest as s, detectEcosystemPackages as t, PEER_REQUIREMENTS as u };