vitest 4.1.12 → 5.1.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.
Files changed (121) hide show
  1. package/LICENSE.md +192 -10
  2. package/browser/context.d.ts +7 -1
  3. package/browser/context.js +5 -5
  4. package/config.d.ts +0 -2
  5. package/dist/browser.d.ts +52 -21
  6. package/dist/browser.js +12 -13
  7. package/dist/chunks/{acorn.B2iPLyUM.js → acorn.C1kjbUFw.js} +30 -30
  8. package/dist/chunks/{base.B6Opl8PE.js → base.Cof-UHJf.js} +81 -52
  9. package/dist/chunks/{browser.d.BcoexmFG.d.ts → browser.d.C7tWgUvw.d.ts} +17 -14
  10. package/dist/chunks/{cac.DzDtg8hz.js → cac.BYbt0aJp.js} +143 -87
  11. package/dist/chunks/{cli-api.B0Pz1_R7.js → cli-api.COfZo8lK.js} +7160 -7189
  12. package/dist/chunks/config.d.B3YV4t0O.d.ts +3873 -0
  13. package/dist/chunks/{console.3WNpx0tS.js → console.CQZ877Hi.js} +69 -63
  14. package/dist/chunks/{constants.CPYnjOGj.js → constants.DLYM6cZY.js} +2 -2
  15. package/dist/chunks/coverage.9iqXE2gN.js +26 -0
  16. package/dist/chunks/{coverage.CTzCuANN.js → coverage.jGCktcGP.js} +7 -2
  17. package/dist/chunks/{creator.DgVhQm5q.js → creator.DHWmytIK.js} +65 -28
  18. package/dist/chunks/{defaults.9aQKnqFk.js → defaults.B1FCaFfh.js} +16 -9
  19. package/dist/chunks/display.BlTmubjj.js +194 -0
  20. package/dist/chunks/doctor.B-oPbwps.js +465 -0
  21. package/dist/chunks/{env.D4Lgay0q.js → env.BKKtU2WC.js} +2 -1
  22. package/dist/chunks/{environment.d.CrsxCzP1.d.ts → environment.d.BFQtFKdZ.d.ts} +9 -1
  23. package/dist/chunks/globals.ZKtKSkEf.js +29 -0
  24. package/dist/chunks/index.Bi0NXYPf.js +1708 -0
  25. package/dist/chunks/{index.CMESou6r.js → index.BoyTG_B7.js} +82 -81
  26. package/dist/chunks/index.CZzC1gGg.js +8501 -0
  27. package/dist/chunks/index.D0heQG4v.js +1318 -0
  28. package/dist/chunks/index.Di8au7q4.js +15665 -0
  29. package/dist/chunks/{index.Chj8NDwU.js → index.DmDMHCg8.js} +6 -12
  30. package/dist/chunks/{index.DXx9Dtk7.js → index.w_oBZ9N8.js} +25 -12
  31. package/dist/chunks/{init-forks.H5ZuobOQ.js → init-forks.BaDXQSD8.js} +7 -10
  32. package/dist/chunks/{init-threads.6kl1khcL.js → init-threads.ZX_Vov0z.js} +1 -1
  33. package/dist/chunks/{init.k9zZ9sLh.js → init.CO4AB7HZ.js} +113 -38
  34. package/dist/chunks/module-dependencies._2Eei3FO.js +71 -0
  35. package/dist/chunks/{native.DPzPHdi5.js → native.upB-V0CK.js} +50 -37
  36. package/dist/chunks/{nativeModuleMocker.BkNfQMkH.js → nativeModuleMocker.Dh5azSB4.js} +48 -19
  37. package/dist/chunks/{index.BCY_7LL2.js → nativeModuleRunner.9xPIMzi7.js} +110 -42
  38. package/dist/chunks/node.B9mkVmLH.js +47 -0
  39. package/dist/chunks/offset.Dy-5Fdfn.js +24 -0
  40. package/dist/chunks/pathe.M-eThtNZ.zq3TM4NT.js +492 -0
  41. package/dist/chunks/{reporters.d.DtoKVV2s.d.ts → plugin.d.LRFSN46m.d.ts} +2573 -1453
  42. package/dist/chunks/plugins.DPQHVT0p.js +37 -0
  43. package/dist/chunks/rawSnapshot.DqSiqIEx.js +356 -0
  44. package/dist/chunks/resolver.BzpmeQeT.js +48 -0
  45. package/dist/chunks/rpc.Uhkwr2NM.js +93 -0
  46. package/dist/chunks/rpc.d.3FOhdFx8.d.ts +75 -0
  47. package/dist/chunks/run.CjdgFZiW.js +4231 -0
  48. package/dist/chunks/setup-common.CqAQCXzx.js +36 -0
  49. package/dist/chunks/source-map.DakdQc29.js +1788 -0
  50. package/dist/chunks/source-map.d.BkG8YK_3.d.ts +89 -0
  51. package/dist/chunks/spy.DDMXghXv.js +509 -0
  52. package/dist/chunks/task-utils.d.D-gFPNFi.d.ts +144 -0
  53. package/dist/chunks/tinyrainbow.Do8I1XRG.js +88 -0
  54. package/dist/chunks/{utils.BS4fH3nR.js → utils.BBk_icFG.js} +50 -52
  55. package/dist/chunks/{utils.BX5Fg8C4.js → utils.DYj33du9.js} +1 -17
  56. package/dist/chunks/vm.b4MbCAJQ.js +1329 -0
  57. package/dist/chunks/{worker.d.ZpHpO4yb.d.ts → worker.d.CyJRpyfZ.d.ts} +34 -19
  58. package/dist/cli.js +5 -6
  59. package/dist/config.cjs +9 -6
  60. package/dist/config.d.ts +27 -25
  61. package/dist/config.js +3 -3
  62. package/dist/index.d.ts +471 -38
  63. package/dist/index.js +18 -19
  64. package/dist/module-evaluator.d.ts +64 -5
  65. package/dist/module-evaluator.js +122 -62
  66. package/dist/node.d.ts +355 -87
  67. package/dist/node.js +49 -73
  68. package/dist/runtime.d.ts +43 -6
  69. package/dist/runtime.js +7 -9
  70. package/dist/spy.js +1 -1
  71. package/dist/task-utils.js +290 -0
  72. package/dist/{chunks/traces.DT5aQ62U.js → traces.js} +3 -2
  73. package/dist/worker.d.ts +8 -10
  74. package/dist/worker.js +33 -43
  75. package/dist/workers/forks.js +30 -40
  76. package/dist/workers/runVmTests.js +66 -43
  77. package/dist/workers/threads.js +30 -40
  78. package/dist/workers/vmForks.js +19 -20
  79. package/dist/workers/vmThreads.js +19 -20
  80. package/globals.d.ts +19 -19
  81. package/index.cjs +3 -3
  82. package/optional-runtime-types.d.ts +1 -1
  83. package/optional-types.d.ts +1 -1
  84. package/package.json +59 -74
  85. package/suppress-warnings.cjs +1 -1
  86. package/dist/chunks/_commonjsHelpers.D26ty3Ew.js +0 -6
  87. package/dist/chunks/benchmark.CX_oY03V.js +0 -40
  88. package/dist/chunks/benchmark.d.DAaHLpsq.d.ts +0 -24
  89. package/dist/chunks/config.d.A1h_Y6Jt.d.ts +0 -232
  90. package/dist/chunks/coverage.DM_a_rWm.js +0 -1087
  91. package/dist/chunks/coverage.d.BZtK59WP.d.ts +0 -37
  92. package/dist/chunks/evaluatedModules.Dg1zASAC.js +0 -17
  93. package/dist/chunks/global.d.DVsSRdQ5.d.ts +0 -100
  94. package/dist/chunks/globals.Dj1TGiMC.js +0 -31
  95. package/dist/chunks/index.DC7d2Pf8.js +0 -729
  96. package/dist/chunks/index.DdgEv5B1.js +0 -42
  97. package/dist/chunks/index.UpGiHP7g.js +0 -4255
  98. package/dist/chunks/index.og1WyBLx.js +0 -6358
  99. package/dist/chunks/nativeModuleRunner.BIakptoF.js +0 -36
  100. package/dist/chunks/node.COQbm6gK.js +0 -14
  101. package/dist/chunks/plugin.d.DwFIiJ7i.d.ts +0 -38
  102. package/dist/chunks/rpc.MzXet3jl.js +0 -144
  103. package/dist/chunks/rpc.d.B_8sPU0w.d.ts +0 -30
  104. package/dist/chunks/setup-common.DYx3LtFI.js +0 -60
  105. package/dist/chunks/startVitestModuleRunner.DB-7oCpn.js +0 -740
  106. package/dist/chunks/suite.d.udJtyAgw.d.ts +0 -10
  107. package/dist/chunks/test.DNmyFkvJ.js +0 -4430
  108. package/dist/chunks/traces.d.D2T_R8rx.d.ts +0 -60
  109. package/dist/chunks/vm.CXMd5FHa.js +0 -785
  110. package/dist/coverage.d.ts +0 -123
  111. package/dist/coverage.js +0 -27
  112. package/dist/environments.d.ts +0 -22
  113. package/dist/environments.js +0 -5
  114. package/dist/reporters.d.ts +0 -27
  115. package/dist/reporters.js +0 -26
  116. package/dist/runners.d.ts +0 -70
  117. package/dist/runners.js +0 -19
  118. package/dist/snapshot.d.ts +0 -9
  119. package/dist/snapshot.js +0 -6
  120. package/dist/suite.d.ts +0 -5
  121. package/dist/suite.js +0 -8
@@ -1,8 +1,3 @@
1
- //#region src/messages.ts
2
- const TYPE_REQUEST = "q";
3
- const TYPE_RESPONSE = "s";
4
-
5
- //#endregion
6
1
  //#region src/utils.ts
7
2
  function createPromiseWithResolvers() {
8
3
  let resolve;
@@ -24,7 +19,6 @@ function nanoid(size = 21) {
24
19
  while (i--) id += urlAlphabet[random() * 64 | 0];
25
20
  return id;
26
21
  }
27
-
28
22
  //#endregion
29
23
  //#region src/main.ts
30
24
  const DEFAULT_TIMEOUT = 6e4;
@@ -42,7 +36,7 @@ function createBirpc($functions, options) {
42
36
  const req = {
43
37
  m: method,
44
38
  a: args,
45
- t: TYPE_REQUEST
39
+ t: "q"
46
40
  };
47
41
  if (optional) req.o = true;
48
42
  const send = async (_req) => post(serialize(_req));
@@ -96,7 +90,7 @@ function createBirpc($functions, options) {
96
90
  $call: (method, ...args) => _call(method, args, false),
97
91
  $callOptional: (method, ...args) => _call(method, args, false, true),
98
92
  $callEvent: (method, ...args) => _call(method, args, true),
99
- $callRaw: (options$1) => _call(options$1.method, options$1.args, options$1.event, options$1.optional),
93
+ $callRaw: (options) => _call(options.method, options.args, options.event, options.optional),
100
94
  $rejectPendingCalls,
101
95
  get $closed() {
102
96
  return $closed;
@@ -108,7 +102,7 @@ function createBirpc($functions, options) {
108
102
  $functions
109
103
  };
110
104
  if (proxify) rpc = new Proxy({}, { get(_, method) {
111
- if (Object.prototype.hasOwnProperty.call(builtinMethods, method)) return builtinMethods[method];
105
+ if (Object.hasOwn(builtinMethods, method)) return builtinMethods[method];
112
106
  if (method === "then" && !eventNames.includes("then") && !("then" in $functions)) return void 0;
113
107
  const sendEvent = (...args) => _call(method, args, true);
114
108
  if (eventNames.includes(method)) {
@@ -152,7 +146,7 @@ function createBirpc($functions, options) {
152
146
  if (options.onGeneralError?.call(rpc, e) !== true) throw e;
153
147
  return;
154
148
  }
155
- if (msg.t === TYPE_REQUEST) {
149
+ if (msg.t === "q") {
156
150
  const { m: method, a: args, o: optional } = msg;
157
151
  let result, error;
158
152
  let fn = await (resolver ? resolver.call(rpc, method, $functions[method]) : $functions[method]);
@@ -169,7 +163,7 @@ function createBirpc($functions, options) {
169
163
  }
170
164
  if (!error) try {
171
165
  await post(serialize({
172
- t: TYPE_RESPONSE,
166
+ t: "s",
173
167
  i: msg.i,
174
168
  r: result
175
169
  }), ...extra);
@@ -180,7 +174,7 @@ function createBirpc($functions, options) {
180
174
  }
181
175
  try {
182
176
  await post(serialize({
183
- t: TYPE_RESPONSE,
177
+ t: "s",
184
178
  i: msg.i,
185
179
  e: error
186
180
  }), ...extra);
@@ -1,9 +1,10 @@
1
- import { chai } from '@vitest/expect';
1
+ import * as chai from 'chai';
2
2
  import { createHook } from 'node:async_hooks';
3
- import { l as loadDiffConfig, a as loadSnapshotSerializers, t as takeCoverageInsideWorker } from './setup-common.DYx3LtFI.js';
4
- import { r as rpc } from './rpc.MzXet3jl.js';
5
- import { g as getWorkerState } from './utils.BX5Fg8C4.js';
6
- import { T as TestRunner, N as NodeBenchmarkRunner } from './test.DNmyFkvJ.js';
3
+ import { t as takeCoverageInsideWorker } from './coverage.9iqXE2gN.js';
4
+ import { r as rpc } from './rpc.Uhkwr2NM.js';
5
+ import { l as loadDiffConfig, a as loadSnapshotSerializers } from './setup-common.CqAQCXzx.js';
6
+ import { g as getWorkerState } from './utils.DYj33du9.js';
7
+ import { T as TestRunner } from './index.CZzC1gGg.js';
7
8
 
8
9
  function setupChaiConfig(config) {
9
10
  Object.assign(chai.config, config);
@@ -11,7 +12,7 @@ function setupChaiConfig(config) {
11
12
 
12
13
  async function resolveSnapshotEnvironment(config, moduleRunner) {
13
14
  if (!config.snapshotEnvironment) {
14
- const { VitestNodeSnapshotEnvironment } = await import('./node.COQbm6gK.js');
15
+ const { VitestNodeSnapshotEnvironment } = await import('./node.B9mkVmLH.js');
15
16
  return new VitestNodeSnapshotEnvironment();
16
17
  }
17
18
  const mod = await moduleRunner.import(config.snapshotEnvironment);
@@ -19,7 +20,7 @@ async function resolveSnapshotEnvironment(config, moduleRunner) {
19
20
  return mod.default;
20
21
  }
21
22
 
22
- const IGNORED_TYPES = new Set([
23
+ const IGNORED_TYPES = /* @__PURE__ */ new Set([
23
24
  "DNSCHANNEL",
24
25
  "ELDHISTOGRAM",
25
26
  "PerformanceObserver",
@@ -31,6 +32,7 @@ const IGNORED_TYPES = new Set([
31
32
  "TLSWRAP",
32
33
  "ZLIB"
33
34
  ]);
35
+ const STDIO_TYPES = /* @__PURE__ */ new Set(["PIPEWRAP", "TTYWRAP"]);
34
36
  function detectAsyncLeaks(testFile, projectName) {
35
37
  const resources = /* @__PURE__ */ new Map();
36
38
  const hook = createHook({
@@ -48,6 +50,8 @@ function detectAsyncLeaks(testFile, projectName) {
48
50
  } finally {
49
51
  Error.stackTraceLimit = limit;
50
52
  }
53
+ // a builtin loaded on first use can create pending promises at the module level
54
+ if (stack.includes("node:internal/bootstrap/realm")) return;
51
55
  if (!stack.includes(testFile)) {
52
56
  const trigger = resources.get(triggerAsyncId);
53
57
  if (!trigger) return;
@@ -63,7 +67,8 @@ function detectAsyncLeaks(testFile, projectName) {
63
67
  stack,
64
68
  projectName,
65
69
  filename: testFile,
66
- isActive
70
+ isActive,
71
+ handle: STDIO_TYPES.has(type) ? new WeakRef(resource) : void 0
67
72
  });
68
73
  },
69
74
  destroy(asyncId) {
@@ -75,10 +80,10 @@ function detectAsyncLeaks(testFile, projectName) {
75
80
  });
76
81
  hook.enable();
77
82
  return async function collect() {
78
- await Promise.resolve(setImmediate);
83
+ await new Promise((resolve) => setImmediate(resolve));
79
84
  hook.disable();
80
85
  const leaks = [];
81
- for (const resource of resources.values()) if (resource.isActive()) leaks.push({
86
+ for (const resource of resources.values()) if (resource.isActive() && !isStdioHandle(resource.handle?.deref())) leaks.push({
82
87
  stack: resource.stack,
83
88
  type: resource.type,
84
89
  filename: resource.filename,
@@ -91,9 +96,17 @@ function detectAsyncLeaks(testFile, projectName) {
91
96
  function isActiveDefault() {
92
97
  return true;
93
98
  }
99
+ function isStdioHandle(handle) {
100
+ if (!handle) return false;
101
+ return [
102
+ process.stdin,
103
+ process.stdout,
104
+ process.stderr
105
+ ].some((stream) => stream._handle === handle);
106
+ }
94
107
 
95
108
  async function getTestRunnerConstructor(config, moduleRunner) {
96
- if (!config.runner) return config.mode === "test" ? TestRunner : NodeBenchmarkRunner;
109
+ if (!config.runner) return TestRunner;
97
110
  const mod = await moduleRunner.import(config.runner);
98
111
  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}`);
99
112
  return mod.default;
@@ -110,7 +123,7 @@ async function resolveTestRunner(config, moduleRunner, traces) {
110
123
  if (!testRunner.importFile) throw new Error("Runner must implement \"importFile\" method.");
111
124
  if ("__setTraces" in testRunner) testRunner.__setTraces(traces);
112
125
  const [diffOptions] = await Promise.all([loadDiffConfig(config, moduleRunner), loadSnapshotSerializers(config, moduleRunner)]);
113
- testRunner.config.diffOptions = diffOptions;
126
+ testRunner.config._diffOptions = diffOptions;
114
127
  // patch some methods, so custom runners don't need to call RPC
115
128
  const originalOnTaskUpdate = testRunner.onTaskUpdate;
116
129
  testRunner.onTaskUpdate = async (task, events) => {
@@ -1,4 +1,4 @@
1
- import { i as init } from './init.k9zZ9sLh.js';
1
+ import { i as init } from './init.CO4AB7HZ.js';
2
2
 
3
3
  if (!process.send) throw new Error("Expected worker to be run in node:child_process");
4
4
  // Store globals in case tests overwrite them
@@ -19,18 +19,15 @@ function workerInit(options) {
19
19
  teardown: () => {
20
20
  processRemoveAllListeners("message");
21
21
  processOff("error", onError);
22
+ // the guard installed by the test runner stays active between test
23
+ // files: with `isolate: false` a late process.exit would kill the
24
+ // other files sharing this process
25
+ process.exit = processExit;
22
26
  },
23
- runTests: (state, traces) => executeTests("run", state, traces),
24
- collectTests: (state, traces) => executeTests("collect", state, traces),
27
+ runTests: (state, traces) => runTests("run", state, traces),
28
+ collectTests: (state, traces) => runTests("collect", state, traces),
25
29
  setup: options.setup
26
30
  });
27
- async function executeTests(method, state, traces) {
28
- try {
29
- await runTests(method, state, traces);
30
- } finally {
31
- process.exit = processExit;
32
- }
33
- }
34
31
  }
35
32
  // Prevent leaving worker in loops where it tries to send message to closed main
36
33
  // thread, errors, and tries to send the error.
@@ -1,5 +1,5 @@
1
1
  import { isMainThread, parentPort } from 'node:worker_threads';
2
- import { i as init } from './init.k9zZ9sLh.js';
2
+ import { i as init } from './init.CO4AB7HZ.js';
3
3
 
4
4
  if (isMainThread || !parentPort) throw new Error("Expected worker to be run in node:worker_threads");
5
5
  function workerInit(options) {
@@ -1,19 +1,15 @@
1
1
  import { readFileSync } from 'node:fs';
2
- import { isBuiltin } from 'node:module';
2
+ import module$1, { isBuiltin } from 'node:module';
3
3
  import { pathToFileURL } from 'node:url';
4
- import { resolve } from 'pathe';
5
- import { ModuleRunner, EvaluatedModules } from 'vite/module-runner';
6
- import { b as VitestTransport } from './startVitestModuleRunner.DB-7oCpn.js';
7
- import { e as environments } from './index.DC7d2Pf8.js';
8
- import { serializeValue } from '@vitest/utils/serialize';
9
- import { serializeError } from '@vitest/utils/error';
10
- import { disableDefaultColors } from 'tinyrainbow';
11
- import { T as Traces } from './traces.DT5aQ62U.js';
12
- import { o as onCancel, a as rpcDone, c as createRuntimeRpc } from './rpc.MzXet3jl.js';
13
- import { createStackString, parseStacktrace } from '@vitest/utils/source-map';
4
+ import { EvaluatedModules, ModuleRunner } from 'vite/module-runner';
5
+ import { e as environments, b as VitestTransport } from './index.Bi0NXYPf.js';
6
+ import { r as resolve } from './pathe.M-eThtNZ.zq3TM4NT.js';
7
+ import { b as serializeValue, c as createStackString, p as parseStacktrace } from './source-map.DakdQc29.js';
8
+ import { w } from './tinyrainbow.Do8I1XRG.js';
9
+ import { Traces } from '../traces.js';
10
+ import { o as onCancel, V as VitestEvaluatedModules, a as rpcDone, c as createRuntimeRpc } from './rpc.Uhkwr2NM.js';
14
11
  import { s as setupInspect } from './inspector.CvyFGlXm.js';
15
- import { V as VitestEvaluatedModules } from './evaluatedModules.Dg1zASAC.js';
16
- import { E as EnvironmentTeardownError } from './utils.BX5Fg8C4.js';
12
+ import { E as EnvironmentTeardownError } from './utils.DYj33du9.js';
17
13
 
18
14
  function isBuiltinEnvironment(env) {
19
15
  return env in environments;
@@ -24,6 +20,7 @@ function createEnvironmentLoader(root, rpc) {
24
20
  const cachedLoader = _loaders.get(root);
25
21
  if (!cachedLoader || cachedLoader.isClosed()) {
26
22
  _loaders.delete(root);
23
+ const evaluatedModules = new EvaluatedModules();
27
24
  const moduleRunner = new ModuleRunner({
28
25
  hmr: false,
29
26
  sourcemapInterceptor: "prepareStackTrace",
@@ -43,7 +40,7 @@ function createEnvironmentLoader(root, rpc) {
43
40
  async resolveId(id, importer) {
44
41
  return rpc.resolve(id, importer, "__vitest__");
45
42
  }
46
- }, new EvaluatedModules(), /* @__PURE__ */ new WeakMap())
43
+ }, evaluatedModules, /* @__PURE__ */ new WeakMap())
47
44
  });
48
45
  _loaders.set(root, moduleRunner);
49
46
  }
@@ -81,7 +78,7 @@ function onCleanup(cb) {
81
78
  cleanupListeners.add(cb);
82
79
  }
83
80
  async function cleanup() {
84
- await Promise.all([...cleanupListeners].map((l) => l()));
81
+ await Promise.all(Array.from(cleanupListeners, (l) => l()));
85
82
  }
86
83
  function onModuleRunner(cb) {
87
84
  moduleRunnerListeners.add(cb);
@@ -120,6 +117,33 @@ function listenForErrors(state) {
120
117
  });
121
118
  }
122
119
 
120
+ class GetterTracker {
121
+ static EXPORTS_MAX_INVOCATIONS = 1e6;
122
+ invocations = /* @__PURE__ */ new Map();
123
+ excessiveInvocations = /* @__PURE__ */ new Map();
124
+ createTracker(moduleId, defineExport) {
125
+ return (name, getter) => {
126
+ const key = `${moduleId}:${name}`;
127
+ defineExport(name, () => {
128
+ const count = (this.invocations.get(key) || 0) + 1;
129
+ this.invocations.set(key, count);
130
+ if (count > GetterTracker.EXPORTS_MAX_INVOCATIONS && !this.excessiveInvocations.has(key)) this.excessiveInvocations.set(key, {
131
+ moduleId,
132
+ exportName: name
133
+ });
134
+ return getter();
135
+ });
136
+ };
137
+ }
138
+ resetInvocations() {
139
+ this.invocations.clear();
140
+ this.excessiveInvocations.clear();
141
+ }
142
+ getExcessiveInvocations() {
143
+ return [...this.excessiveInvocations.values()];
144
+ }
145
+ }
146
+
123
147
  const resolvingModules = /* @__PURE__ */ new Set();
124
148
  async function execute(method, ctx, worker, traces) {
125
149
  const prepareStart = performance.now();
@@ -135,14 +159,18 @@ async function execute(method, ctx, worker, traces) {
135
159
  });
136
160
  const state = {
137
161
  ctx,
162
+ // here we create a new one, workers can reassign this if they need to keep it non-isolated
138
163
  evaluatedModules: new VitestEvaluatedModules(),
139
164
  resolvingModules,
140
165
  moduleExecutionInfo: /* @__PURE__ */ new Map(),
166
+ dependencies: ctx.config.experimental.recordDependencies ? /* @__PURE__ */ new Set() : void 0,
141
167
  config: ctx.config,
168
+ // this is set later by vm or base
142
169
  environment: null,
143
170
  durations: {
144
171
  environment: 0,
145
- prepare: prepareStart
172
+ prepare: prepareStart,
173
+ fetch: 0
146
174
  },
147
175
  rpc,
148
176
  onCancel,
@@ -151,7 +179,8 @@ async function execute(method, ctx, worker, traces) {
151
179
  onFilterStackTrace(stack) {
152
180
  return createStackString(parseStacktrace(stack));
153
181
  },
154
- metaEnv: createImportMetaEnvProxy()
182
+ metaEnv: ctx.metaEnv,
183
+ getterTracker: ctx.config.benchmark.enabled && !ctx.config.benchmark.suppressExportGetterWarnings ? new GetterTracker() : void 0
155
184
  };
156
185
  const methodName = method === "collect" ? "collectTests" : "runTests";
157
186
  if (!worker[methodName] || typeof worker[methodName] !== "function") throw new TypeError(`Test worker should expose "runTests" method. Received "${typeof worker.runTests}".`);
@@ -170,15 +199,16 @@ function collect(ctx, worker, traces) {
170
199
  async function teardown() {
171
200
  await cleanup();
172
201
  }
173
- const env = process.env;
202
+
203
+ // default import: `flushCompileCache` only exists since Node 22.10, a named
204
+ // import would fail to link on older versions
174
205
  function createImportMetaEnvProxy() {
175
- // packages/vitest/src/node/plugins/index.ts:146
176
206
  const booleanKeys = [
177
207
  "DEV",
178
208
  "PROD",
179
209
  "SSR"
180
210
  ];
181
- return new Proxy(env, {
211
+ return new Proxy(process.env, {
182
212
  get(_, key) {
183
213
  if (typeof key !== "string") return;
184
214
  if (booleanKeys.includes(key)) return !!process.env[key];
@@ -192,19 +222,39 @@ function createImportMetaEnvProxy() {
192
222
  }
193
223
  });
194
224
  }
195
-
225
+ const importMetaEnvProxy = createImportMetaEnvProxy();
196
226
  const __vitest_worker_response__ = true;
197
227
  const memoryUsage = process.memoryUsage.bind(process);
198
228
  let reportMemory = false;
229
+ const streams = [{ write: process.stdout.write.bind(process.stdout) }, { write: process.stderr.write.bind(process.stderr) }];
230
+ // In worker threads stdio is proxied to the parent over a MessagePort with a
231
+ // backpressure protocol: a chunk stays buffered inside the worker until the
232
+ // parent acks the previous one. The pool starts `runner.stop()` as soon as it
233
+ // receives `testfileFinished`, and `thread.terminate()` halts the worker before
234
+ // buffered chunks are ever posted, losing output. An empty write's callback
235
+ // only fires after every previously buffered chunk has been acked, so awaiting
236
+ // it before signaling completion guarantees the output reached the parent.
237
+ // A cheap no-op for forks, where stdio goes through OS pipes.
238
+ function flushStdio() {
239
+ const flush = (stream) => new Promise((resolve) => {
240
+ try {
241
+ stream.write("", () => resolve(void 0));
242
+ } catch {
243
+ resolve(void 0);
244
+ }
245
+ });
246
+ return Promise.all(streams.map((stream) => flush(stream)));
247
+ }
199
248
  let traces;
200
249
  /** @experimental */
201
250
  function init(worker) {
202
- worker.on(onMessage);
203
- if (worker.onModuleRunner) onModuleRunner(worker.onModuleRunner);
204
251
  let runPromise;
205
252
  let isRunning = false;
206
253
  let workerTeardown;
207
254
  let setupContext;
255
+ let poolId;
256
+ worker.on(onMessage);
257
+ if (worker.onModuleRunner) onModuleRunner(worker.onModuleRunner);
208
258
  function send(response) {
209
259
  worker.post(worker.serialize ? worker.serialize(response) : response);
210
260
  }
@@ -216,7 +266,8 @@ function init(worker) {
216
266
  process.env.VITEST_POOL_ID = String(message.poolId);
217
267
  process.env.VITEST_WORKER_ID = String(message.workerId);
218
268
  reportMemory = message.options.reportMemory;
219
- if (message.context.config.isAgent) disableDefaultColors();
269
+ poolId = message.poolId;
270
+ if (message.context.config.disableColors) w();
220
271
  traces ??= await new Traces({
221
272
  enabled: message.traces.enabled,
222
273
  sdkPath: message.traces.sdkPath
@@ -231,6 +282,7 @@ function init(worker) {
231
282
  config,
232
283
  pool,
233
284
  rpc: createRuntimeRpc(worker),
285
+ metaEnv: importMetaEnvProxy,
234
286
  projectName: config.name || "",
235
287
  traces
236
288
  };
@@ -243,7 +295,7 @@ function init(worker) {
243
295
  send({
244
296
  type: "started",
245
297
  __vitest_worker_response__,
246
- error: serializeError(error)
298
+ error: serializeValue(error)
247
299
  });
248
300
  }
249
301
  break;
@@ -254,7 +306,7 @@ function init(worker) {
254
306
  send({
255
307
  type: "testfileFinished",
256
308
  __vitest_worker_response__,
257
- error: serializeError(/* @__PURE__ */ new Error("[vitest-worker]: Worker is already running tests"))
309
+ error: serializeValue(/* @__PURE__ */ new Error("[vitest-worker]: Worker is already running tests"))
258
310
  });
259
311
  return;
260
312
  }
@@ -264,7 +316,7 @@ function init(worker) {
264
316
  return send({
265
317
  type: "testfileFinished",
266
318
  __vitest_worker_response__,
267
- error: serializeError(error),
319
+ error: serializeValue(error),
268
320
  usedMemory: reportMemory ? memoryUsage().heapUsed : void 0
269
321
  });
270
322
  }
@@ -279,12 +331,15 @@ function init(worker) {
279
331
  }
280
332
  }, () => run({
281
333
  ...setupContext,
282
- ...message.context
283
- }, worker, traces).catch((error) => serializeError(error)));
334
+ ...message.context,
335
+ concurrencyId: poolId
336
+ }, worker, traces).catch((error) => serializeValue(error)));
337
+ const error = await runPromise;
338
+ await flushStdio();
284
339
  send({
285
340
  type: "testfileFinished",
286
341
  __vitest_worker_response__,
287
- error: await runPromise,
342
+ error,
288
343
  usedMemory: reportMemory ? memoryUsage().heapUsed : void 0
289
344
  });
290
345
  } finally {
@@ -298,7 +353,7 @@ function init(worker) {
298
353
  send({
299
354
  type: "testfileFinished",
300
355
  __vitest_worker_response__,
301
- error: serializeError(/* @__PURE__ */ new Error("[vitest-worker]: Worker is already running tests"))
356
+ error: serializeValue(/* @__PURE__ */ new Error("[vitest-worker]: Worker is already running tests"))
302
357
  });
303
358
  return;
304
359
  }
@@ -308,7 +363,7 @@ function init(worker) {
308
363
  return send({
309
364
  type: "testfileFinished",
310
365
  __vitest_worker_response__,
311
- error: serializeError(error),
366
+ error: serializeValue(error),
312
367
  usedMemory: reportMemory ? memoryUsage().heapUsed : void 0
313
368
  });
314
369
  }
@@ -323,12 +378,15 @@ function init(worker) {
323
378
  }
324
379
  }, () => collect({
325
380
  ...setupContext,
326
- ...message.context
327
- }, worker, traces).catch((error) => serializeError(error)));
381
+ ...message.context,
382
+ concurrencyId: poolId
383
+ }, worker, traces).catch((error) => serializeValue(error)));
384
+ const error = await runPromise;
385
+ await flushStdio();
328
386
  send({
329
387
  type: "testfileFinished",
330
388
  __vitest_worker_response__,
331
- error: await runPromise,
389
+ error,
332
390
  usedMemory: reportMemory ? memoryUsage().heapUsed : void 0
333
391
  });
334
392
  } finally {
@@ -336,30 +394,47 @@ function init(worker) {
336
394
  isRunning = false;
337
395
  }
338
396
  break;
339
- case "stop":
397
+ case "stop": {
340
398
  await runPromise;
399
+ // Persist this worker's compile cache before the parent tears the
400
+ // worker down — forks are SIGTERM'd and never reach Node's exit-time
401
+ // flush, so without this the cache stays write-only for them. Runs
402
+ // even when teardown throws (the compiled modules are still worth
403
+ // persisting). A no-op when the cache is disabled or was fully loaded
404
+ // from disk, and cheap (~tens of ms) otherwise, so every worker can
405
+ // afford it.
406
+ const persistCompileCache = () => {
407
+ try {
408
+ module$1.flushCompileCache?.();
409
+ } catch {}
410
+ };
341
411
  try {
342
412
  const context = traces.getContextFromCarrier(message.otelCarrier);
343
413
  const error = await traces.$("vitest.runtime.teardown", { context }, async () => {
344
- const error = await teardown().catch((error) => serializeError(error));
414
+ const error = await teardown().catch((error) => serializeValue(error));
345
415
  await workerTeardown?.();
346
416
  return error;
347
417
  });
348
418
  await traces.finish();
419
+ persistCompileCache();
420
+ await flushStdio();
349
421
  send({
350
422
  type: "stopped",
351
423
  error,
352
424
  __vitest_worker_response__
353
425
  });
354
426
  } catch (error) {
427
+ persistCompileCache();
428
+ await flushStdio();
355
429
  send({
356
430
  type: "stopped",
357
- error: serializeError(error),
431
+ error: serializeValue(error),
358
432
  __vitest_worker_response__
359
433
  });
360
434
  }
361
435
  worker.teardown?.();
362
436
  break;
437
+ }
363
438
  }
364
439
  }
365
440
  }
@@ -0,0 +1,71 @@
1
+ import module$1 from 'node:module';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { s as slash } from './pathe.M-eThtNZ.zq3TM4NT.js';
4
+ import { distDir } from '../path.js';
5
+
6
+ const vitestDistDir = `${slash(distDir)}/`;
7
+ /**
8
+ * Ids of the roots and of every module reachable from them through the runtime import edges.
9
+ */
10
+ function collectDependencies(getImports, ...roots) {
11
+ const visited = /* @__PURE__ */ new Set();
12
+ const queue = [];
13
+ for (const ids of roots) for (const id of ids) if (!visited.has(id)) {
14
+ visited.add(id);
15
+ queue.push(id);
16
+ }
17
+ while (queue.length) {
18
+ const imports = getImports(queue.pop());
19
+ if (!imports) continue;
20
+ for (const id of imports) if (!visited.has(id)) {
21
+ visited.add(id);
22
+ queue.push(id);
23
+ }
24
+ }
25
+ return Array.from(visited);
26
+ }
27
+ function getEvaluatedImports(evaluatedModules) {
28
+ return (id) => evaluatedModules.getModuleById(id)?.imports;
29
+ }
30
+ class NativeImportGraph {
31
+ imports = /* @__PURE__ */ new Map();
32
+ /**
33
+ * Returns the imported file, or `undefined` if the import is not tracked.
34
+ */
35
+ record(url, parentURL) {
36
+ if (!url.startsWith("file:") || url.includes("/node_modules/")) return;
37
+ const file = slash(fileURLToPath(url));
38
+ const importer = parentURL.startsWith("file:") ? slash(fileURLToPath(parentURL)) : parentURL;
39
+ // Vitest imports every test file, its edges would connect unrelated test files
40
+ if (!importer.startsWith(vitestDistDir)) {
41
+ let imports = this.imports.get(importer);
42
+ if (!imports) this.imports.set(importer, imports = /* @__PURE__ */ new Set());
43
+ imports.add(file);
44
+ }
45
+ return file;
46
+ }
47
+ getImports = (id) => this.imports.get(id);
48
+ }
49
+ /**
50
+ * Import edges of the modules loaded with native `import`, reported by a Node.js resolve hook.
51
+ * Node.js never loads a module twice, so the edges are kept as long as the thread runs.
52
+ */
53
+ const nativeImports = new NativeImportGraph();
54
+ let trackingNativeImports = false;
55
+ /**
56
+ * Registers a resolve hook that records the native imports of this thread.
57
+ * Returns `false` if the runtime has no synchronous module hooks.
58
+ */
59
+ function trackNativeImports() {
60
+ if (!trackingNativeImports && typeof module$1.registerHooks === "function") {
61
+ module$1.registerHooks({ resolve(specifier, context, nextResolve) {
62
+ const result = nextResolve(specifier, context);
63
+ if (context.parentURL) nativeImports.record(result.url, context.parentURL);
64
+ return result;
65
+ } });
66
+ trackingNativeImports = true;
67
+ }
68
+ return trackingNativeImports;
69
+ }
70
+
71
+ export { collectDependencies as c, getEvaluatedImports as g, nativeImports as n, trackNativeImports as t };