@provino/mock 0.0.0-stage → 0.1.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2312 @@
1
+ import { builtinModules } from "node:module";
2
+ import { readdirSync, statSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { AsyncLocalStorage } from "node:async_hooks";
5
+
6
+ // src/errors.ts
7
+ /**
8
+ * An `Error` from the mock engine; its `name` stays `Error`.
9
+ * @public
10
+ */
11
+ var MockError = class extends Error {
12
+ code;
13
+ constructor(code, message) {
14
+ super(message);
15
+ this.code = code;
16
+ }
17
+ };
18
+ /**
19
+ * A `TypeError` from the mock engine; its `name` stays `TypeError`.
20
+ * @public
21
+ */
22
+ var MockTypeError = class extends TypeError {
23
+ code;
24
+ constructor(code, message, options) {
25
+ super(message, options);
26
+ this.code = code;
27
+ }
28
+ };
29
+
30
+ // src/internal/args-equal.ts
31
+ const toStringTag = (value) => Object.prototype.toString.call(value);
32
+ function isAsymmetric(value) {
33
+ if (value === null || value === void 0) return false;
34
+ const match = value.asymmetricMatch;
35
+ return toStringTag(match) === "[object Function]";
36
+ }
37
+ /** Own enumerable string keys, then own enumerable symbols. */
38
+ function ownKeys(value) {
39
+ const symbols = Object.getOwnPropertySymbols(value).filter((symbol) => Object.getOwnPropertyDescriptor(value, symbol)?.enumerable === true);
40
+ return [...Object.keys(value), ...symbols];
41
+ }
42
+ function isIterable(value) {
43
+ return Boolean(value[Symbol.iterator]);
44
+ }
45
+ function isNative(fn) {
46
+ return typeof fn === "function" && Function.prototype.toString.call(fn).includes("[native code]");
47
+ }
48
+ /** Constructors differ: the same native class from another realm still counts as the same. */
49
+ function sameConstructor(a, b) {
50
+ if (a.constructor === b.constructor) return true;
51
+ if (a.constructor === null || a.constructor === void 0) return false;
52
+ if (b.constructor === null || b.constructor === void 0) return false;
53
+ return a.constructor.name === b.constructor.name && isNative(a.constructor) && isNative(b.constructor);
54
+ }
55
+ function setsEqual(a, b, iterables) {
56
+ for (const value of a) {
57
+ if (b.has(value)) continue;
58
+ let found = false;
59
+ for (const other of b) if (eq(value, other, {
60
+ a: [],
61
+ b: []
62
+ }, iterables)) found = true;
63
+ if (!found) return false;
64
+ }
65
+ return true;
66
+ }
67
+ function mapsEqual(a, b, iterables) {
68
+ for (const [key, value] of a) {
69
+ if (b.has(key) && eq(value, b.get(key), {
70
+ a: [],
71
+ b: []
72
+ }, iterables)) continue;
73
+ let found = false;
74
+ for (const [otherKey, otherValue] of b) if (eq(key, otherKey, {
75
+ a: [],
76
+ b: []
77
+ }, iterables) && eq(value, otherValue, {
78
+ a: [],
79
+ b: []
80
+ }, iterables)) found = true;
81
+ if (!found) return false;
82
+ }
83
+ return true;
84
+ }
85
+ /** The own properties an iterable has beside what it iterates over. */
86
+ function extraEntries(value) {
87
+ return [...Object.getOwnPropertySymbols(value).filter((symbol) => symbol !== Symbol.iterator).map((symbol) => [symbol, value[symbol]]), ...Object.entries(value)];
88
+ }
89
+ /** `iterableEquality`: `undefined` when it has no opinion, so the object comparison decides. */
90
+ function iterablesEqual(a, b, stacks) {
91
+ if (Array.isArray(a) || Array.isArray(b) || ArrayBuffer.isView(a) || ArrayBuffer.isView(b)) return;
92
+ if (!isIterable(a) || !isIterable(b)) return void 0;
93
+ if (!sameConstructor(a, b)) return false;
94
+ for (let index = stacks.a.length - 1; index >= 0; index--) if (stacks.a[index] === a) return stacks.b[index] === b;
95
+ const inner = {
96
+ a: [...stacks.a, a],
97
+ b: [...stacks.b, b]
98
+ };
99
+ const sizeOfA = a.size;
100
+ if (sizeOfA !== void 0) {
101
+ if (sizeOfA !== b.size) return false;
102
+ if (toStringTag(a) === "[object Set]") return setsEqual(a, b, inner);
103
+ if (toStringTag(a) === "[object Map]") return mapsEqual(a, b, inner);
104
+ }
105
+ let left;
106
+ let right;
107
+ try {
108
+ left = a[Symbol.iterator]();
109
+ right = b[Symbol.iterator]();
110
+ } catch {
111
+ return;
112
+ }
113
+ for (let step = left.next(); !step.done; step = left.next()) {
114
+ const other = right.next();
115
+ if (other.done || !eq(step.value, other.value, {
116
+ a: [],
117
+ b: []
118
+ }, inner)) return false;
119
+ }
120
+ if (!right.next().done) return false;
121
+ return eq(extraEntries(a), extraEntries(b), {
122
+ a: [],
123
+ b: []
124
+ }, null);
125
+ }
126
+ function isDomNode(value) {
127
+ const node = value;
128
+ return typeof node.nodeType === "number" && typeof node.nodeName === "string" && typeof node.isEqualNode === "function";
129
+ }
130
+ function objectsEqual(a, b, stacks, iterables) {
131
+ if (isDomNode(a) && isDomNode(b)) return a.isEqualNode(b);
132
+ for (let index = stacks.a.length - 1; index >= 0; index--) {
133
+ if (stacks.a[index] === a) return stacks.b[index] === b;
134
+ if (stacks.b[index] === b) return false;
135
+ }
136
+ stacks.a.push(a);
137
+ stacks.b.push(b);
138
+ const left = a;
139
+ const right = b;
140
+ const aKeys = ownKeys(a);
141
+ const bKeys = ownKeys(b);
142
+ const countsWhenMissing = (value) => value === void 0 || isAsymmetric(value);
143
+ for (const key of [...bKeys]) if (countsWhenMissing(right[key]) && !Object.hasOwn(a, key)) aKeys.push(key);
144
+ for (const key of [...aKeys]) if (countsWhenMissing(left[key]) && !Object.hasOwn(b, key)) bKeys.push(key);
145
+ if (aKeys.length !== bKeys.length) return false;
146
+ for (let index = aKeys.length - 1; index >= 0; index--) {
147
+ const key = aKeys[index];
148
+ if (!Object.hasOwn(b, key) && !countsWhenMissing(left[key])) return false;
149
+ if (!eq(left[key], right[key], stacks, iterables)) return false;
150
+ }
151
+ stacks.a.pop();
152
+ stacks.b.pop();
153
+ return true;
154
+ }
155
+ function eq(a, b, stacks, iterables) {
156
+ const asymmetricA = isAsymmetric(a);
157
+ const asymmetricB = isAsymmetric(b);
158
+ if (asymmetricA && !asymmetricB) return a.asymmetricMatch(b);
159
+ if (asymmetricB && !asymmetricA) return b.asymmetricMatch(a);
160
+ if (iterables !== null && typeof a === "object" && typeof b === "object" && a && b) {
161
+ const result = iterablesEqual(a, b, iterables);
162
+ if (result !== void 0) return result;
163
+ }
164
+ if (a instanceof Error && b instanceof Error) return a.message === b.message;
165
+ if (Object.is(a, b)) return true;
166
+ if (a === null || b === null) return false;
167
+ const tag = toStringTag(a);
168
+ if (tag !== toStringTag(b)) return false;
169
+ switch (tag) {
170
+ case "[object Boolean]":
171
+ case "[object String]":
172
+ case "[object Number]":
173
+ if (typeof a !== "object" || typeof b !== "object") return false;
174
+ return Object.is(a.valueOf(), b.valueOf());
175
+ case "[object Date]": return +a === +b;
176
+ case "[object RegExp]": return a.source === b.source && a.flags === b.flags;
177
+ case "[object URL]": return a.href === b.href;
178
+ }
179
+ if (typeof a !== "object" || typeof b !== "object") return false;
180
+ return objectsEqual(a, b, stacks, iterables);
181
+ }
182
+ /** Whether two call-argument values are equal, as `equals(a, b, [iterableEquality])` says. */
183
+ function argsEqual(a, b) {
184
+ return eq(a, b, {
185
+ a: [],
186
+ b: []
187
+ }, {
188
+ a: [],
189
+ b: []
190
+ });
191
+ }
192
+
193
+ // src/internal/guards.ts
194
+ /** An object or a function (anything a property can be read from, except `null`). */
195
+ function isObjectLike(value) {
196
+ return value !== null && (typeof value === "object" || typeof value === "function");
197
+ }
198
+ /** Whether `value` has a callable `then`. */
199
+ function isThenable(value) {
200
+ return isObjectLike(value) && typeof value.then === "function";
201
+ }
202
+
203
+ // src/internal/messages.ts
204
+ const NEUTRAL_MESSAGES = {
205
+ "spy-primitive": "Cannot spy on a primitive value; {type} given",
206
+ "spy-no-key": "No property name supplied",
207
+ "spy-missing": "Property `{key}` does not exist in the provided object",
208
+ "spy-not-a-function": "Cannot spy on `{key}` because it is not a function; {type} given",
209
+ "spy-not-a-function-primitive": "Cannot spy on `{key}` because it is not a function; {type} given. To mock a property, use replaceProperty",
210
+ "spy-not-configurable": "Property `{key}` is not declared configurable",
211
+ "spy-no-access-type": "Property `{key}` does not have access type {type}",
212
+ "spy-nullish": "Cannot spy on nothing: the first argument must be defined",
213
+ "spy-define-primitive": "Cannot spy on a primitive value",
214
+ "spy-define-missing": "The property \"{key}\" is not defined on the {type}",
215
+ "spy-define-not-a-function": "Can only spy on a function. Received {type}",
216
+ "spy-namespace": "Cannot spy on export \"{key}\". A module namespace is not configurable in ESM",
217
+ "replace-primitive": "Cannot replace a property of a primitive value; {type} given",
218
+ "replace-no-key": "No property name supplied",
219
+ "replace-missing": "Property `{key}` does not exist in the provided object",
220
+ "replace-not-configurable": "Property `{key}` is not declared configurable",
221
+ "replace-getter": "Cannot replace `{key}` because it has a getter. Spy on its getter instead",
222
+ "replace-setter": "Cannot replace `{key}` because it has a setter. Spy on its setter instead",
223
+ "replace-function": "Cannot replace `{key}` because it is a function. Spy on it instead",
224
+ "new-shorthand": "Cannot use `{name}` when called with `new`. Use `mockImplementation` with a `class` instead"
225
+ };
226
+ /** Fills a code's text from the policy, or from the neutral table. */
227
+ function messageFor(policy, code, values) {
228
+ return fill(policy.messages[code] ?? NEUTRAL_MESSAGES[code], values);
229
+ }
230
+ /** Replaces `{word}` with its value; a `{word}` with no value stays. */
231
+ function fill(text, values) {
232
+ return text.replace(/\{(\w+)\}/g, (whole, word) => values[word] ?? whole);
233
+ }
234
+
235
+ // src/mock-fn.ts
236
+ /**
237
+ * Marks a mock made by this engine. Every mock also has `_isMockFunction: true`, for the ecosystem
238
+ * and for `isMockFunction`.
239
+ * @public
240
+ */
241
+ const MOCK_BRAND = Symbol.for("@provino/mock.brand");
242
+ /**
243
+ * The key of a mock's slot: own, enumerable, and never read by anything outside this file. A symbol
244
+ * rather than a `#private` field, because a `Proxy` around a mock must keep working.
245
+ */
246
+ const SLOT = Symbol("@provino/mock.slot");
247
+ function noop() {}
248
+ const reflectApply = Reflect.apply;
249
+ const functionBind = Function.prototype.bind;
250
+ /**
251
+ * `lastCall` as an own enumerable getter, under `lastCallKey: 'always'`. One shared descriptor, as
252
+ * a `get` in the object literal costs about 330 ns more per mock (`local`).
253
+ */
254
+ const LAST_CALL_GETTER = Object.freeze({
255
+ configurable: true,
256
+ enumerable: true,
257
+ get() {
258
+ return this.calls.at(-1);
259
+ }
260
+ });
261
+ function freshState(policy) {
262
+ const state = policy.settledResults ? {
263
+ calls: [],
264
+ contexts: [],
265
+ instances: [],
266
+ invocationCallOrder: [],
267
+ settledResults: [],
268
+ results: []
269
+ } : {
270
+ calls: [],
271
+ contexts: [],
272
+ instances: [],
273
+ invocationCallOrder: [],
274
+ results: []
275
+ };
276
+ if (policy.lastCallKey === "always") Object.defineProperty(state, "lastCall", LAST_CALL_GETTER);
277
+ return state;
278
+ }
279
+ var MockSlot = class {
280
+ policy;
281
+ registry;
282
+ layout;
283
+ fn = null;
284
+ /** Falsy once the state object is replaced by `fn.mock = undefined`, as jest-mock's check is. */
285
+ state = null;
286
+ /**
287
+ * The persistent implementation. `undefined` is "none", as in jest-mock; a `null` the user set is
288
+ * kept apart from it, which `whenCalledWith`'s dispatcher can tell (`mockImpl !== undefined`).
289
+ */
290
+ impl = void 0;
291
+ /** The `mockImplementationOnce` queue; an entry can be a falsy value the caller passed. */
292
+ onces = null;
293
+ /** What a call runs with no implementation: a spied function or `options.fallback`. */
294
+ fallback = null;
295
+ /** What it was built from: what `mockReset` returns to, and what `mockRestore` runs. */
296
+ options = null;
297
+ name = null;
298
+ when = null;
299
+ chained = false;
300
+ stateDirty = false;
301
+ configDirty = false;
302
+ ref = null;
303
+ /** The methods read so far, each bound to this mock. */
304
+ bound = null;
305
+ /** The last `registry.resets` generation this mock saw. */
306
+ seenResets;
307
+ /** Bumped by every `resetMock`, so a restore queued before a reset can tell it is stale. */
308
+ epoch = 0;
309
+ constructor(policy, registry, layout) {
310
+ this.policy = policy;
311
+ this.registry = registry;
312
+ this.layout = layout;
313
+ this.seenResets = registry.resets;
314
+ }
315
+ /** A `resetAll` this mock wasn't in a dirty set for. See the top of the file. */
316
+ catchUpOnResets() {
317
+ if (this.seenResets === this.registry.resets) return;
318
+ this.seenResets = this.registry.resets;
319
+ if (this.policy.resetTo === "empty") this.dropImplementation();
320
+ }
321
+ /** `resetTo: 'empty'`: nothing is left but what the options built the mock with as a fallback. */
322
+ dropImplementation() {
323
+ this.impl = void 0;
324
+ this.fallback = this.options?.fallback ?? null;
325
+ }
326
+ enterStateDirty() {
327
+ if (this.stateDirty) return;
328
+ this.catchUpOnResets();
329
+ this.registry.markStateDirty(this);
330
+ }
331
+ touchConfig() {
332
+ if (this.configDirty) return;
333
+ this.catchUpOnResets();
334
+ this.registry.markConfigDirty(this);
335
+ }
336
+ /** `fn.mock`, read. */
337
+ readState() {
338
+ if (this.policy.clearReplacesStateObject) this.enterStateDirty();
339
+ return this.currentState();
340
+ }
341
+ currentState() {
342
+ let state = this.state;
343
+ if (!state) {
344
+ state = freshState(this.policy);
345
+ this.state = state;
346
+ }
347
+ if (this.policy.lastCallKey === "after-first-call" && state.calls.length > 0) state.lastCall = state.calls.at(-1);
348
+ return state;
349
+ }
350
+ clearState() {
351
+ if (this.policy.clearReplacesStateObject) {
352
+ this.state = null;
353
+ return;
354
+ }
355
+ const state = this.state;
356
+ if (!state) return;
357
+ state.calls = [];
358
+ state.contexts = [];
359
+ state.instances = [];
360
+ state.invocationCallOrder = [];
361
+ state.results = [];
362
+ if (this.policy.settledResults) state.settledResults = [];
363
+ }
364
+ resetMock() {
365
+ this.seenResets = this.registry.resets;
366
+ this.epoch++;
367
+ this.clearState();
368
+ const when = this.when;
369
+ if (when !== null) {
370
+ for (const branch of when.branches) branch.subMock[SLOT].resetMock();
371
+ this.when = null;
372
+ }
373
+ this.onces = null;
374
+ this.name = null;
375
+ if (this.policy.resetTo === "empty") this.dropImplementation();
376
+ else this.impl = this.options?.impl;
377
+ if (this.layout.chain) this.syncPrototype(this.impl ?? this.fallback);
378
+ }
379
+ /** `mockRestore` and `[Symbol.dispose]`: a reset, then whatever put the original back. */
380
+ restore() {
381
+ this.resetMock();
382
+ this.options?.restore?.();
383
+ }
384
+ setImpl(impl) {
385
+ this.touchConfig();
386
+ const when = this.when;
387
+ if (when !== null && this.impl === when.dispatcher) when.fallback = impl ?? null;
388
+ else this.impl = impl;
389
+ if (this.layout.chain) this.syncPrototype(this.nextImpl());
390
+ }
391
+ addOnce(impl) {
392
+ this.touchConfig();
393
+ if (this.onces === null) this.onces = [impl];
394
+ else this.onces.push(impl);
395
+ if (this.layout.chain) this.syncPrototype(this.nextImpl());
396
+ }
397
+ /** What the next call runs, without consuming it. */
398
+ nextImpl() {
399
+ return this.onces?.[0] ?? this.impl ?? this.fallback;
400
+ }
401
+ /**
402
+ * Keeps `fn.prototype`'s parent on the prototype of what the next construction runs, so instances
403
+ * inherit its methods (`classMockPrototype: 'chain-to-impl'`, @vitest/spy's
404
+ * `reparentMockPrototype`). An implementation with no prototype, such as an arrow, leaves
405
+ * `fn.prototype` unallocated.
406
+ */
407
+ syncPrototype(next) {
408
+ const parent = next?.prototype ?? null;
409
+ if (parent === null && !this.chained) return;
410
+ const own = this.fn.prototype;
411
+ if (own === null || own === void 0) return;
412
+ const target = parent ?? Object.prototype;
413
+ if (own !== target && Object.getPrototypeOf(own) !== target) Object.setPrototypeOf(own, target);
414
+ this.chained = parent !== null;
415
+ }
416
+ /** One call of the mock. */
417
+ invoke(self, args, newTarget) {
418
+ this.enterStateDirty();
419
+ const policy = this.policy;
420
+ const constructing = newTarget !== void 0 && policy.newCall === "construct";
421
+ const context = constructing ? void 0 : self;
422
+ const result = {
423
+ type: "incomplete",
424
+ value: void 0
425
+ };
426
+ let settled = null;
427
+ if (policy.settledResults) settled = {
428
+ type: "incomplete",
429
+ value: void 0
430
+ };
431
+ const order = this.registry.nextInvocationOrder();
432
+ let state = this.state;
433
+ let instanceIndex = 0;
434
+ let contextIndex = 0;
435
+ if (!state && !policy.settledResults && policy.lastCallKey !== "always") {
436
+ state = {
437
+ calls: [args],
438
+ contexts: [context],
439
+ instances: [context],
440
+ invocationCallOrder: [order],
441
+ results: [result]
442
+ };
443
+ this.state = state;
444
+ } else {
445
+ state = this.currentState();
446
+ state.calls.push(args);
447
+ instanceIndex = state.instances.push(context) - 1;
448
+ contextIndex = state.contexts.push(context) - 1;
449
+ state.results.push(result);
450
+ if (settled !== null) state.settledResults?.push(settled);
451
+ state.invocationCallOrder.push(order);
452
+ }
453
+ const onces = this.onces;
454
+ let impl;
455
+ if (onces !== null && onces.length > 0) {
456
+ const queued = onces.shift();
457
+ if (queued) impl = queued;
458
+ else if (newTarget !== void 0) impl = null;
459
+ else impl = (queued === void 0 ? this.impl : null) || this.fallback;
460
+ } else impl = this.impl || this.fallback;
461
+ let value;
462
+ try {
463
+ if (constructing) {
464
+ if (this.layout.chain) this.syncPrototype(impl);
465
+ value = Reflect.construct(impl || noop, args, newTarget);
466
+ state.contexts[contextIndex] = value;
467
+ state.instances[instanceIndex] = value;
468
+ } else if (impl) value = impl.apply(self, args);
469
+ } catch (error) {
470
+ finish(result, "throw", error);
471
+ if (settled !== null) finish(settled, "rejected", error);
472
+ if (constructing) this.warnIfNotConstructor(error);
473
+ throw error;
474
+ }
475
+ finish(result, "return", value);
476
+ if (settled !== null) settle(settled, value);
477
+ return value;
478
+ }
479
+ warnIfNotConstructor(error) {
480
+ const text = this.policy.messages["new-not-a-constructor"];
481
+ if (text === void 0) return;
482
+ if (error instanceof TypeError && error.message.includes("is not a constructor")) console.warn(fill(text, { name: this.mockName() }));
483
+ }
484
+ mockName() {
485
+ if (this.name) return this.name;
486
+ if (this.options?.spy === true && this.policy.spyNameFromMethod) return this.fn.name || this.policy.defaultName;
487
+ return this.policy.defaultName;
488
+ }
489
+ implementation() {
490
+ this.catchUpOnResets();
491
+ if (this.policy.getImplPrefersOnce) {
492
+ const once = this.onces?.[0];
493
+ if (once != null) return once;
494
+ }
495
+ const when = this.when;
496
+ if (when !== null && this.impl === when.dispatcher) return when.fallback ?? void 0;
497
+ return this.impl ?? void 0;
498
+ }
499
+ /** The implementations `withImplementation` swaps out, as a function that puts them back. */
500
+ swapImpl(impl) {
501
+ this.touchConfig();
502
+ const { impl: previous, onces: previousOnces } = this;
503
+ const when = this.when;
504
+ const previousFallback = when?.fallback ?? null;
505
+ const epoch = this.epoch;
506
+ this.impl = impl;
507
+ this.onces = null;
508
+ if (this.layout.chain) this.syncPrototype(impl);
509
+ return () => {
510
+ if (this.epoch !== epoch) return;
511
+ this.touchConfig();
512
+ this.impl = previous;
513
+ this.onces = previousOnces;
514
+ if (when !== null) when.fallback = previousFallback;
515
+ if (this.layout.chain) this.syncPrototype(this.nextImpl());
516
+ };
517
+ }
518
+ /**
519
+ * A method, bound to this mock, made on first read. `bind` keeps the method's `length`, which a
520
+ * `beforeEach` reads to decide whether it takes `done`, and its result. It prefixes the `name`
521
+ * with `bound `: renaming costs a `defineProperty` per method, for a name nothing has been seen
522
+ * to read.
523
+ */
524
+ boundMethod(key, method) {
525
+ let bound = this.bound;
526
+ if (bound === null) {
527
+ bound = Object.create(null);
528
+ this.bound = bound;
529
+ }
530
+ let closure = bound[key];
531
+ if (closure === void 0) {
532
+ closure = reflectApply(functionBind, method, [this.fn]);
533
+ bound[key] = closure;
534
+ }
535
+ return closure;
536
+ }
537
+ whenState() {
538
+ if (this.when !== null) return this.when;
539
+ const when = {
540
+ dispatcher: makeDispatcher(this),
541
+ branches: [],
542
+ fallback: null
543
+ };
544
+ this.when = when;
545
+ return when;
546
+ }
547
+ };
548
+ /** Settles a result cell in place: the cell is what the arrays hold, so it is mutated, not replaced. */
549
+ function finish(cell, type, value) {
550
+ const target = cell;
551
+ target.type = type;
552
+ target.value = value;
553
+ }
554
+ function settle(settled, value) {
555
+ if (value instanceof Promise) {
556
+ value.then((fulfilled) => finish(settled, "fulfilled", fulfilled), (rejected) => finish(settled, "rejected", rejected));
557
+ return;
558
+ }
559
+ finish(settled, "fulfilled", value);
560
+ }
561
+ /** The slot of a mock, or `undefined` for anything else (a bound copy, the prototype, a non-function). */
562
+ function peekSlot(value) {
563
+ return value?.[SLOT];
564
+ }
565
+ /** An assignment to an accessor over a mock's own name: an own data property on the receiver. */
566
+ function setOwn(target, key, value) {
567
+ Object.defineProperty(target, key, {
568
+ value,
569
+ writable: true,
570
+ enumerable: true,
571
+ configurable: true
572
+ });
573
+ }
574
+ /** The order of jest-mock's dispatcher (index.ts L616-L625). Targets always run through `apply`. */
575
+ function makeDispatcher(slot) {
576
+ return function whenCalledWithDispatcherImpl(...args) {
577
+ const when = slot.when;
578
+ if (when === null) return void 0;
579
+ const matching = when.branches.filter((branch) => argsEqual(branch.matchers, args));
580
+ const queued = matching.find((branch) => (branch.subMock[SLOT].onces?.length ?? 0) > 0);
581
+ if (queued !== void 0) return queued.subMock.apply(this, args);
582
+ for (let index = matching.length - 1; index >= 0; index--) {
583
+ const branch = matching[index];
584
+ if (branch !== void 0 && branch.subMock[SLOT].impl !== void 0) return branch.subMock.apply(this, args);
585
+ }
586
+ const fallThrough = when.fallback ?? slot.fallback;
587
+ return fallThrough === null ? void 0 : fallThrough.apply(this, args);
588
+ };
589
+ }
590
+ function slotOf(fn) {
591
+ const slot = peekSlot(fn);
592
+ if (slot === void 0) throw new MockTypeError("MOCK_DETACHED_METHOD", "A mock method was called without its mock. Call it as `mock.method()`, or wrap it in a function.");
593
+ return slot;
594
+ }
595
+ /** A value shorthand's implementation; `name` is what a policy that refuses `new` says it was. */
596
+ function shorthand(slot, name, produce) {
597
+ if (!slot.policy.valueShorthandsThrowOnNew) return () => produce();
598
+ const policy = slot.policy;
599
+ return function valueShorthand() {
600
+ if (new.target !== void 0) throw new MockTypeError("MOCK_NEW_SHORTHAND", messageFor(policy, "new-shorthand", { name }));
601
+ return produce();
602
+ };
603
+ }
604
+ function throwing(value) {
605
+ return function throwValue() {
606
+ throw value;
607
+ };
608
+ }
609
+ /**
610
+ * The shared methods, unbound. Each finds its slot through `this`, which `boundMethod` fixes to the
611
+ * mock. Only the prototype itself hands out one of these, and calling that throws
612
+ * `MOCK_DETACHED_METHOD` rather than acting on nothing.
613
+ */
614
+ const METHODS = {
615
+ getMockImplementation() {
616
+ return slotOf(this).implementation();
617
+ },
618
+ getMockName() {
619
+ return slotOf(this).mockName();
620
+ },
621
+ mockName(name) {
622
+ const slot = slotOf(this);
623
+ if (name) {
624
+ slot.touchConfig();
625
+ slot.name = name;
626
+ }
627
+ return this;
628
+ },
629
+ mockClear() {
630
+ slotOf(this).clearState();
631
+ return this;
632
+ },
633
+ mockReset() {
634
+ slotOf(this).resetMock();
635
+ return this;
636
+ },
637
+ mockRestore() {
638
+ slotOf(this).restore();
639
+ },
640
+ mockImplementation(impl) {
641
+ slotOf(this).setImpl(impl);
642
+ return this;
643
+ },
644
+ mockImplementationOnce(impl) {
645
+ slotOf(this).addOnce(impl);
646
+ return this;
647
+ },
648
+ withImplementation(impl, callback) {
649
+ const slot = slotOf(this);
650
+ const restore = slot.swapImpl(impl);
651
+ const answer = slot.policy.withImplementationReturnsMock ? this : void 0;
652
+ const returned = callback();
653
+ if (isThenable(returned)) return returned.then(() => {
654
+ restore();
655
+ return answer;
656
+ });
657
+ restore();
658
+ return answer;
659
+ },
660
+ mockReturnThis() {
661
+ slotOf(this).setImpl(function returnThis() {
662
+ return this;
663
+ });
664
+ return this;
665
+ },
666
+ mockReturnValue(value) {
667
+ const slot = slotOf(this);
668
+ slot.setImpl(shorthand(slot, "mockReturnValue", () => value));
669
+ return this;
670
+ },
671
+ mockReturnValueOnce(value) {
672
+ const slot = slotOf(this);
673
+ slot.addOnce(shorthand(slot, "mockReturnValueOnce", () => value));
674
+ return this;
675
+ },
676
+ mockResolvedValue(value) {
677
+ const slot = slotOf(this);
678
+ slot.setImpl(shorthand(slot, "mockResolvedValue", () => Promise.resolve(value)));
679
+ return this;
680
+ },
681
+ mockResolvedValueOnce(value) {
682
+ const slot = slotOf(this);
683
+ slot.addOnce(shorthand(slot, "mockResolvedValueOnce", () => Promise.resolve(value)));
684
+ return this;
685
+ },
686
+ mockRejectedValue(value) {
687
+ const slot = slotOf(this);
688
+ slot.setImpl(shorthand(slot, "mockRejectedValue", () => Promise.reject(value)));
689
+ return this;
690
+ },
691
+ mockRejectedValueOnce(value) {
692
+ const slot = slotOf(this);
693
+ slot.addOnce(shorthand(slot, "mockRejectedValueOnce", () => Promise.reject(value)));
694
+ return this;
695
+ },
696
+ mockThrow(value) {
697
+ slotOf(this).setImpl(throwing(value));
698
+ return this;
699
+ },
700
+ mockThrowOnce(value) {
701
+ slotOf(this).addOnce(throwing(value));
702
+ return this;
703
+ },
704
+ whenCalledWith(...matchers) {
705
+ const slot = slotOf(this);
706
+ slot.touchConfig();
707
+ const when = slot.whenState();
708
+ if (slot.impl !== when.dispatcher) {
709
+ when.fallback = slot.impl ?? null;
710
+ slot.impl = when.dispatcher;
711
+ }
712
+ const subMock = createMockFn(slot.policy, slot.registry);
713
+ when.branches.push({
714
+ matchers,
715
+ subMock
716
+ });
717
+ return subMock;
718
+ },
719
+ [Symbol.dispose]() {
720
+ slotOf(this).restore();
721
+ }
722
+ };
723
+ /**
724
+ * One method as a prototype accessor. Enumerable, so `for...in` over a mock lists it. A read never
725
+ * throws; a write makes an own data property on the mock, as assigning over jest-mock's own
726
+ * properties does, which also is what a frozen prototype's data property would have refused.
727
+ */
728
+ function methodAccessor(key, method) {
729
+ return {
730
+ enumerable: true,
731
+ get() {
732
+ const slot = peekSlot(this);
733
+ return slot === void 0 ? method : slot.boundMethod(key, method);
734
+ },
735
+ set(value) {
736
+ setOwn(this, key, value);
737
+ }
738
+ };
739
+ }
740
+ /**
741
+ * `_isMockFunction` and `MOCK_BRAND`: `true` only where there is a slot. `Function.prototype.bind`
742
+ * gives a bound function the mock's prototype, so a plain `true` there would make a bound mock look
743
+ * like one, with no slot to back it. `Object.create(mock)` children and `util.promisify` copies
744
+ * have the slot (an inherited or copied symbol key), so they still answer `true`. A write defines
745
+ * an own data property, as the method accessors' does.
746
+ */
747
+ function flagAccessor(key) {
748
+ return {
749
+ enumerable: true,
750
+ get() {
751
+ return peekSlot(this) !== void 0 ? true : void 0;
752
+ },
753
+ set(value) {
754
+ setOwn(this, key, value);
755
+ }
756
+ };
757
+ }
758
+ function prototypeDescriptors() {
759
+ const descriptors = {
760
+ _isMockFunction: flagAccessor("_isMockFunction"),
761
+ [MOCK_BRAND]: flagAccessor(MOCK_BRAND)
762
+ };
763
+ for (const key of Reflect.ownKeys(METHODS)) {
764
+ const method = METHODS[key];
765
+ descriptors[key] = methodAccessor(key, method);
766
+ }
767
+ return descriptors;
768
+ }
769
+ const PROTOTYPE_DESCRIPTORS = prototypeDescriptors();
770
+ /**
771
+ * Copies `arguments` with no global or prototype lookup on the call path. The common short lists are
772
+ * exact literals: storing into `[]` by index would keep a 17-slot store for even one argument, and
773
+ * `state.calls` holds each list until a clear.
774
+ */
775
+ function copyArguments(source) {
776
+ switch (source.length) {
777
+ case 0: return [];
778
+ case 1: return [source[0]];
779
+ case 2: return [source[0], source[1]];
780
+ case 3: return [
781
+ source[0],
782
+ source[1],
783
+ source[2]
784
+ ];
785
+ case 4: return [
786
+ source[0],
787
+ source[1],
788
+ source[2],
789
+ source[3]
790
+ ];
791
+ }
792
+ const copy = [];
793
+ for (let index = 0; index < source.length; index++) copy[index] = source[index];
794
+ return copy;
795
+ }
796
+ /**
797
+ * The function makers by arity, 0 to 9, for each own name. `Object.defineProperty(fn, 'length')` costs
798
+ * more than the rest of creation, so as jest-mock's `matchArity` does (index.ts L352-L465), the
799
+ * arity is in the source, written out rather than generated: nothing here builds code from a
800
+ * string, which a host can forbid. Each maker is a plain closure over the slot.
801
+ */
802
+ const MOCK_CONSTRUCTOR_MAKERS = [
803
+ (slot) => function mockConstructor() {
804
+ return slot.invoke(this, copyArguments(arguments), new.target);
805
+ },
806
+ (slot) => function mockConstructor(_0) {
807
+ return slot.invoke(this, copyArguments(arguments), new.target);
808
+ },
809
+ (slot) => function mockConstructor(_0, _1) {
810
+ return slot.invoke(this, copyArguments(arguments), new.target);
811
+ },
812
+ (slot) => function mockConstructor(_0, _1, _2) {
813
+ return slot.invoke(this, copyArguments(arguments), new.target);
814
+ },
815
+ (slot) => function mockConstructor(_0, _1, _2, _3) {
816
+ return slot.invoke(this, copyArguments(arguments), new.target);
817
+ },
818
+ (slot) => function mockConstructor(_0, _1, _2, _3, _4) {
819
+ return slot.invoke(this, copyArguments(arguments), new.target);
820
+ },
821
+ (slot) => function mockConstructor(_0, _1, _2, _3, _4, _5) {
822
+ return slot.invoke(this, copyArguments(arguments), new.target);
823
+ },
824
+ (slot) => function mockConstructor(_0, _1, _2, _3, _4, _5, _6) {
825
+ return slot.invoke(this, copyArguments(arguments), new.target);
826
+ },
827
+ (slot) => function mockConstructor(_0, _1, _2, _3, _4, _5, _6, _7) {
828
+ return slot.invoke(this, copyArguments(arguments), new.target);
829
+ },
830
+ (slot) => function mockConstructor(_0, _1, _2, _3, _4, _5, _6, _7, _8) {
831
+ return slot.invoke(this, copyArguments(arguments), new.target);
832
+ }
833
+ ];
834
+ const MOCK_MAKERS = [
835
+ (slot) => function Mock() {
836
+ return slot.invoke(this, copyArguments(arguments), new.target);
837
+ },
838
+ (slot) => function Mock(_0) {
839
+ return slot.invoke(this, copyArguments(arguments), new.target);
840
+ },
841
+ (slot) => function Mock(_0, _1) {
842
+ return slot.invoke(this, copyArguments(arguments), new.target);
843
+ },
844
+ (slot) => function Mock(_0, _1, _2) {
845
+ return slot.invoke(this, copyArguments(arguments), new.target);
846
+ },
847
+ (slot) => function Mock(_0, _1, _2, _3) {
848
+ return slot.invoke(this, copyArguments(arguments), new.target);
849
+ },
850
+ (slot) => function Mock(_0, _1, _2, _3, _4) {
851
+ return slot.invoke(this, copyArguments(arguments), new.target);
852
+ },
853
+ (slot) => function Mock(_0, _1, _2, _3, _4, _5) {
854
+ return slot.invoke(this, copyArguments(arguments), new.target);
855
+ },
856
+ (slot) => function Mock(_0, _1, _2, _3, _4, _5, _6) {
857
+ return slot.invoke(this, copyArguments(arguments), new.target);
858
+ },
859
+ (slot) => function Mock(_0, _1, _2, _3, _4, _5, _6, _7) {
860
+ return slot.invoke(this, copyArguments(arguments), new.target);
861
+ },
862
+ (slot) => function Mock(_0, _1, _2, _3, _4, _5, _6, _7, _8) {
863
+ return slot.invoke(this, copyArguments(arguments), new.target);
864
+ }
865
+ ];
866
+ function readMock() {
867
+ return this[SLOT].readState();
868
+ }
869
+ function writeMock(value) {
870
+ const slot = this[SLOT];
871
+ slot.state = value;
872
+ slot.enterStateDirty();
873
+ }
874
+ function buildLayout(policy) {
875
+ const proto = Object.freeze(Object.create(Function.prototype, PROTOTYPE_DESCRIPTORS));
876
+ let accessor = null;
877
+ if (policy.clearReplacesStateObject || policy.mockPropertyWritable) {
878
+ accessor = {
879
+ configurable: false,
880
+ enumerable: true,
881
+ get: readMock
882
+ };
883
+ if (policy.mockPropertyWritable) accessor.set = writeMock;
884
+ Object.freeze(accessor);
885
+ }
886
+ return {
887
+ proto,
888
+ makers: policy.functionName === "mockConstructor" ? MOCK_CONSTRUCTOR_MAKERS : MOCK_MAKERS,
889
+ accessor,
890
+ chain: policy.classMockPrototype === "chain-to-impl",
891
+ ownNameFromOriginal: policy.functionName === "impl-or-Mock"
892
+ };
893
+ }
894
+ const LAYOUTS = /* @__PURE__ */ new WeakMap();
895
+ function layoutOf(policy) {
896
+ let layout = LAYOUTS.get(policy);
897
+ if (layout === void 0) {
898
+ layout = buildLayout(policy);
899
+ LAYOUTS.set(policy, layout);
900
+ }
901
+ return layout;
902
+ }
903
+ const STATIC_PROPERTIES_SKIPPED = /* @__PURE__ */ new Set([
904
+ "length",
905
+ "name",
906
+ "prototype",
907
+ Symbol.for("nodejs.util.promisify.custom")
908
+ ]);
909
+ /** `copyStaticProps`: @vitest/spy's `copyOriginalStaticProperties`, skipping what the mock has. */
910
+ function copyStatics(mock, source) {
911
+ let from = source;
912
+ while (from !== null && from !== Object.prototype && from !== Function.prototype) {
913
+ const keys = Reflect.ownKeys(from);
914
+ if (keys.length > 3 || keys.length === 3 && keys[2] !== "prototype") for (const key of keys) {
915
+ if (STATIC_PROPERTIES_SKIPPED.has(key) || key in mock) continue;
916
+ const descriptor = Object.getOwnPropertyDescriptor(from, key);
917
+ if (descriptor !== void 0) Object.defineProperty(mock, key, descriptor);
918
+ }
919
+ from = Object.getPrototypeOf(from);
920
+ }
921
+ }
922
+ /** The parts of the options only a spy or an automock member has. */
923
+ function applyRareOptions(slot, mock, options) {
924
+ const original = options.original;
925
+ if (options.fallback !== void 0) slot.fallback = options.fallback;
926
+ if (original !== void 0) {
927
+ if (slot.policy.spyReportsBridgeImpl) slot.setImpl(function spyBridge(...args) {
928
+ return original.apply(this, args);
929
+ });
930
+ else slot.fallback = original;
931
+ }
932
+ const ownName = options.name ?? (slot.layout.ownNameFromOriginal ? original?.name : void 0);
933
+ if (ownName) Object.defineProperty(mock, "name", {
934
+ value: ownName,
935
+ configurable: true
936
+ });
937
+ }
938
+ /** The own length a mock is made with, unless `options.length` says otherwise. */
939
+ function lengthFor(options, layout) {
940
+ if (options.length !== void 0) return options.length;
941
+ return (options.impl ?? (layout.ownNameFromOriginal ? options.original : void 0))?.length ?? 0;
942
+ }
943
+ function makeFunction(layout, slot, length) {
944
+ const arity = length >= 0 && length < layout.makers.length ? length : 0;
945
+ const fn = layout.makers[arity](slot);
946
+ if (arity !== length) Object.defineProperty(fn, "length", {
947
+ value: length,
948
+ configurable: true
949
+ });
950
+ return fn;
951
+ }
952
+ /**
953
+ * Builds a mock function: `fn()`, `fn(impl)`, and through its options every other builder (spies,
954
+ * automock members, factories). Takes one policy slice, and the file's registry.
955
+ * @public
956
+ */
957
+ function createMockFn(policy, registry, options) {
958
+ if (options !== void 0 && policy.fnOfMockReturnsSame && peekSlot(options.impl) !== void 0) return options.impl;
959
+ const layout = layoutOf(policy);
960
+ const slot = new MockSlot(policy, registry, layout);
961
+ const opts = options;
962
+ const fn = makeFunction(layout, slot, opts === void 0 ? 0 : lengthFor(opts, layout));
963
+ slot.fn = fn;
964
+ Object.setPrototypeOf(fn, layout.proto);
965
+ fn[SLOT] = slot;
966
+ if (layout.accessor !== null) Object.defineProperty(fn, "mock", layout.accessor);
967
+ else {
968
+ const state = freshState(policy);
969
+ slot.state = state;
970
+ Object.defineProperty(fn, "mock", {
971
+ configurable: false,
972
+ enumerable: true,
973
+ writable: false,
974
+ value: state
975
+ });
976
+ }
977
+ if (opts !== void 0) {
978
+ slot.options = opts;
979
+ if (opts.impl !== void 0) slot.impl = opts.impl;
980
+ if (opts.spy === true || opts.fallback !== void 0 || opts.name !== void 0 || opts.original !== void 0) applyRareOptions(slot, fn, opts);
981
+ if (layout.chain) slot.syncPrototype(slot.nextImpl());
982
+ if (policy.copyStaticProps) {
983
+ const source = opts.original ?? opts.impl;
984
+ if (source !== void 0) copyStatics(fn, source);
985
+ }
986
+ }
987
+ return fn;
988
+ }
989
+ /**
990
+ * Whether a value is a mock function. Under `isMockAcceptsObjects` any value with
991
+ * `_isMockFunction: true` is; otherwise only a function is.
992
+ * @public
993
+ */
994
+ function isMockFunction(policy, value) {
995
+ if (value === null || value === void 0) return false;
996
+ if (!policy.isMockAcceptsObjects && typeof value !== "function") return false;
997
+ return value._isMockFunction === true;
998
+ }
999
+
1000
+ // src/module/automock.ts
1001
+ const OBJECT_PROTOTYPE = Object.prototype;
1002
+ const FUNCTION_PROTOTYPE = Function.prototype;
1003
+ const REGEXP_PROTOTYPE = RegExp.prototype;
1004
+ const FUNCTION_NAME_RESERVED_PATTERN = /[\s!-/:-@[-`{-~]/;
1005
+ const FUNCTION_NAME_RESERVED_REPLACE = /[\s!-/:-@[-`{-~]/g;
1006
+ const RESERVED_KEYWORDS = /* @__PURE__ */ new Set([
1007
+ "arguments",
1008
+ "await",
1009
+ "break",
1010
+ "case",
1011
+ "catch",
1012
+ "class",
1013
+ "const",
1014
+ "continue",
1015
+ "debugger",
1016
+ "default",
1017
+ "delete",
1018
+ "do",
1019
+ "else",
1020
+ "enum",
1021
+ "eval",
1022
+ "export",
1023
+ "extends",
1024
+ "false",
1025
+ "finally",
1026
+ "for",
1027
+ "function",
1028
+ "if",
1029
+ "implements",
1030
+ "import",
1031
+ "in",
1032
+ "instanceof",
1033
+ "interface",
1034
+ "let",
1035
+ "new",
1036
+ "null",
1037
+ "package",
1038
+ "private",
1039
+ "protected",
1040
+ "public",
1041
+ "return",
1042
+ "static",
1043
+ "super",
1044
+ "switch",
1045
+ "this",
1046
+ "throw",
1047
+ "true",
1048
+ "try",
1049
+ "typeof",
1050
+ "var",
1051
+ "void",
1052
+ "while",
1053
+ "with",
1054
+ "yield"
1055
+ ]);
1056
+ function tagOf(value) {
1057
+ return Object.prototype.toString.call(value).slice(8, -1);
1058
+ }
1059
+ function isFunctionTag(tag) {
1060
+ return tag === "Function" || tag === "AsyncFunction" || tag === "GeneratorFunction" || tag === "AsyncGeneratorFunction";
1061
+ }
1062
+ /** jest-mock's and @vitest/mocker's `isReadonlyProp`: the same table. */
1063
+ function isReadonlyProp(object, prop) {
1064
+ if (typeof prop === "symbol") return false;
1065
+ if (prop === "arguments" || prop === "caller" || prop === "callee" || prop === "name" || prop === "length") return isFunctionTag(tagOf(object));
1066
+ if (prop === "source" || prop === "global" || prop === "ignoreCase" || prop === "multiline") return tagOf(object) === "RegExp";
1067
+ return false;
1068
+ }
1069
+ /**
1070
+ * Every own property of `object` and of its prototypes, up to (not including) `Object.prototype`,
1071
+ * `Function.prototype` and `RegExp.prototype`. The nearest descriptor wins.
1072
+ */
1073
+ function collectSlots(object, symbols) {
1074
+ const seen = /* @__PURE__ */ new Map();
1075
+ let current = object;
1076
+ while (current !== null && current !== OBJECT_PROTOTYPE && current !== FUNCTION_PROTOTYPE && current !== REGEXP_PROTOTYPE) {
1077
+ const keys = Object.getOwnPropertyNames(current);
1078
+ if (symbols) keys.push(...Object.getOwnPropertySymbols(current));
1079
+ for (const key of keys) {
1080
+ if (seen.has(key)) continue;
1081
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
1082
+ if (descriptor !== void 0) seen.set(key, {
1083
+ key,
1084
+ descriptor
1085
+ });
1086
+ }
1087
+ current = Object.getPrototypeOf(current);
1088
+ }
1089
+ return [...seen.values()];
1090
+ }
1091
+ function assign(container, key, value) {
1092
+ try {
1093
+ container[key] = value;
1094
+ return true;
1095
+ } catch {
1096
+ return false;
1097
+ }
1098
+ }
1099
+ function read(container, key) {
1100
+ try {
1101
+ return { value: container[key] };
1102
+ } catch {
1103
+ return null;
1104
+ }
1105
+ }
1106
+ /**
1107
+ * The name a Jest automock gives a function, as `_createMockFunction` writes it (index.ts
1108
+ * L1011-L1063): a `bound ` prefix survives once, `mockConstructor` and the empty name leave the
1109
+ * mock its default, and a name that wouldn't be an identifier is rewritten.
1110
+ */
1111
+ function metadataName(raw) {
1112
+ if (typeof raw !== "string" || raw === "") return void 0;
1113
+ let name = raw;
1114
+ let bound = false;
1115
+ while (name.startsWith("bound ")) {
1116
+ name = name.slice(6);
1117
+ bound = true;
1118
+ }
1119
+ if (name === "mockConstructor" || name === "") return void 0;
1120
+ if (RESERVED_KEYWORDS.has(name) || /^\d/.test(name)) name = `$${name}`;
1121
+ if (FUNCTION_NAME_RESERVED_PATTERN.test(name)) name = name.replaceAll(FUNCTION_NAME_RESERVED_REPLACE, "$");
1122
+ return bound ? `bound ${name}` : name;
1123
+ }
1124
+ /**
1125
+ * What a mocked class does when constructed: give the instance its own mock for each method on the
1126
+ * prototype, falling through to the prototype's own mock. A plain call does nothing.
1127
+ */
1128
+ function instanceMethods(mk, members, nameOf, owner) {
1129
+ return function constructInstance() {
1130
+ if (this === null || typeof this !== "object") return void 0;
1131
+ if (owner.mock === null || !(this instanceof owner.mock)) return void 0;
1132
+ const instance = this;
1133
+ for (const key of members) {
1134
+ const protoMethod = instance[key];
1135
+ if (typeof protoMethod !== "function") continue;
1136
+ const name = nameOf(key);
1137
+ instance[key] = mk(name === void 0 ? { fallback: protoMethod } : {
1138
+ name,
1139
+ fallback: protoMethod
1140
+ });
1141
+ }
1142
+ };
1143
+ }
1144
+ function functionKeys(prototype, symbols) {
1145
+ const keys = [];
1146
+ for (const { key, descriptor } of collectSlots(prototype, symbols)) {
1147
+ if (key === "constructor" || descriptor.get !== void 0) continue;
1148
+ if (typeof descriptor.value === "function") keys.push(key);
1149
+ }
1150
+ return keys;
1151
+ }
1152
+ /** jest-mock's `getType` (index.ts L471-L506). `null` means "no metadata": the value is left out. */
1153
+ function metadataType(ref) {
1154
+ const tag = tagOf(ref);
1155
+ if (isFunctionTag(tag)) return "function";
1156
+ if (Array.isArray(ref)) return "array";
1157
+ if (tag === "Object" || tag === "Module") return "object";
1158
+ if (tag === "Number" || tag === "String" || tag === "Boolean" || tag === "Symbol") return "constant";
1159
+ if (tag === "Map" || tag === "WeakMap" || tag === "Set") return "collection";
1160
+ if (tag === "RegExp") return "regexp";
1161
+ if (ref === void 0) return "undefined";
1162
+ if (ref === null) return "null";
1163
+ return null;
1164
+ }
1165
+ /** jest-mock's `_getSlots` (index.ts L557-L599): a getter is not a slot, unless the object is an ES module. */
1166
+ function metadataSlots(object) {
1167
+ const esModule = object.__esModule;
1168
+ const slots = [];
1169
+ for (const { key, descriptor } of collectSlots(object, false)) {
1170
+ if (typeof key !== "string" || isReadonlyProp(object, key)) continue;
1171
+ if (descriptor.get === void 0 || esModule) slots.push(key);
1172
+ }
1173
+ return slots;
1174
+ }
1175
+ function isMockLike(value) {
1176
+ return typeof value === "function" && value._isMockFunction === true;
1177
+ }
1178
+ function fromMetadata(root, mode, mk) {
1179
+ const made = /* @__PURE__ */ new Map();
1180
+ const backReferences = [];
1181
+ const build = (value) => {
1182
+ const type = metadataType(value);
1183
+ if (type === null) return null;
1184
+ if (type === "constant" || type === "collection" || type === "null" || type === "undefined") return { mock: value };
1185
+ let mock;
1186
+ const protoSlots = [];
1187
+ const owner = { mock: null };
1188
+ if (type === "object") mock = {};
1189
+ else if (type === "array") mock = [];
1190
+ else if (type === "regexp") mock = /(?:)/;
1191
+ else {
1192
+ const original = value;
1193
+ const name = metadataName(original.name);
1194
+ const base = name === void 0 ? {} : { name };
1195
+ mock = mode === "autospy" ? mk({
1196
+ ...base,
1197
+ original
1198
+ }) : mk({
1199
+ ...base,
1200
+ fallback: instanceMethods(mk, protoSlots, (key) => typeof key === "string" ? metadataName(key) : void 0, owner)
1201
+ });
1202
+ owner.mock = mock;
1203
+ }
1204
+ made.set(value, mock);
1205
+ if (type !== "array") {
1206
+ const source = value;
1207
+ for (const slot of metadataSlots(source)) {
1208
+ if (type === "function" && isMockLike(source) && slot.startsWith("mock")) continue;
1209
+ const got = read(source, slot);
1210
+ if (got === null) continue;
1211
+ const seen = made.get(got.value);
1212
+ if (seen !== void 0) {
1213
+ backReferences.push(() => {
1214
+ assign(mock, slot, seen);
1215
+ });
1216
+ continue;
1217
+ }
1218
+ const child = build(got.value);
1219
+ if (child !== null) assign(mock, slot, child.mock);
1220
+ }
1221
+ }
1222
+ if (type === "function") {
1223
+ const proto = mock.prototype;
1224
+ if (proto !== null && typeof proto === "object") {
1225
+ protoSlots.push(...functionKeys(proto, false));
1226
+ assign(proto, "constructor", mock);
1227
+ }
1228
+ }
1229
+ return { mock };
1230
+ };
1231
+ const result = build(root);
1232
+ for (const link of backReferences) link();
1233
+ if (result === null) throw new MockError("automock-no-metadata", "Failed to get mock metadata");
1234
+ const mock = result.mock;
1235
+ if (tagOf(root) === "Module" && mock !== null && typeof mock === "object" && !Object.hasOwn(mock, "__esModule")) Object.defineProperty(mock, "__esModule", {
1236
+ value: true,
1237
+ enumerable: false
1238
+ });
1239
+ return mock;
1240
+ }
1241
+ function fromDeep(root, mode, mk) {
1242
+ const finalizers = [];
1243
+ const refs = /* @__PURE__ */ new Map();
1244
+ const createMock = (current) => {
1245
+ const name = current.name;
1246
+ const proto = current.prototype;
1247
+ const options = name === "" ? {} : { name };
1248
+ if (mode === "autospy") return mk({
1249
+ ...options,
1250
+ original: current
1251
+ });
1252
+ const members = proto !== null && typeof proto === "object" ? functionKeys(proto, true) : [];
1253
+ if (members.length === 0) return mk(options);
1254
+ const owner = { mock: null };
1255
+ const made = mk({
1256
+ ...options,
1257
+ fallback: instanceMethods(mk, members, (key) => typeof key === "string" ? key : void 0, owner)
1258
+ });
1259
+ owner.mock = made;
1260
+ return made;
1261
+ };
1262
+ const mockPropertiesOf = (container, target) => {
1263
+ const isModule = tagOf(container) === "Module" || Boolean(container.__esModule);
1264
+ for (const { key, descriptor } of collectSlots(container, true)) {
1265
+ if (!isModule && descriptor.get !== void 0) {
1266
+ try {
1267
+ if (mode === "autospy") Object.defineProperty(target, key, descriptor);
1268
+ else {
1269
+ const accessor = {
1270
+ configurable: descriptor.configurable === true,
1271
+ enumerable: descriptor.enumerable === true,
1272
+ get: () => void 0
1273
+ };
1274
+ if (descriptor.set !== void 0) accessor.set = () => void 0;
1275
+ Object.defineProperty(target, key, accessor);
1276
+ }
1277
+ } catch {}
1278
+ continue;
1279
+ }
1280
+ const got = read(container, key);
1281
+ if (got === null) continue;
1282
+ if (isReadonlyProp(container, key)) continue;
1283
+ const value = got.value;
1284
+ if (refs.has(value)) {
1285
+ const mocked = refs.get(value);
1286
+ finalizers.push(() => {
1287
+ assign(target, key, mocked);
1288
+ });
1289
+ continue;
1290
+ }
1291
+ const tag = tagOf(value);
1292
+ if (Array.isArray(value)) {
1293
+ if (mode === "automock") assign(target, key, []);
1294
+ else {
1295
+ const copies = [];
1296
+ refs.set(value, copies);
1297
+ for (const item of value) {
1298
+ const known = refs.get(item);
1299
+ if (known !== void 0) copies.push(known);
1300
+ else if (item !== null && typeof item === "object") {
1301
+ const copy = {};
1302
+ refs.set(item, copy);
1303
+ copies.push(copy);
1304
+ mockPropertiesOf(item, copy);
1305
+ } else if (typeof item === "function") copies.push(createMock(item));
1306
+ else copies.push(item);
1307
+ }
1308
+ assign(target, key, copies);
1309
+ }
1310
+ continue;
1311
+ }
1312
+ const isFunction = tag.includes("Function") && typeof value === "function";
1313
+ if ((!isFunction || isMockLike(value)) && tag !== "Object" && tag !== "Module") {
1314
+ assign(target, key, value);
1315
+ continue;
1316
+ }
1317
+ if (mode === "autospy" && tag === "Module") {
1318
+ const namespace = Object.create(null);
1319
+ Object.defineProperty(namespace, Symbol.toStringTag, {
1320
+ value: "Module",
1321
+ configurable: true,
1322
+ writable: true
1323
+ });
1324
+ if (!assign(target, key, namespace)) continue;
1325
+ } else if (!assign(target, key, isFunction || mode === "autospy" ? value : {})) continue;
1326
+ let child = target[key];
1327
+ if (isFunction) {
1328
+ child = createMock(child);
1329
+ target[key] = child;
1330
+ }
1331
+ refs.set(value, child);
1332
+ mockPropertiesOf(value, child);
1333
+ }
1334
+ };
1335
+ if (root === null || typeof root !== "object" && typeof root !== "function") return root;
1336
+ if (Array.isArray(root)) return mode === "automock" ? [] : root;
1337
+ if (isMockLike(root)) return root;
1338
+ const mocked = typeof root === "function" ? createMock(root) : {};
1339
+ refs.set(root, mocked);
1340
+ mockPropertiesOf(root, mocked);
1341
+ for (const finalize of finalizers) finalize();
1342
+ return mocked;
1343
+ }
1344
+ /**
1345
+ * Builds the automock of a module's real exports (T4.6). Functions become mocks that return
1346
+ * `undefined`; a class's constructor body never runs, and each instance's methods record into the
1347
+ * prototype's mocks too. Statics, nested objects and getters are mocked (a getter reads
1348
+ * `undefined`); arrays become `[]`; `Map`s, primitives and `null` are kept. Cycles are followed.
1349
+ * `metadata` is jest-mock's shape (a `Date` or `BigInt` is dropped, a `RegExp` emptied, the module
1350
+ * gets `__esModule`); `deep` is `@vitest/mocker`'s. `autospy` keeps the real behaviour.
1351
+ *
1352
+ * Throws `MockError` with code `automock-no-metadata` under `metadata` when the root has no
1353
+ * metadata, as `getMetadata` returning `null` does.
1354
+ * @public
1355
+ */
1356
+ function automock(value, shape, mode, mk) {
1357
+ return shape === "metadata" ? fromMetadata(value, mode, mk) : fromDeep(value, mode, mk);
1358
+ }
1359
+
1360
+ // src/module/manual-mocks.ts
1361
+ const CORE_NAMES = new Set(builtinModules);
1362
+ /** Whether `specifier` names a Node core module, with or without `node:`. */
1363
+ function isCoreSpecifier(specifier) {
1364
+ return specifier.startsWith("node:") || CORE_NAMES.has(specifier);
1365
+ }
1366
+ /** `node:fs` and `fs` to `fs`: the name a root mock file has. */
1367
+ function coreName(specifier) {
1368
+ return specifier.startsWith("node:") ? specifier.slice(5) : specifier;
1369
+ }
1370
+ function isFile(path) {
1371
+ try {
1372
+ return statSync(path, { throwIfNoEntry: false })?.isFile() === true;
1373
+ } catch {
1374
+ return false;
1375
+ }
1376
+ }
1377
+ function dotted(extension) {
1378
+ return extension.startsWith(".") ? extension : `.${extension}`;
1379
+ }
1380
+ /** A specifier that names a package or core module, not a relative or absolute path. */
1381
+ function isBareSpecifier(specifier) {
1382
+ return !specifier.startsWith(".") && !specifier.startsWith("/") && !isAbsolute(specifier) && !/^[a-zA-Z]:[\\/]/.test(specifier);
1383
+ }
1384
+ /**
1385
+ * Looks for the root mock of `specifier`: only a package or core name has one. Returns the first
1386
+ * root, then the first extension, that has the file.
1387
+ * @public
1388
+ */
1389
+ function findRootMock(specifier, options) {
1390
+ if (!isBareSpecifier(specifier) || specifier.split(/[\\/]/).includes("..")) return null;
1391
+ const name = isCoreSpecifier(specifier) ? coreName(specifier) : specifier;
1392
+ for (const root of options.roots) for (const extension of options.extensions) {
1393
+ const path = join(root, "__mocks__", `${name}${dotted(extension)}`);
1394
+ if (isFile(path)) return {
1395
+ path,
1396
+ kind: "root"
1397
+ };
1398
+ }
1399
+ return null;
1400
+ }
1401
+ /**
1402
+ * Lists each root's `__mocks__` tree on first use. A name is the file's path under `__mocks__`
1403
+ * without its extension (`pkg`, `@scope/pkg`, `pkg/sub`, `fs`); the first root wins, then the
1404
+ * first extension, as in `findRootMock`.
1405
+ * @public
1406
+ */
1407
+ function createRootMockIndex(options) {
1408
+ let byName = null;
1409
+ const build = () => {
1410
+ const found = /* @__PURE__ */ new Map();
1411
+ const extensions = options.extensions.map(dotted);
1412
+ for (const root of options.roots) {
1413
+ const dir = join(root, "__mocks__");
1414
+ let files;
1415
+ try {
1416
+ files = readdirSync(dir, {
1417
+ recursive: true,
1418
+ encoding: "utf8"
1419
+ });
1420
+ } catch {
1421
+ continue;
1422
+ }
1423
+ for (const extension of extensions) for (const file of files) {
1424
+ if (!file.endsWith(extension)) continue;
1425
+ const name = file.slice(0, -extension.length).split(sep).join("/");
1426
+ const path = join(dir, file);
1427
+ if (found.has(name) || !isFile(path)) continue;
1428
+ found.set(name, {
1429
+ path,
1430
+ kind: "root"
1431
+ });
1432
+ }
1433
+ }
1434
+ return found;
1435
+ };
1436
+ const index = () => {
1437
+ byName ??= build();
1438
+ return byName;
1439
+ };
1440
+ return {
1441
+ find(specifier) {
1442
+ if (!isBareSpecifier(specifier) || specifier.split(/[\\/]/).includes("..")) return null;
1443
+ const name = isCoreSpecifier(specifier) ? coreName(specifier) : specifier;
1444
+ return index().get(name) ?? null;
1445
+ },
1446
+ isEmpty: () => index().size === 0
1447
+ };
1448
+ }
1449
+ /** `__mocks__/<file>` beside a resolved file, or `null`. */
1450
+ function findAdjacentMock(resolved) {
1451
+ const sibling = join(dirname(resolved), "__mocks__", basename(resolved));
1452
+ return isFile(sibling) ? {
1453
+ path: sibling,
1454
+ kind: "adjacent"
1455
+ } : null;
1456
+ }
1457
+ /**
1458
+ * Looks for the manual mock of a module: the root mock for a package or core name first, then
1459
+ * `__mocks__/<file>` beside the resolved file. Pure file-system reads; callers cache.
1460
+ * @public
1461
+ */
1462
+ function findManualMock(specifier, options) {
1463
+ const root = findRootMock(specifier, options);
1464
+ if (root !== null) return root;
1465
+ const resolved = options.resolved;
1466
+ if (resolved === null || resolved === void 0 || isCoreSpecifier(specifier)) return null;
1467
+ const sibling = join(dirname(resolved), "__mocks__", basename(resolved));
1468
+ return isFile(sibling) ? {
1469
+ path: sibling,
1470
+ kind: "adjacent"
1471
+ } : null;
1472
+ }
1473
+
1474
+ // src/module/messages.ts
1475
+ const NEUTRAL_MODULE_MESSAGES = {
1476
+ "module-missing": "Cannot find module '{specifier}' from '{from}'. To mock a module that does not exist on disk, pass the `virtual` option",
1477
+ "unmock-module-missing": "Cannot find module '{specifier}' from '{from}'",
1478
+ "factory-not-object": "The mock factory for \"{raw}\" must return an object",
1479
+ "missing-factory-export": "No \"{name}\" export is defined on the \"{raw}\" mock",
1480
+ "nested-isolation": "{caller} cannot be nested inside another {caller} or {other}",
1481
+ "automock-no-metadata": "Failed to get mock metadata: {id}",
1482
+ "circular-mock": "The mock factory for \"{raw}\" imports the module it mocks",
1483
+ "registry-disposed": "The module mock registry was disposed",
1484
+ "unresolved-relative-mock": "Cannot find module '{id}'"
1485
+ };
1486
+ /** Fills a code's text from the policy, or from the neutral table. */
1487
+ function moduleMessage(policy, code, values) {
1488
+ return fill(policy.messages[code] ?? NEUTRAL_MODULE_MESSAGES[code], values);
1489
+ }
1490
+
1491
+ // src/module/registry.ts
1492
+ const NOT_MOCKED = Object.freeze({ mocked: false });
1493
+ const PUBLIC_SYMBOLS = /* @__PURE__ */ new Set([
1494
+ Symbol.asyncIterator,
1495
+ Symbol.hasInstance,
1496
+ Symbol.isConcatSpreadable,
1497
+ Symbol.iterator,
1498
+ Symbol.match,
1499
+ Symbol.matchAll,
1500
+ Symbol.replace,
1501
+ Symbol.search,
1502
+ Symbol.split,
1503
+ Symbol.species,
1504
+ Symbol.toPrimitive,
1505
+ Symbol.toStringTag,
1506
+ Symbol.unscopables
1507
+ ]);
1508
+ /** `pkg` or `@scope/pkg` from the last `node_modules` in a path, or `null`. */
1509
+ function packageNameOf(path) {
1510
+ const parts = path.split(sep === "\\" ? /[\\/]/ : "/");
1511
+ const at = parts.lastIndexOf("node_modules");
1512
+ const first = parts[at + 1];
1513
+ if (at === -1 || first === void 0 || first === "") return null;
1514
+ if (!first.startsWith("@")) return first;
1515
+ const second = parts[at + 2];
1516
+ return second === void 0 || second === "" ? null : `${first}/${second}`;
1517
+ }
1518
+ var Registry$1 = class {
1519
+ #options;
1520
+ #policy;
1521
+ #entries = /* @__PURE__ */ new Map();
1522
+ /** The id a dual package's other ids stand for: one entry, one cached value. */
1523
+ #canonical = /* @__PURE__ */ new Map();
1524
+ /** The bare specifier `decide` saw for an id that has no entry, for its manual-mock name. */
1525
+ #specifiers = /* @__PURE__ */ new Map();
1526
+ /** Ids whose value is being built (a factory still running or pending). */
1527
+ #building = /* @__PURE__ */ new Set();
1528
+ /** Ids whose automock's real load is running, at any scratch depth (`#automockOf`). */
1529
+ #automocking = /* @__PURE__ */ new Set();
1530
+ /** The ids whose factory the current call stack, or async continuation, is inside; made on the first factory. */
1531
+ #inside = null;
1532
+ #values = /* @__PURE__ */ new Map();
1533
+ #overlay = null;
1534
+ /** Manual mocks by id; a root mock for an uninstalled package is seeded here by `decideUnresolved`. */
1535
+ #manual = /* @__PURE__ */ new Map();
1536
+ /** The root mocks by name: the worker's list, or one of this registry's own. */
1537
+ #rootMocks;
1538
+ /** The ids `deepUnmock` named, and what they import under automock-all, and what those import. */
1539
+ #deep = /* @__PURE__ */ new Set();
1540
+ /** `onGenerateMock`'s callbacks, in the order registered. */
1541
+ #onGenerate = [];
1542
+ #automock;
1543
+ #generation = 0;
1544
+ #disposed = false;
1545
+ constructor(options) {
1546
+ this.#options = options;
1547
+ this.#policy = options.policy;
1548
+ this.#automock = options.policy.automock;
1549
+ this.#rootMocks = options.rootMocks ?? createRootMockIndex({
1550
+ roots: options.roots,
1551
+ extensions: options.extensions
1552
+ });
1553
+ }
1554
+ register(specifier, spec, options) {
1555
+ this.#live();
1556
+ this.#generation++;
1557
+ const targets = this.#identify(specifier, options.from, options.virtual === true, spec);
1558
+ const [primary] = targets;
1559
+ if (primary === void 0) return;
1560
+ const entry = {
1561
+ spec,
1562
+ specifier,
1563
+ from: options.from
1564
+ };
1565
+ for (const id of targets) {
1566
+ this.#entries.set(id, entry);
1567
+ this.#canonical.set(id, primary);
1568
+ if (spec.kind === "unmock" && spec.deep === true) this.#deep.add(id);
1569
+ else this.#deep.delete(id);
1570
+ this.#manual.delete(id);
1571
+ if (this.#policy.mockValueOwner === "registration") {
1572
+ this.#values.delete(id);
1573
+ this.#overlay?.delete(id);
1574
+ }
1575
+ }
1576
+ }
1577
+ decide(resolvedId, importer, kind, specifier) {
1578
+ this.#live();
1579
+ if (!this.active()) return NOT_MOCKED;
1580
+ const entry = this.#entries.get(resolvedId);
1581
+ if (entry !== void 0) return entry.spec.kind === "unmock" ? NOT_MOCKED : {
1582
+ mocked: true,
1583
+ id: this.#canonical.get(resolvedId) ?? resolvedId
1584
+ };
1585
+ if (kind === "builtin") return NOT_MOCKED;
1586
+ if (this.#automock && !this.#unmockedByPattern(resolvedId)) {
1587
+ if (this.#deep.has(importer)) {
1588
+ this.#deep.add(resolvedId);
1589
+ return NOT_MOCKED;
1590
+ }
1591
+ this.#noteSpecifier(resolvedId, specifier);
1592
+ return {
1593
+ mocked: true,
1594
+ id: resolvedId
1595
+ };
1596
+ }
1597
+ if (this.#policy.rootMocksAutoApply) {
1598
+ const name = specifier === void 0 ? packageNameOf(resolvedId) : isBareSpecifier(specifier) ? specifier : null;
1599
+ if (name !== null && this.#rootMocks.find(name) !== null) {
1600
+ this.#noteSpecifier(resolvedId, specifier);
1601
+ return {
1602
+ mocked: true,
1603
+ id: resolvedId
1604
+ };
1605
+ }
1606
+ }
1607
+ return NOT_MOCKED;
1608
+ }
1609
+ active() {
1610
+ this.#live();
1611
+ return this.#entries.size > 0 || this.#automock || this.#policy.rootMocksAutoApply && !this.#rootMocks.isEmpty();
1612
+ }
1613
+ generation() {
1614
+ this.#live();
1615
+ return this.#generation;
1616
+ }
1617
+ decideUnresolved(specifier, importer) {
1618
+ this.#live();
1619
+ if (isCoreSpecifier(specifier)) return this.decide(`node:${coreName(specifier)}`, importer, "builtin");
1620
+ const id = this.#virtualId(specifier, importer);
1621
+ const entry = this.#entries.get(id);
1622
+ if (entry !== void 0) {
1623
+ if (entry.spec.kind === "unmock") return NOT_MOCKED;
1624
+ if (!this.#policy.virtualRelative && !isBareSpecifier(specifier)) {
1625
+ const shown = relative(this.#options.roots[0] ?? "", id.slice(8));
1626
+ throw new MockError("unresolved-relative-mock", this.#text("unresolved-relative-mock", { id: `/${shown.split(sep).join("/")}` }));
1627
+ }
1628
+ return {
1629
+ mocked: true,
1630
+ id
1631
+ };
1632
+ }
1633
+ if (this.#manual.get(id) != null) return {
1634
+ mocked: true,
1635
+ id
1636
+ };
1637
+ if (this.#policy.rootMocksAutoApply && isBareSpecifier(specifier)) {
1638
+ const found = this.#rootMocks.find(specifier);
1639
+ if (found !== null) {
1640
+ this.#manual.set(id, found);
1641
+ return {
1642
+ mocked: true,
1643
+ id
1644
+ };
1645
+ }
1646
+ }
1647
+ return NOT_MOCKED;
1648
+ }
1649
+ materialize(requested) {
1650
+ this.#live();
1651
+ const id = this.#canonical.get(requested) ?? requested;
1652
+ if (this.#building.has(id) && this.#inside?.getStore()?.has(id) === true) {
1653
+ const error = new MockError("circular-mock", this.#text("circular-mock", { raw: this.#entries.get(id)?.specifier ?? id }));
1654
+ if (this.#policy.awaitFactory) return Promise.reject(error);
1655
+ throw error;
1656
+ }
1657
+ const overlay = this.#overlay;
1658
+ if (overlay?.has(id)) return overlay.get(id);
1659
+ if (this.#values.has(id)) return this.#values.get(id);
1660
+ this.#building.add(id);
1661
+ let value;
1662
+ try {
1663
+ value = this.#create(id);
1664
+ } catch (error) {
1665
+ this.#building.delete(id);
1666
+ throw error;
1667
+ }
1668
+ const store = overlay ?? this.#values;
1669
+ store.set(id, value);
1670
+ if (isThenable(value)) {
1671
+ const settled = () => {
1672
+ this.#building.delete(id);
1673
+ };
1674
+ Promise.resolve(value).then(settled, () => {
1675
+ settled();
1676
+ if (store.get(id) === value) store.delete(id);
1677
+ });
1678
+ } else this.#building.delete(id);
1679
+ return value;
1680
+ }
1681
+ mockFor(specifier, from) {
1682
+ this.#live();
1683
+ return this.materialize(this.#idFor(specifier, from));
1684
+ }
1685
+ createMockFromModule(specifier, from) {
1686
+ this.#live();
1687
+ return this.#automockOf(this.#idFor(specifier, from), from, false);
1688
+ }
1689
+ onResetModules() {
1690
+ this.#live();
1691
+ if (this.#policy.resetModulesClearsMocks) {
1692
+ this.#generation++;
1693
+ this.#entries.clear();
1694
+ this.#canonical.clear();
1695
+ this.#manual.clear();
1696
+ }
1697
+ if (this.#policy.mockValueOwner === "module-registry" || this.#policy.resetModulesClearsMocks) {
1698
+ this.#values.clear();
1699
+ this.#overlay?.clear();
1700
+ }
1701
+ }
1702
+ onGenerateMock(callback) {
1703
+ this.#live();
1704
+ this.#onGenerate.push(callback);
1705
+ }
1706
+ setAutomock(enabled) {
1707
+ this.#live();
1708
+ this.#generation++;
1709
+ this.#automock = enabled;
1710
+ }
1711
+ enterIsolation(caller = "isolateModules", other = "isolateModulesAsync") {
1712
+ this.#live();
1713
+ if (this.#overlay !== null) throw new MockError("nested-isolation", this.#text("nested-isolation", {
1714
+ caller,
1715
+ other
1716
+ }));
1717
+ this.#overlay = /* @__PURE__ */ new Map();
1718
+ }
1719
+ exitIsolation() {
1720
+ this.#live();
1721
+ this.#overlay = null;
1722
+ }
1723
+ dispose() {
1724
+ this.#disposed = true;
1725
+ this.#entries.clear();
1726
+ this.#canonical.clear();
1727
+ this.#specifiers.clear();
1728
+ this.#building.clear();
1729
+ this.#automocking.clear();
1730
+ this.#deep.clear();
1731
+ this.#onGenerate.length = 0;
1732
+ this.#values.clear();
1733
+ this.#manual.clear();
1734
+ this.#overlay = null;
1735
+ this.#inside?.disable();
1736
+ this.#inside = null;
1737
+ }
1738
+ #live() {
1739
+ if (this.#disposed) throw new MockError("registry-disposed", this.#text("registry-disposed", {}));
1740
+ }
1741
+ #text(code, values) {
1742
+ return moduleMessage(this.#policy, code, values);
1743
+ }
1744
+ #virtualId(specifier, from) {
1745
+ return `virtual:${isBareSpecifier(specifier) ? specifier : resolve(dirname(from), specifier)}`;
1746
+ }
1747
+ /** Resolves a registration's target to the id the loader will ask about. */
1748
+ #identify(specifier, from, virtual, spec) {
1749
+ if (isCoreSpecifier(specifier)) return [`node:${coreName(specifier)}`];
1750
+ const resolve = (kind) => this.#options.resolver.resolve(specifier, {
1751
+ importer: from,
1752
+ kind,
1753
+ conditions: this.#options.conditions ?? []
1754
+ });
1755
+ const result = resolve(this.#policy.mockResolveKind);
1756
+ switch (result.type) {
1757
+ case "file": {
1758
+ const targets = [result.path];
1759
+ if (!isBareSpecifier(specifier)) return targets;
1760
+ for (const kind of ["import", "require"]) {
1761
+ const other = resolve(kind);
1762
+ if (other.type === "file" && !targets.includes(other.path)) targets.push(other.path);
1763
+ }
1764
+ return targets;
1765
+ }
1766
+ case "builtin": return [result.id];
1767
+ case "virtual": return [`virtual:${specifier}`];
1768
+ case "not-found":
1769
+ if (!(virtual || !this.#policy.requireVirtualFlag || this.#policy.rootMocksAutoApply && isBareSpecifier(specifier) && this.#rootMocks.find(specifier) !== null)) throw new MockError("module-missing", this.#text(spec.kind === "unmock" ? "unmock-module-missing" : "module-missing", {
1770
+ specifier,
1771
+ from: this.#displayPath(from)
1772
+ }));
1773
+ return [this.#virtualId(specifier, from)];
1774
+ }
1775
+ }
1776
+ /** The importer relative to the first root, with `/` separators and `.` for the root itself. */
1777
+ #displayPath(from) {
1778
+ const root = this.#options.roots[0];
1779
+ const shown = root === void 0 ? from : relative(root, from);
1780
+ return shown === "" ? "." : shown.split(sep).join("/");
1781
+ }
1782
+ #unmockedByPattern(path) {
1783
+ for (const pattern of this.#policy.unmockedPathPatterns) {
1784
+ pattern.lastIndex = 0;
1785
+ if (pattern.test(path)) return true;
1786
+ }
1787
+ return false;
1788
+ }
1789
+ #chains() {
1790
+ this.#inside ??= new AsyncLocalStorage();
1791
+ return this.#inside;
1792
+ }
1793
+ /** Remembers the specifier `decide` was given for `id`: a bare one wins over a relative one. */
1794
+ #noteSpecifier(id, specifier) {
1795
+ if (specifier === void 0) return;
1796
+ const known = this.#specifiers.get(id);
1797
+ if (known === void 0 || !isBareSpecifier(known) && isBareSpecifier(specifier)) this.#specifiers.set(id, specifier);
1798
+ }
1799
+ /** A manual mock for `id`, by the entry's specifier or, with no entry, the package its path is in. */
1800
+ #manualFor(id, entry) {
1801
+ const cached = this.#manual.get(id);
1802
+ if (cached !== void 0) return cached;
1803
+ const name = entry?.specifier ?? this.#specifiers.get(id) ?? packageNameOf(id) ?? id;
1804
+ const found = this.#rootMocks.find(name) ?? (isAbsolute(id) && !isCoreSpecifier(name) ? findAdjacentMock(id) : null);
1805
+ this.#manual.set(id, found);
1806
+ return found;
1807
+ }
1808
+ #create(id) {
1809
+ const entry = this.#entries.get(id);
1810
+ if (entry === void 0) {
1811
+ const manual = this.#manualFor(id, void 0);
1812
+ if (manual !== null) return this.#options.loadActual(manual.path, "");
1813
+ return this.#automockOf(id, "", false);
1814
+ }
1815
+ const spec = entry.spec;
1816
+ switch (spec.kind) {
1817
+ case "factory": return this.#runFactory(id, entry, spec.factory);
1818
+ case "redirect": return this.#options.loadActual(spec.to, entry.from);
1819
+ case "automock":
1820
+ if (!spec.spy) {
1821
+ const manual = this.#manualFor(id, entry);
1822
+ if (manual !== null) return this.#options.loadActual(manual.path, entry.from);
1823
+ }
1824
+ return this.#automockOf(id, entry.from, spec.spy);
1825
+ case "unmock": return this.#options.loadActual(id, entry.from);
1826
+ }
1827
+ }
1828
+ #automockOf(id, from, spy) {
1829
+ const options = this.#options;
1830
+ const build = (actual) => {
1831
+ try {
1832
+ let mock = automock(actual, this.#policy.automockShape, spy ? "autospy" : "automock", (o) => createMockFn(options.mockPolicy, options.mocks, o));
1833
+ for (const callback of this.#onGenerate) mock = callback(id, mock);
1834
+ return mock;
1835
+ } catch (error) {
1836
+ if (error instanceof MockError && error.code === "automock-no-metadata") throw new MockError(error.code, this.#text("automock-no-metadata", { id }));
1837
+ throw error;
1838
+ }
1839
+ };
1840
+ if (this.#automocking.has(id)) return build({});
1841
+ this.#automocking.add(id);
1842
+ let actual;
1843
+ try {
1844
+ actual = this.#scratch(() => options.loadActual(id, from, { scratch: true }));
1845
+ } catch (error) {
1846
+ this.#automocking.delete(id);
1847
+ throw error;
1848
+ }
1849
+ if (!isThenable(actual)) {
1850
+ this.#automocking.delete(id);
1851
+ return build(actual);
1852
+ }
1853
+ return Promise.resolve(actual).finally(() => {
1854
+ this.#automocking.delete(id);
1855
+ }).then(build);
1856
+ }
1857
+ /**
1858
+ * Runs automock's real load with fresh mock values, as Jest's `_generateMock` swaps its mock
1859
+ * registry with its module registry (the loader swaps the module instances for a scratch load).
1860
+ * A mocked dependency of the real module is built again inside and dropped. Only the
1861
+ * synchronous part runs inside: an async load (`actual: 'async-import'`) shares the values
1862
+ * after its first await, as Vitest's automock loads its dependencies normally.
1863
+ */
1864
+ #scratch(load) {
1865
+ const values = this.#values;
1866
+ const overlay = this.#overlay;
1867
+ this.#values = /* @__PURE__ */ new Map();
1868
+ this.#overlay = null;
1869
+ try {
1870
+ return load();
1871
+ } finally {
1872
+ this.#values = values;
1873
+ this.#overlay = overlay;
1874
+ }
1875
+ }
1876
+ /** The id `specifier` names from `from`, as a registration resolves it, or a virtual or root-mocked one. */
1877
+ #idFor(specifier, from) {
1878
+ if (isCoreSpecifier(specifier)) return `node:${coreName(specifier)}`;
1879
+ const result = this.#options.resolver.resolve(specifier, {
1880
+ importer: from,
1881
+ kind: this.#policy.mockResolveKind,
1882
+ conditions: this.#options.conditions ?? []
1883
+ });
1884
+ if (result.type === "file") return result.path;
1885
+ if (result.type === "builtin") return result.id;
1886
+ const found = this.decideUnresolved(specifier, from);
1887
+ if (found.mocked) return found.id;
1888
+ throw new MockError("module-missing", this.#text("unmock-module-missing", {
1889
+ specifier,
1890
+ from: this.#displayPath(from)
1891
+ }));
1892
+ }
1893
+ #runFactory(id, entry, factory) {
1894
+ const importOriginal = () => new Promise((done) => {
1895
+ done(this.#options.loadActual(id, entry.from));
1896
+ });
1897
+ const wrap = this.#policy.messages["factory-error"];
1898
+ const helpful = (cause) => wrap === void 0 ? cause : new Error(wrap, { cause });
1899
+ let result;
1900
+ try {
1901
+ const inside = this.#chains();
1902
+ const chain = new Set(inside.getStore());
1903
+ chain.add(id);
1904
+ result = inside.run(chain, () => factory(importOriginal));
1905
+ } catch (error) {
1906
+ if (this.#policy.awaitFactory) return Promise.reject(helpful(error));
1907
+ throw helpful(error);
1908
+ }
1909
+ if (this.#policy.awaitFactory) return Promise.resolve(result).then((value) => this.#shape(value, entry), (error) => {
1910
+ throw helpful(error);
1911
+ });
1912
+ return this.#shape(result, entry);
1913
+ }
1914
+ /** `factoryShape` and `missingFactoryExport`: what the consumer sees of the factory's result. */
1915
+ #shape(value, entry) {
1916
+ const policy = this.#policy;
1917
+ if (policy.factoryShape === "namespace" && (value === null || typeof value !== "object" || Array.isArray(value))) throw new MockTypeError("factory-not-object", this.#text("factory-not-object", { raw: entry.specifier }));
1918
+ if (policy.missingFactoryExport !== "throw" || !isObjectLike(value) || isThenable(value)) return value;
1919
+ const raw = entry.specifier;
1920
+ return new Proxy(value, { get: (target, prop, receiver) => {
1921
+ if (prop in target || prop === "then" || prop === "__esModule") return Reflect.get(target, prop, receiver);
1922
+ if (typeof prop === "symbol" && PUBLIC_SYMBOLS.has(prop)) return void 0;
1923
+ throw new MockError("missing-factory-export", this.#text("missing-factory-export", {
1924
+ name: String(prop),
1925
+ raw
1926
+ }));
1927
+ } });
1928
+ }
1929
+ };
1930
+ /**
1931
+ * Creates a test file's module-mock registry. It never imports a dialect: every difference between
1932
+ * Jest and Vitest is a key of `options.policy`.
1933
+ * @public
1934
+ */
1935
+ function createModuleMockRegistry(options) {
1936
+ return new Registry$1(options);
1937
+ }
1938
+
1939
+ // src/registry.ts
1940
+ var Registry = class {
1941
+ resets = 0;
1942
+ order = 1;
1943
+ dirtyStates = /* @__PURE__ */ new Set();
1944
+ dirtyConfigs = /* @__PURE__ */ new Set();
1945
+ restorers = /* @__PURE__ */ new Set();
1946
+ stubs = /* @__PURE__ */ new Set();
1947
+ nextInvocationOrder() {
1948
+ return this.order++;
1949
+ }
1950
+ markStateDirty(mock) {
1951
+ mock.stateDirty = true;
1952
+ this.dirtyStates.add(refOf(mock));
1953
+ }
1954
+ markConfigDirty(mock) {
1955
+ mock.configDirty = true;
1956
+ this.dirtyConfigs.add(refOf(mock));
1957
+ }
1958
+ clearAll() {
1959
+ for (const ref of this.dirtyStates) {
1960
+ const mock = ref.deref();
1961
+ if (mock === void 0) continue;
1962
+ mock.stateDirty = false;
1963
+ mock.clearState();
1964
+ }
1965
+ this.dirtyStates.clear();
1966
+ }
1967
+ resetAll() {
1968
+ this.resets++;
1969
+ for (const dirty of [this.dirtyStates, this.dirtyConfigs]) {
1970
+ for (const ref of dirty) {
1971
+ const mock = ref.deref();
1972
+ if (mock === void 0 || !mock.stateDirty && !mock.configDirty) continue;
1973
+ mock.stateDirty = false;
1974
+ mock.configDirty = false;
1975
+ mock.resetMock();
1976
+ }
1977
+ dirty.clear();
1978
+ }
1979
+ }
1980
+ restoreAll() {
1981
+ const restorers = [...this.restorers];
1982
+ this.restorers.clear();
1983
+ runAll(restorers);
1984
+ }
1985
+ beforeEach(cfg, between) {
1986
+ for (const step of between.order) {
1987
+ if (!(cfg[step] ?? between[step])) continue;
1988
+ switch (step) {
1989
+ case "clear":
1990
+ this.clearAll();
1991
+ break;
1992
+ case "reset":
1993
+ this.resetAll();
1994
+ break;
1995
+ case "restore":
1996
+ this.restoreAll();
1997
+ break;
1998
+ case "unstubEnvs":
1999
+ for (const stubs of this.stubs) stubs.unstubAllEnvs();
2000
+ break;
2001
+ case "unstubGlobals": for (const stubs of this.stubs) stubs.unstubAllGlobals();
2002
+ }
2003
+ }
2004
+ }
2005
+ dispose() {
2006
+ const steps = [...this.restorers];
2007
+ for (const stubs of this.stubs) steps.push(() => stubs.unstubAllEnvs(), () => stubs.unstubAllGlobals());
2008
+ this.restorers.clear();
2009
+ this.stubs.clear();
2010
+ this.dirtyStates.clear();
2011
+ this.dirtyConfigs.clear();
2012
+ runAll(steps);
2013
+ }
2014
+ addRestorer(restorer) {
2015
+ this.restorers.add(restorer);
2016
+ }
2017
+ deleteRestorer(restorer) {
2018
+ this.restorers.delete(restorer);
2019
+ }
2020
+ findRestorer(object, property) {
2021
+ for (const restorer of this.restorers) if (restorer.object === object && restorer.property === property) return restorer;
2022
+ }
2023
+ addStubs(stubs) {
2024
+ this.stubs.add(stubs);
2025
+ }
2026
+ dirtyCounts() {
2027
+ return {
2028
+ state: this.dirtyStates.size,
2029
+ config: this.dirtyConfigs.size
2030
+ };
2031
+ }
2032
+ };
2033
+ function refOf(mock) {
2034
+ if (mock.ref === null) mock.ref = new WeakRef(mock);
2035
+ return mock.ref;
2036
+ }
2037
+ /** Runs every step even when one throws, so one bad restorer can't leak the rest; then rethrows. */
2038
+ function runAll(steps) {
2039
+ const errors = [];
2040
+ for (const step of steps) try {
2041
+ step();
2042
+ } catch (error) {
2043
+ errors.push(error);
2044
+ }
2045
+ if (errors.length === 1) throw errors[0];
2046
+ if (errors.length > 1) throw new AggregateError(errors, "Several mock restorers threw");
2047
+ }
2048
+ /**
2049
+ * A new registry, one per test file. The first invocation order it hands out is 1.
2050
+ * @public
2051
+ */
2052
+ function createMockRegistry() {
2053
+ return new Registry();
2054
+ }
2055
+
2056
+ // src/spy.ts
2057
+ /** `MOCK_SPY_MISSING` for `spy-missing`: an error's stable code comes from its message's. */
2058
+ function errorCode(code) {
2059
+ return `MOCK_${code.toUpperCase().replaceAll("-", "_")}`;
2060
+ }
2061
+ function text(policy, code, key, type) {
2062
+ return messageFor(policy, code, {
2063
+ key: String(key),
2064
+ type
2065
+ });
2066
+ }
2067
+ function fail(policy, code, key, type = "") {
2068
+ throw new MockError(errorCode(code), text(policy, code, key, type));
2069
+ }
2070
+ function failType(policy, code, key, type) {
2071
+ throw new MockTypeError(errorCode(code), text(policy, code, key, type));
2072
+ }
2073
+ function typeOf(value) {
2074
+ return value === null || value === void 0 ? `${value}` : typeof value;
2075
+ }
2076
+ /**
2077
+ * The property's descriptor, from the object or the nearest prototype that has it. A mock's methods
2078
+ * are accessors on a frozen prototype only as an implementation detail: to a spy they are the plain
2079
+ * inherited methods they stand for, and copying that accessor would install a non-configurable one.
2080
+ */
2081
+ function findDescriptor(object, key) {
2082
+ let current = object;
2083
+ while (current !== null) {
2084
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
2085
+ if (descriptor?.get !== void 0 && current !== object && Object.hasOwn(current, MOCK_BRAND)) return {
2086
+ value: Reflect.get(object, key),
2087
+ writable: true,
2088
+ enumerable: true,
2089
+ configurable: true
2090
+ };
2091
+ if (descriptor !== void 0) return descriptor;
2092
+ current = Object.getPrototypeOf(current);
2093
+ }
2094
+ }
2095
+ /** An own property gets its descriptor back; one that was inherited is deleted. */
2096
+ function putBackDescriptor(isOwner, subject, key, descriptor) {
2097
+ if (isOwner && descriptor !== void 0) Object.defineProperty(subject, key, descriptor);
2098
+ else Reflect.deleteProperty(subject, key);
2099
+ }
2100
+ /** An own property gets its value assigned back; one that was inherited is deleted. */
2101
+ function putBackValue(isOwner, target, key, value) {
2102
+ if (isOwner) target[key] = value;
2103
+ else delete target[key];
2104
+ }
2105
+ function makeSpy(policy, registry, original, restore) {
2106
+ return createMockFn(policy, registry, {
2107
+ spy: true,
2108
+ original,
2109
+ restore
2110
+ });
2111
+ }
2112
+ /** Install first, then register, so a failed install leaves nothing to restore (DV7). */
2113
+ function install(registry, spy, restore, run) {
2114
+ run();
2115
+ registry.addRestorer(restore);
2116
+ return spy;
2117
+ }
2118
+ function spyAssign(policy, registry, subject, key, access) {
2119
+ if (!isObjectLike(subject)) fail(policy, "spy-primitive", key, typeOf(subject));
2120
+ if (key === null || key === void 0) fail(policy, "spy-no-key");
2121
+ if (access !== void 0) return spyAssignAccessor(policy, registry, subject, key, access);
2122
+ const target = subject;
2123
+ const original = target[key];
2124
+ if (!original) fail(policy, "spy-missing", key);
2125
+ if (isMockFunction(policy, original)) return original;
2126
+ if (typeof original !== "function") failType(policy, typeof original === "object" ? "spy-not-a-function" : "spy-not-a-function-primitive", key, typeOf(original));
2127
+ const isOwner = Object.hasOwn(subject, key);
2128
+ const descriptor = findDescriptor(subject, key);
2129
+ if (descriptor?.get !== void 0) {
2130
+ const installed = { ...descriptor };
2131
+ const restore = () => putBackDescriptor(isOwner, subject, key, descriptor);
2132
+ const spy = makeSpy(policy, registry, original, restore);
2133
+ installed.get = () => spy;
2134
+ return install(registry, spy, restore, () => Object.defineProperty(subject, key, installed));
2135
+ }
2136
+ const restore = () => putBackValue(isOwner, target, key, original);
2137
+ const spy = makeSpy(policy, registry, original, restore);
2138
+ return install(registry, spy, restore, () => {
2139
+ try {
2140
+ target[key] = spy;
2141
+ } catch (error) {
2142
+ throw readOnlyError(policy, subject, key, error);
2143
+ }
2144
+ });
2145
+ }
2146
+ /**
2147
+ * V8's error for assigning to a read-only property names the object, and how it does depends on the
2148
+ * realm the assignment runs in. A policy recorded from another realm gives the text as
2149
+ * `spy-read-only`, with `{tag}` as `Object.prototype.toString` has it. Without one, or for any other
2150
+ * error, the original goes through.
2151
+ */
2152
+ function readOnlyError(policy, subject, key, error) {
2153
+ const message = policy.messages["spy-read-only"];
2154
+ if (message === void 0) return error;
2155
+ if (!(error instanceof TypeError)) return error;
2156
+ if (!error.message.startsWith("Cannot assign to read only property")) return error;
2157
+ const tag = Object.prototype.toString.call(subject);
2158
+ return new MockTypeError("MOCK_SPY_READ_ONLY", fill(message, {
2159
+ key: String(key),
2160
+ tag
2161
+ }), { cause: error });
2162
+ }
2163
+ function spyAssignAccessor(policy, registry, subject, key, access) {
2164
+ const isOwner = Object.hasOwn(subject, key);
2165
+ const descriptor = findDescriptor(subject, key);
2166
+ if (descriptor === void 0) fail(policy, "spy-missing", key);
2167
+ if (!descriptor.configurable) fail(policy, "spy-not-configurable", key);
2168
+ const original = descriptor[access];
2169
+ if (original === void 0) fail(policy, "spy-no-access-type", key, access);
2170
+ if (isMockFunction(policy, original)) return original;
2171
+ const restore = () => putBackDescriptor(isOwner, subject, key, descriptor);
2172
+ const spy = makeSpy(policy, registry, original, restore);
2173
+ return install(registry, spy, restore, () => Object.defineProperty(subject, key, {
2174
+ ...descriptor,
2175
+ [access]: spy
2176
+ }));
2177
+ }
2178
+ function spyDefine(policy, registry, subject, key, access) {
2179
+ if (subject === null || subject === void 0) fail(policy, "spy-nullish");
2180
+ if (!isObjectLike(subject)) fail(policy, "spy-define-primitive");
2181
+ const isOwner = Object.hasOwn(subject, key);
2182
+ const descriptor = findDescriptor(subject, key);
2183
+ if (descriptor === void 0 && !(key in subject)) fail(policy, "spy-define-missing", key, typeof subject);
2184
+ const target = subject;
2185
+ let slot = access ?? "value";
2186
+ let ssr = false;
2187
+ if (slot === "value" && descriptor?.value == null && descriptor?.get !== void 0) {
2188
+ slot = "get";
2189
+ ssr = true;
2190
+ }
2191
+ let original;
2192
+ if (descriptor !== void 0) {
2193
+ original = descriptor[slot];
2194
+ if (original == null && slot === "value") original = target[key];
2195
+ } else if (slot !== "value") original = () => target[key];
2196
+ else original = target[key];
2197
+ const implementation = ssr && typeof original === "function" ? original() : original;
2198
+ if (typeof implementation !== "function" && (slot === "value" || original != null)) fail(policy, "spy-define-not-a-function", key, typeof implementation);
2199
+ if (isMockFunction(policy, implementation)) return implementation;
2200
+ const define = (value) => {
2201
+ const { value: _replaced, ...rest } = descriptor ?? {
2202
+ configurable: true,
2203
+ writable: true
2204
+ };
2205
+ if (slot !== "value") delete rest.writable;
2206
+ Object.defineProperty(subject, key, {
2207
+ ...rest,
2208
+ [slot]: value
2209
+ });
2210
+ };
2211
+ const restore = () => {
2212
+ if (!isOwner || descriptor !== void 0 && !original) putBackDescriptor(isOwner, subject, key, descriptor);
2213
+ else define(original);
2214
+ };
2215
+ const spy = makeSpy(policy, registry, implementation, restore);
2216
+ return install(registry, spy, restore, () => {
2217
+ try {
2218
+ define(ssr ? () => spy : spy);
2219
+ } catch (error) {
2220
+ if (error instanceof TypeError && isNamespaceRefusal(subject, error)) throw new MockTypeError(errorCode("spy-namespace"), text(policy, "spy-namespace", key, ""), { cause: error });
2221
+ throw error;
2222
+ }
2223
+ });
2224
+ }
2225
+ function isNamespaceRefusal(subject, error) {
2226
+ return subject[Symbol.toStringTag] === "Module" && (error.message.includes("Cannot redefine property") || error.message.includes("Cannot replace module namespace"));
2227
+ }
2228
+ function spyOn(policy, registry, object, key, access) {
2229
+ return policy.spyInstall === "assign" ? spyAssign(policy, registry, object, key, access) : spyDefine(policy, registry, object, key, access);
2230
+ }
2231
+ /**
2232
+ * Replaces a plain value property until `restore` or the registry's `restoreAll`. Follows
2233
+ * jest-mock's `replaceProperty` (index.ts L1448-L1558), but, like `spyOn`, registers its restorer
2234
+ * only after the first write has worked.
2235
+ * @public
2236
+ */
2237
+ function replaceProperty(policy, registry, object, key, value) {
2238
+ if (!isObjectLike(object)) fail(policy, "replace-primitive", key, typeOf(object));
2239
+ if (key === null || key === void 0) fail(policy, "replace-no-key");
2240
+ const descriptor = findDescriptor(object, key);
2241
+ if (descriptor === void 0) fail(policy, "replace-missing", key);
2242
+ if (!descriptor.configurable) fail(policy, "replace-not-configurable", key);
2243
+ if (descriptor.get !== void 0) fail(policy, "replace-getter", key);
2244
+ if (descriptor.set !== void 0) fail(policy, "replace-setter", key);
2245
+ if (typeof descriptor.value === "function") failType(policy, "replace-function", key, "");
2246
+ const existing = registry.findRestorer(object, key);
2247
+ if (existing !== void 0) return existing.replaced.replaceValue(value);
2248
+ const isOwner = Object.hasOwn(object, key);
2249
+ const originalValue = descriptor.value;
2250
+ const restorer = () => putBackValue(isOwner, object, key, originalValue);
2251
+ const replaced = {
2252
+ replaceValue(next) {
2253
+ object[key] = next;
2254
+ return replaced;
2255
+ },
2256
+ restore() {
2257
+ restorer();
2258
+ registry.deleteRestorer(restorer);
2259
+ }
2260
+ };
2261
+ restorer.object = object;
2262
+ restorer.property = key;
2263
+ restorer.replaced = replaced;
2264
+ replaced.replaceValue(value);
2265
+ registry.addRestorer(restorer);
2266
+ return replaced;
2267
+ }
2268
+
2269
+ // src/stubs.ts
2270
+ /**
2271
+ * The stubs for one test file. `env` is the object to stub variables on and `global` the
2272
+ * environment's global; the registry's between-test `unstub*` steps and `dispose` reach them.
2273
+ * @public
2274
+ */
2275
+ function createStubs(registry, env, global = globalThis) {
2276
+ const stubbedEnv = /* @__PURE__ */ new Map();
2277
+ const stubbedGlobals = /* @__PURE__ */ new Map();
2278
+ const stubs = {
2279
+ stubEnv(name, value) {
2280
+ if (!stubbedEnv.has(name)) stubbedEnv.set(name, env[name]);
2281
+ if (value === void 0) delete env[name];
2282
+ else env[name] = String(value);
2283
+ return stubs;
2284
+ },
2285
+ stubGlobal(name, value) {
2286
+ if (!stubbedGlobals.has(name)) stubbedGlobals.set(name, Object.getOwnPropertyDescriptor(global, name));
2287
+ Object.defineProperty(global, name, {
2288
+ value,
2289
+ writable: true,
2290
+ configurable: true,
2291
+ enumerable: true
2292
+ });
2293
+ return stubs;
2294
+ },
2295
+ unstubAllEnvs() {
2296
+ for (const [name, original] of stubbedEnv) if (original === void 0) delete env[name];
2297
+ else env[name] = original;
2298
+ stubbedEnv.clear();
2299
+ return stubs;
2300
+ },
2301
+ unstubAllGlobals() {
2302
+ for (const [name, original] of stubbedGlobals) if (original === void 0) Reflect.deleteProperty(global, name);
2303
+ else Object.defineProperty(global, name, original);
2304
+ stubbedGlobals.clear();
2305
+ return stubs;
2306
+ }
2307
+ };
2308
+ registry.addStubs(stubs);
2309
+ return stubs;
2310
+ }
2311
+
2312
+ export { MOCK_BRAND, MockError, MockTypeError, automock, createMockFn, createMockRegistry, createModuleMockRegistry, createRootMockIndex, createStubs, findManualMock, isMockFunction, replaceProperty, spyOn };