vitest 5.0.5 → 5.1.0-beta.1

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 (52) hide show
  1. package/LICENSE.md +1 -1
  2. package/dist/browser.d.ts +4 -4
  3. package/dist/browser.js +3 -3
  4. package/dist/chunks/{base.CzXt2BO_.js → base.PJyN9N0u.js} +12 -11
  5. package/dist/chunks/{browser.d.FGQ9_rK6.d.ts → browser.d.D7a15z82.d.ts} +4 -3
  6. package/dist/chunks/{cac.CLrZKo1g.js → cac.Ccf5Je_F.js} +21 -9
  7. package/dist/chunks/{cli-api.De07GUeT.js → cli-api.DE22LIzq.js} +3091 -2891
  8. package/dist/chunks/{config.d.QBNYCgFU.d.ts → config.d.BgktgHfG.d.ts} +134 -93
  9. package/dist/chunks/{console.DtI4yxfN.js → console.DrMPSuFo.js} +5 -2
  10. package/dist/chunks/{constants.-juJ8b_4.js → constants.DLYM6cZY.js} +1 -1
  11. package/dist/chunks/{creator.C5g4egeG.js → creator.BQ3onxbh.js} +5 -5
  12. package/dist/chunks/{doctor.BK86Cncq.js → doctor.CPlMs7-y.js} +1 -1
  13. package/dist/chunks/{environment.d.BY56MoGs.d.ts → environment.d.CbTLsZSj.d.ts} +1 -1
  14. package/dist/chunks/{globals.CXEE6_2C.js → globals.TipXUFcZ.js} +5 -5
  15. package/dist/chunks/{index.CoUIxZd4.js → index.B03wg4V0.js} +3 -3
  16. package/dist/chunks/{index.CK-t0WMg.js → index.BFXLpwll.js} +114 -37
  17. package/dist/chunks/{index.aTZaPVhf.js → index.BXttT2gP.js} +37 -18
  18. package/dist/chunks/{index.1TqnEahn.js → index.D14IAvnE.js} +43 -17
  19. package/dist/chunks/{init-forks.CRxIPOJR.js → init-forks.BL1E3__4.js} +1 -1
  20. package/dist/chunks/{init-threads.Dv3kwST_.js → init-threads.CYXAGzKQ.js} +1 -1
  21. package/dist/chunks/{init.PvxYpuCm.js → init.DVorxUyL.js} +3 -3
  22. package/dist/chunks/{nativeModuleMocker.BxrHJNAF.js → nativeModuleMocker.3uBcOd84.js} +2 -1
  23. package/dist/chunks/{plugin.d.C8mmycim.d.ts → plugin.d.olEn8IL9.d.ts} +108 -20
  24. package/dist/chunks/{rpc.DpkUyY1N.js → rpc.BV0XpJ5q.js} +1 -1
  25. package/dist/chunks/{rpc.d.Cft1biqy.d.ts → rpc.d.DGFP7vWr.d.ts} +1 -1
  26. package/dist/chunks/{run.BPv-BBRv.js → run.BfrMbGVD.js} +22 -4
  27. package/dist/chunks/{setup-common.HGAqWOnX.js → setup-common.llxJkJaD.js} +2 -2
  28. package/dist/chunks/{source-map.DdKI5IHB.js → source-map.BjWcsIL9.js} +32 -24
  29. package/dist/chunks/{source-map.d.kzFtk_dj.d.ts → source-map.d.C5A_Tr6V.d.ts} +2 -1
  30. package/dist/chunks/{task-utils.d.PFh2BV6Q.d.ts → task-utils.d.BUh7ylUT.d.ts} +2 -1
  31. package/dist/chunks/{vm.FGl2rw_t.js → vm.Cwj01UFE.js} +16 -5
  32. package/dist/chunks/{worker.d.BH-r1bPu.d.ts → worker.d.gsA26mmR.d.ts} +3 -3
  33. package/dist/cli.js +2 -2
  34. package/dist/config.cjs +1 -1
  35. package/dist/config.d.ts +11 -11
  36. package/dist/config.js +1 -1
  37. package/dist/index.d.ts +14 -13
  38. package/dist/index.js +4 -4
  39. package/dist/module-evaluator.d.ts +3 -2
  40. package/dist/node.d.ts +29 -11
  41. package/dist/node.js +7 -7
  42. package/dist/runtime.d.ts +4 -4
  43. package/dist/runtime.js +3 -2
  44. package/dist/task-utils.js +3 -1
  45. package/dist/worker.d.ts +4 -4
  46. package/dist/worker.js +9 -9
  47. package/dist/workers/forks.js +10 -10
  48. package/dist/workers/runVmTests.js +9 -8
  49. package/dist/workers/threads.js +10 -10
  50. package/dist/workers/vmForks.js +9 -8
  51. package/dist/workers/vmThreads.js +9 -8
  52. package/package.json +14 -14
@@ -1,93 +1,7 @@
1
+ /// <reference types="chai" />
1
2
  import { Disposable } from 'vitest/optional-runtime-types.js';
2
3
  import { Fn, FnOptions, BenchOptions as BenchOptions$1, TaskResultCompleted, TaskResultRuntimeInfo, TaskResultTimestampProviderInfo, Statistics } from 'tinybench';
3
4
 
4
- type VoidVarArgsFunc = (...args: unknown[]) => void;
5
- type SetImmediate = (callback: VoidVarArgsFunc, ...args: unknown[]) => NodeImmediate;
6
- type SetTimeout = (callback: VoidVarArgsFunc, delay?: number, ...args: unknown[]) => TimerId;
7
- type ClearTimeout = (id?: TimerId) => void;
8
- type SetInterval = (callback: VoidVarArgsFunc, delay?: number, ...args: unknown[]) => TimerId;
9
- type ClearInterval = (id?: TimerId) => void;
10
- type QueueMicrotask = (callback: VoidVarArgsFunc) => void;
11
- type TimeRemaining = () => number;
12
- type IdleDeadline = {
13
- didTimeout: boolean;
14
- timeRemaining: TimeRemaining;
15
- };
16
- type RequestIdleCallbackCallback = (deadline: IdleDeadline) => any;
17
- type RequestIdleCallback = (callback: RequestIdleCallbackCallback, options?: {
18
- timeout?: number;
19
- }) => number;
20
- type AnimationFrameCallback = (timestamp: number) => any;
21
- type RequestAnimationFrame = (callback: AnimationFrameCallback) => TimerId;
22
- type CancelAnimationFrame = (id: TimerId) => void;
23
- type CancelIdleCallback = (id: TimerId) => void;
24
- type ClearImmediate = (id: NodeImmediate) => void;
25
- type TemporalTimelike = {
26
- epochMilliseconds: number;
27
- };
28
- type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date" | "nextTick" | "hrtime" | "requestAnimationFrame" | "cancelAnimationFrame" | "requestIdleCallback" | "cancelIdleCallback" | "performance" | "queueMicrotask" | "Intl" | "Temporal";
29
- type TimerId = number | NodeImmediate | Timer;
30
- type GlobalObject = Record<string, any> & {
31
- setTimeout?: SetTimeout;
32
- clearTimeout?: ClearTimeout;
33
- setInterval?: SetInterval;
34
- clearInterval?: ClearInterval;
35
- setImmediate?: SetImmediate;
36
- clearImmediate?: ClearImmediate;
37
- queueMicrotask?: QueueMicrotask;
38
- requestAnimationFrame?: RequestAnimationFrame;
39
- cancelAnimationFrame?: CancelAnimationFrame;
40
- requestIdleCallback?: RequestIdleCallback;
41
- cancelIdleCallback?: CancelIdleCallback;
42
- process?: any;
43
- performance?: any;
44
- Performance?: any;
45
- Intl?: any;
46
- Temporal?: any;
47
- Promise?: typeof Promise;
48
- Date: typeof Date & {
49
- isFake?: boolean;
50
- toSource?: () => string;
51
- clock?: any;
52
- };
53
- };
54
- type TimerInitialProps = {
55
- func: VoidVarArgsFunc;
56
- args?: unknown[];
57
- type?: 'Timeout' | 'Interval' | 'Immediate' | 'AnimationFrame' | 'IdleCallback';
58
- delay?: number;
59
- callAt?: number;
60
- createdAt?: number;
61
- immediate?: boolean;
62
- id?: number;
63
- error?: Error;
64
- interval?: number;
65
- animation?: boolean;
66
- requestIdleCallback?: boolean;
67
- order?: number;
68
- heapIndex?: number;
69
- };
70
- type Config$1 = {
71
- now?: number | Date | TemporalTimelike;
72
- toFake?: FakeMethod[];
73
- toNotFake?: FakeMethod[];
74
- loopLimit?: number;
75
- shouldAdvanceTime?: boolean;
76
- advanceTimeDelta?: number;
77
- shouldClearNativeTimers?: boolean;
78
- ignoreMissingTimers?: boolean;
79
- target?: GlobalObject;
80
- };
81
- type Timer = TimerInitialProps;
82
- type NodeImmediateHasRef = () => boolean;
83
- type NodeImmediateRef = () => NodeImmediate;
84
- type NodeImmediateUnref = () => NodeImmediate;
85
- type NodeImmediate = {
86
- hasRef: NodeImmediateHasRef;
87
- ref: NodeImmediateRef;
88
- unref: NodeImmediateUnref;
89
- };
90
-
91
5
  /**
92
6
  * Copyright (c) Meta Platforms, Inc. and affiliates.
93
7
  *
@@ -250,7 +164,7 @@ interface PrettyFormatOptions {
250
164
  quoteKeys?: boolean;
251
165
  }
252
166
  type OptionsReceived = PrettyFormatOptions;
253
- interface Config {
167
+ interface Config$1 {
254
168
  callToJSON: boolean;
255
169
  compareKeys: CompareKeys;
256
170
  colors: Colors;
@@ -270,10 +184,10 @@ interface Config {
270
184
  quoteKeys: boolean;
271
185
  maxOutputLength: number;
272
186
  }
273
- type Printer = (val: unknown, config: Config, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean) => string;
187
+ type Printer = (val: unknown, config: Config$1, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean) => string;
274
188
  type Test$1 = (arg0: any) => boolean;
275
189
  interface NewPlugin {
276
- serialize: (val: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer) => string;
190
+ serialize: (val: any, config: Config$1, indentation: string, depth: number, refs: Refs, printer: Printer) => string;
277
191
  test: Test$1;
278
192
  }
279
193
  interface PluginOptions {
@@ -607,6 +521,109 @@ interface Memorize {
607
521
  declare function diff(a: any, b: any, options?: DiffOptions, memorize?: Memorize): string | undefined;
608
522
  declare function printDiffOrStringify(received: unknown, expected: unknown, options?: DiffOptions, memory?: StringifiedMemory): string | undefined;
609
523
 
524
+ type VoidVarArgsFunc = (...args: unknown[]) => void;
525
+ type SetImmediate = (callback: VoidVarArgsFunc, ...args: unknown[]) => NodeImmediate;
526
+ type SetTimeout = (callback: VoidVarArgsFunc, delay?: number, ...args: unknown[]) => TimerId;
527
+ type ClearTimeout = (id?: TimerId) => void;
528
+ type SetInterval = (callback: VoidVarArgsFunc, delay?: number, ...args: unknown[]) => TimerId;
529
+ type ClearInterval = (id?: TimerId) => void;
530
+ type QueueMicrotask = (callback: VoidVarArgsFunc) => void;
531
+ type TimeRemaining = () => number;
532
+ type IdleDeadline = {
533
+ didTimeout: boolean;
534
+ timeRemaining: TimeRemaining;
535
+ };
536
+ type RequestIdleCallbackCallback = (deadline: IdleDeadline) => any;
537
+ type RequestIdleCallback = (callback: RequestIdleCallbackCallback, options?: {
538
+ timeout?: number;
539
+ }) => number;
540
+ type AnimationFrameCallback = (timestamp: number) => any;
541
+ type RequestAnimationFrame = (callback: AnimationFrameCallback) => TimerId;
542
+ type CancelAnimationFrame = (id: TimerId) => void;
543
+ type CancelIdleCallback = (id: TimerId) => void;
544
+ type ClearImmediate = (id: NodeImmediate) => void;
545
+ type TemporalTimelike = {
546
+ epochMilliseconds: number;
547
+ };
548
+ type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date" | "nextTick" | "hrtime" | "requestAnimationFrame" | "cancelAnimationFrame" | "requestIdleCallback" | "cancelIdleCallback" | "performance" | "queueMicrotask" | "Intl" | "Temporal";
549
+ type TimerId = number | NodeImmediate | Timer;
550
+ type GlobalObject = Record<string, any> & {
551
+ setTimeout?: SetTimeout;
552
+ clearTimeout?: ClearTimeout;
553
+ setInterval?: SetInterval;
554
+ clearInterval?: ClearInterval;
555
+ setImmediate?: SetImmediate;
556
+ clearImmediate?: ClearImmediate;
557
+ queueMicrotask?: QueueMicrotask;
558
+ requestAnimationFrame?: RequestAnimationFrame;
559
+ cancelAnimationFrame?: CancelAnimationFrame;
560
+ requestIdleCallback?: RequestIdleCallback;
561
+ cancelIdleCallback?: CancelIdleCallback;
562
+ process?: any;
563
+ performance?: any;
564
+ Performance?: any;
565
+ Intl?: any;
566
+ Temporal?: any;
567
+ Promise?: typeof Promise;
568
+ Date: typeof Date & {
569
+ isFake?: boolean;
570
+ toSource?: () => string;
571
+ clock?: any;
572
+ };
573
+ };
574
+ type TimerInitialProps = {
575
+ func: VoidVarArgsFunc;
576
+ args?: unknown[];
577
+ type?: 'Timeout' | 'Interval' | 'Immediate' | 'AnimationFrame' | 'IdleCallback';
578
+ delay?: number;
579
+ callAt?: number;
580
+ createdAt?: number;
581
+ immediate?: boolean;
582
+ id?: number;
583
+ error?: Error;
584
+ interval?: number;
585
+ animation?: boolean;
586
+ requestIdleCallback?: boolean;
587
+ order?: number;
588
+ heapIndex?: number;
589
+ };
590
+ type Config = {
591
+ now?: number | Date | TemporalTimelike;
592
+ toFake?: FakeMethod[];
593
+ toNotFake?: FakeMethod[];
594
+ loopLimit?: number;
595
+ shouldAdvanceTime?: boolean;
596
+ advanceTimeDelta?: number;
597
+ shouldClearNativeTimers?: boolean;
598
+ ignoreMissingTimers?: boolean;
599
+ target?: GlobalObject;
600
+ };
601
+ type Timer = TimerInitialProps;
602
+ type NodeImmediateHasRef = () => boolean;
603
+ type NodeImmediateRef = () => NodeImmediate;
604
+ type NodeImmediateUnref = () => NodeImmediate;
605
+ type NodeImmediate = {
606
+ hasRef: NodeImmediateHasRef;
607
+ ref: NodeImmediateRef;
608
+ unref: NodeImmediateUnref;
609
+ };
610
+
611
+ /**
612
+ * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
613
+ *
614
+ * This source code is licensed under the MIT license found in the
615
+ * LICENSE file in the root directory of https://github.com/jestjs/jest.
616
+ */
617
+
618
+ interface FakeTimersConfig extends Config {
619
+ /**
620
+ * Mock timer APIs imported from `node:timers` and `node:timers/promises`.
621
+ *
622
+ * @default false
623
+ */
624
+ fakeNodeBuiltins?: boolean;
625
+ }
626
+
610
627
  interface AfterSuiteRunMeta {
611
628
  coverage?: unknown;
612
629
  testFiles: string[];
@@ -2429,6 +2446,23 @@ interface TaskMeta {
2429
2446
  __vitest_label__?: string;
2430
2447
  }
2431
2448
  /**
2449
+ * The result of an individual test attempt.
2450
+ */
2451
+ interface TaskResultAttempt {
2452
+ /** The state after applying the test's expected failure option. */
2453
+ state: "pass" | "fail" | "skip";
2454
+ /** Errors produced by this attempt. */
2455
+ errors?: TestError[];
2456
+ /** How long in milliseconds the attempt took to run. */
2457
+ duration: number;
2458
+ /** Time in milliseconds when the attempt started running. */
2459
+ startTime: number;
2460
+ /** The zero-based retry index within the repeat. */
2461
+ retryIndex: number;
2462
+ /** The zero-based repeat index. */
2463
+ repeatIndex: number;
2464
+ }
2465
+ /**
2432
2466
  * The result of calling a task.
2433
2467
  */
2434
2468
  interface TaskResult {
@@ -2445,6 +2479,10 @@ interface TaskResult {
2445
2479
  */
2446
2480
  errors?: TestError[];
2447
2481
  /**
2482
+ * Individual results for every retry and repeat attempt.
2483
+ */
2484
+ attempts?: TaskResultAttempt[];
2485
+ /**
2448
2486
  * How long in milliseconds the task took to run.
2449
2487
  */
2450
2488
  duration?: number;
@@ -3480,6 +3518,7 @@ interface FileSpecification {
3480
3518
  testNamePattern?: RegExp | undefined;
3481
3519
  testTagsFilter?: string[] | undefined;
3482
3520
  testIds?: string[] | undefined;
3521
+ testNames?: string[] | undefined;
3483
3522
  }
3484
3523
  type VitestRunnerImportSource = "collect" | "setup";
3485
3524
  type CancelReason = "keyboard-input" | "test-failure" | (string & Record<string, never>);
@@ -3655,7 +3694,7 @@ interface SerializedConfig {
3655
3694
  restoreMocks: boolean;
3656
3695
  unstubGlobals: boolean;
3657
3696
  unstubEnvs: boolean;
3658
- fakeTimers: Config$1;
3697
+ fakeTimers: FakeTimersConfig;
3659
3698
  defines: Record<string, any>;
3660
3699
  expect: {
3661
3700
  requireAssertions?: boolean;
@@ -3731,8 +3770,10 @@ interface SerializedConfig {
3731
3770
  enabled: boolean;
3732
3771
  recordCanvas: boolean;
3733
3772
  inlineImages: boolean;
3773
+ ariaSnapshot: boolean;
3734
3774
  };
3735
3775
  trackUnhandledErrors: boolean;
3776
+ importMapMocks: boolean | undefined;
3736
3777
  detailsPanelPosition: "right" | "bottom";
3737
3778
  };
3738
3779
  standalone: boolean;
@@ -3793,5 +3834,5 @@ type RuntimeConfig = Pick<SerializedConfig, "allowOnly" | "testTimeout" | "hookT
3793
3834
  type RuntimeOptions = Partial<RuntimeConfig>;
3794
3835
  type BrowserTraceViewMode = "on" | "off" | "on-first-retry" | "on-all-retries" | "retain-on-failure";
3795
3836
 
3796
- export { _vitest_spy as _, createChainable as a1, afterAll as b7, afterEach as b8, aroundAll as b9, aroundEach as ba, beforeAll as bb, beforeEach as bc, onTestFailed as bd, onTestFinished as be, disableDefaultColors as bh, SnapshotState as bn, format as f, inspect as i, stringify as s, spyOn as x, fn as y };
3797
- export type { TestContext as $, Awaitable as A, MaybeMocked as B, Config$1 as C, DiffOptions as D, ExpectStatic as E, FileSpecification as F, MaybePartiallyMocked as G, MaybePartiallyMockedDeep as H, MockInstance as I, TestAPI as J, SuiteCollector as K, LabelColor as L, ModuleGraphData as M, SuiteAPI as N, Suite as O, ParsedStack as P, SuiteHooks as Q, RuntimeOptions as R, SerializedCoverageConfig as S, TestError as T, UserConsoleLog as U, VitestRunner as V, VitestRunnerImportSource as W, Task as X, CancelReason as Y, TestTryOptions as Z, File as a, TestAttachment as a$, ImportDuration as a0, AfterSuiteRunMeta as a2, Assertion as a3, AsymmetricMatchersContaining as a4, BaselineData as a5, Bench as a6, BenchFn as a7, BenchFnOptions as a8, BenchFromSource as a9, MockedClass as aA, MockedFunction as aB, MockedObject as aC, OnTestFailedHandler as aD, OnTestFinishedHandler as aE, RunMode as aF, TaskBase as aG, TaskResult as aH, RuntimeConfig as aI, SerializedError as aJ, SnapshotData as aK, SnapshotMatchOptions as aL, SnapshotResult as aM, SnapshotSerializer as aN, SnapshotStateOptions as aO, SnapshotSummary as aP, SnapshotUpdateState as aQ, SuiteFactory as aR, SuiteOptions as aS, TaskCustomOptions as aT, TaskMeta as aU, TaskState as aV, TestAnnotationArtifact as aW, TestAnnotationLocation as aX, TestArtifactBase as aY, TestArtifactLocation as aZ, TestArtifactRegistry as a_, BenchOptions as aa, BenchRegistration as ab, BenchRegistrationInput as ac, BenchResult as ad, BenchRunOptions as ae, BenchStorage as af, BenchmarkGroup as ag, BenchmarkProvider as ah, BrowserTraceArtifact as ai, DeeplyAllowMatchers as aj, DomainMatchResult as ak, FailureScreenshotArtifact as al, JestAssertion as am, RawMatcherFn as an, Matchers as ao, MatchersObject as ap, MockContext as aq, MockResult as ar, MockResultIncomplete as as, MockResultReturn as at, MockResultThrow as au, MockSettledResult as av, MockSettledResultFulfilled as aw, MockSettledResultIncomplete as ax, MockSettledResultRejected as ay, Mocked as az, SerializedConfig as b, TestBenchmark as b0, TestBenchmarkTask as b1, TestFunction as b2, TestOptions as b3, TestTags as b4, UncheckedSnapshot as b5, VisualRegressionArtifact as b6, SequenceHooks as bf, SequenceSetupFiles as bg, SerializableRetry as bi, BrowserTraceViewMode as bj, Arrayable as bk, AsyncLeak as bl, PrettyFormatOptions as bm, PromisifyAssertion as bo, Tester as bp, Plugin as bq, SnapshotEnvironment as br, SnapshotEnvironmentOptions as bs, FetchCachedFileSystemResult as bt, ResolveFunctionResult as bu, SerializedDiffOptions as c, StringifyOptions as d, TestTagDefinition as e, TestAnnotation as g, TestArtifact as h, TaskResultPack as j, TaskEventPack as k, SerializedRootConfig as l, Test as m, TaskPopulated as n, ProvidedContext as o, MatcherState as p, SyncExpectationResult as q, AsyncExpectationResult as r, DomainSnapshotAdapter as t, ExpectationResult as u, Procedure as v, Mock as w, MaybeMockedDeep as z };
3837
+ export { fn as B, _vitest_spy as _, createChainable as a2, afterAll as b9, afterEach as ba, aroundAll as bb, aroundEach as bc, beforeAll as bd, beforeEach as be, onTestFailed as bf, onTestFinished as bg, disableDefaultColors as bj, SnapshotState as bp, format as f, inspect as i, stringify as s, spyOn as z };
3838
+ export type { TestTryOptions as $, Awaitable as A, MaybeMockedDeep as C, DiffOptions as D, ExpectStatic as E, FileSpecification as F, MaybeMocked as G, MaybePartiallyMocked as H, MaybePartiallyMockedDeep as I, MockInstance as J, TestAPI as K, LabelColor as L, ModuleGraphData as M, SuiteCollector as N, SuiteAPI as O, ParsedStack as P, Suite as Q, RuntimeOptions as R, SerializedCoverageConfig as S, TestError as T, UserConsoleLog as U, VitestRunner as V, SuiteHooks as W, VitestRunnerImportSource as X, Task as Y, CancelReason as Z, File as a, TestArtifactLocation as a$, TestContext as a0, ImportDuration as a1, AfterSuiteRunMeta as a3, Assertion as a4, AsymmetricMatchersContaining as a5, BaselineData as a6, Bench as a7, BenchFn as a8, BenchFnOptions as a9, Mocked as aA, MockedClass as aB, MockedFunction as aC, MockedObject as aD, OnTestFailedHandler as aE, OnTestFinishedHandler as aF, RunMode as aG, TaskBase as aH, TaskResult as aI, TaskResultAttempt as aJ, RuntimeConfig as aK, SerializedError as aL, SnapshotData as aM, SnapshotMatchOptions as aN, SnapshotResult as aO, SnapshotSerializer as aP, SnapshotStateOptions as aQ, SnapshotSummary as aR, SnapshotUpdateState as aS, SuiteFactory as aT, SuiteOptions as aU, TaskCustomOptions as aV, TaskMeta as aW, TaskState as aX, TestAnnotationArtifact as aY, TestAnnotationLocation as aZ, TestArtifactBase as a_, BenchFromSource as aa, BenchOptions as ab, BenchRegistration as ac, BenchRegistrationInput as ad, BenchResult as ae, BenchRunOptions as af, BenchStorage as ag, BenchmarkGroup as ah, BenchmarkProvider as ai, BrowserTraceArtifact as aj, DeeplyAllowMatchers as ak, DomainMatchResult as al, FailureScreenshotArtifact as am, JestAssertion as an, RawMatcherFn as ao, Matchers as ap, MatchersObject as aq, MockContext as ar, MockResult as as, MockResultIncomplete as at, MockResultReturn as au, MockResultThrow as av, MockSettledResult as aw, MockSettledResultFulfilled as ax, MockSettledResultIncomplete as ay, MockSettledResultRejected as az, SerializedConfig as b, TestArtifactRegistry as b0, TestAttachment as b1, TestBenchmark as b2, TestBenchmarkTask as b3, TestFunction as b4, TestOptions as b5, TestTags as b6, UncheckedSnapshot as b7, VisualRegressionArtifact as b8, SequenceHooks as bh, SequenceSetupFiles as bi, SerializableRetry as bk, BrowserTraceViewMode as bl, Arrayable as bm, AsyncLeak as bn, PrettyFormatOptions as bo, PromisifyAssertion as bq, Tester as br, Plugin as bs, SnapshotEnvironment as bt, SnapshotEnvironmentOptions as bu, FetchCachedFileSystemResult as bv, ResolveFunctionResult as bw, SerializedDiffOptions as c, StringifyOptions as d, FakeTimersConfig as e, TestTagDefinition as g, TestAnnotation as h, TestArtifact as j, TaskResultPack as k, TaskEventPack as l, SerializedRootConfig as m, Test as n, TaskPopulated as o, ProvidedContext as p, MatcherState as q, SyncExpectationResult as r, AsyncExpectationResult as t, DomainSnapshotAdapter as u, ExpectationResult as v, Procedure as w, Mock as x, TemporalTimelike as y };
@@ -1,9 +1,9 @@
1
1
  import { Console } from 'node:console';
2
2
  import { relative } from 'node:path';
3
3
  import { Writable } from 'node:stream';
4
- import { a as getSafeTimers } from './source-map.DdKI5IHB.js';
4
+ import { a as getSafeTimers } from './source-map.BjWcsIL9.js';
5
5
  import { $ } from './tinyrainbow.Do8I1XRG.js';
6
- import { g as getWorkerState } from './utils.DYj33du9.js';
6
+ import { g as getWorkerState, E as EnvironmentTeardownError } from './utils.DYj33du9.js';
7
7
  import './index.D0heQG4v.js';
8
8
  import './pathe.M-eThtNZ.Ba-7h1rE.js';
9
9
 
@@ -78,6 +78,9 @@ function createCustomConsole(defaultState) {
78
78
  time: time || RealDate.now(),
79
79
  size,
80
80
  origin
81
+ }).catch((error) => {
82
+ // the log is already sent, the worker only closed before the reporter answered
83
+ if (!(error instanceof EnvironmentTeardownError)) throw error;
81
84
  });
82
85
  }
83
86
  const stdout = new Writable({ write(data, encoding, callback) {
@@ -1,6 +1,6 @@
1
1
  // if changed, update also jsdocs and docs
2
2
  const defaultPort = 51204;
3
- const defaultBrowserPort = 63315;
3
+ const defaultBrowserPort = 23315;
4
4
  const defaultInspectPort = 9229;
5
5
  const API_PATH = "/__vitest_api__";
6
6
  const CONFIG_NAMES = ["vitest.config", "vite.config"];
@@ -2,7 +2,7 @@ import { existsSync, writeFileSync, readFileSync } from 'node:fs';
2
2
  import { mkdir, writeFile } from 'node:fs/promises';
3
3
  import { resolve, dirname, relative } from 'node:path';
4
4
  import { detectPackageManager, installPackage } from './index.BoyTG_B7.js';
5
- import { p as prompt, n as findConfigFile } from './index.1TqnEahn.js';
5
+ import { p as prompt, n as findConfigFile } from './index.D14IAvnE.js';
6
6
  import { x } from 'tinyexec';
7
7
  import { $ } from './tinyrainbow.Do8I1XRG.js';
8
8
  import 'node:process';
@@ -16,7 +16,7 @@ import 'node:util';
16
16
  import 'vite/module-runner';
17
17
  import 'tinyglobby';
18
18
  import 'vite';
19
- import './constants.-juJ8b_4.js';
19
+ import './constants.DLYM6cZY.js';
20
20
  import './defaults.B1FCaFfh.js';
21
21
  import 'node:os';
22
22
  import './env.BKKtU2WC.js';
@@ -31,8 +31,8 @@ import 'node:stream';
31
31
  import './display.BlTmubjj.js';
32
32
  import './index.D0heQG4v.js';
33
33
  import 'node:perf_hooks';
34
- import './source-map.DdKI5IHB.js';
35
- import './run.BPv-BBRv.js';
34
+ import './source-map.BjWcsIL9.js';
35
+ import './run.BfrMbGVD.js';
36
36
  import '../task-utils.js';
37
37
  import 'obug';
38
38
  import './resolver.CtCcxIy1.js';
@@ -48,7 +48,7 @@ import 'node:events';
48
48
  import './index.DmDMHCg8.js';
49
49
  import 'node:child_process';
50
50
  import 'node:worker_threads';
51
- import './cac.CLrZKo1g.js';
51
+ import './cac.Ccf5Je_F.js';
52
52
  import 'events';
53
53
  import 'readline';
54
54
 
@@ -100,7 +100,7 @@ function log(...args) {
100
100
  console.log(...args);
101
101
  }
102
102
  async function doctor(cliFilters, options) {
103
- const { prepareVitest } = await import('./cli-api.De07GUeT.js').then(function (n) { return n.g; });
103
+ const { prepareVitest } = await import('./cli-api.DE22LIzq.js').then(function (n) { return n.j; });
104
104
  log();
105
105
  log($.inverse($.bold($.blue(" DOCTOR "))), "resolving the current configuration...");
106
106
  const ctx = await prepareVitest({
@@ -1,4 +1,4 @@
1
- import { A as Awaitable } from './config.d.QBNYCgFU.js';
1
+ import { A as Awaitable } from './config.d.BgktgHfG.js';
2
2
 
3
3
  interface EnvironmentReturn {
4
4
  teardown: (global: any) => Awaitable<void>;
@@ -1,18 +1,18 @@
1
- import { g as globalApis } from './constants.-juJ8b_4.js';
2
- import { i as index } from './index.aTZaPVhf.js';
3
- import './run.BPv-BBRv.js';
1
+ import { g as globalApis } from './constants.DLYM6cZY.js';
2
+ import { i as index } from './index.BXttT2gP.js';
3
+ import './run.BfrMbGVD.js';
4
4
  import './index.D0heQG4v.js';
5
5
  import './tinyrainbow.Do8I1XRG.js';
6
6
  import './display.BlTmubjj.js';
7
7
  import './pathe.M-eThtNZ.Ba-7h1rE.js';
8
- import './source-map.DdKI5IHB.js';
8
+ import './source-map.BjWcsIL9.js';
9
9
  import '../task-utils.js';
10
10
  import './utils.DYj33du9.js';
11
11
  import './spy.DDMXghXv.js';
12
12
  import 'chai';
13
13
  import './plugins.DPQHVT0p.js';
14
14
  import './offset.Dy-5Fdfn.js';
15
- import './rpc.DpkUyY1N.js';
15
+ import './rpc.BV0XpJ5q.js';
16
16
  import 'vite/module-runner';
17
17
  import './index.DmDMHCg8.js';
18
18
  import 'tinybench';
@@ -1,10 +1,10 @@
1
1
  import * as chai from 'chai';
2
2
  import { createHook } from 'node:async_hooks';
3
3
  import { t as takeCoverageInsideWorker } from './coverage.-bm5IxnW.js';
4
- import { r as rpc } from './rpc.DpkUyY1N.js';
5
- import { l as loadDiffConfig, a as loadSnapshotSerializers } from './setup-common.HGAqWOnX.js';
4
+ import { r as rpc } from './rpc.BV0XpJ5q.js';
5
+ import { l as loadDiffConfig, a as loadSnapshotSerializers } from './setup-common.llxJkJaD.js';
6
6
  import { g as getWorkerState } from './utils.DYj33du9.js';
7
- import { T as TestRunner } from './index.aTZaPVhf.js';
7
+ import { T as TestRunner } from './index.BXttT2gP.js';
8
8
 
9
9
  function setupChaiConfig(config) {
10
10
  Object.assign(chai.config, config);
@@ -5,6 +5,7 @@ import { E as EnvironmentTeardownError, a as getSafeWorkerState } from './utils.
5
5
  import { pathToFileURL, URL as URL$1 } from 'node:url';
6
6
  import { distDir } from '../path.js';
7
7
  import { VitestModuleEvaluator, unwrapId } from '../module-evaluator.js';
8
+ import { AsyncLocalStorage } from 'node:async_hooks';
8
9
  import { isAbsolute, resolve } from 'node:path';
9
10
  import vm from 'node:vm';
10
11
  import { MockerRegistry, mockObject, RedirectedModule, AutomockedModule } from '@vitest/mocker';
@@ -104,10 +105,20 @@ class BareModuleMocker {
104
105
  };
105
106
  });
106
107
  }
108
+ registeringMocks;
107
109
  async resolveMocks() {
108
- if (!BareModuleMocker.pendingIds.length) return;
109
- const pendingIds = BareModuleMocker.pendingIds;
110
- BareModuleMocker.pendingIds = [];
110
+ if (BareModuleMocker.pendingIds.length) {
111
+ const pendingIds = BareModuleMocker.pendingIds;
112
+ BareModuleMocker.pendingIds = [];
113
+ const registration = this.registerMocks(pendingIds, this.registeringMocks).finally(() => {
114
+ if (this.registeringMocks === registration) this.registeringMocks = void 0;
115
+ });
116
+ this.registeringMocks = registration;
117
+ }
118
+ await this.registeringMocks;
119
+ }
120
+ async registerMocks(pendingIds, previous) {
121
+ await previous?.catch(() => {});
111
122
  const resolveMock = async (mock) => {
112
123
  return {
113
124
  mock,
@@ -275,6 +286,9 @@ class VitestMocker extends BareModuleMocker {
275
286
  moduleRunner;
276
287
  options;
277
288
  filterPublicKeys;
289
+ // factories that run in the current async context, the innermost is last
290
+ factoryContexts = new AsyncLocalStorage();
291
+ pendingFactories = /* @__PURE__ */ new Map();
278
292
  constructor(moduleRunner, options) {
279
293
  super(options);
280
294
  this.moduleRunner = moduleRunner;
@@ -308,12 +322,48 @@ class VitestMocker extends BareModuleMocker {
308
322
  }
309
323
  invalidateModuleById(id) {
310
324
  const mockId = this.getMockPath(id);
325
+ this.pendingFactories.delete(mockId);
311
326
  const node = this.evaluatedModules.getModuleById(mockId);
312
327
  if (node) {
313
328
  this.evaluatedModules.invalidateModule(node);
314
329
  node.mockedExports = void 0;
315
330
  }
316
331
  }
332
+ getMockContext() {
333
+ return { callstack: (this.factoryContexts.getStore()?.findLast((context) => this.pendingFactories.has(context.mockId)))?.callstack ?? null };
334
+ }
335
+ /**
336
+ * Whether the factory of this mock runs in the current async context,
337
+ * or waits for a factory that runs in it. Such imports get the original module.
338
+ * The callstack cannot tell it: all imports from one module share the same array.
339
+ */
340
+ isResolvingMock(mockId) {
341
+ if (!this.pendingFactories.has(mockId)) return false;
342
+ return (this.factoryContexts.getStore() ?? []).some((context) => context.mockId === mockId) || this.waitsForCurrentFactory(mockId);
343
+ }
344
+ /**
345
+ * Whether the module is still evaluating and waits for a factory
346
+ * that runs in the current async context.
347
+ */
348
+ isWaitingForFactory(mod) {
349
+ return !!mod.promise && !mod.evaluated && this.waitsForCurrentFactory(mod.id);
350
+ }
351
+ waitsForCurrentFactory(id) {
352
+ const factories = (this.factoryContexts.getStore() ?? []).map((context) => context.mockId);
353
+ const visited = new Set(factories);
354
+ // a factory that waits for the current one makes everything that waits for it wait too
355
+ while (factories.length) {
356
+ const waiting = this.pendingFactories.get(factories.pop())?.waiting;
357
+ if (waiting?.has(id)) return true;
358
+ waiting?.forEach((waiter) => {
359
+ if (this.pendingFactories.has(waiter) && !visited.has(waiter)) {
360
+ visited.add(waiter);
361
+ factories.push(waiter);
362
+ }
363
+ });
364
+ }
365
+ return false;
366
+ }
317
367
  ensureModule(id, url) {
318
368
  const node = this.evaluatedModules.ensureModule(id, url);
319
369
  // TODO
@@ -326,9 +376,53 @@ class VitestMocker extends BareModuleMocker {
326
376
  };
327
377
  return node;
328
378
  }
329
- async callFunctionMock(id, url, mock) {
379
+ callFunctionMock(id, url, mock, callstack) {
330
380
  const node = this.ensureModule(id, url);
331
- if (node.exports) return node.exports;
381
+ if (node.exports) return Promise.resolve(node.exports);
382
+ return this.resolveMockOnce(id, callstack, () => this.resolveFunctionMock(node, mock));
383
+ }
384
+ resolveMockOnce(id, callstack, resolve) {
385
+ const contexts = this.factoryContexts.getStore() ?? [];
386
+ const waiting = [...callstack, ...contexts.map((context) => context.mockId)];
387
+ const pending = this.pendingFactories.get(id);
388
+ if (pending) {
389
+ waiting.forEach((waiter) => pending.waiting.add(waiter));
390
+ return pending.promise;
391
+ }
392
+ const factory = {
393
+ promise: this.factoryContexts.run([...contexts, {
394
+ mockId: id,
395
+ callstack
396
+ }], resolve).finally(() => {
397
+ if (this.pendingFactories.get(id) === factory) this.pendingFactories.delete(id);
398
+ if (!this.pendingFactories.size)
399
+ // an enabled storage slows down every promise on Node 22
400
+ this.factoryContexts.disable();
401
+ }),
402
+ waiting: new Set(waiting)
403
+ };
404
+ this.pendingFactories.set(id, factory);
405
+ return factory.promise;
406
+ }
407
+ async resolveAutomock(url, mockId, evaluatedNode, callstack, type) {
408
+ const Object = this.primitives.Object;
409
+ // we have to define a separate object that will copy all properties into itself
410
+ // and can't just use the same `exports` define automatically by Vite before the evaluator
411
+ const exports = Object.create(null);
412
+ Object.defineProperty(exports, Symbol.toStringTag, {
413
+ value: "Module",
414
+ configurable: true,
415
+ writable: true
416
+ });
417
+ const node = this.ensureModule(mockId, this.getMockPath(evaluatedNode.url));
418
+ node.meta = evaluatedNode.meta;
419
+ node.file = evaluatedNode.file;
420
+ node.mockedExports = exports;
421
+ const mod = await this.moduleRunner.cachedRequest(url, node, callstack, void 0, true);
422
+ this.mockObject(mod, exports, type);
423
+ return exports;
424
+ }
425
+ async resolveFunctionMock(node, mock) {
332
426
  const exports = await mock.resolve();
333
427
  const moduleExports = new Proxy(exports, { get: (target, prop) => {
334
428
  const val = target[prop];
@@ -372,7 +466,10 @@ If you need to partially mock a module, you can use "importOriginal" helper insi
372
466
  const Object = this.primitives.Object;
373
467
  return this.mockObject(mod, Object.create(Object.prototype), mock.type);
374
468
  }
375
- if (mock.type === "manual") return this.callFunctionMock(this.getMockPath(id), this.getMockPath(url), mock);
469
+ if (mock.type === "manual") {
470
+ const mockId = this.getMockPath(id);
471
+ return this.callFunctionMock(mockId, this.getMockPath(url), mock, [importer, mockId]);
472
+ }
376
473
  const node = await this.moduleRunner.fetchModule(mock.redirect);
377
474
  return this.moduleRunner.cachedRequest(mock.redirect, node, [importer], void 0, true);
378
475
  }
@@ -388,36 +485,14 @@ If you need to partially mock a module, you can use "importOriginal" helper insi
388
485
  });
389
486
  if (mock.type === "automock" || mock.type === "autospy") {
390
487
  const cache = this.evaluatedModules.getModuleById(mockId);
391
- if (cache && cache.mockedExports) return cache.mockedExports;
392
- const Object = this.primitives.Object;
393
- // we have to define a separate object that will copy all properties into itself
394
- // and can't just use the same `exports` define automatically by Vite before the evaluator
395
- const exports = Object.create(null);
396
- Object.defineProperty(exports, Symbol.toStringTag, {
397
- value: "Module",
398
- configurable: true,
399
- writable: true
400
- });
401
- const node = this.ensureModule(mockId, this.getMockPath(evaluatedNode.url));
402
- node.meta = evaluatedNode.meta;
403
- node.file = evaluatedNode.file;
404
- node.mockedExports = exports;
405
- const mod = await this.moduleRunner.cachedRequest(url, node, callstack, void 0, true);
406
- this.mockObject(mod, exports, mock.type);
407
- return exports;
408
- }
409
- if (mock.type === "manual" && !callstack.includes(mockId) && !callstack.includes(url)) try {
410
- callstack.push(mockId);
411
- // this will not work if user does Promise.all(import(), import())
412
- // we can also use AsyncLocalStorage to store callstack, but this won't work in the browser
413
- // maybe we should improve mock API in the future?
414
- this.mockContext.callstack = callstack;
415
- return await this.callFunctionMock(mockId, this.getMockPath(url), mock);
416
- } finally {
417
- this.mockContext.callstack = null;
418
- const indexMock = callstack.indexOf(mockId);
419
- callstack.splice(indexMock, 1);
488
+ if (cache?.mockedExports) {
489
+ // while the original module evaluates, only its own imports get the partial object, like in a cycle
490
+ const isSelfImport = callstack.includes(evaluatedNode.id) || this.isResolvingMock(mockId);
491
+ if (!this.pendingFactories.has(mockId) || isSelfImport) return cache.mockedExports;
492
+ }
493
+ return this.resolveMockOnce(mockId, [...callstack, mockId], () => this.resolveAutomock(url, mockId, evaluatedNode, callstack, mock.type));
420
494
  }
495
+ if (mock.type === "manual" && !callstack.includes(mockId) && !callstack.includes(url) && !this.isResolvingMock(mockId)) return this.callFunctionMock(mockId, this.getMockPath(url), mock, [...callstack, mockId]);
421
496
  else if (mock.type === "redirect" && !callstack.includes(mock.redirect)) {
422
497
  span.setAttribute("vitest.mock.redirect", mock.redirect);
423
498
  return mock.redirect;
@@ -574,6 +649,8 @@ class VitestModuleRunner extends viteModuleRunner.ModuleRunner {
574
649
  async cachedRequest(url, mod, callstack = [], metadata, ignoreMock = false) {
575
650
  // Track for a better error message if dynamic import is not resolved properly
576
651
  this._callstacks.set(mod, callstack);
652
+ // the factory imports a module that waits for this factory, treat it as a cycle
653
+ if (mod.exports && this.mocker.isWaitingForFactory(mod)) return mod.exports;
577
654
  if (ignoreMock) return this._cachedRequest(url, mod, callstack, metadata);
578
655
  let mocked;
579
656
  if (mod.meta && "mockedModule" in mod.meta) {
@@ -585,7 +662,7 @@ class VitestModuleRunner extends viteModuleRunner.ModuleRunner {
585
662
  const node = await this.fetchModule(injectQuery(url, "_vitest_original"));
586
663
  return this._cachedRequest(node.url, node, callstack, metadata);
587
664
  }
588
- if (callstack.includes(mockId) || callstack.includes(url) || "redirect" in currentMock && callstack.includes(currentMock.redirect)) {
665
+ if (callstack.includes(mockId) || this.mocker.isResolvingMock(mockId) || callstack.includes(url) || "redirect" in currentMock && callstack.includes(currentMock.redirect)) {
589
666
  const node = await this.fetchModule(injectQuery(url, "_vitest_original"));
590
667
  return this._cachedRequest(node.url, node, callstack, metadata);
591
668
  }
@@ -758,7 +835,7 @@ function startVitestModuleRunner(options) {
758
835
  const rawId = unwrapId(id);
759
836
  resolvingModules.add(rawId);
760
837
  try {
761
- if (VitestMocker.pendingIds.length) await moduleRunner.mocker.resolveMocks();
838
+ if (VitestMocker.pendingIds.length || moduleRunner.mocker.registeringMocks) await moduleRunner.mocker.resolveMocks();
762
839
  if (!isImportActual) {
763
840
  const resolvedMock = moduleRunner.mocker.getDependencyMockByUrl(id);
764
841
  if (resolvedMock?.type === "manual" || resolvedMock?.type === "redirect") return {