vitest-native 0.14.1 → 0.15.0-rc.2

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 (89) hide show
  1. package/README.md +11 -10
  2. package/dist/cli.d.mts +9 -1
  3. package/dist/cli.mjs +2609 -361
  4. package/dist/context.d.mts +19 -0
  5. package/dist/context.mjs +47 -1
  6. package/dist/docs-url.d.mts +4 -0
  7. package/dist/docs-url.mjs +9 -0
  8. package/dist/errors.d.mts +21 -1
  9. package/dist/hang-watch-setup.mjs +55 -0
  10. package/dist/hang-watch.d.mts +56 -0
  11. package/dist/hang-watch.mjs +343 -0
  12. package/dist/helpers.cjs +24 -53
  13. package/dist/helpers.mjs +22 -1
  14. package/dist/host-D0r3P_T1.mjs +1985 -0
  15. package/dist/{index-aNBCTfA5.d.mts → index-JOR602XU.d.mts} +105 -2
  16. package/dist/index.d.mts +2 -1
  17. package/dist/index.mjs +723 -149
  18. package/dist/jest-compat/aliases.d.mts +1 -0
  19. package/dist/jest-compat/aliases.mjs +11 -0
  20. package/dist/jest-compat/interop.mjs +1 -1
  21. package/dist/jest-compat/jest-object.mjs +23 -5
  22. package/dist/jest-compat/node-registry.mjs +836 -68
  23. package/dist/jest-compat/setup.mjs +205 -12
  24. package/dist/jest-compat.cjs +383 -47
  25. package/dist/jest-compat.d.cts +19 -2
  26. package/dist/jest-compat.d.mts +19 -2
  27. package/dist/jest-compat.mjs +232 -47
  28. package/dist/matchers.d.cts +0 -1
  29. package/dist/matchers.d.mts +0 -1
  30. package/dist/native/assets.mjs +3 -1
  31. package/dist/native/babel-caller.d.mts +13 -0
  32. package/dist/native/babel-caller.mjs +24 -0
  33. package/dist/native/babel-toolchain.mjs +27 -3
  34. package/dist/native/boundary.mjs +45 -8
  35. package/dist/native/bounded-process.mjs +63 -5
  36. package/dist/native/bridge-client.mjs +133 -0
  37. package/dist/native/bridge-server.mjs +215 -0
  38. package/dist/native/bridge-thread.mjs +79 -0
  39. package/dist/native/bridge.mjs +512 -0
  40. package/dist/native/compile-error.mjs +120 -0
  41. package/dist/native/explain.mjs +3 -2
  42. package/dist/native/expo-module-mocks.mjs +2 -0
  43. package/dist/native/export-condition-recovery.mjs +20 -99
  44. package/dist/native/hooks.mjs +256 -133
  45. package/dist/native/jest-resolvers.mjs +94 -0
  46. package/dist/native/library-jest.mjs +352 -0
  47. package/dist/native/loader.mjs +167 -73
  48. package/dist/native/match.mjs +67 -7
  49. package/dist/native/module-reset.mjs +44 -49
  50. package/dist/native/ownership-ledger.d.mts +87 -0
  51. package/dist/native/ownership-ledger.mjs +524 -0
  52. package/dist/native/ownership.d.mts +20 -0
  53. package/dist/native/ownership.mjs +114 -0
  54. package/dist/native/registry-compiler.mjs +39 -5
  55. package/dist/native/registry-process.mjs +327 -28
  56. package/dist/native/registry.mjs +752 -200
  57. package/dist/native/resident-health.mjs +1 -0
  58. package/dist/native/resolve.d.mts +7 -0
  59. package/dist/native/resolve.mjs +119 -4
  60. package/dist/native/rntl-hooks.mjs +9 -5
  61. package/dist/native/rntl-text-host.mjs +5 -15
  62. package/dist/native/root-spelling.d.mts +6 -0
  63. package/dist/native/root-spelling.mjs +77 -0
  64. package/dist/native/runner.mjs +2 -19
  65. package/dist/native/setup.mjs +119 -38
  66. package/dist/native/shared-resolver.d.mts +141 -0
  67. package/dist/native/shared-resolver.mjs +719 -0
  68. package/dist/native/test-runner.mjs +26 -0
  69. package/dist/native/transform.mjs +18 -22
  70. package/dist/native/worker.mjs +9 -4
  71. package/dist/node-dispatch.mjs +293 -0
  72. package/dist/{preset-map-CogjYmSw.mjs → preset-map-DdAexIwz.mjs} +113 -2
  73. package/dist/{presets-CXDyg51l.mjs → presets-_EaSw29m.mjs} +710 -130
  74. package/dist/presets.d.mts +1 -1
  75. package/dist/presets.mjs +1 -1
  76. package/dist/rntl-matchers.d.ts +11 -15
  77. package/dist/rntl-support.mjs +28 -13
  78. package/dist/root-mocks-BNXeosbR.mjs +155 -0
  79. package/dist/serializer.cjs +7 -5
  80. package/dist/serializer.d.cts +7 -5
  81. package/dist/serializer.d.mts +7 -5
  82. package/dist/serializer.mjs +7 -5
  83. package/dist/setup.mjs +26 -27
  84. package/docs/migrating-from-jest.md +9 -232
  85. package/docs/migrating-from-vitest-react-native.md +4 -4
  86. package/docs/release-readiness.md +9 -11
  87. package/docs/versioning.md +38 -9
  88. package/package.json +59 -33
  89. package/dist/host-BAAAlSkO.mjs +0 -1028
package/dist/cli.mjs CHANGED
@@ -1,14 +1,21 @@
1
1
  #!/usr/bin/env node
2
- import { c as detectEcosystemPackages, d as fsModuleCacheOnByDefault, g as unsupportedExpoSdkMessage, h as installedExpoVersion, i as ownVitestPackage, l as detectEngine, o as usesVitePlus, p as PEER_REQUIREMENTS, r as installedViteVersion, v as validatePeerDependency } from "./host-BAAAlSkO.mjs";
3
- import { i as autoDetectedPresetApplies, n as DEFAULT_ASSET_EXTS, o as presetShadowing, r as PRESET_MODULES, s as testsItself, t as AUTO_DETECT_PRESETS } from "./preset-map-CogjYmSw.mjs";
2
+ import { A as unsupportedExpoSdkMessage, E as PEER_REQUIREMENTS, N as validatePeerDependency, O as installedExpoVersion, S as SUPPORTED_NODE, T as unsupportedNodeMessage, _ as normalizeBabelName, c as detectEcosystemPackages, g as isKnownPlugin, h as classifyBabelPlugins, i as ownVitestPackage, j as unsupportedReactNativeMessage, k as isBelowSupportedReactNative, l as babelParser, m as projectBabelTrigger, o as usesVitePlus, r as installedViteVersion, u as isPlainJavaScript, v as installedManifest, w as satisfiesNodeRange, y as detectEngine } from "./host-D0r3P_T1.mjs";
3
+ import { a as PRESET_MODULES, f as presetShadowing, i as LIBRARY_SETUP_FILES, m as testsItself, r as DEFAULT_ASSET_EXTS, s as autoDetectedPresetApplies, t as AUTO_DETECT_PRESETS } from "./preset-map-DdAexIwz.mjs";
4
+ import { n as ignorePattern, t as findNodeModuleMocks } from "./root-mocks-BNXeosbR.mjs";
4
5
  import { n as formatHotMemoryPlan, t as createHotMemoryPlan } from "./memory-Couw0Esx.mjs";
5
6
  import { createRequire } from "node:module";
6
- import { fileURLToPath } from "node:url";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
8
  import path from "node:path";
8
9
  import fs from "node:fs";
10
+ import os from "node:os";
11
+ import { VitestNativeError } from "./errors.mjs";
12
+ import { docsUrl } from "./docs-url.mjs";
9
13
  import { createNativeOwnershipPolicy, formatNativeOwnershipManifest } from "./native/ownership.mjs";
10
14
  import { resolveTransformPreset } from "./native/babel-preset.mjs";
11
15
  import { HOT_STATE_MANIFEST_ENTRIES } from "./native/state-manifest.mjs";
16
+ import { isDeepStrictEqual } from "node:util";
17
+ import { spawn, spawnSync } from "node:child_process";
18
+ import { StringDecoder } from "node:string_decoder";
12
19
  // src/cli/manifest.ts
13
20
  /**
14
21
  * Installed-package facts for the CLI, read from disk.
@@ -20,18 +27,6 @@ import { HOT_STATE_MANIFEST_ENTRIES } from "./native/state-manifest.mjs";
20
27
  * runtime) answers `require.resolve` for preset packages that are not installed.
21
28
  * The manifest file itself is what a package manager writes, so look for it.
22
29
  */
23
- /** A package's manifest, found by walking node_modules upward from root, or null. */
24
- function installedManifest(root, pkg) {
25
- for (let dir = path.resolve(root);; dir = path.dirname(dir)) {
26
- const file = path.join(dir, "node_modules", pkg, "package.json");
27
- if (fs.existsSync(file)) try {
28
- return JSON.parse(fs.readFileSync(file, "utf8"));
29
- } catch {
30
- return null;
31
- }
32
- if (path.dirname(dir) === dir) return null;
33
- }
34
- }
35
30
  /** The installed major version of `pkg`, or null when absent or unversioned. */
36
31
  function installedMajor(root, pkg) {
37
32
  const version = installedManifest(root, pkg)?.version;
@@ -84,20 +79,6 @@ const RELATIVE_FILES = [
84
79
  ".babelrc.mjs",
85
80
  ".babelrc.json"
86
81
  ];
87
- /**
88
- * @babel/core's `standardizeName` (lib/config/files/plugins.js), rule for rule except that a name
89
- * starting with `.` is taken as a relative path: `foo` →
90
- * `babel-plugin-foo`, `@babel/foo` → `@babel/plugin-foo` (`@babel/plugin-foo` unchanged),
91
- * `@scope/foo` → `@scope/babel-plugin-foo`, `@scope` → `@scope/babel-plugin`, `module:foo` →
92
- * `foo`. A relative or absolute path is returned as written.
93
- */
94
- function normalizeBabelName(name, kind = "plugin") {
95
- if (name.startsWith(".") || path.isAbsolute(name)) return name;
96
- const prefix = new RegExp(`^(?!@|module:|[^/]+/|babel-${kind}-)`);
97
- const babelOrg = new RegExp(`^(@babel/)(?!${kind}-|[^/]+/)`);
98
- const otherOrg = new RegExp(`^(@(?!babel/)[^/]+/)(?![^/]*babel-${kind}(?:-|/|$)|[^/]+/)`);
99
- return name.replace(prefix, `babel-${kind}-`).replace(babelOrg, `$1${kind}-`).replace(otherOrg, `$1babel-${kind}-`).replace(/^(@(?!babel$)[^/]+)$/, `$1/babel-${kind}`).replace(/^module:/, "");
100
- }
101
82
  function entryOf(item, kind) {
102
83
  const [target, options] = Array.isArray(item) ? item : [item, void 0];
103
84
  if (typeof target !== "string") return {
@@ -251,7 +232,7 @@ function readBabelConfig(root) {
251
232
  lazyInText.push(...lazyImportSettingsInText(text));
252
233
  for (const written of new Set([...text.matchAll(/["'`]([^"'`\s]+)["'`]/g)].map((m) => m[1]))) {
253
234
  const name = normalizeBabelName(written);
254
- if (KNOWN_PLUGINS.some((known) => known.names.includes(name))) plugins.push({
235
+ if (isKnownPlugin(name)) plugins.push({
255
236
  written,
256
237
  name
257
238
  });
@@ -262,82 +243,10 @@ function readBabelConfig(root) {
262
243
  evaluated,
263
244
  plugins,
264
245
  presets: presetEntries.map((p) => p.name),
246
+ presetEntries,
265
247
  lazyImports: [.../* @__PURE__ */ new Set([...lazyImportSettings(presetEntries, plugins), ...lazyInText])]
266
248
  };
267
249
  }
268
- /** Why a worklet plugin is not needed — only when the preset replacing its library is active. */
269
- function workletReason(pkg, active, root) {
270
- const preset = presetShadowing(pkg);
271
- if (preset && active.includes(preset)) return `transforms worklets for ${pkg}; the active ${preset} preset (auto-detected from ${Object.entries(AUTO_DETECT_PRESETS).filter(([, name]) => name === preset).map(([detect]) => detect).join(", ")}) replaces ${pkg} with a mock, so no worklet runs.`;
272
- if (!installedManifest(root, pkg)) return `transforms worklets for ${pkg}, which is not installed.`;
273
- return null;
274
- }
275
- const KNOWN_PLUGINS = [
276
- {
277
- names: ["babel-plugin-macros", "@lingui/babel-plugin-lingui-macro"],
278
- verdict: "required",
279
- reason: (e) => `${e.written} compiles macro imports away at build time; without it the macro module is imported for real and fails (e.g. "Cannot find module 'babel-plugin-macros'").`
280
- },
281
- {
282
- names: ["babel-plugin-module-resolver"],
283
- verdict: "alias",
284
- reason: () => `module-resolver rewrites import paths; its aliases map onto resolve.alias.`
285
- },
286
- {
287
- names: ["react-native-worklets/plugin"],
288
- verdict: "unneeded",
289
- reason: () => ""
290
- },
291
- {
292
- names: ["react-native-reanimated/plugin"],
293
- verdict: "unneeded",
294
- reason: () => ""
295
- },
296
- {
297
- names: ["babel-plugin-react-compiler"],
298
- verdict: "unneeded",
299
- reason: () => "React Compiler only adds memoization to components that follow the Rules of React (react.dev/learn/react-compiler); they render the same without it."
300
- }
301
- ];
302
- const unknownReason = (e) => `${e.written} ran on every file under babel-jest and does not run under vitest-native; check whether tests depend on what it does.`;
303
- function classifyBabelPlugins(report, root, active) {
304
- return report.plugins.map((entry) => {
305
- const worklets = /^(react-native-worklets|react-native-reanimated)\/plugin$/.exec(entry.name);
306
- if (worklets) {
307
- const reason = workletReason(worklets[1], active, root);
308
- return reason ? {
309
- ...entry,
310
- verdict: "unneeded",
311
- reason
312
- } : {
313
- ...entry,
314
- verdict: "unknown",
315
- reason: unknownReason(entry)
316
- };
317
- }
318
- const known = KNOWN_PLUGINS.find((k) => k.names.includes(entry.name));
319
- if (known) return {
320
- ...entry,
321
- verdict: known.verdict,
322
- reason: known.reason(entry, active)
323
- };
324
- if (/(^|[/-])macros?($|[/-])/.test(entry.name)) return {
325
- ...entry,
326
- verdict: "required",
327
- reason: `${entry.written} looks like a macro plugin; macros are compiled away at build time and fail when imported for real.`
328
- };
329
- return {
330
- ...entry,
331
- verdict: "unknown",
332
- reason: unknownReason(entry)
333
- };
334
- });
335
- }
336
- /** The installed major version of `vite`, or null. */
337
- function viteMajor(root) {
338
- const major = Number(installedViteVersion(root)?.replace(/^[^0-9]*/, "").split(".")[0]);
339
- return Number.isFinite(major) ? major : installedMajor(root, "vite");
340
- }
341
250
  /** Whether `name` is installed where the project resolves it. */
342
251
  function installed(root, name) {
343
252
  return installedManifest(root, name) !== null;
@@ -347,14 +256,11 @@ function pluginListSource(plugins) {
347
256
  return `[${plugins.map((p) => p.options === void 0 ? JSON.stringify(p.written) : `[${JSON.stringify(p.written)}, ${JSON.stringify(p.options)}]`).join(", ")}]`;
348
257
  }
349
258
  /**
350
- * How to run Babel plugins per Vite major. @vitejs/plugin-react 6 (Vite 8) dropped
351
- * Babel and points at @rolldown/plugin-babel; on Vite 7 and earlier its `babel`
352
- * option adds plugins.
259
+ * How to run Babel plugins: @vitejs/plugin-react 6 (Vite 8) dropped Babel and points at
260
+ * @rolldown/plugin-babel.
353
261
  */
354
- function babelRecipe(major, plugins) {
355
- const list = pluginListSource(plugins);
356
- if (major !== null && major < 8) return `install @vitejs/plugin-react and @babel/core, then add \`react({ babel: { plugins: ${list} } })\` (import react from '@vitejs/plugin-react') to plugins`;
357
- return `install @rolldown/plugin-babel and @babel/core, then add \`babel({ plugins: ${list} })\` (import babel from '@rolldown/plugin-babel') to plugins`;
262
+ function babelRecipe(plugins) {
263
+ return `install @rolldown/plugin-babel and @babel/core, then add \`babel({ plugins: ${pluginListSource(plugins)} })\` (import babel from '@rolldown/plugin-babel') to plugins`;
358
264
  }
359
265
  /** Whether a plugin's options are plain data (JSON.stringify drops functions silently). */
360
266
  function serializableOptions(entry) {
@@ -376,6 +282,13 @@ function serializableOptions(entry) {
376
282
  * engine resolution (and why), detected presets, RNTL/Node compatibility, and
377
283
  * config presence. Read-only; never mutates the project.
378
284
  */
285
+ /**
286
+ * The Vitest that runs here, as the peer check reports it: the project's own, or under
287
+ * Vite+ the copy this package loads.
288
+ */
289
+ function runningVitestVersion(from) {
290
+ return packageVersion(from, "vitest") ?? (usesVitePlus(from) ? ownVitestPackage()?.version ?? null : null);
291
+ }
379
292
  function packageVersion(root, name) {
380
293
  try {
381
294
  return createRequire(path.join(root, "package.json"))(`${name}/package.json`).version ?? null;
@@ -384,12 +297,11 @@ function packageVersion(root, name) {
384
297
  }
385
298
  }
386
299
  /**
387
- * The supported Node versions, as this package's own `engines.node` states them.
388
- * Single source: the manifest is what a package manager enforces at install time, so a
389
- * diagnostic must not carry its own copy of the range.
300
+ * The supported Node range: SUPPORTED_NODE, the constant the plugin enforces at startup,
301
+ * which a test holds equal to `engines.node` (what a package manager enforces).
390
302
  */
391
303
  function nodeRange() {
392
- const fallback = ">=22.13.0 <23 || >=24.3.0";
304
+ const fallback = SUPPORTED_NODE;
393
305
  for (let dir = path.dirname(fileURLToPath(import.meta.url));; dir = path.dirname(dir)) {
394
306
  const manifest = readManifest(path.join(dir, "package.json"));
395
307
  if (manifest?.name === "vitest-native") return manifest.engines?.node?.trim() || fallback;
@@ -404,37 +316,6 @@ function readManifest(file) {
404
316
  return null;
405
317
  }
406
318
  }
407
- const versionParts = (version) => {
408
- const [major = 0, minor = 0, patch = 0] = version.replace(/^v/, "").split(/[.-]/).map((part) => Number.parseInt(part, 10) || 0);
409
- return [
410
- major,
411
- minor,
412
- patch
413
- ];
414
- };
415
- const compareVersions = (a, b) => {
416
- const [x, y] = [versionParts(a), versionParts(b)];
417
- return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
418
- };
419
- /**
420
- * Whether `version` is in `range`: `||`-separated sets of space-separated comparators
421
- * (`>=`, `>`, `<=`, `<`, `=`), the forms `engines.node` uses. A version missing parts
422
- * reads them as 0 (`<23` is `<23.0.0`).
423
- */
424
- function satisfiesNodeRange(version, range) {
425
- return range.split("||").some((set) => set.trim().split(/\s+/).filter(Boolean).every((comparator) => {
426
- const match = /^(>=|<=|>|<|=)?\s*v?(\d[\w.-]*)$/.exec(comparator);
427
- if (!match) return false;
428
- const order = compareVersions(version, match[2]);
429
- switch (match[1] ?? "=") {
430
- case ">=": return order >= 0;
431
- case ">": return order > 0;
432
- case "<=": return order <= 0;
433
- case "<": return order < 0;
434
- default: return order === 0;
435
- }
436
- }));
437
- }
438
319
  /**
439
320
  * In Vitest's own precedence order: a `vitest.config.*` wins, and `vite.config.*`
440
321
  * is used when there is none.
@@ -464,77 +345,16 @@ function findConfigFile(root) {
464
345
  return null;
465
346
  }
466
347
  /** Source with comments removed, so a mention inside one cannot be mistaken for use. */
467
- function withoutComments(source) {
348
+ function withoutComments$1(source) {
468
349
  return source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:])\/\/[^\n]*/g, "$1");
469
350
  }
470
- const settingOf = (value) => value === void 0 ? null : value === "false" ? "off" : "set";
471
- /**
472
- * How a config sets Vitest's `fsModuleCache`, read as text, in each spelling: inside
473
- * `experimental: { ... }` (Vitest 4.0.11 and later) and anywhere else (the top-level
474
- * option, Vitest 5). `off` for a literal `false`, `set` for any other value, null when
475
- * that spelling is absent.
476
- */
477
- function fsModuleCacheSetting(source) {
478
- const code = withoutComments(source);
479
- const nested = /\bexperimental\s*:\s*\{[^{}]*?\bfsModuleCache\s*:\s*([^,}\s]*)/.exec(code);
480
- const rest = nested ? code.replace(nested[0], " ") : code;
481
- const top = /\bfsModuleCache\s*:\s*([^,}\s]*)/.exec(rest);
482
- return {
483
- experimental: settingOf(nested?.[1]),
484
- topLevel: settingOf(top?.[1])
485
- };
486
- }
487
- /** Whether `version` is at or above `[major, minor, patch]`. */
488
- function versionAtLeast(version, floor) {
489
- const parts = version.replace(/^[^0-9]*/, "").split(/[.-]/).slice(0, 3).map(Number);
490
- for (let i = 0; i < 3; i++) {
491
- const part = parts[i] ?? 0;
492
- if (part !== floor[i]) return part > floor[i];
493
- }
494
- return true;
495
- }
496
- /** The first Vitest with `experimental.fsModuleCache`. */
497
- const EXPERIMENTAL_FS_MODULE_CACHE_FROM = [
498
- 4,
499
- 0,
500
- 11
501
- ];
502
- const TROUBLESHOOTING_STALE_IMPORT = "https://danfry1.github.io/vitest-native/guide/troubleshooting#cannot-find-module-keeps-failing-after-the-missing-file-exists";
503
- /**
504
- * The transform-cache note for a Vitest the plugin does not turn the cache on for.
505
- * Empty where it does (fsModuleCacheOnByDefault, which the plugin reads too), and where
506
- * the config turns the cache off on purpose.
507
- */
508
- function transformCacheAdvice(vitestVersion, configSource) {
509
- const major = Number(vitestVersion?.replace(/^[^0-9]*/, "").split(".")[0]);
510
- if (!vitestVersion || !(major >= 4) || fsModuleCacheOnByDefault(major)) return [];
511
- const setting = configSource === null ? {
512
- experimental: null,
513
- topLevel: null
514
- } : fsModuleCacheSetting(configSource);
515
- if (setting.experimental === "off") return [];
516
- const hasOption = versionAtLeast(vitestVersion, EXPERIMENTAL_FS_MODULE_CACHE_FROM);
517
- const caveat = `A Vitest bug can keep a "Cannot find module" failure cached after the file exists (reproduced on Vitest 5.0.5, unverified on 4); ${TROUBLESHOOTING_STALE_IMPORT} lists when it happens and how to recover.`;
518
- if (setting.experimental === "set" && hasOption) return [`Vitest ${vitestVersion}: the config sets \`experimental.fsModuleCache\`; while it is on, transformed modules are kept on disk between runs. ${caveat}`];
519
- const lines = [`Vitest ${vitestVersion} re-transforms every imported module on each run, about half a second per thousand imported modules on one benchmark. Vitest 5 keeps transformed modules on disk between runs, and vitest-native turns that on.`];
520
- if (setting.topLevel !== null) lines.push("The config sets `test.fsModuleCache`, the Vitest 5 spelling, which has no effect on Vitest 4.");
521
- lines.push(hasOption ? `To keep them on disk on Vitest 4, set \`test.experimental.fsModuleCache: true\`. ${caveat}` : `Vitest 4.0.11 adds \`test.experimental.fsModuleCache\` to keep them on disk.`);
522
- return lines;
523
- }
524
- /**
525
- * The Vitest that runs here, as the peer check reports it: the project's own, or under
526
- * Vite+ the copy this package loads.
527
- */
528
- function runningVitestVersion(from) {
529
- return packageVersion(from, "vitest") ?? (usesVitePlus(from) ? ownVitestPackage()?.version ?? null : null);
530
- }
531
351
  /**
532
352
  * Whether a config is built on one imported from elsewhere — a shared preset in a
533
353
  * workspace, typically. Such a file legitimately never mentions vitest-native, and
534
354
  * reporting it as unconfigured is a false alarm on a working project.
535
355
  */
536
356
  function extendsSharedConfig(source) {
537
- const code = withoutComments(source);
357
+ const code = withoutComments$1(source);
538
358
  const imports = [...code.matchAll(/import\s+([^;]+?)\s+from\s*["']([^"'.][^"']*)["']/g)];
539
359
  for (const [, clause, specifier] of imports) {
540
360
  if (specifier === "vitest" || specifier.startsWith("vitest/")) continue;
@@ -562,7 +382,7 @@ function extendsSharedConfig(source) {
562
382
  * working project.
563
383
  */
564
384
  function analyzeConfigUsage(source) {
565
- const code = withoutComments(source);
385
+ const code = withoutComments$1(source);
566
386
  const named = /import\s*\{([^}]*)\}\s*from\s*["']vitest-native["']/.exec(code);
567
387
  const namespaced = /import\s*\*\s*as\s*([A-Za-z_$][\w$]*)\s*from\s*["']vitest-native["']/.exec(code);
568
388
  const required = /(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*["']vitest-native["']\s*\)/.exec(code);
@@ -625,6 +445,8 @@ function resolutionRoot(start, exists = fs.existsSync) {
625
445
  dir = parent;
626
446
  }
627
447
  }
448
+ /** doctor's warning for Node 24.13.0, which troubleshooting.md explains. */
449
+ const NODE_24_13_0_CRASH = `Node 24.13.0 can crash a test run at startup with a segmentation fault (an intermittent V8 garbage-collection crash on worker threads). Use another Node 24 release, such as 24.14 or later. See ${docsUrl("/guide/troubleshooting#node-24-13-0-segmentation-fault-at-startup")}`;
628
450
  function runDoctor(root, nodeVersion = process.versions.node) {
629
451
  const lines = [];
630
452
  let ok = true;
@@ -640,14 +462,16 @@ function runDoctor(root, nodeVersion = process.versions.node) {
640
462
  lines.push(`vitest-native doctor — ${root}`);
641
463
  lines.push("", "Runtime");
642
464
  const range = nodeRange();
643
- if (satisfiesNodeRange(nodeVersion, range)) pass(`Node ${nodeVersion} (supported: ${range})`);
644
- else fail(`Node ${nodeVersion} — vitest-native supports Node ${range}.`);
465
+ if (satisfiesNodeRange(nodeVersion, range)) {
466
+ pass(`Node ${nodeVersion} (supported: ${range})`);
467
+ if (nodeVersion === "24.13.0") warn(NODE_24_13_0_CRASH);
468
+ } else fail(unsupportedNodeMessage(nodeVersion));
645
469
  lines.push("", "Peer dependencies");
646
- for (const { name, minimum, maximumMajor, minimumByMajor, optional } of PEER_REQUIREMENTS) {
470
+ for (const { name, minimum, maximumMajor, optional } of PEER_REQUIREMENTS) {
647
471
  if (optional) continue;
648
472
  const from = rootFor(name);
649
473
  const running = name === "vite" ? installedViteVersion(from) : name === "vitest" ? runningVitestVersion(from) : null;
650
- const error = validatePeerDependency(name, minimum, from, maximumMajor, minimumByMajor, running);
474
+ const error = validatePeerDependency(name, minimum, from, maximumMajor, running);
651
475
  if (error) fail(error);
652
476
  else {
653
477
  pass(`${name} ${running ?? packageVersion(from, name)}`);
@@ -659,8 +483,12 @@ function runDoctor(root, nodeVersion = process.versions.node) {
659
483
  const decision = detectEngine("auto", rootFor("@react-native/babel-preset"));
660
484
  const transformPreset = resolveTransformPreset(rootFor("@react-native/babel-preset"));
661
485
  const presetLabel = transformPreset ? `${transformPreset.name} ${transformPreset.version}` : "a React Native Babel preset";
662
- if (decision.engine === "native") pass(`engine 'auto' resolves to NATIVE — real React Native${rnVersion ? ` ${rnVersion}` : ""} with ${presetLabel} + @babel/core present.`);
663
- else if (rnVersion) warn(`engine 'auto' resolves to MOCK: react-native ${rnVersion} is installed but no React Native Babel preset (@react-native/babel-preset, or Expo's from SDK 56) and/or @babel/core resolve. Install both as devDependencies to run the real-RN native engine.`);
486
+ if (decision.engine === "native") {
487
+ pass(`engine 'auto' resolves to NATIVE — real React Native${rnVersion ? ` ${rnVersion}` : ""} with ${presetLabel} + @babel/core present.`);
488
+ const rnProblem = rnVersion && unsupportedReactNativeMessage(rnVersion);
489
+ if (rnProblem && isBelowSupportedReactNative(rnVersion)) fail(rnProblem);
490
+ else if (rnProblem) warn(rnProblem);
491
+ } else if (rnVersion) warn(`engine 'auto' resolves to MOCK: react-native ${rnVersion} is installed but no React Native Babel preset (@react-native/babel-preset, or Expo's from SDK 56) and/or @babel/core resolve. Install both as devDependencies to run the real-RN native engine.`);
664
492
  else warn("engine 'auto' resolves to MOCK: react-native is not installed. That is fine for pure-logic suites; install react-native (+ its babel preset) for the native engine.");
665
493
  if (decision.engine === "native") {
666
494
  const inferredRoot = configRoot;
@@ -688,9 +516,8 @@ function runDoctor(root, nodeVersion = process.versions.node) {
688
516
  else {
689
517
  const rntlMajor = Number(rntl.split(".")[0]);
690
518
  const rntlReq = PEER_REQUIREMENTS.find((r) => r.name === "@testing-library/react-native");
691
- const rntlError = rntlReq && validatePeerDependency(rntlReq.name, rntlReq.minimum, root, rntlReq.maximumMajor, rntlReq.minimumByMajor);
519
+ const rntlError = rntlReq && validatePeerDependency(rntlReq.name, rntlReq.minimum, root, rntlReq.maximumMajor);
692
520
  if (rntlError) warn(rntlError);
693
- else if (rntlMajor >= 14 && !satisfiesNodeRange(nodeVersion, ">=22.13.0")) fail(`@testing-library/react-native ${rntl} requires Node >= 22.13, but this is Node ${nodeVersion}. Upgrade Node or pin @testing-library/react-native@13.`);
694
521
  else if (rntlMajor >= 14 && !packageVersion(rootFor("test-renderer"), "test-renderer")) fail(`@testing-library/react-native ${rntl} requires the 'test-renderer' package, which is not installed. Every render() will fail with "Cannot find module 'test-renderer'". Install it:\n\n npm install -D test-renderer\n`);
695
522
  else pass(`@testing-library/react-native ${rntl}${rntlMajor >= 14 ? " (14 is async: await render/fireEvent)" : ""}`);
696
523
  }
@@ -701,8 +528,10 @@ function runDoctor(root, nodeVersion = process.versions.node) {
701
528
  if (!installedManifest(root, pkg)) continue;
702
529
  installedAny = true;
703
530
  if (installedTestsItself(root, pkg)) lines.push(` · ${pkg} ${installedMajor(root, pkg)} runs its own test mode under Vitest, so no preset replaces it`);
704
- else if (!autoDetectedPresetApplies(preset, decision.engine)) lines.push(` · ${pkg} runs as itself under the native engine, on its native-module mocks; the ${preset} preset applies under the mock engine or with \`presets: { ${preset}: true }\``);
705
- else detected.push(`${pkg} → ${preset}`);
531
+ else if (!autoDetectedPresetApplies(preset, decision.engine)) {
532
+ const setupFile = LIBRARY_SETUP_FILES[preset];
533
+ lines.push(` · ${pkg} runs as itself under the native engine, ` + (setupFile ? `with its own Jest setup (${setupFile}); ` : `on its native-module mocks; `) + `the ${preset} preset applies under the mock engine or with \`presets: { ${preset}: true }\``);
534
+ } else detected.push(`${pkg} → ${preset}`);
706
535
  }
707
536
  if (detected.length) for (const d of detected) pass(d);
708
537
  else if (!installedAny) lines.push(" (none — no preset-covered packages installed)");
@@ -713,38 +542,63 @@ function runDoctor(root, nodeVersion = process.versions.node) {
713
542
  warn(unsupported);
714
543
  } else if (expo) {
715
544
  lines.push("", "Expo");
716
- pass((decision.engine === "native" ? `expo ${expo} detected. Under the native engine Expo modules run their real JavaScript on native-module mocks, as under jest-expo (unless the config sets \`engine: 'mock'\` or \`presets: { expo: true }\`, where the expo preset shadows ${PRESET_MODULES.expo.join(", ")}). ` : `expo ${expo} detected. Under the mock engine the expo preset shadows ${PRESET_MODULES.expo.join(", ")}; other Expo modules load their real JavaScript. `) + `Coming from jest-expo, run \`vitest-native migrate\`. See https://danfry1.github.io/vitest-native/guide/expo`);
545
+ pass((decision.engine === "native" ? `expo ${expo} detected. Under the native engine Expo modules run their real JavaScript on native-module mocks, as under jest-expo (unless the config sets \`engine: 'mock'\` or \`presets: { expo: true }\`, where the expo preset shadows ${PRESET_MODULES.expo.join(", ")}). ` : `expo ${expo} detected. Under the mock engine the expo preset shadows ${PRESET_MODULES.expo.join(", ")}; other Expo modules load their real JavaScript. `) + `Coming from jest-expo, run \`vitest-native migrate\`. See ${docsUrl("/guide/expo")}`);
717
546
  }
718
547
  const babel = readBabelConfig(root);
548
+ const engineAppliedPlugins = [];
719
549
  if (babel.source) {
720
550
  lines.push("", "Babel");
721
- const classified = classifyBabelPlugins(babel, root, activePresets(root, [], decision.engine));
722
- const required = classified.filter((p) => p.verdict === "required");
723
- for (const p of classified) if (p.verdict === "required") warn(`${p.reason} Required: ${babelRecipe(viteMajor(rootFor("vite")), required)}.`);
724
- else if (p.verdict === "alias") warn(`${p.reason} \`vitest-native migrate\` writes them; otherwise add them to resolve.alias.`);
725
- else if (p.verdict === "unknown") warn(p.reason);
726
- else lines.push(` · ${p.written}: ${p.reason}`);
551
+ const active = activePresets(root, [], decision.engine);
552
+ const classified = classifyBabelPlugins(babel, root, active);
553
+ const byEngine = (name, kind, options) => projectBabelTrigger({
554
+ name,
555
+ kind,
556
+ options
557
+ }, root, active);
558
+ const babelCore = installedManifest(root, "@babel/core") !== null;
559
+ for (const p of babel.presetEntries ?? []) {
560
+ const reason = byEngine(p.name, "preset", p.options);
561
+ if (reason && !babelCore) warn(`preset ${p.name} needs projectBabel (${reason}), which needs @babel/core installed in the project.`);
562
+ else if (reason) lines.push(` · preset ${p.name}: applied by the engine where needed (${reason}).`);
563
+ }
564
+ const required = classified.filter((p) => p.verdict === "required" && !byEngine(p.name, "plugin", p.options));
565
+ for (const p of classified) {
566
+ const reason = byEngine(p.name, "plugin", p.options);
567
+ if (reason && !babelCore) warn(`${p.written} needs projectBabel (${reason}), which needs @babel/core installed in the project; it does not resolve from here. Add @babel/core as a devDependency.`);
568
+ else if (reason) {
569
+ lines.push(` · ${p.written}: applied by the engine where needed (${reason}).`);
570
+ engineAppliedPlugins.push(p.name);
571
+ } else if (p.verdict === "required") warn(`${p.reason} Required: ${babelRecipe(required)}.`);
572
+ else if (p.verdict === "alias") warn(`${p.reason} \`vitest-native migrate\` writes them; otherwise add them to resolve.alias.`);
573
+ else if (p.verdict === "unknown") warn(p.reason);
574
+ else lines.push(` · ${p.written}: ${p.reason}`);
575
+ }
727
576
  if (!babel.evaluated) lines.push(` · ${babel.source} could not be evaluated; only plugins recognized by name are listed.`);
728
577
  else if (classified.length === 0) lines.push(` · ${babel.source} declares no plugins.`);
729
578
  }
730
579
  lines.push("", "Config");
731
580
  const configFile = findConfigFile(configRoot);
732
- let configSource = null;
733
581
  if (!configFile) warn("no vitest.config.* found — run `vitest-native init` to create one.");
734
582
  else {
735
583
  const content = fs.readFileSync(path.join(configRoot, configFile), "utf8");
736
- configSource = content;
737
584
  const usage = analyzeConfigUsage(content);
738
- if (usage.imports && usage.invokes) pass(`${configFile} uses vitest-native.`);
739
- else if (usage.imports) warn(`${configFile} imports vitest-native but never calls reactNative() — the plugin is not in \`plugins: [...]\`, so React Native imports will not resolve.`);
585
+ const code = withoutComments$1(content);
586
+ if (/@rolldown\/plugin-babel|vite-plugin-babel/.test(code)) {
587
+ const listed = new Set([...code.matchAll(/["'`]([^"'`\s]+)["'`]/g)].map((m) => normalizeBabelName(m[1])));
588
+ const repeated = engineAppliedPlugins.filter((name) => listed.has(name));
589
+ if (repeated.length) warn(`${configFile}'s babel() lists ${repeated.join(", ")}, which the engine already applies to the project source that needs it; the entry is redundant and can be removed.`);
590
+ }
591
+ if (usage.imports && usage.invokes) {
592
+ pass(`${configFile} uses vitest-native.`);
593
+ const model = /\bownershipModel\s*:\s*["'](resolver|resolution)["']/.exec(withoutComments$1(content))?.[1];
594
+ if (model) {
595
+ lines.push(` · experimental.ownershipModel: '${model}' is on: Vite and Node's loaders resolve bare imports through one shared resolver (${docsUrl("/guide/plugin-options#experimental")}).`);
596
+ if (model === "resolution") lines.push(" · 'resolution' turns on experimental.nodeMocks: a vi.mock also reaches the modules Node loads, and a mock Node cannot have synchronously fails as MOCK_NOT_SEEN_BY_NODE.");
597
+ }
598
+ } else if (usage.imports) warn(`${configFile} imports vitest-native but never calls reactNative() — the plugin is not in \`plugins: [...]\`, so React Native imports will not resolve.`);
740
599
  else if (extendsSharedConfig(content)) lines.push(` · ${configFile} builds on a shared config, so this cannot tell from here whether the plugin is wired up. Check the config it extends.`);
741
600
  else warn(`${configFile} exists but does not import vitest-native` + (content.includes("vitest-native") ? " (it is only mentioned in a comment)" : "") + " — add `reactNative()` to `plugins: [...]`, or run `vitest-native init`.");
742
601
  }
743
- const advice = transformCacheAdvice(runningVitestVersion(rootFor("vitest")), configSource);
744
- if (advice.length) {
745
- lines.push("", "Transform cache");
746
- for (const line of advice) lines.push(` · ${line}`);
747
- }
748
602
  lines.push("", ok ? "✓ No blocking problems found." : "✗ Blocking problems found (see ✗ above).");
749
603
  return {
750
604
  lines,
@@ -765,7 +619,7 @@ const HOT_RUNTIME_NOTE = [
765
619
  "Hot runtime: off by default. `hotRuntime: 'auto'` reuses workers across test files instead of",
766
620
  "starting a fresh one per file. Whether that is faster depends on the suite, so measure it on yours.",
767
621
  "It has known differences from per-file isolation:",
768
- " https://danfry1.github.io/vitest-native/guide/troubleshooting#a-test-passes-on-its-own-but-fails-when-run-with-other-files"
622
+ ` ${docsUrl("/guide/troubleshooting#a-test-passes-on-its-own-but-fails-when-run-with-other-files")}`
769
623
  ];
770
624
  const PLAIN_CONFIG = `import { defineConfig } from 'vitest/config'
771
625
  import { reactNative } from 'vitest-native'
@@ -809,22 +663,53 @@ function renderInitConfig(jestCompat, vitePlus = false) {
809
663
  const source = jestCompat ? JEST_COMPAT_CONFIG : PLAIN_CONFIG;
810
664
  return vitePlus ? source.replace("import { defineConfig } from 'vitest/config'", "import { defineConfig } from 'vite-plus'") : source;
811
665
  }
666
+ /**
667
+ * Vitest's config file names, in the order it looks them up (CONFIG_NAMES and
668
+ * CONFIG_EXTENSIONS in vitest/dist/chunks/constants): the first that exists is the one
669
+ * it loads, every vitest.config.* before any vite.config.*, and it does not merge the two.
670
+ */
671
+ const CONFIG_EXTENSIONS = [
672
+ ".ts",
673
+ ".mts",
674
+ ".cts",
675
+ ".js",
676
+ ".mjs",
677
+ ".cjs"
678
+ ];
679
+ const VITEST_CONFIG_FILES = CONFIG_EXTENSIONS.map((ext) => `vitest.config${ext}`);
680
+ const VITE_CONFIG_FILES = CONFIG_EXTENSIONS.map((ext) => `vite.config${ext}`);
681
+ function firstExisting(root, names) {
682
+ return names.find((name) => fs.existsSync(path.join(root, name))) ?? null;
683
+ }
684
+ /**
685
+ * The config Vitest would load from `root`, or null when there is none to replace. A
686
+ * vite.config.* counts only under Vite+, which keeps tests in it; elsewhere a new
687
+ * vitest.config.* goes beside it, and the takeover is reported.
688
+ */
812
689
  function existingConfig(root, vitePlus) {
813
- for (const name of [
814
- ...vitePlus ? [
815
- "vite.config.ts",
816
- "vite.config.mts",
817
- "vite.config.js",
818
- "vite.config.mjs"
819
- ] : [],
820
- "vitest.config.ts",
821
- "vitest.config.mts",
822
- "vitest.config.js",
823
- "vitest.config.mjs",
824
- "vitest.config.cts",
825
- "vitest.config.cjs"
826
- ]) if (fs.existsSync(path.join(root, name))) return name;
827
- return null;
690
+ return firstExisting(root, [...VITEST_CONFIG_FILES, ...vitePlus ? VITE_CONFIG_FILES : []]);
691
+ }
692
+ /**
693
+ * Printed when a new vitest.config.* takes over from a vite.config.* Vitest was reading:
694
+ * from then on, that file's plugins, `resolve` options and aliases no longer reach tests.
695
+ */
696
+ function viteConfigTakeoverNotice(viteConfig, written) {
697
+ const specifier = `./${viteConfig.replace(/\.[cm]?[jt]s$/, "")}`;
698
+ return [
699
+ `! Vitest now loads ${written} instead of ${viteConfig}: it reads a vite.config.* only when`,
700
+ ` there is no vitest.config.*, and does not merge the two. Plugins, \`resolve\` options and`,
701
+ ` aliases in ${viteConfig} no longer apply to tests. If tests need them, extend it in ${written}:`,
702
+ ``,
703
+ ` import { defineConfig, mergeConfig } from 'vitest/config'`,
704
+ ` import viteConfig from '${specifier}'`,
705
+ ``,
706
+ ` export default mergeConfig(viteConfig, defineConfig({ /* the settings this file has now */ }))`,
707
+ ``,
708
+ ` If ${viteConfig} exports a function, call it:`,
709
+ ` defineConfig((env) => mergeConfig(viteConfig(env), { /* ... */ }))`,
710
+ ``,
711
+ ` or copy over the settings tests need.`
712
+ ];
828
713
  }
829
714
  function runInit(root, opts = {}) {
830
715
  const lines = [];
@@ -846,22 +731,28 @@ function runInit(root, opts = {}) {
846
731
  ],
847
732
  ok: false
848
733
  };
734
+ if (existing && /\.c[jt]s$/.test(existing)) return {
735
+ lines: [`✗ ${existing} is a CommonJS config. vitest-native writes ES module configs and does not`, ` rewrite a CommonJS one; remove or rename ${existing}, then re-run.`],
736
+ ok: false
737
+ };
849
738
  if (existing && !opts.force) return {
850
739
  lines: [`✗ ${existing} already exists — not overwriting. Re-run with --force to replace it,`, ` or run \`vitest-native migrate\` to analyze an existing Jest setup first.`],
851
740
  ok: false
852
741
  };
853
- const file = vitePlus ? "vite.config.ts" : fs.existsSync(path.join(root, "tsconfig.json")) ? "vitest.config.mts" : "vitest.config.mjs";
742
+ const file = existing ?? (vitePlus ? "vite.config.ts" : fs.existsSync(path.join(root, "tsconfig.json")) ? "vitest.config.mts" : "vitest.config.mjs");
743
+ const viteConfig = existing ? null : firstExisting(root, VITE_CONFIG_FILES);
854
744
  const target = path.join(root, file);
855
745
  fs.writeFileSync(target, renderInitConfig(opts.jestCompat ?? false, vitePlus));
856
- lines.push(`✓ wrote ${file}${opts.jestCompat ? " (jest-compat variant)" : ""}`);
857
- if (existing && opts.force) lines.push(` (replaced ${existing === file ? "it" : existing})`);
746
+ const notices = [...existing ? [` (replaced the existing ${existing}, the config Vitest loads)`] : [], ...viteConfig ? ["", ...viteConfigTakeoverNotice(viteConfig, file)] : []];
747
+ lines.push(`✓ wrote ${file}${opts.jestCompat ? " (jest-compat variant)" : ""}`, ...notices);
858
748
  lines.push("", "Next steps:", vitePlus ? ` 1. add a script: "test": "vp test"` : ` 1. add a script: "test": "vitest"`, vitePlus ? ` 2. run: vp test` : ` 2. run: npx vitest`, ` 3. check the environment: npx vitest-native doctor`);
859
749
  if (opts.jestCompat) lines.push(` 4. migrating a Jest suite? \`vitest-native migrate\` maps your jest.config onto this file.`);
860
750
  lines.push("", ...HOT_RUNTIME_NOTE);
861
751
  return {
862
752
  lines,
863
753
  ok: true,
864
- wrote: file
754
+ wrote: file,
755
+ notices
865
756
  };
866
757
  }
867
758
  const MAX_EXPANSIONS = 256;
@@ -984,7 +875,7 @@ function topLevelAlternatives(body) {
984
875
  const NAME = /^(@[a-z0-9~-][a-z0-9._~-]*\/)?[a-z0-9~-][a-z0-9._~-]*$/i;
985
876
  const SCOPE = /^@[a-z0-9~-][a-z0-9._~-]*$/i;
986
877
  const PREFIX = /^(@[a-z0-9~-][a-z0-9._~-]*(\/[a-z0-9._~-]*)?|[a-z0-9~-][a-z0-9._~-]*)$/i;
987
- function classify(expansion) {
878
+ function classify$1(expansion) {
988
879
  const trimmed = expansion.replace(new RegExp(`/$`), "/");
989
880
  if (trimmed.includes("\0")) return null;
990
881
  if (trimmed.endsWith("/")) {
@@ -1013,7 +904,7 @@ function extractAllowlistPackages(pattern) {
1013
904
  const entries = [];
1014
905
  const unparseable = [];
1015
906
  for (const alternative of topLevelAlternatives(body)) {
1016
- const classified = tryExpand(alternative, true)?.filter((e) => !e.startsWith(".")).map(classify);
907
+ const classified = tryExpand(alternative, true)?.filter((e) => !e.startsWith(".")).map(classify$1);
1017
908
  if (!classified || classified.some((c) => c === null)) {
1018
909
  unparseable.push(alternative);
1019
910
  continue;
@@ -1137,11 +1028,12 @@ function loadJestPreset(root, preset) {
1137
1028
  * against root-relative paths. So `<rootDir>/x` anchors at the root, anything else may
1138
1029
  * start mid-segment (`bskylink/.*` also ignores `notbskylink/`, hence `**\/*`), `/.*\/`
1139
1030
  * spans whole segments (`*\/**`), a trailing `/`, `/.*` or `.*` leaves the rest free,
1140
- * a pattern ending mid-segment covers a file and a directory, and `$` is left for a human.
1031
+ * a pattern ending mid-segment covers a file and a directory, and a `$`-anchored literal
1032
+ * (`\\.d\\.ts$`) becomes one file glob only when `directories` shows it prunes no directory.
1141
1033
  * Jest substitutes `<rootDir>` unescaped; it is read here as the directory it names.
1142
1034
  * A match starting above the root has no relative form and is not attempted.
1143
1035
  */
1144
- function ignorePatternToGlobs(pattern) {
1036
+ function ignorePatternToGlobs(pattern, directories) {
1145
1037
  let rest = pattern;
1146
1038
  let anchored = false;
1147
1039
  if (rest.startsWith("<rootDir>")) {
@@ -1155,13 +1047,13 @@ function ignorePatternToGlobs(pattern) {
1155
1047
  if (!expansions) return null;
1156
1048
  const globs = [];
1157
1049
  for (const expansion of expansions) {
1158
- const converted = expansionToGlobs(expansion, anchored, endAnchored);
1050
+ const converted = expansionToGlobs(expansion, anchored, endAnchored, directories);
1159
1051
  if (!converted) return null;
1160
1052
  globs.push(...converted);
1161
1053
  }
1162
1054
  return [...new Set(globs)];
1163
1055
  }
1164
- function expansionToGlobs(expansion, anchored, endAnchored) {
1056
+ function expansionToGlobs(expansion, anchored, endAnchored, directories) {
1165
1057
  let s = expansion;
1166
1058
  if (/[*?[\]{}()!\\]/.test(s.replaceAll("\0", ""))) return null;
1167
1059
  if (s.endsWith("\0")) {
@@ -1170,7 +1062,12 @@ function expansionToGlobs(expansion, anchored, endAnchored) {
1170
1062
  }
1171
1063
  if (!anchored) s = s.replace(new RegExp(`^+`), "");
1172
1064
  if (s === "" || anchored && s.startsWith(`/`)) return null;
1173
- if (endAnchored) return s.endsWith("/") ? [] : null;
1065
+ if (endAnchored) {
1066
+ if (s.endsWith("/")) return [];
1067
+ if (!directories || s.includes("\0")) return null;
1068
+ if ((typeof directories === "function" ? directories() : directories).some((dir) => anchored ? `/${dir}` === s : `/${dir}`.endsWith(s))) return null;
1069
+ return [anchored ? s.slice(1) : s.startsWith("/") ? `**/${s.slice(1)}` : `**/*${s}`];
1070
+ }
1174
1071
  const parts = s.split(`//`);
1175
1072
  if (parts.some((part) => part.includes("\0") || part === "")) return null;
1176
1073
  let glob = parts.join("/*/**/");
@@ -1208,7 +1105,7 @@ function extensionExclude(moduleFileExtensions) {
1208
1105
  * config (null when none). Merged as `setupPreset` does — the user's keys win,
1209
1106
  * `modulePathIgnorePatterns` concatenates — and defaulted as `normalize` does.
1210
1107
  */
1211
- function translateDiscovery(options, preset, major) {
1108
+ function translateDiscovery(options, preset, major, directories) {
1212
1109
  const defaults = JEST_DEFAULTS[major ?? 30];
1213
1110
  const automatic = [];
1214
1111
  const attention = [];
@@ -1277,7 +1174,7 @@ function translateDiscovery(options, preset, major) {
1277
1174
  const extra = key === "modulePathIgnorePatterns" ? " Jest also hid these paths from module resolution; Vite has no equivalent, which only matters if a test imported a module from one." : "";
1278
1175
  for (const pattern of patterns) {
1279
1176
  if (pattern === "/node_modules/") continue;
1280
- const globs = ignorePatternToGlobs(pattern);
1177
+ const globs = ignorePatternToGlobs(pattern, directories);
1281
1178
  if (globs) {
1282
1179
  exclude.push(...globs);
1283
1180
  automatic.push(`${key} '${pattern}' → test.exclude ${JSON.stringify(globs)}.${extra}`);
@@ -1297,7 +1194,7 @@ function translateDiscovery(options, preset, major) {
1297
1194
  };
1298
1195
  }
1299
1196
  /** Jest CLI flags that take a value (https://jestjs.io/docs/cli). */
1300
- const VALUED_FLAGS = /* @__PURE__ */ new Set([
1197
+ const VALUED_FLAGS$1 = /* @__PURE__ */ new Set([
1301
1198
  "testTimeout",
1302
1199
  "maxWorkers",
1303
1200
  "w",
@@ -1377,7 +1274,7 @@ function parseJestScript(script, command) {
1377
1274
  const [rawName, inline] = token.replace(/^--?/, "").split(/=(.*)/s, 2);
1378
1275
  const name = rawName.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
1379
1276
  if (inline !== void 0) flags.set(name, inline);
1380
- else if (VALUED_FLAGS.has(name) && args[i + 1] !== void 0) flags.set(name, args[++i]);
1277
+ else if (VALUED_FLAGS$1.has(name) && args[i + 1] !== void 0) flags.set(name, args[++i]);
1381
1278
  else if (name === "bail" && /^\d+$/.test(args[i + 1] ?? "")) flags.set(name, args[++i]);
1382
1279
  else flags.set(name, true);
1383
1280
  }
@@ -1394,6 +1291,252 @@ function booleanFlag(value) {
1394
1291
  if (value === true || value === "true") return true;
1395
1292
  if (value === "false") return false;
1396
1293
  }
1294
+ /**
1295
+ * The project's directories, root-relative with `/`, as Vitest walks them: outside
1296
+ * node_modules and .git (configDefaults.exclude). A symlink to a directory is listed
1297
+ * (tinyglobby follows it) but not walked into.
1298
+ */
1299
+ function projectDirectories(root) {
1300
+ const dirs = [];
1301
+ const entries = (rel) => {
1302
+ try {
1303
+ return fs.readdirSync(path.join(root, rel), { withFileTypes: true });
1304
+ } catch {
1305
+ return [];
1306
+ }
1307
+ };
1308
+ const linksToDirectory = (file) => {
1309
+ try {
1310
+ return fs.statSync(file).isDirectory();
1311
+ } catch {
1312
+ return false;
1313
+ }
1314
+ };
1315
+ const walk = (rel) => {
1316
+ for (const entry of entries(rel)) {
1317
+ if (entry.name === "node_modules" || entry.name === ".git") continue;
1318
+ const child = rel ? `${rel}/${entry.name}` : entry.name;
1319
+ if (entry.isDirectory()) {
1320
+ dirs.push(child);
1321
+ walk(child);
1322
+ } else if (entry.isSymbolicLink() && linksToDirectory(path.join(root, child))) dirs.push(child);
1323
+ }
1324
+ };
1325
+ walk("");
1326
+ return dirs;
1327
+ }
1328
+ // src/cli/jest-preset.ts
1329
+ /**
1330
+ * A Jest preset's settings, read as Jest applies them, for migrate.
1331
+ *
1332
+ * Jest applies a preset under the project's config (jest-config `setupPreset`): the
1333
+ * project's keys win, setupFiles and setupFilesAfterEnv run the preset's files first,
1334
+ * moduleNameMapper tries the project's patterns first, and transform and globals merge.
1335
+ * A project-local preset is often a known one spread and extended
1336
+ * (`module.exports = { ...require('jest-expo/jest-preset') }`); migrate recognises it
1337
+ * as that preset, so it gets the same translation, and carries over what it adds.
1338
+ */
1339
+ /** The presets migrate translates by name, in the order a local preset is matched against. */
1340
+ const KNOWN_PRESETS = [
1341
+ "jest-expo",
1342
+ "jest-expo/ios",
1343
+ "jest-expo/android",
1344
+ "jest-expo/universal",
1345
+ "jest-expo/web",
1346
+ "jest-expo/node",
1347
+ "react-native",
1348
+ "@react-native/jest-preset"
1349
+ ];
1350
+ /** Keys the discovery translation reads from the preset itself (translateDiscovery). */
1351
+ const DISCOVERY_KEYS = /* @__PURE__ */ new Set([
1352
+ "testMatch",
1353
+ "testRegex",
1354
+ "testPathIgnorePatterns",
1355
+ "modulePathIgnorePatterns",
1356
+ "moduleFileExtensions",
1357
+ "roots"
1358
+ ]);
1359
+ const isLocal = (preset) => preset.startsWith(".") || preset.startsWith("<rootDir>") || path.isAbsolute(preset);
1360
+ const isPlainObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
1361
+ /** What `local` sets beyond `base`: new keys, changed values, array items and entries `base` lacks. */
1362
+ function beyond(local, base) {
1363
+ const own = {};
1364
+ for (const [key, value] of Object.entries(local)) {
1365
+ const from = base[key];
1366
+ if (isDeepStrictEqual(value, from)) continue;
1367
+ if (Array.isArray(value) && Array.isArray(from)) own[key] = value.filter((item) => !from.some((f) => isDeepStrictEqual(f, item)));
1368
+ else if (isPlainObject(value) && isPlainObject(from)) own[key] = Object.fromEntries(Object.entries(value).filter(([k, v]) => !isDeepStrictEqual(v, from[k])));
1369
+ else own[key] = value;
1370
+ }
1371
+ return own;
1372
+ }
1373
+ /**
1374
+ * The known preset a local preset spreads: every key of the known preset is present,
1375
+ * and more of its values are kept than changed. The best match wins (jest-expo/ios
1376
+ * and jest-expo share keys).
1377
+ */
1378
+ function recognise(root, local) {
1379
+ let best;
1380
+ for (const name of KNOWN_PRESETS) {
1381
+ const loaded = loadJestPreset(root, name);
1382
+ if (!("config" in loaded)) continue;
1383
+ const keys = Object.keys(loaded.config);
1384
+ if (keys.length === 0 || !keys.every((k) => k in local)) continue;
1385
+ const kept = keys.filter((k) => isDeepStrictEqual(local[k], loaded.config[k])).length;
1386
+ if (kept * 2 <= keys.length) continue;
1387
+ if (!best || kept > best.kept) best = {
1388
+ name,
1389
+ config: loaded.config,
1390
+ kept
1391
+ };
1392
+ }
1393
+ return best;
1394
+ }
1395
+ function resolveJestPreset(root, preset) {
1396
+ const known = KNOWN_PRESETS.includes(preset);
1397
+ const loaded = loadJestPreset(root, preset);
1398
+ if (!("config" in loaded)) return {
1399
+ name: preset,
1400
+ label: `'${preset}'`,
1401
+ loaded: null,
1402
+ loadError: loaded.error,
1403
+ own: {},
1404
+ known
1405
+ };
1406
+ const config = loaded.config;
1407
+ if (known) return {
1408
+ name: preset,
1409
+ label: `'${preset}'`,
1410
+ loaded: config,
1411
+ own: {},
1412
+ known
1413
+ };
1414
+ const match = isLocal(preset) ? recognise(root, config) : void 0;
1415
+ const own = match ? beyond(config, match.config) : { ...config };
1416
+ for (const key of DISCOVERY_KEYS) delete own[key];
1417
+ delete own.preset;
1418
+ for (const [key, value] of Object.entries(own)) if (Array.isArray(value) && value.length === 0 || isPlainObject(value) && Object.keys(value).length === 0) delete own[key];
1419
+ return match ? {
1420
+ name: match.name,
1421
+ label: `'${preset}' (${match.name}'s preset, spread)`,
1422
+ loaded: config,
1423
+ own,
1424
+ known: true
1425
+ } : {
1426
+ name: preset,
1427
+ label: `'${preset}'`,
1428
+ loaded: config,
1429
+ own,
1430
+ known: false
1431
+ };
1432
+ }
1433
+ /** The project's config with the preset's settings under it, as jest-config's setupPreset merges them. */
1434
+ function withPresetSettings(config, own) {
1435
+ const merged = {
1436
+ ...own,
1437
+ ...config
1438
+ };
1439
+ for (const key of ["setupFiles", "setupFilesAfterEnv"]) if (Array.isArray(own[key]) && Array.isArray(config[key])) merged[key] = [...own[key], ...config[key]];
1440
+ for (const key of [
1441
+ "moduleNameMapper",
1442
+ "transform",
1443
+ "globals"
1444
+ ]) if (isPlainObject(own[key]) && isPlainObject(config[key])) merged[key] = {
1445
+ ...own[key],
1446
+ ...config[key]
1447
+ };
1448
+ if (isPlainObject(own.moduleNameMapper) && isPlainObject(config.moduleNameMapper)) merged.moduleNameMapper = {
1449
+ ...config.moduleNameMapper,
1450
+ ...Object.fromEntries(Object.entries(own.moduleNameMapper).filter(([k]) => !(k in config.moduleNameMapper)))
1451
+ };
1452
+ return merged;
1453
+ }
1454
+ // src/cli/superseded.ts
1455
+ /**
1456
+ * Jest settings a project wires up for a library vitest-native handles itself, which
1457
+ * migrate reports as covered (delete) instead of carrying them over. Each recogniser is
1458
+ * narrow: it matches a setting whose whole effect is known, and anything more stays
1459
+ * with the project.
1460
+ *
1461
+ * Reanimated, wherever its preset applies:
1462
+ * - Its and Worklets' Jest resolvers: the native engine applies both itself where their
1463
+ * own mocks run (native/jest-resolvers.mjs); elsewhere the preset replaces the package.
1464
+ * - A snapshot serializer that only strips `jestAnimatedProps`, `jestAnimatedStyle` and
1465
+ * `jestInlineStyle`: Reanimated's real AnimatedComponent adds those props under Jest;
1466
+ * its mock's createAnimatedComponent and the preset's module add none.
1467
+ * - A setup file that only calls `setUpTests()`: vitest-native registers
1468
+ * toHaveAnimatedStyle and toHaveAnimatedProps itself, and Reanimated's own versions read
1469
+ * props its mock does not set (presets/reanimated.ts keeps the engine's).
1470
+ */
1471
+ const RESOLVER = /(?:^|node_modules\/)(react-native-(?:reanimated|worklets))\/jest\/resolver(?:\.js)?$/;
1472
+ /** The library whose own Jest resolver `resolver` names, or null. */
1473
+ function libraryResolver(resolver) {
1474
+ return RESOLVER.exec(resolver.replace(/\\/g, "/"))?.[1] ?? null;
1475
+ }
1476
+ const REANIMATED_TEST_PROPS = /* @__PURE__ */ new Set([
1477
+ "jestAnimatedProps",
1478
+ "jestAnimatedStyle",
1479
+ "jestInlineStyle"
1480
+ ]);
1481
+ /**
1482
+ * The source without its whole-line comments, or null when a comment marker appears
1483
+ * anywhere else (a trailing comment, `src/*` inside a comment, `//` in a string): a
1484
+ * regex that strips comments across lines can swallow real code between a stray `/*`
1485
+ * and a later `*\/`, and a file that cannot be read exactly is kept.
1486
+ */
1487
+ function withoutComments(source) {
1488
+ const code = [];
1489
+ let inBlock = false;
1490
+ for (const raw of source.split("\n")) {
1491
+ const line = raw.trim();
1492
+ if (inBlock) {
1493
+ const end = line.indexOf("*/");
1494
+ if (end === -1) {
1495
+ if (line.includes("/*") || line.includes("//")) return null;
1496
+ continue;
1497
+ }
1498
+ if (end !== line.length - 2) return null;
1499
+ inBlock = false;
1500
+ } else if (line.startsWith("//")) {
1501
+ if (line.includes("/*") || line.includes("*/")) return null;
1502
+ } else if (line.startsWith("/*")) {
1503
+ const end = line.indexOf("*/", 2);
1504
+ if (line.indexOf("/*", 2) !== -1 || line.includes("//")) return null;
1505
+ if (end === -1) inBlock = true;
1506
+ else if (end !== line.length - 2) return null;
1507
+ } else if (line.includes("/*") || line.includes("*/") || line.includes("//")) return null;
1508
+ else code.push(raw);
1509
+ }
1510
+ return inBlock ? null : code.join("\n");
1511
+ }
1512
+ /**
1513
+ * Whether a serializer's source only strips Reanimated's Jest props: it names at least
1514
+ * one of them, loads nothing, and its only other string is `object` (typeof checks).
1515
+ */
1516
+ function stripsOnlyReanimatedProps(source) {
1517
+ const code = withoutComments(source);
1518
+ if (code === null || /\brequire\s*\(|^\s*import\b/m.test(code)) return false;
1519
+ const strings = [...code.matchAll(/(['"`])((?:\\.|(?!\1)[^\\])*)\1/g)].map((m) => m[2]);
1520
+ return strings.some((s) => REANIMATED_TEST_PROPS.has(s)) && strings.every((s) => REANIMATED_TEST_PROPS.has(s) || s === "object");
1521
+ }
1522
+ const Q = `(['"])react-native-reanimated\\1`;
1523
+ const SETUP_STATEMENTS = [
1524
+ /^(['"])use strict\1$/,
1525
+ new RegExp(`^import\\s*\\{\\s*setUpTests\\s*\\}\\s*from\\s*${Q}$`),
1526
+ new RegExp(`^(?:const|let|var)\\s*\\{\\s*setUpTests\\s*\\}\\s*=\\s*require\\(\\s*${Q}\\s*\\)$`),
1527
+ /^setUpTests\(\s*\)$/,
1528
+ new RegExp(`^require\\(\\s*${Q}\\s*\\)\\.setUpTests\\(\\s*\\)$`)
1529
+ ];
1530
+ /**
1531
+ * Whether a setup file's source only calls Reanimated's `setUpTests()`, with no
1532
+ * arguments (a frame-time argument is a setting the project chose).
1533
+ */
1534
+ function onlyCallsSetUpTests(source) {
1535
+ const code = withoutComments(source);
1536
+ if (code === null) return false;
1537
+ const statements = code.split(/[;\n]/).map((s) => s.trim()).filter(Boolean);
1538
+ return statements.filter((s) => /setUpTests\(\s*\)$/.test(s)).length === 1 && statements.every((s) => SETUP_STATEMENTS.some((re) => re.test(s)));
1539
+ }
1397
1540
  // src/cli/untranspiled.ts
1398
1541
  /**
1399
1542
  * Evidence that a package needs `transform`: a `.js` file under one of its entry
@@ -1403,13 +1546,6 @@ function booleanFlag(value) {
1403
1546
  * both. Parsed with the project's @babel/parser and no syntax plugins; without the
1404
1547
  * parser there is no evidence and nothing is claimed.
1405
1548
  */
1406
- function babelParser(root) {
1407
- const req = createRequire(path.join(root, "package.json"));
1408
- for (const from of [() => req, () => createRequire(req.resolve("@babel/core"))]) try {
1409
- return from()("@babel/parser").parse;
1410
- } catch {}
1411
- return null;
1412
- }
1413
1549
  /** Directories in a package that are not part of what it runs. */
1414
1550
  const SKIP_DIRS = /* @__PURE__ */ new Set([
1415
1551
  "node_modules",
@@ -1489,15 +1625,7 @@ function untranspiledFile(root, pkg) {
1489
1625
  continue;
1490
1626
  }
1491
1627
  if (!/\.(js|cjs|mjs)$/.test(name) || budget-- <= 0) continue;
1492
- try {
1493
- parse(fs.readFileSync(file, "utf8"), {
1494
- sourceType: "unambiguous",
1495
- allowReturnOutsideFunction: true,
1496
- allowAwaitOutsideFunction: true
1497
- });
1498
- } catch {
1499
- return path.relative(dir, file).split(path.sep).join("/");
1500
- }
1628
+ if (!isPlainJavaScript(parse, file)) return path.relative(dir, file).split(path.sep).join("/");
1501
1629
  }
1502
1630
  }
1503
1631
  return null;
@@ -1637,6 +1765,24 @@ function exactMapperKey(pattern) {
1637
1765
  const expansions = m ? tryExpand(m[1], true) : null;
1638
1766
  return expansions?.length === 1 && !expansions[0].includes("\0") ? expansions[0] : null;
1639
1767
  }
1768
+ /**
1769
+ * A `^prefix/(.*)$` → `<rootDir>/dir/$1` moduleNameMapper, which is a plain prefix
1770
+ * alias: the literal prefix (escapes read as literals, as exactMapperKey reads them)
1771
+ * and the project-relative target directory, or null.
1772
+ */
1773
+ function prefixMapper(pattern, target) {
1774
+ const m = /^\^(.+)\/\((\.\*|\.\+)\)\$?$/.exec(pattern);
1775
+ if (!m || typeof target !== "string") return null;
1776
+ const expansions = tryExpand(m[1], true);
1777
+ if (expansions?.length !== 1 || expansions[0].includes("\0")) return null;
1778
+ const t = /^(<rootDir>|\.)(\/.*)?\/\$1$/.exec(target);
1779
+ if (!t || target.indexOf("$") !== target.length - 2) return null;
1780
+ return {
1781
+ key: expansions[0],
1782
+ dir: `.${t[2] ?? ""}`,
1783
+ rest: m[2]
1784
+ };
1785
+ }
1640
1786
  /** `pkg` and `/sub` of a bare specifier (scope-aware). */
1641
1787
  function splitSpecifier(specifier) {
1642
1788
  const parts = specifier.split("/");
@@ -1684,7 +1830,7 @@ function analyzeJestConfig(root) {
1684
1830
  }
1685
1831
  } catch {}
1686
1832
  const explicitConfig = scriptFlags?.flags.get("config") ?? scriptFlags?.flags.get("c");
1687
- const { source, config, error: configError } = loadJestConfig(root, typeof explicitConfig === "string" ? explicitConfig : void 0);
1833
+ const { source, config: projectConfig, error: configError } = loadJestConfig(root, typeof explicitConfig === "string" ? explicitConfig : void 0);
1688
1834
  const automatic = [];
1689
1835
  const attention = [];
1690
1836
  if (source && configError) attention.push(`${source} could not be loaded (${configError}), so none of its settings are in the suggested config; carry them over by hand.`);
@@ -1699,11 +1845,18 @@ function analyzeJestConfig(root) {
1699
1845
  const extraImports = [];
1700
1846
  const extraPlugins = [];
1701
1847
  let excludeGlobs = [];
1848
+ let jestRoots = null;
1849
+ let jestIgnorePatterns = null;
1850
+ let directories;
1702
1851
  let needsUrlImport = false;
1703
1852
  const pluginOptions = [];
1704
- const jestPreset = typeof config?.preset === "string" ? config.preset : void 0;
1853
+ const resolvedPreset = typeof projectConfig?.preset === "string" ? resolveJestPreset(root, projectConfig.preset) : void 0;
1854
+ const presetKeys = Object.keys(resolvedPreset?.own ?? {});
1855
+ const config = projectConfig && resolvedPreset && presetKeys.length ? withPresetSettings(projectConfig, resolvedPreset.own) : projectConfig;
1856
+ const jestPreset = resolvedPreset?.name;
1705
1857
  const navigationOff = /^jest-expo(\/(ios|android|universal))?$/.test(jestPreset ?? "") && activePresets(root).includes("navigation") && !fs.existsSync(path.join(root, "__mocks__", "@react-navigation"));
1706
1858
  const active = activePresets(root, navigationOff ? ["navigation"] : []);
1859
+ const runsWithOwnSetup = (preset) => LIBRARY_SETUP_FILES[preset] !== void 0 && !active.includes(preset);
1707
1860
  const autoInlined = new Set(detectEcosystemPackages(root, [], [], [], active));
1708
1861
  const addAlias = (key, value) => {
1709
1862
  if (aliasKeys.has(key)) return false;
@@ -1711,6 +1864,18 @@ function analyzeJestConfig(root) {
1711
1864
  aliasEntries.push(`${JSON.stringify(key)}: ${value}`);
1712
1865
  return true;
1713
1866
  };
1867
+ const projectSource = (file) => {
1868
+ if (/^(?:<rootDir>\/|\.\/)?node_modules\//.test(file)) return null;
1869
+ const rel = file.replace(/^<rootDir>\/?/, "");
1870
+ const base = path.resolve(root, rel);
1871
+ const found = [
1872
+ base,
1873
+ `${base}.js`,
1874
+ `${base}.ts`
1875
+ ].find((candidate) => fs.statSync(candidate, { throwIfNoEntry: false })?.isFile());
1876
+ return found === void 0 ? null : fs.readFileSync(found, "utf8");
1877
+ };
1878
+ const reanimatedActive = active.includes("reanimated");
1714
1879
  const absolutePath = (relative) => {
1715
1880
  needsUrlImport = true;
1716
1881
  return `fileURLToPath(new URL(${JSON.stringify(relative)}, import.meta.url))`;
@@ -1721,30 +1886,33 @@ function analyzeJestConfig(root) {
1721
1886
  handled.add(key);
1722
1887
  return config[key];
1723
1888
  };
1724
- const preset = take("preset");
1725
- if (preset === "react-native" || preset === "@react-native/jest-preset") automatic.push(`preset: '${preset}' → replaced by the reactNative() plugin.`);
1889
+ take("preset");
1890
+ const preset = resolvedPreset?.name;
1891
+ const label = resolvedPreset?.label;
1892
+ if (preset === "react-native" || preset === "@react-native/jest-preset") automatic.push(`preset: ${label} → replaced by the reactNative() plugin.`);
1726
1893
  else if (preset === "jest-expo" || preset === "jest-expo/ios" || preset === "jest-expo/android") {
1727
1894
  const android = preset === "jest-expo/android";
1728
1895
  if (android) pluginOptions.push(`platform: 'android'`);
1729
- automatic.push(`preset: '${preset}' → replaced by the reactNative() plugin${android ? " with platform: 'android'" : ""}.`);
1730
- attention.push(`preset: '${preset}' — ${expoPresetCoverage()}.`);
1731
- } else if (preset === "jest-expo/universal") attention.push("preset: 'jest-expo/universal' runs one Jest project per platform. Define a Vitest project for each native platform (reactNative({ platform: 'ios' }) and reactNative({ platform: 'android' })); its web and node projects are not React Native renders and stay outside vitest-native.");
1732
- else if (preset === "jest-expo/web" || preset === "jest-expo/node") attention.push(`preset: '${preset}' targets ${preset.slice(10)}, not a React Native render; run these suites without vitest-native.`);
1733
- else if (preset) attention.push(`preset: '${preset}' — unknown preset; review what it configured.`);
1734
- let presetConfig = null;
1735
- if (preset) {
1736
- const loaded = loadJestPreset(root, preset);
1737
- if ("config" in loaded) presetConfig = loaded.config;
1738
- else attention.push(`preset: '${preset}' could not be loaded (${loaded.error}), so its testMatch/testPathIgnorePatterns could not be read; test.include falls back to Jest's defaults — compare with the preset.`);
1739
- }
1896
+ automatic.push(`preset: ${label} → replaced by the reactNative() plugin${android ? " with platform: 'android'" : ""}.`);
1897
+ attention.push(`preset: ${label} — ${expoPresetCoverage()}.`);
1898
+ } else if (preset === "jest-expo/universal") attention.push(`preset: ${label} runs one Jest project per platform. Define a Vitest project for each native platform (reactNative({ platform: 'ios' }) and reactNative({ platform: 'android' })); its web and node projects are not React Native renders and stay outside vitest-native.`);
1899
+ else if (preset === "jest-expo/web" || preset === "jest-expo/node") attention.push(`preset: ${label} targets ${preset.slice(10)}, not a React Native render; run these suites without vitest-native.`);
1900
+ else if (preset && resolvedPreset?.loaded) attention.push(`preset: ${label} — not a preset vitest-native translates by name; its settings are translated below as Jest applies them, under this config's own. Review what else it did.`);
1901
+ else if (preset) attention.push(`preset: ${label} — unknown preset; review what it configured.`);
1902
+ if (presetKeys.length) automatic.push(`preset: ${label} also sets ${list(presetKeys)} → each is handled below like this config's own keys, merged with them as Jest merges a preset's.`);
1903
+ const presetConfig = resolvedPreset?.loaded ?? null;
1904
+ if (resolvedPreset && !resolvedPreset.loaded) attention.push(`preset: ${label} could not be loaded (${resolvedPreset.loadError}), so its testMatch/testPathIgnorePatterns could not be read; test.include falls back to Jest's defaults — compare with the preset.`);
1740
1905
  for (const key of ["setupFiles", "setupFilesAfterEnv"]) {
1741
1906
  const files = take(key);
1742
1907
  if (!files?.length) continue;
1743
1908
  for (const f of files) {
1744
- const setupPackage = /^(@[^/]+\/[^/]+|[^@./][^/]*)\//.exec(f)?.[1];
1909
+ const asRequest = f.replace(/^(?:<rootDir>\/|\.\/)?node_modules\//, "");
1910
+ const setupPackage = /^(@[^/]+\/[^/]+|[^@./<][^/]*)\//.exec(asRequest)?.[1];
1745
1911
  const setupPreset = setupPackage ? presetShadowing(setupPackage) : void 0;
1746
1912
  if (/react-native\/jest\/setup/.test(f)) presetCovered.push(`${key}: '${f}' — the plugin injects its own setup; delete.`);
1747
1913
  else if (setupPreset && active.includes(setupPreset)) presetCovered.push(`${key}: '${f}' — ${setupPackage}'s own test setup; the auto-detected ${setupPreset} preset shadows ${setupPackage}, and this file's jest.mock() calls would replace it; delete.`);
1914
+ else if (setupPreset && runsWithOwnSetup(setupPreset) && asRequest.replace(/\.js$/, "") === LIBRARY_SETUP_FILES[setupPreset]?.replace(/\.js$/, "")) presetCovered.push(`${key}: '${f}' — ${setupPackage}'s own test setup, which the native engine runs before the setup files (${LIBRARY_SETUP_FILES[setupPreset]}); delete.`);
1915
+ else if (reanimatedActive && onlyCallsSetUpTests(projectSource(f) ?? "")) presetCovered.push(`${key}: '${f}' — only calls Reanimated's setUpTests(), whose matchers cannot see the rendered style here; vitest-native registers toHaveAnimatedStyle and toHaveAnimatedProps itself; delete.`);
1748
1916
  else if (/jest-expo/.test(f)) attention.push(`${key}: '${f}' — ${expoPresetCoverage()}.`);
1749
1917
  else if (f.startsWith("<rootDir>")) {
1750
1918
  setupFiles.push(absolutePath(f.replace(/^<rootDir>\/?/, "./")));
@@ -1759,6 +1927,12 @@ function analyzeJestConfig(root) {
1759
1927
  if (mapper) for (const [pattern, target] of Object.entries(mapper)) {
1760
1928
  const assetGroup = /\\\.\(\??:?([a-z0-9|]+)\)\$?$/i.exec(pattern);
1761
1929
  const literal = exactMapperKey(pattern);
1930
+ const prefix = assetGroup ? null : prefixMapper(pattern, target);
1931
+ const plainPrefix = prefix && ![
1932
+ "@",
1933
+ "~",
1934
+ "src"
1935
+ ].includes(prefix.key) ? prefix : null;
1762
1936
  if (assetGroup) {
1763
1937
  const exts = assetGroup[1].toLowerCase().split("|");
1764
1938
  const missing = exts.filter((e) => !DEFAULT_ASSET_EXTS.includes(e));
@@ -1767,6 +1941,10 @@ function analyzeJestConfig(root) {
1767
1941
  pluginOptions.push(`assetExts: ${JSON.stringify(missing)}`);
1768
1942
  automatic.push(`moduleNameMapper '${pattern}' — ${list(missing)} ${missing.length === 1 ? "is" : "are"} not among the extensions the plugin handles by default → reactNative({ assetExts: ${JSON.stringify(missing)} }).`);
1769
1943
  }
1944
+ } else if (plainPrefix) {
1945
+ const find = `${regexLiteral(plainPrefix.key).slice(0, -2)}\\/(${plainPrefix.rest})$/`;
1946
+ regexAliases.push(`{ find: ${find}, replacement: ${absolutePath(plainPrefix.dir)} + "/$1" }`);
1947
+ automatic.push(`moduleNameMapper '${pattern}' → resolve.alias { find: ${find} } (absolute path).`);
1770
1948
  } else if (/^\^?@\/|\^~\/|\^src\//.test(pattern)) {
1771
1949
  const aliasKey = pattern.replace(/[\^$]/g, "").replace(/\((\.\*|\.\+)\)\$?$/, "").replace(/\/$/, "");
1772
1950
  const aliasTarget = String(target).replace(/^<rootDir>\/?/, "./").replace(/\/\$1$/, "").replace(/\/$/, "");
@@ -1865,7 +2043,9 @@ function analyzeJestConfig(root) {
1865
2043
  const value = take(key);
1866
2044
  if (value !== void 0) discoveryOptions[key] = value;
1867
2045
  }
1868
- const discovery = translateDiscovery(discoveryOptions, presetConfig, jestMajor(root));
2046
+ if (Array.isArray(discoveryOptions.modulePathIgnorePatterns)) jestIgnorePatterns = discoveryOptions.modulePathIgnorePatterns.filter((p) => typeof p === "string");
2047
+ if (Array.isArray(discoveryOptions.roots)) jestRoots = discoveryOptions.roots.filter((r) => typeof r === "string").map((r) => path.posix.normalize(r.replace(/^<rootDir>/, ".")).replace(/\/$/, "") || ".");
2048
+ const discovery = translateDiscovery(discoveryOptions, presetConfig, jestMajor(root), () => directories ??= projectDirectories(root));
1869
2049
  if (discovery.include) testEntries.push(`include: [${discovery.include.map((g) => JSON.stringify(g)).join(", ")}]`);
1870
2050
  excludeGlobs = discovery.exclude;
1871
2051
  automatic.push(...discovery.automatic);
@@ -1892,7 +2072,9 @@ function analyzeJestConfig(root) {
1892
2072
  "transform",
1893
2073
  "globals",
1894
2074
  "snapshotSerializers",
1895
- "reporters"
2075
+ "reporters",
2076
+ "watchPathIgnorePatterns",
2077
+ "workerIdleMemoryLimit"
1896
2078
  ]) if (config[key] !== void 0) {
1897
2079
  handled.add(key);
1898
2080
  if (key === "transform") dropped.push(`transform — Babel/esbuild transforms are the plugin's job; dropped.`);
@@ -1900,25 +2082,63 @@ function analyzeJestConfig(root) {
1900
2082
  const vitestKey = key === "resetMocks" ? "mockReset" : key;
1901
2083
  automatic.push(key === vitestKey ? `${key} → test.${key} (same name in Vitest).` : `${key} → test.${vitestKey} (Vitest's name for it).`);
1902
2084
  testEntries.push(`${vitestKey}: ${JSON.stringify(config[key])}`);
1903
- } else if (key === "snapshotSerializers") attention.push(`snapshotSerializers — Vitest uses expect.addSnapshotSerializer; vitest-native ships one for RN trees.`);
2085
+ } else if (key === "snapshotSerializers") {
2086
+ const serializers = Array.isArray(config[key]) ? config[key] : [];
2087
+ const rest = [];
2088
+ for (const entry of serializers) {
2089
+ const code = typeof entry === "string" ? projectSource(entry) : null;
2090
+ if (reanimatedActive && code !== null && stripsOnlyReanimatedProps(code)) presetCovered.push(`snapshotSerializers '${entry}' — strips the jest* props Reanimated's real components add under Jest; the Reanimated preset's components add none; delete.`);
2091
+ else rest.push(String(entry));
2092
+ }
2093
+ if (rest.length || !serializers.length) attention.push(`snapshotSerializers${rest.length ? ` ${rest.map((r) => `'${r}'`).join(", ")}` : ""} — Vitest has no such key: register each with expect.addSnapshotSerializer() in a setup file. React trees need none: they print as under Jest.`);
2094
+ } else if (key === "watchPathIgnorePatterns") dropped.push(`${key} — affects only Jest's watch mode; Vitest's watch mode reruns by the module graph (tune it with server.watch.ignored if needed); dropped.`);
2095
+ else if (key === "workerIdleMemoryLimit") dropped.push(`${key} — Vitest recycles workers by memory only in its vm pools (test.vmMemoryLimit), which vitest-native does not use; dropped. Watch memory on the first full run.`);
1904
2096
  else dropped.push(`${key} — no vitest-native equivalent needed; dropped.`);
1905
2097
  }
1906
2098
  if (config.clearMocks === void 0) {
1907
2099
  testEntries.push(`clearMocks: false`);
1908
2100
  automatic.push("Jest keeps mock calls between tests unless clearMocks is set → test.clearMocks: false (Vitest 5 clears them before each test by default).");
1909
2101
  }
2102
+ const resolver = typeof config.resolver === "string" ? config.resolver : void 0;
2103
+ const resolverLibrary = resolver ? libraryResolver(resolver) : null;
2104
+ if (resolverLibrary && (reanimatedActive || active.includes("worklets"))) {
2105
+ handled.add("resolver");
2106
+ presetCovered.push(`resolver: '${resolver}' — ${resolverLibrary}'s own Jest resolver: the native engine applies Reanimated's and Worklets' resolvers itself where their own mocks run, and their presets replace the packages elsewhere; delete.`);
2107
+ }
1910
2108
  for (const key of Object.keys(config)) if (!handled.has(key)) attention.push(`'${key}' — unrecognized Jest key; review manually.`);
1911
2109
  }
1912
- const mocksDir = path.join(root, "__mocks__");
1913
- if (fs.existsSync(mocksDir)) for (const entry of fs.readdirSync(mocksDir)) {
1914
- const name = entry.replace(/\.(js|cjs|mjs|ts|tsx)$/, "");
1915
- const candidates = fs.statSync(path.join(mocksDir, entry)).isDirectory() ? fs.readdirSync(path.join(mocksDir, entry)).map((f) => `${name}/${f.replace(/\.(js|cjs|mjs|ts|tsx)$/, "")}`) : [name];
1916
- for (const candidate of candidates) {
1917
- const preset = presetShadowing(candidate);
1918
- if (preset && active.includes(preset)) presetCovered.push(`__mocks__/${candidate} — the auto-detected ${preset} preset shadows ${candidate}; delete the manual mock.`);
1919
- else if (installedManifest(root, candidate) && installedTestsItself(root, candidate)) attention.push(`__mocks__/${candidate} — ${candidate} ${installedMajor(root, candidate)} runs its own test mode under Vitest, so no preset replaces it, and Vitest applies a root __mocks__ file only through vi.mock; the library's test mode stands in for this mock.`);
2110
+ const snapshotFiles = (directories ??= projectDirectories(root)).filter((dir) => path.posix.basename(dir) === "__snapshots__").reduce((count, dir) => {
2111
+ let names = [];
2112
+ try {
2113
+ names = fs.readdirSync(path.join(root, dir));
2114
+ } catch {
2115
+ names = [];
1920
2116
  }
2117
+ return count + names.filter((name) => name.endsWith(".snap")).length;
2118
+ }, 0);
2119
+ if (snapshotFiles > 0) attention.push(`${snapshotFiles} Jest snapshot file${snapshotFiles === 1 ? "" : "s"} (__snapshots__/*.snap) — most entries need one re-record. Vitest names a snapshot inside a describe 'group > test 1' where Jest wrote 'group test 1', and a snapshot of React Native components differs: Jest's preset renders stand-ins named View and Text with the props as given, and vitest-native renders React Native's own host components (RCTView, RCTText) with the props React Native passes them. Once the rest of the suite passes, re-record them once with \`vitest -u\` and review the diff. Vitest also rewrites each file's first line to its own header when it runs it.`);
2120
+ const mockRoots = jestRoots ?? ["."];
2121
+ const ignored = (jestIgnorePatterns ?? []).flatMap((pattern) => {
2122
+ const regex = ignorePattern(pattern, root);
2123
+ return regex ? [regex] : [];
2124
+ });
2125
+ const manualMocks = findNodeModuleMocks(mockRoots.map((r) => path.resolve(root, r)), root, ignored);
2126
+ const relative = (file) => path.relative(root, file).split(path.sep).join("/");
2127
+ const byFile = /* @__PURE__ */ new Map();
2128
+ for (const mock of manualMocks.mocks) byFile.set(mock.file, [...byFile.get(mock.file) ?? [], mock.spec]);
2129
+ for (const [file, specs] of byFile) {
2130
+ const shown = relative(file).replace(/\.[^./]+$/, "");
2131
+ const candidate = specs[specs.length - 1];
2132
+ const preset = presetShadowing(candidate);
2133
+ const applied = `${shown} → applied to ${specs.slice().reverse().join(" and ")} in every test by jestMockTransform(), with no jest.mock() call, as Jest applies it.`;
2134
+ if (preset && active.includes(preset)) presetCovered.push(`${shown} — the auto-detected ${preset} preset shadows ${candidate}; delete the manual mock.`);
2135
+ else if (preset && runsWithOwnSetup(preset)) presetCovered.push(`${shown} — the native engine runs ${candidate} with its own Jest setup (${LIBRARY_SETUP_FILES[preset]}), which replaces its native layer; delete the manual mock.`);
2136
+ else if (installedTestsItself(root, candidate)) automatic.push(`${applied} ${candidate} ${installedMajor(root, candidate)} also runs its own test mode under Vitest, which can stand in for this mock.`);
2137
+ else automatic.push(applied);
1921
2138
  }
2139
+ for (const duplicate of manualMocks.duplicates) attention.push(`duplicate manual mock ${duplicate.name}: ${duplicate.files.map(relative).join(", ")} — Jest warns and uses one; jestMockTransform() uses the last listed. Delete the others.`);
2140
+ const transformOptions = [...jestRoots && jestRoots.some((r) => r !== ".") ? [`roots: [${jestRoots.map((r) => JSON.stringify(r)).join(", ")}]`] : [], ...manualMocks.mocks.length > 0 && jestIgnorePatterns?.length ? [`modulePathIgnorePatterns: [${jestIgnorePatterns.map((p) => JSON.stringify(p)).join(", ")}]`] : []];
2141
+ const transformCall = transformOptions.length ? `jestMockTransform({ ${transformOptions.join(", ")} })` : "jestMockTransform()";
1922
2142
  if (navigationOff) {
1923
2143
  pluginOptions.push(`presets: { navigation: false }`);
1924
2144
  automatic.push("jest-expo renders the real React Navigation → presets: { navigation: false }, so screens keep running in real navigators.");
@@ -1926,14 +2146,40 @@ function analyzeJestConfig(root) {
1926
2146
  const babel = readBabelConfig(root);
1927
2147
  if (babel.source) {
1928
2148
  const classified = classifyBabelPlugins(babel, root, active);
1929
- const required = classified.filter((p) => p.verdict === "required");
1930
- const vite = viteMajor(root);
2149
+ const engineApplied = /* @__PURE__ */ new Map();
2150
+ for (const p of classified) {
2151
+ const reason = projectBabelTrigger({
2152
+ name: p.name,
2153
+ kind: "plugin",
2154
+ options: p.options
2155
+ }, root, active);
2156
+ if (reason) engineApplied.set(`plugin:${p.name}`, reason);
2157
+ }
2158
+ for (const p of babel.presetEntries ?? []) {
2159
+ const reason = projectBabelTrigger({
2160
+ name: p.name,
2161
+ kind: "preset",
2162
+ options: p.options
2163
+ }, root, active);
2164
+ if (reason) engineApplied.set(`preset:${p.name}`, reason);
2165
+ }
2166
+ const babelCore = installed(root, "@babel/core");
2167
+ if (engineApplied.size && !babelCore) {
2168
+ const names = [...engineApplied.keys()].map((k) => k.slice(k.indexOf(":") + 1));
2169
+ attention.push(`${babel.source}: ${list(names)} must reach your own source, and the engine applies ${names.length === 1 ? "it" : "them"} with your Babel config (projectBabel 'auto'), which needs @babel/core installed in the project. It does not resolve from here (often it came only with babel-jest). Add @babel/core as a devDependency.`);
2170
+ }
2171
+ for (const [key, reason] of babelCore ? engineApplied : /* @__PURE__ */ new Map()) {
2172
+ const [kind, name] = [key.slice(0, key.indexOf(":")), key.slice(key.indexOf(":") + 1)];
2173
+ automatic.push(`${babel.source}: ${kind} ${name} → applied by the engine to the project source that needs it (projectBabel 'auto'; ${reason}); nothing to add.`);
2174
+ }
2175
+ const byEngine = (p) => engineApplied.has(`plugin:${p.name}`);
2176
+ const required = classified.filter((p) => p.verdict === "required" && !byEngine(p));
1931
2177
  if (required.length) {
1932
- if (vite !== null && vite >= 8 && installed(root, "@rolldown/plugin-babel") && installed(root, "@babel/core") && required.every(serializableOptions)) {
2178
+ if (installed(root, "@rolldown/plugin-babel") && installed(root, "@babel/core") && required.every(serializableOptions)) {
1933
2179
  extraImports.push(`import babel from '@rolldown/plugin-babel'`);
1934
2180
  extraPlugins.push(`babel({ plugins: ${pluginListSource(required)} })`);
1935
2181
  for (const p of required) automatic.push(`${babel.source}: ${p.reason} → babel() from @rolldown/plugin-babel.`);
1936
- } else for (const p of required) attention.push(`${babel.source}: ${p.reason} Required: ${babelRecipe(vite, required)}.`);
2182
+ } else for (const p of required) attention.push(`${babel.source}: ${p.reason} Required: ${babelRecipe(required)}.`);
1937
2183
  }
1938
2184
  for (const p of classified.filter((c) => c.verdict === "alias")) {
1939
2185
  const options = p.options ?? {};
@@ -1947,7 +2193,7 @@ function analyzeJestConfig(root) {
1947
2193
  if (options.root !== void 0) attention.push(`${babel.source}: module-resolver root ${JSON.stringify(options.root)} — bare imports resolved from those directories need resolve.alias entries by hand.`);
1948
2194
  }
1949
2195
  for (const p of classified.filter((c) => c.verdict === "unneeded")) dropped.push(`${babel.source}: ${p.written} — ${p.reason}`);
1950
- for (const p of classified.filter((c) => c.verdict === "unknown")) attention.push(`${babel.source}: ${p.reason}`);
2196
+ for (const p of classified.filter((c) => c.verdict === "unknown" && !byEngine(c))) attention.push(`${babel.source}: ${p.reason}`);
1951
2197
  if (babel.lazyImports.length) attention.push(`${babel.source}: ${babel.lazyImports.join(", ")} — under Jest a package import ran only when the test first used it; here every import runs when its file loads. A module a test never touched is now evaluated, so a partial jest.mock of something it needs can fail (e.g. "requireOptionalNativeModule is not a function"). Give such a mock the rest of the module: jest.mock('x', () => ({ ...jest.requireActual('x'), ... })).`);
1952
2198
  if (!babel.evaluated) attention.push(`${babel.source} could not be evaluated, so only plugins recognized by name are listed; review it for others.`);
1953
2199
  }
@@ -1972,7 +2218,7 @@ export default defineConfig({
1972
2218
  plugins: [${[
1973
2219
  transformLine,
1974
2220
  ...extraPlugins,
1975
- "jestMockTransform()"
2221
+ transformCall
1976
2222
  ].join(", ")}],
1977
2223
  resolve: {
1978
2224
  dedupe: ['react', 'react-test-renderer', 'react-is'],
@@ -2058,56 +2304,2041 @@ function renderMigrationReport(report, { write = false } = {}) {
2058
2304
  lines.push(...HOT_RUNTIME_NOTE);
2059
2305
  return lines;
2060
2306
  }
2061
- // src/cli/index.ts
2307
+ // src/cli/compare.ts
2062
2308
  /**
2063
- * vitest-native CLI: `init` (write a ready config), `doctor` (diagnose the
2064
- * environment), `migrate` (analyze a Jest config and report the mapping).
2065
- * Deliberately vitest-free at module load — it runs via npx outside any test
2066
- * process.
2309
+ * `vitest-native compare`: the pure half. It reads a Jest `--json` report and a Vitest
2310
+ * JSON-reporter report, matches their tests, sorts each into a bucket and renders the
2311
+ * result. Running the two runners is compare-run.ts. The design, and why the summary
2312
+ * makes the one claim it does, is in docs/compare-mode.md.
2313
+ *
2314
+ * Formats: Jest's `FormattedTestResults` (@jest/test-result 30: testResults[].name,
2315
+ * .status, .message, .assertionResults[] with ancestorTitles/title/status/
2316
+ * failureMessages) and Vitest's `JsonTestResults` (vitest 4–5, the same field names).
2317
+ * Identities come from the structured fields, never from `fullName`: both runners join
2318
+ * it with spaces, so `describe("a b")` and `describe("a", () => describe("b"))` collide.
2067
2319
  */
2068
- const USAGE = `vitest-native — test React Native with Vitest
2069
-
2070
- Usage:
2071
- vitest-native init [--jest-compat] [--force] write a ready-to-run vitest config
2072
- vitest-native doctor diagnose peers, engine, presets, RNTL/Node
2073
- vitest-native migrate [--write] [--force] analyze jest config → migration report
2074
- (--write also saves the suggested config)
2075
- Options:
2076
- --root <dir> project root (default: cwd)
2077
- --help this text
2078
-
2079
- Docs: https://danfry1.github.io/vitest-native/`;
2080
- function main(argv, log = console.log) {
2081
- const args = argv.filter((a) => a !== "--");
2082
- const command = args.find((a, i) => !a.startsWith("-") && args[i - 1] !== "--root");
2083
- const has = (flag) => args.includes(flag);
2084
- const rootIdx = args.indexOf("--root");
2085
- const root = path.resolve(rootIdx !== -1 ? args[rootIdx + 1] ?? "." : ".");
2086
- if (has("--help") || has("-h")) {
2087
- log(USAGE);
2088
- return 0;
2320
+ const BUCKETS = [
2321
+ "same-pass",
2322
+ "same-fail",
2323
+ "same-skip",
2324
+ "regression",
2325
+ "improvement",
2326
+ "skip-difference",
2327
+ "only-jest",
2328
+ "only-vitest"
2329
+ ];
2330
+ const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
2331
+ const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2332
+ /**
2333
+ * Every way a message can spell `p`: as written, with either separator, JSON-escaped
2334
+ * (`C:\\x`), as a file URL. A Windows drive letter matches in either case.
2335
+ */
2336
+ function spellingPattern(paths) {
2337
+ const out = /* @__PURE__ */ new Set();
2338
+ for (const p of paths) {
2339
+ if (!p || p.length < 2) continue;
2340
+ const forward = p.replace(/\\/g, "/").replace(/\/$/, "");
2341
+ if (forward.length < 2) continue;
2342
+ out.add(forward);
2343
+ out.add(forward.replace(/\//g, "\\"));
2344
+ out.add(forward.replace(/\//g, "\\\\"));
2345
+ out.add(`file://${forward.startsWith("/") ? "" : "/"}${forward}`);
2089
2346
  }
2090
- if (!command) {
2091
- log(USAGE);
2092
- return 1;
2347
+ if (!out.size) return null;
2348
+ const alternatives = [...out].sort((a, b) => b.length - a.length).map((s) => escapeRegex(s).replace(/^([A-Za-z]):/, (_, d) => `[${d.toLowerCase()}${d.toUpperCase()}]:`));
2349
+ return new RegExp(alternatives.join("|"), "g");
2350
+ }
2351
+ /** A Node location line (`/x/y.js:2`) heading a source line and a `^^^` marker. */
2352
+ const LOCATION = /^\s*\S+:\d+(?::\d+)?\s*$/;
2353
+ /** A marker line under a source excerpt: Node's `^^^`, TypeScript's `~~~`. */
2354
+ const MARKER = /^\s*[\^~]+\s*$/;
2355
+ /** A code-frame line: an optional `>`/`❯` marker, a line number, a vertical bar. */
2356
+ const FRAME = /^\s*[>❯]?\s*\d*\s*[|│┃┆┊]/;
2357
+ /** Box drawing (oxc/Vite 8's frames: `╭─[`, `───╯`, `╰──`). */
2358
+ const BOX = /^\s*[─-╿]/;
2359
+ /** A React component stack line: `in SecretVault (at vault.js:3)`, `in App`. */
2360
+ const COMPONENT_STACK = /^\s+in [A-Z$_][\w$.]*(?: \(at [^)]*\)| \(created by [^)]*\))?\s*$/;
2361
+ /**
2362
+ * Directories that only ever hold a machine's files — macOS's, a drive, a UNC share, and
2363
+ * the checkouts CI and containers use (GitHub Actions `/github/workspace`, `/__w`,
2364
+ * `/runner`; GitLab `/builds`; Buildkite; Netlify `/opt/build`; Docker's `/app`,
2365
+ * `/workspace`; WSL's `/mnt`): a path under one is a path, whatever it is followed by,
2366
+ * spaces included (`/Volumes/Client Work/app.js`).
2367
+ */
2368
+ const MACHINE_ROOT = String.raw`(?:\/(?:Users|Volumes|private|var\/folders|builds|github\/workspace|app|runner|__w|workspace|opt\/build|buildkite|mnt)\/|[A-Za-z]:[\\/]|\\\\(?=[\w.$-]+\\))`;
2369
+ /** A machine-rooted path, up to a file name with an extension, else to the next space. */
2370
+ const MACHINE_PATH = new RegExp(String.raw`(?<![\w.<>/~:@-])${MACHINE_ROOT}(?:[^\n'"\`<>|]*?\.[A-Za-z0-9]{1,10}(?=[\s'"\`)\]},;:]|$)|[^\s'"\`)\]},;]*)`, "g");
2371
+ /** Other absolute-looking spans; replaced only when they are paths (see isPath). */
2372
+ const POSIX_CANDIDATE = /(?<![\w.<>/~:@-])\/[\w.@+~-]+(?:\/[\w.@+~-]*)+/g;
2373
+ /** Roots shared with app routes (`/home/profile/edit`): a path needs a dotted segment there. */
2374
+ const SHARED_ROOT = /^\/(?:home\/[^/]+|tmp|var|opt|root|srv|etc|usr)\//;
2375
+ /** A home directory with at least two segments below the user: `/home/alice/clients/x`. */
2376
+ const DEEP_HOME = /^\/home\/[^/]+\/[^/]+\/[^/]+/;
2377
+ const FILE_URL = /file:\/\/\/[^\s'"`)\]},;]*/g;
2378
+ /** `/home/<user>/…`: the user segment, replaced wherever the rest of the span is kept. */
2379
+ const HOME_USER = /^\/home\/[^/]+\//;
2380
+ /**
2381
+ * Roots that never begin an app route, for assertion values: macOS's, a drive, a UNC
2382
+ * share. CI and container roots (`/app`, `/workspace`, …) begin routes too
2383
+ * (`/app/settings/privacy`, `/workspace/42/members`), so there a span needs a file name.
2384
+ */
2385
+ const STRONG_ROOT = /^(?:\/(?:Users|Volumes|private|var\/folders)\/|[A-Za-z]:[\\/]|\\\\)/;
2386
+ const STRONG_PATH = new RegExp(String.raw`(?<![\w.<>/~:@-])(?:\/(?:Users|Volumes|private|var\/folders)\/|[A-Za-z]:[\\/]|\\\\(?=[\w.$-]+\\))(?:[^\n'"\`<>|]*?\.[A-Za-z0-9]{1,10}(?=[\s'"\`)\]},;:]|$)|[^\s'"\`)\]},;]*)`, "g");
2387
+ /** Any absolute-looking span, POSIX or Windows, without spaces. */
2388
+ const ANY_CANDIDATE = /(?<![\w.<>/~:@-])(?:\/[\w.@+~-]+(?:\/[\w.@+~-]*)+|[A-Za-z]:[\\/][^\s'"`)\]},;]*)/g;
2389
+ /** An assertion's value lines: `Expected: …`, `Received: …`, and a diff's `-` / `+` lines. */
2390
+ const ASSERTION_VALUE = /^\s*(?:[-+]\s|Expected\b|Received\b)/;
2391
+ const namesFile = (span) => /\.[A-Za-z0-9]{1,10}$/.test(span.replace(/[\\/]+$/, ""));
2392
+ function exists(span) {
2393
+ try {
2394
+ return fs.existsSync(span);
2395
+ } catch {
2396
+ return false;
2093
2397
  }
2094
- if (!fs.existsSync(path.join(root, "package.json"))) {
2095
- log(`✗ no package.json at ${root} — run from a project root or pass --root.`);
2096
- return 1;
2398
+ }
2399
+ /**
2400
+ * Paths in an assertion's values, which are usually app data — navigation routes such as
2401
+ * `"/home/profile/edit/photo"` or `"/workspace/42/members"` — and must stay readable: a span
2402
+ * is replaced only when it names a file, exists on disk, or begins with a root no route
2403
+ * begins with (STRONG_ROOT).
2404
+ */
2405
+ function stripAssertionLine(line) {
2406
+ return line.replace(FILE_URL, "<path>").replace(STRONG_PATH, "<path>").replace(ANY_CANDIDATE, (span) => namesFile(span) || exists(span) || STRONG_ROOT.test(span) ? "<path>" : span);
2407
+ }
2408
+ /** Paths anywhere else in a message: every machine root, and a home directory's user. */
2409
+ function stripLine(line) {
2410
+ return line.replace(FILE_URL, "<path>").replace(MACHINE_PATH, "<path>").replace(POSIX_CANDIDATE, (span) => isPath(span) ? "<path>" : span.replace(HOME_USER, "/home/<user>/"));
2411
+ }
2412
+ /**
2413
+ * Whether an absolute-looking span is a path on a machine, not an app route: it exists
2414
+ * on disk, it goes two or more segments below a `/home/<user>/`, or it sits under a root
2415
+ * that routes share (`/home/<user>/`, `/tmp/`, …) and names a file (`.npmrc`, `app.js`).
2416
+ * `/home/profile/edit` and `/settings/privacy` stay.
2417
+ */
2418
+ function isPath(span) {
2419
+ if (fs.existsSync(span)) return true;
2420
+ if (DEEP_HOME.test(span)) return true;
2421
+ return SHARED_ROOT.test(span) && span.split("/").some((segment) => /\./.test(segment));
2422
+ }
2423
+ /**
2424
+ * A runner's failure message, kept to the error's own text. Removed: ANSI codes, the
2425
+ * stack (cut at the first ` at ` or `❯` frame), React component stacks, code frames of
2426
+ * every runner (`> 12 |`, `12| `, `12 │`, box drawing), any line a `^^^`/`~~~` marker
2427
+ * points at with its marker (Node's and esbuild's source excerpts, TypeScript
2428
+ * diagnostics), Node's `file:line` + source + `^^^` blocks (Jest's "Details:"), and
2429
+ * absolute paths: the root becomes `<root>`, the temporary directory `<tmp>`, the home
2430
+ * directory `~`, any other path on a machine `<path>` (UNC, Windows, file URLs, paths
2431
+ * with spaces). App routes such as `/home/profile/edit` are kept. What remains can still
2432
+ * include values a test put in its error, such as expected and received values.
2433
+ */
2434
+ function sanitizeMessage(raw, ctx) {
2435
+ const lines = raw.replace(ANSI, "").replace(/\r\n?/g, "\n").split("\n");
2436
+ const end = lines.findIndex((l) => /^\s+at\s/.test(l) || /^\s*❯\s/.test(l));
2437
+ const body = end === -1 ? lines : lines.slice(0, end);
2438
+ const drop = /* @__PURE__ */ new Set();
2439
+ for (let i = 0; i < body.length; i++) {
2440
+ const line = body[i];
2441
+ if (FRAME.test(line) || BOX.test(line) || COMPONENT_STACK.test(line)) drop.add(i);
2442
+ else if (MARKER.test(line)) {
2443
+ drop.add(i);
2444
+ for (let j = i - 1; j >= 0; j--) {
2445
+ if (body[j].trim() === "") continue;
2446
+ drop.add(j);
2447
+ if (j > 0 && LOCATION.test(body[j - 1])) drop.add(j - 1);
2448
+ break;
2449
+ }
2450
+ }
2097
2451
  }
2098
- switch (command) {
2099
- case "doctor": {
2100
- const result = runDoctor(root);
2101
- for (const line of result.lines) log(line);
2102
- return result.ok ? 0 : 1;
2452
+ let text = body.filter((_, i) => !drop.has(i)).join("\n").replace(/\n{3,}/g, "\n\n").trim();
2453
+ const replace = (paths, to) => {
2454
+ const pattern = spellingPattern(paths);
2455
+ if (pattern) text = text.replace(pattern, to);
2456
+ };
2457
+ replace(ctx.roots, "<root>");
2458
+ replace(ctx.tmp ?? [], "<tmp>");
2459
+ if (ctx.home) replace([ctx.home], "~");
2460
+ text = text.split("\n").map((line) => ASSERTION_VALUE.test(line) ? stripAssertionLine(line) : stripLine(line)).join("\n");
2461
+ const capped = text.split("\n").slice(0, 30).join("\n");
2462
+ return capped.length > 4e3 ? `${capped.slice(0, 4e3)}…` : capped;
2463
+ }
2464
+ /**
2465
+ * The first non-empty line, whitespace collapsed: the key errors are grouped by. Jest's
2466
+ * `● <test name>` / `● Test suite failed to run` headers are skipped, so its file
2467
+ * failures group by the error.
2468
+ */
2469
+ function firstLine(message) {
2470
+ const lines = (message ?? "").split("\n").filter((l) => l.trim() !== "");
2471
+ const collapsed = (lines.find((l) => !l.trim().startsWith("●")) ?? lines[0] ?? "").trim().replace(/\s+/g, " ");
2472
+ return collapsed.length > 160 ? `${collapsed.slice(0, 160)}…` : collapsed || "(no message)";
2473
+ }
2474
+ function defaultRealpath(p) {
2475
+ try {
2476
+ return fs.realpathSync.native(p);
2477
+ } catch {
2478
+ return p;
2479
+ }
2480
+ }
2481
+ /** `/` separators and a lowercase drive letter: Jest writes `D:\x`, Vitest `D:/x`. */
2482
+ function slashed(p) {
2483
+ return p.replace(/\\/g, "/").replace(/^([A-Za-z]):/, (_, d) => `${d.toLowerCase()}:`);
2484
+ }
2485
+ function rootSpellings(ctx) {
2486
+ const real = ctx.realpath ?? defaultRealpath;
2487
+ return [.../* @__PURE__ */ new Set([
2488
+ ctx.root,
2489
+ real(ctx.root),
2490
+ ...ctx.aliases ?? []
2491
+ ])];
2492
+ }
2493
+ /** A reported test file as a root-relative `/` path (absolute when outside the root). */
2494
+ function relativeFile(name, ctx) {
2495
+ const real = ctx.realpath ?? defaultRealpath;
2496
+ const file = slashed(real(name));
2497
+ const roots = rootSpellings(ctx).map((r) => slashed(r).replace(/\/$/, ""));
2498
+ for (const r of roots) if (file.startsWith(`${r}/`)) return file.slice(r.length + 1);
2499
+ const base = slashed(real(ctx.root)).replace(/\/$/, "");
2500
+ if (file.startsWith("/") && base.startsWith("/")) return path.posix.relative(base, file);
2501
+ return file;
2502
+ }
2503
+ /**
2504
+ * Where a report made at another root was recorded: the prefix that, removed from its
2505
+ * absolute file names, leaves the files the other runner reported here. Null when no
2506
+ * prefix accounts for at least half of its files.
2507
+ */
2508
+ function foreignRoot(json, localFiles) {
2509
+ const names = (json?.testResults ?? []).map((r) => typeof r?.name === "string" ? slashed(r.name) : null).filter((n) => n !== null);
2510
+ const votes = /* @__PURE__ */ new Map();
2511
+ for (const name of names) {
2512
+ const match = localFiles.find((rel) => name.endsWith(`/${rel}`));
2513
+ if (match) {
2514
+ const prefix = name.slice(0, -(match.length + 1));
2515
+ votes.set(prefix, (votes.get(prefix) ?? 0) + 1);
2103
2516
  }
2104
- case "init": {
2105
- const result = runInit(root, {
2106
- jestCompat: has("--jest-compat"),
2107
- force: has("--force")
2108
- });
2109
- for (const line of result.lines) log(line);
2110
- return result.ok ? 0 : 1;
2517
+ }
2518
+ const [best] = [...votes].sort((a, b) => b[1] - a[1]);
2519
+ return best && best[1] * 2 >= names.length ? best[0] : null;
2520
+ }
2521
+ function outcome(status) {
2522
+ return status === "passed" ? "passed" : status === "failed" ? "failed" : "skipped";
2523
+ }
2524
+ /**
2525
+ * One runner's report as files of tests. Throws when the JSON is not a Jest or Vitest
2526
+ * report, so a wrong file is an error and not an empty run.
2527
+ */
2528
+ function normaliseReport(json, runner, ctx) {
2529
+ const report = json;
2530
+ if (!report || typeof report !== "object" || !Array.isArray(report.testResults)) throw new VitestNativeError("COMPARE_REPORT_INVALID", `not a ${runner} JSON report: it has no testResults array`);
2531
+ const sanitize = {
2532
+ roots: rootSpellings(ctx),
2533
+ tmp: ctx.tmp ?? tmpSpellings(),
2534
+ home: ctx.home ?? os.homedir()
2535
+ };
2536
+ const files = /* @__PURE__ */ new Map();
2537
+ for (const raw of report.testResults) {
2538
+ if (typeof raw?.name !== "string") continue;
2539
+ const file = relativeFile(raw.name, ctx);
2540
+ const tests = (Array.isArray(raw.assertionResults) ? raw.assertionResults : []).map((a) => {
2541
+ const first = (Array.isArray(a.failureMessages) ? a.failureMessages : []).find((m) => typeof m === "string" && m.trim() !== "");
2542
+ return {
2543
+ ancestors: Array.isArray(a.ancestorTitles) ? a.ancestorTitles.map(String) : [],
2544
+ title: String(a.title ?? ""),
2545
+ status: outcome(a.status),
2546
+ rawStatus: String(a.status ?? ""),
2547
+ message: first ? sanitizeMessage(first, sanitize) : null
2548
+ };
2549
+ });
2550
+ const status = outcome(raw.status);
2551
+ const message = typeof raw.message === "string" ? sanitizeMessage(raw.message, sanitize) : "";
2552
+ const broken = status === "failed" && (tests.length === 0 || !tests.some((t) => t.status === "failed") || runner === "vitest" && message !== "");
2553
+ const existing = files.get(file);
2554
+ if (existing) {
2555
+ existing.tests.push(...tests);
2556
+ if (status === "failed") existing.status = "failed";
2557
+ existing.broken ||= broken;
2558
+ existing.message ||= message;
2559
+ } else files.set(file, {
2560
+ file,
2561
+ status,
2562
+ message,
2563
+ broken,
2564
+ tests
2565
+ });
2566
+ }
2567
+ return {
2568
+ runner,
2569
+ files
2570
+ };
2571
+ }
2572
+ /** The system temporary directory, as written and with symlinks resolved. */
2573
+ function tmpSpellings() {
2574
+ const tmp = os.tmpdir();
2575
+ return [.../* @__PURE__ */ new Set([tmp, defaultRealpath(tmp)])];
2576
+ }
2577
+ /** Tests grouped by identity, in the order each identity first appears. */
2578
+ function grouped(tests) {
2579
+ const out = /* @__PURE__ */ new Map();
2580
+ for (const t of tests) {
2581
+ const key = JSON.stringify([t.ancestors, t.title]);
2582
+ const group = out.get(key) ?? {
2583
+ ancestors: t.ancestors,
2584
+ title: t.title,
2585
+ tests: []
2586
+ };
2587
+ group.tests.push(t);
2588
+ out.set(key, group);
2589
+ }
2590
+ return out;
2591
+ }
2592
+ /**
2593
+ * One result for every copy of an identity: passed only if every copy passed, failed if
2594
+ * any failed, otherwise skipped. Pairing copies by order would match a passing copy with
2595
+ * a failing one when the runners order them differently (concurrent tests, Jest's
2596
+ * randomize, projects).
2597
+ */
2598
+ function aggregate(group) {
2599
+ const { tests } = group;
2600
+ const failed = tests.find((t) => t.status === "failed");
2601
+ const side = {
2602
+ status: failed ? "failed" : tests.every((t) => t.status === "passed") ? "passed" : "skipped",
2603
+ rawStatus: tests.length === 1 ? tests[0].rawStatus : tests.map((t) => t.rawStatus).join(", "),
2604
+ message: failed?.message ?? null
2605
+ };
2606
+ if (tests.length > 1) side.copies = tests.length;
2607
+ return side;
2608
+ }
2609
+ const BROKEN_WITHOUT_MESSAGE = {
2610
+ jest: "the file failed outside any test under Jest",
2611
+ vitest: "failed outside any test (a beforeAll hook, for example); Vitest's JSON report has no message for it, so run the file with `vitest run <file>` to see the error"
2612
+ };
2613
+ function fileFailure(file, runner) {
2614
+ return file.message || BROKEN_WITHOUT_MESSAGE[runner];
2615
+ }
2616
+ function notRunSide(file, runner) {
2617
+ return {
2618
+ status: "failed",
2619
+ rawStatus: "not run",
2620
+ message: fileFailure(file, runner),
2621
+ notRun: "file-failed"
2622
+ };
2623
+ }
2624
+ /**
2625
+ * A Jest pass that Vitest confirms: Vitest passed it, at least as many times as Jest ran
2626
+ * it. Fewer copies means a Jest project (a platform, say) did not run under Vitest.
2627
+ */
2628
+ function isConfirmed(e) {
2629
+ return e.matchedBy !== "shape" && e.jest?.status === "passed" && e.vitest?.status === "passed" && (e.vitest.copies ?? 1) >= (e.jest.copies ?? 1);
2630
+ }
2631
+ function bucketOf(j, v) {
2632
+ if (j === v) return j === "passed" ? "same-pass" : j === "failed" ? "same-fail" : "same-skip";
2633
+ if (j === "skipped" || v === "skipped") return "skip-difference";
2634
+ return j === "passed" ? "regression" : "improvement";
2635
+ }
2636
+ function summary(file, runner) {
2637
+ return {
2638
+ file: file.file,
2639
+ status: file.status,
2640
+ tests: file.tests.length,
2641
+ message: file.broken ? fileFailure(file, runner) : null
2642
+ };
2643
+ }
2644
+ /**
2645
+ * The end of a printed string that starts at `start`: the index of its closing `"`, or -1.
2646
+ * Jest's pretty-format prints a string `%p` value in double quotes, escaping `"` and `\`
2647
+ * inside it. Only a quote that ends the token (followed by the end, whitespace or
2648
+ * punctuation) closes it, so a lone `"` in ordinary text does not start a value.
2649
+ */
2650
+ function printedStringEnd(title, start) {
2651
+ for (let j = start + 1; j < title.length; j++) {
2652
+ if (title[j] === "\\") {
2653
+ j++;
2654
+ continue;
2655
+ }
2656
+ if (title[j] === "\"") return /^($|[\s,;:)\]}])/.test(title.slice(j + 1)) ? j : -1;
2657
+ }
2658
+ return -1;
2659
+ }
2660
+ /**
2661
+ * A title as words, balanced `{…}` / `[…]` groups and double-quoted strings (printed
2662
+ * values), in order. A printed string is one token however many words it holds, so it
2663
+ * lines up with Vitest's literal `%p` for the same value.
2664
+ */
2665
+ function titleTokens(title) {
2666
+ const tokens = [];
2667
+ let word = "";
2668
+ const flush = () => {
2669
+ if (word) tokens.push(word);
2670
+ word = "";
2671
+ };
2672
+ for (let i = 0; i < title.length; i++) {
2673
+ const c = title[i];
2674
+ const stringEnd = c === "\"" && word === "" ? printedStringEnd(title, i) : -1;
2675
+ if (stringEnd !== -1) {
2676
+ let end = stringEnd + 1;
2677
+ while (end < title.length && !/\s/.test(title[end])) end++;
2678
+ tokens.push(title.slice(i, end));
2679
+ i = end - 1;
2680
+ continue;
2681
+ }
2682
+ if (c === "{" || c === "[") {
2683
+ flush();
2684
+ let depth = 0;
2685
+ let j = i;
2686
+ for (; j < title.length; j++) {
2687
+ if (title[j] === "{" || title[j] === "[") depth++;
2688
+ else if (title[j] === "}" || title[j] === "]") depth--;
2689
+ if (depth === 0) break;
2690
+ }
2691
+ tokens.push(title.slice(i, j + 1));
2692
+ i = j;
2693
+ } else if (/\s/.test(c)) flush();
2694
+ else word += c;
2695
+ }
2696
+ flush();
2697
+ return tokens;
2698
+ }
2699
+ const isGroup = (t) => t.startsWith("{") || t.startsWith("[");
2700
+ /** A printed value without what the two printers do differently: spaces, quotes, trailing commas. */
2701
+ const canonicalValue = (t) => t.replace(/\s+/g, "").replace(/["']/g, "").replace(/,([}\]])/g, "$1");
2702
+ /**
2703
+ * Whether Jest's printed value and Vitest's are the same value. Jest (pretty-format and
2704
+ * util.format at depth 1) prints `{"a": 1}` and `{ a: 1, b: [Array] }`; Vitest prints
2705
+ * `{ a: 1 }` and `{ a: 1, b: [ 1, 2 ] }`. Jest's `[Array]` / `[Object]` stand for any
2706
+ * array or object at that place.
2707
+ */
2708
+ function sameValue(jest, vitest) {
2709
+ const pattern = canonicalValue(jest).replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\[Array\\\]/g, "\\[.*?\\]").replace(/\\\[Object\\\]/g, "\\{.*?\\}");
2710
+ return new RegExp(`^${pattern}$`).test(canonicalValue(vitest));
2711
+ }
2712
+ /**
2713
+ * A title with its printed values normalised and nothing else. Inside each balanced
2714
+ * `{…}` / `[…]` value (titleTokens' groups), quote style is unified (`'` and `"` become
2715
+ * one; quotes are kept), whitespace runs collapse to one space, and a trailing comma goes:
2716
+ * the printers differ there. Text outside printed values is kept verbatim, so `it's on`
2717
+ * and `it"s on`, or `a , b` and `a, b`, are different titles.
2718
+ */
2719
+ function normalTitle(t) {
2720
+ let out = "";
2721
+ for (let i = 0; i < t.length; i++) {
2722
+ const c = t[i];
2723
+ if (c !== "{" && c !== "[") {
2724
+ out += c;
2725
+ continue;
2726
+ }
2727
+ let depth = 0;
2728
+ let j = i;
2729
+ for (; j < t.length; j++) {
2730
+ if (t[j] === "{" || t[j] === "[") depth++;
2731
+ else if (t[j] === "}" || t[j] === "]") depth--;
2732
+ if (depth === 0) break;
2733
+ }
2734
+ out += t.slice(i, j + 1).replace(/'/g, "\"").replace(/\s+/g, " ").replace(/,\s*([}\]])/g, "$1");
2735
+ i = j;
2736
+ }
2737
+ return out;
2738
+ }
2739
+ /**
2740
+ * Whether Vitest's token `b` is literal `%p`s standing in for Jest's printed values in `a`.
2741
+ * Punctuation stays attached to a token, so `%p,` stands for `0,`, `(%p)` for `(1)` and
2742
+ * `%p,%p` for `"",""`: the text around and between the `%p`s must appear in `a` as it is,
2743
+ * and each `%p` must stand for something.
2744
+ */
2745
+ function stoodInForBy(a, b) {
2746
+ if (!b.includes("%p")) return false;
2747
+ const literal = b.split("%p").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
2748
+ return new RegExp(`^${literal.join("(.+)")}$`, "s").test(a);
2749
+ }
2750
+ /**
2751
+ * Whether two titles have the same shape: equal except where the runners are known to
2752
+ * print a parametrised title (`it.each`) differently, each of which can hide a different
2753
+ * value: a printed object or array (quotes and Jest's `[Array]` / `[Object]` ignored),
2754
+ * Vitest's literal `%p` for one value, Jest's `$var` against Vitest's `undefined`, and
2755
+ * the `undefined` Vitest appends after `%%`.
2756
+ */
2757
+ function sameShape(jest, vitest) {
2758
+ const j = titleTokens(jest);
2759
+ const v = titleTokens(vitest);
2760
+ let i = 0;
2761
+ for (; i < j.length; i++) {
2762
+ const a = j[i];
2763
+ const b = v[i];
2764
+ if (b === void 0) return false;
2765
+ if (a === b) continue;
2766
+ if (isGroup(a) && isGroup(b) && sameValue(a, b)) continue;
2767
+ if (stoodInForBy(a, b)) continue;
2768
+ if (/^\$[A-Za-z_$][\w$]*(?:\.[\w$]+)*$/.test(a) && b === "undefined") continue;
2769
+ return false;
2770
+ }
2771
+ const rest = v.slice(i);
2772
+ return rest.length === 0 || jest.includes("%") && rest.every((t) => t === "undefined");
2773
+ }
2774
+ /**
2775
+ * Whether the titles differ only where Vitest left `%p` unformatted: the same number of
2776
+ * tokens, each equal or a `%p` (with what surrounds it) standing in for Jest's value.
2777
+ */
2778
+ function onlyPlaceholders(jest, vitest) {
2779
+ const j = titleTokens(jest);
2780
+ const v = titleTokens(vitest);
2781
+ return j.length === v.length && j.some((a, i) => a !== v[i]) && j.every((a, i) => a === v[i] || stoodInForBy(a, v[i]));
2782
+ }
2783
+ /**
2784
+ * How a Jest title matches a Vitest title, or null.
2785
+ *
2786
+ * - `same`: identical once quote style, whitespace and trailing commas are normalised
2787
+ * (normalTitle). The same test; it confirms a Jest pass.
2788
+ * - `placeholder`: equal except where Vitest printed a literal `%p` (onlyPlaceholders).
2789
+ * Vitest did not format the title at all, so it hides nothing Jest's print shows; the
2790
+ * pair confirms only when classify pairs the rows one to one, in order (see there).
2791
+ * - `shape`: equal only once a printed value is ignored (sameShape). Possibly the same
2792
+ * test printed differently, possibly a different row (`allows { user: [Object] }` is
2793
+ * Jest's print of any user). Listed for review, and never confirms a Jest pass.
2794
+ */
2795
+ function titleMatch(jest, vitest) {
2796
+ if (normalTitle(jest) === normalTitle(vitest)) return "same";
2797
+ if (onlyPlaceholders(jest, vitest)) return "placeholder";
2798
+ return sameShape(jest, vitest) ? "shape" : null;
2799
+ }
2800
+ const SNAPSHOT_MISMATCH = /Snapshot `[^`]*` mismatched/;
2801
+ function classify(jest, vitest, options = {}) {
2802
+ const entries = [];
2803
+ const onlyJest = [];
2804
+ const onlyVitest = [];
2805
+ const allFiles = [.../* @__PURE__ */ new Set([...jest.files.keys(), ...vitest.files.keys()])].sort();
2806
+ for (const file of allFiles) {
2807
+ const jf = jest.files.get(file);
2808
+ const vf = vitest.files.get(file);
2809
+ if (!jf || !vf) {
2810
+ const present = jf ?? vf;
2811
+ const runner = jf ? "jest" : "vitest";
2812
+ (jf ? onlyJest : onlyVitest).push(summary(present, runner));
2813
+ for (const g of grouped(present.tests).values()) entries.push({
2814
+ bucket: jf ? "only-jest" : "only-vitest",
2815
+ file,
2816
+ ancestors: g.ancestors,
2817
+ title: g.title,
2818
+ jest: jf ? aggregate(g) : null,
2819
+ vitest: vf ? aggregate(g) : null
2820
+ });
2821
+ continue;
2822
+ }
2823
+ const jg = grouped(jf.tests);
2824
+ const vg = grouped(vf.tests);
2825
+ const unmatched = {
2826
+ jest: /* @__PURE__ */ new Map(),
2827
+ vitest: /* @__PURE__ */ new Map()
2828
+ };
2829
+ const pairs = [];
2830
+ for (const key of /* @__PURE__ */ new Set([...jg.keys(), ...vg.keys()])) {
2831
+ const a = jg.get(key);
2832
+ const b = vg.get(key);
2833
+ if (a && !b && !vf.broken) {
2834
+ const block = JSON.stringify(a.ancestors);
2835
+ unmatched.jest.set(block, [...unmatched.jest.get(block) ?? [], a]);
2836
+ } else if (b && !a && !jf.broken) {
2837
+ const block = JSON.stringify(b.ancestors);
2838
+ const rows = b.title.includes("%p") && b.tests.length > 1 ? b.tests.map((t) => ({
2839
+ ancestors: b.ancestors,
2840
+ title: b.title,
2841
+ tests: [t]
2842
+ })) : [b];
2843
+ unmatched.vitest.set(block, [...unmatched.vitest.get(block) ?? [], ...rows]);
2844
+ } else pairs.push({
2845
+ a,
2846
+ b
2847
+ });
2848
+ }
2849
+ const at = (tests) => (g) => tests.indexOf(g.tests[0]);
2850
+ for (const [block, groups] of unmatched.jest) {
2851
+ const vs = unmatched.vitest.get(block) ?? [];
2852
+ if (!vs.some((b) => b.title.includes("%p"))) continue;
2853
+ const rows = groups.flatMap((a) => a.tests.length > 1 ? a.tests.map((t) => ({
2854
+ ...a,
2855
+ tests: [t]
2856
+ })) : [a]);
2857
+ unmatched.jest.set(block, rows.sort((x, y) => at(jf.tests)(x) - at(jf.tests)(y)));
2858
+ unmatched.vitest.set(block, [...vs].sort((x, y) => at(vf.tests)(x) - at(vf.tests)(y)));
2859
+ }
2860
+ for (const [block, js] of unmatched.jest) {
2861
+ const vs = unmatched.vitest.get(block) ?? [];
2862
+ const left = [];
2863
+ const oneToOne = options.ordered !== false && js.length === vs.length;
2864
+ js.forEach((a, i) => {
2865
+ const b = vs[i];
2866
+ let match = b ? titleMatch(a.title, b.title) : null;
2867
+ if (match === "placeholder" && !oneToOne) match = "shape";
2868
+ if (b && match) {
2869
+ pairs.push({
2870
+ a,
2871
+ b,
2872
+ vitestTitle: b.title,
2873
+ matchedBy: match
2874
+ });
2875
+ vs[i] = void 0;
2876
+ } else pairs.push({
2877
+ a,
2878
+ b: void 0,
2879
+ vitestCandidate: b?.title
2880
+ });
2881
+ });
2882
+ for (const b of vs) if (b) left.push(b);
2883
+ unmatched.vitest.set(block, left);
2884
+ }
2885
+ for (const vs of unmatched.vitest.values()) for (const b of vs) pairs.push({
2886
+ a: void 0,
2887
+ b
2888
+ });
2889
+ for (const { a, b, vitestTitle, matchedBy, vitestCandidate } of pairs) {
2890
+ const ref = a ?? b;
2891
+ let j = a ? aggregate(a) : jf.broken ? notRunSide(jf, "jest") : null;
2892
+ let v = b ? aggregate(b) : vf.broken ? notRunSide(vf, "vitest") : null;
2893
+ if (j && v && j.status === "skipped" && v.status !== "skipped" && jf.broken) j = notRunSide(jf, "jest");
2894
+ if (j && v && v.status === "skipped" && j.status !== "skipped" && vf.broken) v = notRunSide(vf, "vitest");
2895
+ const bucket = j && v ? bucketOf(j.status, v.status) : j ? "only-jest" : "only-vitest";
2896
+ const entry = {
2897
+ bucket,
2898
+ file,
2899
+ ancestors: ref.ancestors,
2900
+ title: ref.title,
2901
+ jest: j,
2902
+ vitest: v
2903
+ };
2904
+ if (vitestTitle !== void 0 && vitestTitle !== ref.title) entry.vitestTitle = vitestTitle;
2905
+ if (matchedBy === "shape") entry.matchedBy = "shape";
2906
+ else if (matchedBy === "placeholder") entry.matchedBy = "position";
2907
+ if (vitestCandidate !== void 0 && !v) entry.vitestCandidate = vitestCandidate;
2908
+ const message = v?.message ?? "";
2909
+ if (bucket === "regression" && options.snapshotHint && SNAPSHOT_MISMATCH.test(message)) {
2910
+ const hint = options.snapshotHint(file, message);
2911
+ if (hint) entry.hint = hint;
2912
+ }
2913
+ entries.push(entry);
2914
+ }
2915
+ }
2916
+ const counts = Object.fromEntries(BUCKETS.map((b) => [b, 0]));
2917
+ for (const e of entries) counts[e.bucket]++;
2918
+ const total = (r) => {
2919
+ const t = {
2920
+ files: r.files.size,
2921
+ tests: 0,
2922
+ passed: 0,
2923
+ failed: 0,
2924
+ skipped: 0
2925
+ };
2926
+ for (const f of r.files.values()) for (const test of f.tests) {
2927
+ t.tests++;
2928
+ t[test.status]++;
2929
+ }
2930
+ return t;
2931
+ };
2932
+ const jestPassed = entries.filter((e) => e.jest?.status === "passed").length;
2933
+ const confirmed = entries.filter(isConfirmed).length;
2934
+ const confirmedByPosition = entries.filter((e) => isConfirmed(e) && e.matchedBy === "position").length;
2935
+ const broken = (r) => [...r.files.values()].filter((f) => f.broken).map((f) => summary(f, r.runner));
2936
+ const brokenVitest = broken(vitest);
2937
+ const vitestFailing = entries.filter((e) => e.vitest?.status === "failed");
2938
+ const derivedExit = vitestFailing.length || brokenVitest.length ? 1 : 0;
2939
+ const run = options.vitestRun ?? {
2940
+ exitCode: derivedExit,
2941
+ errors: [],
2942
+ engine: null
2943
+ };
2944
+ const problems = [];
2945
+ if (run.exitCode !== 0) {
2946
+ if (vitestFailing.length) {
2947
+ const by = (bucket) => vitestFailing.filter((e) => e.bucket === bucket).length;
2948
+ const parts = [
2949
+ [by("regression"), "pass under Jest"],
2950
+ [by("same-fail"), "fail under Jest too"],
2951
+ [by("only-vitest"), "Jest did not run"]
2952
+ ].filter(([n]) => n > 0);
2953
+ problems.push(`${vitestFailing.length} ${vitestFailing.length === 1 ? "test fails" : "tests fail"} under Vitest` + (parts.length ? ` (${parts.map(([n, what]) => `${n} ${what}`).join(", ")})` : ""));
2954
+ }
2955
+ for (const f of brokenVitest.filter((b) => b.tests === 0 && !jest.files.get(b.file)?.broken)) problems.push(`${f.file} fails to load under Vitest: ${firstLine(f.message)}`);
2956
+ problems.push(...run.errors);
2957
+ if (!problems.length) problems.push(`Vitest exited ${run.exitCode ?? "by a signal"} although its JSON report shows no failure (a globalSetup teardown, process.exit, or an error outside any test); run \`vitest run\` to see it`);
2958
+ }
2959
+ return {
2960
+ entries,
2961
+ counts,
2962
+ files: {
2963
+ onlyJest,
2964
+ onlyVitest,
2965
+ brokenJest: broken(jest),
2966
+ brokenVitest
2967
+ },
2968
+ totals: {
2969
+ jest: total(jest),
2970
+ vitest: total(vitest)
2971
+ },
2972
+ jestPassed,
2973
+ confirmed,
2974
+ confirmedByPosition,
2975
+ vitest: {
2976
+ ...run,
2977
+ problems,
2978
+ ignoredErrors: run.exitCode === 0 ? run.errors : []
2979
+ },
2980
+ claimHolds: jestPassed > 0 && confirmed === jestPassed && run.exitCode === 0
2981
+ };
2982
+ }
2983
+ const SNAPSHOT_HINTS = {
2984
+ "no-vitest-snapshot": `no Vitest snapshot recorded. Give Vitest its own snapshot directory first (the resolveSnapshotPath recipe at ${docsUrl("/migration/from-jest#snapshots")}), so recording cannot rewrite Jest's .snap files; then run \`vitest run\` once and review the new files`,
2985
+ "shared-snapshot-dir": `your Vitest config resolves snapshots to Jest's .snap files. This snapshot's key is the same in both runners, but Vitest rewrites the header of a Jest .snap file it reads, so compare does not let it read Jest's. Give Vitest its own directory (the resolveSnapshotPath recipe at ${docsUrl("/migration/from-jest#snapshots")}) and record there`,
2986
+ "shared-snapshot-dir-nested": `your Vitest config resolves snapshots to Jest's .snap files. Vitest names this snapshot differently (\`a > b 1\`, where Jest writes \`a b 1\`), so it would not find Jest's entry, and it rewrites the header of a Jest .snap file it reads. Give Vitest its own directory (the resolveSnapshotPath recipe at ${docsUrl("/migration/from-jest#snapshots")}) and record there`
2987
+ };
2988
+ /** Entries grouped by the first line of the given side's message, largest group first. */
2989
+ function clusters(entries, by) {
2990
+ const groups = /* @__PURE__ */ new Map();
2991
+ for (const e of entries) {
2992
+ const key = e.hint ? SNAPSHOT_HINTS[e.hint] : firstLine(e[by]?.message ?? null);
2993
+ const group = groups.get(key) ?? {
2994
+ message: key,
2995
+ count: 0,
2996
+ tests: []
2997
+ };
2998
+ group.count++;
2999
+ group.tests.push({
3000
+ file: e.file,
3001
+ ancestors: e.ancestors,
3002
+ title: e.title
3003
+ });
3004
+ groups.set(key, group);
3005
+ }
3006
+ return [...groups.values()].sort((a, b) => b.count - a.count || a.message.localeCompare(b.message));
3007
+ }
3008
+ function testName(t) {
3009
+ return [
3010
+ t.file,
3011
+ ...t.ancestors,
3012
+ t.title
3013
+ ].join(" › ");
3014
+ }
3015
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
3016
+ function totalsLine(t) {
3017
+ return `${plural(t.files, "file")}, ${plural(t.tests, "test")} (${t.passed} passed, ${t.failed} failed, ${t.skipped} skipped)`;
3018
+ }
3019
+ /** Jest-passing tests that Vitest does not confirm (isConfirmed), by why. */
3020
+ function unconfirmed(c) {
3021
+ const out = {
3022
+ failed: [],
3023
+ skipped: [],
3024
+ fewer: [],
3025
+ shape: [],
3026
+ renamed: [],
3027
+ missing: []
3028
+ };
3029
+ for (const e of c.entries) {
3030
+ if (e.jest?.status !== "passed" || isConfirmed(e)) continue;
3031
+ if (!e.vitest) out[e.vitestCandidate !== void 0 ? "renamed" : "missing"].push(e);
3032
+ else if (e.vitest.status === "failed") out.failed.push(e);
3033
+ else if (e.vitest.status === "skipped") out.skipped.push(e);
3034
+ else if (e.matchedBy === "shape") out.shape.push(e);
3035
+ else out.fewer.push(e);
3036
+ }
3037
+ return out;
3038
+ }
3039
+ const UNCONFIRMED_LABELS = {
3040
+ failed: "fail",
3041
+ skipped: "skipped",
3042
+ fewer: "run fewer times (a Jest project missing)",
3043
+ shape: "matched only by title shape",
3044
+ renamed: "named differently",
3045
+ missing: "not collected"
3046
+ };
3047
+ function engineLabel(engine) {
3048
+ return engine ? `engine: ${engine}` : "no vitest-native engine reported";
3049
+ }
3050
+ function renderComparison(c, options) {
3051
+ const lines = [];
3052
+ const top = Math.max(1, options.top);
3053
+ const label = (r, name) => `${name} ${r.version ?? "(version unknown)"}`.padEnd(15);
3054
+ lines.push(`Jest ${label(options.jest, "jest")} ${totalsLine(c.totals.jest)} — config: ${options.jest.config}`, `Vitest ${label(options.vitest, "vitest")} ${totalsLine(c.totals.vitest)} — config: ${options.vitest.config}`, "");
3055
+ const gap = unconfirmed(c);
3056
+ const engine = engineLabel(c.vitest.engine);
3057
+ if (c.jestPassed === 0) lines.push("✗ No test passed under Jest, so there is nothing to compare against.");
3058
+ else if (c.claimHolds && options.projectChanged) lines.push(`✗ All ${plural(c.jestPassed, "test")} that pass under Jest also pass under Vitest (${engine}), but the runs changed files in the project (listed below), so the comparison does not count.`);
3059
+ else if (c.claimHolds) lines.push(`✓ All ${plural(c.jestPassed, "test")} that pass under Jest also pass under Vitest (${engine}), and \`vitest run\` exits 0.`);
3060
+ else if (c.confirmed === c.jestPassed) lines.push(`✗ \`vitest run\` exits ${c.vitest.exitCode ?? "by a signal"} (${engine}), although all ${plural(c.jestPassed, "test")} that pass under Jest also pass under Vitest:`);
3061
+ else {
3062
+ const why = Object.keys(UNCONFIRMED_LABELS).filter((k) => gap[k].length > 0).map((k) => `${gap[k].length} ${UNCONFIRMED_LABELS[k]}`);
3063
+ lines.push(`✗ ${c.jestPassed - c.confirmed} of the ${plural(c.jestPassed, "test")} that pass under Jest do not pass under Vitest (${engine}): ${why.join(", ")}.`);
3064
+ if (gap.shape.length) lines.push(`✗ ${plural(gap.shape.length, "test")} could only be matched by title shape; check them (Jest prints values differently, so a different row can look the same).`);
3065
+ }
3066
+ if (c.confirmedByPosition) lines.push(`! ${plural(c.confirmedByPosition, "test")} confirmed by row position only: Vitest printed \`%p\` instead of the value, so each was paired with the Jest row at its place in the table, not by its data. A table built differently under the two runners would pair wrong rows.`);
3067
+ if (!c.vitest.engine) lines.push("! Vitest reported no vitest-native engine: is reactNative() in this Vitest config?");
3068
+ if (c.vitest.problems.length) {
3069
+ if (c.confirmed !== c.jestPassed || c.jestPassed === 0) lines.push(`✗ \`vitest run\` exits ${c.vitest.exitCode ?? "by a signal"}:`);
3070
+ for (const p of c.vitest.problems.slice(0, top)) lines.push(` ${p}`);
3071
+ if (c.vitest.problems.length > top) lines.push(` … and ${c.vitest.problems.length - top} more (see --json)`);
3072
+ }
3073
+ if (c.vitest.ignoredErrors.length) {
3074
+ lines.push("! Vitest printed these errors but exited 0 (its config ignores unhandled errors):");
3075
+ for (const e of c.vitest.ignoredErrors.slice(0, top)) lines.push(` ${e}`);
3076
+ }
3077
+ lines.push("");
3078
+ const n = c.counts;
3079
+ const row = (mark, name, count, note) => lines.push(` ${mark} ${name.padEnd(22)} ${String(count).padStart(5)} ${note}`);
3080
+ row(" ", "same result", n["same-pass"] + n["same-fail"] + n["same-skip"], `${n["same-pass"]} pass, ${n["same-fail"]} fail, ${n["same-skip"]} skipped in both`);
3081
+ row(n.regression ? "✗" : " ", "regressions", n.regression, "pass under Jest, fail under Vitest — fix these first");
3082
+ row(" ", "improvements", n.improvement, "fail under Jest, pass under Vitest");
3083
+ row(n["skip-difference"] ? "~" : " ", "skipped differently", n["skip-difference"], "skipped by one runner, run by the other");
3084
+ row(n["only-jest"] ? "!" : " ", "only under Jest", n["only-jest"], "no Vitest result: its file or the test was not collected");
3085
+ row(n["only-vitest"] ? "!" : " ", "only under Vitest", n["only-vitest"], "no Jest result");
3086
+ lines.push("");
3087
+ const fileList = (title, files) => {
3088
+ if (!files.length) return;
3089
+ lines.push(`${title} (${files.length}):`);
3090
+ for (const f of files.slice(0, top)) {
3091
+ const why = f.message ? ` — ${firstLine(f.message)}` : "";
3092
+ lines.push(` ${f.file} (${plural(f.tests, "test")}, ${f.status})${why}`);
3093
+ }
3094
+ if (files.length > top) lines.push(` … and ${files.length - top} more (see --json)`);
3095
+ lines.push("");
3096
+ };
3097
+ fileList("! Test files only Jest collected", c.files.onlyJest);
3098
+ fileList("! Test files only Vitest collected", c.files.onlyVitest);
3099
+ fileList("✗ Test files that failed outside any test under Vitest", c.files.brokenVitest);
3100
+ const regressions = c.entries.filter((e) => e.bucket === "regression");
3101
+ if (regressions.length) {
3102
+ const groups = clusters(regressions, "vitest");
3103
+ lines.push(`Regressions by first Vitest error (top ${Math.min(top, groups.length)} of ${groups.length}):`);
3104
+ for (const g of groups.slice(0, top)) {
3105
+ lines.push(` ${g.count}× ${g.message}`);
3106
+ for (const t of g.tests.slice(0, 3)) lines.push(` ${testName(t)}`);
3107
+ if (g.tests.length > 3) lines.push(` … and ${g.tests.length - 3} more`);
3108
+ }
3109
+ lines.push("");
3110
+ }
3111
+ const testList = (title, list, describe = testName) => {
3112
+ if (!list.length) return;
3113
+ lines.push(`${title} (${list.length}):`);
3114
+ for (const e of list.slice(0, top)) lines.push(` ${describe(e)}`);
3115
+ if (list.length > top) lines.push(` … and ${list.length - top} more (see --json)`);
3116
+ lines.push("");
3117
+ };
3118
+ testList("Skipped under Vitest, passed under Jest", c.entries.filter((e) => e.bucket === "skip-difference" && e.jest?.status === "passed"));
3119
+ testList("Matched by position: the same test, its title formatted differently by each runner (Jest ⇄ Vitest)", c.entries.filter((e) => e.vitestTitle !== void 0 && e.matchedBy !== "shape"), (e) => `${testName(e)} ⇄ ${e.vitestTitle}`);
3120
+ testList("Matched by title shape — review: equal only if the values Jest and Vitest print are (unconfirmed)", c.entries.filter((e) => e.matchedBy === "shape"), (e) => `${testName(e)} ~ ${e.vitestTitle ?? e.title}`);
3121
+ testList("Named differently? Jest's test has no Vitest test of that name; at its place Vitest has another (unconfirmed)", c.entries.filter((e) => e.vitestCandidate !== void 0), (e) => `${testName(e)} ≠ ${e.vitestCandidate}`);
3122
+ const collected = new Set([...c.files.onlyJest, ...c.files.onlyVitest].map((f) => f.file));
3123
+ testList("Tests only Jest reported, in files both ran", c.entries.filter((e) => e.bucket === "only-jest" && !collected.has(e.file)));
3124
+ testList("Tests only Vitest reported, in files both ran", c.entries.filter((e) => e.bucket === "only-vitest" && !collected.has(e.file)));
3125
+ testList("Reported a different number of times (projects or repeated titles; each passes only if every copy passed)", c.entries.filter((e) => (e.jest?.copies ?? 1) !== (e.vitest?.copies ?? 1) && e.jest && e.vitest), (e) => `${testName(e)} (Jest ${e.jest?.copies ?? 1}×, Vitest ${e.vitest?.copies ?? 1}×)`);
3126
+ lines.push(options.jsonPath ? `Report: ${options.jsonPath} — test names, statuses and error messages, with stack traces, code frames and absolute paths removed. Read it before attaching it to an issue: a message can still contain whatever a test put in its error.` : "Write a report to attach to an issue with --json <file>.");
3127
+ return lines;
3128
+ }
3129
+ /** The `--json` report: identities, statuses and messages. */
3130
+ function jsonReport(c, meta) {
3131
+ const listed = c.entries.filter((e) => e.bucket !== "same-pass" && e.bucket !== "same-skip" || e.vitestTitle !== void 0);
3132
+ return {
3133
+ format: "vitest-native-compare@1",
3134
+ about: "One run of a suite under Jest and one under Vitest: test identities (file relative to the project root, describe titles, title), statuses and error messages. Stack traces, code frames and absolute paths (<root>, <tmp>, ~, <path>) are removed from messages; a message can still contain whatever a test put in its error. Tests with the same result under both runners are counted, not listed, except failures.",
3135
+ tool: {
3136
+ vitestNative: meta.vitestNative,
3137
+ node: process.version,
3138
+ platform: process.platform
3139
+ },
3140
+ runners: {
3141
+ jest: meta.jest,
3142
+ vitest: meta.vitest
3143
+ },
3144
+ verdict: {
3145
+ claim: "every test that passes under Jest also passes under Vitest, and `vitest run` exits 0",
3146
+ holds: c.claimHolds,
3147
+ jestPassed: c.jestPassed,
3148
+ confirmed: c.confirmed,
3149
+ confirmedByPosition: c.confirmedByPosition,
3150
+ vitestExitCode: c.vitest.exitCode,
3151
+ vitestProblems: c.vitest.problems,
3152
+ vitestIgnoredErrors: c.vitest.ignoredErrors,
3153
+ engine: c.vitest.engine
3154
+ },
3155
+ totals: c.totals,
3156
+ counts: c.counts,
3157
+ files: c.files,
3158
+ clusters: { regression: clusters(listed.filter((e) => e.bucket === "regression"), "vitest") },
3159
+ tests: listed.map((e) => ({
3160
+ bucket: e.bucket,
3161
+ file: e.file,
3162
+ ancestors: e.ancestors,
3163
+ title: e.title,
3164
+ ...e.vitestTitle !== void 0 ? { vitestTitle: e.vitestTitle } : {},
3165
+ ...e.matchedBy ? { matchedBy: e.matchedBy } : {},
3166
+ ...e.vitestCandidate !== void 0 ? { vitestCandidate: e.vitestCandidate } : {},
3167
+ jest: e.jest,
3168
+ vitest: e.vitest,
3169
+ ...e.hint ? { hint: e.hint } : {}
3170
+ }))
3171
+ };
3172
+ }
3173
+ // src/cli/compare-run.ts
3174
+ /**
3175
+ * `vitest-native compare`: the half that runs things. It runs the project's own Jest and
3176
+ * Vitest one after the other, each a bounded child process, and hands their JSON reports
3177
+ * to compare.ts. See docs/compare-mode.md.
3178
+ */
3179
+ /** Split an argument string into words: whitespace separates, quotes group. */
3180
+ function splitArgs(value) {
3181
+ const words = [];
3182
+ let word = null;
3183
+ for (let i = 0; i < value.length; i++) {
3184
+ const c = value[i];
3185
+ if (c === "'" || c === "\"") {
3186
+ const close = value.indexOf(c, i + 1);
3187
+ const stop = close === -1 ? value.length : close;
3188
+ word = (word ?? "") + value.slice(i + 1, stop);
3189
+ i = stop;
3190
+ } else if (/\s/.test(c)) {
3191
+ if (word !== null) words.push(word);
3192
+ word = null;
3193
+ } else word = (word ?? "") + c;
3194
+ }
3195
+ if (word !== null) words.push(word);
3196
+ return words;
3197
+ }
3198
+ /**
3199
+ * The runner arguments compare passes through. Anything else is refused: a deny-list
3200
+ * let `-ut .` (Vitest's -u inside a cluster of short flags) and Jest's `--ci false`
3201
+ * through, and both write snapshots. Positional arguments (path filters) are allowed.
3202
+ */
3203
+ const JEST_ARGS = {
3204
+ long: {
3205
+ maxWorkers: "value",
3206
+ testTimeout: "value",
3207
+ runInBand: "flag",
3208
+ selectProjects: "value",
3209
+ testNamePattern: "value",
3210
+ testPathPatterns: "value",
3211
+ testPathPattern: "value",
3212
+ testPathIgnorePatterns: "value",
3213
+ shard: "value",
3214
+ silent: "flag",
3215
+ forceExit: "flag",
3216
+ detectOpenHandles: "flag",
3217
+ logHeapUsage: "flag",
3218
+ workerIdleMemoryLimit: "value",
3219
+ passWithNoTests: "flag",
3220
+ randomize: "flag",
3221
+ seed: "value",
3222
+ maxConcurrency: "value",
3223
+ watchAll: "false-only",
3224
+ watch: "false-only",
3225
+ cache: "flag",
3226
+ clearMocks: "flag",
3227
+ config: "value",
3228
+ watchman: "flag",
3229
+ verbose: "flag",
3230
+ bail: "optional",
3231
+ coverage: "false-only"
3232
+ },
3233
+ short: {
3234
+ i: "flag",
3235
+ w: "value",
3236
+ t: "value",
3237
+ c: "value"
3238
+ }
3239
+ };
3240
+ const VITEST_ARGS = {
3241
+ long: {
3242
+ maxWorkers: "value",
3243
+ testTimeout: "value",
3244
+ hookTimeout: "value",
3245
+ teardownTimeout: "value",
3246
+ project: "value",
3247
+ testNamePattern: "value",
3248
+ shard: "value",
3249
+ pool: "value",
3250
+ silent: "flag",
3251
+ mode: "value",
3252
+ passWithNoTests: "flag",
3253
+ fileParallelism: "flag",
3254
+ isolate: "flag",
3255
+ retry: "value",
3256
+ dir: "value",
3257
+ logHeapUsage: "flag",
3258
+ watch: "false-only",
3259
+ root: "value",
3260
+ "coverage.enabled": "false-only",
3261
+ coverage: "false-only",
3262
+ bail: "value",
3263
+ allowOnly: "flag",
3264
+ "sequence.shuffle": "flag"
3265
+ },
3266
+ short: { t: "value" }
3267
+ };
3268
+ const camel = (name) => name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
3269
+ /** The first argument the spec does not allow, with why, or null. */
3270
+ function refusedArg(args, spec) {
3271
+ for (let i = 0; i < args.length; i++) {
3272
+ const arg = args[i];
3273
+ if (!arg.startsWith("-")) continue;
3274
+ if (arg.startsWith("--")) {
3275
+ const [rawName, inline] = arg.slice(2).split(/=(.*)/s, 2);
3276
+ let name = camel(rawName);
3277
+ let negated = false;
3278
+ if (!(name in spec.long) && name.startsWith("no") && /^no[A-Z]/.test(name)) {
3279
+ name = name[2].toLowerCase() + name.slice(3);
3280
+ negated = true;
3281
+ }
3282
+ const kind = spec.long[name];
3283
+ if (!kind) return arg;
3284
+ if (kind === "value") {
3285
+ if (negated) return arg;
3286
+ if (inline === void 0) {
3287
+ if (args[i + 1] === void 0) return `${arg} (no value)`;
3288
+ i++;
3289
+ }
3290
+ } else if (kind === "optional") {
3291
+ if (negated) return arg;
3292
+ } else if (kind === "false-only") {
3293
+ if (!(negated || inline === "false")) return arg;
3294
+ } else if (inline !== void 0 && inline !== "true" && inline !== "false") return arg;
3295
+ continue;
3296
+ }
3297
+ const short = arg.slice(1);
3298
+ const kind = spec.short[short];
3299
+ if (!kind) return arg;
3300
+ if (kind === "value") {
3301
+ if (args[i + 1] === void 0) return `${arg} (no value)`;
3302
+ i++;
3303
+ }
3304
+ }
3305
+ return null;
3306
+ }
3307
+ const VALUED = [
3308
+ "root",
3309
+ "jest-args",
3310
+ "vitest-args",
3311
+ "vitest-config",
3312
+ "jest-results",
3313
+ "jest-root",
3314
+ "json",
3315
+ "top",
3316
+ "timeout"
3317
+ ];
3318
+ const COMPARE_VALUED_FLAGS = VALUED.map((f) => `--${f}`);
3319
+ /** compare's switches (no value). */
3320
+ const SWITCHES = ["show-output", "strict"];
3321
+ const COMPARE_SWITCHES = SWITCHES.map((f) => `--${f}`);
3322
+ /** `compare`'s options from argv (after the command), or an error to print. */
3323
+ function parseCompareArgs(argv) {
3324
+ const values = /* @__PURE__ */ new Map();
3325
+ const flags = /* @__PURE__ */ new Set();
3326
+ for (let i = 0; i < argv.length; i++) {
3327
+ const arg = argv[i];
3328
+ if (!arg.startsWith("--")) continue;
3329
+ const [name, inline] = arg.slice(2).split(/=(.*)/s, 2);
3330
+ if (VALUED.includes(name)) {
3331
+ const value = inline ?? argv[++i];
3332
+ if (value === void 0) return { error: `--${name} needs a value.` };
3333
+ values.set(name, value);
3334
+ } else if (SWITCHES.includes(name) || name === "help") flags.add(name);
3335
+ else return { error: `unknown option --${name} for compare. Valid: ` + [
3336
+ ...COMPARE_VALUED_FLAGS,
3337
+ ...COMPARE_SWITCHES,
3338
+ "--help"
3339
+ ].join(", ") + "." };
3340
+ }
3341
+ const jestArgs = splitArgs(values.get("jest-args") ?? "");
3342
+ const vitestArgs = splitArgs(values.get("vitest-args") ?? "");
3343
+ const refusedJest = refusedArg(jestArgs, JEST_ARGS);
3344
+ if (refusedJest) return { error: `--jest-args may not contain ${refusedJest}: compare passes only arguments that cannot write snapshots or replace its reports (see ${docsUrl("/guide/cli#compare")}).` };
3345
+ const refusedVitest = refusedArg(vitestArgs, VITEST_ARGS);
3346
+ if (refusedVitest) return { error: `--vitest-args may not contain ${refusedVitest}: compare passes only arguments that cannot write snapshots or replace its reports or config (name a config with --vitest-config; see ${docsUrl("/guide/cli#compare")}).` };
3347
+ const top = Number(values.get("top") ?? 10);
3348
+ const timeout = Number(values.get("timeout") ?? 1800);
3349
+ if (!Number.isInteger(top) || top < 1) return { error: "--top needs a positive whole number." };
3350
+ if (!Number.isFinite(timeout) || timeout <= 0) return { error: "--timeout needs a number of seconds." };
3351
+ return {
3352
+ root: path.resolve(values.get("root") ?? "."),
3353
+ jestArgs,
3354
+ vitestArgs,
3355
+ vitestConfig: values.get("vitest-config"),
3356
+ jestResults: values.get("jest-results"),
3357
+ jestRoot: values.get("jest-root"),
3358
+ json: values.get("json"),
3359
+ top,
3360
+ timeoutMs: timeout * 1e3,
3361
+ showOutput: flags.has("show-output"),
3362
+ strict: flags.has("strict")
3363
+ };
3364
+ }
3365
+ /**
3366
+ * Runs between compare and each runner: `node -e WATCHDOG -- <cleanup JSON> <runner
3367
+ * args…>`. It starts the runner on compare's pipes and exits with its code. When compare
3368
+ * dies without stopping it (SIGKILL, a crash), the IPC channel disconnects: it stops the
3369
+ * runner, removes compare's temporary directories and kills its own process group,
3370
+ * which holds the runner's workers. On Windows, which has no process groups, it ends
3371
+ * the runner's tree with taskkill, and after the runner exits it stops processes the
3372
+ * runner started that outlived it (orphans keep their parent's id).
3373
+ */
3374
+ const WATCHDOG = `
3375
+ const { spawn, spawnSync } = require("node:child_process");
3376
+ const fs = require("node:fs");
3377
+ const [cleanup, ...args] = process.argv.slice(1);
3378
+ const win = process.platform === "win32";
3379
+ const started = Date.now();
3380
+ const child = spawn(process.execPath, args, { stdio: "inherit", windowsHide: true });
3381
+ let orphaned = false;
3382
+ function reapWindowsOrphans() {
3383
+ if (!win || child.pid === undefined) return;
3384
+ const since = Date.now() - started + 1000;
3385
+ const script =
3386
+ "$t=[DateTime]::Now.AddMilliseconds(-" + since + ");" +
3387
+ "function K($p){Get-CimInstance Win32_Process -Filter \\"ParentProcessId=$p\\" | " +
3388
+ "Where-Object { $_.CreationDate -ge $t } | ForEach-Object { K $_.ProcessId; " +
3389
+ "Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } }; K " + child.pid;
3390
+ spawnSync("powershell", ["-NoProfile", "-NonInteractive", "-Command", script], {
3391
+ stdio: "ignore", windowsHide: true, timeout: 20000,
3392
+ });
3393
+ }
3394
+ function shutdown(code) {
3395
+ if (orphaned) {
3396
+ for (const dir of JSON.parse(cleanup)) {
3397
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch {}
3398
+ }
3399
+ if (!win) { try { process.kill(-process.pid, "SIGKILL"); } catch {} }
3400
+ }
3401
+ process.exit(code);
3402
+ }
3403
+ child.on("exit", (code) => { reapWindowsOrphans(); shutdown(code ?? 1); });
3404
+ child.on("error", () => shutdown(1));
3405
+ process.on("disconnect", () => {
3406
+ orphaned = true;
3407
+ if (win) spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
3408
+ else { try { child.kill("SIGTERM"); } catch {} }
3409
+ setTimeout(() => shutdown(1), 3000).unref();
3410
+ });
3411
+ `;
3412
+ /**
3413
+ * Owns compare's temporary directories for the whole run: `node -e GUARDIAN -- <dirs
3414
+ * JSON> <empty-parents JSON>`, over an IPC channel. When the channel closes — compare
3415
+ * finished, or died between or during runs (SIGKILL included) — it removes the
3416
+ * directories (a no-op after a normal run, which removed them) and exits.
3417
+ */
3418
+ const GUARDIAN = `
3419
+ const fs = require("node:fs");
3420
+ const [dirs, parents] = process.argv.slice(1).map((a) => JSON.parse(a));
3421
+ for (const s of ["SIGINT", "SIGHUP", "SIGTERM"]) process.on(s, () => {});
3422
+ process.on("disconnect", () => {
3423
+ for (const d of dirs) { try { fs.rmSync(d, { recursive: true, force: true }); } catch {} }
3424
+ for (const d of parents) { try { fs.rmdirSync(d); } catch {} }
3425
+ process.exit(0);
3426
+ });
3427
+ `;
3428
+ function startGuardian(dirs, parents) {
3429
+ try {
3430
+ const guardian = spawn(process.execPath, [
3431
+ "-e",
3432
+ GUARDIAN,
3433
+ "--",
3434
+ JSON.stringify(dirs),
3435
+ JSON.stringify(parents)
3436
+ ], {
3437
+ stdio: [
3438
+ "ignore",
3439
+ "ignore",
3440
+ "ignore",
3441
+ "ipc"
3442
+ ],
3443
+ detached: process.platform !== "win32",
3444
+ windowsHide: true
3445
+ });
3446
+ guardian.on("error", () => {});
3447
+ guardian.unref();
3448
+ guardian.channel?.unref?.();
3449
+ return guardian;
3450
+ } catch {
3451
+ return null;
3452
+ }
3453
+ }
3454
+ const SIGNALS = [
3455
+ "SIGINT",
3456
+ "SIGTERM",
3457
+ "SIGHUP"
3458
+ ];
3459
+ /** How long to wait for a runner's pipes after it exits: a test's own daemon can hold them. */
3460
+ const DRAIN_MS = 2e3;
3461
+ /**
3462
+ * Splits a child's stdout and stderr into lines, each stream on its own: the two pipes
3463
+ * deliver chunks in any order and a chunk can end mid-line or mid-character, so a shared
3464
+ * buffer would join half a stderr line to a stdout line and lose what it said.
3465
+ */
3466
+ function outputLines(onLine) {
3467
+ const streams = {
3468
+ stdout: {
3469
+ decoder: new StringDecoder("utf8"),
3470
+ partial: ""
3471
+ },
3472
+ stderr: {
3473
+ decoder: new StringDecoder("utf8"),
3474
+ partial: ""
3475
+ }
3476
+ };
3477
+ return {
3478
+ push(stream, chunk) {
3479
+ const state = streams[stream];
3480
+ const parts = (state.partial + state.decoder.write(chunk)).split("\n");
3481
+ state.partial = parts.pop() ?? "";
3482
+ for (const line of parts) onLine(line, stream);
3483
+ },
3484
+ flush() {
3485
+ for (const stream of ["stdout", "stderr"]) {
3486
+ const state = streams[stream];
3487
+ const rest = state.partial + state.decoder.end();
3488
+ state.partial = "";
3489
+ if (rest) onLine(rest, stream);
3490
+ }
3491
+ }
3492
+ };
3493
+ }
3494
+ /**
3495
+ * Run a runner (`node <args>`) under the watchdog, with a timeout. On POSIX the watchdog
3496
+ * leads its own process group, so the whole group — the runner's workers included — can
3497
+ * be signalled: on timeout, Ctrl-C, SIGTERM or SIGHUP it gets SIGTERM, then SIGKILL after
3498
+ * 5 s, and once the runner exits whatever is left in its group is killed. A process a
3499
+ * test starts in a session of its own is out of reach, as it is under the runners.
3500
+ */
3501
+ function runBounded(args, options) {
3502
+ return new Promise((resolve) => {
3503
+ const posix = process.platform !== "win32";
3504
+ const child = spawn(process.execPath, [
3505
+ "-e",
3506
+ WATCHDOG,
3507
+ "--",
3508
+ JSON.stringify(options.cleanup),
3509
+ ...args
3510
+ ], {
3511
+ cwd: options.cwd,
3512
+ env: options.env,
3513
+ stdio: [
3514
+ "ignore",
3515
+ "pipe",
3516
+ "pipe",
3517
+ "ipc"
3518
+ ],
3519
+ detached: posix,
3520
+ windowsHide: true
3521
+ });
3522
+ const tail = [];
3523
+ const lines = outputLines((line, stream) => {
3524
+ options.onLine?.(line, stream);
3525
+ tail.push(line);
3526
+ if (tail.length > 40) tail.splice(0, tail.length - 40);
3527
+ });
3528
+ const onData = (stream) => (chunk) => {
3529
+ if (options.showOutput) process.stderr.write(chunk);
3530
+ lines.push(stream, chunk);
3531
+ };
3532
+ child.stdout?.on("data", onData("stdout"));
3533
+ child.stderr?.on("data", onData("stderr"));
3534
+ const killTree = (signal) => {
3535
+ if (child.pid === void 0) return;
3536
+ if (posix) try {
3537
+ process.kill(-child.pid, signal);
3538
+ } catch (error) {
3539
+ if (errorCode(error) !== "ESRCH") child.kill(signal);
3540
+ }
3541
+ else spawnSync("taskkill", [
3542
+ "/pid",
3543
+ String(child.pid),
3544
+ "/T",
3545
+ "/F"
3546
+ ], {
3547
+ stdio: "ignore",
3548
+ windowsHide: true
3549
+ });
3550
+ };
3551
+ let timedOut = false;
3552
+ let interrupted = false;
3553
+ let escalate;
3554
+ let drain;
3555
+ const stop = () => {
3556
+ killTree("SIGTERM");
3557
+ escalate ??= setTimeout(() => killTree("SIGKILL"), 5e3);
3558
+ };
3559
+ const timer = setTimeout(() => {
3560
+ timedOut = true;
3561
+ stop();
3562
+ }, options.timeoutMs);
3563
+ const onSignal = () => {
3564
+ interrupted = true;
3565
+ stop();
3566
+ };
3567
+ const signals = SIGNALS;
3568
+ for (const s of signals) process.on(s, onSignal);
3569
+ let settled = false;
3570
+ let exitCode = null;
3571
+ const finish = (code) => {
3572
+ if (settled) return;
3573
+ settled = true;
3574
+ clearTimeout(timer);
3575
+ clearTimeout(escalate);
3576
+ clearTimeout(drain);
3577
+ for (const s of signals) process.off(s, onSignal);
3578
+ lines.flush();
3579
+ if (child.connected) child.disconnect();
3580
+ resolve({
3581
+ code,
3582
+ timedOut,
3583
+ interrupted,
3584
+ tail
3585
+ });
3586
+ };
3587
+ child.on("exit", (code) => {
3588
+ exitCode = code;
3589
+ if (posix) killTree("SIGKILL");
3590
+ drain = setTimeout(() => {
3591
+ child.stdout?.destroy();
3592
+ child.stderr?.destroy();
3593
+ finish(exitCode);
3594
+ }, DRAIN_MS);
3595
+ });
3596
+ child.on("error", (error) => {
3597
+ tail.push(String(error));
3598
+ finish(null);
3599
+ });
3600
+ child.on("close", (code) => finish(code ?? exitCode));
3601
+ });
3602
+ }
3603
+ /**
3604
+ * The environment for a runner: a parent test runner's per-worker identity removed, and
3605
+ * nothing that asks either runner to write snapshots.
3606
+ */
3607
+ function runnerEnv() {
3608
+ const env = {};
3609
+ for (const [key, value] of Object.entries(process.env)) {
3610
+ if (key.startsWith("VITEST") || key === "JEST_WORKER_ID" || key === "UPDATE_SNAPSHOT") continue;
3611
+ env[key] = value;
3612
+ }
3613
+ env.CI = "true";
3614
+ return env;
3615
+ }
3616
+ /** A package's bin, found as installedManifest finds the package (walking node_modules up). */
3617
+ function locateBin(root, pkg, binName) {
3618
+ for (let dir = path.resolve(root);; dir = path.dirname(dir)) {
3619
+ const pkgDir = path.join(dir, "node_modules", pkg);
3620
+ if (fs.existsSync(path.join(pkgDir, "package.json"))) {
3621
+ const manifest = installedManifest(dir, pkg) ?? {};
3622
+ const bin = manifest.bin;
3623
+ const relative = typeof bin === "string" ? bin : bin?.[binName];
3624
+ if (!relative) return null;
3625
+ return {
3626
+ bin: path.join(fs.realpathSync(pkgDir), relative),
3627
+ version: typeof manifest.version === "string" ? manifest.version : null
3628
+ };
3629
+ }
3630
+ if (path.dirname(dir) === dir) return null;
3631
+ }
3632
+ }
3633
+ /** The config Vitest itself would load from the root (vitest.config.* before vite.config.*). */
3634
+ function findVitestConfig(root) {
3635
+ for (const base of ["vitest.config", "vite.config"]) for (const ext of [
3636
+ ".ts",
3637
+ ".mts",
3638
+ ".cts",
3639
+ ".js",
3640
+ ".mjs",
3641
+ ".cjs"
3642
+ ]) if (fs.existsSync(path.join(root, base + ext))) return base + ext;
3643
+ return null;
3644
+ }
3645
+ /**
3646
+ * An import specifier from `fromDir` to `file`: relative with `/` separators, or the
3647
+ * absolute path with `/` separators when no relative path exists (another drive).
3648
+ */
3649
+ function importSpecifier(fromDir, file, p = path) {
3650
+ const rel = p.relative(fromDir, file);
3651
+ if (p.isAbsolute(rel)) return rel.split(p.sep).join("/");
3652
+ const forward = rel.split(p.sep).join("/");
3653
+ return forward.startsWith(".") ? forward : `./${forward}`;
3654
+ }
3655
+ /**
3656
+ * The config compare's Vitest run loads: the project's config, unchanged, except that
3657
+ * every snapshot file it resolves — through its own resolveSnapshotPath, a project's, or
3658
+ * the `__vitest_snapshots__/` recipe when it sets none — is read from a copy in an
3659
+ * isolated directory, and `update` is false. Only files with Vitest's header are copied:
3660
+ * Vitest cannot read Jest's (other keys), and with CI set Vitest 5.0.5 still rewrote the
3661
+ * header of every Jest .snap file it read. Each resolution is logged to `manifest`.
3662
+ */
3663
+ function wrapperSource(baseSpecifier, isolated, manifest, root) {
3664
+ return `import path from "node:path";
3665
+ import fs from "node:fs";
3666
+ import { mergeConfig } from "vitest/config";
3667
+ import base from ${JSON.stringify(baseSpecifier)};
3668
+
3669
+ const ROOT = ${JSON.stringify(root)};
3670
+ const ISOLATED = ${JSON.stringify(isolated)};
3671
+ const MANIFEST = ${JSON.stringify(manifest)};
3672
+ const recipe = (testPath, extension) =>
3673
+ path.join(path.dirname(testPath), "__vitest_snapshots__", path.basename(testPath) + extension);
3674
+ const seen = new Set();
3675
+
3676
+ function isolate(own) {
3677
+ return (testPath, extension, context) => {
3678
+ const original = own ? own(testPath, extension, context) : recipe(testPath, extension);
3679
+ const rel = path.relative(ROOT, original);
3680
+ const inside = rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
3681
+ const target = path.join(ISOLATED, inside ? rel : path.join("outside", Buffer.from(original).toString("hex").slice(-80)));
3682
+ if (!seen.has(target)) {
3683
+ seen.add(target);
3684
+ let header = null;
3685
+ try { header = fs.readFileSync(original, "utf8").slice(0, 40); } catch {}
3686
+ const vitests = header !== null && header.startsWith("// Vitest Snapshot");
3687
+ fs.mkdirSync(path.dirname(target), { recursive: true });
3688
+ if (vitests) fs.copyFileSync(original, target);
3689
+ fs.appendFileSync(MANIFEST, JSON.stringify({ testPath, original, copied: vitests, foreign: header !== null && !vitests }) + "\\n");
3690
+ }
3691
+ return target;
3692
+ };
3693
+ }
3694
+
3695
+ // Vitest 5.0.5 resolves every project's snapshots through the root's setting (one
3696
+ // SnapshotManager), so the root's isolation covers inline projects there; a project's own
3697
+ // is wrapped too, for a Vitest that honours it.
3698
+ function isolateProject(project, inherited) {
3699
+ if (!project || typeof project !== "object" || typeof project.then === "function") return project;
3700
+ const test = project.test ?? {};
3701
+ const own = test.resolveSnapshotPath ?? (project.extends ? inherited : undefined);
3702
+ return {
3703
+ ...project,
3704
+ test: { ...test, resolveSnapshotPath: isolate(own), taskTitleValueFormatTruncate: 0 },
3705
+ };
3706
+ }
3707
+
3708
+ function compareConfig(config) {
3709
+ const resolved = mergeConfig(config ?? {}, {});
3710
+ const test = resolved.test ?? {};
3711
+ const own = test.resolveSnapshotPath;
3712
+ resolved.test = {
3713
+ ...test,
3714
+ resolveSnapshotPath: isolate(own),
3715
+ projects: Array.isArray(test.projects) ? test.projects.map((p) => isolateProject(p, own)) : test.projects,
3716
+ update: false,
3717
+ // Full parametrised titles: Vitest cuts each formatted value at 40 characters by
3718
+ // default, so two rows can print the same title and none matches Jest's.
3719
+ taskTitleValueFormatTruncate: 0,
3720
+ };
3721
+ return resolved;
3722
+ }
3723
+
3724
+ export default typeof base === "function"
3725
+ ? async (env) => compareConfig(await base(env))
3726
+ : compareConfig(await base);
3727
+ `;
3728
+ }
3729
+ /** The `test` script's flags `migrate` maps into the Vitest config, for Jest too. */
3730
+ const FORWARDED = [
3731
+ "config",
3732
+ "c",
3733
+ "testTimeout",
3734
+ "maxWorkers",
3735
+ "w",
3736
+ "runInBand",
3737
+ "i",
3738
+ "silent",
3739
+ "passWithNoTests"
3740
+ ];
3741
+ function forwardedScriptFlags(root) {
3742
+ const forwarded = [];
3743
+ const ignored = [];
3744
+ let pkg;
3745
+ try {
3746
+ pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
3747
+ } catch (error) {
3748
+ if (errorCode(error) === "ENOENT") return {
3749
+ forwarded,
3750
+ ignored
3751
+ };
3752
+ return {
3753
+ forwarded,
3754
+ ignored,
3755
+ unreadable: error.message.split("\n")[0]
3756
+ };
3757
+ }
3758
+ {
3759
+ const script = pkg?.scripts?.test;
3760
+ const parsed = typeof script === "string" ? parseJestScript("test", script) : null;
3761
+ for (const [name, value] of parsed?.flags ?? []) if (FORWARDED.includes(name)) {
3762
+ const long = {
3763
+ c: "config",
3764
+ w: "maxWorkers",
3765
+ i: "runInBand"
3766
+ }[name] ?? name;
3767
+ forwarded.push(value === true ? `--${long}` : `--${long}=${value}`);
3768
+ } else if (![
3769
+ "ci",
3770
+ "json",
3771
+ "outputFile",
3772
+ "watch",
3773
+ "watchAll",
3774
+ "coverage"
3775
+ ].includes(name)) ignored.push(`--${name}`);
3776
+ }
3777
+ return {
3778
+ forwarded,
3779
+ ignored
3780
+ };
3781
+ }
3782
+ /** The state of a path the walk could not read, followed by its error code. */
3783
+ const UNREADABLE = "unreadable:";
3784
+ /** Paths a tree state could not read (treeState), for the summary. */
3785
+ function unreadablePaths(state) {
3786
+ return [...state].filter(([, v]) => v.startsWith(UNREADABLE)).map(([k, v]) => `${k} (${v.slice(11)})`);
3787
+ }
3788
+ /** Directories skipped by name anywhere: package installs and version control. */
3789
+ const SKIPPED_DIR_NAMES = /* @__PURE__ */ new Set(["node_modules", ".git"]);
3790
+ /**
3791
+ * Output directories tools write as a matter of course, by root-relative path only: a
3792
+ * `coverage/` inside `src/features/` is the project's own and is checked.
3793
+ */
3794
+ const OUTPUT_DIR_PATHS = [
3795
+ "coverage",
3796
+ ".expo",
3797
+ ".gradle",
3798
+ ".cache",
3799
+ ".turbo",
3800
+ ".nyc_output",
3801
+ "android/build",
3802
+ "android/app/build",
3803
+ "android/.gradle",
3804
+ "ios/build",
3805
+ "ios/Pods",
3806
+ "ios/DerivedData"
3807
+ ];
3808
+ /**
3809
+ * Size and modification time of every file under the root, except in node_modules, .git
3810
+ * and the output directories. Symlinked directories are followed only while they stay
3811
+ * inside the root (each real directory once, so a cycle ends): a link out of the
3812
+ * project leads to files the project does not own.
3813
+ */
3814
+ function treeState(root, limit = 2e5) {
3815
+ const out = /* @__PURE__ */ new Map();
3816
+ const seen = /* @__PURE__ */ new Set();
3817
+ let realRoot;
3818
+ try {
3819
+ realRoot = fs.realpathSync(root);
3820
+ } catch (error) {
3821
+ out.set(".", `${UNREADABLE}${errorCode(error) ?? "error"}`);
3822
+ return out;
3823
+ }
3824
+ const unreadable = (abs, error) => out.set(path.relative(root, abs).split(path.sep).join("/") || ".", `${UNREADABLE}${errorCode(error) ?? "error"}`);
3825
+ const inside = (real) => real === realRoot || real.startsWith(realRoot + path.sep);
3826
+ const stack = [root];
3827
+ while (stack.length) {
3828
+ const dir = stack.pop();
3829
+ let real;
3830
+ try {
3831
+ real = fs.realpathSync(dir);
3832
+ } catch (error) {
3833
+ unreadable(dir, error);
3834
+ continue;
3835
+ }
3836
+ if (seen.has(real) || !inside(real)) continue;
3837
+ seen.add(real);
3838
+ let entries;
3839
+ try {
3840
+ entries = fs.readdirSync(dir, { withFileTypes: true });
3841
+ } catch (error) {
3842
+ unreadable(dir, error);
3843
+ continue;
3844
+ }
3845
+ for (const e of entries) {
3846
+ if (SKIPPED_DIR_NAMES.has(e.name)) continue;
3847
+ const abs = path.join(dir, e.name);
3848
+ const rel = path.relative(root, abs).split(path.sep).join("/");
3849
+ if (OUTPUT_DIR_PATHS.includes(rel)) continue;
3850
+ let stat;
3851
+ try {
3852
+ stat = e.isSymbolicLink() ? fs.statSync(abs) : fs.lstatSync(abs);
3853
+ } catch (error) {
3854
+ if (errorCode(error) !== "ENOENT") unreadable(abs, error);
3855
+ continue;
3856
+ }
3857
+ if (stat.isDirectory()) stack.push(abs);
3858
+ else if (stat.isFile()) {
3859
+ if (e.isSymbolicLink()) {
3860
+ let target;
3861
+ try {
3862
+ target = fs.realpathSync(abs);
3863
+ } catch (error) {
3864
+ if (errorCode(error) !== "ENOENT") unreadable(abs, error);
3865
+ continue;
3866
+ }
3867
+ if (!inside(target)) continue;
3868
+ }
3869
+ out.set(rel, `${stat.size}:${stat.mtimeMs}`);
3870
+ if (out.size > limit) return null;
3871
+ }
3872
+ }
3873
+ }
3874
+ return out;
3875
+ }
3876
+ const SNAPSHOT = /(?:^|\/)(?:__snapshots__|__vitest_snapshots__)\/|\.snap$/;
3877
+ const SOURCE = /\.(?:[cm]?[jt]sx?|json)$/;
3878
+ /** A change compare itself could have caused: a snapshot, or a test/source file (inline snapshots). */
3879
+ function isSnapshotOrSource(change) {
3880
+ const file = change.replace(/^(?:added|changed|removed) /, "");
3881
+ return SNAPSHOT.test(file) || SOURCE.test(file);
3882
+ }
3883
+ /**
3884
+ * What the runs did to the project. A file that existed before is the project's, so any
3885
+ * change to it, whatever its kind (`.graphql`, `.yaml`, an image), is fatal; so is a new
3886
+ * snapshot file. Only new files of other kinds are reported neutrally.
3887
+ */
3888
+ function treeChanges(before, after) {
3889
+ const fatal = [];
3890
+ const other = [];
3891
+ for (const [file, state] of after) if (!before.has(file)) (SNAPSHOT.test(file) ? fatal : other).push(`added ${file}`);
3892
+ else if (before.get(file) !== state) fatal.push(`changed ${file}`);
3893
+ for (const file of before.keys()) if (!after.has(file)) fatal.push(`removed ${file}`);
3894
+ return {
3895
+ fatal: fatal.sort(),
3896
+ other: other.sort()
3897
+ };
3898
+ }
3899
+ /** Jest's `--randomize` option exists from Jest 29.2; an older Jest rejects the flag. */
3900
+ function jestRandomizeFlag(version) {
3901
+ const [major, minor] = (version ?? "").split(".").map(Number);
3902
+ return major > 29 || major === 29 && minor >= 2;
3903
+ }
3904
+ /** The `code` of a Node system error (`ENOENT`, `ESRCH`, …), or undefined. */
3905
+ function errorCode(error) {
3906
+ return error?.code;
3907
+ }
3908
+ function readReport(file) {
3909
+ try {
3910
+ return JSON.parse(fs.readFileSync(file, "utf8"));
3911
+ } catch {
3912
+ return null;
3913
+ }
3914
+ }
3915
+ function seconds(since) {
3916
+ return `${((Date.now() - since) / 1e3).toFixed(1)}s`;
3917
+ }
3918
+ /** Reads Vitest's own output for what its JSON report leaves out. */
3919
+ function vitestOutputReader(sanitize) {
3920
+ const errors = [];
3921
+ let engine = null;
3922
+ const pending = {
3923
+ stdout: null,
3924
+ stderr: null
3925
+ };
3926
+ let running = false;
3927
+ const plain = (line) => line.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, "");
3928
+ return {
3929
+ errors,
3930
+ engine: () => engine,
3931
+ onLine(raw, stream = "stdout") {
3932
+ const line = plain(raw);
3933
+ if (/^\s*RUN\s+v\d/.test(line)) running = true;
3934
+ const m = running ? null : /^\[vitest-native\] engine: (native|mock) — /.exec(line);
3935
+ if (m) engine ??= m[1];
3936
+ const header = /⎯+\s*(Unhandled (?:Rejection|Error)|Uncaught Exception)\s*⎯+/.exec(line);
3937
+ if (header) {
3938
+ pending[stream] = header[1];
3939
+ return;
3940
+ }
3941
+ if (pending[stream] && line.trim() !== "") {
3942
+ errors.push(`${pending[stream]}: ${sanitize(line.trim())}`);
3943
+ pending[stream] = null;
3944
+ return;
3945
+ }
3946
+ const close = /^error during close (.*)$/.exec(line);
3947
+ if (close) errors.push(`error during close: ${sanitize(close[1])}`);
3948
+ }
3949
+ };
3950
+ }
3951
+ async function runCompare(options) {
3952
+ const { root, log } = options;
3953
+ const vitest = locateBin(root, "vitest", "vitest");
3954
+ const jest = options.jestResults ? null : locateBin(root, "jest", "jest");
3955
+ if (!vitest) {
3956
+ log(`✗ Vitest is not installed at ${root}; compare runs the project's own Vitest.`);
3957
+ return 2;
3958
+ }
3959
+ if (!options.jestResults && !jest) {
3960
+ log(`✗ Jest is not installed at ${root}; compare runs the project's own Jest (or reads a Jest --json report given with --jest-results).`);
3961
+ return 2;
3962
+ }
3963
+ const analysis = analyzeJestConfig(root);
3964
+ const vitestConfigFile = options.vitestConfig ?? findVitestConfig(root);
3965
+ if (options.vitestConfig && !fs.existsSync(path.resolve(root, options.vitestConfig))) {
3966
+ log(`✗ --vitest-config ${options.vitestConfig} does not exist under ${root}.`);
3967
+ return 2;
3968
+ }
3969
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "vn-compare-"));
3970
+ const nodeModules = path.join(root, "node_modules");
3971
+ const hadNodeModules = fs.existsSync(nodeModules);
3972
+ const configParent = path.join(nodeModules, ".vitest-native");
3973
+ const hadConfigParent = fs.existsSync(configParent);
3974
+ fs.mkdirSync(configParent, { recursive: true });
3975
+ const configDir = fs.mkdtempSync(path.join(configParent, "compare-"));
3976
+ const cleanup = [work, configDir];
3977
+ const guardian = startGuardian(cleanup, [...hadConfigParent ? [] : [configParent], ...hadNodeModules ? [] : [nodeModules]]);
3978
+ let interrupted = false;
3979
+ const onSignal = () => {
3980
+ interrupted = true;
3981
+ };
3982
+ for (const s of SIGNALS) process.on(s, onSignal);
3983
+ const before = treeState(root);
3984
+ const notChecked = before ? unreadablePaths(before) : [];
3985
+ if (notChecked.length) log(` ${notChecked.length} ${notChecked.length === 1 ? "path" : "paths"} could not be read, so the check that the runs change nothing does not cover them: ${notChecked.slice(0, 5).join(", ")}` + (notChecked.length > 5 ? ", …" : ""));
3986
+ try {
3987
+ let baseFile;
3988
+ let vitestConfigLabel;
3989
+ if (vitestConfigFile) {
3990
+ baseFile = path.resolve(root, vitestConfigFile);
3991
+ const rel = path.relative(root, baseFile);
3992
+ vitestConfigLabel = rel.startsWith("..") || path.isAbsolute(rel) ? path.basename(baseFile) : rel.split(path.sep).join("/");
3993
+ } else {
3994
+ baseFile = path.join(configDir, "migrate.config.mjs");
3995
+ const rootUrl = pathToFileURL(root + path.sep).href;
3996
+ fs.writeFileSync(baseFile, analysis.suggestedConfig.replaceAll("import.meta.url", JSON.stringify(rootUrl)));
3997
+ vitestConfigLabel = "the one `vitest-native migrate` suggests (not saved)";
3998
+ }
3999
+ const manifest = path.join(work, "snapshots.jsonl");
4000
+ const wrapper = path.join(configDir, "vitest.compare.config.mjs");
4001
+ fs.writeFileSync(wrapper, wrapperSource(importSpecifier(configDir, baseFile), path.join(configDir, "snapshots"), manifest, root));
4002
+ const jestInfo = {
4003
+ version: jest?.version ?? null,
4004
+ config: options.jestResults ? `report ${path.basename(options.jestResults)}` : analysis.source ?? "Jest's defaults (no Jest config found)"
4005
+ };
4006
+ const vitestInfo = {
4007
+ version: vitest.version,
4008
+ config: vitestConfigLabel
4009
+ };
4010
+ let jestReport;
4011
+ if (options.jestResults) {
4012
+ jestReport = readReport(path.resolve(options.jestResults));
4013
+ if (jestReport === null) {
4014
+ log(`✗ could not read a JSON report from ${options.jestResults}.`);
4015
+ return 2;
4016
+ }
4017
+ } else {
4018
+ const out = path.join(work, "jest.json");
4019
+ const script = forwardedScriptFlags(root);
4020
+ if (script.unreadable) log(` package.json could not be read (${script.unreadable}); no script flags forwarded.`);
4021
+ if (script.ignored.length) log(` scripts.test also passes ${script.ignored.join(" ")} to Jest; not forwarded (add them with --jest-args if they matter).`);
4022
+ const started = Date.now();
4023
+ log(`Running Jest ${jest?.version ?? ""}…`);
4024
+ const run = await runBounded([
4025
+ jest.bin,
4026
+ "--json",
4027
+ `--outputFile=${out}`,
4028
+ "--coverage=false",
4029
+ "--reporters=default",
4030
+ ...jestRandomizeFlag(jest?.version ?? null) ? ["--randomize=false"] : [],
4031
+ ...script.forwarded,
4032
+ ...options.jestArgs,
4033
+ "--ci"
4034
+ ], {
4035
+ cwd: root,
4036
+ env: runnerEnv(),
4037
+ timeoutMs: options.timeoutMs,
4038
+ showOutput: options.showOutput,
4039
+ cleanup
4040
+ });
4041
+ const failure = runFailure("Jest", run, options.timeoutMs);
4042
+ if (failure) return reportFailure(log, failure, run);
4043
+ jestReport = readReport(out);
4044
+ if (jestReport === null) return reportFailure(log, `Jest exited (${run.code}) without writing its JSON report.`, run);
4045
+ log(` done in ${seconds(started)}`);
4046
+ }
4047
+ const vitestOut = path.join(work, "vitest.json");
4048
+ const sanitizeCtx = {
4049
+ roots: [root, fs.realpathSync(root)],
4050
+ tmp: tmpSpellings(),
4051
+ home: os.homedir()
4052
+ };
4053
+ const reader = vitestOutputReader((s) => sanitizeMessage(s, sanitizeCtx));
4054
+ const started = Date.now();
4055
+ log(`Running Vitest ${vitest.version ?? ""}…`);
4056
+ const run = await runBounded([
4057
+ vitest.bin,
4058
+ "run",
4059
+ "--config",
4060
+ wrapper,
4061
+ "--reporter=json",
4062
+ `--outputFile.json=${vitestOut}`,
4063
+ "--reporter=default",
4064
+ "--coverage.enabled=false",
4065
+ ...options.vitestArgs
4066
+ ], {
4067
+ cwd: root,
4068
+ env: runnerEnv(),
4069
+ timeoutMs: options.timeoutMs,
4070
+ showOutput: options.showOutput,
4071
+ cleanup,
4072
+ onLine: reader.onLine
4073
+ });
4074
+ const failure = runFailure("Vitest", run, options.timeoutMs);
4075
+ if (failure) return reportFailure(log, failure, run);
4076
+ const vitestReport = readReport(vitestOut);
4077
+ if (vitestReport === null) return reportFailure(log, `Vitest exited (${run.code}) without writing its JSON report.`, run);
4078
+ log(` done in ${seconds(started)}`);
4079
+ log("");
4080
+ if (options.rawReportsDir) {
4081
+ fs.mkdirSync(options.rawReportsDir, { recursive: true });
4082
+ const save = (name, report) => fs.writeFileSync(path.join(options.rawReportsDir, name), JSON.stringify(report));
4083
+ save("jest.json", jestReport);
4084
+ save("vitest.json", vitestReport);
4085
+ }
4086
+ let jestResults;
4087
+ let vitestResults;
4088
+ try {
4089
+ vitestResults = normaliseReport(vitestReport, "vitest", { root });
4090
+ let aliases = options.jestRoot ? [options.jestRoot] : [];
4091
+ if (!aliases.length && options.jestResults) {
4092
+ const local = [...vitestResults.files.keys()];
4093
+ const prefix = [...normaliseReport(jestReport, "jest", { root }).files.keys()].some((f) => /^(\/|\.\.\/|[a-z]:)/.test(f)) ? foreignRoot(jestReport, local) : null;
4094
+ if (prefix) {
4095
+ aliases = [prefix];
4096
+ log(` Jest's report was made at ${prefix}; its paths are read relative to that directory.`);
4097
+ }
4098
+ }
4099
+ jestResults = normaliseReport(jestReport, "jest", {
4100
+ root,
4101
+ aliases
4102
+ });
4103
+ } catch (error) {
4104
+ log(`✗ ${error.message}`);
4105
+ return 2;
4106
+ }
4107
+ const resolutions = /* @__PURE__ */ new Map();
4108
+ if (fs.existsSync(manifest)) for (const line of fs.readFileSync(manifest, "utf8").split("\n")) {
4109
+ if (!line.trim()) continue;
4110
+ const entry = JSON.parse(line);
4111
+ const rel = path.relative(root, entry.testPath).split(path.sep).join("/");
4112
+ resolutions.set(rel, entry);
4113
+ }
4114
+ const comparison = classify(jestResults, vitestResults, {
4115
+ snapshotHint: (file, message) => snapshotHint(root, resolutions.get(file), file, message),
4116
+ vitestRun: {
4117
+ exitCode: run.code,
4118
+ errors: reader.errors,
4119
+ engine: reader.engine()
4120
+ },
4121
+ ordered: !options.strict && !options.jestResults && !options.jestArgs.some((a) => /^--randomize(=true)?$/.test(a)) && !options.vitestArgs.some((a) => /^--sequence\.shuffle(=true)?$/.test(a))
4122
+ });
4123
+ vitestInfo.config += "; snapshots read from an isolated copy";
4124
+ const after = treeState(root);
4125
+ const changes = before && after ? treeChanges(before, after) : {
4126
+ fatal: [],
4127
+ other: []
4128
+ };
4129
+ if (!before || !after) log(" The project has too many files to check that the runs changed none.");
4130
+ for (const line of renderComparison(comparison, {
4131
+ jest: jestInfo,
4132
+ vitest: vitestInfo,
4133
+ top: options.top,
4134
+ jsonPath: options.json ?? null,
4135
+ projectChanged: changes.fatal.length > 0
4136
+ })) log(line);
4137
+ if (!vitestConfigFile && analysis.attention.length) log(`Note: \`vitest-native migrate\` lists ${analysis.attention.length} item(s) that need attention; they can explain differences.`);
4138
+ if (changes.other.length) {
4139
+ log(` The runs wrote ${changes.other.length} other file(s) in the project:`);
4140
+ for (const c of changes.other.slice(0, options.top)) log(` ${c}`);
4141
+ if (changes.other.length > options.top) log(` … and ${changes.other.length - options.top} more`);
4142
+ }
4143
+ if (options.json) {
4144
+ const report = jsonReport(comparison, {
4145
+ vitestNative: installedManifest(root, "vitest-native")?.version ?? null,
4146
+ jest: jestInfo,
4147
+ vitest: vitestInfo
4148
+ });
4149
+ report.projectChanges = changes.fatal;
4150
+ report.projectWrites = changes.other;
4151
+ fs.writeFileSync(path.resolve(options.json), `${JSON.stringify(report, null, 2)}\n`);
4152
+ }
4153
+ if (changes.fatal.length) {
4154
+ const own = changes.fatal.filter(isSnapshotOrSource);
4155
+ const suites = changes.fatal.filter((c) => !isSnapshotOrSource(c));
4156
+ const list = (items) => {
4157
+ for (const c of items.slice(0, options.top)) log(` ${c}`);
4158
+ if (items.length > options.top) log(` … and ${items.length - options.top} more`);
4159
+ };
4160
+ if (own.length) {
4161
+ log("");
4162
+ log(`✗ The runs changed ${own.length} snapshot or source file(s) in the project, which compare must never do:`);
4163
+ list(own);
4164
+ log(" Restore them from version control, and report this with the command you ran.");
4165
+ }
4166
+ if (suites.length) {
4167
+ log("");
4168
+ log("✗ The test run changed these existing files (compare's comparison does not count while the suite rewrites tracked files):");
4169
+ list(suites);
4170
+ }
4171
+ return 2;
4172
+ }
4173
+ if (interrupted) {
4174
+ log("✗ compare was interrupted.");
4175
+ return 130;
4176
+ }
4177
+ if (comparison.jestPassed === 0) return 2;
4178
+ return comparison.claimHolds ? 0 : 1;
4179
+ } finally {
4180
+ for (const s of SIGNALS) process.off(s, onSignal);
4181
+ fs.rmSync(work, {
4182
+ recursive: true,
4183
+ force: true
4184
+ });
4185
+ fs.rmSync(configDir, {
4186
+ recursive: true,
4187
+ force: true
4188
+ });
4189
+ for (const [dir, existed] of [[configParent, hadConfigParent], [nodeModules, hadNodeModules]]) {
4190
+ if (existed) continue;
4191
+ try {
4192
+ fs.rmdirSync(dir);
4193
+ } catch (error) {
4194
+ const code = errorCode(error);
4195
+ if (code !== "ENOTEMPTY" && code !== "EEXIST" && code !== "ENOENT") log(` Could not remove ${dir}, which compare created: ${error.message}`);
4196
+ }
4197
+ }
4198
+ if (guardian?.connected) guardian.disconnect();
4199
+ }
4200
+ }
4201
+ /**
4202
+ * Which snapshot hint a Vitest snapshot mismatch gets. Inline and file snapshots fail with
4203
+ * the same message as a `.snap` one, and recording those is not what the hints say, so
4204
+ * a test gets one only when it is a `.snap` case: its key, in Jest's spelling (Vitest's
4205
+ * `a > b 1` is Jest's `a b 1`), is in Jest's `.snap` file, which it must be for the test
4206
+ * to have passed under Jest. Then: Vitest's config resolves to Jest's own file
4207
+ * (`shared-snapshot-dir`), or Vitest's own file lacks the key (`no-vitest-snapshot`).
4208
+ */
4209
+ function snapshotHint(root, resolution, file, message) {
4210
+ const key = /Snapshot `([^`]*)` mismatched/.exec(message)?.[1];
4211
+ if (!key || !resolution) return void 0;
4212
+ const read = (p) => {
4213
+ try {
4214
+ return fs.readFileSync(p, "utf8");
4215
+ } catch {
4216
+ return "";
4217
+ }
4218
+ };
4219
+ const abs = path.resolve(root, file);
4220
+ const jestFile = resolution.foreign ? resolution.original : path.join(path.dirname(abs), "__snapshots__", `${path.basename(abs)}.snap`);
4221
+ const jestKey = key.split(" > ").join(" ");
4222
+ if (!read(jestFile).includes(`exports[\`${jestKey}\`]`)) return void 0;
4223
+ if (resolution.foreign) return key.includes(" > ") ? "shared-snapshot-dir-nested" : "shared-snapshot-dir";
4224
+ if (!resolution.copied) return "no-vitest-snapshot";
4225
+ return read(resolution.original).includes(`exports[\`${key}\`]`) ? void 0 : "no-vitest-snapshot";
4226
+ }
4227
+ function runFailure(name, run, timeoutMs) {
4228
+ if (run.interrupted) return `${name} was interrupted.`;
4229
+ if (run.timedOut) return `${name} did not finish within ${timeoutMs / 1e3}s and was stopped; raise --timeout if the suite needs longer.`;
4230
+ return null;
4231
+ }
4232
+ function reportFailure(log, message, run) {
4233
+ log(`✗ ${message}`);
4234
+ const tail = run.tail.filter((l) => l.trim() !== "").slice(-20);
4235
+ if (tail.length) {
4236
+ log(" Last output:");
4237
+ for (const line of tail) log(` ${line}`);
4238
+ }
4239
+ return run.interrupted ? 130 : 2;
4240
+ }
4241
+ // src/cli/index.ts
4242
+ /**
4243
+ * vitest-native CLI: `init` (write a ready config), `doctor` (diagnose the
4244
+ * environment), `migrate` (analyze a Jest config and report the mapping),
4245
+ * `compare` (run the suite under Jest and under Vitest and list the differences).
4246
+ * Deliberately vitest-free at module load — it runs via npx outside any test
4247
+ * process.
4248
+ */
4249
+ /** Each command's flags, besides --root <dir> and --help, which every command takes. */
4250
+ const COMMAND_FLAGS = {
4251
+ init: ["--jest-compat", "--force"],
4252
+ doctor: [],
4253
+ migrate: ["--write", "--force"],
4254
+ compare: [...COMPARE_VALUED_FLAGS, ...COMPARE_SWITCHES]
4255
+ };
4256
+ /** Flags whose value is the next argument (unless written as --flag=value). */
4257
+ const VALUED_FLAGS = /* @__PURE__ */ new Set(["--root", ...COMPARE_VALUED_FLAGS]);
4258
+ /**
4259
+ * The first flag `command` does not take, or null. An ignored typo (`--wirte`, `--stirct`)
4260
+ * would run something other than what was asked, so it is refused instead. The argument
4261
+ * after a valued flag is its value, even when it starts with "--" (`--jest-args "--ci"`).
4262
+ */
4263
+ function unknownFlag(command, args) {
4264
+ const allowed = /* @__PURE__ */ new Set([
4265
+ "--root",
4266
+ "--help",
4267
+ "-h",
4268
+ ...COMMAND_FLAGS[command] ?? []
4269
+ ]);
4270
+ for (let i = 0; i < args.length; i++) {
4271
+ const arg = args[i];
4272
+ if (!arg.startsWith("-")) continue;
4273
+ const name = arg.split("=")[0];
4274
+ if (!allowed.has(name)) return name;
4275
+ if (VALUED_FLAGS.has(name) && !arg.includes("=")) i++;
4276
+ }
4277
+ return null;
4278
+ }
4279
+ const USAGE = `vitest-native — test React Native with Vitest
4280
+
4281
+ Usage:
4282
+ vitest-native init [--jest-compat] [--force] write a ready-to-run vitest config
4283
+ vitest-native doctor diagnose peers, engine, presets, RNTL/Node
4284
+ vitest-native migrate [--write] [--force] analyze jest config → migration report
4285
+ (--write also saves the suggested config)
4286
+ vitest-native compare run the suite under Jest and under Vitest,
4287
+ list every test whose result differs
4288
+ --jest-args "<args>" extra Jest arguments --vitest-args "<args>" extra Vitest arguments
4289
+ --vitest-config <file> Vitest config to use --jest-results <file> read Jest's --json report
4290
+ --jest-root <dir> where that report was made (detected when omitted)
4291
+ --json <file> write a report to attach to an issue (no source code)
4292
+ --top <n> groups and files to list (10)
4293
+ --timeout <seconds> per runner (1800) --show-output stream both runners' output
4294
+ --strict confirm a parametrised (%p) row only by its title, never by its place
4295
+ exits 0 when every Jest-passing test passes under Vitest and \`vitest run\` exits 0,
4296
+ 1 when not, 2 when a runner could not run or the project changed, 130 when interrupted
4297
+ Options:
4298
+ --root <dir> project root (default: cwd)
4299
+ --help this text
4300
+
4301
+ Docs: ${docsUrl("/")}`;
4302
+ function main(argv, log = console.log) {
4303
+ const args = argv.filter((a) => a !== "--");
4304
+ const command = args.find((a, i) => !a.startsWith("-") && !COMPARE_VALUED_FLAGS.includes(args[i - 1]));
4305
+ const has = (flag) => args.includes(flag);
4306
+ const rootIdx = args.indexOf("--root");
4307
+ const root = path.resolve(rootIdx !== -1 ? args[rootIdx + 1] ?? "." : ".");
4308
+ if (has("--help") || has("-h")) {
4309
+ log(USAGE);
4310
+ return 0;
4311
+ }
4312
+ if (!command) {
4313
+ log(USAGE);
4314
+ return 1;
4315
+ }
4316
+ const unknown = command in COMMAND_FLAGS ? unknownFlag(command, args) : null;
4317
+ if (unknown) {
4318
+ log(`✗ unknown option ${unknown} for ${command}. Valid: ${[
4319
+ "--root",
4320
+ "--help",
4321
+ ...COMMAND_FLAGS[command]
4322
+ ].join(", ")}.`);
4323
+ return 1;
4324
+ }
4325
+ if (!fs.existsSync(path.join(root, "package.json"))) {
4326
+ log(`✗ no package.json at ${root} — run from a project root or pass --root.`);
4327
+ return 1;
4328
+ }
4329
+ switch (command) {
4330
+ case "doctor": {
4331
+ const result = runDoctor(root);
4332
+ for (const line of result.lines) log(line);
4333
+ return result.ok ? 0 : 1;
4334
+ }
4335
+ case "init": {
4336
+ const result = runInit(root, {
4337
+ jestCompat: has("--jest-compat"),
4338
+ force: has("--force")
4339
+ });
4340
+ for (const line of result.lines) log(line);
4341
+ return result.ok ? 0 : 1;
2111
4342
  }
2112
4343
  case "migrate": {
2113
4344
  const report = analyzeJestConfig(root);
@@ -2122,9 +4353,22 @@ function main(argv, log = console.log) {
2122
4353
  const target = path.join(root, init.wrote);
2123
4354
  fs.writeFileSync(target, report.suggestedConfig);
2124
4355
  log(`✓ wrote ${init.wrote} from the analysis above. Next: ${migrationNextStep(report)}`);
4356
+ for (const line of init.notices ?? []) log(line);
2125
4357
  }
2126
4358
  return report.ok ? 0 : 1;
2127
4359
  }
4360
+ case "compare": {
4361
+ const parsed = parseCompareArgs(args.filter((_, i) => i !== args.indexOf(command)));
4362
+ if ("error" in parsed) {
4363
+ log(`✗ ${parsed.error}`);
4364
+ return 1;
4365
+ }
4366
+ return runCompare({
4367
+ ...parsed,
4368
+ root,
4369
+ log
4370
+ });
4371
+ }
2128
4372
  default:
2129
4373
  log(`✗ unknown command '${command}'.`);
2130
4374
  log(USAGE);
@@ -2132,5 +4376,9 @@ function main(argv, log = console.log) {
2132
4376
  }
2133
4377
  }
2134
4378
  const entry = process.argv[1] ? path.basename(process.argv[1]) : "";
2135
- if (entry === "cli.mjs" || entry === "cli.cjs" || entry === "vitest-native") process.exit(main(process.argv.slice(2)));
2136
- export { main };
4379
+ if (entry === "cli.mjs" || entry === "vitest-native") {
4380
+ const code = main(process.argv.slice(2));
4381
+ if (typeof code === "number") process.exit(code);
4382
+ else code.then((c) => process.exit(c));
4383
+ }
4384
+ export { COMMAND_FLAGS, main, unknownFlag };