vitest 4.0.0-beta.8 → 4.0.0-beta.9

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 (56) hide show
  1. package/dist/browser.d.ts +5 -5
  2. package/dist/browser.js +4 -4
  3. package/dist/chunks/{runBaseTests.D6sfuWBM.js → base.CA5N8Af0.js} +55 -26
  4. package/dist/chunks/{benchmark.UW6Ezvxy.js → benchmark.CJUa-Hsa.js} +1 -1
  5. package/dist/chunks/{browser.d.DOMmqJQx.d.ts → browser.d.DtfyY9yS.d.ts} +1 -1
  6. package/dist/chunks/{cac.By1HvRIk.js → cac.Dt7e1TIu.js} +6 -24
  7. package/dist/chunks/{cli-api.C-JHgQgp.js → cli-api.eAzsLIxz.js} +41 -32
  8. package/dist/chunks/{config.d._GBBbReY.d.ts → config.d.DacWrqWe.d.ts} +1 -0
  9. package/dist/chunks/{console.B0quX7yH.js → console.7h5kHUIf.js} +1 -1
  10. package/dist/chunks/{coverage.DarITf6U.js → coverage.CDRAMTt7.js} +19 -50
  11. package/dist/chunks/{globals.lgsmH00r.js → globals.CJrTTbxC.js} +5 -6
  12. package/dist/chunks/{index.AzwzFtyi.js → index.BIP7prJq.js} +1 -1
  13. package/dist/chunks/{index.BuwjkI-q.js → index.BjKEiSn0.js} +1 -1
  14. package/dist/chunks/{index.AR8aAkCC.js → index.C832ioot.js} +5 -6
  15. package/dist/chunks/{moduleRunner.d.CX4DuqOx.d.ts → moduleRunner.d.DxTLreRD.d.ts} +4 -1
  16. package/dist/chunks/{node.BOqcT2jW.js → node.CyipiPvJ.js} +1 -1
  17. package/dist/chunks/{plugin.d.CHe6slQs.d.ts → plugin.d.CIk0YiKb.d.ts} +1 -1
  18. package/dist/chunks/{reporters.d.37tJQ2uV.d.ts → reporters.d.DmP-iHLr.d.ts} +9 -16
  19. package/dist/chunks/{index.CsFXYRkW.js → resolveSnapshotEnvironment.Bvv2zr69.js} +16 -21
  20. package/dist/chunks/{rpc.RpPylpp0.js → rpc.BKr6mtxz.js} +1 -1
  21. package/dist/chunks/{setup-common.hLGRxhC8.js → setup-common.B7I37Tji.js} +4 -4
  22. package/dist/chunks/{startModuleRunner.C8TW8zTN.js → startModuleRunner.BDRvKSdz.js} +7 -2
  23. package/dist/chunks/test.BAlBebnP.js +214 -0
  24. package/dist/chunks/{typechecker.DSo_maXz.js → typechecker.DB-fIMaH.js} +44 -1
  25. package/dist/chunks/{utils.C7__0Iv5.js → utils.D2R2NiOH.js} +1 -10
  26. package/dist/chunks/{vi.BfdOiD4j.js → vi.BB37KeLx.js} +16 -16
  27. package/dist/chunks/{vm.BHBje7cC.js → vm.CjLTDaST.js} +12 -7
  28. package/dist/chunks/{worker.d.DYlqbejz.d.ts → worker.d.B2r4Ln6p.d.ts} +1 -1
  29. package/dist/chunks/{worker.d.BKu8cnnX.d.ts → worker.d.DJ6qxO2w.d.ts} +1 -1
  30. package/dist/cli.js +3 -3
  31. package/dist/config.d.ts +7 -7
  32. package/dist/coverage.d.ts +5 -5
  33. package/dist/coverage.js +2 -2
  34. package/dist/index.d.ts +11 -12
  35. package/dist/index.js +5 -8
  36. package/dist/module-evaluator.d.ts +4 -3
  37. package/dist/module-evaluator.js +3 -3
  38. package/dist/module-runner.js +2 -2
  39. package/dist/node.d.ts +9 -10
  40. package/dist/node.js +8 -8
  41. package/dist/reporters.d.ts +5 -5
  42. package/dist/reporters.js +3 -3
  43. package/dist/runners.d.ts +1 -1
  44. package/dist/runners.js +11 -215
  45. package/dist/snapshot.js +2 -2
  46. package/dist/suite.js +2 -2
  47. package/dist/worker.js +2 -3
  48. package/dist/workers/forks.js +27 -4
  49. package/dist/workers/runVmTests.js +18 -19
  50. package/dist/workers/threads.js +27 -4
  51. package/dist/workers/vmForks.js +4 -4
  52. package/dist/workers/vmThreads.js +4 -4
  53. package/dist/workers.d.ts +3 -3
  54. package/dist/workers.js +26 -8
  55. package/package.json +10 -13
  56. package/dist/chunks/base.BXI97p6t.js +0 -39
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import { getTasks, getFullName, getTests } from '@vitest/runner/utils';
3
3
  import * as pathe from 'pathe';
4
4
  import c from 'tinyrainbow';
5
- import { g as getStateSymbol, t as truncateString, F as F_RIGHT, D as DefaultReporter, f as formatProjectName } from './index.AzwzFtyi.js';
5
+ import { g as getStateSymbol, t as truncateString, F as F_RIGHT, D as DefaultReporter, f as formatProjectName } from './index.BIP7prJq.js';
6
6
  import { stripVTControlCharacters } from 'node:util';
7
7
  import { notNullish } from '@vitest/utils';
8
8
 
@@ -1,14 +1,13 @@
1
- import { c as createExpect, a as globalExpect, i as inject, v as vi, b as vitest } from './vi.BfdOiD4j.js';
2
- import { b as bench } from './benchmark.UW6Ezvxy.js';
1
+ import { b as assert, c as createExpect, g as globalExpect, i as inject, s as should, v as vi, d as vitest } from './vi.BB37KeLx.js';
2
+ import { b as bench } from './benchmark.CJUa-Hsa.js';
3
3
  import { expectTypeOf } from 'expect-type';
4
4
  import { afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, suite, test } from '@vitest/runner';
5
5
  import { EvaluatedModules } from 'vite/module-runner';
6
- import * as chai from 'chai';
7
- import { assert, should } from 'chai';
6
+ import { chai } from '@vitest/expect';
8
7
 
9
8
  const assertType = function assertType() {};
10
9
 
11
- var VitestIndex = /*#__PURE__*/Object.freeze({
10
+ var index = /*#__PURE__*/Object.freeze({
12
11
  __proto__: null,
13
12
  EvaluatedModules: EvaluatedModules,
14
13
  afterAll: afterAll,
@@ -34,4 +33,4 @@ var VitestIndex = /*#__PURE__*/Object.freeze({
34
33
  vitest: vitest
35
34
  });
36
35
 
37
- export { VitestIndex as V, assertType as a };
36
+ export { assertType as a, index as i };
@@ -1,6 +1,7 @@
1
+ import * as _vitest_spy from '@vitest/spy';
1
2
  import vm from 'node:vm';
2
3
  import { ModuleEvaluator, ModuleRunnerImportMeta, ModuleRunnerContext, EvaluatedModuleNode, FetchFunction, ModuleRunner, EvaluatedModules } from 'vite/module-runner';
3
- import { R as RuntimeRPC, W as WorkerGlobalState } from './worker.d.DYlqbejz.js';
4
+ import { R as RuntimeRPC, W as WorkerGlobalState } from './worker.d.B2r4Ln6p.js';
4
5
  import { R as ResolveFunctionResult } from './environment.d.2fYMoz3o.js';
5
6
  import { MockedModule, MockedModuleType } from '@vitest/mocker';
6
7
  import { P as PendingSuiteMock, b as MockFactory, a as MockOptions } from './mocker.d.BE_2ls6u.js';
@@ -116,6 +117,7 @@ interface MockContext {
116
117
  }
117
118
  interface VitestMockerOptions {
118
119
  context?: vm.Context;
120
+ spyModule?: typeof _vitest_spy;
119
121
  root: string;
120
122
  moduleDirectories: string[];
121
123
  resolveId: (id: string, importer?: string) => Promise<{
@@ -192,6 +194,7 @@ interface VitestModuleRunnerOptions {
192
194
  getWorkerState: () => WorkerGlobalState;
193
195
  mocker?: VitestMocker;
194
196
  vm?: VitestVmOptions;
197
+ spyModule?: typeof _vitest_spy;
195
198
  }
196
199
  interface VitestVmOptions {
197
200
  context: vm.Context;
@@ -1,5 +1,5 @@
1
1
  import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment';
2
- import { g as getWorkerState } from './utils.C7__0Iv5.js';
2
+ import { g as getWorkerState } from './utils.D2R2NiOH.js';
3
3
  import '@vitest/utils';
4
4
 
5
5
  class VitestNodeSnapshotEnvironment extends NodeSnapshotEnvironment {
@@ -1,4 +1,4 @@
1
- import { V as Vitest, T as TestProject, a as TestProjectConfiguration } from './reporters.d.37tJQ2uV.js';
1
+ import { V as Vitest, T as TestProject, a as TestProjectConfiguration } from './reporters.d.DmP-iHLr.js';
2
2
 
3
3
  interface VitestPluginContext {
4
4
  vitest: Vitest;
@@ -5,12 +5,12 @@ import { Writable } from 'node:stream';
5
5
  import { ViteDevServer, TransformResult as TransformResult$1, DepOptimizationConfig, ServerOptions, UserConfig as UserConfig$1, ConfigEnv, AliasOptions } from 'vite';
6
6
  import { MockedModule } from '@vitest/mocker';
7
7
  import { StackTraceParserOptions } from '@vitest/utils/source-map';
8
- import { B as BrowserTesterOptions, S as SerializedTestSpecification } from './browser.d.DOMmqJQx.js';
9
- import { a as SerializedConfig, F as FakeTimerInstallOpts } from './config.d._GBBbReY.js';
8
+ import { B as BrowserTesterOptions, S as SerializedTestSpecification } from './browser.d.DtfyY9yS.js';
9
+ import { a as SerializedConfig, F as FakeTimerInstallOpts } from './config.d.DacWrqWe.js';
10
10
  import { PrettyFormatOptions } from '@vitest/pretty-format';
11
11
  import { SnapshotSummary, SnapshotStateOptions } from '@vitest/snapshot';
12
12
  import { SerializedDiffOptions } from '@vitest/utils/diff';
13
- import * as chai from 'chai';
13
+ import { chai } from '@vitest/expect';
14
14
  import { happyDomTypes, jsdomTypes } from 'vitest/optional-types.js';
15
15
  import { B as BenchmarkResult } from './benchmark.d.DAaHLpsq.js';
16
16
  import { a as RuntimeCoverageProviderModule } from './coverage.d.BZtK59WP.js';
@@ -460,8 +460,6 @@ interface ResolvedPoolOptions extends PoolOptions {
460
460
  vmForks?: ResolvedForksOptions & VmOptions;
461
461
  }
462
462
  interface ThreadsOptions {
463
- /** Minimum amount of threads to use */
464
- minThreads?: number | string;
465
463
  /** Maximum amount of threads to use */
466
464
  maxThreads?: number | string;
467
465
  /**
@@ -480,12 +478,9 @@ interface ThreadsOptions {
480
478
  useAtomics?: boolean;
481
479
  }
482
480
  interface ResolvedThreadsOptions extends ThreadsOptions {
483
- minThreads?: number;
484
481
  maxThreads?: number;
485
482
  }
486
483
  interface ForksOptions {
487
- /** Minimum amount of child processes to use */
488
- minForks?: number | string;
489
484
  /** Maximum amount of child processes to use */
490
485
  maxForks?: number | string;
491
486
  /**
@@ -496,7 +491,6 @@ interface ForksOptions {
496
491
  singleFork?: boolean;
497
492
  }
498
493
  interface ResolvedForksOptions extends ForksOptions {
499
- minForks?: number;
500
494
  maxForks?: number;
501
495
  }
502
496
  interface WorkerContextOptions {
@@ -1790,6 +1784,10 @@ declare class Vitest {
1790
1784
  */
1791
1785
  setGlobalTestNamePattern(pattern: string | RegExp): void;
1792
1786
  /**
1787
+ * Returns the regexp used for the global test name pattern.
1788
+ */
1789
+ getGlobalTestNamePattern(): RegExp | undefined;
1790
+ /**
1793
1791
  * Resets the global test name pattern. This method doesn't run any tests.
1794
1792
  */
1795
1793
  resetGlobalTestNamePattern(): void;
@@ -2495,12 +2493,8 @@ interface InlineConfig {
2495
2493
  */
2496
2494
  maxWorkers?: number | string;
2497
2495
  /**
2498
- * Minimum number or percentage of workers to run tests in. `poolOptions.{threads,vmThreads}.minThreads`/`poolOptions.forks.minForks` has higher priority.
2499
- */
2500
- minWorkers?: number | string;
2501
- /**
2502
2496
  * Should all test files run in parallel. Doesn't affect tests running in the same file.
2503
- * Setting this to `false` will override `maxWorkers` and `minWorkers` options to `1`.
2497
+ * Setting this to `false` will override `maxWorkers` option to `1`.
2504
2498
  *
2505
2499
  * @default true
2506
2500
  */
@@ -3073,9 +3067,8 @@ interface ResolvedConfig extends Omit<Required<UserConfig>, "project" | "config"
3073
3067
  };
3074
3068
  runner?: string;
3075
3069
  maxWorkers: number;
3076
- minWorkers: number;
3077
3070
  }
3078
- type NonProjectOptions = "shard" | "watch" | "run" | "cache" | "update" | "reporters" | "outputFile" | "teardownTimeout" | "silent" | "forceRerunTriggers" | "testNamePattern" | "ui" | "open" | "uiBase" | "snapshotFormat" | "resolveSnapshotPath" | "passWithNoTests" | "onConsoleLog" | "onStackTrace" | "dangerouslyIgnoreUnhandledErrors" | "slowTestThreshold" | "inspect" | "inspectBrk" | "coverage" | "maxWorkers" | "minWorkers" | "fileParallelism" | "watchTriggerPatterns";
3071
+ type NonProjectOptions = "shard" | "watch" | "run" | "cache" | "update" | "reporters" | "outputFile" | "teardownTimeout" | "silent" | "forceRerunTriggers" | "testNamePattern" | "ui" | "open" | "uiBase" | "snapshotFormat" | "resolveSnapshotPath" | "passWithNoTests" | "onConsoleLog" | "onStackTrace" | "dangerouslyIgnoreUnhandledErrors" | "slowTestThreshold" | "inspect" | "inspectBrk" | "coverage" | "maxWorkers" | "fileParallelism" | "watchTriggerPatterns";
3079
3072
  interface ServerDepsOptions {
3080
3073
  /**
3081
3074
  * Externalize means that Vite will bpass the package to native Node.
@@ -1,30 +1,15 @@
1
- import * as chai from 'chai';
2
- import { resolve, join } from 'node:path';
3
- import { l as loadDiffConfig, b as loadSnapshotSerializers, t as takeCoverageInsideWorker } from './setup-common.hLGRxhC8.js';
4
- import { distDir } from '../path.js';
5
- import { r as rpc } from './rpc.RpPylpp0.js';
6
- import { g as getWorkerState } from './utils.C7__0Iv5.js';
1
+ import { chai } from '@vitest/expect';
2
+ import { l as loadDiffConfig, b as loadSnapshotSerializers, t as takeCoverageInsideWorker } from './setup-common.B7I37Tji.js';
3
+ import { r as rpc } from './rpc.BKr6mtxz.js';
4
+ import { g as getWorkerState } from './utils.D2R2NiOH.js';
5
+ import { V as VitestTestRunner, N as NodeBenchmarkRunner } from './test.BAlBebnP.js';
7
6
 
8
7
  function setupChaiConfig(config) {
9
8
  Object.assign(chai.config, config);
10
9
  }
11
10
 
12
- async function resolveSnapshotEnvironment(config, executor) {
13
- if (!config.snapshotEnvironment) {
14
- const { VitestNodeSnapshotEnvironment } = await import('./node.BOqcT2jW.js');
15
- return new VitestNodeSnapshotEnvironment();
16
- }
17
- const mod = await executor.import(config.snapshotEnvironment);
18
- if (typeof mod.default !== "object" || !mod.default) throw new Error("Snapshot environment module must have a default export object with a shape of `SnapshotEnvironment`");
19
- return mod.default;
20
- }
21
-
22
- const runnersFile = resolve(distDir, "runners.js");
23
11
  async function getTestRunnerConstructor(config, moduleRunner) {
24
- if (!config.runner) {
25
- const { VitestTestRunner, NodeBenchmarkRunner } = await moduleRunner.import(join("/@fs/", runnersFile));
26
- return config.mode === "test" ? VitestTestRunner : NodeBenchmarkRunner;
27
- }
12
+ if (!config.runner) return config.mode === "test" ? VitestTestRunner : NodeBenchmarkRunner;
28
13
  const mod = await moduleRunner.import(config.runner);
29
14
  if (!mod.default && typeof mod.default !== "function") throw new Error(`Runner must export a default function, but got ${typeof mod.default} imported from ${config.runner}`);
30
15
  return mod.default;
@@ -83,4 +68,14 @@ async function resolveTestRunner(config, moduleRunner) {
83
68
  }, testRunner;
84
69
  }
85
70
 
71
+ async function resolveSnapshotEnvironment(config, executor) {
72
+ if (!config.snapshotEnvironment) {
73
+ const { VitestNodeSnapshotEnvironment } = await import('./node.CyipiPvJ.js');
74
+ return new VitestNodeSnapshotEnvironment();
75
+ }
76
+ const mod = await executor.import(config.snapshotEnvironment);
77
+ if (typeof mod.default !== "object" || !mod.default) throw new Error("Snapshot environment module must have a default export object with a shape of `SnapshotEnvironment`");
78
+ return mod.default;
79
+ }
80
+
86
81
  export { resolveSnapshotEnvironment as a, resolveTestRunner as r, setupChaiConfig as s };
@@ -1,6 +1,6 @@
1
1
  import { getSafeTimers } from '@vitest/utils';
2
2
  import { c as createBirpc } from './index.Bgo3tNWt.js';
3
- import { g as getWorkerState } from './utils.C7__0Iv5.js';
3
+ import { g as getWorkerState } from './utils.D2R2NiOH.js';
4
4
 
5
5
  const { get } = Reflect;
6
6
  function withSafeTimers(fn) {
@@ -1,7 +1,7 @@
1
1
  import { r as resolveCoverageProviderModule } from './coverage.D_JHT54q.js';
2
2
  import { addSerializer } from '@vitest/snapshot';
3
3
  import { setSafeTimers } from '@vitest/utils';
4
- import { g as getWorkerState } from './utils.C7__0Iv5.js';
4
+ import { g as getWorkerState } from './utils.D2R2NiOH.js';
5
5
 
6
6
  async function startCoverageInsideWorker(options, loader, runtimeOptions) {
7
7
  const coverageModule = await resolveCoverageProviderModule(options, loader);
@@ -18,10 +18,10 @@ async function stopCoverageInsideWorker(options, loader, runtimeOptions) {
18
18
 
19
19
  let globalSetup = false;
20
20
  async function setupCommonEnv(config) {
21
- if (setupDefines(config.defines), setupEnv(config.env), !globalSetup && (globalSetup = true, setSafeTimers(), config.globals)) (await import('./globals.lgsmH00r.js')).registerApiGlobally();
21
+ if (setupDefines(config), setupEnv(config.env), !globalSetup && (globalSetup = true, setSafeTimers(), config.globals)) (await import('./globals.CJrTTbxC.js')).registerApiGlobally();
22
22
  }
23
- function setupDefines(defines) {
24
- for (const key in defines) globalThis[key] = defines[key];
23
+ function setupDefines(config) {
24
+ for (const key in config.defines) globalThis[key] = config.defines[key];
25
25
  }
26
26
  function setupEnv(env) {
27
27
  const state = getWorkerState(), { PROD, DEV,...restEnvs } = env;
@@ -233,6 +233,7 @@ class VitestMocker {
233
233
  Array,
234
234
  Map
235
235
  };
236
+ if (options.spyModule) this.spyModule = options.spyModule;
236
237
  const Symbol = this.primitives.Symbol;
237
238
  this.filterPublicKeys = [
238
239
  "__esModule",
@@ -500,6 +501,7 @@ class VitestModuleRunner extends ModuleRunner {
500
501
  evaluatedModules,
501
502
  sourcemapInterceptor: "prepareStackTrace"
502
503
  }, options.evaluator), this.options = options, this.moduleExecutionInfo = options.getWorkerState().moduleExecutionInfo, this.mocker = options.mocker || new VitestMocker(this, {
504
+ spyModule: options.spyModule,
503
505
  context: options.vm?.context,
504
506
  resolveId: options.transport.resolveId,
505
507
  get root() {
@@ -561,7 +563,7 @@ class VitestModuleRunner extends ModuleRunner {
561
563
  const { readFileSync } = fs, browserExternalId = "__vite-browser-external", browserExternalLength = 24;
562
564
  const VITEST_VM_CONTEXT_SYMBOL = "__vitest_vm_context__";
563
565
  const cwd = process.cwd(), isWindows = process.platform === "win32";
564
- async function startVitestModuleRunner(options) {
566
+ function startVitestModuleRunner(options) {
565
567
  const state = () => globalThis.__vitest_worker__ || options.state, rpc = () => state().rpc;
566
568
  process.exit = (code = process.exitCode || 0) => {
567
569
  throw new Error(`process.exit unexpectedly called with "${code}"`);
@@ -581,6 +583,7 @@ async function startVitestModuleRunner(options) {
581
583
  },
582
584
  getCurrentTestFilepath: () => state().filepath
583
585
  }), moduleRunner = new VitestModuleRunner({
586
+ spyModule: options.spyModule,
584
587
  evaluatedModules: options.evaluatedModules,
585
588
  evaluator,
586
589
  mocker: options.mocker,
@@ -644,7 +647,9 @@ async function startVitestModuleRunner(options) {
644
647
  getWorkerState: state,
645
648
  vm
646
649
  });
647
- return await moduleRunner.import("/@vite/env"), await moduleRunner.mocker.initializeSpyModule(), moduleRunner;
650
+ // await moduleRunner.import('/@vite/env')
651
+ // await moduleRunner.mocker.initializeSpyModule()
652
+ return moduleRunner;
648
653
  }
649
654
  function toBuiltin(id) {
650
655
  if (id.startsWith(browserExternalId)) id = id.slice(browserExternalLength);
@@ -0,0 +1,214 @@
1
+ import { updateTask } from '@vitest/runner';
2
+ import { createDefer, getSafeTimers } from '@vitest/utils';
3
+ import { a as getBenchOptions, g as getBenchFn } from './benchmark.CJUa-Hsa.js';
4
+ import { g as getWorkerState } from './utils.D2R2NiOH.js';
5
+ import { setState, GLOBAL_EXPECT, getState } from '@vitest/expect';
6
+ import { getTests, getNames, getTestName } from '@vitest/runner/utils';
7
+ import { processError } from '@vitest/utils/error';
8
+ import { normalize } from 'pathe';
9
+ import { a as getSnapshotClient, i as inject, c as createExpect, v as vi } from './vi.BB37KeLx.js';
10
+ import { r as rpc } from './rpc.BKr6mtxz.js';
11
+
12
+ function createBenchmarkResult(name) {
13
+ return {
14
+ name,
15
+ rank: 0,
16
+ rme: 0,
17
+ samples: []
18
+ };
19
+ }
20
+ const benchmarkTasks = /* @__PURE__ */ new WeakMap();
21
+ async function runBenchmarkSuite(suite, runner) {
22
+ const { Task, Bench } = await runner.importTinybench(), start = performance.now(), benchmarkGroup = [], benchmarkSuiteGroup = [];
23
+ for (const task of suite.tasks) {
24
+ if (task.mode !== "run" && task.mode !== "queued") continue;
25
+ if (task.meta?.benchmark) benchmarkGroup.push(task);
26
+ else if (task.type === "suite") benchmarkSuiteGroup.push(task);
27
+ }
28
+ // run sub suites sequentially
29
+ for (const subSuite of benchmarkSuiteGroup) await runBenchmarkSuite(subSuite, runner);
30
+ if (benchmarkGroup.length) {
31
+ const defer = createDefer();
32
+ suite.result = {
33
+ state: "run",
34
+ startTime: start,
35
+ benchmark: createBenchmarkResult(suite.name)
36
+ }, updateTask$1("suite-prepare", suite);
37
+ const addBenchTaskListener = (task, benchmark) => {
38
+ task.addEventListener("complete", (e) => {
39
+ const task = e.task, taskRes = task.result, result = benchmark.result.benchmark;
40
+ benchmark.result.state = "pass", Object.assign(result, taskRes);
41
+ // compute extra stats and free raw samples as early as possible
42
+ const samples = result.samples;
43
+ if (result.sampleCount = samples.length, result.median = samples.length % 2 ? samples[Math.floor(samples.length / 2)] : (samples[samples.length / 2] + samples[samples.length / 2 - 1]) / 2, !runner.config.benchmark?.includeSamples) result.samples.length = 0;
44
+ updateTask$1("test-finished", benchmark);
45
+ }, { once: true }), task.addEventListener("error", (e) => {
46
+ const task = e.task;
47
+ defer.reject(benchmark ? task.result.error : e);
48
+ }, { once: true });
49
+ };
50
+ benchmarkGroup.forEach((benchmark) => {
51
+ const options = getBenchOptions(benchmark), benchmarkInstance = new Bench(options), benchmarkFn = getBenchFn(benchmark);
52
+ benchmark.result = {
53
+ state: "run",
54
+ startTime: start,
55
+ benchmark: createBenchmarkResult(benchmark.name)
56
+ };
57
+ const task = new Task(benchmarkInstance, benchmark.name, benchmarkFn);
58
+ benchmarkTasks.set(benchmark, task), addBenchTaskListener(task, benchmark);
59
+ });
60
+ const { setTimeout } = getSafeTimers(), tasks = [];
61
+ for (const benchmark of benchmarkGroup) {
62
+ const task = benchmarkTasks.get(benchmark);
63
+ updateTask$1("test-prepare", benchmark), await task.warmup(), tasks.push([await new Promise((resolve) => setTimeout(async () => {
64
+ resolve(await task.run());
65
+ })), benchmark]);
66
+ }
67
+ suite.result.duration = performance.now() - start, suite.result.state = "pass", updateTask$1("suite-finished", suite), defer.resolve(null), await defer;
68
+ }
69
+ function updateTask$1(event, task) {
70
+ updateTask(event, task, runner);
71
+ }
72
+ }
73
+ class NodeBenchmarkRunner {
74
+ moduleRunner;
75
+ constructor(config) {
76
+ this.config = config;
77
+ }
78
+ async importTinybench() {
79
+ return await import('tinybench');
80
+ }
81
+ importFile(filepath, source) {
82
+ if (source === "setup") {
83
+ const moduleNode = getWorkerState().evaluatedModules.getModuleById(filepath);
84
+ if (moduleNode) getWorkerState().evaluatedModules.invalidateModule(moduleNode);
85
+ }
86
+ return this.moduleRunner.import(filepath);
87
+ }
88
+ async runSuite(suite) {
89
+ await runBenchmarkSuite(suite, this);
90
+ }
91
+ async runTask() {
92
+ throw new Error("`test()` and `it()` is only available in test mode.");
93
+ }
94
+ }
95
+
96
+ // import type { VitestExecutor } from '../execute'
97
+ // worker context is shared between all tests
98
+ const workerContext = Object.create(null);
99
+ class VitestTestRunner {
100
+ snapshotClient = getSnapshotClient();
101
+ workerState = getWorkerState();
102
+ moduleRunner;
103
+ cancelRun = false;
104
+ assertionsErrors = /* @__PURE__ */ new WeakMap();
105
+ pool = this.workerState.ctx.pool;
106
+ constructor(config) {
107
+ this.config = config;
108
+ }
109
+ importFile(filepath, source) {
110
+ if (source === "setup") {
111
+ const moduleNode = this.workerState.evaluatedModules.getModuleById(filepath);
112
+ if (moduleNode) this.workerState.evaluatedModules.invalidateModule(moduleNode);
113
+ }
114
+ return this.moduleRunner.import(filepath);
115
+ }
116
+ onCollectStart(file) {
117
+ this.workerState.current = file;
118
+ }
119
+ onCleanupWorkerContext(listener) {
120
+ this.workerState.onCleanup(listener);
121
+ }
122
+ onAfterRunFiles() {
123
+ this.snapshotClient.clear(), this.workerState.current = void 0;
124
+ }
125
+ getWorkerContext() {
126
+ return workerContext;
127
+ }
128
+ async onAfterRunSuite(suite) {
129
+ if (this.config.logHeapUsage && typeof process !== "undefined") suite.result.heap = process.memoryUsage().heapUsed;
130
+ if (suite.mode !== "skip" && "filepath" in suite) {
131
+ // mark snapshots in skipped tests as not obsolete
132
+ for (const test of getTests(suite)) if (test.mode === "skip") {
133
+ const name = getNames(test).slice(1).join(" > ");
134
+ this.snapshotClient.skipTest(suite.file.filepath, name);
135
+ }
136
+ const result = await this.snapshotClient.finish(suite.file.filepath);
137
+ if (this.workerState.config.snapshotOptions.updateSnapshot === "none" && result.unchecked) {
138
+ let message = `Obsolete snapshots found when no snapshot update is expected.\n`;
139
+ for (const key of result.uncheckedKeys) message += `· ${key}\n`;
140
+ suite.result.errors ??= [], suite.result.errors.push(processError(new Error(message))), suite.result.state = "fail";
141
+ }
142
+ await rpc().snapshotSaved(result);
143
+ }
144
+ this.workerState.current = suite.suite || suite.file;
145
+ }
146
+ onAfterRunTask(test) {
147
+ if (this.config.logHeapUsage && typeof process !== "undefined") test.result.heap = process.memoryUsage().heapUsed;
148
+ this.workerState.current = test.suite || test.file;
149
+ }
150
+ cancel(_reason) {
151
+ this.cancelRun = true;
152
+ }
153
+ injectValue(key) {
154
+ // inject has a very limiting type controlled by ProvidedContext
155
+ // some tests override it which causes the build to fail
156
+ return inject(key);
157
+ }
158
+ async onBeforeRunTask(test) {
159
+ if (this.cancelRun) test.mode = "skip";
160
+ test.mode !== "run" && test.mode !== "queued" || (this.workerState.current = test);
161
+ }
162
+ async onBeforeRunSuite(suite) {
163
+ if (this.cancelRun) suite.mode = "skip";
164
+ // initialize snapshot state before running file suite
165
+ if (suite.mode !== "skip" && "filepath" in suite) await this.snapshotClient.setup(suite.file.filepath, this.workerState.config.snapshotOptions);
166
+ this.workerState.current = suite;
167
+ }
168
+ onBeforeTryTask(test) {
169
+ clearModuleMocks(this.config), this.snapshotClient.clearTest(test.file.filepath, test.id), setState({
170
+ assertionCalls: 0,
171
+ isExpectingAssertions: false,
172
+ isExpectingAssertionsError: null,
173
+ expectedAssertionsNumber: null,
174
+ expectedAssertionsNumberErrorGen: null,
175
+ currentTestName: getTestName(test),
176
+ snapshotState: this.snapshotClient.getSnapshotState(test.file.filepath)
177
+ }, globalThis[GLOBAL_EXPECT]);
178
+ }
179
+ onAfterTryTask(test) {
180
+ const { assertionCalls, expectedAssertionsNumber, expectedAssertionsNumberErrorGen, isExpectingAssertions, isExpectingAssertionsError } = test.context._local ? test.context.expect.getState() : getState(globalThis[GLOBAL_EXPECT]);
181
+ if (expectedAssertionsNumber !== null && assertionCalls !== expectedAssertionsNumber) throw expectedAssertionsNumberErrorGen();
182
+ if (isExpectingAssertions === true && assertionCalls === 0) throw isExpectingAssertionsError;
183
+ if (this.config.expect.requireAssertions && assertionCalls === 0) throw this.assertionsErrors.get(test);
184
+ }
185
+ extendTaskContext(context) {
186
+ // create error during the test initialization so we have a nice stack trace
187
+ if (this.config.expect.requireAssertions) this.assertionsErrors.set(context.task, /* @__PURE__ */ new Error("expected any number of assertion, but got none"));
188
+ let _expect;
189
+ return Object.defineProperty(context, "expect", { get() {
190
+ if (!_expect) _expect = createExpect(context.task);
191
+ return _expect;
192
+ } }), Object.defineProperty(context, "_local", { get() {
193
+ return _expect != null;
194
+ } }), context;
195
+ }
196
+ getImportDurations() {
197
+ const entries = [...this.workerState.moduleExecutionInfo?.entries() ?? []];
198
+ return Object.fromEntries(entries.map(([filepath, { duration, selfTime }]) => [normalize(filepath), {
199
+ selfTime,
200
+ totalTime: duration
201
+ }]));
202
+ }
203
+ }
204
+ function clearModuleMocks(config) {
205
+ const { clearMocks, mockReset, restoreMocks, unstubEnvs, unstubGlobals } = config;
206
+ // since each function calls another, we can just call one
207
+ if (restoreMocks) vi.restoreAllMocks();
208
+ else if (mockReset) vi.resetAllMocks();
209
+ else if (clearMocks) vi.clearAllMocks();
210
+ if (unstubEnvs) vi.unstubAllEnvs();
211
+ if (unstubGlobals) vi.unstubAllGlobals();
212
+ }
213
+
214
+ export { NodeBenchmarkRunner as N, VitestTestRunner as V };
@@ -30,6 +30,49 @@ function wrapSerializableConfig(config) {
30
30
  defines
31
31
  };
32
32
  }
33
+ function createDefinesScript(define) {
34
+ if (!define) return "";
35
+ const serializedDefine = serializeDefine(define);
36
+ return serializedDefine === "{}" ? "" : `
37
+ const defines = ${serializeDefine(define)}
38
+ Object.keys(defines).forEach((key) => {
39
+ const segments = key.split('.')
40
+ let target = globalThis
41
+ for (let i = 0; i < segments.length; i++) {
42
+ const segment = segments[i]
43
+ if (i === segments.length - 1) {
44
+ target[segment] = defines[key]
45
+ } else {
46
+ target = target[segment] || (target[segment] = {})
47
+ }
48
+ }
49
+ })
50
+ `;
51
+ }
52
+ /**
53
+ * Like `JSON.stringify` but keeps raw string values as a literal
54
+ * in the generated code. For example: `"window"` would refer to
55
+ * the global `window` object directly.
56
+ */
57
+ function serializeDefine(define) {
58
+ const userDefine = {};
59
+ for (const key in define) {
60
+ // vitest sets this to avoid vite:client-inject plugin
61
+ if (key === "process.env.NODE_ENV" && define[key] === "process.env.NODE_ENV") continue;
62
+ // import.meta.env.* is handled in `importAnalysis` plugin
63
+ if (!key.startsWith("import.meta.env.")) userDefine[key] = define[key];
64
+ }
65
+ let res = `{`;
66
+ const keys = Object.keys(userDefine).sort();
67
+ for (let i = 0; i < keys.length; i++) {
68
+ const key = keys[i], val = userDefine[key];
69
+ if (res += `${JSON.stringify(key)}: ${handleDefineValue(val)}`, i !== keys.length - 1) res += `, `;
70
+ }
71
+ return `${res}}`;
72
+ }
73
+ function handleDefineValue(value) {
74
+ return typeof value === "undefined" ? "undefined" : typeof value === "string" ? value : JSON.stringify(value);
75
+ }
33
76
 
34
77
  function hasFailedSnapshot(suite) {
35
78
  return getTests(suite).some((s) => {
@@ -759,4 +802,4 @@ function findGeneratedPosition(traceMap, { line, column, source }) {
759
802
  };
760
803
  }
761
804
 
762
- export { TypeCheckError as T, Typechecker as a, ancestor as b, convertTasksToEvents as c, getOutputFile as g, hasFailedSnapshot as h, wrapSerializableConfig as w };
805
+ export { TypeCheckError as T, Typechecker as a, ancestor as b, createDefinesScript as c, convertTasksToEvents as d, getOutputFile as g, hasFailedSnapshot as h, wrapSerializableConfig as w };
@@ -18,18 +18,9 @@ function provideWorkerState(context, state) {
18
18
  enumerable: false
19
19
  }), state;
20
20
  }
21
- function getCurrentEnvironment() {
22
- const state = getWorkerState();
23
- return state?.environment.name;
24
- }
25
21
  function isChildProcess() {
26
22
  return typeof process !== "undefined" && !!process.send;
27
23
  }
28
- function setProcessTitle(title) {
29
- try {
30
- process.title = `node (${title})`;
31
- } catch {}
32
- }
33
24
  function resetModules(modules, resetMocks = false) {
34
25
  const skipPaths = [
35
26
  /\/vitest\/dist\//,
@@ -52,4 +43,4 @@ async function waitForImportsToResolve() {
52
43
  !promises.length && !resolvingCount || (await Promise.allSettled(promises), await waitForImportsToResolve());
53
44
  }
54
45
 
55
- export { getCurrentEnvironment as a, getWorkerState as g, isChildProcess as i, provideWorkerState as p, resetModules as r, setProcessTitle as s, waitForImportsToResolve as w };
46
+ export { getWorkerState as g, isChildProcess as i, provideWorkerState as p, resetModules as r, waitForImportsToResolve as w };