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