vitest 2.0.0-beta.2 → 2.0.0-beta.5

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 (46) hide show
  1. package/dist/browser.d.ts +5 -1
  2. package/dist/browser.js +18 -2
  3. package/dist/chunks/{integrations-globals.B5Jl0grA.js → integrations-globals.BK0Cn4q1.js} +3 -4
  4. package/dist/chunks/{runtime-console.CUES-L8X.js → runtime-console.DiVMr5d4.js} +54 -24
  5. package/dist/chunks/{runtime-runBaseTests._dXkRAZc.js → runtime-runBaseTests.C-Bkopka.js} +5 -6
  6. package/dist/cli.js +2 -2
  7. package/dist/config.cjs +2 -2
  8. package/dist/config.d.ts +2 -2
  9. package/dist/config.js +2 -2
  10. package/dist/coverage.d.ts +1 -1
  11. package/dist/environments.d.ts +1 -1
  12. package/dist/execute.d.ts +2 -2
  13. package/dist/execute.js +1 -1
  14. package/dist/index-C7JhjWOq.d.ts +1565 -0
  15. package/dist/index.d.ts +6 -1445
  16. package/dist/index.js +3 -4
  17. package/dist/node.d.ts +3 -6
  18. package/dist/node.js +7 -7
  19. package/dist/{reporters-DFgqsvtL.d.ts → reporters-qky6mwBH.d.ts} +398 -195
  20. package/dist/reporters.d.ts +1 -1
  21. package/dist/reporters.js +4 -4
  22. package/dist/runners.d.ts +4 -2
  23. package/dist/runners.js +9 -1
  24. package/dist/{suite-C_sqQjdz.d.ts → suite-B5_jYIf8.d.ts} +1 -1
  25. package/dist/suite.d.ts +2 -2
  26. package/dist/vendor/{base.VFkIJ66g.js → base.D4XK-wRp.js} +2 -2
  27. package/dist/vendor/{cac.CtP0aXu-.js → cac.sXjWMctD.js} +58 -20
  28. package/dist/vendor/{cli-api.B2QW76dQ.js → cli-api.BH9TJcYU.js} +487 -357
  29. package/dist/vendor/{constants.5SOfHUj0.js → constants.TCjCaw2D.js} +4 -3
  30. package/dist/vendor/{execute.CLLNVNnK.js → execute.BHj6OMh4.js} +3 -3
  31. package/dist/vendor/{index.CRxYS9H3.js → index.CyGfDRbW.js} +266 -49
  32. package/dist/vendor/{index.BfoZyXD1.js → index.DHRpy7zp.js} +1 -1
  33. package/dist/vendor/{index.CmILuxzC.js → index.DwR86H5i.js} +26 -3
  34. package/dist/vendor/{setup-common.XeoZAW8t.js → setup-common.BhJvzjns.js} +2 -2
  35. package/dist/vendor/{utils.D5gGkwyH.js → utils.YuQ3LT2a.js} +1 -1
  36. package/dist/vendor/{vi.ClD3hi7L.js → vi.C6AfDXK6.js} +97 -46
  37. package/dist/vendor/{vm.Bi3bljci.js → vm.Ow-X2mkS.js} +2 -2
  38. package/dist/workers/forks.js +2 -2
  39. package/dist/workers/runVmTests.js +4 -5
  40. package/dist/workers/threads.js +2 -2
  41. package/dist/workers/vmForks.js +3 -3
  42. package/dist/workers/vmThreads.js +3 -3
  43. package/dist/workers.d.ts +1 -1
  44. package/dist/workers.js +4 -4
  45. package/package.json +10 -10
  46. package/dist/vendor/run-once.DLomgGUH.js +0 -27
@@ -1,12 +1,12 @@
1
- import { dirname, join, resolve, relative, isAbsolute, normalize, basename, toNamespacedPath } from 'pathe';
2
- import { A as API_PATH, d as defaultPort, e as extraInlineDeps, a as defaultBrowserPort, b as defaultInspectPort, E as EXIT_CODE_RESTART, w as workspacesFiles, C as CONFIG_NAMES, c as configFiles } from './constants.5SOfHUj0.js';
1
+ import { join, resolve, isAbsolute, relative, dirname, normalize, basename, extname as extname$1, toNamespacedPath } from 'pathe';
2
+ import { A as API_PATH, d as defaultPort, e as extraInlineDeps, a as defaultBrowserPort, b as defaultInspectPort, B as BROWSER_API_PATH, E as EXIT_CODE_RESTART, w as workspacesFiles, C as CONFIG_NAMES, c as configFiles } from './constants.TCjCaw2D.js';
3
3
  import { g as getCoverageProvider, C as CoverageProviderMap } from './coverage.ChSqD-qS.js';
4
4
  import { g as getEnvPackageName } from './index.DeR1hhfY.js';
5
- import { isFileServingAllowed, searchForWorkspaceRoot, version, createServer, mergeConfig } from 'vite';
5
+ import { searchForWorkspaceRoot, version, isFileServingAllowed, createServer, mergeConfig } from 'vite';
6
6
  import path$8, { win32 } from 'node:path';
7
7
  import url, { fileURLToPath as fileURLToPath$1, pathToFileURL as pathToFileURL$1, URL as URL$2 } from 'node:url';
8
8
  import process$1 from 'node:process';
9
- import fs$8, { promises as promises$1, existsSync, statSync as statSync$1, realpathSync, readFileSync } from 'node:fs';
9
+ import fs$8, { promises as promises$1, existsSync, statSync as statSync$1, realpathSync, readdirSync, readFileSync } from 'node:fs';
10
10
  import { MessageChannel, isMainThread } from 'node:worker_threads';
11
11
  import { c as commonjsGlobal, g as getDefaultExportFromCjs } from './_commonjsHelpers.BFTU3MAI.js';
12
12
  import require$$0 from 'os';
@@ -19,13 +19,14 @@ import c from 'picocolors';
19
19
  import { ViteNodeRunner } from 'vite-node/client';
20
20
  import { SnapshotManager } from '@vitest/snapshot/manager';
21
21
  import { ViteNodeServer } from 'vite-node/server';
22
- import { v as version$1 } from './cac.CtP0aXu-.js';
23
- import { hasFailed, getTasks, getTests } from '@vitest/runner/utils';
24
- import { n as noop$2, b as isPrimitive, c as groupBy, A as AggregateErrorPonyfill, a as slash$1, t as toArray, d as deepMerge, e as nanoid, w as wildcardPatternToRegExp, f as stdout } from './base._gnK9Slw.js';
22
+ import { v as version$1 } from './cac.sXjWMctD.js';
23
+ import { hasFailed, createFileTask, getTasks, getTests } from '@vitest/runner/utils';
24
+ import { n as noop$1, b as isPrimitive, c as groupBy, A as AggregateErrorPonyfill, a as slash$1, t as toArray, d as deepMerge, e as nanoid, w as wildcardPatternToRegExp, f as stdout } from './base._gnK9Slw.js';
25
25
  import { createDefer, toArray as toArray$1, notNullish } from '@vitest/utils';
26
26
  import { a as isWindows } from './env.bmJgw1qP.js';
27
- import { rootDir } from '../path.js';
27
+ import { rootDir, distDir } from '../path.js';
28
28
  import { c as createBirpc } from './index.BpSiYbpB.js';
29
+ import { s as stringify, p as parse$3, w as wrapSerializableConfig, f as Typechecker, R as ReportersMap, e as BenchmarkReportsMap, g as RandomSequencer, B as BaseSequencer, h as findNodeAround, i as generateCodeFrame, j as highlightCode, L as Logger, k as BlobReporter, r as readBlobs } from './index.CyGfDRbW.js';
29
30
  import require$$0$4 from 'zlib';
30
31
  import require$$0$5 from 'buffer';
31
32
  import require$$1 from 'crypto';
@@ -40,20 +41,19 @@ import * as nodeos from 'node:os';
40
41
  import nodeos__default, { tmpdir } from 'node:os';
41
42
  import EventEmitter$2 from 'node:events';
42
43
  import Tinypool$1, { Tinypool } from 'tinypool';
43
- import { w as wrapSerializableConfig, f as Typechecker, R as ReportersMap, e as BenchmarkReportsMap, g as RandomSequencer, B as BaseSequencer, h as findNodeAround, i as generateCodeFrame, j as highlightCode, L as Logger } from './index.CRxYS9H3.js';
44
44
  import crypto, { createHash as createHash$2 } from 'node:crypto';
45
45
  import { mkdir, writeFile, rm } from 'node:fs/promises';
46
46
  import { builtinModules, createRequire } from 'node:module';
47
47
  import assert from 'node:assert';
48
48
  import { format as format$2, inspect } from 'node:util';
49
49
  import { isCI, provider as provider$1 } from 'std-env';
50
- import { normalizeRequestId, cleanUrl } from 'vite-node/utils';
50
+ import { normalizeRequestId, isNodeBuiltin, cleanUrl } from 'vite-node/utils';
51
51
  import MagicString from 'magic-string';
52
52
  import { esmWalker } from '@vitest/utils/ast';
53
- import { d as divider, s as stripAnsi } from './utils.D5gGkwyH.js';
54
53
  import { a as removeUndefinedValues } from './index._7XLd8Kd.js';
55
54
  import readline from 'node:readline';
56
55
  import require$$0$6 from 'readline';
56
+ import { s as stripAnsi } from './utils.YuQ3LT2a.js';
57
57
 
58
58
  function _mergeNamespaces(n, m) {
59
59
  m.forEach(function (e) {
@@ -70,21 +70,23 @@ function _mergeNamespaces(n, m) {
70
70
  return Object.freeze(n);
71
71
  }
72
72
 
73
- async function getModuleGraph(ctx, id) {
73
+ async function getModuleGraph(ctx, projectName, id, browser = false) {
74
74
  const graph = {};
75
75
  const externalized = /* @__PURE__ */ new Set();
76
76
  const inlined = /* @__PURE__ */ new Set();
77
+ const project = ctx.getProjectByName(projectName);
77
78
  function clearId(id2) {
78
79
  return (id2 == null ? void 0 : id2.replace(/\?v=\w+$/, "")) || "";
79
80
  }
80
81
  async function get(mod, seen = /* @__PURE__ */ new Map()) {
82
+ var _a;
81
83
  if (!mod || !mod.id)
82
84
  return;
83
85
  if (seen.has(mod))
84
86
  return seen.get(mod);
85
87
  let id2 = clearId(mod.id);
86
88
  seen.set(mod, id2);
87
- const rewrote = await ctx.vitenode.shouldExternalize(id2);
89
+ const rewrote = browser ? ((_a = mod.file) == null ? void 0 : _a.includes(project.browser.config.cacheDir)) ? mod.id : false : await project.vitenode.shouldExternalize(id2);
88
90
  if (rewrote) {
89
91
  id2 = rewrote;
90
92
  externalized.add(id2);
@@ -96,7 +98,10 @@ async function getModuleGraph(ctx, id) {
96
98
  graph[id2] = (await Promise.all(mods.map((m) => get(m, seen)))).filter(Boolean);
97
99
  return id2;
98
100
  }
99
- await get(ctx.server.moduleGraph.getModuleById(id));
101
+ if (browser && project.browser)
102
+ await get(project.browser.moduleGraph.getModuleById(id));
103
+ else
104
+ await get(project.server.moduleGraph.getModuleById(id));
100
105
  return {
101
106
  graph,
102
107
  externalized: Array.from(externalized),
@@ -1790,8 +1795,8 @@ function fastqueue (context, worker, concurrency) {
1790
1795
 
1791
1796
  var self = {
1792
1797
  push: push,
1793
- drain: noop$1,
1794
- saturated: noop$1,
1798
+ drain: noop,
1799
+ saturated: noop,
1795
1800
  pause: pause,
1796
1801
  paused: false,
1797
1802
  concurrency: concurrency,
@@ -1801,7 +1806,7 @@ function fastqueue (context, worker, concurrency) {
1801
1806
  length: length,
1802
1807
  getQueue: getQueue,
1803
1808
  unshift: unshift,
1804
- empty: noop$1,
1809
+ empty: noop,
1805
1810
  kill: kill,
1806
1811
  killAndDrain: killAndDrain,
1807
1812
  error: error
@@ -1860,7 +1865,7 @@ function fastqueue (context, worker, concurrency) {
1860
1865
  current.context = context;
1861
1866
  current.release = release;
1862
1867
  current.value = value;
1863
- current.callback = done || noop$1;
1868
+ current.callback = done || noop;
1864
1869
  current.errorHandler = errorHandler;
1865
1870
 
1866
1871
  if (_running === self.concurrency || self.paused) {
@@ -1884,7 +1889,7 @@ function fastqueue (context, worker, concurrency) {
1884
1889
  current.context = context;
1885
1890
  current.release = release;
1886
1891
  current.value = value;
1887
- current.callback = done || noop$1;
1892
+ current.callback = done || noop;
1888
1893
 
1889
1894
  if (_running === self.concurrency || self.paused) {
1890
1895
  if (queueHead) {
@@ -1928,14 +1933,14 @@ function fastqueue (context, worker, concurrency) {
1928
1933
  function kill () {
1929
1934
  queueHead = null;
1930
1935
  queueTail = null;
1931
- self.drain = noop$1;
1936
+ self.drain = noop;
1932
1937
  }
1933
1938
 
1934
1939
  function killAndDrain () {
1935
1940
  queueHead = null;
1936
1941
  queueTail = null;
1937
1942
  self.drain();
1938
- self.drain = noop$1;
1943
+ self.drain = noop;
1939
1944
  }
1940
1945
 
1941
1946
  function error (handler) {
@@ -1943,13 +1948,13 @@ function fastqueue (context, worker, concurrency) {
1943
1948
  }
1944
1949
  }
1945
1950
 
1946
- function noop$1 () {}
1951
+ function noop () {}
1947
1952
 
1948
1953
  function Task () {
1949
1954
  this.value = null;
1950
- this.callback = noop$1;
1955
+ this.callback = noop;
1951
1956
  this.next = null;
1952
- this.release = noop$1;
1957
+ this.release = noop;
1953
1958
  this.context = null;
1954
1959
  this.errorHandler = null;
1955
1960
 
@@ -1960,7 +1965,7 @@ function Task () {
1960
1965
  var errorHandler = self.errorHandler;
1961
1966
  var val = self.value;
1962
1967
  self.value = null;
1963
- self.callback = noop$1;
1968
+ self.callback = noop;
1964
1969
  if (self.errorHandler) {
1965
1970
  errorHandler(err, val);
1966
1971
  }
@@ -2008,7 +2013,7 @@ function queueAsPromised (context, worker, concurrency) {
2008
2013
  // Let's fork the promise chain to
2009
2014
  // make the error bubble up to the user but
2010
2015
  // not lead to a unhandledRejection
2011
- p.catch(noop$1);
2016
+ p.catch(noop);
2012
2017
 
2013
2018
  return p
2014
2019
  }
@@ -2027,7 +2032,7 @@ function queueAsPromised (context, worker, concurrency) {
2027
2032
  // Let's fork the promise chain to
2028
2033
  // make the error bubble up to the user but
2029
2034
  // not lead to a unhandledRejection
2030
- p.catch(noop$1);
2035
+ p.catch(noop);
2031
2036
 
2032
2037
  return p
2033
2038
  }
@@ -3128,113 +3133,6 @@ var out = FastGlob;
3128
3133
 
3129
3134
  var fg = /*@__PURE__*/getDefaultExportFromCjs(out);
3130
3135
 
3131
- /// <reference types="../types/index.d.ts" />
3132
-
3133
- // (c) 2020-present Andrea Giammarchi
3134
-
3135
- const {parse: $parse, stringify: $stringify} = JSON;
3136
- const {keys: keys$1} = Object;
3137
-
3138
- const Primitive = String; // it could be Number
3139
- const primitive = 'string'; // it could be 'number'
3140
-
3141
- const ignore = {};
3142
- const object = 'object';
3143
-
3144
- const noop = (_, value) => value;
3145
-
3146
- const primitives = value => (
3147
- value instanceof Primitive ? Primitive(value) : value
3148
- );
3149
-
3150
- const Primitives = (_, value) => (
3151
- typeof value === primitive ? new Primitive(value) : value
3152
- );
3153
-
3154
- const revive = (input, parsed, output, $) => {
3155
- const lazy = [];
3156
- for (let ke = keys$1(output), {length} = ke, y = 0; y < length; y++) {
3157
- const k = ke[y];
3158
- const value = output[k];
3159
- if (value instanceof Primitive) {
3160
- const tmp = input[value];
3161
- if (typeof tmp === object && !parsed.has(tmp)) {
3162
- parsed.add(tmp);
3163
- output[k] = ignore;
3164
- lazy.push({k, a: [input, parsed, tmp, $]});
3165
- }
3166
- else
3167
- output[k] = $.call(output, k, tmp);
3168
- }
3169
- else if (output[k] !== ignore)
3170
- output[k] = $.call(output, k, value);
3171
- }
3172
- for (let {length} = lazy, i = 0; i < length; i++) {
3173
- const {k, a} = lazy[i];
3174
- output[k] = $.call(output, k, revive.apply(null, a));
3175
- }
3176
- return output;
3177
- };
3178
-
3179
- const set = (known, input, value) => {
3180
- const index = Primitive(input.push(value) - 1);
3181
- known.set(value, index);
3182
- return index;
3183
- };
3184
-
3185
- /**
3186
- * Converts a specialized flatted string into a JS value.
3187
- * @param {string} text
3188
- * @param {(this: any, key: string, value: any) => any} [reviver]
3189
- * @returns {any}
3190
- */
3191
- const parse$3 = (text, reviver) => {
3192
- const input = $parse(text, Primitives).map(primitives);
3193
- const value = input[0];
3194
- const $ = reviver || noop;
3195
- const tmp = typeof value === object && value ?
3196
- revive(input, new Set, value, $) :
3197
- value;
3198
- return $.call({'': tmp}, '', tmp);
3199
- };
3200
-
3201
- /**
3202
- * Converts a JS value into a specialized flatted string.
3203
- * @param {any} value
3204
- * @param {((this: any, key: string, value: any) => any) | (string | number)[] | null | undefined} [replacer]
3205
- * @param {string | number | undefined} [space]
3206
- * @returns {string}
3207
- */
3208
- const stringify = (value, replacer, space) => {
3209
- const $ = replacer && typeof replacer === object ?
3210
- (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0) :
3211
- (replacer || noop);
3212
- const known = new Map;
3213
- const input = [];
3214
- const output = [];
3215
- let i = +set(known, input, $.call({'': value}, '', value));
3216
- let firstRun = !i;
3217
- while (i < input.length) {
3218
- firstRun = true;
3219
- output[i] = $stringify(input[i++], replace, space);
3220
- }
3221
- return '[' + output.join(',') + ']';
3222
- function replace(key, value) {
3223
- if (firstRun) {
3224
- firstRun = !firstRun;
3225
- return value;
3226
- }
3227
- const after = $.call(this, key, value);
3228
- switch (typeof after) {
3229
- case object:
3230
- if (after === null) return after;
3231
- case primitive:
3232
- return known.get(after) || set(known, input, after);
3233
- }
3234
- return after;
3235
- }
3236
- };
3237
-
3238
3136
  var bufferUtil$1 = {exports: {}};
3239
3137
 
3240
3138
  var constants = {
@@ -7689,9 +7587,8 @@ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
7689
7587
 
7690
7588
  var WebSocketServer$1 = /*@__PURE__*/getDefaultExportFromCjs(websocketServer);
7691
7589
 
7692
- function setup(vitestOrWorkspace, _server) {
7590
+ function setup(ctx, _server) {
7693
7591
  var _a;
7694
- const ctx = "ctx" in vitestOrWorkspace ? vitestOrWorkspace.ctx : vitestOrWorkspace;
7695
7592
  const wss = new WebSocketServer$1({ noServer: true });
7696
7593
  const clients = /* @__PURE__ */ new Map();
7697
7594
  const server = _server || ctx.server;
@@ -7706,16 +7603,9 @@ function setup(vitestOrWorkspace, _server) {
7706
7603
  setupClient(ws);
7707
7604
  });
7708
7605
  });
7709
- function checkFileAccess(path) {
7710
- if (!isFileServingAllowed(path, server))
7711
- throw new Error(`Access denied to "${path}". See Vite config documentation for "server.fs": https://vitejs.dev/config/server-options.html#server-fs-strict.`);
7712
- }
7713
7606
  function setupClient(ws) {
7714
7607
  const rpc = createBirpc(
7715
7608
  {
7716
- async onUnhandledError(error, type) {
7717
- ctx.state.catchError(error, type);
7718
- },
7719
7609
  async onCollected(files) {
7720
7610
  ctx.state.collectFiles(files);
7721
7611
  await ctx.report("onCollected", files);
@@ -7724,31 +7614,12 @@ function setup(vitestOrWorkspace, _server) {
7724
7614
  ctx.state.updateTasks(packs);
7725
7615
  await ctx.report("onTaskUpdate", packs);
7726
7616
  },
7727
- onAfterSuiteRun(meta) {
7728
- var _a2;
7729
- (_a2 = ctx.coverageProvider) == null ? void 0 : _a2.onAfterSuiteRun(meta);
7730
- },
7731
7617
  getFiles() {
7732
7618
  return ctx.state.getFiles();
7733
7619
  },
7734
7620
  getPaths() {
7735
7621
  return ctx.state.getPaths();
7736
7622
  },
7737
- sendLog(log) {
7738
- return ctx.report("onUserConsoleLog", log);
7739
- },
7740
- resolveSnapshotPath(testPath) {
7741
- return ctx.snapshot.resolvePath(testPath);
7742
- },
7743
- resolveSnapshotRawPath(testPath, rawPath) {
7744
- return ctx.snapshot.resolveRawPath(testPath, rawPath);
7745
- },
7746
- async readSnapshotFile(snapshotPath) {
7747
- checkFileAccess(snapshotPath);
7748
- if (!existsSync(snapshotPath))
7749
- return null;
7750
- return promises$1.readFile(snapshotPath, "utf-8");
7751
- },
7752
7623
  async readTestFile(id) {
7753
7624
  if (!ctx.state.filesMap.has(id) || !existsSync(id))
7754
7625
  return null;
@@ -7759,32 +7630,11 @@ function setup(vitestOrWorkspace, _server) {
7759
7630
  throw new Error(`Test file "${id}" was not registered, so it cannot be updated using the API.`);
7760
7631
  return promises$1.writeFile(id, content, "utf-8");
7761
7632
  },
7762
- async saveSnapshotFile(id, content) {
7763
- checkFileAccess(id);
7764
- await promises$1.mkdir(dirname(id), { recursive: true });
7765
- return promises$1.writeFile(id, content, "utf-8");
7766
- },
7767
- async removeSnapshotFile(id) {
7768
- checkFileAccess(id);
7769
- if (!existsSync(id))
7770
- throw new Error(`Snapshot file "${id}" does not exist.`);
7771
- return promises$1.unlink(id);
7772
- },
7773
- snapshotSaved(snapshot) {
7774
- ctx.snapshot.add(snapshot);
7775
- },
7776
7633
  async rerun(files) {
7777
7634
  await ctx.rerunFiles(files);
7778
7635
  },
7779
7636
  getConfig() {
7780
- return vitestOrWorkspace.config;
7781
- },
7782
- async getBrowserFileSourceMap(id) {
7783
- var _a2, _b;
7784
- if (!("ctx" in vitestOrWorkspace))
7785
- return void 0;
7786
- const mod = (_a2 = vitestOrWorkspace.browser) == null ? void 0 : _a2.moduleGraph.getModuleById(id);
7787
- return (_b = mod == null ? void 0 : mod.transformResult) == null ? void 0 : _b.map;
7637
+ return ctx.config;
7788
7638
  },
7789
7639
  async getTransformResult(id) {
7790
7640
  const result = await ctx.vitenode.transformRequest(id);
@@ -7796,51 +7646,29 @@ function setup(vitestOrWorkspace, _server) {
7796
7646
  return result;
7797
7647
  }
7798
7648
  },
7799
- async getModuleGraph(id) {
7800
- return getModuleGraph(ctx, id);
7649
+ async getModuleGraph(project, id, browser) {
7650
+ return getModuleGraph(ctx, project, id, browser);
7801
7651
  },
7802
7652
  updateSnapshot(file) {
7803
7653
  if (!file)
7804
7654
  return ctx.updateSnapshot();
7805
7655
  return ctx.updateSnapshot([file.filepath]);
7806
7656
  },
7807
- onCancel(reason) {
7808
- ctx.cancelCurrentRun(reason);
7809
- },
7810
- debug(...args) {
7811
- ctx.logger.console.debug(...args);
7812
- },
7813
- getCountOfFailedTests() {
7814
- return ctx.state.getCountOfFailedTests();
7815
- },
7816
7657
  getUnhandledErrors() {
7817
7658
  return ctx.state.getUnhandledErrors();
7818
7659
  },
7819
- // TODO: have a separate websocket conection for private browser API
7820
- getBrowserFiles() {
7821
- var _a2;
7822
- if (!("ctx" in vitestOrWorkspace))
7823
- throw new Error("`getBrowserTestFiles` is only available in the browser API");
7824
- return ((_a2 = vitestOrWorkspace.browserState) == null ? void 0 : _a2.files) ?? [];
7825
- },
7826
- finishBrowserTests() {
7827
- var _a2;
7828
- if (!("ctx" in vitestOrWorkspace))
7829
- throw new Error("`finishBrowserTests` is only available in the browser API");
7830
- return (_a2 = vitestOrWorkspace.browserState) == null ? void 0 : _a2.resolve();
7831
- },
7832
- getProvidedContext() {
7833
- return "ctx" in vitestOrWorkspace ? vitestOrWorkspace.getProvidedContext() : {};
7834
- },
7835
7660
  async getTestFiles() {
7836
7661
  const spec = await ctx.globTestFiles();
7837
- return spec.map(([project, file]) => [project.getName(), file]);
7662
+ return spec.map(([project, file]) => [{
7663
+ name: project.config.name,
7664
+ root: project.config.root
7665
+ }, file]);
7838
7666
  }
7839
7667
  },
7840
7668
  {
7841
7669
  post: (msg) => ws.send(msg),
7842
7670
  on: (fn) => ws.on("message", fn),
7843
- eventNames: ["onUserConsoleLog", "onFinished", "onFinishedReportCoverage", "onCollected", "onCancel", "onTaskUpdate"],
7671
+ eventNames: ["onUserConsoleLog", "onFinished", "onFinishedReportCoverage", "onCollected", "onTaskUpdate"],
7844
7672
  serialize: (data) => stringify(data, stringifyReplace),
7845
7673
  deserialize: parse$3,
7846
7674
  onTimeoutError(functionName) {
@@ -7848,7 +7676,6 @@ function setup(vitestOrWorkspace, _server) {
7848
7676
  }
7849
7677
  }
7850
7678
  );
7851
- ctx.onCancel((reason) => rpc.onCancel(reason));
7852
7679
  clients.set(ws, rpc);
7853
7680
  ws.on("close", () => {
7854
7681
  clients.delete(ws);
@@ -7867,7 +7694,15 @@ class WebSocketReporter {
7867
7694
  return;
7868
7695
  this.clients.forEach((client) => {
7869
7696
  var _a, _b, _c;
7870
- (_c = (_b = (_a = client.onCollected) == null ? void 0 : _a.call(client, files)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$2);
7697
+ (_c = (_b = (_a = client.onCollected) == null ? void 0 : _a.call(client, files)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$1);
7698
+ });
7699
+ }
7700
+ onSpecsCollected(specs) {
7701
+ if (this.clients.size === 0)
7702
+ return;
7703
+ this.clients.forEach((client) => {
7704
+ var _a, _b, _c;
7705
+ (_c = (_b = (_a = client.onSpecsCollected) == null ? void 0 : _a.call(client, specs)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$1);
7871
7706
  });
7872
7707
  }
7873
7708
  async onTaskUpdate(packs) {
@@ -7886,25 +7721,25 @@ class WebSocketReporter {
7886
7721
  });
7887
7722
  this.clients.forEach((client) => {
7888
7723
  var _a, _b, _c;
7889
- (_c = (_b = (_a = client.onTaskUpdate) == null ? void 0 : _a.call(client, packs)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$2);
7724
+ (_c = (_b = (_a = client.onTaskUpdate) == null ? void 0 : _a.call(client, packs)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$1);
7890
7725
  });
7891
7726
  }
7892
7727
  onFinished(files, errors) {
7893
7728
  this.clients.forEach((client) => {
7894
7729
  var _a, _b, _c;
7895
- (_c = (_b = (_a = client.onFinished) == null ? void 0 : _a.call(client, files, errors)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$2);
7730
+ (_c = (_b = (_a = client.onFinished) == null ? void 0 : _a.call(client, files, errors)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$1);
7896
7731
  });
7897
7732
  }
7898
7733
  onFinishedReportCoverage() {
7899
7734
  this.clients.forEach((client) => {
7900
7735
  var _a, _b, _c;
7901
- (_c = (_b = (_a = client.onFinishedReportCoverage) == null ? void 0 : _a.call(client)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$2);
7736
+ (_c = (_b = (_a = client.onFinishedReportCoverage) == null ? void 0 : _a.call(client)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$1);
7902
7737
  });
7903
7738
  }
7904
7739
  onUserConsoleLog(log) {
7905
7740
  this.clients.forEach((client) => {
7906
7741
  var _a, _b, _c;
7907
- (_c = (_b = (_a = client.onUserConsoleLog) == null ? void 0 : _a.call(client, log)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$2);
7742
+ (_c = (_b = (_a = client.onUserConsoleLog) == null ? void 0 : _a.call(client, log)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$1);
7908
7743
  });
7909
7744
  }
7910
7745
  }
@@ -7932,7 +7767,7 @@ async function groupFilesByEnv(files) {
7932
7767
  const filesWithEnv = await Promise.all(files.map(async ([project, file]) => {
7933
7768
  var _a, _b;
7934
7769
  const code = await promises$1.readFile(file, "utf-8");
7935
- let env = (_a = code.match(/@(?:vitest|jest)-environment\s+?([\w-]+)\b/)) == null ? void 0 : _a[1];
7770
+ let env = (_a = code.match(/@(?:vitest|jest)-environment\s+([\w-]+)\b/)) == null ? void 0 : _a[1];
7936
7771
  if (!env) {
7937
7772
  for (const [glob, target] of project.config.environmentMatchGlobs || []) {
7938
7773
  if (mm.isMatch(file, glob, { cwd: project.config.root })) {
@@ -8374,6 +8209,11 @@ function createBrowserPool(ctx) {
8374
8209
  const runTests = async (project, files) => {
8375
8210
  var _a;
8376
8211
  ctx.state.clearFiles(project, files);
8212
+ const mocker = project.browserMocker;
8213
+ mocker.mocks.forEach((_, id) => {
8214
+ mocker.invalidateModuleById(id);
8215
+ });
8216
+ mocker.mocks.clear();
8377
8217
  const provider = project.browserProvider;
8378
8218
  providers.add(provider);
8379
8219
  const resolvedUrls = (_a = project.browser) == null ? void 0 : _a.resolvedUrls;
@@ -8381,7 +8221,14 @@ function createBrowserPool(ctx) {
8381
8221
  if (!origin)
8382
8222
  throw new Error(`Can't find browser origin URL for project "${project.config.name}"`);
8383
8223
  const promise = waitForTests(project, files);
8384
- await provider.openPage(new URL("/", origin).toString());
8224
+ const orchestrators = project.browserRpc.orchestrators;
8225
+ if (orchestrators.size) {
8226
+ orchestrators.forEach((orchestrator) => {
8227
+ orchestrator.createTesters(files);
8228
+ });
8229
+ } else {
8230
+ await provider.openPage(new URL("/", origin).toString());
8231
+ }
8385
8232
  await promise;
8386
8233
  };
8387
8234
  const runWorkspaceTests = async (specs) => {
@@ -8420,7 +8267,7 @@ function stringToBytes(input, percentageReference) {
8420
8267
  return input;
8421
8268
  if (typeof input === "string") {
8422
8269
  if (Number.isNaN(Number.parseFloat(input.slice(-1)))) {
8423
- let [, numericString, trailingChars] = input.match(/(.*?)([^0-9.-]+)$/i) || [];
8270
+ let [, numericString, trailingChars] = input.match(/(.*?)([^0-9.-]+)$/) || [];
8424
8271
  if (trailingChars && numericString) {
8425
8272
  const numericValue = Number.parseFloat(numericString);
8426
8273
  trailingChars = trailingChars.toLowerCase();
@@ -9068,6 +8915,9 @@ class StateManager {
9068
8915
  files.forEach((file) => {
9069
8916
  const existing = this.filesMap.get(file.filepath) || [];
9070
8917
  const otherProject = existing.filter((i) => i.projectName !== file.projectName);
8918
+ const currentFile = existing.find((i) => i.projectName === file.projectName);
8919
+ if (currentFile)
8920
+ file.logs = currentFile.logs;
9071
8921
  otherProject.push(file);
9072
8922
  this.filesMap.set(file.filepath, otherProject);
9073
8923
  this.updateId(file);
@@ -9078,13 +8928,21 @@ class StateManager {
9078
8928
  const project = _project;
9079
8929
  paths.forEach((path) => {
9080
8930
  const files = this.filesMap.get(path);
9081
- if (!files)
8931
+ const fileTask = createFileTask(path, project.config.root, project.config.name);
8932
+ this.idMap.set(fileTask.id, fileTask);
8933
+ if (!files) {
8934
+ this.filesMap.set(path, [fileTask]);
9082
8935
  return;
8936
+ }
9083
8937
  const filtered = files.filter((file) => file.projectName !== project.config.name);
9084
- if (!filtered.length)
9085
- this.filesMap.delete(path);
9086
- else
9087
- this.filesMap.set(path, filtered);
8938
+ if (!filtered.length) {
8939
+ this.filesMap.set(path, [fileTask]);
8940
+ } else {
8941
+ this.filesMap.set(path, [
8942
+ ...filtered,
8943
+ fileTask
8944
+ ]);
8945
+ }
9088
8946
  });
9089
8947
  }
9090
8948
  updateId(task) {
@@ -9123,25 +8981,7 @@ class StateManager {
9123
8981
  }).length;
9124
8982
  }
9125
8983
  cancelFiles(files, root, projectName) {
9126
- this.collectFiles(files.map((filepath) => {
9127
- const file = {
9128
- filepath,
9129
- name: relative(root, filepath),
9130
- id: filepath,
9131
- mode: "skip",
9132
- type: "suite",
9133
- result: {
9134
- state: "skip"
9135
- },
9136
- meta: {},
9137
- // Cancelled files have not yet collected tests
9138
- tasks: [],
9139
- projectName,
9140
- file: null
9141
- };
9142
- file.file = file;
9143
- return file;
9144
- }));
8984
+ this.collectFiles(files.map((filepath) => createFileTask(filepath, root, projectName)));
9145
8985
  }
9146
8986
  }
9147
8987
 
@@ -11513,7 +11353,7 @@ function resolveApiServerConfig(options) {
11513
11353
  return api;
11514
11354
  }
11515
11355
  function resolveConfig(mode, options, viteConfig, logger) {
11516
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M;
11356
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O;
11517
11357
  if (options.dom) {
11518
11358
  if (((_a = viteConfig.test) == null ? void 0 : _a.environment) != null && viteConfig.test.environment !== "happy-dom") {
11519
11359
  logger.console.warn(
@@ -11554,27 +11394,26 @@ function resolveConfig(mode, options, viteConfig, logger) {
11554
11394
  }
11555
11395
  if (resolved.standalone && !resolved.watch)
11556
11396
  throw new Error(`Vitest standalone mode requires --watch`);
11397
+ if (resolved.mergeReports && resolved.watch)
11398
+ throw new Error(`Cannot merge reports with --watch enabled`);
11557
11399
  if (resolved.maxWorkers)
11558
11400
  resolved.maxWorkers = Number(resolved.maxWorkers);
11559
11401
  if (resolved.minWorkers)
11560
11402
  resolved.minWorkers = Number(resolved.minWorkers);
11561
11403
  resolved.browser ?? (resolved.browser = {});
11562
- (_c = resolved.browser).fileParallelism ?? (_c.fileParallelism = resolved.fileParallelism ?? false);
11563
11404
  resolved.fileParallelism ?? (resolved.fileParallelism = mode !== "benchmark");
11564
11405
  if (!resolved.fileParallelism) {
11565
11406
  resolved.maxWorkers = 1;
11566
11407
  resolved.minWorkers = 1;
11567
11408
  }
11568
11409
  if (resolved.inspect || resolved.inspectBrk) {
11569
- const isSingleThread = resolved.pool === "threads" && ((_e = (_d = resolved.poolOptions) == null ? void 0 : _d.threads) == null ? void 0 : _e.singleThread);
11570
- const isSingleFork = resolved.pool === "forks" && ((_g = (_f = resolved.poolOptions) == null ? void 0 : _f.forks) == null ? void 0 : _g.singleFork);
11410
+ const isSingleThread = resolved.pool === "threads" && ((_d = (_c = resolved.poolOptions) == null ? void 0 : _c.threads) == null ? void 0 : _d.singleThread);
11411
+ const isSingleFork = resolved.pool === "forks" && ((_f = (_e = resolved.poolOptions) == null ? void 0 : _e.forks) == null ? void 0 : _f.singleFork);
11571
11412
  if (resolved.fileParallelism && !isSingleThread && !isSingleFork) {
11572
11413
  const inspectOption = `--inspect${resolved.inspectBrk ? "-brk" : ""}`;
11573
11414
  throw new Error(`You cannot use ${inspectOption} without "--no-file-parallelism", "poolOptions.threads.singleThread" or "poolOptions.forks.singleFork"`);
11574
11415
  }
11575
11416
  }
11576
- if (resolved.coverage.provider === "c8")
11577
- throw new Error('"coverage.provider: c8" is not supported anymore. Use "coverage.provider: v8" instead');
11578
11417
  if (resolved.coverage.provider === "v8" && resolved.coverage.enabled && isBrowserEnabled(resolved))
11579
11418
  throw new Error("@vitest/coverage-v8 does not work with --browser. Use @vitest/coverage-istanbul instead");
11580
11419
  if (resolved.coverage.enabled && resolved.coverage.reportsDirectory) {
@@ -11582,8 +11421,9 @@ function resolveConfig(mode, options, viteConfig, logger) {
11582
11421
  if (reportsDirectory === resolved.root || reportsDirectory === process.cwd())
11583
11422
  throw new Error(`You cannot set "coverage.reportsDirectory" as ${reportsDirectory}. Vitest needs to be able to remove this directory before test run`);
11584
11423
  }
11424
+ resolved.expect ?? (resolved.expect = {});
11585
11425
  resolved.deps ?? (resolved.deps = {});
11586
- (_h = resolved.deps).moduleDirectories ?? (_h.moduleDirectories = []);
11426
+ (_g = resolved.deps).moduleDirectories ?? (_g.moduleDirectories = []);
11587
11427
  resolved.deps.moduleDirectories = resolved.deps.moduleDirectories.map((dir) => {
11588
11428
  if (!dir.startsWith("/"))
11589
11429
  dir = `/${dir}`;
@@ -11593,17 +11433,17 @@ function resolveConfig(mode, options, viteConfig, logger) {
11593
11433
  });
11594
11434
  if (!resolved.deps.moduleDirectories.includes("/node_modules/"))
11595
11435
  resolved.deps.moduleDirectories.push("/node_modules/");
11596
- (_i = resolved.deps).optimizer ?? (_i.optimizer = {});
11597
- (_j = resolved.deps.optimizer).ssr ?? (_j.ssr = {});
11598
- (_k = resolved.deps.optimizer.ssr).enabled ?? (_k.enabled = true);
11599
- (_l = resolved.deps.optimizer).web ?? (_l.web = {});
11600
- (_m = resolved.deps.optimizer.web).enabled ?? (_m.enabled = true);
11601
- (_n = resolved.deps).web ?? (_n.web = {});
11602
- (_o = resolved.deps.web).transformAssets ?? (_o.transformAssets = true);
11603
- (_p = resolved.deps.web).transformCss ?? (_p.transformCss = true);
11604
- (_q = resolved.deps.web).transformGlobPattern ?? (_q.transformGlobPattern = []);
11436
+ (_h = resolved.deps).optimizer ?? (_h.optimizer = {});
11437
+ (_i = resolved.deps.optimizer).ssr ?? (_i.ssr = {});
11438
+ (_j = resolved.deps.optimizer.ssr).enabled ?? (_j.enabled = true);
11439
+ (_k = resolved.deps.optimizer).web ?? (_k.web = {});
11440
+ (_l = resolved.deps.optimizer.web).enabled ?? (_l.enabled = true);
11441
+ (_m = resolved.deps).web ?? (_m.web = {});
11442
+ (_n = resolved.deps.web).transformAssets ?? (_n.transformAssets = true);
11443
+ (_o = resolved.deps.web).transformCss ?? (_o.transformCss = true);
11444
+ (_p = resolved.deps.web).transformGlobPattern ?? (_p.transformGlobPattern = []);
11605
11445
  resolved.server ?? (resolved.server = {});
11606
- (_r = resolved.server).deps ?? (_r.deps = {});
11446
+ (_q = resolved.server).deps ?? (_q.deps = {});
11607
11447
  const deprecatedDepsOptions = ["inline", "external", "fallbackCJS"];
11608
11448
  deprecatedDepsOptions.forEach((option) => {
11609
11449
  if (resolved.deps[option] === void 0)
@@ -11628,11 +11468,11 @@ function resolveConfig(mode, options, viteConfig, logger) {
11628
11468
  if ((ssrOptions == null ? void 0 : ssrOptions.noExternal) === true && resolved.server.deps.inline == null) {
11629
11469
  resolved.server.deps.inline = true;
11630
11470
  } else {
11631
- (_s = resolved.server.deps).inline ?? (_s.inline = []);
11471
+ (_r = resolved.server.deps).inline ?? (_r.inline = []);
11632
11472
  resolved.server.deps.inline.push(...extraInlineDeps);
11633
11473
  }
11634
11474
  }
11635
- (_t = resolved.server.deps).moduleDirectories ?? (_t.moduleDirectories = []);
11475
+ (_s = resolved.server.deps).moduleDirectories ?? (_s.moduleDirectories = []);
11636
11476
  resolved.server.deps.moduleDirectories.push(...resolved.deps.moduleDirectories);
11637
11477
  if (resolved.runner)
11638
11478
  resolved.runner = resolvePath(resolved.runner, resolved.root);
@@ -11662,11 +11502,11 @@ function resolveConfig(mode, options, viteConfig, logger) {
11662
11502
  resolved.poolOptions = {
11663
11503
  ...resolved.poolOptions,
11664
11504
  threads: {
11665
- ...(_u = resolved.poolOptions) == null ? void 0 : _u.threads,
11505
+ ...(_t = resolved.poolOptions) == null ? void 0 : _t.threads,
11666
11506
  maxThreads: Number.parseInt(process.env.VITEST_MAX_THREADS)
11667
11507
  },
11668
11508
  vmThreads: {
11669
- ...(_v = resolved.poolOptions) == null ? void 0 : _v.vmThreads,
11509
+ ...(_u = resolved.poolOptions) == null ? void 0 : _u.vmThreads,
11670
11510
  maxThreads: Number.parseInt(process.env.VITEST_MAX_THREADS)
11671
11511
  }
11672
11512
  };
@@ -11675,11 +11515,11 @@ function resolveConfig(mode, options, viteConfig, logger) {
11675
11515
  resolved.poolOptions = {
11676
11516
  ...resolved.poolOptions,
11677
11517
  threads: {
11678
- ...(_w = resolved.poolOptions) == null ? void 0 : _w.threads,
11518
+ ...(_v = resolved.poolOptions) == null ? void 0 : _v.threads,
11679
11519
  minThreads: Number.parseInt(process.env.VITEST_MIN_THREADS)
11680
11520
  },
11681
11521
  vmThreads: {
11682
- ...(_x = resolved.poolOptions) == null ? void 0 : _x.vmThreads,
11522
+ ...(_w = resolved.poolOptions) == null ? void 0 : _w.vmThreads,
11683
11523
  minThreads: Number.parseInt(process.env.VITEST_MIN_THREADS)
11684
11524
  }
11685
11525
  };
@@ -11688,11 +11528,11 @@ function resolveConfig(mode, options, viteConfig, logger) {
11688
11528
  resolved.poolOptions = {
11689
11529
  ...resolved.poolOptions,
11690
11530
  forks: {
11691
- ...(_y = resolved.poolOptions) == null ? void 0 : _y.forks,
11531
+ ...(_x = resolved.poolOptions) == null ? void 0 : _x.forks,
11692
11532
  maxForks: Number.parseInt(process.env.VITEST_MAX_FORKS)
11693
11533
  },
11694
11534
  vmForks: {
11695
- ...(_z = resolved.poolOptions) == null ? void 0 : _z.vmForks,
11535
+ ...(_y = resolved.poolOptions) == null ? void 0 : _y.vmForks,
11696
11536
  maxForks: Number.parseInt(process.env.VITEST_MAX_FORKS)
11697
11537
  }
11698
11538
  };
@@ -11701,11 +11541,11 @@ function resolveConfig(mode, options, viteConfig, logger) {
11701
11541
  resolved.poolOptions = {
11702
11542
  ...resolved.poolOptions,
11703
11543
  forks: {
11704
- ...(_A = resolved.poolOptions) == null ? void 0 : _A.forks,
11544
+ ...(_z = resolved.poolOptions) == null ? void 0 : _z.forks,
11705
11545
  minForks: Number.parseInt(process.env.VITEST_MIN_FORKS)
11706
11546
  },
11707
11547
  vmForks: {
11708
- ...(_B = resolved.poolOptions) == null ? void 0 : _B.vmForks,
11548
+ ...(_A = resolved.poolOptions) == null ? void 0 : _A.vmForks,
11709
11549
  minForks: Number.parseInt(process.env.VITEST_MIN_FORKS)
11710
11550
  }
11711
11551
  };
@@ -11801,8 +11641,8 @@ function resolveConfig(mode, options, viteConfig, logger) {
11801
11641
  resolved.passWithNoTests ?? (resolved.passWithNoTests = true);
11802
11642
  resolved.css ?? (resolved.css = {});
11803
11643
  if (typeof resolved.css === "object") {
11804
- (_C = resolved.css).modules ?? (_C.modules = {});
11805
- (_D = resolved.css.modules).classNameStrategy ?? (_D.classNameStrategy = "stable");
11644
+ (_B = resolved.css).modules ?? (_B.modules = {});
11645
+ (_C = resolved.css.modules).classNameStrategy ?? (_C.classNameStrategy = "stable");
11806
11646
  }
11807
11647
  if (resolved.cache !== false) {
11808
11648
  let cacheDir = VitestCache.resolveCacheDir("", resolve(viteConfig.cacheDir, "vitest"), resolved.name);
@@ -11819,29 +11659,34 @@ function resolveConfig(mode, options, viteConfig, logger) {
11819
11659
  resolved.sequence ?? (resolved.sequence = {});
11820
11660
  if (resolved.sequence.shuffle && typeof resolved.sequence.shuffle === "object") {
11821
11661
  const { files, tests } = resolved.sequence.shuffle;
11822
- (_E = resolved.sequence).sequencer ?? (_E.sequencer = files ? RandomSequencer : BaseSequencer);
11662
+ (_D = resolved.sequence).sequencer ?? (_D.sequencer = files ? RandomSequencer : BaseSequencer);
11823
11663
  resolved.sequence.shuffle = tests;
11824
11664
  }
11825
- if (!((_F = resolved.sequence) == null ? void 0 : _F.sequencer)) {
11665
+ if (!((_E = resolved.sequence) == null ? void 0 : _E.sequencer)) {
11826
11666
  resolved.sequence.sequencer = resolved.sequence.shuffle ? RandomSequencer : BaseSequencer;
11827
11667
  }
11828
- (_G = resolved.sequence).hooks ?? (_G.hooks = "stack");
11668
+ (_F = resolved.sequence).hooks ?? (_F.hooks = "stack");
11829
11669
  if (resolved.sequence.sequencer === RandomSequencer)
11830
- (_H = resolved.sequence).seed ?? (_H.seed = Date.now());
11670
+ (_G = resolved.sequence).seed ?? (_G.seed = Date.now());
11831
11671
  resolved.typecheck = {
11832
11672
  ...configDefaults.typecheck,
11833
11673
  ...resolved.typecheck
11834
11674
  };
11835
- resolved.environmentMatchGlobs = (resolved.environmentMatchGlobs || []).map((i) => [resolve(resolved.root, i[0]), i[1]]);
11675
+ resolved.environmentMatchGlobs = (resolved.environmentMatchGlobs || []).map(
11676
+ (i) => [resolve(resolved.root, i[0]), i[1]]
11677
+ );
11836
11678
  resolved.typecheck ?? (resolved.typecheck = {});
11837
- (_I = resolved.typecheck).enabled ?? (_I.enabled = false);
11679
+ (_H = resolved.typecheck).enabled ?? (_H.enabled = false);
11838
11680
  if (resolved.typecheck.enabled)
11839
11681
  logger.console.warn(c.yellow("Testing types with tsc and vue-tsc is an experimental feature.\nBreaking changes might not follow SemVer, please pin Vitest's version when using it."));
11840
11682
  resolved.browser ?? (resolved.browser = {});
11841
- (_J = resolved.browser).enabled ?? (_J.enabled = false);
11842
- (_K = resolved.browser).headless ?? (_K.headless = isCI);
11843
- (_L = resolved.browser).slowHijackESM ?? (_L.slowHijackESM = false);
11844
- (_M = resolved.browser).isolate ?? (_M.isolate = true);
11683
+ (_I = resolved.browser).enabled ?? (_I.enabled = false);
11684
+ (_J = resolved.browser).headless ?? (_J.headless = isCI);
11685
+ (_K = resolved.browser).isolate ?? (_K.isolate = true);
11686
+ (_L = resolved.browser).ui ?? (_L.ui = !isCI);
11687
+ (_M = resolved.browser).viewport ?? (_M.viewport = {});
11688
+ (_N = resolved.browser.viewport).width ?? (_N.width = 414);
11689
+ (_O = resolved.browser.viewport).height ?? (_O.height = 896);
11845
11690
  if (resolved.browser.enabled && provider$1 === "stackblitz")
11846
11691
  resolved.browser.provider = "none";
11847
11692
  resolved.browser.api = resolveApiServerConfig(resolved.browser) || {
@@ -11901,7 +11746,7 @@ function getBetterEnd(code, node) {
11901
11746
  end += 1;
11902
11747
  return end;
11903
11748
  }
11904
- const regexpHoistable = /\b(vi|vitest)\s*\.\s*(mock|unmock|hoisted|doMock|doUnmock)\(/;
11749
+ const regexpHoistable = /\b(?:vi|vitest)\s*\.\s*(?:mock|unmock|hoisted|doMock|doUnmock)\(/;
11905
11750
  const hashbangRE = /^#!.*\n/;
11906
11751
  function hoistMocks(code, id, parse, colors) {
11907
11752
  var _a;
@@ -12151,6 +11996,8 @@ function MocksPlugin() {
12151
11996
  name: "vitest:mocks",
12152
11997
  enforce: "post",
12153
11998
  transform(code, id) {
11999
+ if (id.includes(distDir))
12000
+ return;
12154
12001
  return hoistMocks(code, id, this.parse);
12155
12002
  }
12156
12003
  };
@@ -12253,6 +12100,157 @@ function resolveFsAllow(projectRoot, rootConfigFile) {
12253
12100
  return [dirname(rootConfigFile), searchForWorkspaceRoot(projectRoot), rootDir];
12254
12101
  }
12255
12102
 
12103
+ function setupBrowserRpc(project, server) {
12104
+ var _a;
12105
+ const ctx = project.ctx;
12106
+ const wss = new WebSocketServer$1({ noServer: true });
12107
+ (_a = server.httpServer) == null ? void 0 : _a.on("upgrade", (request, socket, head) => {
12108
+ if (!request.url)
12109
+ return;
12110
+ const { pathname, searchParams } = new URL(request.url, "http://localhost");
12111
+ if (pathname !== BROWSER_API_PATH)
12112
+ return;
12113
+ const type = searchParams.get("type") ?? "tester";
12114
+ const sessionId = searchParams.get("sessionId") ?? "0";
12115
+ wss.handleUpgrade(request, socket, head, (ws) => {
12116
+ wss.emit("connection", ws, request);
12117
+ const rpc = setupClient(sessionId, ws);
12118
+ const rpcs = project.browserRpc;
12119
+ const clients = type === "tester" ? rpcs.testers : rpcs.orchestrators;
12120
+ clients.set(sessionId, rpc);
12121
+ ws.on("close", () => {
12122
+ clients.delete(sessionId);
12123
+ });
12124
+ });
12125
+ });
12126
+ function checkFileAccess(path) {
12127
+ if (!isFileServingAllowed(path, server))
12128
+ throw new Error(`Access denied to "${path}". See Vite config documentation for "server.fs": https://vitejs.dev/config/server-options.html#server-fs-strict.`);
12129
+ }
12130
+ function setupClient(sessionId, ws) {
12131
+ const rpc = createBirpc(
12132
+ {
12133
+ async onUnhandledError(error, type) {
12134
+ ctx.state.catchError(error, type);
12135
+ },
12136
+ async onCollected(files) {
12137
+ ctx.state.collectFiles(files);
12138
+ await ctx.report("onCollected", files);
12139
+ },
12140
+ async onTaskUpdate(packs) {
12141
+ ctx.state.updateTasks(packs);
12142
+ await ctx.report("onTaskUpdate", packs);
12143
+ },
12144
+ onAfterSuiteRun(meta) {
12145
+ var _a2;
12146
+ (_a2 = ctx.coverageProvider) == null ? void 0 : _a2.onAfterSuiteRun(meta);
12147
+ },
12148
+ sendLog(log) {
12149
+ return ctx.report("onUserConsoleLog", log);
12150
+ },
12151
+ resolveSnapshotPath(testPath) {
12152
+ return ctx.snapshot.resolvePath(testPath);
12153
+ },
12154
+ resolveSnapshotRawPath(testPath, rawPath) {
12155
+ return ctx.snapshot.resolveRawPath(testPath, rawPath);
12156
+ },
12157
+ snapshotSaved(snapshot) {
12158
+ ctx.snapshot.add(snapshot);
12159
+ },
12160
+ async readSnapshotFile(snapshotPath) {
12161
+ checkFileAccess(snapshotPath);
12162
+ if (!existsSync(snapshotPath))
12163
+ return null;
12164
+ return promises$1.readFile(snapshotPath, "utf-8");
12165
+ },
12166
+ async saveSnapshotFile(id, content) {
12167
+ checkFileAccess(id);
12168
+ await promises$1.mkdir(dirname(id), { recursive: true });
12169
+ return promises$1.writeFile(id, content, "utf-8");
12170
+ },
12171
+ async removeSnapshotFile(id) {
12172
+ checkFileAccess(id);
12173
+ if (!existsSync(id))
12174
+ throw new Error(`Snapshot file "${id}" does not exist.`);
12175
+ return promises$1.unlink(id);
12176
+ },
12177
+ async getBrowserFileSourceMap(id) {
12178
+ var _a2, _b;
12179
+ const mod = (_a2 = project.browser) == null ? void 0 : _a2.moduleGraph.getModuleById(id);
12180
+ return (_b = mod == null ? void 0 : mod.transformResult) == null ? void 0 : _b.map;
12181
+ },
12182
+ onCancel(reason) {
12183
+ ctx.cancelCurrentRun(reason);
12184
+ },
12185
+ async resolveId(id, importer) {
12186
+ const result = await project.server.pluginContainer.resolveId(id, importer, {
12187
+ ssr: false
12188
+ });
12189
+ return result;
12190
+ },
12191
+ debug(...args) {
12192
+ ctx.logger.console.debug(...args);
12193
+ },
12194
+ getCountOfFailedTests() {
12195
+ return ctx.state.getCountOfFailedTests();
12196
+ },
12197
+ triggerCommand(command, testPath, payload) {
12198
+ var _a2;
12199
+ if (!project.browserProvider)
12200
+ throw new Error("Commands are only available for browser tests.");
12201
+ const commands = (_a2 = project.config.browser) == null ? void 0 : _a2.commands;
12202
+ if (!commands || !commands[command])
12203
+ throw new Error(`Unknown command "${command}".`);
12204
+ return commands[command]({
12205
+ testPath,
12206
+ project,
12207
+ provider: project.browserProvider
12208
+ }, ...payload);
12209
+ },
12210
+ getBrowserFiles() {
12211
+ var _a2;
12212
+ return ((_a2 = project.browserState) == null ? void 0 : _a2.files) ?? [];
12213
+ },
12214
+ finishBrowserTests() {
12215
+ var _a2;
12216
+ return (_a2 = project.browserState) == null ? void 0 : _a2.resolve();
12217
+ },
12218
+ getProvidedContext() {
12219
+ return "ctx" in project ? project.getProvidedContext() : {};
12220
+ },
12221
+ async queueMock(id, importer, hasFactory) {
12222
+ return project.browserMocker.mock(sessionId, id, importer, hasFactory);
12223
+ },
12224
+ async queueUnmock(id, importer) {
12225
+ return project.browserMocker.unmock(id, importer);
12226
+ },
12227
+ resolveMock(rawId, importer) {
12228
+ return project.browserMocker.resolveMock(rawId, importer, false);
12229
+ },
12230
+ invalidateMocks() {
12231
+ const mocker = project.browserMocker;
12232
+ mocker.mocks.forEach((_, id) => {
12233
+ mocker.invalidateModuleById(id);
12234
+ });
12235
+ mocker.mocks.clear();
12236
+ }
12237
+ },
12238
+ {
12239
+ post: (msg) => ws.send(msg),
12240
+ on: (fn) => ws.on("message", fn),
12241
+ eventNames: ["onCancel"],
12242
+ serialize: (data) => stringify(data, stringifyReplace),
12243
+ deserialize: parse$3,
12244
+ onTimeoutError(functionName) {
12245
+ throw new Error(`[vitest-api]: Timeout calling "${functionName}"`);
12246
+ }
12247
+ }
12248
+ );
12249
+ ctx.onCancel((reason) => rpc.onCancel(reason));
12250
+ return rpc;
12251
+ }
12252
+ }
12253
+
12256
12254
  async function createBrowserServer(project, configFile) {
12257
12255
  var _a;
12258
12256
  const root = project.config.root;
@@ -12267,12 +12265,11 @@ async function createBrowserServer(project, configFile) {
12267
12265
  // watch is handled by Vitest
12268
12266
  server: {
12269
12267
  hmr: false,
12270
- watch: {
12271
- ignored: ["**/**"]
12272
- }
12268
+ watch: null
12273
12269
  },
12274
12270
  plugins: [
12275
12271
  ...((_a = project.options) == null ? void 0 : _a.plugins) || [],
12272
+ MocksPlugin(),
12276
12273
  (await import('@vitest/browser')).default(project, "/"),
12277
12274
  CoverageTransform(project.ctx),
12278
12275
  {
@@ -12301,16 +12298,18 @@ async function createBrowserServer(project, configFile) {
12301
12298
  alias: (_c = config.test) == null ? void 0 : _c.alias
12302
12299
  },
12303
12300
  server: {
12304
- watch: null
12301
+ watch: null,
12302
+ preTransformRequests: false
12305
12303
  }
12306
12304
  };
12307
12305
  }
12308
- },
12309
- MocksPlugin()
12306
+ }
12310
12307
  ]
12311
12308
  });
12312
12309
  await server.listen();
12313
- (await Promise.resolve().then(function () { return setup$1; })).setup(project, server);
12310
+ setupBrowserRpc(project, server);
12311
+ if (project.config.browser.ui)
12312
+ setup(project.ctx, server);
12314
12313
  return server;
12315
12314
  }
12316
12315
 
@@ -12333,6 +12332,91 @@ async function getBrowserProvider(options, project) {
12333
12332
  return customProviderModule.default;
12334
12333
  }
12335
12334
 
12335
+ var __defProp = Object.defineProperty;
12336
+ var __typeError = (msg) => {
12337
+ throw TypeError(msg);
12338
+ };
12339
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12340
+ var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
12341
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
12342
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
12343
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
12344
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
12345
+ var _project;
12346
+ class VitestBrowserServerMocker {
12347
+ constructor(project) {
12348
+ // string means it will read from __mocks__ folder
12349
+ // undefined means there is a factory mock that will be called on the server
12350
+ // null means it should be auto mocked
12351
+ __publicField(this, "mocks", /* @__PURE__ */ new Map());
12352
+ // private because the typecheck fails on build if it's exposed
12353
+ // due to a self reference
12354
+ __privateAdd(this, _project);
12355
+ __privateSet(this, _project, project);
12356
+ }
12357
+ async mock(sessionId, rawId, importer, hasFactory) {
12358
+ const { type, mockPath, resolvedId } = await this.resolveMock(rawId, importer, hasFactory);
12359
+ this.invalidateModuleById(resolvedId);
12360
+ if (type === "factory") {
12361
+ this.mocks.set(resolvedId, { sessionId, mock: void 0 });
12362
+ return resolvedId;
12363
+ }
12364
+ this.mocks.set(resolvedId, { sessionId, mock: mockPath });
12365
+ return resolvedId;
12366
+ }
12367
+ async unmock(rawId, importer) {
12368
+ const { id } = await this.resolveId(rawId, importer);
12369
+ this.invalidateModuleById(id);
12370
+ this.mocks.delete(id);
12371
+ return id;
12372
+ }
12373
+ async resolveMock(rawId, importer, hasFactory) {
12374
+ const { id, fsPath, external } = await this.resolveId(rawId, importer);
12375
+ if (hasFactory)
12376
+ return { type: "factory", resolvedId: id };
12377
+ const mockPath = this.resolveMockPath(fsPath, external);
12378
+ return {
12379
+ type: mockPath === null ? "automock" : "redirect",
12380
+ mockPath,
12381
+ resolvedId: id
12382
+ };
12383
+ }
12384
+ invalidateModuleById(id) {
12385
+ const moduleGraph = __privateGet(this, _project).browser.moduleGraph;
12386
+ const module = moduleGraph.getModuleById(id);
12387
+ if (module)
12388
+ moduleGraph.invalidateModule(module, /* @__PURE__ */ new Set(), Date.now(), true);
12389
+ }
12390
+ async resolveId(rawId, importer) {
12391
+ const resolved = await __privateGet(this, _project).browser.pluginContainer.resolveId(rawId, importer, {
12392
+ ssr: false
12393
+ });
12394
+ return __privateGet(this, _project).vitenode.resolveModule(rawId, resolved);
12395
+ }
12396
+ resolveMockPath(mockPath, external) {
12397
+ const path = external || mockPath;
12398
+ if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) {
12399
+ const mockDirname = dirname(path);
12400
+ const mockFolder = join(__privateGet(this, _project).config.root, "__mocks__", mockDirname);
12401
+ if (!existsSync(mockFolder))
12402
+ return null;
12403
+ const files = readdirSync(mockFolder);
12404
+ const baseOriginal = basename(path);
12405
+ for (const file of files) {
12406
+ const baseFile = basename(file, extname$1(file));
12407
+ if (baseFile === baseOriginal)
12408
+ return resolve(mockFolder, file);
12409
+ }
12410
+ return null;
12411
+ }
12412
+ const dir = dirname(path);
12413
+ const baseId = basename(path);
12414
+ const fullPath = resolve(dir, "__mocks__", baseId);
12415
+ return existsSync(fullPath) ? fullPath : null;
12416
+ }
12417
+ }
12418
+ _project = new WeakMap();
12419
+
12336
12420
  function generateCssFilenameHash(filepath) {
12337
12421
  return createHash$2("md5").update(filepath).digest("hex").slice(0, 6);
12338
12422
  }
@@ -12345,10 +12429,10 @@ function generateScopedClassName(strategy, name, filename) {
12345
12429
  return `_${name}_${hash}`;
12346
12430
  }
12347
12431
 
12348
- const cssLangs = "\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)";
12432
+ const cssLangs = "\\.(?:css|less|sass|scss|styl|stylus|pcss|postcss)(?:$|\\?)";
12349
12433
  const cssLangRE = new RegExp(cssLangs);
12350
12434
  const cssModuleRE = new RegExp(`\\.module${cssLangs}`);
12351
- const cssInlineRE = /[?&]inline(&|$)/;
12435
+ const cssInlineRE = /[?&]inline(?:&|$)/;
12352
12436
  function isCSS(id) {
12353
12437
  return cssLangRE.test(id);
12354
12438
  }
@@ -12960,7 +13044,7 @@ function NormalizeURLPlugin() {
12960
13044
  if (ssr || !code.includes("new URL") || !code.includes("import.meta.url"))
12961
13045
  return;
12962
13046
  const cleanString = stripLiteral(code);
12963
- const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/g;
13047
+ const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*(?:'[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/g;
12964
13048
  let updatedCode = code;
12965
13049
  let match;
12966
13050
  while (match = assetImportMetaUrlRE.exec(cleanString)) {
@@ -13053,17 +13137,12 @@ function WorkspaceVitestPlugin(project, options) {
13053
13137
  hijackVitePluginInject(viteConfig);
13054
13138
  },
13055
13139
  async configureServer(server) {
13056
- try {
13057
- const options2 = deepMerge(
13058
- {},
13059
- configDefaults,
13060
- server.config.test || {}
13061
- );
13062
- await project.setServer(options2, server);
13063
- } catch (err) {
13064
- project.ctx.logger.printError(err, { fullStack: true });
13065
- process.exit(1);
13066
- }
13140
+ const options2 = deepMerge(
13141
+ {},
13142
+ configDefaults,
13143
+ server.config.test || {}
13144
+ );
13145
+ await project.setServer(options2, server);
13067
13146
  await server.watcher.close();
13068
13147
  }
13069
13148
  },
@@ -13152,7 +13231,14 @@ class WorkspaceProject {
13152
13231
  browser;
13153
13232
  typechecker;
13154
13233
  closingPromise;
13234
+ // TODO: abstract browser related things and move to @vitest/browser
13155
13235
  browserProvider;
13236
+ browserMocker = new VitestBrowserServerMocker(this);
13237
+ // TODO: I mean, we really need to abstract it
13238
+ browserRpc = {
13239
+ orchestrators: /* @__PURE__ */ new Map(),
13240
+ testers: /* @__PURE__ */ new Map()
13241
+ };
13156
13242
  browserState;
13157
13243
  testFilesList = null;
13158
13244
  id = nanoid();
@@ -13188,35 +13274,21 @@ class WorkspaceProject {
13188
13274
  if (this._globalSetups)
13189
13275
  return;
13190
13276
  this._globalSetups = await loadGlobalSetupFiles(this.runner, this.config.globalSetup);
13191
- try {
13192
- for (const globalSetupFile of this._globalSetups) {
13193
- const teardown = await ((_a = globalSetupFile.setup) == null ? void 0 : _a.call(globalSetupFile, { provide: this.provide, config: this.config }));
13194
- if (teardown == null || !!globalSetupFile.teardown)
13195
- continue;
13196
- if (typeof teardown !== "function")
13197
- throw new Error(`invalid return value in globalSetup file ${globalSetupFile.file}. Must return a function`);
13198
- globalSetupFile.teardown = teardown;
13199
- }
13200
- } catch (e) {
13201
- this.logger.error(`
13202
- ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
13203
- this.logger.printError(e);
13204
- process.exit(1);
13277
+ for (const globalSetupFile of this._globalSetups) {
13278
+ const teardown = await ((_a = globalSetupFile.setup) == null ? void 0 : _a.call(globalSetupFile, { provide: this.provide, config: this.config }));
13279
+ if (teardown == null || !!globalSetupFile.teardown)
13280
+ continue;
13281
+ if (typeof teardown !== "function")
13282
+ throw new Error(`invalid return value in globalSetup file ${globalSetupFile.file}. Must return a function`);
13283
+ globalSetupFile.teardown = teardown;
13205
13284
  }
13206
13285
  }
13207
13286
  async teardownGlobalSetup() {
13208
13287
  var _a;
13209
13288
  if (!this._globalSetups)
13210
13289
  return;
13211
- for (const globalSetupFile of [...this._globalSetups].reverse()) {
13212
- try {
13213
- await ((_a = globalSetupFile.teardown) == null ? void 0 : _a.call(globalSetupFile));
13214
- } catch (error) {
13215
- this.logger.error(`error during global teardown of ${globalSetupFile.file}`, error);
13216
- this.logger.printError(error);
13217
- process.exitCode = 1;
13218
- }
13219
- }
13290
+ for (const globalSetupFile of [...this._globalSetups].reverse())
13291
+ await ((_a = globalSetupFile.teardown) == null ? void 0 : _a.call(globalSetupFile));
13220
13292
  }
13221
13293
  get logger() {
13222
13294
  return this.ctx.logger;
@@ -13419,7 +13491,14 @@ ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
13419
13491
  env: {
13420
13492
  ...(_v = this.server) == null ? void 0 : _v.config.env,
13421
13493
  ...this.config.env
13422
- }
13494
+ },
13495
+ browser: {
13496
+ ...this.ctx.config.browser,
13497
+ indexScripts: [],
13498
+ testerScripts: [],
13499
+ commands: {}
13500
+ },
13501
+ printConsoleTrace: this.config.printConsoleTrace ?? this.ctx.config.printConsoleTrace
13423
13502
  }, this.ctx.configOverride || {});
13424
13503
  }
13425
13504
  close() {
@@ -13617,9 +13696,12 @@ class Vitest {
13617
13696
  getProjectByTaskId(taskId) {
13618
13697
  var _a;
13619
13698
  const task = this.state.idMap.get(taskId);
13620
- const projectName = task.projectName || ((_a = task == null ? void 0 : task.file) == null ? void 0 : _a.projectName);
13699
+ const projectName = task.projectName || ((_a = task == null ? void 0 : task.file) == null ? void 0 : _a.projectName) || "";
13621
13700
  return this.projects.find((p) => p.getName() === projectName) || this.getCoreWorkspaceProject() || this.projects[0];
13622
13701
  }
13702
+ getProjectByName(name = "") {
13703
+ return this.projects.find((p) => p.getName() === name) || this.getCoreWorkspaceProject() || this.projects[0];
13704
+ }
13623
13705
  async getWorkspaceConfigPath() {
13624
13706
  if (this.config.workspace)
13625
13707
  return this.config.workspace;
@@ -13707,7 +13789,8 @@ class Vitest {
13707
13789
  "testNamePattern",
13708
13790
  "passWithNoTests",
13709
13791
  "bail",
13710
- "isolate"
13792
+ "isolate",
13793
+ "printConsoleTrace"
13711
13794
  ];
13712
13795
  const cliOverrides = overridesOptions.reduce((acc, name) => {
13713
13796
  if (name in cliOptions)
@@ -13766,8 +13849,52 @@ class Vitest {
13766
13849
  async initBrowserProviders() {
13767
13850
  return Promise.all(this.projects.map((w) => w.initBrowserProvider()));
13768
13851
  }
13769
- async start(filters) {
13852
+ async mergeReports() {
13770
13853
  var _a, _b;
13854
+ if (this.reporters.some((r) => r instanceof BlobReporter))
13855
+ throw new Error("Cannot merge reports when `--reporter=blob` is used. Remove blob reporter from the config first.");
13856
+ const { files, errors, coverages } = await readBlobs(this.config.mergeReports, this.projects);
13857
+ await this.report("onInit", this);
13858
+ await this.report("onPathsCollected", files.flatMap((f) => f.filepath));
13859
+ const workspaceSpecs = /* @__PURE__ */ new Map();
13860
+ for (const file of files) {
13861
+ const project = this.getProjectByName(file.projectName);
13862
+ const specs = workspaceSpecs.get(project) || [];
13863
+ specs.push(file);
13864
+ workspaceSpecs.set(project, specs);
13865
+ }
13866
+ for (const [project, files2] of workspaceSpecs) {
13867
+ const filepaths = files2.map((f) => f.filepath);
13868
+ this.state.clearFiles(project, filepaths);
13869
+ files2.forEach((file) => {
13870
+ var _a2;
13871
+ (_a2 = file.logs) == null ? void 0 : _a2.forEach((log) => this.state.updateUserLog(log));
13872
+ });
13873
+ this.state.collectFiles(files2);
13874
+ }
13875
+ await this.report("onCollected", files).catch(noop$1);
13876
+ for (const file of files) {
13877
+ const logs = [];
13878
+ const taskPacks = [];
13879
+ const tasks = getTasks(file);
13880
+ for (const task of tasks) {
13881
+ if (task.logs)
13882
+ logs.push(...task.logs);
13883
+ taskPacks.push([task.id, task.result, task.meta]);
13884
+ }
13885
+ logs.sort((log1, log2) => log1.time - log2.time);
13886
+ for (const log of logs)
13887
+ await this.report("onUserConsoleLog", log).catch(noop$1);
13888
+ await this.report("onTaskUpdate", taskPacks).catch(noop$1);
13889
+ }
13890
+ if (hasFailed(files))
13891
+ process.exitCode = 1;
13892
+ await this.report("onFinished", files, errors);
13893
+ await this.initCoverageProvider();
13894
+ await ((_b = (_a = this.coverageProvider) == null ? void 0 : _a.mergeReports) == null ? void 0 : _b.call(_a, coverages));
13895
+ }
13896
+ async start(filters) {
13897
+ var _a, _b, _c, _d;
13771
13898
  this._onClose = [];
13772
13899
  try {
13773
13900
  await this.initCoverageProvider();
@@ -13780,9 +13907,10 @@ class Vitest {
13780
13907
  await this.globTestFiles(filters)
13781
13908
  );
13782
13909
  if (!files.length) {
13783
- await this.reportCoverage(true);
13910
+ const coverage = await ((_c = (_b = this.coverageProvider) == null ? void 0 : _b.generateCoverage) == null ? void 0 : _c.call(_b, { allTestsRun: true }));
13911
+ await this.reportCoverage(coverage, true);
13784
13912
  this.logger.printNoTestFound(filters);
13785
- if (!this.config.watch || !(this.config.changed || ((_b = this.config.related) == null ? void 0 : _b.length))) {
13913
+ if (!this.config.watch || !(this.config.changed || ((_d = this.config.related) == null ? void 0 : _d.length))) {
13786
13914
  const exitCode = this.config.passWithNoTests ? 0 : 1;
13787
13915
  process.exit(exitCode);
13788
13916
  }
@@ -13884,11 +14012,14 @@ class Vitest {
13884
14012
  const vitestDir = projectVitestPath ? resolve(projectVitestPath.id, "../..") : rootDir;
13885
14013
  this.distPath = join(vitestDir, "dist");
13886
14014
  }
13887
- async runFiles(paths, allTestsRun) {
14015
+ async runFiles(specs, allTestsRun) {
13888
14016
  await this.initializeDistPath();
13889
- const filepaths = paths.map(([, file]) => file);
14017
+ const filepaths = specs.map(([, file]) => file);
13890
14018
  this.state.collectPaths(filepaths);
13891
14019
  await this.report("onPathsCollected", filepaths);
14020
+ await this.report("onSpecsCollected", specs.map(
14021
+ ([project, file]) => [{ name: project.config.name, root: project.config.root }, file]
14022
+ ));
13892
14023
  await this.runningPromise;
13893
14024
  this._onCancelListeners = [];
13894
14025
  this.isCancelling = false;
@@ -13902,9 +14033,9 @@ class Vitest {
13902
14033
  this.state.clearErrors();
13903
14034
  if (!this.isFirstRun && this.config.coverage.cleanOnRerun)
13904
14035
  await ((_a = this.coverageProvider) == null ? void 0 : _a.clean());
13905
- await this.initializeGlobalSetup(paths);
14036
+ await this.initializeGlobalSetup(specs);
13906
14037
  try {
13907
- await this.pool.runTests(paths, invalidates);
14038
+ await this.pool.runTests(specs, invalidates);
13908
14039
  } catch (err) {
13909
14040
  this.state.catchError(err, "Unhandled Error");
13910
14041
  }
@@ -13914,9 +14045,11 @@ class Vitest {
13914
14045
  this.cache.results.updateResults(files);
13915
14046
  await this.cache.results.writeToCache();
13916
14047
  })().finally(async () => {
13917
- const specs = Array.from(new Set(paths.map(([, p]) => p)));
13918
- await this.report("onFinished", this.state.getFiles(specs), this.state.getUnhandledErrors());
13919
- await this.reportCoverage(allTestsRun);
14048
+ var _a;
14049
+ const files = Array.from(new Set(specs.map(([, p]) => p)));
14050
+ const coverage = await ((_a = this.coverageProvider) == null ? void 0 : _a.generateCoverage({ allTestsRun }));
14051
+ await this.report("onFinished", this.state.getFiles(files), this.state.getUnhandledErrors(), coverage);
14052
+ await this.reportCoverage(coverage, allTestsRun);
13920
14053
  this.runningPromise = void 0;
13921
14054
  this.isFirstRun = false;
13922
14055
  this.config.changed = false;
@@ -14037,7 +14170,7 @@ class Vitest {
14037
14170
  tests.map((test) => slash$1(test))
14038
14171
  );
14039
14172
  }
14040
- unregisterWatcher = noop$2;
14173
+ unregisterWatcher = noop$1;
14041
14174
  registerWatcher() {
14042
14175
  const updateLastChanged = (filepath) => {
14043
14176
  const projects = this.getModuleProjects(filepath);
@@ -14101,7 +14234,7 @@ class Vitest {
14101
14234
  watcher.off("change", onChange);
14102
14235
  watcher.off("unlink", onUnlink);
14103
14236
  watcher.off("add", onAdd);
14104
- this.unregisterWatcher = noop$2;
14237
+ this.unregisterWatcher = noop$1;
14105
14238
  };
14106
14239
  }
14107
14240
  /**
@@ -14148,11 +14281,11 @@ class Vitest {
14148
14281
  }
14149
14282
  return Array.from(new Set(files));
14150
14283
  }
14151
- async reportCoverage(allTestsRun) {
14284
+ async reportCoverage(coverage, allTestsRun) {
14152
14285
  if (!this.config.coverage.reportOnFailure && this.state.getCountOfFailedTests() > 0)
14153
14286
  return;
14154
14287
  if (this.coverageProvider) {
14155
- await this.coverageProvider.reportCoverage({ allTestsRun });
14288
+ await this.coverageProvider.reportCoverage(coverage, { allTestsRun });
14156
14289
  for (const reporter of this.reporters) {
14157
14290
  if (reporter instanceof WebSocketReporter)
14158
14291
  reporter.onFinishedReportCoverage();
@@ -14396,14 +14529,9 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
14396
14529
  console.log("[debug] watcher is ready");
14397
14530
  });
14398
14531
  }
14399
- try {
14400
- await ctx.setServer(options, server, userConfig);
14401
- if (options.api && options.watch)
14402
- (await Promise.resolve().then(function () { return setup$1; })).setup(ctx);
14403
- } catch (err) {
14404
- ctx.logger.printError(err, { fullStack: true });
14405
- process.exit(1);
14406
- }
14532
+ await ctx.setServer(options, server, userConfig);
14533
+ if (options.api && options.watch)
14534
+ (await Promise.resolve().then(function () { return setup$1; })).setup(ctx);
14407
14535
  if (!options.watch)
14408
14536
  await server.watcher.close();
14409
14537
  }
@@ -21038,13 +21166,15 @@ async function startVitest(mode, cliFilters = [], options = {}, viteOverrides, v
21038
21166
  ctx.start(cliFilters);
21039
21167
  });
21040
21168
  try {
21041
- if (ctx.config.standalone)
21169
+ if (ctx.config.mergeReports)
21170
+ await ctx.mergeReports();
21171
+ else if (ctx.config.standalone)
21042
21172
  await ctx.init();
21043
21173
  else
21044
21174
  await ctx.start(cliFilters);
21045
21175
  } catch (e) {
21046
21176
  process.exitCode = 1;
21047
- await ctx.logger.printError(e, { fullStack: true, type: "Unhandled Error" });
21177
+ ctx.logger.printError(e, { fullStack: true, type: "Unhandled Error" });
21048
21178
  ctx.logger.error("\n\n");
21049
21179
  return ctx;
21050
21180
  }