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
@@ -14,10 +14,20 @@ import fs from "node:fs";
14
14
  import path from "node:path";
15
15
  import { fileURLToPath } from "node:url";
16
16
  import { expandAlias } from "./aliases.mjs";
17
- import { resolvePlatformFile, resolveRelativePlatformFile } from "../native/resolve.mjs";
17
+ import { expandResolutionAlias } from "../native/shared-resolver.mjs";
18
+ import {
19
+ isWholePackageRequest,
20
+ resolvePackageMainField,
21
+ platformSubpathFile,
22
+ resolvePlatformFile,
23
+ resolveRelativePlatformFile,
24
+ } from "../native/resolve.mjs";
18
25
  import { resetEvaluatedModules, restoreEvaluatedModules } from "../native/module-reset.mjs";
19
26
  import { VitestNativeError } from "../errors.mjs";
20
- import { projectContext } from "../context.mjs";
27
+ import { activeRegistry, projectContext } from "../context.mjs";
28
+ import { nodeDispatch } from "../node-dispatch.mjs";
29
+ import { jestMockInterop } from "./interop.mjs";
30
+ import { owningPackageOfFile, packageNameOf } from "../native/match.mjs";
21
31
 
22
32
  const STATE = "__vitest_native_jest_registry";
23
33
  /** The manifest id under which the hot runtime clears the registry per file. */
@@ -30,16 +40,53 @@ const UNRESETTABLE = /\.node$/;
30
40
  // modules, while Node's loader gives the parsed object or the asset stub itself.
31
41
  const SOURCE_FILE = /\.[cm]?[jt]sx?$/;
32
42
  const NONE = Symbol("vitest-native.jest-registry.none");
43
+ // `requireActual`'s one load: the real module, past every mock (lookup).
44
+ const BYPASSED = Symbol("vitest-native.jest-registry.bypassed");
33
45
 
34
46
  const context = projectContext();
47
+ // The ownership guard's channel on the engine's dispatcher (native/ownership-ledger.mjs).
48
+ const ownershipChannel = nodeDispatch().channel("ownership");
35
49
 
36
50
  /** Configuration the plugin hands the worker, shared with the compat setup. */
51
+ // Under experimental.ownershipModel the project's aliases have one record, the shared
52
+ // resolver's (every string and RegExp alias, and tsconfig `paths`, in Vite's order), and
53
+ // the plugin writes no second one.
54
+ const resolverAliases =
55
+ context?.ownershipModel === "resolver" || context?.ownershipModel === "resolution"
56
+ ? (context.resolverInputs?.aliases ?? [])
57
+ : null;
58
+ const requireAliases = context?.requireAliases ?? [];
59
+
60
+ /** The name of the factory that loads a manual mock (see `manual` in state.register). */
61
+ export const MANUAL_MOCK_FACTORY = "__vnManualMock";
62
+
63
+ /**
64
+ * Whether `entry` is a manual mock still executing: its factory running, or its async
65
+ * variant pending. A request for the module it mocks is then the real module, as under
66
+ * Jest (`_isCurrentlyExecutingManualMock`), through Node's loader and through the
67
+ * precompiled React Native registry alike.
68
+ */
69
+ function isExecutingManualMock(entry) {
70
+ return (
71
+ entry !== undefined &&
72
+ typeof entry === "object" &&
73
+ entry.manual === true &&
74
+ !entry.has &&
75
+ (entry.evaluating || entry.pending !== null)
76
+ );
77
+ }
78
+
37
79
  export const config = {
38
80
  projectRoot: context?.projectRoot ?? process.cwd(),
39
81
  platform: context?.platform === "android" ? "android" : "ios",
40
- // The project's string-to-string `resolve.alias` entries (and tsconfig `paths` when
41
- // Vite resolves them), which Node knows nothing of.
42
- aliases: context?.requireAliases ?? [],
82
+ /** `specifier` with the project's alias applied, which Node knows nothing of. */
83
+ expandAlias:
84
+ resolverAliases === null
85
+ ? // The string-to-string `resolve.alias` entries (and tsconfig `paths` when Vite
86
+ // resolves them).
87
+ (specifier) => expandAlias(specifier, requireAliases)
88
+ : (specifier) => expandResolutionAlias(specifier, resolverAliases),
89
+ // Under the flag none: an alias Node cannot apply is refused when the plugin loads.
43
90
  skippedAliases: context?.requireAliasesSkipped ?? [],
44
91
  };
45
92
  const sourceExts = context?.sourceExts ?? [];
@@ -50,6 +97,7 @@ function canonical(file) {
50
97
  let real = realpathCache.get(file);
51
98
  if (real === undefined) {
52
99
  try {
100
+ // Node's spelling (fs.realpathSync): the key Module._cache holds the file under.
53
101
  real = fs.realpathSync(file);
54
102
  } catch {
55
103
  real = file;
@@ -70,10 +118,45 @@ function parentModuleFor(file) {
70
118
  /** Vitest's worker state: the evaluated module graph and the running test file. */
71
119
  const worker = () => globalThis.__vitest_worker__;
72
120
 
121
+ /**
122
+ * The directory of the package `file` is in, by the same rule as `owningPackageOfFile`
123
+ * (the one after its last `node_modules/`), with forward slashes. Null outside
124
+ * node_modules.
125
+ */
126
+ function installedPackageDirOf(file) {
127
+ const norm = file.replace(/\\/g, "/");
128
+ const pkg = owningPackageOfFile(norm);
129
+ if (pkg === null) return null;
130
+ const at = norm.lastIndexOf("/node_modules/") + "/node_modules/".length;
131
+ return norm.slice(0, at + pkg.length);
132
+ }
133
+
134
+ /** A Map that reports each change, so what is derived from its contents can be rebuilt. */
135
+ class WatchedMap extends Map {
136
+ constructor(onChange) {
137
+ super();
138
+ this.onChange = onChange;
139
+ }
140
+ set(key, value) {
141
+ super.set(key, value);
142
+ this.onChange();
143
+ return this;
144
+ }
145
+ delete(key) {
146
+ const had = super.delete(key);
147
+ if (had) this.onChange();
148
+ return had;
149
+ }
150
+ clear() {
151
+ super.clear();
152
+ this.onChange();
153
+ }
154
+ }
155
+
73
156
  function createState() {
74
157
  const rootFile = path.join(config.projectRoot, "package.json");
75
158
  const rootParent = parentModuleFor(rootFile);
76
- const registryFile = context?.registry;
159
+ const registryFile = activeRegistry(context);
77
160
  const realRegistryFile = registryFile ? canonical(registryFile) : null;
78
161
  const exts = sourceExts.length > 0 ? sourceExts : undefined;
79
162
  const platformFile = (base) => {
@@ -85,11 +168,16 @@ function createState() {
85
168
  return hit && canonical(hit);
86
169
  };
87
170
 
171
+ let reach = null;
172
+ const changed = () => {
173
+ reach = null;
174
+ };
175
+
88
176
  const state = {
89
177
  /** Resolved file -> entry. */
90
- entries: new Map(),
178
+ entries: new WatchedMap(changed),
91
179
  /** Specifiers no resolver could place (Jest's virtual mocks) -> entry. */
92
- unresolved: new Map(),
180
+ unresolved: new WatchedMap(changed),
93
181
  /** `parentFile\0request` -> resolved file or null. Valid for the worker's life. */
94
182
  resolutions: new Map(),
95
183
  /** What `requireActual` is loading: its next load skips the mock. */
@@ -103,6 +191,8 @@ function createState() {
103
191
  */
104
192
  baseline: new Set(Object.keys(Module._cache)),
105
193
  baselineFixed: false,
194
+ /** Platform files a React Native subpath resolved to (subpathPlatformFile). */
195
+ platformSubpaths: new Set(),
106
196
  };
107
197
 
108
198
  // Resolve as the require hooks will, so registration and lookup share one key:
@@ -117,12 +207,13 @@ function createState() {
117
207
  }
118
208
  try {
119
209
  const resolved = Module._resolveFilename(request, parent, false);
210
+ if (Module.isBuiltin(resolved)) return null;
120
211
  // The hooks' fallbacks return the path as found, not the real path.
121
- return Module.isBuiltin(resolved) ? null : canonical(resolved);
212
+ return subpathPlatformFile(request, resolved) ?? canonical(resolved);
122
213
  } catch {
123
214
  // fall through
124
215
  }
125
- const expanded = isPath ? request : expandAlias(request, config.aliases);
216
+ const expanded = isPath ? request : config.expandAlias(request);
126
217
  if (expanded === request) return null;
127
218
  if (path.isAbsolute(expanded) && !path.extname(expanded)) {
128
219
  const hit = platformFile(expanded);
@@ -135,6 +226,19 @@ function createState() {
135
226
  }
136
227
  }
137
228
 
229
+ // A React Native subpath lands on its platform file (#573). Recorded, so
230
+ // requireActual loads that file itself (state.require): by the subpath, Node would
231
+ // load the shim the package's `exports` map names, whose require of the platform
232
+ // file would come back to the mock.
233
+ const subpathPlatformFile = (request, resolved) => {
234
+ if (!request.startsWith("react-native/")) return null;
235
+ const hit = platformSubpathFile(request, resolved, config.platform, exts);
236
+ if (!hit) return null;
237
+ const file = canonical(hit);
238
+ state.platformSubpaths.add(file);
239
+ return file;
240
+ };
241
+
138
242
  /**
139
243
  * How often the load hook asked `state.resolve`, how often that resolved afresh rather
140
244
  * than from its cache, and how often a request went to Node without either.
@@ -247,34 +351,55 @@ function createState() {
247
351
  // in turn is mocked as usual. A virtual mock has no real module, so Node's
248
352
  // loader reports it missing, as Jest does.
249
353
  state.bypass = null;
250
- return undefined;
354
+ return BYPASSED;
251
355
  }
252
356
  return filename !== null ? state.entries.get(filename) : state.unresolved.get(request);
253
357
  };
254
358
 
255
359
  // `asyncFactory` is jestMockTransform's async variant of `factory`, when it made one.
256
- state.register = (from, spec, factory, asyncFactory) => {
360
+ // `library`: registered by a library's own test support (native/library-jest.mjs),
361
+ // whose lifetime the native setup decides at each file boundary; `owner` is what it
362
+ // keeps it by.
363
+ state.register = (from, spec, factory, asyncFactory, { library = false, owner = null } = {}) => {
257
364
  const filename = state.resolveFrom(spec, from);
258
365
  const entry = {
259
366
  spec,
260
367
  factory,
261
368
  asyncFactory,
369
+ // A manual mock (a __mocks__ file, jest-compat/root-mocks.ts): while it executes, a
370
+ // request for the module it mocks is the real module, as jest-runtime's
371
+ // `_isCurrentlyExecutingManualMock` has it, not a cycle.
372
+ manual: factory?.name === MANUAL_MOCK_FACTORY,
262
373
  has: false,
263
374
  value: undefined,
264
375
  pending: null,
265
376
  evaluating: false,
377
+ library,
378
+ owner,
266
379
  };
267
- if (filename !== null) state.entries.set(filename, entry);
268
- else state.unresolved.set(spec, entry);
380
+ if (filename !== null) {
381
+ state.entries.set(filename, entry);
382
+ state.decided.add(canonical(filename));
383
+ } else state.unresolved.set(spec, entry);
269
384
  // The hoisted `vi.mock` factory looks its entry up by where it was written.
270
385
  state.byCall.set(`${from}\0${spec}`, entry);
271
386
  return entry;
272
387
  };
273
388
  state.byCall = new Map();
389
+ /**
390
+ * The files a jest.* call registered or unregistered in this test file. Jest-compat
391
+ * applies each to Node's require at once, and also queues it with Vitest for the
392
+ * test's next import; that queued vi.doMock/vi.doUnmock is jest-compat's own, already
393
+ * applied here, so it is no pending mock for Node (assertNoPendingMockOf).
394
+ */
395
+ state.decided = new Set();
274
396
 
275
397
  state.unregister = (from, spec) => {
276
398
  const filename = state.resolveFrom(spec, from);
277
- if (filename !== null) state.entries.delete(filename);
399
+ if (filename !== null) {
400
+ state.entries.delete(filename);
401
+ state.decided.add(canonical(filename));
402
+ }
278
403
  state.unresolved.delete(spec);
279
404
  };
280
405
 
@@ -285,10 +410,22 @@ function createState() {
285
410
  const isPath = spec.startsWith(".") || path.isAbsolute(spec);
286
411
  const anchor = isPath && caller ? caller : rootFile;
287
412
  const filename = state.resolveFrom(spec, anchor);
288
- if (actual) state.bypass = filename ?? `\0${spec}`;
413
+ if (actual) {
414
+ state.bypass = filename ?? `\0${spec}`;
415
+ // A preset shadows its package by name (native/hooks.mjs); the actual module is
416
+ // the package, as Jest's requireActual gives it, so this one load skips it too.
417
+ if (!isPath) state.presetActual = spec;
418
+ }
419
+ // Tells the ownership guard that what Node compiles now is a jest-compat load, so
420
+ // a dual evaluation it causes is reported with the jest-compat route and fix
421
+ // (native/ownership-ledger.mjs) without a stack captured per compile.
422
+ ownershipChannel.jestRequireDepth = (ownershipChannel.jestRequireDepth ?? 0) + 1;
289
423
  try {
290
424
  const load = createRequire(anchor);
291
- if (filename !== null && (isPath || expandAlias(spec, config.aliases) !== spec)) {
425
+ if (
426
+ filename !== null &&
427
+ (isPath || config.expandAlias(spec) !== spec || state.platformSubpaths.has(filename))
428
+ ) {
292
429
  return load(filename);
293
430
  }
294
431
  return load(spec);
@@ -305,7 +442,11 @@ function createState() {
305
442
  }
306
443
  throw error;
307
444
  } finally {
308
- if (actual) state.bypass = null;
445
+ ownershipChannel.jestRequireDepth -= 1;
446
+ if (actual) {
447
+ state.bypass = null;
448
+ state.presetActual = undefined;
449
+ }
309
450
  }
310
451
  };
311
452
 
@@ -390,16 +531,93 @@ function createState() {
390
531
  };
391
532
  };
392
533
 
393
- state.clear = () => {
394
- state.entries.clear();
395
- state.unresolved.clear();
396
- state.byCall.clear();
534
+ /**
535
+ * Drop the registrations. The compat setup clears the test file's own before each
536
+ * file (`keepLibrary`): libraries' registrations were settled already, by the native
537
+ * setup, which runs first and keeps those `keep` says. The hot runtime clears
538
+ * everything at the file boundary, before the setup files run again.
539
+ */
540
+ state.clear = ({ keepLibrary = false, keep: kept } = {}) => {
541
+ const keep = (map) => {
542
+ for (const [key, entry] of map) {
543
+ if (!((keepLibrary && entry.library) || kept?.(entry))) map.delete(key);
544
+ }
545
+ };
546
+ keep(state.entries);
547
+ keep(state.unresolved);
548
+ keep(state.byCall);
549
+ // Decisions are derived from the registrations: recomputed after any clear.
550
+ state.decided.clear();
397
551
  state.bypass = null;
398
552
  state.isolation = null;
399
553
  };
400
554
 
401
555
  state.isEmpty = () => state.entries.size === 0 && state.unresolved.size === 0;
402
556
 
557
+ /**
558
+ * What the registered mocks can be reached by, rebuilt after a registration changes:
559
+ * the package names a bare request can name them by, and the package directories
560
+ * their files are in. `wide` when an entry is outside node_modules (a project file)
561
+ * or a virtual mock of a path, which any request may reach through an alias or a
562
+ * relative path, so every request is resolved, as when this index did not exist.
563
+ */
564
+ function reachIndex() {
565
+ if (reach !== null) return reach;
566
+ const names = new Set();
567
+ const dirs = new Set();
568
+ let wide = false;
569
+ for (const [file, entry] of state.entries) {
570
+ const dir = installedPackageDirOf(file);
571
+ if (dir === null) {
572
+ wide = true;
573
+ break;
574
+ }
575
+ dirs.add(dir);
576
+ names.add(owningPackageOfFile(file));
577
+ // An npm alias installs a package under a name its manifest does not carry.
578
+ if (typeof entry.spec === "string" && isBare(entry.spec)) {
579
+ names.add(packageNameOf(entry.spec));
580
+ }
581
+ }
582
+ for (const spec of state.unresolved.keys()) {
583
+ if (isBare(spec)) names.add(packageNameOf(spec));
584
+ else wide = true;
585
+ }
586
+ reach = { names, dirs, wide, aliased: new Map() };
587
+ return reach;
588
+ }
589
+
590
+ /**
591
+ * Whether a load of `request` from `parent` can be served a registered mock, without
592
+ * resolving it: the mocks a library's Jest setup registers stay in every file, and
593
+ * resolving every require of every file to look for them costs more than the file.
594
+ * A bare request reaches a mock by its package name, or by an alias the require hooks
595
+ * apply when Node cannot resolve it; a path reaches one in the package directory it
596
+ * points into. Any request a mocked package makes may reach its own mocks, since its
597
+ * `react-native` or `browser` field can send even a bare name to its own files, and a
598
+ * subpath import (`#internal`) maps through its importer's manifest.
599
+ */
600
+ state.mayIntercept = (request, parent) => {
601
+ if (state.isEmpty()) return false;
602
+ const index = reachIndex();
603
+ if (index.wide) return true;
604
+ const from = typeof parent?.filename === "string" ? parent.filename : null;
605
+ if (from !== null && index.dirs.has(installedPackageDirOf(from))) return true;
606
+ if (request.startsWith("#") || request.startsWith("file:")) return true;
607
+ if (isBare(request)) {
608
+ if (index.names.has(packageNameOf(request))) return true;
609
+ let aliased = index.aliased.get(request);
610
+ if (aliased === undefined) {
611
+ aliased = config.expandAlias(request) !== request;
612
+ index.aliased.set(request, aliased);
613
+ }
614
+ return aliased;
615
+ }
616
+ if (from === null && !path.isAbsolute(request)) return true;
617
+ const target = from === null ? request : path.resolve(path.dirname(from), request);
618
+ return index.dirs.has(installedPackageDirOf(target));
619
+ };
620
+
403
621
  return state;
404
622
  }
405
623
 
@@ -438,25 +656,60 @@ export function shareProjectModules() {
438
656
  * Vite's instance of a project module this file already evaluated, for a CommonJS
439
657
  * consumer, or NONE — so `require('./store')` after `import './store'` is one module,
440
658
  * as under Jest's single registry. Read from Vitest's worker state (`getModulesByFile`
441
- * is Vite's `EvaluatedModules` API). Skipped: nodes mid-evaluation, `mock:` nodes
442
- * (this registry serves those), and CommonJS Vite evaluated, whose `module.exports`
443
- * is a plain `default` data property where an ES module's exports are all getters.
444
- * The facade adds `__esModule` for Babel's interop, and a write defines a value on
445
- * the shared exports object, as `require(x).FLAG = true` does under babel-jest.
659
+ * is Vite's `EvaluatedModules` API). Skipped: nodes mid-evaluation and `mock:` nodes
660
+ * (this registry serves those). The facade adds `__esModule` for Babel's interop, and
661
+ * a write defines a value on the shared exports object, as `require(x).FLAG = true`
662
+ * does under babel-jest.
663
+ *
664
+ * CommonJS that Vite evaluated is told apart by its `default`: a plain data property
665
+ * holding `module.exports` (Vitest's `_createCJSGlobals` stores it there), where an
666
+ * ES module's exports are all getters. Its `module.exports` is what `require` returns,
667
+ * so that value is handed back as is. It used to be skipped, and Node compiled a
668
+ * second copy of the file: the ownership guard reported it (docs/ownership-guard.md).
446
669
  */
447
670
  const viteFacades = new WeakMap();
448
671
  function viteInstanceOf(filename) {
449
- if (!SOURCE_FILE.test(filename)) return NONE;
672
+ const json = filename.endsWith(".json");
673
+ if (!json && !SOURCE_FILE.test(filename)) return NONE;
450
674
  const nodes = worker()?.evaluatedModules?.getModulesByFile?.(filename.replace(/\\/g, "/"));
451
675
  for (const node of nodes ?? []) {
452
676
  if (node.id?.startsWith("mock:") || !node.evaluated || node.exports == null) continue;
453
677
  const ns = node.exports;
454
- if (isCommonJsNamespace(ns)) return NONE;
678
+ // JSON: `require` returns the parsed object, which Vite's module exports as default.
679
+ if (json) return "default" in ns ? ns.default : NONE;
680
+ if (isCommonJsNamespace(ns)) return ns.default;
455
681
  return requireFacade(ns);
456
682
  }
457
683
  return NONE;
458
684
  }
459
685
 
686
+ const bridging = context?.ownershipModel === "resolution";
687
+ let bridge = null;
688
+ let loadingBridge = false;
689
+ /**
690
+ * The require bridge's answer for `filename` (native/bridge.mjs), loaded on first use so
691
+ * a worker that never needs it loads nothing: an ES namespace through the same facade as
692
+ * viteInstanceOf, CommonJS as its module.exports, or NONE for a file Vite does not own or
693
+ * loads through Node (externalized).
694
+ */
695
+ function bridgedInstanceOf(filename, parent) {
696
+ if (!SOURCE_FILE.test(filename)) return NONE;
697
+ if (bridge === null) {
698
+ // Loading the bridge is itself a require through this interceptor: it is never bridged.
699
+ if (loadingBridge) return NONE;
700
+ loadingBridge = true;
701
+ try {
702
+ bridge = createRequire(import.meta.url)("../native/bridge.mjs");
703
+ } finally {
704
+ loadingBridge = false;
705
+ }
706
+ }
707
+ if (!bridge.isViteOwned(filename)) return NONE;
708
+ const value = bridge.requireViteOwned(filename, parent);
709
+ if (value === undefined) return NONE;
710
+ return Object.prototype.toString.call(value) === "[object Module]" ? requireFacade(value) : value;
711
+ }
712
+
460
713
  /**
461
714
  * A bare specifier (a package name). Aliases need no check here: the require hooks
462
715
  * apply them only after Node fails, so Node's answer for an aliased name is already the
@@ -550,48 +803,434 @@ function requireFacade(ns) {
550
803
  return facade;
551
804
  }
552
805
 
553
- function installLoadHook(state) {
554
- const origLoad = Module._load;
555
- Module._load = function (request, parent, ...rest) {
556
- // A project file is what a test or a Node-loaded project module requires. Only
557
- // those requests can share Vite's instances; any request can hit a mock, but
558
- // only when there is one.
559
- const fromProject =
560
- typeof parent?.filename === "string" &&
561
- !NODE_MODULES.test(parent.filename) &&
562
- state.isResettable(parent.filename);
563
- if ((!fromProject && state.isEmpty()) || Module.isBuiltin(request)) {
564
- return origLoad.call(this, request, parent, ...rest);
806
+ // experimental.nodeMocks (docs: node-mocks-design.md in the planning repository, rules
807
+ // R1-R10): a `vi.mock` applies to the modules Node loads, as a jest.mock factory does
808
+ // (#322). Vitest keeps the file's mocks in its mocker's registry, keyed by the file Vite
809
+ // resolved. A request is served one when the file Node resolves for that requester is
810
+ // that file. Off unless the project opts in: it changes what an installed package's own
811
+ // require returns.
812
+ const nodeMocks = context?.nodeMocks === true;
813
+
814
+ // R1: only a module's own require is served a Vitest mock. A load with no parent module
815
+ // is Node's: its ESM loader evaluating CommonJS an import reached, which is how Vitest
816
+ // loads a mocked module's original (importOriginal, vi.importActual, an automock) by
817
+ // its URL. That decision for Node's ESM imports is made in loader.mjs's resolve hook.
818
+ const madeByVitest = (parentFile) => typeof parentFile !== "string";
819
+ const pendingCount = () => globalThis.__vitest_mocker__?.constructor?.pendingIds?.length ?? 0;
820
+
821
+ /** A mock entry's file: its Vite id as a path, without a query, or null for a virtual id. */
822
+ function mockedFileOf(entry) {
823
+ if (typeof entry?.id !== "string") return null;
824
+ let file = entry.id.startsWith("/@fs/") ? entry.id.slice(4) : entry.id;
825
+ const query = file.indexOf("?");
826
+ if (query !== -1) file = file.slice(0, query);
827
+ // A virtual id (the engine's react-native facade for `vi.mock('react-native')`) is
828
+ // Vite's alone: its factory's importOriginal() reaches React Native through Node's
829
+ // require of the package, so it is not served to Node.
830
+ return path.isAbsolute(file) ? canonical(file) : null;
831
+ }
832
+
833
+ /** The directory of the package `file` belongs to, or null outside node_modules. */
834
+ function packageDirOf(file) {
835
+ const pkg = owningPackageOfFile(file);
836
+ if (pkg !== null) {
837
+ const norm = file.replace(/\\/g, "/");
838
+ const at = norm.lastIndexOf("/node_modules/") + "/node_modules/".length;
839
+ return norm.slice(0, at + pkg.length);
840
+ }
841
+ return nearestNamedPackage(file)?.dir ?? null;
842
+ }
843
+
844
+ /** The name in the nearest package.json above `file` that names a package, or null. */
845
+ function packageNameAt(file) {
846
+ return nearestNamedPackage(file)?.name ?? null;
847
+ }
848
+
849
+ /**
850
+ * A workspace package (a link to source, at its real path): the nearest package.json
851
+ * that names a package, as `{ dir, name }`.
852
+ */
853
+ function nearestNamedPackage(file) {
854
+ for (let dir = path.dirname(file); ; dir = path.dirname(dir)) {
855
+ let name;
856
+ if (packageDirs.has(dir)) name = packageDirs.get(dir);
857
+ else {
858
+ try {
859
+ name = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")).name ?? null;
860
+ } catch {
861
+ name = null; // No manifest here, or an unreadable one: look further up.
862
+ }
863
+ packageDirs.set(dir, name);
565
864
  }
566
- // With no mocks, only a project file can be served from Vite. For a bare specifier,
567
- // Node's own answer decides: a file under node_modules goes to Node's loader as is;
568
- // anything else (a workspace link to source, a package's self-reference, an alias the
569
- // hooks apply) is resolved as below, reusing that answer.
570
- if (state.isEmpty() && isBare(request)) {
571
- const resolved = nodeResolution(request, parent);
572
- if (resolved !== null && NODE_MODULES.test(resolved)) {
573
- state.stats.toNode++;
574
- return origLoad.call(this, request, parent, ...rest);
865
+ if (typeof name === "string") return { dir: dir.replace(/\\/g, "/"), name };
866
+ if (path.dirname(dir) === dir) return null;
867
+ }
868
+ }
869
+ const packageDirs = new Map();
870
+ /** Test seam: the package directory a mock's file and a request's file are compared by. */
871
+ export const _packageDirOf = packageDirOf;
872
+
873
+ /**
874
+ * The current file's Vitest mocks, indexed by the file each mocks, or null when there
875
+ * are none. R6: rebuilt whenever the registry, or any entry in it, is another object
876
+ * (a re-mock or an unmock and a mock change entries without changing their count).
877
+ */
878
+ function vitestMocks() {
879
+ const registry = globalThis.__vitest_mocker__?.getMockerRegistry?.();
880
+ const byId = registry?.registryById;
881
+ if (!(byId instanceof Map) || byId.size === 0) return null;
882
+ const held = vitestMocks.held;
883
+ if (held !== undefined && held.registry === registry && held.entries.length === byId.size) {
884
+ let same = true;
885
+ let i = 0;
886
+ for (const entry of byId.values()) {
887
+ if (held.entries[i++] !== entry) {
888
+ same = false;
889
+ break;
575
890
  }
576
- if (resolved !== null) state.resolutions.set(`${parent.filename}\0${request}`, resolved);
577
891
  }
578
- const filename = state.resolve(request, parent);
579
- const entry = state.lookup(filename, request);
580
- if (entry !== undefined) return state.valueOf(entry);
581
- // A module Node already holds stays the one `require` returns: switching a later
582
- // require to Vite's copy would change its identity mid-file.
892
+ if (same) return held.index;
893
+ }
894
+ const entries = [...byId.values()];
895
+ const index = { byFile: new Map(), packages: new Set(), projectFiles: false };
896
+ for (const entry of entries) {
897
+ const file = mockedFileOf(entry);
898
+ if (file === null) continue;
899
+ index.byFile.set(file, entry);
900
+ const pkg = owningPackageOfFile(file);
901
+ if (pkg !== null) index.packages.add(pkg);
902
+ else {
903
+ index.projectFiles = true;
904
+ // A workspace package, mocked at its real path, is still reached by its name
905
+ // through a node_modules link.
906
+ const name = packageNameAt(file);
907
+ if (name !== null) index.packages.add(name);
908
+ }
909
+ }
910
+ vitestMocks.held = { registry, entries, index: index.byFile.size === 0 ? null : index };
911
+ return vitestMocks.held.index;
912
+ }
913
+
914
+ /** Whether Vitest's registry holds any mock: one Map read, for the registry's side channel. */
915
+ const vitestHasMocks = () =>
916
+ (globalThis.__vitest_mocker__?.getMockerRegistry?.()?.registryById?.size ?? 0) > 0;
917
+
918
+ /**
919
+ * Whether `request` from `parent` can reach a mocked file at all, without resolving it:
920
+ * a package name, an absolute path or a relative request into a mocked package, or into project files
921
+ * when one is mocked. R10: an unrelated request costs this.
922
+ */
923
+ function mayReachMock(index, request, parent) {
924
+ if (isBare(request)) return index.packages.has(packageNameOf(request)) || index.projectFiles;
925
+ // An absolute path names its file, so its package is known without resolving it, as
926
+ // React Native's precompiled registry's requires of its helpers are; a relative one
927
+ // stays in its requester's package.
928
+ const pkg = path.isAbsolute(request)
929
+ ? packageOfPath(request)
930
+ : typeof parent?.filename === "string"
931
+ ? owningPackageOfFile(parent.filename)
932
+ : null;
933
+ return pkg === null ? index.projectFiles : index.packages.has(pkg);
934
+ }
935
+
936
+ /** The path a `file:` URL names, or the URL itself when it names none Node accepts. */
937
+ function fileOfUrl(url) {
938
+ try {
939
+ return fileURLToPath(url);
940
+ } catch {
941
+ return url;
942
+ }
943
+ }
944
+
945
+ /** The package under the last `node_modules/` of a path, its own directory included. */
946
+ function packageOfPath(file) {
947
+ const norm = file.replace(/\\/g, "/").replace(/\/+$/, "");
948
+ const at = norm.lastIndexOf("/node_modules/");
949
+ return at === -1 ? null : packageNameOf(norm.slice(at + "/node_modules/".length));
950
+ }
951
+
952
+ /**
953
+ * The Vitest mock for the file Node resolved for this requester, or undefined (R5: by
954
+ * resolved file only). A package name that resolves to a different file of the package
955
+ * a mock is in, which happens when Vite and Node pick different entry files, fails by
956
+ * name: the mock might be meant, and serving either module would be a guess.
957
+ */
958
+ function vitestMockFor(index, request, parent, filename) {
959
+ if (filename === null) return undefined;
960
+ const entry = index.byFile.get(canonical(filename));
961
+ if (entry !== undefined || !isBare(request)) return entry;
962
+ const dir = packageDirOf(filename);
963
+ if (dir === null) return undefined;
964
+ for (const [file, mocked] of index.byFile) {
965
+ if (packageDirOf(file) === dir && mocked.raw === request) {
966
+ throw mockNotSeenByNode(
967
+ request,
968
+ parent,
969
+ `Vite resolves it to ${file} and Node to ${filename}, so the mock cannot be matched`,
970
+ );
971
+ }
972
+ }
973
+ return undefined;
974
+ }
975
+
976
+ /**
977
+ * R3: the module a Vitest mock is, the instance the test's own import gets: a factory's
978
+ * result (Vitest caches it on the entry), an automock's mocked exports, or the module
979
+ * a `__mocks__` redirect evaluated. R9: one that cannot be had synchronously fails by name.
980
+ */
981
+ const FACTORY_NOT_SETTLED =
982
+ "its factory is async and has not settled; import the module in the test first";
983
+ /** Manual-mock entries whose factory returned a promise that has not settled. */
984
+ const settlingFactories = new WeakSet();
985
+
986
+ /**
987
+ * Whether Vitest is building this mock now: running its factory (its id is on the mock
988
+ * context's callstack until the factory settles), or loading an automock's original.
989
+ * Vitest sets the `mock:` node's `mockedExports` to an empty object before that load and
990
+ * fills it, synchronously, after; a node `jest.resetModules()` reset keeps its filled
991
+ * object. A request for the file meanwhile comes from inside the build, the original's
992
+ * own graph, and is the real module, as Vitest's own load of the original is.
993
+ */
994
+ function vitestMockBuilding(entry) {
995
+ const mockId = `mock:${entry.id}`;
996
+ if (globalThis.__vitest_mocker__?.getMockContext?.()?.callstack?.includes?.(mockId)) {
997
+ return true;
998
+ }
999
+ if (entry.type !== "automock" && entry.type !== "autospy") return false;
1000
+ const node = worker()?.evaluatedModules?.getModuleById?.(mockId);
1001
+ return (
1002
+ node?.mockedExports != null &&
1003
+ node.evaluated !== true &&
1004
+ Object.keys(node.mockedExports).length === 0
1005
+ );
1006
+ }
1007
+
1008
+ function vitestMockValue(entry, request, parent) {
1009
+ const value = vitestMockModule(entry, request, parent);
1010
+ return value === NONE ? NONE : requireFacade(value);
1011
+ }
1012
+
1013
+ /**
1014
+ * The module a Vitest mock is, as the test's own import gets it (the factory's result, an
1015
+ * automock's mocked exports, the module a redirect evaluated), or NONE while Vitest is
1016
+ * building it. R9: one that cannot be had synchronously fails by name.
1017
+ */
1018
+ function vitestMockModule(entry, request, parent) {
1019
+ if (vitestMockBuilding(entry)) return NONE;
1020
+ if (entry.type === "manual") {
1021
+ // Vitest caches a factory's settled result only, and wraps every factory in a
1022
+ // synchronous arrow, so whether one is async is known only by calling it. It is
1023
+ // called once: while its promise is pending, a require fails by name without calling
1024
+ // it again; once it settles, Vitest's own handler has cached the result, which the
1025
+ // test's import and every later require share.
1026
+ if (entry.cache === undefined && settlingFactories.has(entry)) {
1027
+ throw mockNotSeenByNode(request, parent, FACTORY_NOT_SETTLED);
1028
+ }
1029
+ const value = entry.resolve();
1030
+ if (typeof value?.then !== "function") return value;
1031
+ settlingFactories.add(entry);
1032
+ value.then(
1033
+ () => settlingFactories.delete(entry),
1034
+ () => settlingFactories.delete(entry),
1035
+ );
1036
+ throw mockNotSeenByNode(request, parent, FACTORY_NOT_SETTLED);
1037
+ }
1038
+ const modules = worker()?.evaluatedModules;
1039
+ if (entry.type === "automock" || entry.type === "autospy") {
1040
+ const node = modules?.getModuleById?.(`mock:${entry.id}`);
1041
+ if (node?.mockedExports != null) return node.mockedExports;
1042
+ } else if (entry.type === "redirect" && typeof entry.redirect === "string") {
1043
+ const node =
1044
+ modules?.getModuleByUrl?.(entry.redirect) ?? modules?.getModuleById?.(entry.redirect);
1045
+ // Evaluated in this file: the hot runtime resets an earlier file's node in place.
1046
+ if (node?.evaluated === true) return node.exports;
1047
+ }
1048
+ throw mockNotSeenByNode(
1049
+ request,
1050
+ parent,
1051
+ `Vitest builds this ${entry.type} module when the test imports it, which it has not yet`,
1052
+ );
1053
+ }
1054
+
1055
+ /**
1056
+ * R7: a `vi.doMock` Vitest has queued but not registered (it registers queued mocks on
1057
+ * the test's next import) of the file this requester resolved. Matched per requester:
1058
+ * the pending specifier is resolved from where it was written.
1059
+ *
1060
+ * Returns true when the file is unmocked for Node already: a jest.* call decided it
1061
+ * (state.decided), jest-compat holds no mock for it, and the last queued action for it
1062
+ * is an unmock (`jest.dontMock`/`doUnmock`'s own). Vitest's registry still holds the
1063
+ * mock that unmock replaces until the next import, so the caller serves the real module,
1064
+ * as Jest does from the call on, instead of that stale mock.
1065
+ */
1066
+ function assertNoPendingMockOf(state, filename, request, parent) {
1067
+ const pending = globalThis.__vitest_mocker__?.constructor?.pendingIds;
1068
+ if (!Array.isArray(pending) || pending.length === 0 || filename === null) return false;
1069
+ const target = canonical(filename);
1070
+ const decided = state.decided.has(target);
1071
+ let last;
1072
+ for (const queued of pending) {
583
1073
  if (
584
- fromProject &&
585
- filename !== null &&
586
- !state.isolation &&
587
- !NODE_MODULES.test(filename) &&
588
- Module._cache[filename] === undefined
1074
+ (queued?.action !== "mock" && queued?.action !== "unmock") ||
1075
+ typeof queued.id !== "string"
589
1076
  ) {
590
- const shared = viteInstanceOf(filename);
591
- if (shared !== NONE) return shared;
1077
+ continue;
592
1078
  }
593
- return origLoad.call(this, request, parent, ...rest);
594
- };
1079
+ const resolved = state.resolveFrom(queued.id, queued.importer);
1080
+ if (resolved === null || canonical(resolved) !== target) continue;
1081
+ if (!decided) {
1082
+ throw mockNotSeenByNode(
1083
+ request,
1084
+ parent,
1085
+ `it was ${queued.action}ed after the test's last import, and Vitest applies that on the next one`,
1086
+ );
1087
+ }
1088
+ last = queued.action;
1089
+ }
1090
+ // A jest.* call decided this file for Node already: its queued action is applied here.
1091
+ return last === "unmock" && !state.entries.has(target);
1092
+ }
1093
+
1094
+ const marks = new WeakMap();
1095
+ let lastMark = 0;
1096
+ /** A number unique to `entry` (a mock registration) for the life of the worker. */
1097
+ function markOf(entry) {
1098
+ let mark = marks.get(entry);
1099
+ if (mark === undefined) marks.set(entry, (mark = ++lastMark));
1100
+ return mark;
1101
+ }
1102
+
1103
+ function mockNotSeenByNode(request, parent, reason) {
1104
+ const from = typeof parent?.filename === "string" ? parent.filename : "Node";
1105
+ const error = new VitestNativeError(
1106
+ "MOCK_NOT_SEEN_BY_NODE",
1107
+ `the vi.mock of '${request}' cannot be served to ${from}'s require: ${reason}. ` +
1108
+ `Import the mocked module in the test before the code that requires it, or give ` +
1109
+ `the mock a synchronous factory.`,
1110
+ );
1111
+ // Also said out loud, once: a package that probes an optional dependency with
1112
+ // `try { require(x) } catch {}` would otherwise turn this into "not installed".
1113
+ if (!reportedNotSeen.has(error.message)) {
1114
+ reportedNotSeen.add(error.message);
1115
+ console.warn(error.message);
1116
+ }
1117
+ return error;
1118
+ }
1119
+ const reportedNotSeen = new Set();
1120
+
1121
+ /**
1122
+ * Whether a relative require that landed on `filename`, mocked for a whole package
1123
+ * (`jest.mock('react-native-reanimated', …)`), is the package reaching its own entry as
1124
+ * Metro resolves it: its `react-native` field. The engine registers the mock for that
1125
+ * file; Jest registers it for `main`, so under Jest such a require gets the real module
1126
+ * (`react-native-reanimated/mock` imports `./index`, which the factory would otherwise
1127
+ * require itself through). A package whose mocked file is its `main` gets the mock, as
1128
+ * under Jest.
1129
+ */
1130
+ function isPackageOwnRelativeLoad(entry, request, filename, parentFile) {
1131
+ if (typeof request !== "string" || !request.startsWith(".")) return false;
1132
+ if (typeof entry.spec !== "string" || !isWholePackageRequest(entry.spec)) return false;
1133
+ if (typeof parentFile !== "string" || typeof filename !== "string") return false;
1134
+ const rnEntry = resolvePackageMainField(
1135
+ entry.spec,
1136
+ path.dirname(parentFile),
1137
+ config.platform,
1138
+ sourceExts.length > 0 ? sourceExts : undefined,
1139
+ );
1140
+ return rnEntry !== null && canonical(rnEntry) === canonical(filename);
1141
+ }
1142
+
1143
+ function installLoadHook(state) {
1144
+ // The outermost load step (LOAD_STEPS): a per-file mock beats a preset and the registry.
1145
+ nodeDispatch().load.add(
1146
+ "mocks",
1147
+ (next) =>
1148
+ function (request, parent, ...rest) {
1149
+ // A project file is what a test or a Node-loaded project module requires. Only
1150
+ // those requests can share Vite's instances; any request can hit a mock, but
1151
+ // only when there is one.
1152
+ const fromProject =
1153
+ typeof parent?.filename === "string" &&
1154
+ !NODE_MODULES.test(parent.filename) &&
1155
+ state.isResettable(parent.filename);
1156
+ if (Module.isBuiltin(request)) return next(request, parent, ...rest);
1157
+ const viMocks = nodeMocks && !madeByVitest(parent?.filename) ? vitestMocks() : null;
1158
+ const pendingMocks = nodeMocks && !madeByVitest(parent?.filename) && pendingCount() > 0;
1159
+ // A jest.mock this request can reach (mayIntercept), or a vi.mock: otherwise the
1160
+ // request is Node's, and only a project file goes further.
1161
+ const mockable = state.mayIntercept(request, parent);
1162
+ if (!fromProject && !mockable && viMocks === null && !pendingMocks) {
1163
+ return next(request, parent, ...rest);
1164
+ }
1165
+ // A jest.mock (this registry) is matched first, then a vi.mock (Vitest's). R8:
1166
+ // jest.requireActual's own load is never a vi.mock either; it takes the path
1167
+ // below, whose lookup gives it the real module.
1168
+ const actualLoad =
1169
+ state.bypass !== null &&
1170
+ state.bypass === (state.resolve(request, parent) ?? `\0${request}`);
1171
+ // No jest.mock this request can reach (an empty registry, or one holding only
1172
+ // other packages' registrations, such as a library's own Jest setup): a vi.mock
1173
+ // decides first.
1174
+ if (!mockable && !actualLoad && (viMocks !== null || pendingMocks)) {
1175
+ const served = serveVitestMock(viMocks, pendingMocks, request, parent, () =>
1176
+ state.resolve(request, parent),
1177
+ );
1178
+ if (served !== NONE) return served;
1179
+ // R10: a request no mock matched is Node's, as it was with no mocks at all.
1180
+ if (!fromProject) return next(request, parent, ...rest);
1181
+ }
1182
+ // With no mock it can reach, only a project file can be served from Vite. For a bare specifier,
1183
+ // Node's own answer decides: a file under node_modules goes to Node's loader as is;
1184
+ // anything else (a workspace link to source, a package's self-reference, an alias the
1185
+ // hooks apply) is resolved as below, reusing that answer.
1186
+ if (!mockable && isBare(request)) {
1187
+ const resolved = nodeResolution(request, parent);
1188
+ if (resolved !== null && NODE_MODULES.test(resolved)) {
1189
+ state.stats.toNode++;
1190
+ return next(request, parent, ...rest);
1191
+ }
1192
+ if (resolved !== null) state.resolutions.set(`${parent.filename}\0${request}`, resolved);
1193
+ }
1194
+ const filename = state.resolve(request, parent);
1195
+ const entry = state.lookup(filename, request);
1196
+ // R8: requireActual's load is the real module, past a vi.mock too; it may still
1197
+ // share Vite's instance of a project file below, as before.
1198
+ const bypassed = entry === BYPASSED || isExecutingManualMock(entry);
1199
+ // A package reaching its own entry relatively, mocked for the whole package, is
1200
+ // the real module, as under Jest (isPackageOwnRelativeLoad): no mock serves it.
1201
+ const ownRelative =
1202
+ entry !== undefined &&
1203
+ !bypassed &&
1204
+ isPackageOwnRelativeLoad(entry, request, filename, parent?.filename);
1205
+ if (entry !== undefined && !bypassed && !ownRelative) return state.valueOf(entry);
1206
+ if (!bypassed && !ownRelative && !state.isEmpty() && (viMocks !== null || pendingMocks)) {
1207
+ const served = serveVitestMock(viMocks, pendingMocks, request, parent, () => filename);
1208
+ if (served !== NONE) return served;
1209
+ }
1210
+ // A module Node already holds stays the one `require` returns: switching a later
1211
+ // require to Vite's copy would change its identity mid-file.
1212
+ if (
1213
+ fromProject &&
1214
+ filename !== null &&
1215
+ !state.isolation &&
1216
+ !NODE_MODULES.test(filename) &&
1217
+ Module._cache[filename] === undefined
1218
+ ) {
1219
+ // experimental.ownershipModel 'resolution': a file Vite owns is Vite's instance in
1220
+ // either load order, evaluated now if Vite has not (native/bridge.mjs). Nothing is
1221
+ // put in Module._cache: the next require asks Vite's map again, as this one did. It
1222
+ // answers first: it also refuses a module Vite holds that it must not serve (one
1223
+ // whose evaluation threw, or one still being evaluated).
1224
+ if (bridging) {
1225
+ const bridged = bridgedInstanceOf(filename, parent);
1226
+ if (bridged !== NONE) return bridged;
1227
+ }
1228
+ const shared = viteInstanceOf(filename);
1229
+ if (shared !== NONE) return shared;
1230
+ }
1231
+ return next(request, parent, ...rest);
1232
+ },
1233
+ );
595
1234
 
596
1235
  // The precompiled React Native registry requires its own modules by id, past
597
1236
  // Module._load (see registry.mjs). Jest serves `jest.mock('react-native/Libraries/
@@ -599,11 +1238,140 @@ function installLoadHook(state) {
599
1238
  // AppState')`, so the registry asks here first. Undefined unless a mock exists.
600
1239
  Object.defineProperty(globalThis, "__vitest_native_node_mock_for", {
601
1240
  configurable: true,
602
- get: () => (state.entries.size === 0 ? undefined : nodeMockForRegistry),
1241
+ get: () =>
1242
+ state.entries.size === 0 && (!nodeMocks || (!vitestHasMocks() && pendingCount() === 0))
1243
+ ? undefined
1244
+ : nodeMockForRegistry,
603
1245
  });
604
- function nodeMockForRegistry(filename) {
1246
+ /**
1247
+ * `request` and `parentFile`, when the registry has them, are the require as written
1248
+ * and the file it is in, for isPackageOwnRelativeLoad, as through Node's loader.
1249
+ */
1250
+ function nodeMockForRegistry(filename, request, parentFile) {
605
1251
  const entry = state.lookup(canonical(filename), filename);
606
- return entry === undefined ? NONE : state.valueOf(entry);
1252
+ if (entry === BYPASSED || isExecutingManualMock(entry)) return NONE;
1253
+ if (entry !== undefined) {
1254
+ // The package's own relative load of its entry is the real module (as above).
1255
+ return isPackageOwnRelativeLoad(entry, request, filename, parentFile)
1256
+ ? NONE
1257
+ : state.valueOf(entry);
1258
+ }
1259
+ if (!nodeMocks) return NONE;
1260
+ if (pendingCount() > 0 && assertNoPendingMockOf(state, filename, filename, null)) return NONE;
1261
+ const mocked = vitestMocks()?.byFile.get(canonical(filename));
1262
+ return mocked === undefined ? NONE : vitestMockValue(mocked, filename, null);
607
1263
  }
608
1264
  nodeMockForRegistry.NONE = NONE;
1265
+
1266
+ // The mock seam of the require bridge (experimental.ownershipModel 'resolution',
1267
+ // native/bridge.mjs), which evaluates a Vite-owned module synchronously in Vite's place:
1268
+ // each import it makes asks here first, so a mocked dependency is the instance Vitest's
1269
+ // own import of it gets (ADR-0007 decision 4; the A3 readiness condition 1).
1270
+ const mocks = nodeDispatch().channel("mocks");
1271
+ mocks.NONE = NONE;
1272
+ /**
1273
+ * The id Vitest's registry keys a module by, from the forms the bridge holds it in: an
1274
+ * absolute path (a fetch result's id, an external's target), a `file:` URL (an external's
1275
+ * target on Windows), or Vite's `/@fs/` URL for a file outside the root.
1276
+ */
1277
+ const viteIdOf = (id) => {
1278
+ if (typeof id !== "string") return id;
1279
+ if (id.startsWith("file:")) return fileOfUrl(id).replace(/\\/g, "/");
1280
+ if (id.startsWith("/@fs/")) {
1281
+ const rest = id.slice("/@fs".length);
1282
+ return /^\/[A-Za-z]:\//.test(rest) ? rest.slice(1) : rest;
1283
+ }
1284
+ return path.isAbsolute(id) ? id.replace(/\\/g, "/") : id;
1285
+ };
1286
+ /** Whether Node's own `require` and `import` are served Vitest's mocks (nodeMocks). */
1287
+ mocks.servesNode = nodeMocks;
1288
+ /**
1289
+ * The mock for an import of `id` (Vite's id for it: its file, or a virtual id) made by
1290
+ * the module at `importerFile`, as the test's own import of it gets it; NONE when none
1291
+ * applies; or a `MOCK_NOT_SEEN_BY_NODE` failure naming the importer when one applies
1292
+ * but cannot be had synchronously (an async factory that has not settled, an automock
1293
+ * or `__mocks__` module Vitest has not built, a `vi.doMock`/`vi.doUnmock` of the file
1294
+ * not applied yet). A Vite module's imports are Vite's, so this holds with nodeMocks
1295
+ * off too. A jest.mock is matched first, and jest.requireActual's module stays actual,
1296
+ * as for Node's require.
1297
+ */
1298
+ /**
1299
+ * A jest.mock as an import gets it, not as `require` does: Vitest's `mock:<id>` module
1300
+ * once the test has imported it (jestMockTransform's factory hands Vitest the value
1301
+ * through Jest's CommonJS interop, setup.mjs), else that interop of the settled value,
1302
+ * so `import X from` reads the whole module of a factory returning a function or
1303
+ * named exports only. A factory that has not settled fails by name.
1304
+ */
1305
+ const jestMockForImport = (entry, id, parent) => {
1306
+ const imported = worker()?.evaluatedModules?.getModuleById?.(`mock:${id}`)?.exports;
1307
+ if (imported != null) return imported;
1308
+ // The bridge evaluates synchronously, so it takes the factory as Node's require does
1309
+ // (valueOf): jestMockTransform's original, synchronous one, whose jest.requireActual
1310
+ // is synchronous, as under Jest. The value is memoized, so Vite's import of the module
1311
+ // later gets the same object. Only a factory the author wrote async, or one Vite has
1312
+ // already started, has no synchronous value yet.
1313
+ const value = entry.has ? entry.value : (entry.pending ?? state.valueOf(entry));
1314
+ if (Object.prototype.toString.call(value) === "[object Promise]") {
1315
+ throw mockNotSeenByNode(id, parent, FACTORY_NOT_SETTLED);
1316
+ }
1317
+ return jestMockInterop(value);
1318
+ };
1319
+ mocks.forImport = (rawId, importerFile) => {
1320
+ const parent = { filename: importerFile };
1321
+ const id = viteIdOf(rawId);
1322
+ const bare = typeof id === "string" ? id.replace(/[?#].*$/, "") : null;
1323
+ const file = bare !== null && path.isAbsolute(bare) ? bare : null;
1324
+ if (file !== null) {
1325
+ const entry = state.lookup(canonical(file), file);
1326
+ if (entry === BYPASSED) return NONE;
1327
+ if (entry !== undefined) return jestMockForImport(entry, id, parent);
1328
+ if (pendingCount() > 0 && assertNoPendingMockOf(state, file, id, parent)) return NONE;
1329
+ }
1330
+ const byId = globalThis.__vitest_mocker__?.getMockerRegistry?.()?.registryById;
1331
+ // Keyed by Vite's id, as Vitest's registry is: the bridge has the id Vite resolved.
1332
+ const entry = byId instanceof Map ? byId.get(id) : undefined;
1333
+ if (entry === undefined) return NONE;
1334
+ // Vitest's import of a factory mock gets the module it keeps at `mock:<id>` (a proxy
1335
+ // that names a missing export); once the test has imported it, that one.
1336
+ const imported = worker()?.evaluatedModules?.getModuleById?.(`mock:${entry.id}`)?.exports;
1337
+ if (entry.type === "manual" && imported != null && !vitestMockBuilding(entry)) return imported;
1338
+ return vitestMockModule(entry, id, parent);
1339
+ };
1340
+
1341
+ // experimental.nodeMocks, for Node's ESM loader (loader.mjs), which decides at resolve,
1342
+ // where the importer is known (R1), and gives a mocked import its own URL (R2).
1343
+ /** Whether `request` from `parentFile` can reach a mock at all, without resolving it. */
1344
+ nodeMockForRegistry.mayReach = (request, parentFile) => {
1345
+ if (!nodeMocks) return false;
1346
+ if (request.startsWith("file:")) request = fileOfUrl(request);
1347
+ if (state.entries.size > 0 || pendingCount() > 0) return true;
1348
+ const index = vitestMocks();
1349
+ return index !== null && mayReachMock(index, request, { filename: parentFile });
1350
+ };
1351
+ /**
1352
+ * A mark for the mock that applies to `file`, as `request` from `parentFile` resolved
1353
+ * it, or null: the same mark for the same registration, a new one for each new one.
1354
+ */
1355
+ nodeMockForRegistry.markFor = (file, request, parentFile) => {
1356
+ if (!nodeMocks) return null;
1357
+ const parent = { filename: parentFile };
1358
+ const jestEntry = state.entries.get(canonical(file));
1359
+ if (jestEntry !== undefined) return markOf(jestEntry);
1360
+ if (pendingCount() > 0 && assertNoPendingMockOf(state, file, request, parent)) return null;
1361
+ const index = vitestMocks();
1362
+ const entry = index === null ? undefined : vitestMockFor(index, request, parent, file);
1363
+ // A mark is a cache entry for good: none for a mock Vitest is still building.
1364
+ return entry === undefined || vitestMockBuilding(entry) ? null : markOf(entry);
1365
+ };
1366
+
1367
+ // A Vitest mock for this request, or NONE: the pending check (R7) and the match (R5).
1368
+ function serveVitestMock(index, pending, request, parent, resolve) {
1369
+ const reachable = index !== null && mayReachMock(index, request, parent);
1370
+ if (!reachable && !pending) return NONE;
1371
+ const filename = resolve();
1372
+ if (pending && assertNoPendingMockOf(state, filename, request, parent)) return NONE;
1373
+ if (!reachable) return NONE;
1374
+ const entry = vitestMockFor(index, request, parent, filename);
1375
+ return entry === undefined ? NONE : vitestMockValue(entry, request, parent);
1376
+ }
609
1377
  }