vitest 4.1.0 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/browser.js +3 -3
  2. package/dist/chunks/{base.DM0-RqVb.js → base.C9_VThnT.js} +8 -8
  3. package/dist/chunks/{cac.CWGDZnXT.js → cac.CHfKU_gf.js} +15 -5
  4. package/dist/chunks/{cli-api.DuT9iuvY.js → cli-api.BUXBO6jS.js} +148 -36
  5. package/dist/chunks/{coverage.Bri33R1t.js → coverage.CJ2HXVIG.js} +14 -8
  6. package/dist/chunks/{coverage.D_JHT54q.js → coverage.CTzCuANN.js} +4 -1
  7. package/dist/chunks/{globals.BXNGLnTL.js → globals.8mibwXRO.js} +2 -2
  8. package/dist/chunks/{index.DGNSnENe.js → index.6q6giCZO.js} +2 -2
  9. package/dist/chunks/{index.EY6TCHpo.js → index.DC7d2Pf8.js} +2 -2
  10. package/dist/chunks/{index.DlDSLQD3.js → index.Dkvtd-Ku.js} +1 -1
  11. package/dist/chunks/{init-forks.DeArv0jT.js → init-forks.B4YYSIj4.js} +1 -1
  12. package/dist/chunks/{init-threads.-2OUl4Nn.js → init-threads.Bd2Hsaex.js} +1 -1
  13. package/dist/chunks/{init.DICorXCo.js → init.BVxhC4nR.js} +3 -3
  14. package/dist/chunks/{nativeModuleMocker.DndvSdL6.js → nativeModuleMocker.Dd1Q1VIw.js} +2 -2
  15. package/dist/chunks/{plugin.d.BuW-flqo.d.ts → plugin.d.Dx0ozo6e.d.ts} +1 -1
  16. package/dist/chunks/{reporters.d.DVUYHHhe.d.ts → reporters.d.CZ5E0GCT.d.ts} +49 -26
  17. package/dist/chunks/{setup-common.B41N_kPE.js → setup-common.CB31_KSV.js} +2 -2
  18. package/dist/chunks/{startVitestModuleRunner.C3ZR-4J3.js → startVitestModuleRunner.C3FXk5Gv.js} +3 -3
  19. package/dist/chunks/{test.CTcmp4Su.js → test.CBQUpOM3.js} +2 -1
  20. package/dist/chunks/{traces.CCmnQaNT.js → traces.DT5aQ62U.js} +1 -1
  21. package/dist/chunks/{vm.Dh2rTtmP.js → vm.DId8XBJa.js} +2 -2
  22. package/dist/cli.js +1 -1
  23. package/dist/config.d.ts +3 -3
  24. package/dist/coverage.d.ts +4 -4
  25. package/dist/coverage.js +2 -2
  26. package/dist/environments.js +1 -1
  27. package/dist/index.d.ts +1 -0
  28. package/dist/index.js +2 -2
  29. package/dist/module-evaluator.js +2 -2
  30. package/dist/node.d.ts +3 -3
  31. package/dist/node.js +8 -8
  32. package/dist/reporters.d.ts +1 -1
  33. package/dist/runners.d.ts +2 -1
  34. package/dist/runners.js +1 -1
  35. package/dist/runtime.js +3 -3
  36. package/dist/worker.js +10 -10
  37. package/dist/workers/forks.js +11 -11
  38. package/dist/workers/runVmTests.js +5 -5
  39. package/dist/workers/threads.js +11 -11
  40. package/dist/workers/vmForks.js +6 -6
  41. package/dist/workers/vmThreads.js +6 -6
  42. package/optional-runtime-types.d.ts +6 -0
  43. package/package.json +17 -14
  44. package/dist/chunks/git.Bm2pzPAa.js +0 -71
package/dist/browser.js CHANGED
@@ -1,5 +1,5 @@
1
- export { l as loadDiffConfig, a as loadSnapshotSerializers, s as setupCommonEnv, b as startCoverageInsideWorker, c as stopCoverageInsideWorker, t as takeCoverageInsideWorker } from './chunks/setup-common.B41N_kPE.js';
2
- export { T as Traces } from './chunks/traces.CCmnQaNT.js';
1
+ export { l as loadDiffConfig, a as loadSnapshotSerializers, s as setupCommonEnv, b as startCoverageInsideWorker, c as stopCoverageInsideWorker, t as takeCoverageInsideWorker } from './chunks/setup-common.CB31_KSV.js';
2
+ export { T as Traces } from './chunks/traces.DT5aQ62U.js';
3
3
  export { collectTests, startTests } from '@vitest/runner';
4
4
  import * as spyModule from '@vitest/spy';
5
5
  export { spyModule as SpyModule };
@@ -8,7 +8,7 @@ export { processError } from '@vitest/utils/error';
8
8
  export { getType } from '@vitest/utils/helpers';
9
9
  export { DecodedMap, getOriginalPosition } from '@vitest/utils/source-map';
10
10
  export { getSafeTimers, setSafeTimers } from '@vitest/utils/timers';
11
- import './chunks/coverage.D_JHT54q.js';
11
+ import './chunks/coverage.CTzCuANN.js';
12
12
  import '@vitest/snapshot';
13
13
  import './chunks/utils.BX5Fg8C4.js';
14
14
 
@@ -1,22 +1,22 @@
1
1
  import { runInThisContext } from 'node:vm';
2
2
  import * as spyModule from '@vitest/spy';
3
- import { r as resolveTestRunner, a as resolveSnapshotEnvironment, d as detectAsyncLeaks, s as setupChaiConfig } from './index.DGNSnENe.js';
4
- import { l as loadEnvironment, e as emitModuleRunner, a as listenForErrors } from './init.DICorXCo.js';
3
+ import { r as resolveTestRunner, a as resolveSnapshotEnvironment, d as detectAsyncLeaks, s as setupChaiConfig } from './index.6q6giCZO.js';
4
+ import { l as loadEnvironment, e as emitModuleRunner, a as listenForErrors } from './init.BVxhC4nR.js';
5
5
  import { N as NativeModuleRunner } from './nativeModuleRunner.BIakptoF.js';
6
- import { T as Traces } from './traces.CCmnQaNT.js';
6
+ import { T as Traces } from './traces.DT5aQ62U.js';
7
7
  import { V as VitestEvaluatedModules } from './evaluatedModules.Dg1zASAC.js';
8
- import { s as startVitestModuleRunner, c as createNodeImportMeta } from './startVitestModuleRunner.C3ZR-4J3.js';
8
+ import { s as startVitestModuleRunner, c as createNodeImportMeta } from './startVitestModuleRunner.C3FXk5Gv.js';
9
9
  import { performance as performance$1 } from 'node:perf_hooks';
10
10
  import { startTests, collectTests } from '@vitest/runner';
11
- import { s as setupCommonEnv, b as startCoverageInsideWorker, c as stopCoverageInsideWorker } from './setup-common.B41N_kPE.js';
12
- import { g as globalExpect, v as vi } from './test.CTcmp4Su.js';
11
+ import { s as setupCommonEnv, b as startCoverageInsideWorker, c as stopCoverageInsideWorker } from './setup-common.CB31_KSV.js';
12
+ import { g as globalExpect, v as vi } from './test.CBQUpOM3.js';
13
13
  import { c as closeInspector } from './inspector.CvyFGlXm.js';
14
14
  import { createRequire } from 'node:module';
15
15
  import timers from 'node:timers';
16
16
  import timersPromises from 'node:timers/promises';
17
17
  import util from 'node:util';
18
18
  import { KNOWN_ASSET_TYPES } from '@vitest/utils/constants';
19
- import { i as index } from './index.DlDSLQD3.js';
19
+ import { i as index } from './index.Dkvtd-Ku.js';
20
20
  import { g as getWorkerState, r as resetModules, p as provideWorkerState, a as getSafeWorkerState } from './utils.BX5Fg8C4.js';
21
21
 
22
22
  // this should only be used in Node
@@ -115,7 +115,7 @@ async function startModuleRunner(options) {
115
115
  let mocker;
116
116
  if (options.state.config.experimental.nodeLoader !== false) {
117
117
  // this additionally imports acorn/magic-string
118
- const { NativeModuleMocker } = await import('./nativeModuleMocker.DndvSdL6.js');
118
+ const { NativeModuleMocker } = await import('./nativeModuleMocker.Dd1Q1VIw.js');
119
119
  mocker = new NativeModuleMocker({
120
120
  async resolveId(id, importer) {
121
121
  // TODO: use import.meta.resolve instead
@@ -620,7 +620,7 @@ class CAC extends EventEmitter {
620
620
 
621
621
  const cac = (name = "") => new CAC(name);
622
622
 
623
- var version = "4.1.0";
623
+ var version = "4.1.1";
624
624
 
625
625
  const apiConfig = (port) => ({
626
626
  port: {
@@ -828,6 +828,11 @@ const cliOptionsConfig = {
828
828
  if (value === "false" || value === "no" || value === false) return false;
829
829
  return value;
830
830
  }
831
+ },
832
+ excludeAfterRemap: { description: "Apply exclusions again after coverage has been remapped to original sources. (default: false)" },
833
+ htmlDir: {
834
+ description: "Directory of HTML coverage output to be served in UI mode and HTML reporter.",
835
+ argument: "<path>"
831
836
  }
832
837
  }
833
838
  },
@@ -1167,7 +1172,7 @@ const cliOptionsConfig = {
1167
1172
  description: "Use `bundle` to bundle the config with esbuild or `runner` (experimental) to process it on the fly. This is only available in vite version 6.1.0 and above. (default: `bundle`)",
1168
1173
  argument: "<loader>"
1169
1174
  },
1170
- standalone: { description: "Start Vitest without running tests. Tests will be running only on change. This option is ignored when CLI file filters are passed. (default: `false`)" },
1175
+ standalone: { description: "Start Vitest without running tests. Tests will be running only on change. If browser mode is enabled, the UI will be opened automatically. This option is ignored when CLI file filters are passed. (default: `false`)" },
1171
1176
  mergeReports: {
1172
1177
  description: "Path to a blob reports directory. If this options is used, Vitest won't run any tests, it will only report previously recorded tests",
1173
1178
  argument: "[path]",
@@ -1232,7 +1237,12 @@ const cliOptionsConfig = {
1232
1237
  }
1233
1238
  },
1234
1239
  viteModuleRunner: { description: "Control whether Vitest uses Vite's module runner to run the code or fallback to the native `import`. (default: `true`)" },
1235
- nodeLoader: { description: "Controls whether Vitest will use Node.js Loader API to process in-source or mocked files. This has no effect if `viteModuleRunner` is enabled. Disabling this can increase performance. (default: `true`)" }
1240
+ nodeLoader: { description: "Controls whether Vitest will use Node.js Loader API to process in-source or mocked files. This has no effect if `viteModuleRunner` is enabled. Disabling this can increase performance. (default: `true`)" },
1241
+ vcsProvider: {
1242
+ argument: "<path>",
1243
+ description: "Custom provider for detecting changed files. (default: `git`)",
1244
+ subcommands: null
1245
+ }
1236
1246
  }
1237
1247
  },
1238
1248
  cliExclude: null,
@@ -2312,7 +2322,7 @@ function normalizeCliOptions(cliFilters, argv) {
2312
2322
  }
2313
2323
  async function start(mode, cliFilters, options) {
2314
2324
  try {
2315
- const { startVitest } = await import('./cli-api.DuT9iuvY.js').then(function (n) { return n.q; });
2325
+ const { startVitest } = await import('./cli-api.BUXBO6jS.js').then(function (n) { return n.q; });
2316
2326
  const ctx = await startVitest(mode, cliFilters.map(normalize), normalizeCliOptions(cliFilters, options));
2317
2327
  if (!ctx.shouldKeepServer()) await ctx.exit();
2318
2328
  } catch (e) {
@@ -2334,7 +2344,7 @@ async function init(project) {
2334
2344
  }
2335
2345
  async function collect(mode, cliFilters, options) {
2336
2346
  try {
2337
- const { prepareVitest, processCollected, outputFileList } = await import('./cli-api.DuT9iuvY.js').then(function (n) { return n.q; });
2347
+ const { prepareVitest, processCollected, outputFileList } = await import('./cli-api.BUXBO6jS.js').then(function (n) { return n.q; });
2338
2348
  const ctx = await prepareVitest(mode, {
2339
2349
  ...normalizeCliOptions(cliFilters, options),
2340
2350
  watch: false,
@@ -1,6 +1,6 @@
1
1
  import fs, { promises, existsSync, mkdirSync, readFileSync, statSync, readdirSync, writeFileSync } from 'node:fs';
2
2
  import { relative, resolve, dirname, join, extname, normalize, basename, isAbsolute } from 'pathe';
3
- import { C as CoverageProviderMap } from './coverage.D_JHT54q.js';
3
+ import { C as CoverageProviderMap } from './coverage.CTzCuANN.js';
4
4
  import path, { resolve as resolve$1 } from 'node:path';
5
5
  import { unique, createDefer, slash, withTrailingSlash, cleanUrl, wrapId, isExternalUrl, unwrapId, toArray, noop, deepMerge, nanoid, deepClone, isPrimitive, notNullish } from '@vitest/utils/helpers';
6
6
  import { a as any, p as prompt } from './index.og1WyBLx.js';
@@ -13,13 +13,13 @@ import nodeos__default, { tmpdir } from 'node:os';
13
13
  import { generateHash as generateHash$1, createTaskName, validateTags, calculateSuiteHash, someTasksAreOnly, interpretTaskModes, hasFailed, generateFileHash, limitConcurrency, createFileTask as createFileTask$1, getTasks, isTestCase } from '@vitest/runner/utils';
14
14
  import { SnapshotManager } from '@vitest/snapshot/manager';
15
15
  import { serializeValue } from '@vitest/utils/serialize';
16
- import { v as version$1 } from './cac.CWGDZnXT.js';
16
+ import { v as version$1 } from './cac.CHfKU_gf.js';
17
17
  import { rootDir, distDir } from '../path.js';
18
18
  import { d as createIndexLocationsMap, e as TraceMap, o as originalPositionFor, h as ancestor, i as stringify, p as parse, j as printError, f as formatProjectName, w as withLabel, k as errorBanner, l as divider, m as Typechecker, n as generateCodeFrame, q as escapeRegExp, r as createDefinesScript, R as ReportersMap, u as groupBy, B as BlobReporter, v as readBlobs, x as convertTasksToEvents, H as HangingProcessReporter, y as wildcardPatternToRegExp, z as stdout } from './index.DXMFO5MJ.js';
19
19
  import { N as NativeModuleRunner } from './nativeModuleRunner.BIakptoF.js';
20
- import { T as Traces } from './traces.CCmnQaNT.js';
20
+ import { T as Traces } from './traces.DT5aQ62U.js';
21
21
  import { createDebug } from 'obug';
22
- import { h as hash, R as RandomSequencer, i as isBrowserEnabled, r as resolveConfig, g as getCoverageProvider, b as resolveApiServerConfig } from './coverage.Bri33R1t.js';
22
+ import { h as hash, R as RandomSequencer, i as isBrowserEnabled, r as resolveConfig, g as getCoverageProvider, b as resolveApiServerConfig } from './coverage.CJ2HXVIG.js';
23
23
  import { rm, readFile, writeFile, rename, stat, unlink, mkdir, copyFile } from 'node:fs/promises';
24
24
  import c from 'tinyrainbow';
25
25
  import { VitestModuleEvaluator } from '#module-evaluator';
@@ -59,6 +59,7 @@ import { a as BenchmarkReportsMap } from './index.CEzQDJGb.js';
59
59
  import assert$1 from 'node:assert';
60
60
  import { parseErrorStacktrace } from '@vitest/utils/source-map';
61
61
  import { extractSourcemapFromFile } from '@vitest/utils/source-map/node';
62
+ import { x } from 'tinyexec';
62
63
  import readline from 'node:readline';
63
64
  import { stripVTControlCharacters } from 'node:util';
64
65
 
@@ -178,6 +179,8 @@ function astParseFile(filepath, code) {
178
179
  "scoped",
179
180
  "override"
180
181
  ].includes(property)) return;
182
+ // skip properties on return values of calls - e.g., test('name', fn).skip()
183
+ if (callee.type === "MemberExpression" && callee.object?.type === "CallExpression") return;
181
184
  // derive mode from the full chain (handles any order like .skip.concurrent or .concurrent.skip)
182
185
  let mode = "run";
183
186
  for (const prop of properties) if (prop === "skip" || prop === "only" || prop === "todo") mode = prop;
@@ -455,7 +458,7 @@ class BrowserSessions {
455
458
  this.sessions.delete(sessionId);
456
459
  }
457
460
  createSession(sessionId, project, pool) {
458
- // this promise only waits for the WS connection with the orhcestrator to be established
461
+ // this promise only waits for the WS connection with the orchestrator to be established
459
462
  const defer = createDefer();
460
463
  const timeout = setTimeout(() => {
461
464
  defer.reject(/* @__PURE__ */ new Error(`Failed to connect to the browser session "${sessionId}" [${project.name}] within the timeout.`));
@@ -1990,7 +1993,7 @@ class Logger {
1990
1993
  this.log(PAD + c.dim(c.green(`API started at ${new URL("/", origin)}`)));
1991
1994
  }
1992
1995
  if (this.ctx.coverageProvider) this.log(PAD + c.dim("Coverage enabled with ") + c.yellow(this.ctx.coverageProvider.name));
1993
- if (this.ctx.config.standalone) this.log(c.yellow(`\nVitest is running in standalone mode. Edit a test file to rerun tests.`));
1996
+ if (this.ctx.config.standalone) this.log(c.yellow(`\nVitest is running in standalone mode. Edit a test file to rerun tests.\n`));
1994
1997
  else this.log();
1995
1998
  }
1996
1999
  printBrowserBanner(project) {
@@ -2393,13 +2396,7 @@ function createBrowserPool(vitest) {
2393
2396
  const ensurePool = (project) => {
2394
2397
  if (projectPools.has(project)) return projectPools.get(project);
2395
2398
  debug?.("creating pool for project %s", project.name);
2396
- const resolvedUrls = project.browser.vite.resolvedUrls;
2397
- const origin = resolvedUrls?.local[0] ?? resolvedUrls?.network[0];
2398
- if (!origin) throw new Error(`Can't find browser origin URL for project "${project.name}"`);
2399
- const pool = new BrowserPool(project, {
2400
- maxWorkers: getThreadsCount(project),
2401
- origin
2402
- });
2399
+ const pool = new BrowserPool(project, { maxWorkers: getThreadsCount(project) });
2403
2400
  projectPools.set(project, pool);
2404
2401
  vitest.onCancel(() => {
2405
2402
  pool.cancel();
@@ -2498,7 +2495,7 @@ class BrowserPool {
2498
2495
  _queue = [];
2499
2496
  _promise;
2500
2497
  _providedContext;
2501
- readySessions = /* @__PURE__ */ new Set();
2498
+ readySessions;
2502
2499
  _traces;
2503
2500
  _otel;
2504
2501
  constructor(project, options) {
@@ -2510,6 +2507,7 @@ class BrowserPool {
2510
2507
  "vitest.project": project.name,
2511
2508
  "vitest.browser.provider": this.project.browser.provider.name
2512
2509
  });
2510
+ this.readySessions = project._browserReadySessions;
2513
2511
  }
2514
2512
  cancel() {
2515
2513
  this._queue = [];
@@ -2566,14 +2564,10 @@ class BrowserPool {
2566
2564
  return this._promise;
2567
2565
  }
2568
2566
  async openPage(sessionId, options) {
2569
- const sessionPromise = this.project.vitest._browserSessions.createSession(sessionId, this.project, this);
2570
- const browser = this.project.browser;
2571
- const url = new URL("/__vitest_test__/", this.options.origin);
2572
- url.searchParams.set("sessionId", sessionId);
2573
- const otelCarrier = this._traces.getContextCarrier();
2574
- if (otelCarrier) url.searchParams.set("otelCarrier", JSON.stringify(otelCarrier));
2575
- const pagePromise = browser.provider.openPage(sessionId, url.toString(), options);
2576
- await Promise.all([sessionPromise, pagePromise]);
2567
+ await this.project._openBrowserPage(sessionId, {
2568
+ reject: (error) => this.reject(error),
2569
+ parallel: options.parallel
2570
+ });
2577
2571
  }
2578
2572
  getOrchestrator(sessionId) {
2579
2573
  const orchestrator = this.orchestrators.get(sessionId);
@@ -9007,7 +9001,7 @@ function setup(ctx, _server) {
9007
9001
  try {
9008
9002
  result.source = result.source || (moduleNode.file ? await promises.readFile(moduleNode.file, "utf-8") : void 0);
9009
9003
  } catch {}
9010
- // TODO: store this in HTML reporter separetly
9004
+ // TODO: store this in HTML reporter separately
9011
9005
  const transformDuration = ctx.state.metadata[projectName]?.duration[moduleNode.url]?.[0];
9012
9006
  if (transformDuration != null) result.transformTime = transformDuration;
9013
9007
  try {
@@ -10611,7 +10605,8 @@ class TestProject {
10611
10605
  /** @internal */ _resolver;
10612
10606
  /** @internal */ _fetcher;
10613
10607
  /** @internal */ _serializedDefines;
10614
- /** @inetrnal */ testFilesList = null;
10608
+ /** @internal */ testFilesList = null;
10609
+ /** @internal */ _browserReadySessions = /* @__PURE__ */ new Set();
10615
10610
  runner;
10616
10611
  closingPromise;
10617
10612
  typecheckFilesList = null;
@@ -10942,6 +10937,32 @@ class TestProject {
10942
10937
  _getViteEnvironments() {
10943
10938
  return [...Object.values(this.browser?.vite.environments || {}), ...Object.values(this.vite.environments || {})];
10944
10939
  }
10940
+ /** @internal */
10941
+ async _openBrowserPage(sessionId, pool) {
10942
+ if (!this.browser) throw new Error(`browser is not initialized`);
10943
+ const resolvedUrls = this.browser.vite.resolvedUrls;
10944
+ const origin = resolvedUrls?.local[0] ?? resolvedUrls?.network[0];
10945
+ if (!origin) throw new Error(`Can't find browser origin URL for project "${this.name}"`);
10946
+ const url = new URL("/__vitest_test__/", origin);
10947
+ url.searchParams.set("sessionId", sessionId);
10948
+ const otelCarrier = this.vitest._traces.getContextCarrier();
10949
+ if (otelCarrier) url.searchParams.set("otelCarrier", JSON.stringify(otelCarrier));
10950
+ this.vitest._browserSessions.sessionIds.add(sessionId);
10951
+ const sessionPromise = this.vitest._browserSessions.createSession(sessionId, this, pool);
10952
+ const pagePromise = this.browser.provider.openPage(sessionId, url.toString(), { parallel: pool.parallel ?? false });
10953
+ await Promise.all([sessionPromise, pagePromise]);
10954
+ }
10955
+ /** @internal */
10956
+ async _standalone() {
10957
+ if (!this.isBrowserEnabled()) return;
10958
+ await this._initBrowserProvider();
10959
+ if (!this.browser) return;
10960
+ const sessionId = crypto.randomUUID();
10961
+ await this._openBrowserPage(sessionId, { reject: (error) => {
10962
+ this.vitest.state.catchError(error, "Browser Error");
10963
+ } });
10964
+ this._browserReadySessions.add(sessionId);
10965
+ }
10945
10966
  _serializeOverriddenConfig() {
10946
10967
  // TODO: serialize the config _once_ or when needed
10947
10968
  const config = serializeConfig(this);
@@ -11438,12 +11459,10 @@ class VitestSpecifications {
11438
11459
  }
11439
11460
  async filterTestsBySource(specs) {
11440
11461
  if (this.vitest.config.changed && !this.vitest.config.related) {
11441
- const { VitestGit } = await import('./git.Bm2pzPAa.js');
11442
- const related = await new VitestGit(this.vitest.config.root).findChangedFiles({ changedSince: this.vitest.config.changed });
11443
- if (!related) {
11444
- process.exitCode = 1;
11445
- throw new GitNotFoundError();
11446
- }
11462
+ const related = await this.vitest.vcs.findChangedFiles({
11463
+ root: this.vitest.config.root,
11464
+ changedSince: this.vitest.config.changed
11465
+ });
11447
11466
  this.vitest.config.related = Array.from(new Set(related));
11448
11467
  }
11449
11468
  const related = this.vitest.config.related;
@@ -12028,7 +12047,7 @@ class StateManager {
12028
12047
  return Array.from(this.idMap.values()).filter((t) => t.result?.state === "fail").length;
12029
12048
  }
12030
12049
  cancelFiles(files, project) {
12031
- // if we don't filter existing modules, they will be overriden by `collectFiles`
12050
+ // if we don't filter existing modules, they will be overridden by `collectFiles`
12032
12051
  const nonRegisteredFiles = files.filter(({ filepath }) => {
12033
12052
  const id = generateFileHash(relative(project.config.root, filepath), project.name);
12034
12053
  return !this.idMap.has(id);
@@ -12674,6 +12693,83 @@ function sanitizeFilePath(s) {
12674
12693
  return s.replace(/[\x00-\x2C\x2E\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+/g, "-");
12675
12694
  }
12676
12695
 
12696
+ class GitVCSProvider {
12697
+ root;
12698
+ async resolveFilesWithGitCommand(args) {
12699
+ let result;
12700
+ try {
12701
+ result = await x("git", args, { nodeOptions: { cwd: this.root } });
12702
+ } catch (e) {
12703
+ e.message = e.stderr;
12704
+ throw e;
12705
+ }
12706
+ return result.stdout.split("\n").filter((s) => s !== "").map((changedPath) => resolve(this.root, changedPath));
12707
+ }
12708
+ async findChangedFiles(options) {
12709
+ const root = this.root || await this.getRoot(options.root);
12710
+ if (!root) throw new GitNotFoundError();
12711
+ this.root = root;
12712
+ const changedSince = options.changedSince;
12713
+ if (typeof changedSince === "string") {
12714
+ const [committed, staged, unstaged] = await Promise.all([
12715
+ this.getFilesSince(changedSince),
12716
+ this.getStagedFiles(),
12717
+ this.getUnstagedFiles()
12718
+ ]);
12719
+ return [
12720
+ ...committed,
12721
+ ...staged,
12722
+ ...unstaged
12723
+ ];
12724
+ }
12725
+ const [staged, unstaged] = await Promise.all([this.getStagedFiles(), this.getUnstagedFiles()]);
12726
+ return [...staged, ...unstaged];
12727
+ }
12728
+ getFilesSince(hash) {
12729
+ return this.resolveFilesWithGitCommand([
12730
+ "diff",
12731
+ "--name-only",
12732
+ `${hash}...HEAD`
12733
+ ]);
12734
+ }
12735
+ getStagedFiles() {
12736
+ return this.resolveFilesWithGitCommand([
12737
+ "diff",
12738
+ "--cached",
12739
+ "--name-only"
12740
+ ]);
12741
+ }
12742
+ getUnstagedFiles() {
12743
+ return this.resolveFilesWithGitCommand([
12744
+ "ls-files",
12745
+ "--other",
12746
+ "--modified",
12747
+ "--exclude-standard"
12748
+ ]);
12749
+ }
12750
+ async getRoot(cwd) {
12751
+ const args = ["rev-parse", "--show-cdup"];
12752
+ try {
12753
+ return resolve(cwd, (await x("git", args, { nodeOptions: { cwd } })).stdout.trim());
12754
+ } catch {
12755
+ return null;
12756
+ }
12757
+ }
12758
+ }
12759
+
12760
+ async function loadVCSProvider(runner, vcsProvider) {
12761
+ if (typeof vcsProvider === "object" && vcsProvider != null) return wrapVCSProvider(vcsProvider);
12762
+ if (!vcsProvider || vcsProvider === "git") return new GitVCSProvider();
12763
+ const module = await runner.import(vcsProvider);
12764
+ if (!module.default || typeof module.default !== "object" || typeof module.default.findChangedFiles !== "function") throw new Error(`The vcsProvider module '${vcsProvider}' doesn't have a default export with \`findChangedFiles\` method.`);
12765
+ return wrapVCSProvider(module.default);
12766
+ }
12767
+ function wrapVCSProvider(provider) {
12768
+ return { async findChangedFiles(options) {
12769
+ return (await provider.findChangedFiles(options)).map((file) => resolve(options.root, file));
12770
+ } };
12771
+ }
12772
+
12677
12773
  class VitestWatcher {
12678
12774
  /**
12679
12775
  * Modules that will be invalidated on the next run.
@@ -12874,6 +12970,13 @@ class Vitest {
12874
12970
  * Vitest behaviour.
12875
12971
  */
12876
12972
  watcher;
12973
+ /**
12974
+ * The version control system provider used to detect changed files.
12975
+ * This is used with the `--changed` flag to determine which test files to run.
12976
+ * By default, Vitest uses Git. You can provide a custom implementation via
12977
+ * `experimental.vcsProvider` in your config.
12978
+ */
12979
+ vcs;
12877
12980
  /** @internal */ configOverride = {};
12878
12981
  /** @internal */ filenamePattern;
12879
12982
  /** @internal */ runningPromise;
@@ -12995,6 +13098,7 @@ class Vitest {
12995
13098
  configurable: true
12996
13099
  });
12997
13100
  }
13101
+ this.vcs = await loadVCSProvider(this.runner, resolved.experimental.vcsProvider);
12998
13102
  if (this.config.watch) {
12999
13103
  // hijack server restart
13000
13104
  const serverRestart = server.restart;
@@ -13342,10 +13446,17 @@ class Vitest {
13342
13446
  });
13343
13447
  }
13344
13448
  /**
13449
+ * @deprecated use `standalone()` instead
13450
+ */
13451
+ init() {
13452
+ this.logger.deprecate("`vitest.init()` is deprecated. Use `vitest.standalone()` instead.");
13453
+ return this.standalone();
13454
+ }
13455
+ /**
13345
13456
  * Initialize reporters and the coverage provider. This method doesn't run any tests.
13346
13457
  * If the `--watch` flag is provided, Vitest will still run changed tests even if this method was not called.
13347
13458
  */
13348
- async init() {
13459
+ async standalone() {
13349
13460
  await this._traces.$("vitest.init", async () => {
13350
13461
  try {
13351
13462
  await this.initCoverageProvider();
@@ -13355,6 +13466,7 @@ class Vitest {
13355
13466
  }
13356
13467
  // populate test files cache so watch mode can trigger a file rerun
13357
13468
  await this.globTestSpecifications();
13469
+ await Promise.all(this.projects.map((project) => project._standalone()));
13358
13470
  if (this.config.watch) await this.report("onWatcherStart");
13359
13471
  });
13360
13472
  }
@@ -14173,8 +14285,8 @@ ${c.dim(` ...and ${remainingResultCount} more ${remainingResultCount === 1 ? "
14173
14285
  if (this.stdin.isTTY) this.stdin.setRawMode(false);
14174
14286
  }
14175
14287
  restoreCursor() {
14176
- const cursortPos = this.keywordOffset() + (this.currentKeyword?.length || 0);
14177
- this.write(`${ESC}${cursortPos}G`);
14288
+ const cursorPos = this.keywordOffset() + (this.currentKeyword?.length || 0);
14289
+ this.write(`${ESC}${cursorPos}G`);
14178
14290
  }
14179
14291
  write(data) {
14180
14292
  this.stdout.write(data);
@@ -14369,14 +14481,14 @@ async function startVitest(mode, cliFilters = [], options = {}, viteOverrides, v
14369
14481
  let stdinCleanup;
14370
14482
  if (stdin.isTTY && ctx.config.watch) stdinCleanup = registerConsoleShortcuts(ctx, stdin, stdout);
14371
14483
  ctx.onAfterSetServer(() => {
14372
- if (ctx.config.standalone) ctx.init();
14484
+ if (ctx.config.standalone) ctx.standalone();
14373
14485
  else ctx.start(cliFilters);
14374
14486
  });
14375
14487
  try {
14376
14488
  if (ctx.config.listTags) await ctx.listTags();
14377
14489
  else if (ctx.config.clearCache) await ctx.experimental_clearCache();
14378
14490
  else if (ctx.config.mergeReports) await ctx.mergeReports();
14379
- else if (ctx.config.standalone) await ctx.init();
14491
+ else if (ctx.config.standalone) await ctx.standalone();
14380
14492
  else await ctx.start(cliFilters);
14381
14493
  return ctx;
14382
14494
  } catch (e) {
@@ -15,7 +15,7 @@ import { c as configFiles, d as defaultBrowserPort, a as defaultInspectPort, b a
15
15
  import './env.D4Lgay0q.js';
16
16
  import nodeos__default from 'node:os';
17
17
  import { isCI, isAgent, provider } from 'std-env';
18
- import { r as resolveCoverageProviderModule } from './coverage.D_JHT54q.js';
18
+ import { r as resolveCoverageProviderModule } from './coverage.CTzCuANN.js';
19
19
 
20
20
  const hash = crypto.hash ?? ((algorithm, data, outputEncoding) => crypto.createHash(algorithm).update(data).digest(outputEncoding));
21
21
 
@@ -30,7 +30,7 @@ class BaseSequencer {
30
30
  constructor(ctx) {
31
31
  this.ctx = ctx;
32
32
  }
33
- // async so it can be extended by other sequelizers
33
+ // async so it can be extended by other sequencers
34
34
  async shard(files) {
35
35
  const { config } = this.ctx;
36
36
  const { index, count } = config.shard;
@@ -43,7 +43,7 @@ class BaseSequencer {
43
43
  };
44
44
  }).sort((a, b) => a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0).slice(shardStart, shardEnd).map(({ spec }) => spec);
45
45
  }
46
- // async so it can be extended by other sequelizers
46
+ // async so it can be extended by other sequencers
47
47
  async sort(files) {
48
48
  const cache = this.ctx.cache;
49
49
  return [...files].sort((a, b) => {
@@ -317,7 +317,7 @@ function resolveConfig$1(vitest, options, viteConfig) {
317
317
  resolved.deps.web.transformGlobPattern ??= [];
318
318
  resolved.setupFiles = toArray(resolved.setupFiles || []).map((file) => resolvePath(file, resolved.root));
319
319
  resolved.globalSetup = toArray(resolved.globalSetup || []).map((file) => resolvePath(file, resolved.root));
320
- // Add hard-coded default coverage exclusions. These cannot be overidden by user config.
320
+ // Add hard-coded default coverage exclusions. These cannot be overridden by user config.
321
321
  // Override original exclude array for cases where user re-uses same object in test.exclude.
322
322
  resolved.coverage.exclude = [
323
323
  ...resolved.coverage.exclude,
@@ -534,6 +534,7 @@ function resolveConfig$1(vitest, options, viteConfig) {
534
534
  resolved.experimental.importDurations.thresholds ??= {};
535
535
  resolved.experimental.importDurations.thresholds.warn ??= 100;
536
536
  resolved.experimental.importDurations.thresholds.danger ??= 500;
537
+ if (typeof resolved.experimental.vcsProvider === "string" && resolved.experimental.vcsProvider !== "git") resolved.experimental.vcsProvider = resolvePath(resolved.experimental.vcsProvider, resolved.root);
537
538
  return resolved;
538
539
  }
539
540
  function isBrowserEnabled(config) {
@@ -744,10 +745,15 @@ Update your dependencies and make sure the versions match.`));
744
745
  if (readdirSync(this.options.reportsDirectory).length === 0) await promises.rm(this.options.reportsDirectory, { recursive: true });
745
746
  }
746
747
  async onTestRunStart() {
747
- if (this.options.changed) {
748
- const { VitestGit } = await import('./git.Bm2pzPAa.js');
749
- this.changedFiles = await new VitestGit(this.ctx.config.root).findChangedFiles({ changedSince: this.options.changed }) ?? void 0;
750
- } else if (this.ctx.config.changed) this.changedFiles = this.ctx.config.related;
748
+ if (this.options.changed) try {
749
+ this.changedFiles = await this.ctx.vcs.findChangedFiles({
750
+ root: this.ctx.config.root,
751
+ changedSince: this.options.changed
752
+ });
753
+ } catch {
754
+ this.changedFiles = void 0;
755
+ }
756
+ else if (this.ctx.config.changed) this.changedFiles = this.ctx.config.related;
751
757
  if (this.changedFiles) this.globCache.clear();
752
758
  }
753
759
  async onTestFailure() {
@@ -8,7 +8,10 @@ async function resolveCoverageProviderModule(options, loader) {
8
8
  if (provider === "v8" || provider === "istanbul") {
9
9
  let builtInModule = CoverageProviderMap[provider];
10
10
  if (provider === "v8" && loader.isBrowser) builtInModule += "/browser";
11
- const { default: coverageModule } = await loader.import(builtInModule);
11
+ const { default: coverageModule } = loader.isBrowser ? await loader.import(builtInModule) : await import(
12
+ /* @vite-ignore */
13
+ builtInModule
14
+ );
12
15
  if (!coverageModule) throw new Error(`Failed to load ${CoverageProviderMap[provider]}. Default export is missing.`);
13
16
  return coverageModule;
14
17
  }
@@ -1,6 +1,6 @@
1
1
  import { g as globalApis } from './constants.CPYnjOGj.js';
2
- import { i as index } from './index.DlDSLQD3.js';
3
- import './test.CTcmp4Su.js';
2
+ import { i as index } from './index.Dkvtd-Ku.js';
3
+ import './test.CBQUpOM3.js';
4
4
  import '@vitest/runner';
5
5
  import '@vitest/utils/helpers';
6
6
  import '@vitest/utils/timers';
@@ -1,9 +1,9 @@
1
1
  import { chai } from '@vitest/expect';
2
2
  import { createHook } from 'node:async_hooks';
3
- import { l as loadDiffConfig, a as loadSnapshotSerializers, t as takeCoverageInsideWorker } from './setup-common.B41N_kPE.js';
3
+ import { l as loadDiffConfig, a as loadSnapshotSerializers, t as takeCoverageInsideWorker } from './setup-common.CB31_KSV.js';
4
4
  import { r as rpc } from './rpc.MzXet3jl.js';
5
5
  import { g as getWorkerState } from './utils.BX5Fg8C4.js';
6
- import { T as TestRunner, N as NodeBenchmarkRunner } from './test.CTcmp4Su.js';
6
+ import { T as TestRunner, N as NodeBenchmarkRunner } from './test.CBQUpOM3.js';
7
7
 
8
8
  function setupChaiConfig(config) {
9
9
  Object.assign(chai.config, config);
@@ -254,11 +254,11 @@ function populateGlobal(global, win, options = {}) {
254
254
  const { bindFunctions = false } = options;
255
255
  const keys = getWindowKeys(global, win, options.additionalKeys);
256
256
  const originals = /* @__PURE__ */ new Map();
257
- const overridenKeys = new Set([...KEYS, ...options.additionalKeys || []]);
257
+ const overriddenKeys = new Set([...KEYS, ...options.additionalKeys || []]);
258
258
  const overrideObject = /* @__PURE__ */ new Map();
259
259
  for (const key of keys) {
260
260
  const boundFunction = bindFunctions && typeof win[key] === "function" && !isClassLikeName(key) && win[key].bind(win);
261
- if (overridenKeys.has(key) && key in global) originals.set(key, global[key]);
261
+ if (overriddenKeys.has(key) && key in global) originals.set(key, global[key]);
262
262
  Object.defineProperty(global, key, {
263
263
  get() {
264
264
  if (overrideObject.has(key)) return overrideObject.get(key);
@@ -1,4 +1,4 @@
1
- import { v as vi, N as NodeBenchmarkRunner, T as TestRunner, a as assert, c as createExpect, g as globalExpect, i as inject, s as should, b as vitest } from './test.CTcmp4Su.js';
1
+ import { v as vi, N as NodeBenchmarkRunner, T as TestRunner, a as assert, c as createExpect, g as globalExpect, i as inject, s as should, b as vitest } from './test.CBQUpOM3.js';
2
2
  import { b as bench } from './benchmark.D0SlKNbZ.js';
3
3
  import { V as VitestEvaluatedModules } from './evaluatedModules.Dg1zASAC.js';
4
4
  import { expectTypeOf } from 'expect-type';
@@ -1,4 +1,4 @@
1
- import { i as init } from './init.DICorXCo.js';
1
+ import { i as init } from './init.BVxhC4nR.js';
2
2
 
3
3
  if (!process.send) throw new Error("Expected worker to be run in node:child_process");
4
4
  // Store globals in case tests overwrite them
@@ -1,5 +1,5 @@
1
1
  import { isMainThread, parentPort } from 'node:worker_threads';
2
- import { i as init } from './init.DICorXCo.js';
2
+ import { i as init } from './init.BVxhC4nR.js';
3
3
 
4
4
  if (isMainThread || !parentPort) throw new Error("Expected worker to be run in node:worker_threads");
5
5
  function workerInit(options) {
@@ -3,11 +3,11 @@ import { isBuiltin } from 'node:module';
3
3
  import { pathToFileURL } from 'node:url';
4
4
  import { resolve } from 'pathe';
5
5
  import { ModuleRunner, EvaluatedModules } from 'vite/module-runner';
6
- import { b as VitestTransport } from './startVitestModuleRunner.C3ZR-4J3.js';
7
- import { e as environments } from './index.EY6TCHpo.js';
6
+ import { b as VitestTransport } from './startVitestModuleRunner.C3FXk5Gv.js';
7
+ import { e as environments } from './index.DC7d2Pf8.js';
8
8
  import { serializeValue } from '@vitest/utils/serialize';
9
9
  import { serializeError } from '@vitest/utils/error';
10
- import { T as Traces } from './traces.CCmnQaNT.js';
10
+ import { T as Traces } from './traces.DT5aQ62U.js';
11
11
  import { o as onCancel, a as rpcDone, c as createRuntimeRpc } from './rpc.MzXet3jl.js';
12
12
  import { createStackString, parseStacktrace } from '@vitest/utils/source-map';
13
13
  import { s as setupInspect } from './inspector.CvyFGlXm.js';
@@ -5,7 +5,7 @@ import { cleanUrl, createDefer } from '@vitest/utils/helpers';
5
5
  import { p as parse } from './acorn.B2iPLyUM.js';
6
6
  import { isAbsolute } from 'pathe';
7
7
  import { t as toBuiltin } from './modules.BJuCwlRJ.js';
8
- import { B as BareModuleMocker, n as normalizeModuleId } from './startVitestModuleRunner.C3ZR-4J3.js';
8
+ import { B as BareModuleMocker, n as normalizeModuleId } from './startVitestModuleRunner.C3FXk5Gv.js';
9
9
  import 'node:fs';
10
10
  import './utils.BX5Fg8C4.js';
11
11
  import '@vitest/utils/timers';
@@ -14,7 +14,7 @@ import 'node:path';
14
14
  import '../module-evaluator.js';
15
15
  import 'node:vm';
16
16
  import 'vite/module-runner';
17
- import './traces.CCmnQaNT.js';
17
+ import './traces.DT5aQ62U.js';
18
18
  import '@vitest/mocker';
19
19
  import '@vitest/mocker/redirect';
20
20
 
@@ -1,5 +1,5 @@
1
1
  import { DevEnvironment } from 'vite';
2
- import { V as Vitest, T as TestProject, a as TestProjectConfiguration } from './reporters.d.DVUYHHhe.js';
2
+ import { V as Vitest, T as TestProject, a as TestProjectConfiguration } from './reporters.d.CZ5E0GCT.js';
3
3
 
4
4
  /**
5
5
  * Generate a unique cache identifier.