vitest 5.1.0 → 5.1.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 (60) hide show
  1. package/dist/browser.d.ts +6 -5
  2. package/dist/browser.js +7 -7
  3. package/dist/chunks/{base.Cof-UHJf.js → base.C2su7_N0.js} +12 -12
  4. package/dist/chunks/{browser.d.C7tWgUvw.d.ts → browser.d.B-QwH_F6.d.ts} +3 -3
  5. package/dist/chunks/{cac.BYbt0aJp.js → cac.BK306qhQ.js} +15 -10
  6. package/dist/chunks/{cli-api.COfZo8lK.js → cli-api.D6E8EtSi.js} +317 -134
  7. package/dist/chunks/{config.d.B3YV4t0O.d.ts → config.d.BpJq6tRA.d.ts} +7 -1
  8. package/dist/chunks/{console.CQZ877Hi.js → console.VJUxd1rM.js} +2 -2
  9. package/dist/chunks/{creator.DHWmytIK.js → creator.CoOCr85O.js} +12 -10
  10. package/dist/chunks/{display.BlTmubjj.js → display.Cj2h2zsY.js} +1 -1
  11. package/dist/chunks/{doctor.B-oPbwps.js → doctor.SRjZIZuA.js} +1 -1
  12. package/dist/chunks/{environment.d.BFQtFKdZ.d.ts → environment.d.rlpAM-ON.d.ts} +1 -1
  13. package/dist/chunks/{globals.ZKtKSkEf.js → globals.Mxora3_v.js} +10 -10
  14. package/dist/chunks/{index.Bi0NXYPf.js → index.C7Nn66Gy.js} +21 -9
  15. package/dist/chunks/{index.DmDMHCg8.js → index.CAmut2NG.js} +25 -1
  16. package/dist/chunks/{index.CZzC1gGg.js → index.DNcttN5a.js} +31 -20
  17. package/dist/chunks/{index.w_oBZ9N8.js → index.Da_szXbS.js} +3 -3
  18. package/dist/chunks/{index.Di8au7q4.js → index.ER9afepi.js} +210 -88
  19. package/dist/chunks/{index.D0heQG4v.js → index.Or9psEGe.js} +1 -1
  20. package/dist/chunks/{init-forks.BaDXQSD8.js → init-forks.q4IoGYZe.js} +7 -1
  21. package/dist/chunks/{init-threads.ZX_Vov0z.js → init-threads.Bf1Frg9S.js} +1 -1
  22. package/dist/chunks/{init.CO4AB7HZ.js → init.dGO4K2C0.js} +16 -8
  23. package/dist/chunks/{inspector.CvyFGlXm.js → inspector.D6o1NPo1.js} +12 -1
  24. package/dist/chunks/{modules.BJuCwlRJ.js → moduleSourceMap.Dp1WduWi.js} +31 -1
  25. package/dist/chunks/{native.upB-V0CK.js → native.D5q1ylZC.js} +2 -1
  26. package/dist/chunks/{nativeModuleMocker.Dh5azSB4.js → nativeModuleMocker.ihb3q7Cg.js} +4 -2
  27. package/dist/chunks/{plugin.d.LRFSN46m.d.ts → plugin.d.Du7hHZwb.d.ts} +32 -29
  28. package/dist/chunks/{plugins.DPQHVT0p.js → plugins.BPruPOR8.js} +1 -1
  29. package/dist/chunks/{rawSnapshot.DqSiqIEx.js → rawSnapshot.DvoRLRNr.js} +2 -2
  30. package/dist/chunks/{rpc.Uhkwr2NM.js → rpc.CNYWPa97.js} +3 -19
  31. package/dist/chunks/{rpc.d.3FOhdFx8.d.ts → rpc.d.DHfuwqP0.d.ts} +2 -2
  32. package/dist/chunks/{run.CjdgFZiW.js → run.zBhXlcZQ.js} +113 -49
  33. package/dist/chunks/{setup-common.CqAQCXzx.js → setup-common.wwc_NYRJ.js} +3 -3
  34. package/dist/chunks/{source-map.DakdQc29.js → source-map.DPHGMWvM.js} +3 -1
  35. package/dist/chunks/{source-map.d.BkG8YK_3.d.ts → source-map.d.xB6_75fl.d.ts} +2 -1
  36. package/dist/chunks/{spy.DDMXghXv.js → spy.BO0hTE3G.js} +76 -53
  37. package/dist/chunks/{task-utils.d.D-gFPNFi.d.ts → task-utils.d.DgSjIb7r.d.ts} +1 -1
  38. package/dist/chunks/{utils.BBk_icFG.js → utils.sAsh2ClK.js} +2 -6
  39. package/dist/chunks/{vm.b4MbCAJQ.js → vm.agn4qnmT.js} +4 -4
  40. package/dist/chunks/{worker.d.CyJRpyfZ.d.ts → worker.d.BigfbIsH.d.ts} +3 -3
  41. package/dist/cli.js +1 -1
  42. package/dist/config.d.ts +8 -8
  43. package/dist/index.d.ts +10 -10
  44. package/dist/index.js +10 -10
  45. package/dist/module-evaluator.d.ts +3 -3
  46. package/dist/module-evaluator.js +1 -1
  47. package/dist/node.d.ts +11 -10
  48. package/dist/node.js +17 -15
  49. package/dist/runtime.d.ts +5 -4
  50. package/dist/runtime.js +5 -3
  51. package/dist/spy.js +1 -1
  52. package/dist/worker.d.ts +4 -4
  53. package/dist/worker.js +19 -18
  54. package/dist/workers/forks.js +20 -19
  55. package/dist/workers/runVmTests.js +14 -14
  56. package/dist/workers/threads.js +20 -19
  57. package/dist/workers/vmForks.js +14 -13
  58. package/dist/workers/vmThreads.js +14 -13
  59. package/dist/workers/watchdog.js +20 -0
  60. package/package.json +19 -19
@@ -1,37 +1,37 @@
1
1
  import * as fs from 'node:fs';
2
2
  import fs__default, { promises, existsSync, writeFileSync, mkdirSync, readFileSync, statSync, readdirSync } from 'node:fs';
3
3
  import { r as resolveCoverageProviderModule, g as getCoverageFilesDirectory, C as CoverageProviderMap } from './coverage.jGCktcGP.js';
4
- import { o as parse, s as stringify, k as isFileServingAllowed, q as getSpecificationDocblock, t as resolveStaticMocks, u as getStaticMocks, f as createDebugger, v as hash, w as resolveCoverageReporters, x as createIndexLocationsMap, y as getOutputFile, z as groupBy, A as generateCodeFrame, C as printStack, R as RangeLocationFilterProvidedError, I as IncludeTaskLocationDisabledError, D as LocationFilterFileNotFoundError, E as GitCommandError, G as GitNotFoundError, H as VitestResolver, M as ModuleTransformService, l as resolveConfig$1, J as createClusterServer, S as ServerModuleRunner, K as attachProjectsFromEntries, N as TestProject, O as resolveAndAttachProjects, Q as RandomSequencer, b as FilesNotFoundError, U as createPool, W as astCollectTests, X as createFailedFileTask, Y as matchesProjectFilter, Z as nanoid, L as Logger, V as VitestPackageInstaller, P as PluginHarness, _ as stdout, p as prompt } from './index.Di8au7q4.js';
4
+ import { o as parse, s as stringify, k as isFileServingAllowed, q as getSpecificationDocblock, t as resolveStaticMocks, u as getStaticMocks, f as createDebugger, v as resolveCoverageReporters, w as createIndexLocationsMap, x as getOutputFile, y as groupBy, z as generateCodeFrame, A as printStack, R as RangeLocationFilterProvidedError, I as IncludeTaskLocationDisabledError, C as LocationFilterFileNotFoundError, D as GitCommandError, G as GitNotFoundError, E as VitestResolver, M as ModuleTransformService, l as resolveConfig$1, H as createClusterServer, S as ServerModuleRunner, J as attachProjectsFromEntries, K as TestProject, N as resolveAndAttachProjects, O as RandomSequencer, b as FilesNotFoundError, Q as createPool, U as astCollectTests, W as createFailedFileTask, X as matchesProjectFilter, Y as nanoid, L as Logger, V as VitestPackageInstaller, P as PluginHarness, Z as stdout, p as prompt } from './index.ER9afepi.js';
5
5
  import { readFile, writeFile, rename, stat, unlink, rm, mkdir, readdir, copyFile } from 'node:fs/promises';
6
6
  import os__default, { tmpdir, hostname } from 'node:os';
7
7
  import { j as join, b as basename, d as dirname, i as isAbsolute, r as resolve, D as noop, e as createDefer, c as cleanUrl, a as relative, s as slash, F as sanitizeFilePath, t as toArray, x as ordinal, G as deepMerge, p as isPrimitive, k as extname, n as normalize$1, u as deepClone } from './pathe.M-eThtNZ.zq3TM4NT.js';
8
- import { T as TraceMap, o as originalPositionFor, p as parseStacktrace, e as parseErrorStacktrace, b as serializeValue } from './source-map.DakdQc29.js';
9
- import { v as version } from './cac.BYbt0aJp.js';
8
+ import { T as TraceMap, o as originalPositionFor, p as parseStacktrace, e as parseErrorStacktrace, b as serializeValue } from './source-map.DPHGMWvM.js';
9
+ import { v as version } from './cac.BK306qhQ.js';
10
10
  import { performance as performance$1 } from 'node:perf_hooks';
11
- import { c as createBirpc } from './index.DmDMHCg8.js';
12
- import require$$0$3 from 'events';
11
+ import { c as createBirpc } from './index.CAmut2NG.js';
12
+ import require$$0$4 from 'events';
13
13
  import require$$1$1 from 'https';
14
- import require$$2$1 from 'http';
14
+ import require$$0 from 'http';
15
15
  import require$$3 from 'net';
16
16
  import require$$4 from 'tls';
17
17
  import require$$1 from 'crypto';
18
- import require$$0$2 from 'stream';
18
+ import require$$0$3 from 'stream';
19
19
  import require$$7 from 'url';
20
- import require$$0 from 'zlib';
21
- import require$$0$1 from 'buffer';
20
+ import require$$0$1 from 'zlib';
21
+ import require$$0$2 from 'buffer';
22
22
  import require$$2 from 'util';
23
- import { g as getDefaultExportFromCjs } from './index.D0heQG4v.js';
23
+ import { g as getDefaultExportFromCjs } from './index.Or9psEGe.js';
24
24
  import { A as API_PATH, d as defaultBrowserPort } from './constants.DLYM6cZY.js';
25
- import { i as isBuiltin } from './modules.BJuCwlRJ.js';
26
- import crypto, { createHash } from 'node:crypto';
25
+ import { i as isBuiltin, s as splitSourceMap, b as appendSourceMap } from './moduleSourceMap.Dp1WduWi.js';
26
+ import crypto, { hash, createHash } from 'node:crypto';
27
27
  import { distDir } from '../path.js';
28
- import { A as limitConcurrency, B as createTagsFilter } from './run.CjdgFZiW.js';
28
+ import { B as limitConcurrency, C as createTagsFilter } from './run.zBhXlcZQ.js';
29
29
  import { N as NativeModuleRunner } from './nativeModuleRunner.9xPIMzi7.js';
30
30
  import { getTestName, hasFailed, hasFailedSnapshot, getTests, getSuites, getTasks, getFullName, createFileTask, generateFileHash, interpretTaskModes, convertTasksToEvents } from '../task-utils.js';
31
31
  import { Traces } from '../traces.js';
32
32
  import { $ } from './tinyrainbow.Do8I1XRG.js';
33
33
  import { searchForWorkspaceRoot } from 'vite';
34
- import { w as withLabel, F as F_TREE_NODE_MIDDLE, a as F_TREE_NODE_END, f as formatTimeString, t as taskFail, s as separator, b as F_CHECK, c as F_POINTER, d as F_DOWN_RIGHT, e as formatProjectName, g as getStateSymbol, n as noun, p as padSummaryTitle, r as renderSnapshotSummary, h as getStateString$1, i as formatTime, j as countTestErrors, k as errorBanner, l as divider, m as F_RIGHT, o as getCols } from './utils.BBk_icFG.js';
34
+ import { w as withLabel, F as F_TREE_NODE_MIDDLE, a as F_TREE_NODE_END, f as formatTimeString, t as taskFail, s as separator, b as F_CHECK, c as F_POINTER, d as F_DOWN_RIGHT, e as formatProjectName, g as getStateSymbol, n as noun, p as padSummaryTitle, r as renderSnapshotSummary, h as getStateString$1, i as formatTime, j as errorBanner, k as divider, l as F_RIGHT, m as getCols } from './utils.sAsh2ClK.js';
35
35
  import module$1 from 'node:module';
36
36
  import path, { resolve as resolve$1, normalize } from 'node:path';
37
37
  import { fileURLToPath } from 'node:url';
@@ -44,7 +44,7 @@ import { isCI } from 'std-env';
44
44
  import assert from 'node:assert';
45
45
  import { x, NonZeroExitError } from 'tinyexec';
46
46
  import readline from 'node:readline';
47
- import { a as saveInlineSnapshots, e as evaluateSnapshotFile, s as saveSnapshotFile, b as saveRawSnapshots } from './rawSnapshot.DqSiqIEx.js';
47
+ import { a as saveInlineSnapshots, e as evaluateSnapshotFile, s as saveSnapshotFile, b as saveRawSnapshots } from './rawSnapshot.DvoRLRNr.js';
48
48
 
49
49
  async function saveSnapshotUpdates(snapshots) {
50
50
  const updatesByFile = /* @__PURE__ */ new Map();
@@ -168,6 +168,8 @@ function requireBufferUtil () {
168
168
  if (hasRequiredBufferUtil) return bufferUtil.exports;
169
169
  hasRequiredBufferUtil = 1;
170
170
 
171
+ const { websocketMask, websocketUnmask } = require$$0;
172
+
171
173
  const { EMPTY_BUFFER } = requireConstants();
172
174
 
173
175
  const FastBuffer = Buffer[Symbol.species];
@@ -279,8 +281,17 @@ function requireBufferUtil () {
279
281
  unmask: _unmask
280
282
  };
281
283
 
282
- /* istanbul ignore else */
283
- if (!process.env.WS_NO_BUFFER_UTIL) {
284
+ if (websocketMask) {
285
+ bufferUtil.exports.mask = function (source, mask, output, offset, length) {
286
+ if (length < 24) _mask(source, mask, output, offset, length);
287
+ else websocketMask(source, mask, output, offset, length);
288
+ };
289
+
290
+ bufferUtil.exports.unmask = function (buffer, mask) {
291
+ if (buffer.length < 24) _unmask(buffer, mask);
292
+ else websocketUnmask(buffer, mask);
293
+ };
294
+ } /* istanbul ignore else */ else if (!process.env.WS_NO_BUFFER_UTIL) {
284
295
  try {
285
296
  const bufferUtil$1 = require('bufferutil');
286
297
 
@@ -370,7 +381,7 @@ function requirePermessageDeflate () {
370
381
  if (hasRequiredPermessageDeflate) return permessageDeflate;
371
382
  hasRequiredPermessageDeflate = 1;
372
383
 
373
- const zlib = require$$0;
384
+ const zlib = require$$0$1;
374
385
 
375
386
  const bufferUtil = requireBufferUtil();
376
387
  const Limiter = requireLimiter();
@@ -909,7 +920,7 @@ function requireValidation () {
909
920
  if (hasRequiredValidation) return validation.exports;
910
921
  hasRequiredValidation = 1;
911
922
 
912
- const { isUtf8 } = require$$0$1;
923
+ const { isUtf8 } = require$$0$2;
913
924
 
914
925
  const { hasBlob } = requireConstants();
915
926
 
@@ -1069,7 +1080,7 @@ function requireReceiver () {
1069
1080
  if (hasRequiredReceiver) return receiver;
1070
1081
  hasRequiredReceiver = 1;
1071
1082
 
1072
- const { Writable } = require$$0$2;
1083
+ const { Writable } = require$$0$3;
1073
1084
 
1074
1085
  const PerMessageDeflate = requirePermessageDeflate();
1075
1086
  const {
@@ -1822,7 +1833,7 @@ function requireSender () {
1822
1833
  if (hasRequiredSender) return sender;
1823
1834
  hasRequiredSender = 1;
1824
1835
 
1825
- const { Duplex } = require$$0$2;
1836
+ const { Duplex } = require$$0$3;
1826
1837
  const { randomFillSync } = require$$1;
1827
1838
  const {
1828
1839
  types: { isUint8Array }
@@ -1973,7 +1984,9 @@ function requireSender () {
1973
1984
  target.writeUIntBE(dataLength, 4, 6);
1974
1985
  }
1975
1986
 
1976
- if (!options.mask) return [target, data];
1987
+ if (!options.mask) {
1988
+ return dataLength ? [target, data] : [target];
1989
+ }
1977
1990
 
1978
1991
  target[1] |= 0x80;
1979
1992
  target[offset - 4] = mask[0];
@@ -1981,6 +1994,7 @@ function requireSender () {
1981
1994
  target[offset - 2] = mask[2];
1982
1995
  target[offset - 1] = mask[3];
1983
1996
 
1997
+ if (!dataLength) return [target];
1984
1998
  if (skipMasking) return [target, data];
1985
1999
 
1986
2000
  if (merge) {
@@ -2948,13 +2962,13 @@ function requireWebsocket () {
2948
2962
  if (hasRequiredWebsocket) return websocket;
2949
2963
  hasRequiredWebsocket = 1;
2950
2964
 
2951
- const EventEmitter = require$$0$3;
2965
+ const EventEmitter = require$$0$4;
2952
2966
  const https = require$$1$1;
2953
- const http = require$$2$1;
2967
+ const http = require$$0;
2954
2968
  const net = require$$3;
2955
2969
  const tls = require$$4;
2956
2970
  const { randomBytes, createHash } = require$$1;
2957
- const { Duplex, Readable } = require$$0$2;
2971
+ const { Duplex, Readable } = require$$0$3;
2958
2972
  const { URL } = require$$7;
2959
2973
 
2960
2974
  const PerMessageDeflate = requirePermessageDeflate();
@@ -3765,10 +3779,15 @@ function requireWebsocket () {
3765
3779
  }
3766
3780
 
3767
3781
  if (isIpcUrl) {
3768
- const parts = opts.path.split(':');
3782
+ const i = opts.path.indexOf(':');
3769
3783
 
3770
- opts.socketPath = parts[0];
3771
- opts.path = parts[1];
3784
+ if (i === -1) {
3785
+ opts.socketPath = opts.path;
3786
+ opts.path = '';
3787
+ } else {
3788
+ opts.socketPath = opts.path.slice(0, i);
3789
+ opts.path = opts.path.slice(i + 1);
3790
+ }
3772
3791
  }
3773
3792
 
3774
3793
  let req;
@@ -4378,7 +4397,7 @@ function requireStream () {
4378
4397
  hasRequiredStream = 1;
4379
4398
 
4380
4399
  requireWebsocket();
4381
- const { Duplex } = require$$0$2;
4400
+ const { Duplex } = require$$0$3;
4382
4401
 
4383
4402
  /**
4384
4403
  * Emits the `'close'` event on a stream.
@@ -4631,9 +4650,9 @@ function requireWebsocketServer () {
4631
4650
  if (hasRequiredWebsocketServer) return websocketServer;
4632
4651
  hasRequiredWebsocketServer = 1;
4633
4652
 
4634
- const EventEmitter = require$$0$3;
4635
- const http = require$$2$1;
4636
- const { Duplex } = require$$0$2;
4653
+ const EventEmitter = require$$0$4;
4654
+ const http = require$$0;
4655
+ const { Duplex } = require$$0$3;
4637
4656
  const { createHash } = require$$1;
4638
4657
 
4639
4658
  const extension = requireExtension();
@@ -5938,6 +5957,7 @@ const debugMemory = createDebugger("vitest:cache:memory");
5938
5957
  const cacheComment = "\n//# vitestCache=";
5939
5958
  const cacheCommentLength = 17;
5940
5959
  const METADATA_FILE = "_metadata.json";
5960
+ const MANIFEST_SECTIONS = ["modules", "externalized"];
5941
5961
  // Default location of the module cache. It lives inside `node_modules` at the
5942
5962
  // workspace root so it's shared by every project and is naturally invalidated
5943
5963
  // whenever dependencies are reinstalled.
@@ -5955,7 +5975,7 @@ class FileSystemModuleCache {
5955
5975
  */
5956
5976
  rootCache;
5957
5977
  metadataFilePath;
5958
- version = "1.0.0-beta.9";
5978
+ version = "1.0.0-beta.10";
5959
5979
  fsCacheRoots = /* @__PURE__ */ new WeakMap();
5960
5980
  fsEnvironmentHashMap = /* @__PURE__ */ new WeakMap();
5961
5981
  fsCacheKeyGenerators = /* @__PURE__ */ new WeakMap();
@@ -5963,6 +5983,8 @@ class FileSystemModuleCache {
5963
5983
  // this exists only to avoid the perf. cost of reading a file and generating a hash again
5964
5984
  // surprisingly, on some machines this has negligible effect
5965
5985
  fsCacheKeys = /* @__PURE__ */ new WeakMap();
5986
+ manifests = /* @__PURE__ */ new Map();
5987
+ manifestEntries = /* @__PURE__ */ new WeakMap();
5966
5988
  constructor(vitest) {
5967
5989
  this.vitest = vitest;
5968
5990
  this.rootCache = vitest.config.fsModuleCachePath || join(searchForWorkspaceRoot(vitest.viteConfig.root), "node_modules", DEFAULT_CACHE_DIRNAME);
@@ -5997,7 +6019,8 @@ class FileSystemModuleCache {
5997
6019
  if (log) this.vitest.logger.log(`[cache] cleared fs module cache at ${uniquePaths.join(", ")}`);
5998
6020
  }
5999
6021
  readCachedFileConcurrently(cachedFilePath) {
6000
- if (!parallelFsCacheRead.has(cachedFilePath)) parallelFsCacheRead.set(cachedFilePath, readFile(cachedFilePath, "utf-8").then((code) => {
6022
+ if (!parallelFsCacheRead.has(cachedFilePath)) parallelFsCacheRead.set(cachedFilePath, readFile(cachedFilePath, "utf-8").then((content) => {
6023
+ const { code, sourceMap } = splitSourceMap(content);
6001
6024
  const matchIndex = code.lastIndexOf(cacheComment);
6002
6025
  if (matchIndex === -1) {
6003
6026
  debugFs?.(`${$.red("[empty]")} ${cachedFilePath} exists, but doesn't have a ${cacheComment} comment, transforming by vite instead`);
@@ -6005,26 +6028,28 @@ class FileSystemModuleCache {
6005
6028
  }
6006
6029
  return {
6007
6030
  code,
6031
+ sourceMap,
6008
6032
  meta: this.fromBase64(code.slice(matchIndex + cacheCommentLength))
6009
6033
  };
6034
+ }, (error) => {
6035
+ // another process can remove the cache at any time
6036
+ if (error?.code !== "ENOENT") throw error;
6037
+ debugFs?.(`${$.red("[empty]")} ${cachedFilePath} doesn't exist, transforming by vite first`);
6010
6038
  }).finally(() => {
6011
6039
  parallelFsCacheRead.delete(cachedFilePath);
6012
6040
  }));
6013
6041
  return parallelFsCacheRead.get(cachedFilePath);
6014
6042
  }
6015
6043
  async getCachedModule(cachedFilePath) {
6016
- if (!existsSync(cachedFilePath)) {
6017
- debugFs?.(`${$.red("[empty]")} ${cachedFilePath} doesn't exist, transforming by vite first`);
6018
- return;
6019
- }
6020
6044
  const fileResult = await this.readCachedFileConcurrently(cachedFilePath);
6021
6045
  if (!fileResult) return;
6022
- const { code, meta } = fileResult;
6046
+ const { code, sourceMap, meta } = fileResult;
6023
6047
  debugFs?.(`${$.green("[read]")} ${meta.id} is cached in ${cachedFilePath}`);
6024
6048
  return {
6025
6049
  id: meta.id,
6026
6050
  file: meta.file,
6027
6051
  code,
6052
+ sourceMap,
6028
6053
  imports: meta.imports,
6029
6054
  mappings: meta.mappings,
6030
6055
  moduleType: meta.moduleType,
@@ -6052,7 +6077,7 @@ class FileSystemModuleCache {
6052
6077
  hasCoverageData: coverageData !== void 0
6053
6078
  };
6054
6079
  debugFs?.(`${$.yellow("[write]")} ${fetchResult.id} is cached in ${cachedFilePath}`);
6055
- await Promise.all([result.hasCoverageData && atomicWriteFile(getCoverageDataPath(cachedFilePath), JSON.stringify(coverageData)), atomicWriteFile(cachedFilePath, `${fetchResult.code}${cacheComment}${this.toBase64(result)}`)]);
6080
+ await Promise.all([result.hasCoverageData && atomicWriteFile(getCoverageDataPath(cachedFilePath), JSON.stringify(coverageData)), atomicWriteFile(cachedFilePath, appendSourceMap(`${fetchResult.code}${cacheComment}${this.toBase64(result)}`, fetchResult.sourceMap))]);
6056
6081
  }
6057
6082
  }
6058
6083
  getCoverageData(environment, id) {
@@ -6066,6 +6091,13 @@ class FileSystemModuleCache {
6066
6091
  restoreCoverageData(environment, id, data) {
6067
6092
  this.vitest.coverageProvider?.restoreModuleCacheData?.(environment, id, data);
6068
6093
  }
6094
+ // Vite watches the files outside of the root when it loads them, a cached module skips that
6095
+ watchFile(file) {
6096
+ const server = this.vitest.vite;
6097
+ // plugins can import modules in `configureServer` before the root server is attached
6098
+ if (!server) return;
6099
+ if (!file.startsWith(`${server.config.root}/`) && existsSync(file)) server.watcher.add(file);
6100
+ }
6069
6101
  toBase64(obj) {
6070
6102
  const json = stringify(obj);
6071
6103
  return Buffer.from(json).toString("base64");
@@ -6170,6 +6202,96 @@ class FileSystemModuleCache {
6170
6202
  this.saveMemoryCache(environment, id, fsResultPath);
6171
6203
  return fsResultPath;
6172
6204
  }
6205
+ recordManifestModule(vitestConfig, environment, url, cachePath) {
6206
+ this.getManifestEntries(vitestConfig, environment)?.modules.set(url, cachePath);
6207
+ }
6208
+ recordManifestExternal(vitestConfig, environment, url, externalized) {
6209
+ this.getManifestEntries(vitestConfig, environment)?.externalized.set(url, externalized);
6210
+ }
6211
+ getManifestEntries(vitestConfig, environment) {
6212
+ let entries = this.manifestEntries.get(environment);
6213
+ if (entries) return entries;
6214
+ const cacheRoot = this.getCacheRoot(vitestConfig);
6215
+ if (cacheRoot == null) return;
6216
+ const manifest = this.getManifest(vitestConfig, cacheRoot);
6217
+ entries = manifest.environments.get(environment.name);
6218
+ if (!entries) {
6219
+ entries = {
6220
+ modules: /* @__PURE__ */ new Map(),
6221
+ externalized: /* @__PURE__ */ new Map()
6222
+ };
6223
+ manifest.environments.set(environment.name, entries);
6224
+ }
6225
+ this.manifestEntries.set(environment, entries);
6226
+ return entries;
6227
+ }
6228
+ getManifest(vitestConfig, cacheRoot) {
6229
+ // several projects and Vitest processes can share the cache directory
6230
+ const label = (vitestConfig.name || basename(vitestConfig.root)).replace(/[^\w@-]+/g, "_").slice(0, 50);
6231
+ const key = hash("sha1", `${vitestConfig.root}\0${vitestConfig.name}`, "hex").slice(0, 8);
6232
+ const path = join(cacheRoot, `_manifest-${label}-${key}.json`);
6233
+ let manifest = this.manifests.get(path);
6234
+ if (!manifest) {
6235
+ manifest = {
6236
+ path,
6237
+ name: vitestConfig.name,
6238
+ root: vitestConfig.root,
6239
+ environments: /* @__PURE__ */ new Map()
6240
+ };
6241
+ this.manifests.set(path, manifest);
6242
+ }
6243
+ return manifest;
6244
+ }
6245
+ async writeManifests() {
6246
+ await Promise.all(Array.from(this.manifests.values(), (manifest) => this.writeManifest(manifest)));
6247
+ }
6248
+ async writeManifest(manifest) {
6249
+ if (Array.from(manifest.environments.values()).every((entries) => !entries.modules.size && !entries.externalized.size)) return;
6250
+ const loaded = manifest.content;
6251
+ const content = loaded ?? await readManifestContent(manifest.path);
6252
+ manifest.content = content;
6253
+ const changes = [];
6254
+ for (const [environment, entries] of manifest.environments) for (const section of MANIFEST_SECTIONS) {
6255
+ const values = content[section][environment];
6256
+ for (const [url, recordedValue] of entries[section]) {
6257
+ const value = section === "modules" ? recordedValue.slice(recordedValue.lastIndexOf("/") + 1) : recordedValue;
6258
+ if (values?.[url] !== value) changes.push([
6259
+ section,
6260
+ environment,
6261
+ url,
6262
+ value
6263
+ ]);
6264
+ }
6265
+ entries[section].clear();
6266
+ }
6267
+ if (!changes.length) return;
6268
+ let target = content;
6269
+ if (loaded) {
6270
+ // another process can update the manifest after this one loaded it
6271
+ target = await readManifestContent(manifest.path);
6272
+ for (const section of MANIFEST_SECTIONS) for (const environment in content[section]) target[section][environment] = {
6273
+ ...content[section][environment],
6274
+ ...target[section][environment]
6275
+ };
6276
+ }
6277
+ for (const [section, environment, url, value] of changes) {
6278
+ (target[section][environment] ??= {})[url] = value;
6279
+ // a module can switch between being inlined and externalized
6280
+ delete target[section === "modules" ? "externalized" : "modules"][environment]?.[url];
6281
+ }
6282
+ manifest.content = target;
6283
+ try {
6284
+ const data = {
6285
+ name: manifest.name,
6286
+ root: manifest.root,
6287
+ ...target
6288
+ };
6289
+ await atomicWriteFile(manifest.path, JSON.stringify(data, null, 2));
6290
+ } catch (error) {
6291
+ manifest.content = void 0;
6292
+ debugFs?.(`failed to write fs cache manifest ${manifest.path}: ${error}`);
6293
+ }
6294
+ }
6173
6295
  saveMemoryCache(environment, id, cache) {
6174
6296
  let environmentKeys = this.fsCacheKeys.get(environment);
6175
6297
  if (!environmentKeys) {
@@ -6223,6 +6345,20 @@ class FileSystemModuleCache {
6223
6345
  debugFs?.(`fs cache was cleared because lockfile has changed`);
6224
6346
  }
6225
6347
  }
6348
+ async function readManifestContent(path) {
6349
+ try {
6350
+ const manifest = JSON.parse(await readFile(path, "utf-8"));
6351
+ return {
6352
+ modules: manifest.modules ?? {},
6353
+ externalized: manifest.externalized ?? {}
6354
+ };
6355
+ } catch {
6356
+ return {
6357
+ modules: {},
6358
+ externalized: {}
6359
+ };
6360
+ }
6361
+ }
6226
6362
  /**
6227
6363
  * Performs an atomic write operation using the write-then-rename pattern.
6228
6364
  *
@@ -6818,7 +6954,11 @@ class VitestCache {
6818
6954
  }
6819
6955
  /** @internal */
6820
6956
  async _update(specifications, startTime) {
6821
- await Promise.all([this._results.update(specifications, startTime), this._dependencies.update(specifications, startTime)]);
6957
+ await Promise.all([
6958
+ this._results.update(specifications, startTime),
6959
+ this._dependencies.update(specifications, startTime),
6960
+ this._modules.writeManifests()
6961
+ ]);
6822
6962
  }
6823
6963
  /** @internal */
6824
6964
  async _clear() {
@@ -7353,6 +7493,7 @@ Update your dependencies and make sure the versions match.`));
7353
7493
  const code = await promises.readFile(filename, "utf-8");
7354
7494
  return {
7355
7495
  // `transform` mode will inject source maps comment at the end
7496
+ // Node 26 removed the 'transform' mode, older versions still support it
7356
7497
  code: module$1.stripTypeScriptTypes(code, { mode: isTransform ? "transform" : "strip" }),
7357
7498
  map: null
7358
7499
  };
@@ -7365,7 +7506,7 @@ Update your dependencies and make sure the versions match.`));
7365
7506
  return async (filename) => {
7366
7507
  let lastError;
7367
7508
  for (const project of projects) {
7368
- const root = project.config.root;
7509
+ const root = project.config.root.endsWith("/") ? project.config.root : `${project.config.root}/`;
7369
7510
  if (!filename.startsWith(root) && !filename.startsWith(`/${root}`) && project !== rootProject) continue;
7370
7511
  try {
7371
7512
  const environment = project.config.environment;
@@ -8210,6 +8351,53 @@ function padBenchRow(row, widths) {
8210
8351
  return row.map((v, i) => i === 0 ? v.padEnd(widths[i]) : v.padStart(widths[i]));
8211
8352
  }
8212
8353
 
8354
+ function groupTaskErrors(tasks) {
8355
+ const groups = [];
8356
+ for (const task of tasks)
8357
+ // Merge identical errors
8358
+ for (const { error, attempt } of getErrorsWithAttempt(task)) {
8359
+ let previous;
8360
+ if (error.stack) previous = groups.find((item) => {
8361
+ if (item.error.stack !== error.stack || item.error.diff !== error.diff) return false;
8362
+ const itemTask = item.sources[0].task;
8363
+ const currentProjectName = task?.projectName || task.file?.projectName || "";
8364
+ const projectName = itemTask?.projectName || itemTask.file?.projectName || "";
8365
+ const currentAnnotations = task.type === "test" && task.annotations;
8366
+ const itemAnnotations = itemTask.type === "test" && itemTask.annotations;
8367
+ return projectName === currentProjectName && deepEqual(currentAnnotations, itemAnnotations);
8368
+ });
8369
+ if (previous) previous.sources.push({
8370
+ task,
8371
+ attempt
8372
+ });
8373
+ else groups.push({
8374
+ error,
8375
+ sources: [{
8376
+ task,
8377
+ attempt
8378
+ }]
8379
+ });
8380
+ }
8381
+ return groups;
8382
+ }
8383
+ function getErrorsWithAttempt(task) {
8384
+ const attempts = task.result?.attempts;
8385
+ if (!attempts?.length) return (task.result?.errors ?? []).map((error) => ({ error }));
8386
+ return attempts.flatMap((attempt) => (attempt.errors ?? []).map((error) => ({
8387
+ error,
8388
+ attempt
8389
+ })));
8390
+ }
8391
+ function deepEqual(a, b) {
8392
+ if (a === b) return true;
8393
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
8394
+ const keysA = Object.keys(a);
8395
+ const keysB = Object.keys(b);
8396
+ if (keysA.length !== keysB.length) return false;
8397
+ for (const key of keysA) if (!Object.hasOwn(b, key) || !deepEqual(a[key], b[key])) return false;
8398
+ return true;
8399
+ }
8400
+
8213
8401
  function getTraceAttemptKey(trace) {
8214
8402
  return `${trace.repeats}:${trace.retry}`;
8215
8403
  }
@@ -9015,17 +9203,18 @@ class BaseReporter {
9015
9203
  const tests = getTests(files);
9016
9204
  const failedSuites = suites.filter((i) => i.result?.errors);
9017
9205
  const failedTests = tests.filter((i) => i.result?.state === "fail");
9018
- const failedTotal = countTestErrors(failedSuites) + countTestErrors(failedTests);
9019
- // TODO: error divider should take into account merged errors for counting
9206
+ const suiteErrors = groupTaskErrors(failedSuites);
9207
+ const testErrors = groupTaskErrors(failedTests);
9208
+ const failedTotal = suiteErrors.length + testErrors.length;
9020
9209
  let current = 1;
9021
9210
  const errorDivider = () => this.error(`${$.red($.dim(divider(`[${current++}/${failedTotal}]`, void 0, 1)))}\n`);
9022
9211
  if (failedSuites.length) {
9023
9212
  this.error(`\n${errorBanner(`Failed Suites ${failedSuites.length}`)}\n`);
9024
- this.printTaskErrors(failedSuites, errorDivider);
9213
+ this.printTaskErrors(suiteErrors, errorDivider);
9025
9214
  }
9026
9215
  if (failedTests.length) {
9027
9216
  this.error(`\n${errorBanner(`Failed Tests ${failedTests.length}`)}\n`);
9028
- this.printTaskErrors(failedTests, errorDivider);
9217
+ this.printTaskErrors(testErrors, errorDivider);
9029
9218
  }
9030
9219
  if (errors.length) {
9031
9220
  this.ctx.logger.printUnhandledErrors(errors);
@@ -9118,34 +9307,8 @@ class BaseReporter {
9118
9307
  }
9119
9308
  }
9120
9309
  }
9121
- printTaskErrors(tasks, errorDivider) {
9122
- const errorsQueue = [];
9123
- for (const task of tasks)
9124
- // Merge identical errors
9125
- for (const { error, attempt } of getErrorsWithAttempt(task)) {
9126
- let previous;
9127
- if (error.stack) previous = errorsQueue.find((item) => {
9128
- if (item.error.stack !== error.stack || item.error.diff !== error.diff) return false;
9129
- const itemTask = item.sources[0].task;
9130
- const currentProjectName = task?.projectName || task.file?.projectName || "";
9131
- const projectName = itemTask?.projectName || itemTask.file?.projectName || "";
9132
- const currentAnnotations = task.type === "test" && task.annotations;
9133
- const itemAnnotations = itemTask.type === "test" && itemTask.annotations;
9134
- return projectName === currentProjectName && deepEqual(currentAnnotations, itemAnnotations);
9135
- });
9136
- if (previous) previous.sources.push({
9137
- task,
9138
- attempt
9139
- });
9140
- else errorsQueue.push({
9141
- error,
9142
- sources: [{
9143
- task,
9144
- attempt
9145
- }]
9146
- });
9147
- }
9148
- for (const { error, sources } of errorsQueue) {
9310
+ printTaskErrors(groups, errorDivider) {
9311
+ for (const { error, sources } of groups) {
9149
9312
  const tasks = sources.map(({ task }) => task);
9150
9313
  const attemptsByTask = /* @__PURE__ */ new Map();
9151
9314
  for (const { task, attempt } of sources) attemptsByTask.set(task, [...attemptsByTask.get(task) ?? [], attempt]);
@@ -9193,29 +9356,12 @@ function formatAttempt({ repeatIndex, retryIndex }) {
9193
9356
  if (repeat && retry) return `${retry} of ${repeat}`;
9194
9357
  return repeat || retry || "initial run";
9195
9358
  }
9196
- function getErrorsWithAttempt(task) {
9197
- const attempts = task.result?.attempts;
9198
- if (!attempts?.length) return (task.result?.errors ?? []).map((error) => ({ error }));
9199
- return attempts.flatMap((attempt) => (attempt.errors ?? []).map((error) => ({
9200
- error,
9201
- attempt
9202
- })));
9203
- }
9204
9359
  function getFailureScreenshotPaths(task, attempt) {
9205
9360
  if (task.type !== "test") return [];
9206
9361
  const paths = [];
9207
9362
  for (const artifact of task.artifacts) if (artifact.type === "internal:failureScreenshot" && artifact.attachments.length && artifact.retryIndex === attempt.retryIndex && artifact.repeatIndex === attempt.repeatIndex) paths.push(artifact.attachments[0].originalPath);
9208
9363
  return paths;
9209
9364
  }
9210
- function deepEqual(a, b) {
9211
- if (a === b) return true;
9212
- if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
9213
- const keysA = Object.keys(a);
9214
- const keysB = Object.keys(b);
9215
- if (keysA.length !== keysB.length) return false;
9216
- for (const key of keysA) if (!Object.hasOwn(b, key) || !deepEqual(a[key], b[key])) return false;
9217
- return true;
9218
- }
9219
9365
  function sum(items, cb) {
9220
9366
  return items.reduce((total, next) => {
9221
9367
  return total + Math.max(cb(next) || 0, 0);
@@ -10082,8 +10228,9 @@ class JsonReporter {
10082
10228
  const numTotalTestSuites = suites.length;
10083
10229
  const tests = getTests(files);
10084
10230
  const numTotalTests = tests.length;
10085
- const numFailedTestSuites = suites.filter((s) => s.result?.state === "fail").length;
10086
- const numPendingTestSuites = suites.filter((s) => s.result?.state === "run" || s.result?.state === "queued" || s.mode === "todo").length;
10231
+ const unfinishedFiles = new Set(files.filter(isUnfinished));
10232
+ const numFailedTestSuites = suites.filter((s) => s.result?.state === "fail" || unfinishedFiles.has(s)).length;
10233
+ const numPendingTestSuites = suites.filter((s) => !unfinishedFiles.has(s) && (s.result?.state === "run" || s.result?.state === "queued" || s.mode === "todo")).length;
10087
10234
  const numPassedTestSuites = numTotalTestSuites - numFailedTestSuites - numPendingTestSuites;
10088
10235
  const numFailedTests = tests.filter((t) => t.result?.state === "fail").length;
10089
10236
  const numPassedTests = tests.filter((t) => t.result?.state === "pass").length;
@@ -10131,7 +10278,7 @@ class JsonReporter {
10131
10278
  assertionResults,
10132
10279
  startTime,
10133
10280
  endTime,
10134
- status: file.result?.state === "fail" || hasFailedTests ? "failed" : "passed",
10281
+ status: unfinishedFiles.has(file) || file.result?.state === "fail" || hasFailedTests ? "failed" : "passed",
10135
10282
  message: file.result?.errors?.[0]?.message ?? "",
10136
10283
  name: file.filepath
10137
10284
  });
@@ -10168,6 +10315,12 @@ class JsonReporter {
10168
10315
  }
10169
10316
  }
10170
10317
  }
10318
+ // the file did not finish, for example because its worker crashed
10319
+ // (same as `pending` or `queued` in `TestModule.state()`)
10320
+ function isUnfinished(file) {
10321
+ const state = file.result?.state;
10322
+ return file.mode !== "skip" && file.mode !== "todo" && (state == null || state === "run" || state === "only" || state === "queued");
10323
+ }
10171
10324
 
10172
10325
  class IndentedLogger {
10173
10326
  baseLog;
@@ -11239,7 +11392,7 @@ class TestModule extends SuiteImplementation {
11239
11392
  * Checks the running state of the test file.
11240
11393
  */
11241
11394
  state() {
11242
- if (this.task.result?.state === "queued") return "queued";
11395
+ if (this.task.mode === "queued" && !this.task.result) return "queued";
11243
11396
  return getSuiteState(this.task);
11244
11397
  }
11245
11398
  /**
@@ -11390,7 +11543,7 @@ class StateManager {
11390
11543
  collectFiles(project, files = []) {
11391
11544
  files.forEach((file) => {
11392
11545
  const existing = this.filesMap.get(file.filepath) || [];
11393
- const currentFile = existing.find((i) => i.projectName === file.projectName && i.meta.typecheck === file.meta.typecheck && i.meta.__vitest_label__ === file.meta.__vitest_label__);
11546
+ const currentFile = existing.find((i) => i.id === file.id);
11394
11547
  // keep logs for the previous file because it should always be initiated before the collections phase
11395
11548
  // which means that all logs are collected during the collection and not inside tests
11396
11549
  if (currentFile) file.logs = currentFile.logs;
@@ -12131,15 +12284,16 @@ class Mime {
12131
12284
  for (let [type, extensions] of Object.entries(typeMap)) {
12132
12285
  type = type.toLowerCase();
12133
12286
  extensions = extensions.map((ext) => ext.toLowerCase());
12134
- if (!__classPrivateFieldGet(this, _Mime_typeToExtensions, "f").has(type)) {
12135
- __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").set(type, new Set());
12287
+ let allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type);
12288
+ if (!allExtensions) {
12289
+ allExtensions = new Set();
12290
+ __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").set(type, allExtensions);
12136
12291
  }
12137
- const allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type);
12138
12292
  let first = true;
12139
12293
  for (let extension of extensions) {
12140
12294
  const starred = extension.startsWith('*');
12141
12295
  extension = starred ? extension.slice(1) : extension;
12142
- allExtensions?.add(extension);
12296
+ allExtensions.add(extension);
12143
12297
  if (first) {
12144
12298
  __classPrivateFieldGet(this, _Mime_typeToExtension, "f").set(type, extension);
12145
12299
  }
@@ -12176,16 +12330,14 @@ class Mime {
12176
12330
  if (typeof type !== 'string')
12177
12331
  return null;
12178
12332
  type = type.split(';')[0].trim().toLowerCase();
12179
- return __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type) ?? null;
12333
+ const extensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type);
12334
+ return extensions ? new Set(extensions) : null;
12180
12335
  }
12181
12336
  _freeze() {
12182
12337
  this.define = () => {
12183
12338
  throw new Error('define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances');
12184
12339
  };
12185
12340
  Object.freeze(this);
12186
- for (const extensions of __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").values()) {
12187
- Object.freeze(extensions);
12188
- }
12189
12341
  return this;
12190
12342
  }
12191
12343
  _getTestState() {
@@ -12240,14 +12392,16 @@ class TestRun {
12240
12392
  return artifact;
12241
12393
  }
12242
12394
  if (Array.isArray(artifact.attachments)) await Promise.all(artifact.attachments.map((attachment) => this.resolveTestAttachment(testCase, attachment)));
12243
- // TODO: resolve browser trace locations here too, using `project.browser.parseStacktrace`
12244
- // like `syncUpdateStacks`, and drop the mapping in `__vitest_recordBrowserTrace`
12245
- if (artifact.type === "internal:browserTrace" && testCase.task.file.pool !== "browser") {
12395
+ // trace locations of browser tests need the browser server's source maps here,
12396
+ // while node trace stacks are already mapped in the worker except for external modules
12397
+ if (artifact.type === "internal:browserTrace") {
12246
12398
  const { entries } = artifact.data;
12399
+ const project = testCase.project;
12400
+ const isBrowser = testCase.task.file.pool === "browser";
12247
12401
  for (const entry of entries) if (entry.stack && !entry.location) {
12248
- const [stack] = parseStacktrace(entry.stack, {
12402
+ const [stack] = isBrowser ? project.browser?.parseStacktrace(entry.stack, { firstOnly: true }) || [] : parseStacktrace(entry.stack, {
12249
12403
  firstOnly: true,
12250
- getSourceMap: (file) => getExternalSourceMap(testCase.project, file)
12404
+ getSourceMap: (file) => getExternalSourceMap(project, file)
12251
12405
  });
12252
12406
  if (stack) entry.location = {
12253
12407
  file: stack.file,
@@ -12280,28 +12434,19 @@ class TestRun {
12280
12434
  }
12281
12435
  async end(specifications, errors, coverage) {
12282
12436
  if (coverage) await this.vitest.report("onCoverage", coverage);
12283
- // specification won't have the File task if they were filtered by the --shard command
12284
12437
  const modules = specifications.map((spec) => spec.testModule).filter((s) => s != null);
12285
12438
  const state = this.vitest.isCancelling ? "interrupted" : // by this point, the run will be marked as failed if there are any errors,
12286
12439
  // should it be done by testRun.end?
12287
12440
  this.hasFailed(modules) ? "failed" : "passed";
12288
12441
  if (state !== "passed") process.exitCode = 1;
12289
12442
  await this.vitest.report("onTestRunEnd", modules, [...errors], state);
12290
- for (const project in this.vitest.state.metadata) {
12291
- const meta = this.vitest.state.metadata[project];
12292
- if (!meta?.dumpDir) continue;
12293
- const path = resolve(meta.dumpDir, "vitest-metadata.json");
12294
- meta.outline = {
12295
- externalized: Object.keys(meta.externalized).length,
12296
- inlined: Object.keys(meta.tmps).length
12297
- };
12298
- await writeFile(path, JSON.stringify(meta, null, 2), "utf-8");
12299
- this.vitest.logger.log(`Metadata written to ${path}`);
12300
- }
12301
12443
  }
12302
12444
  hasFailed(modules) {
12303
12445
  if (!modules.length) return !this.vitest.config.passWithNoTests;
12304
- return modules.some((m) => !m.ok() || m.state() === "pending");
12446
+ return modules.some((m) => {
12447
+ const state = m.state();
12448
+ return !m.ok() || state === "pending" || state === "queued";
12449
+ });
12305
12450
  }
12306
12451
  // make sure the error always has a "stacks" property
12307
12452
  syncUpdateStacks(update) {
@@ -12788,6 +12933,7 @@ class Vitest {
12788
12933
  */
12789
12934
  _rootBrowserParent;
12790
12935
  /** @internal */ _browserSessions = new BrowserSessions();
12936
+ /** @internal */ _browserCacheStale = false;
12791
12937
  /** @internal */ reporters = [];
12792
12938
  /** @internal */ runner;
12793
12939
  /** @internal */ _testRun;
@@ -12802,6 +12948,7 @@ class Vitest {
12802
12948
  restartsCount = 0;
12803
12949
  specifications;
12804
12950
  pool;
12951
+ sequencer;
12805
12952
  _coverageProvider;
12806
12953
  /**
12807
12954
  * @deprecated Do not rely on this property, it's always `test`. Scheduled to be removed in the next major.
@@ -12838,9 +12985,15 @@ class Vitest {
12838
12985
  _setRootConfig(config) {
12839
12986
  this.watcher.unregisterWatcher();
12840
12987
  clearTimeout(this._rerunTimer);
12988
+ // the rerun timer is the only place that clears these sets. If a restart
12989
+ // cancels the timer, `handleFileChanged` ignores every later change of the
12990
+ // files that are still in the sets.
12991
+ this.watcher.changedTests.clear();
12992
+ this.watcher.invalidates.clear();
12841
12993
  this.restartsCount += 1;
12842
12994
  this.pool?.close?.();
12843
12995
  this.pool = void 0;
12996
+ this.sequencer = void 0;
12844
12997
  this.closingPromise = void 0;
12845
12998
  this.projects = [];
12846
12999
  this.runningPromise = void 0;
@@ -13215,7 +13368,7 @@ class Vitest {
13215
13368
  return this._traces.$("vitest.collect", async (collectSpan) => {
13216
13369
  const filenamePattern = filters && filters?.length > 0 ? filters : [];
13217
13370
  collectSpan.setAttribute("vitest.collect.filters", filenamePattern);
13218
- const files = await this._traces.$("vitest.config.resolve_include_glob", async () => {
13371
+ let files = await this._traces.$("vitest.config.resolve_include_glob", async () => {
13219
13372
  const specifications = await this.specifications.getRelevantTestSpecifications(filters);
13220
13373
  collectSpan.setAttribute("vitest.collect.specifications", specifications.map((s) => {
13221
13374
  const relativeModuleId = relative(s.project.config.root, s.moduleId);
@@ -13224,6 +13377,7 @@ class Vitest {
13224
13377
  }));
13225
13378
  return specifications;
13226
13379
  });
13380
+ files = await this._shardSpecifications(files);
13227
13381
  // if run with --changed, don't exit if no tests are found
13228
13382
  if (!files.length) return {
13229
13383
  testModules: [],
@@ -13277,13 +13431,7 @@ class Vitest {
13277
13431
  }));
13278
13432
  return specifications;
13279
13433
  });
13280
- if (this.config.experimental.preParse) {
13281
- // This populates specification.testModule with parsed information
13282
- await this.parseSpecifications(specifications);
13283
- specifications = specifications.filter(({ testModule }) => {
13284
- return !testModule || testModule.task.mode !== "skip";
13285
- });
13286
- }
13434
+ specifications = this.config.experimental.preParse ? await this.preParseSpecifications(specifications) : await this._shardSpecifications(specifications);
13287
13435
  // if run with --changed or --last-failed, don't exit if no tests are found
13288
13436
  if (!specifications.length) {
13289
13437
  await this._traces.$("vitest.test_run", async () => {
@@ -13412,7 +13560,8 @@ class Vitest {
13412
13560
  if (!this.isFirstRun && this._coverageOptions.cleanOnRerun) await this.coverageProvider?.clean();
13413
13561
  await this.initializeGlobalSetup(specs);
13414
13562
  try {
13415
- await this.pool.runTests(specs, invalidates);
13563
+ const sorted = await this.getSequencer().sort(specs);
13564
+ await this.pool.runTests(sorted, invalidates);
13416
13565
  } catch (err) {
13417
13566
  this.state.catchError(err, "Unhandled Error");
13418
13567
  }
@@ -13481,6 +13630,23 @@ class Vitest {
13481
13630
  return this.parseSpecifications(specifications, options);
13482
13631
  }
13483
13632
  async parseSpecifications(specifications, options) {
13633
+ return (await this.parseFiles(specifications, options)).map((file, index) => {
13634
+ this.state.collectFiles(specifications[index].project, [file]);
13635
+ return this.state.getReportedEntity(file);
13636
+ });
13637
+ }
13638
+ async preParseSpecifications(specifications) {
13639
+ const files = await this.parseFiles(specifications);
13640
+ const runnable = specifications.filter((_, index) => files[index].mode !== "skip");
13641
+ const sharded = await this._shardSpecifications(runnable);
13642
+ const inShard = new Set(sharded);
13643
+ specifications.forEach((specification, index) => {
13644
+ // files of other shards are not part of this run
13645
+ if (files[index].mode === "skip" || inShard.has(specification)) this.state.collectFiles(specification.project, [files[index]]);
13646
+ });
13647
+ return sharded;
13648
+ }
13649
+ async parseFiles(specifications, options) {
13484
13650
  const concurrency = options?.concurrency ?? (typeof os__default.availableParallelism === "function" ? os__default.availableParallelism() : os__default.cpus().length);
13485
13651
  const limit = limitConcurrency(concurrency);
13486
13652
  // Phase 1: parse all files in parallel (without mode interpretation)
@@ -13498,9 +13664,8 @@ class Vitest {
13498
13664
  for (const { file, specification } of results) {
13499
13665
  const config = specification.project.config;
13500
13666
  interpretTaskModes(file, config.testNamePattern, specification.testLines, specification.testIds, specification.testNames, tagsFilter, globalHasOnly, false, config.allowOnly);
13501
- this.state.collectFiles(specification.project, [file]);
13502
13667
  }
13503
- return results.map(({ file }) => this.state.getReportedEntity(file));
13668
+ return results.map(({ file }) => file);
13504
13669
  }
13505
13670
  async experimental_parseSpecification(specification) {
13506
13671
  const file = await astCollectTests(specification.project, specification.moduleId).catch((error) => {
@@ -13535,7 +13700,8 @@ class Vitest {
13535
13700
  this.state.clearErrors();
13536
13701
  await this.initializeGlobalSetup(specifications);
13537
13702
  try {
13538
- await this.pool.collectTests(specifications, invalidates);
13703
+ const sorted = await this.getSequencer().sort(specifications);
13704
+ await this.pool.collectTests(sorted, invalidates);
13539
13705
  } catch (err) {
13540
13706
  this.state.catchError(err, "Unhandled Error");
13541
13707
  }
@@ -13566,6 +13732,20 @@ class Vitest {
13566
13732
  await this.cancelPromise.finally(() => this.cancelPromise = void 0);
13567
13733
  await this.runningPromise;
13568
13734
  }
13735
+ getSequencer() {
13736
+ if (!this.sequencer) {
13737
+ const Sequencer = this.config.sequence.sequencer;
13738
+ this.sequencer = new Sequencer(this);
13739
+ }
13740
+ return this.sequencer;
13741
+ }
13742
+ /** @internal */
13743
+ async _shardSpecifications(specifications) {
13744
+ const shard = this.config.shard;
13745
+ if (!shard) return specifications;
13746
+ if (!this.config.passWithNoTests && shard.count > specifications.length) throw new Error(`--shard <count> must be a smaller than count of test files. Resolved ${specifications.length} test files for --shard=${shard.index}/${shard.count}.`);
13747
+ return this.getSequencer().shard(Array.from(specifications));
13748
+ }
13569
13749
  async initializeGlobalSetup(paths) {
13570
13750
  const projects = new Set(paths.map((spec) => spec.project));
13571
13751
  const coreProject = this.getRootProject();
@@ -13728,6 +13908,9 @@ class Vitest {
13728
13908
  */
13729
13909
  invalidateFile(filepath) {
13730
13910
  this.specifications.invalidateDocblock(filepath);
13911
+ // during `vitest run` the browser takes modules from its HTTP cache without asking the
13912
+ // server, so the browser pool opens new contexts before the next run
13913
+ if (!this.config.watch) this._browserCacheStale = true;
13731
13914
  this.projects.forEach(({ vite }) => {
13732
13915
  Object.values(vite.environments).forEach((environment) => {
13733
13916
  const { moduleGraph } = environment;