vitest-native 0.13.0 → 0.14.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 (77) hide show
  1. package/CHANGELOG.md +339 -0
  2. package/README.md +138 -48
  3. package/dist/cli.cjs +70 -5
  4. package/dist/cli.d.cts +2 -3
  5. package/dist/cli.d.mts +2 -3
  6. package/dist/cli.mjs +70 -5
  7. package/dist/{ecosystem-Duw40-mO.mjs → ecosystem-DFbU_MPe.mjs} +389 -18
  8. package/dist/{ecosystem-CEIF_-jq.cjs → ecosystem-DI1AhK_k.cjs} +408 -25
  9. package/dist/errors.d.mts +12 -0
  10. package/dist/helpers.cjs +6 -3
  11. package/dist/helpers.d.cts +8 -9
  12. package/dist/helpers.d.mts +8 -9
  13. package/dist/helpers.mjs +6 -3
  14. package/dist/{index-CPGq6p95.d.cts → index-BxzW2D7K.d.cts} +33 -9
  15. package/dist/{index-CmETArCM.d.mts → index-CEbwa4QU.d.mts} +33 -9
  16. package/dist/index.d.mts +4 -4
  17. package/dist/index.mjs +537 -118
  18. package/dist/jest-compat/aliases.d.mts +5 -0
  19. package/dist/jest-compat/aliases.mjs +65 -0
  20. package/dist/jest-compat/caller.mjs +53 -0
  21. package/dist/jest-compat/setup.mjs +72 -36
  22. package/dist/jest-compat.cjs +1 -3
  23. package/dist/jest-compat.d.cts +4 -5
  24. package/dist/jest-compat.d.mts +4 -5
  25. package/dist/jest-compat.mjs +1 -1
  26. package/dist/matchers.d.cts +9 -9
  27. package/dist/matchers.d.mts +9 -9
  28. package/dist/memory-6EPHrJA1.cjs +144 -0
  29. package/dist/memory-FYbP0_gg.mjs +126 -0
  30. package/dist/native/boundary.mjs +13 -2
  31. package/dist/native/bounded-process.mjs +165 -0
  32. package/dist/native/export-condition-recovery-preload.mjs +5 -0
  33. package/dist/native/export-condition-recovery.mjs +195 -0
  34. package/dist/native/globals.mjs +133 -5
  35. package/dist/native/hooks.mjs +131 -71
  36. package/dist/native/loader.mjs +41 -28
  37. package/dist/native/match.d.mts +3 -0
  38. package/dist/native/match.mjs +38 -2
  39. package/dist/native/metro-profile-compiler.mjs +234 -0
  40. package/dist/native/metro-profile.mjs +115 -0
  41. package/dist/native/module-reset.mjs +111 -6
  42. package/dist/native/ownership.d.mts +105 -0
  43. package/dist/native/ownership.mjs +474 -0
  44. package/dist/native/registry-compiler.mjs +43 -0
  45. package/dist/native/registry-process.mjs +124 -0
  46. package/dist/native/registry.mjs +139 -32
  47. package/dist/native/reset.mjs +305 -135
  48. package/dist/native/resolve.d.mts +20 -3
  49. package/dist/native/resolve.mjs +32 -12
  50. package/dist/native/rntl-hooks.mjs +76 -0
  51. package/dist/native/setup.mjs +81 -32
  52. package/dist/native/state-manifest.d.mts +22 -0
  53. package/dist/native/state-manifest.mjs +136 -0
  54. package/dist/native/transform.mjs +29 -8
  55. package/dist/native/worker.mjs +52 -4
  56. package/dist/pool-B4yesGhI.cjs +121 -0
  57. package/dist/pool-DjpOjOf3.mjs +119 -0
  58. package/dist/{presets-CoNf4ByH.cjs → presets-BYHmi7-W.cjs} +117 -18
  59. package/dist/{presets-DGProTaA.mjs → presets-DC-eM5IA.mjs} +117 -18
  60. package/dist/presets.d.mts +1 -1
  61. package/dist/presets.mjs +1 -1
  62. package/dist/rntl-matchers.d.ts +58 -12
  63. package/dist/serializer.cjs +4 -2
  64. package/dist/serializer.d.cts +3 -4
  65. package/dist/serializer.d.mts +3 -4
  66. package/dist/serializer.mjs +4 -2
  67. package/dist/setup.mjs +61 -50
  68. package/dist/worker-vitest-BGPo0ek6.mjs +49 -0
  69. package/dist/worker-vitest-BfiQB8ND.cjs +62 -0
  70. package/docs/hot-default-design.md +175 -88
  71. package/docs/migrating-from-jest.md +12 -5
  72. package/docs/migrating-from-vitest-react-native.md +4 -4
  73. package/docs/release-readiness.md +39 -13
  74. package/docs/versioning.md +19 -18
  75. package/package.json +42 -31
  76. package/dist/pool-BU-1ecIF.cjs +0 -122
  77. package/dist/pool-Bcxn9a3I.mjs +0 -118
@@ -26,7 +26,6 @@
26
26
  // through to the per-file hooks in hooks.mjs / loader.mjs, and a failed build leaves
27
27
  // the engine running exactly as it did before.
28
28
  import Module from "node:module";
29
- import { REACT_NATIVE_PATH } from "./match.mjs";
30
29
  import { createRequire } from "node:module";
31
30
  import path from "node:path";
32
31
  import fs from "node:fs";
@@ -35,6 +34,7 @@ import { transformRN, isFlow, cacheRootFor, TRANSFORM_CACHE_VERSION } from "./tr
35
34
 
36
35
  import { boundarySourceFor, BOUNDARY_SOURCES } from "./boundary.mjs";
37
36
  import { resolvePlatformFile, resolveDeepPackageFile } from "./resolve.mjs";
37
+ import { createNativeOwnershipPolicy } from "./ownership.mjs";
38
38
 
39
39
  /**
40
40
  * Losing the registry is a silent performance cliff, not a correctness problem:
@@ -86,7 +86,7 @@ export function _resetRegistryFailureReports() {
86
86
 
87
87
  // Bump when the emitted registry's shape or the walk's semantics change, so a
88
88
  // stale on-disk registry from an older vitest-native can never be reused.
89
- const REGISTRY_FORMAT_VERSION = 2;
89
+ const REGISTRY_FORMAT_VERSION = 3;
90
90
 
91
91
  /**
92
92
  * Literal `require('…')` / `require("…")` calls. The leading class excludes
@@ -106,17 +106,21 @@ const PASSTHROUGH_EXT = new Set([".json", ".node", ".wasm"]);
106
106
  * Source for one file, applying the same precedence the per-file hooks use:
107
107
  * asset stub → native-boundary mock → Flow-stripped RN → verbatim.
108
108
  */
109
- function sourceFor(file, { projectRoot, platform, reactNativeVersion, assetExtSet }) {
109
+ function sourceFor(file, { projectRoot, platform, reactNativeVersion, assetExtSet, ownership }) {
110
110
  const norm = file.replace(/\\/g, "/");
111
111
  const ext = path.extname(norm).slice(1).toLowerCase();
112
112
  if (ext && assetExtSet.has(ext)) {
113
113
  const basename = norm.split("/").pop() || norm;
114
114
  return { code: `module.exports = ${JSON.stringify(basename)};`, scan: false };
115
115
  }
116
- const boundary = boundarySourceFor(norm, platform, reactNativeVersion);
116
+ const boundary = boundarySourceFor(
117
+ ownership.reactNativePathFor(file) ?? norm,
118
+ platform,
119
+ reactNativeVersion,
120
+ );
117
121
  if (boundary != null) return { code: boundary, scan: true };
118
122
  const src = fs.readFileSync(file, "utf8");
119
- if (norm.endsWith(".js") && isFlow(src)) {
123
+ if (/\.(?:ts|tsx|jsx)$/.test(norm) || (norm.endsWith(".js") && isFlow(src))) {
120
124
  return { code: transformRN(file, src, projectRoot, platform), scan: true };
121
125
  }
122
126
  return { code: src, scan: true };
@@ -127,9 +131,13 @@ function sourceFor(file, { projectRoot, platform, reactNativeVersion, assetExtSe
127
131
  * resolution the hooks apply inside node_modules (`./Foo` → `Foo.ios.js`).
128
132
  * Returns an absolute path, or null when the target cannot be resolved.
129
133
  */
130
- function resolveTarget(request, fromFile, platform) {
134
+ function resolveTarget(request, fromFile, platform, sourceExts) {
131
135
  if (request.startsWith(".") && !path.extname(request)) {
132
- const hit = resolvePlatformFile(path.resolve(path.dirname(fromFile), request), platform);
136
+ const hit = resolvePlatformFile(
137
+ path.resolve(path.dirname(fromFile), request),
138
+ platform,
139
+ sourceExts,
140
+ );
133
141
  if (hit) return hit;
134
142
  }
135
143
  try {
@@ -148,6 +156,18 @@ function ownVersion() {
148
156
  }
149
157
  }
150
158
 
159
+ function canonicalAdditionalEntries(entries) {
160
+ return [...new Set(entries)].sort();
161
+ }
162
+
163
+ function canonicalAssetExtensions(extensions) {
164
+ return [
165
+ ...new Set(extensions.map((extension) => String(extension).replace(/^\./, "").toLowerCase())),
166
+ ]
167
+ .filter(Boolean)
168
+ .sort();
169
+ }
170
+
151
171
  /**
152
172
  * Identity of every input that determines the emitted registry's contents.
153
173
  *
@@ -163,7 +183,14 @@ function ownVersion() {
163
183
  *
164
184
  * Exported for tests. Not part of the public surface — see docs/versioning.md.
165
185
  */
166
- export function registryKey({ projectRoot, platform, reactNativeVersion }) {
186
+ export function registryKey({
187
+ projectRoot,
188
+ platform,
189
+ reactNativeVersion,
190
+ assetExts = [],
191
+ sourceExts = ["js", "jsx", "json", "ts", "tsx"],
192
+ additionalEntries = [],
193
+ }) {
167
194
  const req = createRequire(path.join(projectRoot, "package.json"));
168
195
  const version = (name) => {
169
196
  try {
@@ -211,6 +238,9 @@ export function registryKey({ projectRoot, platform, reactNativeVersion }) {
211
238
  version("@react-native/babel-preset"),
212
239
  version("@babel/core"),
213
240
  process.env.BABEL_ENV || process.env.NODE_ENV || "none",
241
+ ...sourceExts.map((extension) => `source:${extension}`),
242
+ ...canonicalAssetExtensions(assetExts).map((extension) => `asset:${extension}`),
243
+ ...canonicalAdditionalEntries(additionalEntries).map((entry) => `entry:${entry}`),
214
244
  boundaries.digest("hex"),
215
245
  ].join("\0"),
216
246
  )
@@ -372,7 +402,15 @@ export function buildRegistry({
372
402
  platform = "ios",
373
403
  reactNativeVersion = "0.0.0",
374
404
  assetExts = [],
405
+ sourceExts = ["js", "jsx", "json", "ts", "tsx"],
375
406
  diagnostics = false,
407
+ additionalEntries = [],
408
+ // Internal orchestration controls. `cacheOnly` lets the long-lived Vite process
409
+ // perform the cheap key/manifest check without ever loading Babel or compiling
410
+ // RN. `failOnError` lets the bounded compiler child return a structured failure;
411
+ // ordinary callers keep the warning + correctness-preserving fallback contract.
412
+ cacheOnly = false,
413
+ failOnError = false,
376
414
  }) {
377
415
  // See warnRegistryUnavailable: this is the one path that stays quiet, because
378
416
  // the user asked for it.
@@ -392,10 +430,18 @@ export function buildRegistry({
392
430
  let dir;
393
431
  let key;
394
432
  try {
395
- key = registryKey({ projectRoot, platform, reactNativeVersion });
433
+ key = registryKey({
434
+ projectRoot,
435
+ platform,
436
+ reactNativeVersion,
437
+ assetExts,
438
+ sourceExts,
439
+ additionalEntries,
440
+ });
396
441
  dir = path.join(cacheRootFor(projectRoot), "registry");
397
442
  fs.mkdirSync(dir, { recursive: true });
398
443
  } catch (error) {
444
+ if (failOnError) throw error;
399
445
  warnRegistryUnavailable(error?.message ?? "cache directory unavailable");
400
446
  return null;
401
447
  }
@@ -416,9 +462,19 @@ export function buildRegistry({
416
462
  // No usable cache entry — build one below.
417
463
  }
418
464
 
465
+ if (cacheOnly) return null;
466
+
419
467
  const started = Date.now();
420
468
  const assetExtSet = new Set(assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
421
- const options = { projectRoot, platform, reactNativeVersion, assetExtSet };
469
+ const ownership = createNativeOwnershipPolicy({ projectRoot });
470
+ const options = {
471
+ projectRoot,
472
+ platform,
473
+ reactNativeVersion,
474
+ assetExtSet,
475
+ sourceExts,
476
+ ownership,
477
+ };
422
478
  const modules = new Map();
423
479
  const manifest = [];
424
480
  // Targets the registry does NOT inline but DOES bake in as pre-resolved absolute
@@ -427,8 +483,15 @@ export function buildRegistry({
427
483
  // See the note above the manifest write below.
428
484
  const externals = new Set();
429
485
  try {
430
- const entry = createRequire(path.join(projectRoot, "package.json")).resolve("react-native");
431
- const queue = [entry];
486
+ const req = createRequire(path.join(projectRoot, "package.json"));
487
+ const entry = req.resolve("react-native");
488
+ // Keep the public React Native entry first in insertion order: emit() treats
489
+ // module zero as the capsule's default export. Additional ecosystem-owned deep
490
+ // imports are seed roots only; their factories remain lazy like the root graph.
491
+ const extraRoots = canonicalAdditionalEntries(additionalEntries).map((request) =>
492
+ req.resolve(request),
493
+ );
494
+ const queue = [...extraRoots.reverse(), entry];
432
495
  while (queue.length > 0) {
433
496
  const file = queue.pop();
434
497
  if (modules.has(file)) continue;
@@ -438,14 +501,14 @@ export function buildRegistry({
438
501
  for (const match of code.matchAll(REQUIRE_RE)) {
439
502
  const request = match[2];
440
503
  if (request in deps) continue;
441
- const target = resolveTarget(request, file, platform);
504
+ const target = resolveTarget(request, file, platform, sourceExts);
442
505
  // Only React Native's own graph is inlined. Everything else — react,
443
506
  // invariant, JSON manifests, native addons — stays a normal Node require
444
507
  // at a pre-resolved absolute path, so those modules keep their usual
445
508
  // identity and are shared with the rest of the worker.
446
509
  const internal =
447
510
  target !== null &&
448
- REACT_NATIVE_PATH.test(target.replace(/\\/g, "/")) &&
511
+ ownership.isReactNativeFile(target) &&
449
512
  !PASSTHROUGH_EXT.has(path.extname(target).toLowerCase());
450
513
  deps[request] = target;
451
514
  if (internal) queue.push(target);
@@ -485,18 +548,37 @@ export function buildRegistry({
485
548
  // cold cache, and a reader must never observe a partially written registry.
486
549
  // The map lands before the registry that points at it, so a reader can never
487
550
  // find the reference without the file.
551
+ const publishAtomically = (destination, contents) => {
552
+ const temporaryFile = `${destination}.${process.pid}.tmp`;
553
+ try {
554
+ fs.writeFileSync(temporaryFile, contents);
555
+ try {
556
+ fs.renameSync(temporaryFile, destination);
557
+ } catch (error) {
558
+ // POSIX rename replaces an existing file atomically. Windows rejects that
559
+ // shape, which two cold compiler processes can hit together. Remove only
560
+ // the already-published destination and retry; metadata is committed last,
561
+ // so readers never accept a half-published new registry as valid.
562
+ if (
563
+ process.platform !== "win32" ||
564
+ !["EEXIST", "EPERM", "EACCES"].includes(error?.code) ||
565
+ !fs.existsSync(destination)
566
+ ) {
567
+ throw error;
568
+ }
569
+ fs.rmSync(destination, { force: true });
570
+ fs.renameSync(temporaryFile, destination);
571
+ }
572
+ } finally {
573
+ // A failed write or publication must not leave a growing trail of PID
574
+ // temp files. A fatal process kill is recovered by the next cache miss.
575
+ fs.rmSync(temporaryFile, { force: true });
576
+ }
577
+ };
488
578
  const mapFile = `${registryFile}.map`;
489
- const mapTmp = `${mapFile}.${process.pid}.tmp`;
490
- fs.writeFileSync(mapTmp, JSON.stringify(map));
491
- fs.renameSync(mapTmp, mapFile);
492
- const tmp = `${registryFile}.${process.pid}.tmp`;
493
- fs.writeFileSync(tmp, `${code}\n//# sourceMappingURL=${path.basename(mapFile)}\n`);
494
- fs.renameSync(tmp, registryFile);
495
- fs.writeFileSync(
496
- `${metaFile}.${process.pid}.tmp`,
497
- JSON.stringify({ key, count: files.length, manifest }),
498
- );
499
- fs.renameSync(`${metaFile}.${process.pid}.tmp`, metaFile);
579
+ publishAtomically(mapFile, JSON.stringify(map));
580
+ publishAtomically(registryFile, `${code}\n//# sourceMappingURL=${path.basename(mapFile)}\n`);
581
+ publishAtomically(metaFile, JSON.stringify({ key, count: files.length, manifest }));
500
582
  if (diagnostics) {
501
583
  console.log(
502
584
  `[vitest-native] (native) precompiled RN registry: ${files.length} modules in ${Date.now() - started}ms`,
@@ -504,6 +586,7 @@ export function buildRegistry({
504
586
  }
505
587
  return registryFile;
506
588
  } catch (error) {
589
+ if (failOnError) throw error;
507
590
  warnRegistryUnavailable(error?.message ?? "unknown error");
508
591
  return null;
509
592
  }
@@ -516,7 +599,11 @@ export function buildRegistry({
516
599
  * (and therefore takes precedence over) this one — a preset-shadowed package must
517
600
  * still win over anything RN's own graph would provide.
518
601
  */
519
- export function installRegistry(registryFile, projectRoot) {
602
+ export function installRegistry(
603
+ registryFile,
604
+ projectRoot,
605
+ sourceExts = ["js", "jsx", "json", "ts", "tsx"],
606
+ ) {
520
607
  if (globalThis.__vitest_native_registry_installed) return true;
521
608
  const req = createRequire(path.join(projectRoot, "package.json"));
522
609
  // Must precede the require below: Node reads `//# sourceMappingURL` when a script
@@ -538,6 +625,14 @@ export function installRegistry(registryFile, projectRoot) {
538
625
  globalThis.__vitest_native_registry_installed = true;
539
626
  globalThis.__vitest_native_registry_reset = () => registry.reset();
540
627
 
628
+ // Node records the loaded file under its real path (`/private/var/…` for macOS's
629
+ // `/var/…` tmpdir), so match the registry file by both spellings.
630
+ let registryRealFile = registryFile;
631
+ try {
632
+ registryRealFile = fs.realpathSync(registryFile);
633
+ } catch {
634
+ // Just loaded, so it exists; an unresolvable path keeps the given spelling.
635
+ }
541
636
  const idOf = new Map(registry.ids.map((f, i) => [f, i]));
542
637
  const entryId = idOf.get(registry.entry);
543
638
  const origLoad = Module._load;
@@ -552,7 +647,15 @@ export function installRegistry(registryFile, projectRoot) {
552
647
  // @react-native/* packages inlined alongside it must resolve to the SAME
553
648
  // instances the entry graph uses, or RN's singletons would exist twice.
554
649
  if (request.startsWith("react-native/") || request.startsWith("@react-native/")) {
555
- const resolver = parent?.filename ? createRequire(parent.filename) : req;
650
+ // The registry's own code requires with the registry FILE as parent, and that
651
+ // file lives in a cache directory that may be outside the project (tmpdir when
652
+ // the project has no writable node_modules). Resolve those from the project.
653
+ const fromProject =
654
+ !parent?.filename ||
655
+ parent.filename === registryFile ||
656
+ parent.filename === registryRealFile;
657
+ const resolver = fromProject ? req : createRequire(parent.filename);
658
+ const platform = process.env.VITEST_NATIVE_PLATFORM === "android" ? "android" : "ios";
556
659
  let resolved;
557
660
  try {
558
661
  resolved = resolver.resolve(request);
@@ -560,11 +663,15 @@ export function installRegistry(registryFile, projectRoot) {
560
663
  // RN 0.87's exports map refuses the deep self-references its preset
561
664
  // emits; resolve by path (Metro's behavior) so the file still lands on
562
665
  // the registry's instance instead of loading a twin outside it.
563
- resolved = resolveDeepPackageFile(
564
- request,
565
- parent?.filename ? path.dirname(parent.filename) : projectRoot,
566
- process.env.VITEST_NATIVE_PLATFORM === "android" ? "android" : "ios",
567
- );
666
+ resolved =
667
+ (fromProject
668
+ ? null
669
+ : resolveDeepPackageFile(
670
+ request,
671
+ path.dirname(parent.filename),
672
+ platform,
673
+ sourceExts,
674
+ )) ?? resolveDeepPackageFile(request, projectRoot, platform, sourceExts);
568
675
  }
569
676
  const id = resolved === null ? undefined : idOf.get(resolved);
570
677
  if (id !== undefined) return registry.load(id);