vitest 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE.md +0 -83
  2. package/dist/browser.d.ts +3 -2
  3. package/dist/browser.js +4 -8
  4. package/dist/child.js +43 -29
  5. package/dist/{chunk-api-setup.8f785c4a.js → chunk-api-setup.644415c3.js} +13 -7
  6. package/dist/{chunk-install-pkg.23da664c.js → chunk-install-pkg.dd70081b.js} +14 -13
  7. package/dist/{chunk-integrations-globals.0093e2ed.js → chunk-integrations-globals.877c84db.js} +7 -6
  8. package/dist/chunk-runtime-console.ea222ffb.js +108 -0
  9. package/dist/cli.js +14 -15
  10. package/dist/config.cjs +4 -3
  11. package/dist/config.d.ts +15 -19
  12. package/dist/config.js +4 -3
  13. package/dist/coverage.d.ts +3 -2
  14. package/dist/entry-vm.js +60 -0
  15. package/dist/entry.js +34 -213
  16. package/dist/environments.d.ts +3 -2
  17. package/dist/environments.js +4 -2
  18. package/dist/execute.js +15 -0
  19. package/dist/index.d.ts +12 -7
  20. package/dist/index.js +8 -7
  21. package/dist/loader.js +6 -4
  22. package/dist/node.d.ts +6 -53
  23. package/dist/node.js +16 -19
  24. package/dist/runners.d.ts +3 -2
  25. package/dist/runners.js +6 -5
  26. package/dist/{types-198fd1d9.d.ts → types-3c7dbfa5.d.ts} +139 -121
  27. package/dist/vendor-base.9c08bbd0.js +96 -0
  28. package/dist/{vendor-coverage.2e41927a.js → vendor-coverage.78040316.js} +1 -2
  29. package/dist/vendor-date.6e993429.js +50 -0
  30. package/dist/{vendor-environments.392ddf08.js → vendor-environments.443ecd82.js} +199 -3
  31. package/dist/vendor-execute.9ab1c1a7.js +978 -0
  32. package/dist/{vendor-global.6795f91f.js → vendor-global.97e4527c.js} +2 -1
  33. package/dist/{vendor-index.23ac4e13.js → vendor-index.087d1af7.js} +2 -20
  34. package/dist/vendor-index.9378c9a4.js +89 -0
  35. package/dist/vendor-index.b271ebe4.js +92 -0
  36. package/dist/{vendor-index.2af39fbb.js → vendor-index.eff408fd.js} +2 -3
  37. package/dist/{vendor-cli-api.bf4b62a8.js → vendor-node.00226ab1.js} +538 -836
  38. package/dist/{vendor-rpc.ad5b08c7.js → vendor-rpc.cbd8e972.js} +7 -4
  39. package/dist/{vendor-run-once.1fa85ba7.js → vendor-run-once.3e5ef7d7.js} +1 -2
  40. package/dist/vendor-source-map.e6c1997b.js +747 -0
  41. package/dist/{vendor-vi.dd6706cb.js → vendor-vi.271667ef.js} +26 -59
  42. package/dist/vm.js +114 -0
  43. package/dist/worker.js +39 -27
  44. package/execute.d.ts +1 -0
  45. package/package.json +12 -9
  46. package/suppress-warnings.cjs +2 -0
  47. package/dist/vendor-execute.3576af13.js +0 -421
  48. package/dist/vendor-index.cc463d9e.js +0 -189
  49. package/dist/vendor-tasks.f9d75aed.js +0 -14
@@ -1,16 +1,10 @@
1
- import { resolve as resolve$2, relative, isAbsolute, dirname, basename, normalize, join, extname, toNamespacedPath } from 'pathe';
2
- import { E as EXIT_CODE_RESTART, c as configFiles, d as defaultPort, a as defaultBrowserPort, w as workspacesFiles, C as CONFIG_NAMES } from './vendor-constants.538d9b49.js';
3
- import { g as getCoverageProvider, C as CoverageProviderMap } from './vendor-coverage.2e41927a.js';
4
- import { g as getEnvPackageName } from './vendor-environments.392ddf08.js';
5
- import url, { fileURLToPath, pathToFileURL } from 'node:url';
6
- import c from 'picocolors';
7
- import { isPackageExists, resolveModule } from 'local-pkg';
8
- import { a as isNode, b as relativePath, c as removeUndefinedValues, d as isWindows } from './vendor-index.23ac4e13.js';
9
- import { isCI } from 'std-env';
1
+ import { resolve, relative, isAbsolute, dirname, basename, normalize, join, extname, toNamespacedPath } from 'pathe';
10
2
  import { loadConfigFromFile, createServer, version as version$2, mergeConfig } from 'vite';
11
3
  import path$a from 'node:path';
4
+ import url, { fileURLToPath, pathToFileURL } from 'node:url';
12
5
  import process$1 from 'node:process';
13
6
  import fs$8, { promises, existsSync, readFileSync } from 'node:fs';
7
+ import { E as EXIT_CODE_RESTART, c as configFiles, d as defaultPort, a as defaultBrowserPort, w as workspacesFiles, C as CONFIG_NAMES } from './vendor-constants.538d9b49.js';
14
8
  import { g as getDefaultExportFromCjs, c as commonjsGlobal } from './vendor-_commonjsHelpers.7d1333e8.js';
15
9
  import require$$0 from 'os';
16
10
  import f$1 from 'path';
@@ -18,20 +12,26 @@ import require$$2 from 'util';
18
12
  import require$$0$1 from 'stream';
19
13
  import require$$2$1 from 'events';
20
14
  import $ from 'fs';
15
+ import c from 'picocolors';
21
16
  import { slash as slash$2, normalizeRequestId, cleanUrl } from 'vite-node/utils';
22
17
  import { ViteNodeRunner } from 'vite-node/client';
23
18
  import { SnapshotManager } from '@vitest/snapshot/manager';
24
19
  import { ViteNodeServer } from 'vite-node/server';
20
+ import { a as isNode, r as relativePath, b as removeUndefinedValues, c as isWindows } from './vendor-index.087d1af7.js';
21
+ import { g as getCoverageProvider, C as CoverageProviderMap } from './vendor-coverage.78040316.js';
25
22
  import { d as distDir, r as rootDir } from './vendor-paths.84fc7a99.js';
26
23
  import v8 from 'node:v8';
27
24
  import { fork } from 'node:child_process';
28
- import { a as groupBy, b as getEnvironmentTransformMode, c as createBirpc, A as AggregateErrorPonyfill, s as slash$1, t as toArray, i as isPrimitive, d as deepMerge, n as noop$1, e as stdout } from './vendor-index.cc463d9e.js';
25
+ import { c as createBirpc } from './vendor-index.b271ebe4.js';
26
+ import { g as groupBy, A as AggregateErrorPonyfill, s as slash$1, t as toArray, i as isPrimitive, d as deepMerge, n as noop$1, a as stdout } from './vendor-base.9c08bbd0.js';
29
27
  import { MessageChannel } from 'node:worker_threads';
30
- import { cpus, hostname } from 'node:os';
28
+ import { cpus, hostname, totalmem } from 'node:os';
31
29
  import Tinypool from 'tinypool';
32
- import { createDefer, getSafeTimers, notNullish, parseErrorStacktrace, shuffle, stringify as stringify$5, positionToOffset, lineSplitRE } from '@vitest/utils';
30
+ import { createDefer, getSafeTimers, notNullish, shuffle, inspect, positionToOffset, lineSplitRE } from '@vitest/utils';
31
+ import { isPackageExists, resolveModule } from 'local-pkg';
32
+ import { isCI } from 'std-env';
33
33
  import { performance } from 'node:perf_hooks';
34
- import { g as getFullName, h as hasFailedSnapshot } from './vendor-tasks.f9d75aed.js';
34
+ import { g as getFullName, h as hasFailedSnapshot, p as parseErrorStacktrace, T as TraceMap, b as generatedPositionFor } from './vendor-source-map.e6c1997b.js';
35
35
  import { getTests, hasFailed, getSuites, generateHash, calculateSuiteHash, someTasksAreOnly, interpretTaskModes, getTasks } from '@vitest/runner/utils';
36
36
  import { createRequire, builtinModules } from 'node:module';
37
37
  import { createHash } from 'node:crypto';
@@ -42,6 +42,7 @@ import { parse as parse$4 } from 'acorn';
42
42
  import { ancestor, simple, findNodeAround } from 'acorn-walk';
43
43
  import MagicString from 'magic-string';
44
44
  import { stripLiteral } from 'strip-literal';
45
+ import { g as getEnvPackageName } from './vendor-environments.443ecd82.js';
45
46
  import readline from 'node:readline';
46
47
  import require$$0$2 from 'readline';
47
48
 
@@ -60,15 +61,13 @@ function _mergeNamespaces(n, m) {
60
61
  return Object.freeze(n);
61
62
  }
62
63
 
63
- var version$1 = "0.33.0";
64
+ var version$1 = "0.34.0";
64
65
 
65
66
  const __dirname$1 = url.fileURLToPath(new URL(".", import.meta.url));
66
- async function ensurePackageInstalled(dependency, root, errorMessage) {
67
+ async function ensurePackageInstalled(dependency, root) {
67
68
  if (isPackageExists(dependency, { paths: [root, __dirname$1] }))
68
69
  return true;
69
70
  const promptInstall = !isCI && process.stdout.isTTY;
70
- if (errorMessage)
71
- process.stderr.write(c.red(errorMessage));
72
71
  process.stderr.write(c.red(`${c.inverse(c.red(" MISSING DEP "))} Can not find dependency '${dependency}'
73
72
 
74
73
  `));
@@ -81,7 +80,7 @@ async function ensurePackageInstalled(dependency, root, errorMessage) {
81
80
  message: c.reset(`Do you want to install ${c.green(dependency)}?`)
82
81
  });
83
82
  if (install) {
84
- await (await import('./chunk-install-pkg.23da664c.js')).installPackage(dependency, { dev: true });
83
+ await (await import('./chunk-install-pkg.dd70081b.js')).installPackage(dependency, { dev: true });
85
84
  process.stderr.write(c.yellow(`
86
85
  Package ${dependency} installed, re-run the command to start.
87
86
  `));
@@ -527,7 +526,7 @@ var isExtglob$1 = function isExtglob(str) {
527
526
  */
528
527
 
529
528
  var isExtglob = isExtglob$1;
530
- var chars$1 = { '{': '}', '(': ')', '[': ']'};
529
+ var chars = { '{': '}', '(': ')', '[': ']'};
531
530
  var strictCheck = function(str) {
532
531
  if (str[0] === '!') {
533
532
  return true;
@@ -600,7 +599,7 @@ var strictCheck = function(str) {
600
599
  if (str[index] === '\\') {
601
600
  var open = str[index + 1];
602
601
  index += 2;
603
- var close = chars$1[open];
602
+ var close = chars[open];
604
603
 
605
604
  if (close) {
606
605
  var n = str.indexOf(close, index);
@@ -632,7 +631,7 @@ var relaxedCheck = function(str) {
632
631
  if (str[index] === '\\') {
633
632
  var open = str[index + 1];
634
633
  index += 2;
635
- var close = chars$1[open];
634
+ var close = chars[open];
636
635
 
637
636
  if (close) {
638
637
  var n = str.indexOf(close, index);
@@ -7063,6 +7062,13 @@ const envsOrder = [
7063
7062
  "happy-dom",
7064
7063
  "edge-runtime"
7065
7064
  ];
7065
+ function getTransformMode(patterns, filename) {
7066
+ if (patterns.web && mm.isMatch(filename, patterns.web))
7067
+ return "web";
7068
+ if (patterns.ssr && mm.isMatch(filename, patterns.ssr))
7069
+ return "ssr";
7070
+ return void 0;
7071
+ }
7066
7072
  async function groupFilesByEnv(files) {
7067
7073
  const filesWithEnv = await Promise.all(files.map(async ([project, file]) => {
7068
7074
  var _a, _b;
@@ -7077,12 +7083,14 @@ async function groupFilesByEnv(files) {
7077
7083
  }
7078
7084
  }
7079
7085
  env || (env = project.config.environment || "node");
7086
+ const transformMode = getTransformMode(project.config.testTransformMode, file);
7080
7087
  const envOptions = JSON.parse(((_b = code.match(/@(?:vitest|jest)-environment-options\s+?(.+)/)) == null ? void 0 : _b[1]) || "null");
7081
7088
  return {
7082
7089
  file,
7083
7090
  project,
7084
7091
  environment: {
7085
7092
  name: env,
7093
+ transformMode,
7086
7094
  options: envOptions ? { [env]: envOptions } : null
7087
7095
  }
7088
7096
  };
@@ -7094,7 +7102,7 @@ function createMethodsRPC(project) {
7094
7102
  const ctx = project.ctx;
7095
7103
  return {
7096
7104
  async onWorkerExit(error, code) {
7097
- await ctx.logger.printError(error, false, "Unexpected Exit");
7105
+ await ctx.logger.printError(error, { type: "Unexpected Exit" });
7098
7106
  process.exit(code || 1);
7099
7107
  },
7100
7108
  snapshotSaved(snapshot) {
@@ -7112,12 +7120,10 @@ function createMethodsRPC(project) {
7112
7120
  const r = await project.vitenode.transformRequest(id);
7113
7121
  return r == null ? void 0 : r.map;
7114
7122
  },
7115
- fetch(id, environment) {
7116
- const transformMode = getEnvironmentTransformMode(project.config, environment);
7123
+ fetch(id, transformMode) {
7117
7124
  return project.vitenode.fetchModule(id, transformMode);
7118
7125
  },
7119
- resolveId(id, importer, environment) {
7120
- const transformMode = getEnvironmentTransformMode(project.config, environment);
7126
+ resolveId(id, importer, transformMode) {
7121
7127
  return project.vitenode.resolveId(id, importer, transformMode);
7122
7128
  },
7123
7129
  onPathsCollected(paths) {
@@ -7155,7 +7161,7 @@ function createMethodsRPC(project) {
7155
7161
  };
7156
7162
  }
7157
7163
 
7158
- const childPath = fileURLToPath(pathToFileURL(resolve$2(distDir, "./child.js")).href);
7164
+ const childPath = fileURLToPath(pathToFileURL(resolve(distDir, "./child.js")).href);
7159
7165
  function setupChildProcessChannel(project, fork2) {
7160
7166
  const rpc = createBirpc(
7161
7167
  createMethodsRPC(project),
@@ -7202,6 +7208,8 @@ function createChildProcessPool(ctx, { execArgv, env }) {
7202
7208
  const child = fork(childPath, [], {
7203
7209
  execArgv,
7204
7210
  env
7211
+ // TODO: investigate
7212
+ // serialization: 'advanced',
7205
7213
  });
7206
7214
  children.add(child);
7207
7215
  setupChildProcessChannel(project, child);
@@ -7232,7 +7240,7 @@ function createChildProcessPool(ctx, { execArgv, env }) {
7232
7240
  const files = filesByEnv[env2];
7233
7241
  if (!(files == null ? void 0 : files.length))
7234
7242
  continue;
7235
- const filesByOptions = groupBy(files, ({ project, environment }) => project.getName() + JSON.stringify(environment.options));
7243
+ const filesByOptions = groupBy(files, ({ project, environment }) => project.getName() + JSON.stringify(environment.options) + environment.transformMode);
7236
7244
  for (const option in filesByOptions) {
7237
7245
  const files2 = filesByOptions[option];
7238
7246
  if (files2 == null ? void 0 : files2.length) {
@@ -7254,8 +7262,8 @@ function createChildProcessPool(ctx, { execArgv, env }) {
7254
7262
  };
7255
7263
  }
7256
7264
 
7257
- const workerPath = pathToFileURL(resolve$2(distDir, "./worker.js")).href;
7258
- function createWorkerChannel(project) {
7265
+ const workerPath$1 = pathToFileURL(resolve(distDir, "./worker.js")).href;
7266
+ function createWorkerChannel$1(project) {
7259
7267
  const channel = new MessageChannel();
7260
7268
  const port = channel.port2;
7261
7269
  const workerPort = channel.port1;
@@ -7279,7 +7287,7 @@ function createThreadsPool(ctx, { execArgv, env }) {
7279
7287
  const maxThreads = ctx.config.maxThreads ?? threadsCount;
7280
7288
  const minThreads = ctx.config.minThreads ?? threadsCount;
7281
7289
  const options = {
7282
- filename: workerPath,
7290
+ filename: workerPath$1,
7283
7291
  // TODO: investigate further
7284
7292
  // It seems atomics introduced V8 Fatal Error https://github.com/vitest-dev/vitest/issues/1191
7285
7293
  useAtomics: ctx.config.useAtomics ?? false,
@@ -7303,7 +7311,7 @@ function createThreadsPool(ctx, { execArgv, env }) {
7303
7311
  let id = 0;
7304
7312
  async function runFiles(project, config, files, environment, invalidates = []) {
7305
7313
  ctx.state.clearFiles(project, files);
7306
- const { workerPort, port } = createWorkerChannel(project);
7314
+ const { workerPort, port } = createWorkerChannel$1(project);
7307
7315
  const workerId = ++id;
7308
7316
  const data = {
7309
7317
  port: workerPort,
@@ -7353,8 +7361,18 @@ function createThreadsPool(ctx, { execArgv, env }) {
7353
7361
  const multipleThreads = specs.filter(([project]) => !project.config.singleThread);
7354
7362
  if (multipleThreads.length) {
7355
7363
  const filesByEnv = await groupFilesByEnv(multipleThreads);
7356
- const promises = Object.values(filesByEnv).flat();
7357
- const results = await Promise.allSettled(promises.map(({ file, environment, project }) => runFiles(project, getConfig(project), [file], environment, invalidates)));
7364
+ const files = Object.values(filesByEnv).flat();
7365
+ const results = [];
7366
+ if (ctx.config.isolate) {
7367
+ results.push(...await Promise.allSettled(files.map(({ file, environment, project }) => runFiles(project, getConfig(project), [file], environment, invalidates))));
7368
+ } else {
7369
+ const grouped = groupBy(files, ({ project, environment }) => project.getName() + environment.name + JSON.stringify(environment.options));
7370
+ for (const group of Object.values(grouped)) {
7371
+ results.push(...await Promise.allSettled(group.map(({ file, environment, project }) => runFiles(project, getConfig(project), [file], environment, invalidates))));
7372
+ await new Promise((resolve2) => pool.queueSize === 0 ? resolve2() : pool.once("drain", resolve2));
7373
+ await pool.recycleWorkers();
7374
+ }
7375
+ }
7358
7376
  const errors = results.filter((r) => r.status === "rejected").map((r) => r.reason);
7359
7377
  if (errors.length > 0)
7360
7378
  throw new AggregateErrorPonyfill(errors, "Errors occurred while running tests. For more information, see serialized error.");
@@ -7369,11 +7387,11 @@ function createThreadsPool(ctx, { execArgv, env }) {
7369
7387
  if (!(files == null ? void 0 : files.length))
7370
7388
  continue;
7371
7389
  const filesByOptions = groupBy(files, ({ project, environment }) => project.getName() + JSON.stringify(environment.options));
7372
- const promises = Object.values(filesByOptions).map(async (files2) => {
7390
+ for (const files2 of Object.values(filesByOptions)) {
7391
+ await pool.recycleWorkers();
7373
7392
  const filenames = files2.map((f) => f.file);
7374
7393
  await runFiles(files2[0].project, getConfig(files2[0].project), filenames, files2[0].environment, invalidates);
7375
- });
7376
- await Promise.all(promises);
7394
+ }
7377
7395
  }
7378
7396
  }
7379
7397
  };
@@ -7460,17 +7478,130 @@ function createBrowserPool(ctx) {
7460
7478
  };
7461
7479
  }
7462
7480
 
7463
- const loaderPath = pathToFileURL(resolve$2(distDir, "./loader.js")).href;
7464
- const suppressLoaderWarningsPath = resolve$2(rootDir, "./suppress-warnings.cjs");
7481
+ const workerPath = pathToFileURL(resolve(distDir, "./vm.js")).href;
7482
+ const suppressLoaderWarningsPath$1 = resolve(rootDir, "./suppress-warnings.cjs");
7483
+ function createWorkerChannel(project) {
7484
+ const channel = new MessageChannel();
7485
+ const port = channel.port2;
7486
+ const workerPort = channel.port1;
7487
+ const rpc = createBirpc(
7488
+ createMethodsRPC(project),
7489
+ {
7490
+ eventNames: ["onCancel"],
7491
+ post(v) {
7492
+ port.postMessage(v);
7493
+ },
7494
+ on(fn) {
7495
+ port.on("message", fn);
7496
+ }
7497
+ }
7498
+ );
7499
+ project.ctx.onCancel((reason) => rpc.onCancel(reason));
7500
+ return { workerPort, port };
7501
+ }
7502
+ function createVmThreadsPool(ctx, { execArgv, env }) {
7503
+ const threadsCount = ctx.config.watch ? Math.max(Math.floor(cpus().length / 2), 1) : Math.max(cpus().length - 1, 1);
7504
+ const maxThreads = ctx.config.maxThreads ?? threadsCount;
7505
+ const minThreads = ctx.config.minThreads ?? threadsCount;
7506
+ const options = {
7507
+ filename: workerPath,
7508
+ // TODO: investigate further
7509
+ // It seems atomics introduced V8 Fatal Error https://github.com/vitest-dev/vitest/issues/1191
7510
+ useAtomics: ctx.config.useAtomics ?? false,
7511
+ maxThreads,
7512
+ minThreads,
7513
+ env,
7514
+ execArgv: [
7515
+ "--experimental-import-meta-resolve",
7516
+ "--experimental-vm-modules",
7517
+ "--require",
7518
+ suppressLoaderWarningsPath$1,
7519
+ ...execArgv
7520
+ ],
7521
+ terminateTimeout: ctx.config.teardownTimeout
7522
+ };
7523
+ if (ctx.config.singleThread) {
7524
+ options.concurrentTasksPerWorker = 1;
7525
+ options.maxThreads = 1;
7526
+ options.minThreads = 1;
7527
+ }
7528
+ const pool = new Tinypool(options);
7529
+ const runWithFiles = (name) => {
7530
+ let id = 0;
7531
+ async function runFiles(project, config, files, environment, invalidates = []) {
7532
+ ctx.state.clearFiles(project, files);
7533
+ const { workerPort, port } = createWorkerChannel(project);
7534
+ const workerId = ++id;
7535
+ const data = {
7536
+ port: workerPort,
7537
+ config,
7538
+ files,
7539
+ invalidates,
7540
+ environment,
7541
+ workerId
7542
+ };
7543
+ try {
7544
+ await pool.run(data, { transferList: [workerPort], name });
7545
+ } catch (error) {
7546
+ if (error instanceof Error && /Failed to terminate worker/.test(error.message))
7547
+ ctx.state.addProcessTimeoutCause(`Failed to terminate worker while running ${files.join(", ")}.`);
7548
+ else if (ctx.isCancelling && error instanceof Error && /The task has been cancelled/.test(error.message))
7549
+ ctx.state.cancelFiles(files, ctx.config.root);
7550
+ else
7551
+ throw error;
7552
+ } finally {
7553
+ port.close();
7554
+ workerPort.close();
7555
+ }
7556
+ }
7557
+ const Sequencer = ctx.config.sequence.sequencer;
7558
+ const sequencer = new Sequencer(ctx);
7559
+ return async (specs, invalidates) => {
7560
+ const configs = /* @__PURE__ */ new Map();
7561
+ const getConfig = (project) => {
7562
+ if (configs.has(project))
7563
+ return configs.get(project);
7564
+ const config = project.getSerializableConfig();
7565
+ configs.set(project, config);
7566
+ return config;
7567
+ };
7568
+ const { shard } = ctx.config;
7569
+ if (shard)
7570
+ specs = await sequencer.shard(specs);
7571
+ specs = await sequencer.sort(specs);
7572
+ const filesByEnv = await groupFilesByEnv(specs);
7573
+ const promises = Object.values(filesByEnv).flat();
7574
+ const results = await Promise.allSettled(promises.map(({ file, environment, project }) => runFiles(project, getConfig(project), [file], environment, invalidates)));
7575
+ const errors = results.filter((r) => r.status === "rejected").map((r) => r.reason);
7576
+ if (errors.length > 0)
7577
+ throw new AggregateErrorPonyfill(errors, "Errors occurred while running tests. For more information, see serialized error.");
7578
+ };
7579
+ };
7580
+ return {
7581
+ runTests: runWithFiles("run"),
7582
+ close: async () => {
7583
+ var _a;
7584
+ const nodeVersion = Number((_a = process.version.match(/v(\d+)\.(\d+)/)) == null ? void 0 : _a[0].slice(1));
7585
+ if (nodeVersion >= 16.17)
7586
+ await pool.destroy();
7587
+ }
7588
+ };
7589
+ }
7590
+
7591
+ const loaderPath = pathToFileURL(resolve(distDir, "./loader.js")).href;
7592
+ const suppressLoaderWarningsPath = resolve(rootDir, "./suppress-warnings.cjs");
7465
7593
  function createPool(ctx) {
7466
7594
  const pools = {
7467
7595
  child_process: null,
7468
7596
  threads: null,
7469
- browser: null
7597
+ browser: null,
7598
+ experimentalVmThreads: null
7470
7599
  };
7471
7600
  function getDefaultPoolName(project) {
7472
7601
  if (project.config.browser.enabled)
7473
7602
  return "browser";
7603
+ if (project.config.experimentalVmThreads)
7604
+ return "experimentalVmThreads";
7474
7605
  if (project.config.threads)
7475
7606
  return "threads";
7476
7607
  return "child_process";
@@ -7496,7 +7627,8 @@ function createPool(ctx) {
7496
7627
  "--require",
7497
7628
  suppressLoaderWarningsPath,
7498
7629
  "--experimental-loader",
7499
- loaderPath
7630
+ loaderPath,
7631
+ ...conditions
7500
7632
  ] : [
7501
7633
  ...execArgv,
7502
7634
  ...conditions
@@ -7513,10 +7645,13 @@ function createPool(ctx) {
7513
7645
  const filesByPool = {
7514
7646
  child_process: [],
7515
7647
  threads: [],
7516
- browser: []
7648
+ browser: [],
7649
+ experimentalVmThreads: []
7517
7650
  };
7518
7651
  for (const spec of files) {
7519
7652
  const pool = getPoolName(spec);
7653
+ if (!(pool in filesByPool))
7654
+ throw new Error(`Unknown pool name "${pool}" for ${spec[1]}. Available pools: ${Object.keys(filesByPool).join(", ")}`);
7520
7655
  filesByPool[pool].push(spec);
7521
7656
  }
7522
7657
  await Promise.all(Object.entries(filesByPool).map(([pool, files2]) => {
@@ -7526,6 +7661,10 @@ function createPool(ctx) {
7526
7661
  pools.browser ?? (pools.browser = createBrowserPool(ctx));
7527
7662
  return pools.browser.runTests(files2, invalidate);
7528
7663
  }
7664
+ if (pool === "experimentalVmThreads") {
7665
+ pools.experimentalVmThreads ?? (pools.experimentalVmThreads = createVmThreadsPool(ctx, options));
7666
+ return pools.experimentalVmThreads.runTests(files2, invalidate);
7667
+ }
7529
7668
  if (pool === "threads") {
7530
7669
  pools.threads ?? (pools.threads = createThreadsPool(ctx, options));
7531
7670
  return pools.threads.runTests(files2, invalidate);
@@ -8037,8 +8176,13 @@ ${c.cyan(c.inverse(c.bold(" BENCH ")))} ${c.cyan("Summary")}
8037
8176
  for (const task of tasks) {
8038
8177
  (_b = (_a2 = task.result) == null ? void 0 : _a2.errors) == null ? void 0 : _b.forEach((error) => {
8039
8178
  const errorItem = (error == null ? void 0 : error.stackStr) && errorsQueue.find((i) => {
8040
- var _a3;
8041
- return ((_a3 = i[0]) == null ? void 0 : _a3.stackStr) === error.stackStr;
8179
+ var _a3, _b2, _c2, _d;
8180
+ const hasStr = ((_a3 = i[0]) == null ? void 0 : _a3.stackStr) === error.stackStr;
8181
+ if (!hasStr)
8182
+ return false;
8183
+ const currentProjectName = (task == null ? void 0 : task.projectName) || ((_b2 = task.file) == null ? void 0 : _b2.projectName);
8184
+ const projectName = ((_c2 = i[1][0]) == null ? void 0 : _c2.projectName) || ((_d = i[1][0].file) == null ? void 0 : _d.projectName);
8185
+ return projectName === currentProjectName;
8042
8186
  });
8043
8187
  if (errorItem)
8044
8188
  errorItem[1].push(task);
@@ -8055,7 +8199,8 @@ ${c.cyan(c.inverse(c.bold(" BENCH ")))} ${c.cyan("Summary")}
8055
8199
  name = `${name} ${c.dim(`[ ${this.relative(filepath)} ]`)}`;
8056
8200
  this.ctx.logger.error(`${c.red(c.bold(c.inverse(" FAIL ")))} ${formatProjectName(projectName)}${name}`);
8057
8201
  }
8058
- await this.ctx.logger.printError(error);
8202
+ const project = this.ctx.getProjectByTaskId(tasks2[0].id);
8203
+ await this.ctx.logger.printError(error, { project });
8059
8204
  errorDivider();
8060
8205
  await Promise.resolve();
8061
8206
  }
@@ -8063,7 +8208,7 @@ ${c.cyan(c.inverse(c.bold(" BENCH ")))} ${c.cyan("Summary")}
8063
8208
  registerUnhandledRejection() {
8064
8209
  process.on("unhandledRejection", async (err) => {
8065
8210
  process.exitCode = 1;
8066
- await this.ctx.logger.printError(err, true, "Unhandled Rejection");
8211
+ await this.ctx.logger.printError(err, { fullStack: true, type: "Unhandled Rejection" });
8067
8212
  this.ctx.logger.error("\n\n");
8068
8213
  process.exit(1);
8069
8214
  });
@@ -9415,7 +9560,7 @@ let JsonReporter$1 = class JsonReporter {
9415
9560
  async writeReport(report) {
9416
9561
  const outputFile = getOutputFile(this.ctx.config, "json");
9417
9562
  if (outputFile) {
9418
- const reportFile = resolve$2(this.ctx.config.root, outputFile);
9563
+ const reportFile = resolve(this.ctx.config.root, outputFile);
9419
9564
  const outputDirectory = dirname(reportFile);
9420
9565
  if (!existsSync(outputDirectory))
9421
9566
  await promises.mkdir(outputDirectory, { recursive: true });
@@ -9430,7 +9575,10 @@ let JsonReporter$1 = class JsonReporter {
9430
9575
  const error = (_b = (_a = test.result) == null ? void 0 : _a.errors) == null ? void 0 : _b[0];
9431
9576
  if (!error)
9432
9577
  return;
9433
- const stack = parseErrorStacktrace(error);
9578
+ const project = this.ctx.getProjectByTaskId(test.id);
9579
+ const stack = parseErrorStacktrace(error, {
9580
+ getSourceMap: (file) => project.getBrowserSourceMapModuleById(file)
9581
+ });
9434
9582
  const frame = stack[0];
9435
9583
  if (!frame)
9436
9584
  return;
@@ -9529,10 +9677,13 @@ class TapReporter {
9529
9677
  this.logger.log("}");
9530
9678
  } else {
9531
9679
  this.logger.log(`${ok} ${id} - ${tapString(task.name)}${comment}`);
9680
+ const project = this.ctx.getProjectByTaskId(task.id);
9532
9681
  if (((_b = task.result) == null ? void 0 : _b.state) === "fail" && task.result.errors) {
9533
9682
  this.logger.indent();
9534
9683
  task.result.errors.forEach((error) => {
9535
- const stacks = parseErrorStacktrace(error);
9684
+ const stacks = parseErrorStacktrace(error, {
9685
+ getSourceMap: (file) => project.getBrowserSourceMapModuleById(file)
9686
+ });
9536
9687
  const stack = stacks[0];
9537
9688
  this.logger.log("---");
9538
9689
  this.logger.log("error:");
@@ -9606,7 +9757,7 @@ class JUnitReporter {
9606
9757
  this.ctx = ctx;
9607
9758
  const outputFile = getOutputFile(this.ctx.config, "junit");
9608
9759
  if (outputFile) {
9609
- this.reportFile = resolve$2(this.ctx.config.root, outputFile);
9760
+ this.reportFile = resolve(this.ctx.config.root, outputFile);
9610
9761
  const outputDirectory = dirname(this.reportFile);
9611
9762
  if (!existsSync(outputDirectory))
9612
9763
  await promises.mkdir(outputDirectory, { recursive: true });
@@ -9638,11 +9789,14 @@ class JUnitReporter {
9638
9789
  this.logger.unindent();
9639
9790
  await this.logger.log(`</${name}>`);
9640
9791
  }
9641
- async writeErrorDetails(error) {
9792
+ async writeErrorDetails(task, error) {
9642
9793
  const errorName = error.name ?? error.nameStr ?? "Unknown Error";
9643
9794
  const errorDetails = `${errorName}: ${error.message}`;
9644
9795
  await this.baseLog(escapeXML(errorDetails));
9645
- const stack = parseErrorStacktrace(error);
9796
+ const project = this.ctx.getProjectByTaskId(task.id);
9797
+ const stack = parseErrorStacktrace(error, {
9798
+ getSourceMap: (file) => project.getBrowserSourceMapModuleById(file)
9799
+ });
9646
9800
  for (const frame of stack) {
9647
9801
  const path = relative(this.ctx.config.root, frame.file);
9648
9802
  await this.baseLog(escapeXML(` ${F_POINTER} ${[frame.method, `${path}:${frame.line}:${frame.column}`].filter(Boolean).join(" ")}`));
@@ -9665,7 +9819,7 @@ class JUnitReporter {
9665
9819
  async writeTasks(tasks, filename) {
9666
9820
  for (const task of tasks) {
9667
9821
  await this.writeElement("testcase", {
9668
- classname: filename,
9822
+ classname: process.env.VITEST_JUNIT_CLASSNAME ?? filename,
9669
9823
  name: task.name,
9670
9824
  time: getDuration(task)
9671
9825
  }, async () => {
@@ -9683,7 +9837,7 @@ class JUnitReporter {
9683
9837
  }, async () => {
9684
9838
  if (!error)
9685
9839
  return;
9686
- await this.writeErrorDetails(error);
9840
+ await this.writeErrorDetails(task, error);
9687
9841
  });
9688
9842
  }
9689
9843
  }
@@ -9835,7 +9989,7 @@ class JsonReporter {
9835
9989
  async writeReport(report) {
9836
9990
  const outputFile = getOutputFile(this.ctx.config.benchmark, "json");
9837
9991
  if (outputFile) {
9838
- const reportFile = resolve$2(this.ctx.config.root, outputFile);
9992
+ const reportFile = resolve(this.ctx.config.root, outputFile);
9839
9993
  const outputDirectory = dirname(reportFile);
9840
9994
  if (!existsSync(outputDirectory))
9841
9995
  await promises.mkdir(outputDirectory, { recursive: true });
@@ -10134,7 +10288,6 @@ function isAggregateError(err) {
10134
10288
  class StateManager {
10135
10289
  filesMap = /* @__PURE__ */ new Map();
10136
10290
  pathsSet = /* @__PURE__ */ new Set();
10137
- collectingPromise = void 0;
10138
10291
  browserTestPromises = /* @__PURE__ */ new Map();
10139
10292
  idMap = /* @__PURE__ */ new Map();
10140
10293
  taskFileMap = /* @__PURE__ */ new WeakMap();
@@ -10192,7 +10345,9 @@ class StateManager {
10192
10345
  this.updateId(file);
10193
10346
  });
10194
10347
  }
10195
- clearFiles(project, paths = []) {
10348
+ // this file is reused by ws-client, and shoult not rely on heavy dependencies like workspace
10349
+ clearFiles(_project, paths = []) {
10350
+ const project = _project;
10196
10351
  paths.forEach((path) => {
10197
10352
  const files = this.filesMap.get(path);
10198
10353
  if (!files)
@@ -10267,6 +10422,9 @@ const defaultCoverageExcludes = [
10267
10422
  "dist/**",
10268
10423
  "packages/*/test?(s)/**",
10269
10424
  "**/*.d.ts",
10425
+ "**/virtual:*",
10426
+ "**/__x00__*",
10427
+ "**/\0*",
10270
10428
  "cypress/**",
10271
10429
  "test?(s)/**",
10272
10430
  "test?(-*).?(c|m)[jt]s?(x)",
@@ -10282,10 +10440,8 @@ const coverageConfigDefaults = {
10282
10440
  cleanOnRerun: true,
10283
10441
  reportsDirectory: "./coverage",
10284
10442
  exclude: defaultCoverageExcludes,
10285
- reportOnFailure: true,
10443
+ reportOnFailure: false,
10286
10444
  reporter: [["text", {}], ["html", {}], ["clover", {}], ["json", {}]],
10287
- // default extensions used by c8, plus '.vue' and '.svelte'
10288
- // see https://github.com/istanbuljs/schema/blob/master/default-extension.js
10289
10445
  extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte"]
10290
10446
  };
10291
10447
  const fakeTimersDefaults = {
@@ -10345,6 +10501,66 @@ const config = {
10345
10501
  };
10346
10502
  const configDefaults = Object.freeze(config);
10347
10503
 
10504
+ function getDefaultThreadsCount(config) {
10505
+ return config.watch ? Math.max(Math.floor(cpus().length / 2), 1) : Math.max(cpus().length - 1, 1);
10506
+ }
10507
+ function getWorkerMemoryLimit(config) {
10508
+ if (config.experimentalVmWorkerMemoryLimit)
10509
+ return config.experimentalVmWorkerMemoryLimit;
10510
+ return 1 / (config.maxThreads ?? getDefaultThreadsCount(config));
10511
+ }
10512
+ function stringToBytes(input, percentageReference) {
10513
+ if (input === null || input === void 0)
10514
+ return input;
10515
+ if (typeof input === "string") {
10516
+ if (Number.isNaN(Number.parseFloat(input.slice(-1)))) {
10517
+ let [, numericString, trailingChars] = input.match(/(.*?)([^0-9.-]+)$/i) || [];
10518
+ if (trailingChars && numericString) {
10519
+ const numericValue = Number.parseFloat(numericString);
10520
+ trailingChars = trailingChars.toLowerCase();
10521
+ switch (trailingChars) {
10522
+ case "%":
10523
+ input = numericValue / 100;
10524
+ break;
10525
+ case "kb":
10526
+ case "k":
10527
+ return numericValue * 1e3;
10528
+ case "kib":
10529
+ return numericValue * 1024;
10530
+ case "mb":
10531
+ case "m":
10532
+ return numericValue * 1e3 * 1e3;
10533
+ case "mib":
10534
+ return numericValue * 1024 * 1024;
10535
+ case "gb":
10536
+ case "g":
10537
+ return numericValue * 1e3 * 1e3 * 1e3;
10538
+ case "gib":
10539
+ return numericValue * 1024 * 1024 * 1024;
10540
+ }
10541
+ }
10542
+ } else {
10543
+ input = Number.parseFloat(input);
10544
+ }
10545
+ }
10546
+ if (typeof input === "number") {
10547
+ if (input <= 1 && input > 0) {
10548
+ if (percentageReference) {
10549
+ return Math.floor(input * percentageReference);
10550
+ } else {
10551
+ throw new Error(
10552
+ "For a percentage based memory limit a percentageReference must be supplied"
10553
+ );
10554
+ }
10555
+ } else if (input > 1) {
10556
+ return Math.floor(input);
10557
+ } else {
10558
+ throw new Error('Unexpected numerical input for "experimentalVmWorkerMemoryLimit"');
10559
+ }
10560
+ }
10561
+ return null;
10562
+ }
10563
+
10348
10564
  class FilesStatsCache {
10349
10565
  cache = /* @__PURE__ */ new Map();
10350
10566
  getStats(key) {
@@ -10383,7 +10599,7 @@ class ResultsCache {
10383
10599
  setConfig(root, config) {
10384
10600
  this.root = root;
10385
10601
  if (config)
10386
- this.cachePath = resolve$2(config.dir, "results.json");
10602
+ this.cachePath = resolve(config.dir, "results.json");
10387
10603
  }
10388
10604
  getResults(key) {
10389
10605
  return this.cache.get(key);
@@ -10450,12 +10666,12 @@ class VitestCache {
10450
10666
  return this.stats.getStats(key);
10451
10667
  }
10452
10668
  static resolveCacheDir(root, dir) {
10453
- return resolve$2(root, slash$1(dir || "node_modules/.vitest"));
10669
+ return resolve(root, slash$1(dir || "node_modules/.vitest"));
10454
10670
  }
10455
10671
  static async clearCache(options) {
10456
10672
  var _a, _b;
10457
- const root = resolve$2(options.root || process.cwd());
10458
- const configPath = options.config === false ? false : options.config ? resolve$2(root, options.config) : await findUp(configFiles, { cwd: root });
10673
+ const root = resolve(options.root || process.cwd());
10674
+ const configPath = options.config === false ? false : options.config ? resolve(root, options.config) : await findUp(configFiles, { cwd: root });
10459
10675
  const config = configPath ? (_a = await loadConfigFromFile({ command: "serve", mode: "test" }, configPath)) == null ? void 0 : _a.config : void 0;
10460
10676
  const cache = (_b = config == null ? void 0 : config.test) == null ? void 0 : _b.cache;
10461
10677
  if (cache === false)
@@ -10483,7 +10699,7 @@ class BaseSequencer {
10483
10699
  const shardStart = shardSize * (index - 1);
10484
10700
  const shardEnd = shardSize * index;
10485
10701
  return [...files].map((spec) => {
10486
- const fullPath = resolve$2(slash$2(config.root), slash$2(spec[1]));
10702
+ const fullPath = resolve(slash$2(config.root), slash$2(spec[1]));
10487
10703
  const specPath = fullPath == null ? void 0 : fullPath.slice(config.root.length);
10488
10704
  return {
10489
10705
  spec,
@@ -10557,7 +10773,7 @@ function resolveApiServerConfig(options) {
10557
10773
  return api;
10558
10774
  }
10559
10775
  function resolveConfig(mode, options, viteConfig) {
10560
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
10776
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
10561
10777
  if (options.dom) {
10562
10778
  if (((_a = viteConfig.test) == null ? void 0 : _a.environment) != null && viteConfig.test.environment !== "happy-dom") {
10563
10779
  console.warn(
@@ -10597,21 +10813,12 @@ function resolveConfig(mode, options, viteConfig) {
10597
10813
  throw new Error(`You cannot use ${inspectOption} without "threads: false" or "singleThread: true"`);
10598
10814
  }
10599
10815
  }
10600
- if (resolved.coverage.provider === "c8" && resolved.coverage.enabled && isBrowserEnabled(resolved))
10601
- throw new Error("@vitest/coverage-c8 does not work with --browser. Use @vitest/coverage-istanbul instead");
10816
+ if (resolved.coverage.provider === "c8")
10817
+ throw new Error('"coverage.provider: c8" is not supported anymore. Use "coverage.provider: v8" instead');
10602
10818
  if (resolved.coverage.provider === "v8" && resolved.coverage.enabled && isBrowserEnabled(resolved))
10603
10819
  throw new Error("@vitest/coverage-v8 does not work with --browser. Use @vitest/coverage-istanbul instead");
10604
- resolved.deps = resolved.deps || {};
10605
- if (resolved.deps.inline !== true) {
10606
- const ssrOptions = viteConfig.ssr;
10607
- if ((ssrOptions == null ? void 0 : ssrOptions.noExternal) === true && resolved.deps.inline == null) {
10608
- resolved.deps.inline = true;
10609
- } else {
10610
- (_b = resolved.deps).inline ?? (_b.inline = []);
10611
- resolved.deps.inline.push(...extraInlineDeps);
10612
- }
10613
- }
10614
- (_c = resolved.deps).moduleDirectories ?? (_c.moduleDirectories = ["/node_modules/"]);
10820
+ resolved.deps ?? (resolved.deps = {});
10821
+ (_b = resolved.deps).moduleDirectories ?? (_b.moduleDirectories = []);
10615
10822
  resolved.deps.moduleDirectories = resolved.deps.moduleDirectories.map((dir) => {
10616
10823
  if (!dir.startsWith("/"))
10617
10824
  dir = `/${dir}`;
@@ -10619,10 +10826,49 @@ function resolveConfig(mode, options, viteConfig) {
10619
10826
  dir += "/";
10620
10827
  return normalize(dir);
10621
10828
  });
10829
+ if (!resolved.deps.moduleDirectories.includes("/node_modules/"))
10830
+ resolved.deps.moduleDirectories.push("/node_modules/");
10831
+ resolved.server ?? (resolved.server = {});
10832
+ (_c = resolved.server).deps ?? (_c.deps = {});
10833
+ const deprecatedDepsOptions = ["inline", "external", "fallbackCJS"];
10834
+ deprecatedDepsOptions.forEach((option) => {
10835
+ if (resolved.deps[option] === void 0)
10836
+ return;
10837
+ if (option === "fallbackCJS") {
10838
+ console.warn(c.yellow(`${c.inverse(c.yellow(" Vitest "))} "deps.${option}" is deprecated. Use "server.deps.${option}" instead`));
10839
+ } else {
10840
+ const transformMode = resolved.environment === "happy-dom" || resolved.environment === "jsdom" ? "web" : "ssr";
10841
+ console.warn(
10842
+ c.yellow(
10843
+ `${c.inverse(c.yellow(" Vitest "))} "deps.${option}" is deprecated. If you rely on vite-node directly, use "server.deps.${option}" instead. Otherwise, consider using "deps.optimizer.${transformMode}.${option === "external" ? "exclude" : "include"}"`
10844
+ )
10845
+ );
10846
+ }
10847
+ if (resolved.server.deps[option] === void 0)
10848
+ resolved.server.deps[option] = resolved.deps[option];
10849
+ });
10850
+ if (resolved.server.deps.inline !== true) {
10851
+ const ssrOptions = viteConfig.ssr;
10852
+ if ((ssrOptions == null ? void 0 : ssrOptions.noExternal) === true && resolved.server.deps.inline == null) {
10853
+ resolved.server.deps.inline = true;
10854
+ } else {
10855
+ (_d = resolved.server.deps).inline ?? (_d.inline = []);
10856
+ resolved.server.deps.inline.push(...extraInlineDeps);
10857
+ }
10858
+ }
10859
+ (_e = resolved.server.deps).moduleDirectories ?? (_e.moduleDirectories = []);
10860
+ resolved.server.deps.moduleDirectories.push(...resolved.deps.moduleDirectories);
10622
10861
  if (resolved.runner) {
10623
- resolved.runner = resolveModule(resolved.runner, { paths: [resolved.root] }) ?? resolve$2(resolved.root, resolved.runner);
10862
+ resolved.runner = resolveModule(resolved.runner, { paths: [resolved.root] }) ?? resolve(resolved.root, resolved.runner);
10863
+ }
10864
+ if (resolved.deps.registerNodeLoader) {
10865
+ const transformMode = resolved.environment === "happy-dom" || resolved.environment === "jsdom" ? "web" : "ssr";
10866
+ console.warn(
10867
+ c.yellow(
10868
+ `${c.inverse(c.yellow(" Vitest "))} "deps.registerNodeLoader" is deprecated.If you rely on aliases inside external packages, use "deps.optimizer.${transformMode}.include" instead.`
10869
+ )
10870
+ );
10624
10871
  }
10625
- (_d = resolved.deps).registerNodeLoader ?? (_d.registerNodeLoader = false);
10626
10872
  resolved.testNamePattern = resolved.testNamePattern ? resolved.testNamePattern instanceof RegExp ? resolved.testNamePattern : new RegExp(resolved.testNamePattern) : void 0;
10627
10873
  const UPDATE_SNAPSHOT = resolved.update || process.env.UPDATE_SNAPSHOT;
10628
10874
  resolved.snapshotOptions = {
@@ -10632,6 +10878,10 @@ function resolveConfig(mode, options, viteConfig) {
10632
10878
  // resolved inside the worker
10633
10879
  snapshotEnvironment: null
10634
10880
  };
10881
+ resolved.experimentalVmWorkerMemoryLimit = stringToBytes(
10882
+ getWorkerMemoryLimit(resolved),
10883
+ totalmem()
10884
+ );
10635
10885
  if (options.resolveSnapshotPath)
10636
10886
  delete resolved.resolveSnapshotPath;
10637
10887
  if (process.env.VITEST_MAX_THREADS)
@@ -10661,7 +10911,7 @@ function resolveConfig(mode, options, viteConfig) {
10661
10911
  }
10662
10912
  resolved.setupFiles = toArray(resolved.setupFiles || []).map(
10663
10913
  (file) => normalize(
10664
- resolveModule(file, { paths: [resolved.root] }) ?? resolve$2(resolved.root, file)
10914
+ resolveModule(file, { paths: [resolved.root] }) ?? resolve(resolved.root, file)
10665
10915
  )
10666
10916
  );
10667
10917
  resolved.coverage.exclude.push(...resolved.setupFiles.map((file) => relative(resolved.root, file)));
@@ -10671,11 +10921,11 @@ function resolveConfig(mode, options, viteConfig) {
10671
10921
  ];
10672
10922
  resolved.api = resolveApiServerConfig(options);
10673
10923
  if (options.related)
10674
- resolved.related = toArray(options.related).map((file) => resolve$2(resolved.root, file));
10924
+ resolved.related = toArray(options.related).map((file) => resolve(resolved.root, file));
10675
10925
  if (mode !== "benchmark") {
10676
10926
  const cliReporters = toArray(resolved.reporter || []).map((reporter) => {
10677
10927
  if (/^\.\.?\//.test(reporter))
10678
- return resolve$2(process.cwd(), reporter);
10928
+ return resolve(process.cwd(), reporter);
10679
10929
  return reporter;
10680
10930
  });
10681
10931
  const reporters = cliReporters.length ? cliReporters : resolved.reporters;
@@ -10687,35 +10937,36 @@ function resolveConfig(mode, options, viteConfig) {
10687
10937
  resolved.passWithNoTests ?? (resolved.passWithNoTests = true);
10688
10938
  resolved.css ?? (resolved.css = {});
10689
10939
  if (typeof resolved.css === "object") {
10690
- (_e = resolved.css).modules ?? (_e.modules = {});
10691
- (_f = resolved.css.modules).classNameStrategy ?? (_f.classNameStrategy = "stable");
10940
+ (_f = resolved.css).modules ?? (_f.modules = {});
10941
+ (_g = resolved.css.modules).classNameStrategy ?? (_g.classNameStrategy = "stable");
10692
10942
  }
10693
10943
  resolved.cache ?? (resolved.cache = { dir: "" });
10694
10944
  if (resolved.cache)
10695
10945
  resolved.cache.dir = VitestCache.resolveCacheDir(resolved.root, resolved.cache.dir);
10696
10946
  resolved.sequence ?? (resolved.sequence = {});
10697
- if (!((_g = resolved.sequence) == null ? void 0 : _g.sequencer)) {
10947
+ if (!((_h = resolved.sequence) == null ? void 0 : _h.sequencer)) {
10698
10948
  resolved.sequence.sequencer = resolved.sequence.shuffle ? RandomSequencer : BaseSequencer;
10699
10949
  }
10700
- (_h = resolved.sequence).hooks ?? (_h.hooks = "parallel");
10950
+ (_i = resolved.sequence).hooks ?? (_i.hooks = "parallel");
10701
10951
  if (resolved.sequence.sequencer === RandomSequencer)
10702
- (_i = resolved.sequence).seed ?? (_i.seed = Date.now());
10952
+ (_j = resolved.sequence).seed ?? (_j.seed = Date.now());
10703
10953
  resolved.typecheck = {
10704
10954
  ...configDefaults.typecheck,
10705
10955
  ...resolved.typecheck
10706
10956
  };
10707
- resolved.environmentMatchGlobs = (resolved.environmentMatchGlobs || []).map((i) => [resolve$2(resolved.root, i[0]), i[1]]);
10957
+ resolved.environmentMatchGlobs = (resolved.environmentMatchGlobs || []).map((i) => [resolve(resolved.root, i[0]), i[1]]);
10708
10958
  if (mode === "typecheck") {
10709
10959
  resolved.include = resolved.typecheck.include;
10710
10960
  resolved.exclude = resolved.typecheck.exclude;
10711
10961
  }
10712
10962
  resolved.browser ?? (resolved.browser = {});
10713
- (_j = resolved.browser).enabled ?? (_j.enabled = false);
10714
- (_k = resolved.browser).headless ?? (_k.headless = isCI);
10715
- (_l = resolved.browser).slowHijackESM ?? (_l.slowHijackESM = true);
10963
+ (_k = resolved.browser).enabled ?? (_k.enabled = false);
10964
+ (_l = resolved.browser).headless ?? (_l.headless = isCI);
10965
+ (_m = resolved.browser).slowHijackESM ?? (_m.slowHijackESM = true);
10716
10966
  resolved.browser.api = resolveApiServerConfig(resolved.browser) || {
10717
10967
  port: defaultBrowserPort
10718
10968
  };
10969
+ resolved.testTransformMode ?? (resolved.testTransformMode = {});
10719
10970
  return resolved;
10720
10971
  }
10721
10972
  function isBrowserEnabled(config) {
@@ -10725,7 +10976,7 @@ function isBrowserEnabled(config) {
10725
10976
  return ((_b = config.poolMatchGlobs) == null ? void 0 : _b.length) && config.poolMatchGlobs.some(([, pool]) => pool === "browser");
10726
10977
  }
10727
10978
 
10728
- const ESC = '\u001B[';
10979
+ const ESC$1 = '\u001B[';
10729
10980
  const OSC = '\u001B]';
10730
10981
  const BEL = '\u0007';
10731
10982
  const SEP = ';';
@@ -10739,10 +10990,10 @@ ansiEscapes.cursorTo = (x, y) => {
10739
10990
  }
10740
10991
 
10741
10992
  if (typeof y !== 'number') {
10742
- return ESC + (x + 1) + 'G';
10993
+ return ESC$1 + (x + 1) + 'G';
10743
10994
  }
10744
10995
 
10745
- return ESC + (y + 1) + ';' + (x + 1) + 'H';
10996
+ return ESC$1 + (y + 1) + ';' + (x + 1) + 'H';
10746
10997
  };
10747
10998
 
10748
10999
  ansiEscapes.cursorMove = (x, y) => {
@@ -10753,33 +11004,33 @@ ansiEscapes.cursorMove = (x, y) => {
10753
11004
  let returnValue = '';
10754
11005
 
10755
11006
  if (x < 0) {
10756
- returnValue += ESC + (-x) + 'D';
11007
+ returnValue += ESC$1 + (-x) + 'D';
10757
11008
  } else if (x > 0) {
10758
- returnValue += ESC + x + 'C';
11009
+ returnValue += ESC$1 + x + 'C';
10759
11010
  }
10760
11011
 
10761
11012
  if (y < 0) {
10762
- returnValue += ESC + (-y) + 'A';
11013
+ returnValue += ESC$1 + (-y) + 'A';
10763
11014
  } else if (y > 0) {
10764
- returnValue += ESC + y + 'B';
11015
+ returnValue += ESC$1 + y + 'B';
10765
11016
  }
10766
11017
 
10767
11018
  return returnValue;
10768
11019
  };
10769
11020
 
10770
- ansiEscapes.cursorUp = (count = 1) => ESC + count + 'A';
10771
- ansiEscapes.cursorDown = (count = 1) => ESC + count + 'B';
10772
- ansiEscapes.cursorForward = (count = 1) => ESC + count + 'C';
10773
- ansiEscapes.cursorBackward = (count = 1) => ESC + count + 'D';
11021
+ ansiEscapes.cursorUp = (count = 1) => ESC$1 + count + 'A';
11022
+ ansiEscapes.cursorDown = (count = 1) => ESC$1 + count + 'B';
11023
+ ansiEscapes.cursorForward = (count = 1) => ESC$1 + count + 'C';
11024
+ ansiEscapes.cursorBackward = (count = 1) => ESC$1 + count + 'D';
10774
11025
 
10775
- ansiEscapes.cursorLeft = ESC + 'G';
10776
- ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC + 's';
10777
- ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC + 'u';
10778
- ansiEscapes.cursorGetPosition = ESC + '6n';
10779
- ansiEscapes.cursorNextLine = ESC + 'E';
10780
- ansiEscapes.cursorPrevLine = ESC + 'F';
10781
- ansiEscapes.cursorHide = ESC + '?25l';
10782
- ansiEscapes.cursorShow = ESC + '?25h';
11026
+ ansiEscapes.cursorLeft = ESC$1 + 'G';
11027
+ ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC$1 + 's';
11028
+ ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC$1 + 'u';
11029
+ ansiEscapes.cursorGetPosition = ESC$1 + '6n';
11030
+ ansiEscapes.cursorNextLine = ESC$1 + 'E';
11031
+ ansiEscapes.cursorPrevLine = ESC$1 + 'F';
11032
+ ansiEscapes.cursorHide = ESC$1 + '?25l';
11033
+ ansiEscapes.cursorShow = ESC$1 + '?25h';
10783
11034
 
10784
11035
  ansiEscapes.eraseLines = count => {
10785
11036
  let clear = '';
@@ -10795,24 +11046,24 @@ ansiEscapes.eraseLines = count => {
10795
11046
  return clear;
10796
11047
  };
10797
11048
 
10798
- ansiEscapes.eraseEndLine = ESC + 'K';
10799
- ansiEscapes.eraseStartLine = ESC + '1K';
10800
- ansiEscapes.eraseLine = ESC + '2K';
10801
- ansiEscapes.eraseDown = ESC + 'J';
10802
- ansiEscapes.eraseUp = ESC + '1J';
10803
- ansiEscapes.eraseScreen = ESC + '2J';
10804
- ansiEscapes.scrollUp = ESC + 'S';
10805
- ansiEscapes.scrollDown = ESC + 'T';
11049
+ ansiEscapes.eraseEndLine = ESC$1 + 'K';
11050
+ ansiEscapes.eraseStartLine = ESC$1 + '1K';
11051
+ ansiEscapes.eraseLine = ESC$1 + '2K';
11052
+ ansiEscapes.eraseDown = ESC$1 + 'J';
11053
+ ansiEscapes.eraseUp = ESC$1 + '1J';
11054
+ ansiEscapes.eraseScreen = ESC$1 + '2J';
11055
+ ansiEscapes.scrollUp = ESC$1 + 'S';
11056
+ ansiEscapes.scrollDown = ESC$1 + 'T';
10806
11057
 
10807
11058
  ansiEscapes.clearScreen = '\u001Bc';
10808
11059
 
10809
11060
  ansiEscapes.clearTerminal = process.platform === 'win32' ?
10810
- `${ansiEscapes.eraseScreen}${ESC}0f` :
11061
+ `${ansiEscapes.eraseScreen}${ESC$1}0f` :
10811
11062
  // 1. Erases the screen (Only done in case `2` is not supported)
10812
11063
  // 2. Erases the whole screen including scrollback buffer
10813
11064
  // 3. Moves cursor to the top-left position
10814
11065
  // More info: https://www.real-world-systems.com/docs/ANSIcode.html
10815
- `${ansiEscapes.eraseScreen}${ESC}3J${ESC}H`;
11066
+ `${ansiEscapes.eraseScreen}${ESC$1}3J${ESC$1}H`;
10816
11067
 
10817
11068
  ansiEscapes.beep = BEL;
10818
11069
 
@@ -11276,633 +11527,7 @@ createLogUpdate(process$1.stdout);
11276
11527
 
11277
11528
  createLogUpdate(process$1.stderr);
11278
11529
 
11279
- var version = "0.33.0";
11280
-
11281
- const comma = ','.charCodeAt(0);
11282
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
11283
- const intToChar = new Uint8Array(64); // 64 possible chars.
11284
- const charToInt = new Uint8Array(128); // z is 122 in ASCII
11285
- for (let i = 0; i < chars.length; i++) {
11286
- const c = chars.charCodeAt(i);
11287
- intToChar[i] = c;
11288
- charToInt[c] = i;
11289
- }
11290
- function decode(mappings) {
11291
- const state = new Int32Array(5);
11292
- const decoded = [];
11293
- let index = 0;
11294
- do {
11295
- const semi = indexOf(mappings, index);
11296
- const line = [];
11297
- let sorted = true;
11298
- let lastCol = 0;
11299
- state[0] = 0;
11300
- for (let i = index; i < semi; i++) {
11301
- let seg;
11302
- i = decodeInteger(mappings, i, state, 0); // genColumn
11303
- const col = state[0];
11304
- if (col < lastCol)
11305
- sorted = false;
11306
- lastCol = col;
11307
- if (hasMoreVlq(mappings, i, semi)) {
11308
- i = decodeInteger(mappings, i, state, 1); // sourcesIndex
11309
- i = decodeInteger(mappings, i, state, 2); // sourceLine
11310
- i = decodeInteger(mappings, i, state, 3); // sourceColumn
11311
- if (hasMoreVlq(mappings, i, semi)) {
11312
- i = decodeInteger(mappings, i, state, 4); // namesIndex
11313
- seg = [col, state[1], state[2], state[3], state[4]];
11314
- }
11315
- else {
11316
- seg = [col, state[1], state[2], state[3]];
11317
- }
11318
- }
11319
- else {
11320
- seg = [col];
11321
- }
11322
- line.push(seg);
11323
- }
11324
- if (!sorted)
11325
- sort(line);
11326
- decoded.push(line);
11327
- index = semi + 1;
11328
- } while (index <= mappings.length);
11329
- return decoded;
11330
- }
11331
- function indexOf(mappings, index) {
11332
- const idx = mappings.indexOf(';', index);
11333
- return idx === -1 ? mappings.length : idx;
11334
- }
11335
- function decodeInteger(mappings, pos, state, j) {
11336
- let value = 0;
11337
- let shift = 0;
11338
- let integer = 0;
11339
- do {
11340
- const c = mappings.charCodeAt(pos++);
11341
- integer = charToInt[c];
11342
- value |= (integer & 31) << shift;
11343
- shift += 5;
11344
- } while (integer & 32);
11345
- const shouldNegate = value & 1;
11346
- value >>>= 1;
11347
- if (shouldNegate) {
11348
- value = -0x80000000 | -value;
11349
- }
11350
- state[j] += value;
11351
- return pos;
11352
- }
11353
- function hasMoreVlq(mappings, i, length) {
11354
- if (i >= length)
11355
- return false;
11356
- return mappings.charCodeAt(i) !== comma;
11357
- }
11358
- function sort(line) {
11359
- line.sort(sortComparator$1);
11360
- }
11361
- function sortComparator$1(a, b) {
11362
- return a[0] - b[0];
11363
- }
11364
-
11365
- // Matches the scheme of a URL, eg "http://"
11366
- const schemeRegex = /^[\w+.-]+:\/\//;
11367
- /**
11368
- * Matches the parts of a URL:
11369
- * 1. Scheme, including ":", guaranteed.
11370
- * 2. User/password, including "@", optional.
11371
- * 3. Host, guaranteed.
11372
- * 4. Port, including ":", optional.
11373
- * 5. Path, including "/", optional.
11374
- * 6. Query, including "?", optional.
11375
- * 7. Hash, including "#", optional.
11376
- */
11377
- const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
11378
- /**
11379
- * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
11380
- * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
11381
- *
11382
- * 1. Host, optional.
11383
- * 2. Path, which may include "/", guaranteed.
11384
- * 3. Query, including "?", optional.
11385
- * 4. Hash, including "#", optional.
11386
- */
11387
- const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
11388
- var UrlType;
11389
- (function (UrlType) {
11390
- UrlType[UrlType["Empty"] = 1] = "Empty";
11391
- UrlType[UrlType["Hash"] = 2] = "Hash";
11392
- UrlType[UrlType["Query"] = 3] = "Query";
11393
- UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
11394
- UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
11395
- UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
11396
- UrlType[UrlType["Absolute"] = 7] = "Absolute";
11397
- })(UrlType || (UrlType = {}));
11398
- function isAbsoluteUrl(input) {
11399
- return schemeRegex.test(input);
11400
- }
11401
- function isSchemeRelativeUrl(input) {
11402
- return input.startsWith('//');
11403
- }
11404
- function isAbsolutePath(input) {
11405
- return input.startsWith('/');
11406
- }
11407
- function isFileUrl(input) {
11408
- return input.startsWith('file:');
11409
- }
11410
- function isRelative(input) {
11411
- return /^[.?#]/.test(input);
11412
- }
11413
- function parseAbsoluteUrl(input) {
11414
- const match = urlRegex.exec(input);
11415
- return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
11416
- }
11417
- function parseFileUrl(input) {
11418
- const match = fileRegex.exec(input);
11419
- const path = match[2];
11420
- return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
11421
- }
11422
- function makeUrl(scheme, user, host, port, path, query, hash) {
11423
- return {
11424
- scheme,
11425
- user,
11426
- host,
11427
- port,
11428
- path,
11429
- query,
11430
- hash,
11431
- type: UrlType.Absolute,
11432
- };
11433
- }
11434
- function parseUrl(input) {
11435
- if (isSchemeRelativeUrl(input)) {
11436
- const url = parseAbsoluteUrl('http:' + input);
11437
- url.scheme = '';
11438
- url.type = UrlType.SchemeRelative;
11439
- return url;
11440
- }
11441
- if (isAbsolutePath(input)) {
11442
- const url = parseAbsoluteUrl('http://foo.com' + input);
11443
- url.scheme = '';
11444
- url.host = '';
11445
- url.type = UrlType.AbsolutePath;
11446
- return url;
11447
- }
11448
- if (isFileUrl(input))
11449
- return parseFileUrl(input);
11450
- if (isAbsoluteUrl(input))
11451
- return parseAbsoluteUrl(input);
11452
- const url = parseAbsoluteUrl('http://foo.com/' + input);
11453
- url.scheme = '';
11454
- url.host = '';
11455
- url.type = input
11456
- ? input.startsWith('?')
11457
- ? UrlType.Query
11458
- : input.startsWith('#')
11459
- ? UrlType.Hash
11460
- : UrlType.RelativePath
11461
- : UrlType.Empty;
11462
- return url;
11463
- }
11464
- function stripPathFilename(path) {
11465
- // If a path ends with a parent directory "..", then it's a relative path with excess parent
11466
- // paths. It's not a file, so we can't strip it.
11467
- if (path.endsWith('/..'))
11468
- return path;
11469
- const index = path.lastIndexOf('/');
11470
- return path.slice(0, index + 1);
11471
- }
11472
- function mergePaths(url, base) {
11473
- normalizePath(base, base.type);
11474
- // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
11475
- // path).
11476
- if (url.path === '/') {
11477
- url.path = base.path;
11478
- }
11479
- else {
11480
- // Resolution happens relative to the base path's directory, not the file.
11481
- url.path = stripPathFilename(base.path) + url.path;
11482
- }
11483
- }
11484
- /**
11485
- * The path can have empty directories "//", unneeded parents "foo/..", or current directory
11486
- * "foo/.". We need to normalize to a standard representation.
11487
- */
11488
- function normalizePath(url, type) {
11489
- const rel = type <= UrlType.RelativePath;
11490
- const pieces = url.path.split('/');
11491
- // We need to preserve the first piece always, so that we output a leading slash. The item at
11492
- // pieces[0] is an empty string.
11493
- let pointer = 1;
11494
- // Positive is the number of real directories we've output, used for popping a parent directory.
11495
- // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
11496
- let positive = 0;
11497
- // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
11498
- // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
11499
- // real directory, we won't need to append, unless the other conditions happen again.
11500
- let addTrailingSlash = false;
11501
- for (let i = 1; i < pieces.length; i++) {
11502
- const piece = pieces[i];
11503
- // An empty directory, could be a trailing slash, or just a double "//" in the path.
11504
- if (!piece) {
11505
- addTrailingSlash = true;
11506
- continue;
11507
- }
11508
- // If we encounter a real directory, then we don't need to append anymore.
11509
- addTrailingSlash = false;
11510
- // A current directory, which we can always drop.
11511
- if (piece === '.')
11512
- continue;
11513
- // A parent directory, we need to see if there are any real directories we can pop. Else, we
11514
- // have an excess of parents, and we'll need to keep the "..".
11515
- if (piece === '..') {
11516
- if (positive) {
11517
- addTrailingSlash = true;
11518
- positive--;
11519
- pointer--;
11520
- }
11521
- else if (rel) {
11522
- // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
11523
- // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
11524
- pieces[pointer++] = piece;
11525
- }
11526
- continue;
11527
- }
11528
- // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
11529
- // any popped or dropped directories.
11530
- pieces[pointer++] = piece;
11531
- positive++;
11532
- }
11533
- let path = '';
11534
- for (let i = 1; i < pointer; i++) {
11535
- path += '/' + pieces[i];
11536
- }
11537
- if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
11538
- path += '/';
11539
- }
11540
- url.path = path;
11541
- }
11542
- /**
11543
- * Attempts to resolve `input` URL/path relative to `base`.
11544
- */
11545
- function resolve$1(input, base) {
11546
- if (!input && !base)
11547
- return '';
11548
- const url = parseUrl(input);
11549
- let inputType = url.type;
11550
- if (base && inputType !== UrlType.Absolute) {
11551
- const baseUrl = parseUrl(base);
11552
- const baseType = baseUrl.type;
11553
- switch (inputType) {
11554
- case UrlType.Empty:
11555
- url.hash = baseUrl.hash;
11556
- // fall through
11557
- case UrlType.Hash:
11558
- url.query = baseUrl.query;
11559
- // fall through
11560
- case UrlType.Query:
11561
- case UrlType.RelativePath:
11562
- mergePaths(url, baseUrl);
11563
- // fall through
11564
- case UrlType.AbsolutePath:
11565
- // The host, user, and port are joined, you can't copy one without the others.
11566
- url.user = baseUrl.user;
11567
- url.host = baseUrl.host;
11568
- url.port = baseUrl.port;
11569
- // fall through
11570
- case UrlType.SchemeRelative:
11571
- // The input doesn't have a schema at least, so we need to copy at least that over.
11572
- url.scheme = baseUrl.scheme;
11573
- }
11574
- if (baseType > inputType)
11575
- inputType = baseType;
11576
- }
11577
- normalizePath(url, inputType);
11578
- const queryHash = url.query + url.hash;
11579
- switch (inputType) {
11580
- // This is impossible, because of the empty checks at the start of the function.
11581
- // case UrlType.Empty:
11582
- case UrlType.Hash:
11583
- case UrlType.Query:
11584
- return queryHash;
11585
- case UrlType.RelativePath: {
11586
- // The first char is always a "/", and we need it to be relative.
11587
- const path = url.path.slice(1);
11588
- if (!path)
11589
- return queryHash || '.';
11590
- if (isRelative(base || input) && !isRelative(path)) {
11591
- // If base started with a leading ".", or there is no base and input started with a ".",
11592
- // then we need to ensure that the relative path starts with a ".". We don't know if
11593
- // relative starts with a "..", though, so check before prepending.
11594
- return './' + path + queryHash;
11595
- }
11596
- return path + queryHash;
11597
- }
11598
- case UrlType.AbsolutePath:
11599
- return url.path + queryHash;
11600
- default:
11601
- return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
11602
- }
11603
- }
11604
-
11605
- function resolve(input, base) {
11606
- // The base is always treated as a directory, if it's not empty.
11607
- // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
11608
- // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
11609
- if (base && !base.endsWith('/'))
11610
- base += '/';
11611
- return resolve$1(input, base);
11612
- }
11613
-
11614
- /**
11615
- * Removes everything after the last "/", but leaves the slash.
11616
- */
11617
- function stripFilename(path) {
11618
- if (!path)
11619
- return '';
11620
- const index = path.lastIndexOf('/');
11621
- return path.slice(0, index + 1);
11622
- }
11623
-
11624
- const COLUMN = 0;
11625
- const SOURCES_INDEX = 1;
11626
- const SOURCE_LINE = 2;
11627
- const SOURCE_COLUMN = 3;
11628
- const REV_GENERATED_LINE = 1;
11629
- const REV_GENERATED_COLUMN = 2;
11630
-
11631
- function maybeSort(mappings, owned) {
11632
- const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
11633
- if (unsortedIndex === mappings.length)
11634
- return mappings;
11635
- // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
11636
- // not, we do not want to modify the consumer's input array.
11637
- if (!owned)
11638
- mappings = mappings.slice();
11639
- for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
11640
- mappings[i] = sortSegments(mappings[i], owned);
11641
- }
11642
- return mappings;
11643
- }
11644
- function nextUnsortedSegmentLine(mappings, start) {
11645
- for (let i = start; i < mappings.length; i++) {
11646
- if (!isSorted(mappings[i]))
11647
- return i;
11648
- }
11649
- return mappings.length;
11650
- }
11651
- function isSorted(line) {
11652
- for (let j = 1; j < line.length; j++) {
11653
- if (line[j][COLUMN] < line[j - 1][COLUMN]) {
11654
- return false;
11655
- }
11656
- }
11657
- return true;
11658
- }
11659
- function sortSegments(line, owned) {
11660
- if (!owned)
11661
- line = line.slice();
11662
- return line.sort(sortComparator);
11663
- }
11664
- function sortComparator(a, b) {
11665
- return a[COLUMN] - b[COLUMN];
11666
- }
11667
-
11668
- let found = false;
11669
- /**
11670
- * A binary search implementation that returns the index if a match is found.
11671
- * If no match is found, then the left-index (the index associated with the item that comes just
11672
- * before the desired index) is returned. To maintain proper sort order, a splice would happen at
11673
- * the next index:
11674
- *
11675
- * ```js
11676
- * const array = [1, 3];
11677
- * const needle = 2;
11678
- * const index = binarySearch(array, needle, (item, needle) => item - needle);
11679
- *
11680
- * assert.equal(index, 0);
11681
- * array.splice(index + 1, 0, needle);
11682
- * assert.deepEqual(array, [1, 2, 3]);
11683
- * ```
11684
- */
11685
- function binarySearch(haystack, needle, low, high) {
11686
- while (low <= high) {
11687
- const mid = low + ((high - low) >> 1);
11688
- const cmp = haystack[mid][COLUMN] - needle;
11689
- if (cmp === 0) {
11690
- found = true;
11691
- return mid;
11692
- }
11693
- if (cmp < 0) {
11694
- low = mid + 1;
11695
- }
11696
- else {
11697
- high = mid - 1;
11698
- }
11699
- }
11700
- found = false;
11701
- return low - 1;
11702
- }
11703
- function upperBound(haystack, needle, index) {
11704
- for (let i = index + 1; i < haystack.length; index = i++) {
11705
- if (haystack[i][COLUMN] !== needle)
11706
- break;
11707
- }
11708
- return index;
11709
- }
11710
- function lowerBound(haystack, needle, index) {
11711
- for (let i = index - 1; i >= 0; index = i--) {
11712
- if (haystack[i][COLUMN] !== needle)
11713
- break;
11714
- }
11715
- return index;
11716
- }
11717
- function memoizedState() {
11718
- return {
11719
- lastKey: -1,
11720
- lastNeedle: -1,
11721
- lastIndex: -1,
11722
- };
11723
- }
11724
- /**
11725
- * This overly complicated beast is just to record the last tested line/column and the resulting
11726
- * index, allowing us to skip a few tests if mappings are monotonically increasing.
11727
- */
11728
- function memoizedBinarySearch(haystack, needle, state, key) {
11729
- const { lastKey, lastNeedle, lastIndex } = state;
11730
- let low = 0;
11731
- let high = haystack.length - 1;
11732
- if (key === lastKey) {
11733
- if (needle === lastNeedle) {
11734
- found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
11735
- return lastIndex;
11736
- }
11737
- if (needle >= lastNeedle) {
11738
- // lastIndex may be -1 if the previous needle was not found.
11739
- low = lastIndex === -1 ? 0 : lastIndex;
11740
- }
11741
- else {
11742
- high = lastIndex;
11743
- }
11744
- }
11745
- state.lastKey = key;
11746
- state.lastNeedle = needle;
11747
- return (state.lastIndex = binarySearch(haystack, needle, low, high));
11748
- }
11749
-
11750
- // Rebuilds the original source files, with mappings that are ordered by source line/column instead
11751
- // of generated line/column.
11752
- function buildBySources(decoded, memos) {
11753
- const sources = memos.map(buildNullArray);
11754
- for (let i = 0; i < decoded.length; i++) {
11755
- const line = decoded[i];
11756
- for (let j = 0; j < line.length; j++) {
11757
- const seg = line[j];
11758
- if (seg.length === 1)
11759
- continue;
11760
- const sourceIndex = seg[SOURCES_INDEX];
11761
- const sourceLine = seg[SOURCE_LINE];
11762
- const sourceColumn = seg[SOURCE_COLUMN];
11763
- const originalSource = sources[sourceIndex];
11764
- const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = []));
11765
- const memo = memos[sourceIndex];
11766
- // The binary search either found a match, or it found the left-index just before where the
11767
- // segment should go. Either way, we want to insert after that. And there may be multiple
11768
- // generated segments associated with an original location, so there may need to move several
11769
- // indexes before we find where we need to insert.
11770
- const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine));
11771
- insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]);
11772
- }
11773
- }
11774
- return sources;
11775
- }
11776
- function insert(array, index, value) {
11777
- for (let i = array.length; i > index; i--) {
11778
- array[i] = array[i - 1];
11779
- }
11780
- array[index] = value;
11781
- }
11782
- // Null arrays allow us to use ordered index keys without actually allocating contiguous memory like
11783
- // a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations.
11784
- // Numeric properties on objects are magically sorted in ascending order by the engine regardless of
11785
- // the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending
11786
- // order when iterating with for-in.
11787
- function buildNullArray() {
11788
- return { __proto__: null };
11789
- }
11790
-
11791
- const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
11792
- const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
11793
- const LEAST_UPPER_BOUND = -1;
11794
- const GREATEST_LOWER_BOUND = 1;
11795
- /**
11796
- * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
11797
- */
11798
- let decodedMappings;
11799
- /**
11800
- * Finds the generated line/column position of the provided source/line/column source position.
11801
- */
11802
- let generatedPositionFor;
11803
- class TraceMap {
11804
- constructor(map, mapUrl) {
11805
- const isString = typeof map === 'string';
11806
- if (!isString && map._decodedMemo)
11807
- return map;
11808
- const parsed = (isString ? JSON.parse(map) : map);
11809
- const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
11810
- this.version = version;
11811
- this.file = file;
11812
- this.names = names;
11813
- this.sourceRoot = sourceRoot;
11814
- this.sources = sources;
11815
- this.sourcesContent = sourcesContent;
11816
- const from = resolve(sourceRoot || '', stripFilename(mapUrl));
11817
- this.resolvedSources = sources.map((s) => resolve(s || '', from));
11818
- const { mappings } = parsed;
11819
- if (typeof mappings === 'string') {
11820
- this._encoded = mappings;
11821
- this._decoded = undefined;
11822
- }
11823
- else {
11824
- this._encoded = undefined;
11825
- this._decoded = maybeSort(mappings, isString);
11826
- }
11827
- this._decodedMemo = memoizedState();
11828
- this._bySources = undefined;
11829
- this._bySourceMemos = undefined;
11830
- }
11831
- }
11832
- (() => {
11833
- decodedMappings = (map) => {
11834
- return (map._decoded || (map._decoded = decode(map._encoded)));
11835
- };
11836
- generatedPositionFor = (map, { source, line, column, bias }) => {
11837
- return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);
11838
- };
11839
- function generatedPosition(map, source, line, column, bias, all) {
11840
- line--;
11841
- if (line < 0)
11842
- throw new Error(LINE_GTR_ZERO);
11843
- if (column < 0)
11844
- throw new Error(COL_GTR_EQ_ZERO);
11845
- const { sources, resolvedSources } = map;
11846
- let sourceIndex = sources.indexOf(source);
11847
- if (sourceIndex === -1)
11848
- sourceIndex = resolvedSources.indexOf(source);
11849
- if (sourceIndex === -1)
11850
- return all ? [] : GMapping(null, null);
11851
- const generated = (map._bySources || (map._bySources = buildBySources(decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState)))));
11852
- const segments = generated[sourceIndex][line];
11853
- if (segments == null)
11854
- return all ? [] : GMapping(null, null);
11855
- const memo = map._bySourceMemos[sourceIndex];
11856
- if (all)
11857
- return sliceGeneratedPositions(segments, memo, line, column, bias);
11858
- const index = traceSegmentInternal(segments, memo, line, column, bias);
11859
- if (index === -1)
11860
- return GMapping(null, null);
11861
- const segment = segments[index];
11862
- return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);
11863
- }
11864
- })();
11865
- function GMapping(line, column) {
11866
- return { line, column };
11867
- }
11868
- function traceSegmentInternal(segments, memo, line, column, bias) {
11869
- let index = memoizedBinarySearch(segments, column, memo, line);
11870
- if (found) {
11871
- index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
11872
- }
11873
- else if (bias === LEAST_UPPER_BOUND)
11874
- index++;
11875
- if (index === -1 || index === segments.length)
11876
- return -1;
11877
- return index;
11878
- }
11879
- function sliceGeneratedPositions(segments, memo, line, column, bias) {
11880
- let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);
11881
- // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in
11882
- // insertion order) segment that matched. Even if we did respect the bias when tracing, we would
11883
- // still need to call `lowerBound()` to find the first segment, which is slower than just looking
11884
- // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the
11885
- // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to
11886
- // match LEAST_UPPER_BOUND.
11887
- if (!found && bias === LEAST_UPPER_BOUND)
11888
- min++;
11889
- if (min === -1 || min === segments.length)
11890
- return [];
11891
- // We may have found the segment that started at an earlier column. If this is the case, then we
11892
- // need to slice all generated segments that match _that_ column, because all such segments span
11893
- // to our desired column.
11894
- const matchedColumn = found ? column : segments[min][COLUMN];
11895
- // The binary search is not guaranteed to find the lower bound when a match wasn't found.
11896
- if (!found)
11897
- min = lowerBound(segments, matchedColumn, min);
11898
- const max = upperBound(segments, matchedColumn, min);
11899
- const result = [];
11900
- for (; min <= max; min++) {
11901
- const segment = segments[min];
11902
- result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));
11903
- }
11904
- return result;
11905
- }
11530
+ var version = "0.34.0";
11906
11531
 
11907
11532
  const A=r=>r!==null&&typeof r=="object",a=(r,t)=>Object.assign(new Error(`[${r}]: ${t}`),{code:r}),_$1="ERR_INVALID_PACKAGE_CONFIG",E="ERR_INVALID_PACKAGE_TARGET",I="ERR_PACKAGE_PATH_NOT_EXPORTED",R$1=/^\d+$/,O=/^(\.{1,2}|node_modules)$/i,w=/\/|\\/;var h=(r=>(r.Export="exports",r.Import="imports",r))(h||{});const f=(r,t,e,o,c)=>{if(t==null)return [];if(typeof t=="string"){const[n,...i]=t.split(w);if(n===".."||i.some(l=>O.test(l)))throw a(E,`Invalid "${r}" target "${t}" defined in the package config`);return [c?t.replace(/\*/g,c):t]}if(Array.isArray(t))return t.flatMap(n=>f(r,n,e,o,c));if(A(t)){for(const n of Object.keys(t)){if(R$1.test(n))throw a(_$1,"Cannot contain numeric property keys");if(n==="default"||o.includes(n))return f(r,t[n],e,o,c)}return []}throw a(E,`Invalid "${r}" target "${t}"`)},s="*",m=(r,t)=>{const e=r.indexOf(s),o=t.indexOf(s);return e===o?t.length>r.length:o>e};function d$1(r,t){if(!t.includes(s)&&r.hasOwnProperty(t))return [t];let e,o;for(const c of Object.keys(r))if(c.includes(s)){const[n,i,l]=c.split(s);if(l===void 0&&t.startsWith(n)&&t.endsWith(i)){const g=t.slice(n.length,-i.length||void 0);g&&(!e||m(e,c))&&(e=c,o=g);}}return [e,o]}const p=r=>Object.keys(r).reduce((t,e)=>{const o=e===""||e[0]!==".";if(t===void 0||t===o)return o;throw a(_$1,'"exports" cannot contain some keys starting with "." and some not')},void 0),u=/^\w+:/,v=(r,t,e)=>{if(!r)throw new Error('"exports" is required');t=t===""?".":`./${t}`,(typeof r=="string"||Array.isArray(r)||A(r)&&p(r))&&(r={".":r});const[o,c]=d$1(r,t),n=f(h.Export,r[o],t,e,c);if(n.length===0)throw a(I,t==="."?'No "exports" main defined':`Package subpath '${t}' is not defined by "exports"`);for(const i of n)if(!i.startsWith("./")&&!u.test(i))throw a(E,`Invalid "exports" target "${i}" defined in the package config`);return n};
11908
11533
 
@@ -11947,7 +11572,7 @@ async function makeTscErrorInfo(errInfo) {
11947
11572
  }
11948
11573
  async function getTsconfig(root, config) {
11949
11574
  const configName = config.tsconfig ? basename(config.tsconfig) : void 0;
11950
- const configSearchPath = config.tsconfig ? dirname(resolve$2(root, config.tsconfig)) : root;
11575
+ const configSearchPath = config.tsconfig ? dirname(resolve(root, config.tsconfig)) : root;
11951
11576
  const tsconfig = Te(configSearchPath, configName);
11952
11577
  if (!tsconfig)
11953
11578
  throw new Error("no tsconfig.json found");
@@ -12270,7 +11895,7 @@ class Typechecker {
12270
11895
  const errorsMap = await getRawErrsMapFromTsCompile(output);
12271
11896
  const typesErrors = /* @__PURE__ */ new Map();
12272
11897
  errorsMap.forEach((errors, path) => {
12273
- const filepath = resolve$2(this.ctx.config.root, path);
11898
+ const filepath = resolve(this.ctx.config.root, path);
12274
11899
  const suiteErrors = errors.map((info) => {
12275
11900
  const limit = Error.stackTraceLimit;
12276
11901
  Error.stackTraceLimit = 0;
@@ -12379,8 +12004,9 @@ class Typechecker {
12379
12004
  }
12380
12005
  }
12381
12006
 
12382
- async function printError(error, ctx, options = {}) {
12007
+ async function printError(error, project, options) {
12383
12008
  const { showCodeFrame = true, fullStack = false, type } = options;
12009
+ const logger = options.logger;
12384
12010
  let e = error;
12385
12011
  if (isPrimitive(e)) {
12386
12012
  e = {
@@ -12395,25 +12021,31 @@ async function printError(error, ctx, options = {}) {
12395
12021
  stack: error2.stack
12396
12022
  };
12397
12023
  }
12398
- if (!ctx.config)
12399
- return printErrorMessage(e, ctx.logger);
12400
- const stacks = parseErrorStacktrace(e, fullStack ? [] : void 0);
12024
+ if (!project)
12025
+ return printErrorMessage(e, logger);
12026
+ const parserOptions = {
12027
+ // only browser stack traces require remapping
12028
+ getSourceMap: (file) => project.getBrowserSourceMapModuleById(file)
12029
+ };
12030
+ if (fullStack)
12031
+ parserOptions.ignoreStackEntries = [];
12032
+ const stacks = parseErrorStacktrace(e, parserOptions);
12401
12033
  const nearest = error instanceof TypeCheckError ? error.stacks[0] : stacks.find(
12402
- (stack) => ctx.getModuleProjects(stack.file).length && existsSync(stack.file)
12034
+ (stack) => project.getModuleById(stack.file) && existsSync(stack.file)
12403
12035
  );
12404
12036
  const errorProperties = getErrorProperties(e);
12405
12037
  if (type)
12406
- printErrorType(type, ctx);
12407
- printErrorMessage(e, ctx.logger);
12038
+ printErrorType(type, project.ctx);
12039
+ printErrorMessage(e, logger);
12408
12040
  if (e.diff)
12409
- displayDiff(e.diff, ctx.logger.console);
12041
+ displayDiff(e.diff, logger.console);
12410
12042
  if (e.frame) {
12411
- ctx.logger.error(c.yellow(e.frame));
12043
+ logger.error(c.yellow(e.frame));
12412
12044
  } else {
12413
- printStack(ctx, stacks, nearest, errorProperties, (s) => {
12045
+ printStack(project, stacks, nearest, errorProperties, (s) => {
12414
12046
  if (showCodeFrame && s === nearest && nearest) {
12415
12047
  const sourceCode = readFileSync(nearest.file, "utf-8");
12416
- ctx.logger.error(generateCodeFrame(sourceCode, 4, s.line, s.column));
12048
+ logger.error(generateCodeFrame(sourceCode, 4, s.line, s.column));
12417
12049
  }
12418
12050
  });
12419
12051
  }
@@ -12421,20 +12053,20 @@ async function printError(error, ctx, options = {}) {
12421
12053
  const testName = e.VITEST_TEST_NAME;
12422
12054
  const afterEnvTeardown = e.VITEST_AFTER_ENV_TEARDOWN;
12423
12055
  if (testPath)
12424
- ctx.logger.error(c.red(`This error originated in "${c.bold(testPath)}" test file. It doesn't mean the error was thrown inside the file itself, but while it was running.`));
12056
+ logger.error(c.red(`This error originated in "${c.bold(testPath)}" test file. It doesn't mean the error was thrown inside the file itself, but while it was running.`));
12425
12057
  if (testName) {
12426
- ctx.logger.error(c.red(`The latest test that might've caused the error is "${c.bold(testName)}". It might mean one of the following:
12058
+ logger.error(c.red(`The latest test that might've caused the error is "${c.bold(testName)}". It might mean one of the following:
12427
12059
  - The error was thrown, while Vitest was running this test.
12428
12060
  - This was the last recorded test before the error was thrown, if error originated after test finished its execution.`));
12429
12061
  }
12430
12062
  if (afterEnvTeardown) {
12431
- ctx.logger.error(c.red("This error was caught after test environment was torn down. Make sure to cancel any running tasks before test finishes:\n- cancel timeouts using clearTimeout and clearInterval\n- wait for promises to resolve using the await keyword"));
12063
+ logger.error(c.red("This error was caught after test environment was torn down. Make sure to cancel any running tasks before test finishes:\n- cancel timeouts using clearTimeout and clearInterval\n- wait for promises to resolve using the await keyword"));
12432
12064
  }
12433
12065
  if (typeof e.cause === "object" && e.cause && "name" in e.cause) {
12434
12066
  e.cause.name = `Caused by: ${e.cause.name}`;
12435
- await printError(e.cause, ctx, { fullStack, showCodeFrame: false });
12067
+ await printError(e.cause, project, { fullStack, showCodeFrame: false, logger: options.logger });
12436
12068
  }
12437
- handleImportOutsideModuleError(e.stack || e.stackStr || "", ctx);
12069
+ handleImportOutsideModuleError(e.stack || e.stackStr || "", logger);
12438
12070
  }
12439
12071
  function printErrorType(type, ctx) {
12440
12072
  ctx.logger.error(`
@@ -12471,7 +12103,7 @@ const esmErrors = [
12471
12103
  "Cannot use import statement outside a module",
12472
12104
  "Unexpected token 'export'"
12473
12105
  ];
12474
- function handleImportOutsideModuleError(stack, ctx) {
12106
+ function handleImportOutsideModuleError(stack, logger) {
12475
12107
  if (!esmErrors.some((e) => stack.includes(e)))
12476
12108
  return;
12477
12109
  const path = normalize(stack.split("\n")[0].trim());
@@ -12481,9 +12113,9 @@ function handleImportOutsideModuleError(stack, ctx) {
12481
12113
  else
12482
12114
  name = name.split("/")[0];
12483
12115
  if (name)
12484
- printModuleWarningForPackage(ctx.logger, path, name);
12116
+ printModuleWarningForPackage(logger, path, name);
12485
12117
  else
12486
- printModuleWarningForSourceCode(ctx.logger, path);
12118
+ printModuleWarningForSourceCode(logger, path);
12487
12119
  }
12488
12120
  function printModuleWarningForPackage(logger, path, name) {
12489
12121
  logger.error(c.yellow(
@@ -12516,17 +12148,21 @@ ${diff}
12516
12148
  }
12517
12149
  function printErrorMessage(error, logger) {
12518
12150
  const errorName = error.name || error.nameStr || "Unknown Error";
12151
+ if (!error.message) {
12152
+ logger.error(error);
12153
+ return;
12154
+ }
12519
12155
  if (error.message.length > 5e3) {
12520
12156
  logger.error(`${c.red(c.bold(errorName))}: ${error.message}`);
12521
12157
  } else {
12522
12158
  logger.error(c.red(`${c.bold(errorName)}: ${error.message}`));
12523
12159
  }
12524
12160
  }
12525
- function printStack(ctx, stack, highlight, errorProperties, onStack) {
12526
- const logger = ctx.logger;
12161
+ function printStack(project, stack, highlight, errorProperties, onStack) {
12162
+ const logger = project.ctx.logger;
12527
12163
  for (const frame of stack) {
12528
12164
  const color = frame === highlight ? c.cyan : c.gray;
12529
- const path = relative(ctx.config.root, frame.file);
12165
+ const path = relative(project.config.root, frame.file);
12530
12166
  logger.error(color(` ${c.dim(F_POINTER)} ${[frame.method, `${path}:${c.dim(`${frame.line}:${frame.column}`)}`].filter(Boolean).join(" ")}`));
12531
12167
  onStack == null ? void 0 : onStack(frame);
12532
12168
  }
@@ -12535,7 +12171,7 @@ function printStack(ctx, stack, highlight, errorProperties, onStack) {
12535
12171
  const hasProperties = Object.keys(errorProperties).length > 0;
12536
12172
  if (hasProperties) {
12537
12173
  logger.error(c.red(c.dim(divider())));
12538
- const propertiesString = stringify$5(errorProperties, 10, { printBasicPrototype: false });
12174
+ const propertiesString = inspect(errorProperties);
12539
12175
  logger.error(c.red(c.bold("Serialized Error:")), c.gray(propertiesString));
12540
12176
  }
12541
12177
  }
@@ -12580,6 +12216,11 @@ function generateCodeFrame(source, indent = 0, lineNumber, columnNumber, range =
12580
12216
  return res.join("\n");
12581
12217
  }
12582
12218
 
12219
+ const ESC = "\x1B[";
12220
+ const ERASE_DOWN = `${ESC}J`;
12221
+ const ERASE_SCROLLBACK = `${ESC}3J`;
12222
+ const CURSOR_TO_START = `${ESC}1;1H`;
12223
+ const CLEAR_SCREEN = "\x1Bc";
12583
12224
  class Logger {
12584
12225
  constructor(ctx, console = globalThis.console) {
12585
12226
  this.ctx = ctx;
@@ -12606,7 +12247,7 @@ class Logger {
12606
12247
  this.console.log(message);
12607
12248
  return;
12608
12249
  }
12609
- this.console.log(`\x1Bc${message}`);
12250
+ this.console.log(`${ERASE_SCROLLBACK}${CLEAR_SCREEN}${message}`);
12610
12251
  }
12611
12252
  clearScreen(message, force = false) {
12612
12253
  if (this.ctx.server.config.clearScreen === false) {
@@ -12622,16 +12263,20 @@ class Logger {
12622
12263
  return;
12623
12264
  const log = this._clearScreenPending;
12624
12265
  this._clearScreenPending = void 0;
12625
- this.console.log(`\x1B[1;1H\x1B[J${log}`);
12266
+ this.console.log(`${CURSOR_TO_START}${ERASE_DOWN}${log}`);
12626
12267
  }
12627
- printError(err, fullStack = false, type) {
12628
- return printError(err, this.ctx, {
12268
+ printError(err, options = {}) {
12269
+ const { fullStack = false, type } = options;
12270
+ const project = options.project ?? this.ctx.getCoreWorkspaceProject() ?? this.ctx.projects[0];
12271
+ return printError(err, project, {
12629
12272
  fullStack,
12630
12273
  type,
12631
- showCodeFrame: true
12274
+ showCodeFrame: true,
12275
+ logger: this
12632
12276
  });
12633
12277
  }
12634
12278
  printNoTestFound(filters) {
12279
+ var _a;
12635
12280
  const config = this.ctx.config;
12636
12281
  const comma = c.dim(", ");
12637
12282
  if (filters == null ? void 0 : filters.length)
@@ -12642,12 +12287,17 @@ class Logger {
12642
12287
  this.console.error(c.dim("exclude: ") + c.yellow(config.exclude.join(comma)));
12643
12288
  if (config.watchExclude)
12644
12289
  this.console.error(c.dim("watch exclude: ") + c.yellow(config.watchExclude.join(comma)));
12645
- if (config.passWithNoTests)
12646
- this.log(`No ${config.mode} files found, exiting with code 0
12290
+ if (config.watch && (config.changed || ((_a = config.related) == null ? void 0 : _a.length))) {
12291
+ this.log(`No affected ${config.mode} files found
12647
12292
  `);
12648
- else
12649
- this.error(c.red(`
12293
+ } else {
12294
+ if (config.passWithNoTests)
12295
+ this.log(`No ${config.mode} files found, exiting with code 0
12296
+ `);
12297
+ else
12298
+ this.error(c.red(`
12650
12299
  No ${config.mode} files found, exiting with code 1`));
12300
+ }
12651
12301
  }
12652
12302
  printBanner() {
12653
12303
  var _a, _b;
@@ -12682,7 +12332,7 @@ This might cause false positive tests. Resolve unhandled errors to make sure you
12682
12332
  this.log(c.red(divider(c.bold(c.inverse(" Unhandled Errors ")))));
12683
12333
  this.log(errorMessage);
12684
12334
  await Promise.all(errors.map(async (err) => {
12685
- await this.printError(err, true, err.type || "Unhandled Error");
12335
+ await this.printError(err, { fullStack: true, type: err.type || "Unhandled Error" });
12686
12336
  }));
12687
12337
  this.log(c.red(divider()));
12688
12338
  }
@@ -12694,7 +12344,7 @@ Vitest found ${errors.length} error${errors.length > 1 ? "s" : ""} not related t
12694
12344
  this.log(c.red(divider(c.bold(c.inverse(" Source Errors ")))));
12695
12345
  this.log(errorMessage);
12696
12346
  await Promise.all(errors.map(async (err) => {
12697
- await this.printError(err, true);
12347
+ await this.printError(err, { fullStack: true });
12698
12348
  }));
12699
12349
  this.log(c.red(divider()));
12700
12350
  }
@@ -12853,7 +12503,7 @@ function MocksPlugin() {
12853
12503
  async function createBrowserServer(project, options) {
12854
12504
  const root = project.config.root;
12855
12505
  await ensurePackageInstalled("@vitest/browser", root);
12856
- const configPath = options.config === false ? false : options.config ? resolve$2(root, options.config) : await findUp(configFiles, { cwd: root });
12506
+ const configPath = options.config === false ? false : options.config ? resolve(root, options.config) : await findUp(configFiles, { cwd: root });
12857
12507
  const server = await createServer({
12858
12508
  logLevel: "error",
12859
12509
  mode: project.config.mode,
@@ -12891,7 +12541,7 @@ async function createBrowserServer(project, options) {
12891
12541
  });
12892
12542
  await server.listen();
12893
12543
  await server.watcher.close();
12894
- (await import('./chunk-api-setup.8f785c4a.js')).setup(project, server);
12544
+ (await import('./chunk-api-setup.644415c3.js')).setup(project, server);
12895
12545
  return server;
12896
12546
  }
12897
12547
 
@@ -13094,21 +12744,29 @@ function CSSEnablerPlugin(ctx) {
13094
12744
  ];
13095
12745
  }
13096
12746
 
13097
- function EnvReplacerPlugin() {
12747
+ function SsrReplacerPlugin() {
13098
12748
  return {
13099
12749
  name: "vitest:env-replacer",
13100
12750
  enforce: "pre",
13101
12751
  transform(code, id) {
13102
- if (!/\bimport\.meta\.env\b/g.test(code))
12752
+ if (!/\bimport\.meta\.env\b/.test(code) && !/\bimport\.meta\.url\b/.test(code))
13103
12753
  return null;
13104
12754
  let s = null;
13105
- const envs = stripLiteral(code).matchAll(/\bimport\.meta\.env\b/g);
12755
+ const cleanCode = stripLiteral(code);
12756
+ const envs = cleanCode.matchAll(/\bimport\.meta\.env\b/g);
13106
12757
  for (const env of envs) {
13107
12758
  s || (s = new MagicString(code));
13108
12759
  const startIndex = env.index;
13109
12760
  const endIndex = startIndex + env[0].length;
13110
12761
  s.overwrite(startIndex, endIndex, "process.env");
13111
12762
  }
12763
+ const urls = cleanCode.matchAll(/\bimport\.meta\.url\b/g);
12764
+ for (const env of urls) {
12765
+ s || (s = new MagicString(code));
12766
+ const startIndex = env.index;
12767
+ const endIndex = startIndex + env[0].length;
12768
+ s.overwrite(startIndex, endIndex, "__vite_ssr_import_meta__.url");
12769
+ }
13112
12770
  if (s) {
13113
12771
  return {
13114
12772
  code: s.toString(),
@@ -13192,14 +12850,17 @@ ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
13192
12850
  };
13193
12851
  }
13194
12852
 
13195
- function resolveOptimizerConfig(testOptionc, viteOptions, testConfig) {
12853
+ function resolveOptimizerConfig(_testOptions, viteOptions, testConfig) {
13196
12854
  var _a;
12855
+ const testOptions = _testOptions || {};
13197
12856
  const newConfig = {};
13198
12857
  const [major, minor] = version$2.split(".").map(Number);
13199
12858
  const allowed = major >= 5 || major === 4 && minor >= 3;
13200
- if (!allowed && (testOptionc == null ? void 0 : testOptionc.enabled) === true)
12859
+ if (!allowed && (testOptions == null ? void 0 : testOptions.enabled) === true)
13201
12860
  console.warn(`Vitest: "deps.optimizer" is only available in Vite >= 4.3.0, current Vite version: ${version$2}`);
13202
- if (!allowed || (testOptionc == null ? void 0 : testOptionc.enabled) !== true) {
12861
+ else
12862
+ testOptions.enabled ?? (testOptions.enabled = true);
12863
+ if (!allowed || (testOptions == null ? void 0 : testOptions.enabled) !== true) {
13203
12864
  newConfig.cacheDir = void 0;
13204
12865
  newConfig.optimizeDeps = {
13205
12866
  // experimental in Vite >2.9.2, entries remains to help with older versions
@@ -13211,12 +12872,12 @@ function resolveOptimizerConfig(testOptionc, viteOptions, testConfig) {
13211
12872
  newConfig.cacheDir = cacheDir ?? "node_modules/.vitest";
13212
12873
  newConfig.optimizeDeps = {
13213
12874
  ...viteOptions,
13214
- ...testOptionc,
12875
+ ...testOptions,
13215
12876
  noDiscovery: true,
13216
12877
  disabled: false,
13217
12878
  entries: [],
13218
- exclude: ["vitest", ...builtinModules, ...testOptionc.exclude || (viteOptions == null ? void 0 : viteOptions.exclude) || []],
13219
- include: (testOptionc.include || (viteOptions == null ? void 0 : viteOptions.include) || []).filter((n) => n !== "vitest")
12879
+ exclude: ["vitest", ...builtinModules, ...testOptions.exclude || (viteOptions == null ? void 0 : viteOptions.exclude) || []],
12880
+ include: (testOptions.include || (viteOptions == null ? void 0 : viteOptions.include) || []).filter((n) => n !== "vitest")
13220
12881
  };
13221
12882
  }
13222
12883
  return newConfig;
@@ -13334,8 +12995,8 @@ function WorkspaceVitestPlugin(project, options) {
13334
12995
  };
13335
12996
  }
13336
12997
  }
13337
- const webOptimizer = resolveOptimizerConfig((_e = (_d = testConfig.deps) == null ? void 0 : _d.experimentalOptimizer) == null ? void 0 : _e.web, viteConfig.optimizeDeps, testConfig);
13338
- const ssrOptimizer = resolveOptimizerConfig((_g = (_f = testConfig.deps) == null ? void 0 : _f.experimentalOptimizer) == null ? void 0 : _g.ssr, (_h = viteConfig.ssr) == null ? void 0 : _h.optimizeDeps, testConfig);
12998
+ const webOptimizer = resolveOptimizerConfig((_e = (_d = testConfig.deps) == null ? void 0 : _d.optimizer) == null ? void 0 : _e.web, viteConfig.optimizeDeps, testConfig);
12999
+ const ssrOptimizer = resolveOptimizerConfig((_g = (_f = testConfig.deps) == null ? void 0 : _f.optimizer) == null ? void 0 : _g.ssr, (_h = viteConfig.ssr) == null ? void 0 : _h.optimizeDeps, testConfig);
13339
13000
  config.cacheDir = webOptimizer.cacheDir || ssrOptimizer.cacheDir || config.cacheDir;
13340
13001
  config.optimizeDeps = webOptimizer.optimizeDeps;
13341
13002
  config.ssr = {
@@ -13352,13 +13013,13 @@ function WorkspaceVitestPlugin(project, options) {
13352
13013
  );
13353
13014
  await project.setServer(options2, server);
13354
13015
  } catch (err) {
13355
- await project.ctx.logger.printError(err, true);
13016
+ await project.ctx.logger.printError(err, { fullStack: true });
13356
13017
  process.exit(1);
13357
13018
  }
13358
13019
  await server.watcher.close();
13359
13020
  }
13360
13021
  },
13361
- EnvReplacerPlugin(),
13022
+ SsrReplacerPlugin(),
13362
13023
  ...CSSEnablerPlugin(project),
13363
13024
  CoverageTransform(project.ctx),
13364
13025
  GlobalSetupPlugin(project, project.ctx.logger),
@@ -13370,7 +13031,7 @@ function WorkspaceVitestPlugin(project, options) {
13370
13031
  async function initializeProject(workspacePath, ctx, options) {
13371
13032
  var _a, _b, _c, _d, _e, _f, _g;
13372
13033
  const project = new WorkspaceProject(workspacePath, ctx);
13373
- const configFile = options.extends ? resolve$2(dirname(options.workspaceConfigPath), options.extends) : typeof workspacePath === "number" || workspacePath.endsWith("/") ? false : workspacePath;
13034
+ const configFile = options.extends ? resolve(dirname(options.workspaceConfigPath), options.extends) : typeof workspacePath === "number" || workspacePath.endsWith("/") ? false : workspacePath;
13374
13035
  const root = options.root || (typeof workspacePath === "number" ? void 0 : dirname(workspacePath));
13375
13036
  const config = {
13376
13037
  ...options,
@@ -13385,7 +13046,7 @@ async function initializeProject(workspacePath, ctx, options) {
13385
13046
  ]
13386
13047
  };
13387
13048
  const server = await createServer(config);
13388
- if (((_a = ctx.config.api) == null ? void 0 : _a.port) || ((_d = (_c = (_b = project.config.deps) == null ? void 0 : _b.experimentalOptimizer) == null ? void 0 : _c.web) == null ? void 0 : _d.enabled) || ((_g = (_f = (_e = project.config.deps) == null ? void 0 : _e.experimentalOptimizer) == null ? void 0 : _f.ssr) == null ? void 0 : _g.enabled))
13049
+ if (((_a = ctx.config.api) == null ? void 0 : _a.port) || ((_d = (_c = (_b = project.config.deps) == null ? void 0 : _b.optimizer) == null ? void 0 : _c.web) == null ? void 0 : _d.enabled) || ((_g = (_f = (_e = project.config.deps) == null ? void 0 : _e.optimizer) == null ? void 0 : _f.ssr) == null ? void 0 : _g.enabled))
13389
13050
  await server.listen();
13390
13051
  else
13391
13052
  await server.pluginContainer.buildStart({});
@@ -13401,16 +13062,30 @@ class WorkspaceProject {
13401
13062
  server;
13402
13063
  vitenode;
13403
13064
  runner;
13404
- browser = void 0;
13065
+ browser;
13405
13066
  typechecker;
13406
13067
  closingPromise;
13407
13068
  browserProvider;
13069
+ testFilesList = [];
13408
13070
  getName() {
13409
13071
  return this.config.name || "";
13410
13072
  }
13411
13073
  isCore() {
13412
13074
  return this.ctx.getCoreWorkspaceProject() === this;
13413
13075
  }
13076
+ getModuleById(id) {
13077
+ var _a;
13078
+ return this.server.moduleGraph.getModuleById(id) || ((_a = this.browser) == null ? void 0 : _a.moduleGraph.getModuleById(id));
13079
+ }
13080
+ getSourceMapModuleById(id) {
13081
+ var _a, _b;
13082
+ const mod = this.server.moduleGraph.getModuleById(id);
13083
+ return ((_a = mod == null ? void 0 : mod.ssrTransformResult) == null ? void 0 : _a.map) || ((_b = mod == null ? void 0 : mod.transformResult) == null ? void 0 : _b.map);
13084
+ }
13085
+ getBrowserSourceMapModuleById(id) {
13086
+ var _a, _b, _c;
13087
+ return (_c = (_b = (_a = this.browser) == null ? void 0 : _a.moduleGraph.getModuleById(id)) == null ? void 0 : _b.transformResult) == null ? void 0 : _c.map;
13088
+ }
13414
13089
  get reporters() {
13415
13090
  return this.ctx.reporters;
13416
13091
  }
@@ -13434,8 +13109,12 @@ class WorkspaceProject {
13434
13109
  }
13435
13110
  }));
13436
13111
  }
13112
+ this.testFilesList = testFiles;
13437
13113
  return testFiles;
13438
13114
  }
13115
+ isTestFile(id) {
13116
+ return this.testFilesList.includes(id);
13117
+ }
13439
13118
  async globFiles(include, exclude, cwd) {
13440
13119
  const globOptions = {
13441
13120
  absolute: true,
@@ -13572,10 +13251,10 @@ class WorkspaceProject {
13572
13251
  ...this.config.deps,
13573
13252
  optimizer: {
13574
13253
  web: {
13575
- enabled: ((_c = (_b = (_a = this.config.deps) == null ? void 0 : _a.experimentalOptimizer) == null ? void 0 : _b.web) == null ? void 0 : _c.enabled) ?? false
13254
+ enabled: ((_c = (_b = (_a = this.config.deps) == null ? void 0 : _a.optimizer) == null ? void 0 : _b.web) == null ? void 0 : _c.enabled) ?? false
13576
13255
  },
13577
13256
  ssr: {
13578
- enabled: ((_f = (_e = (_d = this.config.deps) == null ? void 0 : _d.experimentalOptimizer) == null ? void 0 : _e.ssr) == null ? void 0 : _f.enabled) ?? false
13257
+ enabled: ((_f = (_e = (_d = this.config.deps) == null ? void 0 : _d.optimizer) == null ? void 0 : _e.ssr) == null ? void 0 : _f.enabled) ?? false
13579
13258
  }
13580
13259
  }
13581
13260
  },
@@ -13677,7 +13356,7 @@ class Vitest {
13677
13356
  this.snapshot = new SnapshotManager({ ...resolved.snapshotOptions });
13678
13357
  if (this.config.watch && this.mode !== "typecheck")
13679
13358
  this.registerWatcher();
13680
- this.vitenode = new ViteNodeServer(server, this.config);
13359
+ this.vitenode = new ViteNodeServer(server, this.config.server);
13681
13360
  const node = this.vitenode;
13682
13361
  this.runner = new ViteNodeRunner({
13683
13362
  root: server.config.root,
@@ -13727,6 +13406,12 @@ class Vitest {
13727
13406
  getCoreWorkspaceProject() {
13728
13407
  return this.coreWorkspace || null;
13729
13408
  }
13409
+ getProjectByTaskId(taskId) {
13410
+ var _a;
13411
+ const task = this.state.idMap.get(taskId);
13412
+ const projectName = task.projectName || ((_a = task == null ? void 0 : task.file) == null ? void 0 : _a.projectName);
13413
+ return this.projects.find((p) => p.getName() === projectName) || this.getCoreWorkspaceProject() || this.projects[0];
13414
+ }
13730
13415
  async resolveWorkspace(options, cliOptions) {
13731
13416
  const configDir = this.server.config.configFile ? dirname(this.server.config.configFile) : this.config.root;
13732
13417
  const rootFiles = await promises.readdir(configDir);
@@ -13826,7 +13511,7 @@ class Vitest {
13826
13511
  return Promise.all(this.projects.map((project) => project.typecheck(filters)));
13827
13512
  }
13828
13513
  async start(filters) {
13829
- var _a;
13514
+ var _a, _b;
13830
13515
  if (this.mode === "typecheck") {
13831
13516
  await this.typecheck(filters);
13832
13517
  return;
@@ -13842,32 +13527,40 @@ class Vitest {
13842
13527
  await this.globTestFiles(filters)
13843
13528
  );
13844
13529
  if (!files.length) {
13845
- const exitCode = this.config.passWithNoTests ? 0 : 1;
13846
13530
  await this.reportCoverage(true);
13847
13531
  this.logger.printNoTestFound(filters);
13848
- process.exit(exitCode);
13532
+ if (!this.config.watch || !(this.config.changed || ((_b = this.config.related) == null ? void 0 : _b.length))) {
13533
+ const exitCode = this.config.passWithNoTests ? 0 : 1;
13534
+ process.exit(exitCode);
13535
+ }
13536
+ }
13537
+ this.config.changed = false;
13538
+ this.config.related = void 0;
13539
+ if (files.length) {
13540
+ await this.cache.stats.populateStats(this.config.root, files);
13541
+ await this.runFiles(files);
13849
13542
  }
13850
- await this.cache.stats.populateStats(this.config.root, files);
13851
- await this.runFiles(files);
13852
13543
  await this.reportCoverage(true);
13853
13544
  if (this.config.watch)
13854
13545
  await this.report("onWatcherStart");
13855
13546
  }
13856
- async getTestDependencies(filepath) {
13857
- const deps = /* @__PURE__ */ new Set();
13547
+ async getTestDependencies(filepath, deps = /* @__PURE__ */ new Set()) {
13858
13548
  const addImports = async ([project, filepath2]) => {
13859
- const transformed = await project.vitenode.transformRequest(filepath2);
13549
+ if (deps.has(filepath2))
13550
+ return;
13551
+ const mod = project.server.moduleGraph.getModuleById(filepath2);
13552
+ const transformed = (mod == null ? void 0 : mod.ssrTransformResult) || await project.vitenode.transformRequest(filepath2);
13860
13553
  if (!transformed)
13861
13554
  return;
13862
13555
  const dependencies = [...transformed.deps || [], ...transformed.dynamicDeps || []];
13863
- for (const dep of dependencies) {
13556
+ await Promise.all(dependencies.map(async (dep) => {
13864
13557
  const path = await this.server.pluginContainer.resolveId(dep, filepath2, { ssr: true });
13865
13558
  const fsPath = path && !path.external && path.id.split("?")[0];
13866
13559
  if (fsPath && !fsPath.includes("node_modules") && !deps.has(fsPath) && existsSync(fsPath)) {
13867
13560
  deps.add(fsPath);
13868
13561
  await addImports([project, fsPath]);
13869
13562
  }
13870
- }
13563
+ }));
13871
13564
  };
13872
13565
  await addImports(filepath);
13873
13566
  return deps;
@@ -13891,7 +13584,7 @@ class Vitest {
13891
13584
  const forceRerunTriggers = this.config.forceRerunTriggers;
13892
13585
  if (forceRerunTriggers.length && mm(related, forceRerunTriggers).length)
13893
13586
  return specs;
13894
- if (!related.length)
13587
+ if (!this.config.watch && !related.length)
13895
13588
  return [];
13896
13589
  const testGraphs = await Promise.all(
13897
13590
  specs.map(async (spec) => {
@@ -14027,8 +13720,7 @@ class Vitest {
14027
13720
  }
14028
13721
  getModuleProjects(id) {
14029
13722
  return this.projects.filter((project) => {
14030
- var _a, _b, _c;
14031
- return project.server.moduleGraph.getModuleById(id) || ((_a = project.browser) == null ? void 0 : _a.moduleGraph.getModuleById(id)) || ((_c = (_b = project.browser) == null ? void 0 : _b.moduleGraph.getModulesByFile(id)) == null ? void 0 : _c.size);
13723
+ return project.getModuleById(id);
14032
13724
  });
14033
13725
  }
14034
13726
  unregisterWatcher = noop$1;
@@ -14095,13 +13787,14 @@ class Vitest {
14095
13787
  return [];
14096
13788
  if (mm.isMatch(id, this.config.forceRerunTriggers)) {
14097
13789
  this.state.getFilepaths().forEach((file) => this.changedTests.add(file));
14098
- return [];
13790
+ return [id];
14099
13791
  }
14100
13792
  const projects = this.getModuleProjects(id);
14101
13793
  if (!projects.length)
14102
13794
  return [];
14103
13795
  const files = [];
14104
- for (const { server, browser } of projects) {
13796
+ for (const project of projects) {
13797
+ const { server, browser } = project;
14105
13798
  const mod = server.moduleGraph.getModuleById(id) || (browser == null ? void 0 : browser.moduleGraph.getModuleById(id));
14106
13799
  if (!mod) {
14107
13800
  const mods = browser == null ? void 0 : browser.moduleGraph.getModulesByFile(id);
@@ -14118,7 +13811,7 @@ class Vitest {
14118
13811
  }
14119
13812
  id = normalizeRequestId(id, server.config.base);
14120
13813
  this.invalidates.add(id);
14121
- if (this.state.filesMap.has(id)) {
13814
+ if (this.state.filesMap.has(id) || project.isTestFile(id)) {
14122
13815
  this.changedTests.add(id);
14123
13816
  files.push(id);
14124
13817
  continue;
@@ -14283,6 +13976,10 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
14283
13976
  preTransformRequests: false
14284
13977
  }
14285
13978
  };
13979
+ if (process.platform === "darwin" && process.env.VITE_TEST_WATCHER_DEBUG) {
13980
+ config.server.watch.useFsEvents = false;
13981
+ config.server.watch.usePolling = false;
13982
+ }
14286
13983
  const classNameStrategy = typeof testConfig.css !== "boolean" && ((_c = (_b = testConfig.css) == null ? void 0 : _b.modules) == null ? void 0 : _c.classNameStrategy) || "stable";
14287
13984
  if (classNameStrategy !== "scoped") {
14288
13985
  config.css ?? (config.css = {});
@@ -14294,8 +13991,8 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
14294
13991
  };
14295
13992
  }
14296
13993
  }
14297
- const webOptimizer = resolveOptimizerConfig((_f = (_e = testConfig.deps) == null ? void 0 : _e.experimentalOptimizer) == null ? void 0 : _f.web, viteConfig.optimizeDeps, testConfig);
14298
- const ssrOptimizer = resolveOptimizerConfig((_h = (_g = testConfig.deps) == null ? void 0 : _g.experimentalOptimizer) == null ? void 0 : _h.ssr, (_i = viteConfig.ssr) == null ? void 0 : _i.optimizeDeps, testConfig);
13994
+ const webOptimizer = resolveOptimizerConfig((_f = (_e = testConfig.deps) == null ? void 0 : _e.optimizer) == null ? void 0 : _f.web, viteConfig.optimizeDeps, testConfig);
13995
+ const ssrOptimizer = resolveOptimizerConfig((_h = (_g = testConfig.deps) == null ? void 0 : _g.optimizer) == null ? void 0 : _h.ssr, (_i = viteConfig.ssr) == null ? void 0 : _i.optimizeDeps, testConfig);
14299
13996
  config.cacheDir = webOptimizer.cacheDir || ssrOptimizer.cacheDir || config.cacheDir;
14300
13997
  config.optimizeDeps = webOptimizer.optimizeDeps;
14301
13998
  config.ssr = {
@@ -14332,19 +14029,24 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
14332
14029
  }
14333
14030
  },
14334
14031
  async configureServer(server) {
14032
+ if (options.watch && process.env.VITE_TEST_WATCHER_DEBUG) {
14033
+ server.watcher.on("ready", () => {
14034
+ console.log("[debug] watcher is ready");
14035
+ });
14036
+ }
14335
14037
  try {
14336
14038
  await ctx.setServer(options, server, userConfig);
14337
14039
  if (options.api && options.watch)
14338
- (await import('./chunk-api-setup.8f785c4a.js')).setup(ctx);
14040
+ (await import('./chunk-api-setup.644415c3.js')).setup(ctx);
14339
14041
  } catch (err) {
14340
- await ctx.logger.printError(err, true);
14042
+ await ctx.logger.printError(err, { fullStack: true });
14341
14043
  process.exit(1);
14342
14044
  }
14343
14045
  if (!options.watch)
14344
14046
  await server.watcher.close();
14345
14047
  }
14346
14048
  },
14347
- EnvReplacerPlugin(),
14049
+ SsrReplacerPlugin(),
14348
14050
  GlobalSetupPlugin(ctx, ctx.logger),
14349
14051
  ...CSSEnablerPlugin(ctx),
14350
14052
  CoverageTransform(ctx),
@@ -14357,8 +14059,8 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
14357
14059
  async function createVitest(mode, options, viteOverrides = {}) {
14358
14060
  var _a, _b, _c, _d, _e, _f, _g;
14359
14061
  const ctx = new Vitest(mode);
14360
- const root = resolve$2(options.root || process.cwd());
14361
- const configPath = options.config === false ? false : options.config ? resolve$2(root, options.config) : await findUp(configFiles, { cwd: root });
14062
+ const root = resolve(options.root || process.cwd());
14063
+ const configPath = options.config === false ? false : options.config ? resolve(root, options.config) : await findUp(configFiles, { cwd: root });
14362
14064
  const config = {
14363
14065
  logLevel: "error",
14364
14066
  configFile: configPath,
@@ -14367,7 +14069,7 @@ async function createVitest(mode, options, viteOverrides = {}) {
14367
14069
  plugins: await VitestPlugin(options, ctx)
14368
14070
  };
14369
14071
  const server = await createServer(mergeConfig(config, mergeConfig(viteOverrides, { root: options.root })));
14370
- if (((_a = ctx.config.api) == null ? void 0 : _a.port) || ((_d = (_c = (_b = ctx.config.deps) == null ? void 0 : _b.experimentalOptimizer) == null ? void 0 : _c.web) == null ? void 0 : _d.enabled) || ((_g = (_f = (_e = ctx.config.deps) == null ? void 0 : _e.experimentalOptimizer) == null ? void 0 : _f.ssr) == null ? void 0 : _g.enabled))
14072
+ if (((_a = ctx.config.api) == null ? void 0 : _a.port) || ((_d = (_c = (_b = ctx.config.deps) == null ? void 0 : _b.optimizer) == null ? void 0 : _c.web) == null ? void 0 : _d.enabled) || ((_g = (_f = (_e = ctx.config.deps) == null ? void 0 : _e.optimizer) == null ? void 0 : _f.ssr) == null ? void 0 : _g.enabled))
14371
14073
  await server.listen();
14372
14074
  else
14373
14075
  await server.pluginContainer.buildStart({});
@@ -20761,13 +20463,13 @@ function registerConsoleShortcuts(ctx) {
20761
20463
  }
20762
20464
 
20763
20465
  async function startVitest(mode, cliFilters = [], options = {}, viteOverrides) {
20764
- var _a, _b, _c, _d;
20466
+ var _a;
20765
20467
  process.env.TEST = "true";
20766
20468
  process.env.VITEST = "true";
20767
20469
  (_a = process.env).NODE_ENV ?? (_a.NODE_ENV = options.mode || "test");
20768
20470
  if (options.run)
20769
20471
  options.watch = false;
20770
- const root = resolve$2(options.root || process.cwd());
20472
+ const root = resolve(options.root || process.cwd());
20771
20473
  if (!await ensurePackageInstalled("vite", root)) {
20772
20474
  process.exitCode = 1;
20773
20475
  return;
@@ -20780,14 +20482,14 @@ async function startVitest(mode, cliFilters = [], options = {}, viteOverrides) {
20780
20482
  options.browser = { enabled: true, name: options.browser };
20781
20483
  if (typeof options.browser === "object" && !("enabled" in options.browser))
20782
20484
  options.browser.enabled = true;
20485
+ if ("threads" in options && options.experimentalVmThreads)
20486
+ throw new Error('Cannot use both "threads" (or "no-threads") and "experimentalVmThreads" at the same time.');
20783
20487
  const ctx = await createVitest(mode, options, viteOverrides);
20784
20488
  if (mode === "test" && ctx.config.coverage.enabled) {
20785
20489
  const provider = ctx.config.coverage.provider || "v8";
20786
20490
  const requiredPackages = CoverageProviderMap[provider];
20787
20491
  if (requiredPackages) {
20788
- const defaultProviderInfo = 'Default coverage provider has changed from "c8" to "v8". New package is required to be installed. To use the old deprecated coverage provider use "--coverage.provider c8" option.\nSee https://github.com/vitest-dev/vitest/pull/3339 for more information.\n\n';
20789
- const isUsingDefaultProvider = ((_c = (_b = ctx.server.config.test) == null ? void 0 : _b.coverage) == null ? void 0 : _c.provider) === void 0 && ((_d = options.coverage) == null ? void 0 : _d.provider) === void 0;
20790
- if (!await ensurePackageInstalled(requiredPackages, root, isUsingDefaultProvider ? defaultProviderInfo : void 0)) {
20492
+ if (!await ensurePackageInstalled(requiredPackages, root)) {
20791
20493
  process.exitCode = 1;
20792
20494
  return ctx;
20793
20495
  }
@@ -20813,7 +20515,7 @@ async function startVitest(mode, cliFilters = [], options = {}, viteOverrides) {
20813
20515
  await ctx.start(cliFilters);
20814
20516
  } catch (e) {
20815
20517
  process.exitCode = 1;
20816
- await ctx.logger.printError(e, true, "Unhandled Error");
20518
+ await ctx.logger.printError(e, { fullStack: true, type: "Unhandled Error" });
20817
20519
  ctx.logger.error("\n\n");
20818
20520
  return ctx;
20819
20521
  }