This commit is contained in:
2026-08-14 16:03:47 +01:00
parent fd53e3f4fb
commit dfdc3b2840
2463 changed files with 186456 additions and 111315 deletions
+4 -3
View File
@@ -1,7 +1,7 @@
import { a as SerializedCoverageConfig, S as SerializedConfig } from './chunks/config.d.Cy95HiCx.js';
import { a as SerializedCoverageConfig, S as SerializedConfig } from './chunks/config.d.A1h_Y6Jt.js';
import { R as RuntimeCoverageModuleLoader } from './chunks/coverage.d.BZtK59WP.js';
import { SerializedDiffOptions } from '@vitest/utils/diff';
export { O as OTELCarrier, T as Traces } from './chunks/traces.d.402V_yFI.js';
export { O as OTELCarrier, T as Traces } from './chunks/traces.d.D2T_R8rx.js';
export { collectTests, startTests } from '@vitest/runner';
import * as _vitest_spy from '@vitest/spy';
export { _vitest_spy as SpyModule };
@@ -41,6 +41,7 @@ interface BrowserCommands {
})) => Promise<void>;
removeFile: (path: string) => Promise<void>;
}
interface CDPSession {}
export { loadDiffConfig, loadSnapshotSerializers, setupCommonEnv, startCoverageInsideWorker, stopCoverageInsideWorker, takeCoverageInsideWorker };
export type { BrowserCommands, FsOptions };
export type { BrowserCommands, CDPSession, FsOptions };
+4 -4
View File
@@ -1,5 +1,5 @@
export { l as loadDiffConfig, b as loadSnapshotSerializers, c as setupCommonEnv, s as startCoverageInsideWorker, a as stopCoverageInsideWorker, t as takeCoverageInsideWorker } from './chunks/setup-common.Cm-kSBVi.js';
export { T as Traces } from './chunks/traces.CCmnQaNT.js';
export { l as loadDiffConfig, a as loadSnapshotSerializers, s as setupCommonEnv, b as startCoverageInsideWorker, c as stopCoverageInsideWorker, t as takeCoverageInsideWorker } from './chunks/setup-common.DYx3LtFI.js';
export { T as Traces } from './chunks/traces.DT5aQ62U.js';
export { collectTests, startTests } from '@vitest/runner';
import * as spyModule from '@vitest/spy';
export { spyModule as SpyModule };
@@ -8,9 +8,9 @@ export { processError } from '@vitest/utils/error';
export { getType } from '@vitest/utils/helpers';
export { DecodedMap, getOriginalPosition } from '@vitest/utils/source-map';
export { getSafeTimers, setSafeTimers } from '@vitest/utils/timers';
import './chunks/coverage.D_JHT54q.js';
import './chunks/coverage.CTzCuANN.js';
import '@vitest/snapshot';
import './chunks/utils.DvEY5TfP.js';
import './chunks/utils.BX5Fg8C4.js';
/**
* @internal
+5958
View File
File diff suppressed because it is too large Load Diff
@@ -1,21 +1,23 @@
import { runInThisContext } from 'node:vm';
import * as spyModule from '@vitest/spy';
import { r as resolveTestRunner, a as resolveSnapshotEnvironment, s as setupChaiConfig } from './index.6Qv1eEA6.js';
import { l as loadEnvironment, e as emitModuleRunner } from './init.B6MLFIaN.js';
import { r as resolveTestRunner, a as resolveSnapshotEnvironment, d as detectAsyncLeaks, s as setupChaiConfig } from './index.DXx9Dtk7.js';
import { l as loadEnvironment, e as emitModuleRunner, a as listenForErrors } from './init.d4hAcNdp.js';
import { N as NativeModuleRunner } from './nativeModuleRunner.BIakptoF.js';
import { T as Traces } from './traces.DT5aQ62U.js';
import { V as VitestEvaluatedModules } from './evaluatedModules.Dg1zASAC.js';
import { s as startVitestModuleRunner, c as createNodeImportMeta } from './startModuleRunner.DEj0jb3e.js';
import { s as startVitestModuleRunner, c as createNodeImportMeta } from './startVitestModuleRunner.CCBQZ9DQ.js';
import { performance as performance$1 } from 'node:perf_hooks';
import { startTests, collectTests } from '@vitest/runner';
import { c as setupCommonEnv, s as startCoverageInsideWorker, a as stopCoverageInsideWorker } from './setup-common.Cm-kSBVi.js';
import { g as globalExpect, v as vi } from './vi.2VT5v0um.js';
import { s as setupCommonEnv, b as startCoverageInsideWorker, c as stopCoverageInsideWorker } from './setup-common.DYx3LtFI.js';
import { g as globalExpect, v as vi } from './test.DNmyFkvJ.js';
import { c as closeInspector } from './inspector.CvyFGlXm.js';
import { createRequire } from 'node:module';
import timers from 'node:timers';
import timersPromises from 'node:timers/promises';
import util from 'node:util';
import { KNOWN_ASSET_TYPES } from '@vitest/utils/constants';
import { i as index } from './index.Z5E_ObnR.js';
import { g as getWorkerState, r as resetModules, p as provideWorkerState } from './utils.DvEY5TfP.js';
import { i as index } from './index.DdgEv5B1.js';
import { g as getWorkerState, r as resetModules, p as provideWorkerState, a as getSafeWorkerState } from './utils.BX5Fg8C4.js';
// this should only be used in Node
let globalSetup = false;
@@ -56,7 +58,7 @@ function resolveAsset(mod, url) {
mod.exports = url;
}
async function setupConsoleLogSpy() {
const { createCustomConsole } = await import('./console.Cf-YriPC.js');
const { createCustomConsole } = await import('./console.3WNpx0tS.js');
globalThis.console = createCustomConsole();
}
@@ -79,12 +81,16 @@ async function run(method, files, config, moduleRunner, environment, traces) {
await traces.$(`vitest.test.runner.${method}`, async () => {
for (const file of files) {
if (config.isolate) {
moduleRunner.mocker.reset();
moduleRunner.mocker?.reset();
resetModules(workerState.evaluatedModules, true);
}
workerState.filepath = file.filepath;
if (method === "run") await traces.$(`vitest.test.runner.${method}.module`, { attributes: { "code.file.path": file.filepath } }, () => startTests([file], testRunner));
else await traces.$(`vitest.test.runner.${method}.module`, { attributes: { "code.file.path": file.filepath } }, () => collectTests([file], testRunner));
if (method === "run") {
const collectAsyncLeaks = config.detectAsyncLeaks ? detectAsyncLeaks(file.filepath, workerState.ctx.projectName) : void 0;
await traces.$(`vitest.test.runner.${method}.module`, { attributes: { "code.file.path": file.filepath } }, () => startTests([file], testRunner));
const leaks = await collectAsyncLeaks?.();
if (leaks?.length) workerState.rpc.onAsyncLeaks(leaks);
} else await traces.$(`vitest.test.runner.${method}.module`, { attributes: { "code.file.path": file.filepath } }, () => collectTests([file], testRunner));
// reset after tests, because user might call `vi.setConfig` in setupFile
vi.resetConfig();
// mocks should not affect different files
@@ -97,15 +103,47 @@ async function run(method, files, config, moduleRunner, environment, traces) {
let _moduleRunner;
const evaluatedModules = new VitestEvaluatedModules();
const moduleExecutionInfo = /* @__PURE__ */ new Map();
function startModuleRunner(options) {
async function startModuleRunner(options) {
if (_moduleRunner) return _moduleRunner;
process.exit = (code = process.exitCode || 0) => {
throw new Error(`process.exit unexpectedly called with "${code}"`);
};
const state = () => getSafeWorkerState() || options.state;
listenForErrors(state);
if (options.state.config.experimental.viteModuleRunner === false) {
const root = options.state.config.root;
let mocker;
if (options.state.config.experimental.nodeLoader !== false) {
// this additionally imports acorn/magic-string
const { NativeModuleMocker } = await import('./nativeModuleMocker.BLzfffNb.js');
mocker = new NativeModuleMocker({
async resolveId(id, importer) {
// TODO: use import.meta.resolve instead
return state().rpc.resolve(id, importer, "__vitest__");
},
root,
moduleDirectories: state().config.deps.moduleDirectories || ["/node_modules/"],
traces: options.traces || new Traces({ enabled: false }),
getCurrentTestFilepath() {
return state().filepath;
},
spyModule
});
}
_moduleRunner = new NativeModuleRunner(root, mocker);
return _moduleRunner;
}
_moduleRunner = startVitestModuleRunner(options);
return _moduleRunner;
}
let _currentEnvironment;
let _environmentTime;
/** @experimental */
async function setupEnvironment(context) {
async function setupBaseEnvironment(context) {
if (context.config.experimental.viteModuleRunner === false) {
const { setupNodeLoaderHooks } = await import('./native.DPzPHdi5.js');
await setupNodeLoaderHooks(context);
}
const startTime = performance.now();
const { environment: { name: environmentName, options: environmentOptions }, rpc, config } = context;
// we could load @vite/env, but it would take ~8ms, while this takes ~0,02ms
@@ -118,7 +156,7 @@ async function setupEnvironment(context) {
throw new Error(`Failed to load custom "defines": ${error.message}`);
}
const otel = context.traces;
const { environment, loader } = await loadEnvironment(environmentName, config.root, rpc, otel);
const { environment, loader } = await loadEnvironment(environmentName, config.root, rpc, otel, context.config.experimental.viteModuleRunner);
_currentEnvironment = environment;
const env = await otel.$("vitest.runtime.environment.setup", { attributes: {
"vitest.environment": environment.name,
@@ -151,7 +189,7 @@ async function runBaseTests(method, state, traces) {
state.evaluatedModules.invalidateModule(module);
});
});
const moduleRunner = startModuleRunner({
const moduleRunner = await startModuleRunner({
state,
evaluatedModules: state.evaluatedModules,
spyModule,
@@ -162,4 +200,4 @@ async function runBaseTests(method, state, traces) {
await run(method, ctx.files, ctx.config, moduleRunner, _currentEnvironment, traces);
}
export { runBaseTests as r, setupEnvironment as s };
export { runBaseTests as r, setupBaseEnvironment as s };
@@ -1,7 +1,7 @@
import { getCurrentSuite } from '@vitest/runner';
import { createChainable } from '@vitest/runner/utils';
import { noop } from '@vitest/utils/helpers';
import { g as getWorkerState } from './utils.DvEY5TfP.js';
import { g as getWorkerState } from './utils.BX5Fg8C4.js';
const benchFns = /* @__PURE__ */ new WeakMap();
const benchOptsMap = /* @__PURE__ */ new WeakMap();
@@ -20,7 +20,7 @@ const bench = createBenchmark(function(name, fn = noop, options = {}) {
benchFns.set(task, fn);
benchOptsMap.set(task, options);
// vitest runner sets mode to `todo` if handler is not passed down
// but we store handler separetly
// but we store handler separately
if (!this.todo && task.mode === "todo") task.mode = "run";
});
function createBenchmark(fn) {
@@ -1,6 +1,6 @@
import { FileSpecification } from '@vitest/runner';
import { O as OTELCarrier } from './traces.d.402V_yFI.js';
import { T as TestExecutionMethod } from './worker.d.Dyxm8DEL.js';
import { O as OTELCarrier } from './traces.d.D2T_R8rx.js';
import { T as TestExecutionMethod } from './worker.d.ZpHpO4yb.js';
type SerializedTestSpecification = [project: {
name: string | undefined;
@@ -8,6 +8,9 @@ type SerializedTestSpecification = [project: {
}, file: string, options: {
pool: string;
testLines?: number[] | undefined;
testIds?: string[] | undefined;
testNamePattern?: RegExp | undefined;
testTagsFilter?: string[] | undefined;
}];
interface ModuleDefinitionLocation {
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,7 +1,8 @@
import { PrettyFormatOptions } from '@vitest/pretty-format';
import { SequenceHooks, SequenceSetupFiles } from '@vitest/runner';
import { SequenceHooks, SequenceSetupFiles, SerializableRetry, TestTagDefinition } from '@vitest/runner';
import { SnapshotUpdateState, SnapshotEnvironment } from '@vitest/snapshot';
import { SerializedDiffOptions } from '@vitest/utils/diff';
import { L as LabelColor } from './traces.d.D2T_R8rx.js';
/**
* Names of clock methods that may be faked by install.
@@ -30,15 +31,13 @@ interface FakeTimerInstallOpts {
now?: number | Date | undefined;
/**
* An array with names of global methods and APIs to fake.
* For instance, `vi.useFakeTimer({ toFake: ['setTimeout', 'performance'] })` will fake only `setTimeout()` and `performance.now()`
* @default everything available globally except `nextTick`
* An array with names of global methods and APIs to fake. By default, `@sinonjs/fake-timers` does not replace `nextTick()` and `queueMicrotask()`.
* For instance, `FakeTimers.install({ toFake: ['setTimeout', 'nextTick'] })` will fake only `setTimeout()` and `nextTick()`
*/
toFake?: FakeMethod[] | undefined;
/**
* The maximum number of timers that will be run when calling runAll()
* @default 10000
* The maximum number of timers that will be run when calling runAll() (default: 1000)
*/
loopLimit?: number | undefined;
@@ -55,14 +54,13 @@ interface FakeTimerInstallOpts {
advanceTimeDelta?: number | undefined;
/**
* Tells FakeTimers to clear 'native' (i.e. not fake) timers by delegating to their respective handlers.
* @default true
* Tells FakeTimers to clear 'native' (i.e. not fake) timers by delegating to their respective handlers. These are not cleared by
* default, leading to potentially unexpected behavior if timers existed prior to installing FakeTimers. (default: false)
*/
shouldClearNativeTimers?: boolean | undefined;
/**
* Don't throw error when asked to fake timers that are not present.
* @default false
* Tells FakeTimers to not throw an error when faking a timer that does not exist in the global object. (default: false)
*/
ignoreMissingTimers?: boolean | undefined;
}
@@ -72,6 +70,7 @@ interface FakeTimerInstallOpts {
*/
interface SerializedConfig {
name: string | undefined;
color?: LabelColor;
globals: boolean;
base: string | undefined;
snapshotEnvironment?: string;
@@ -140,8 +139,12 @@ interface SerializedConfig {
showDiff?: boolean;
truncateThreshold?: number;
} | undefined;
api: {
allowExec: boolean | undefined;
allowWrite: boolean | undefined;
};
diff: string | SerializedDiffOptions | undefined;
retry: number;
retry: SerializableRetry;
includeTaskLocation: boolean | undefined;
inspect: boolean | string | undefined;
inspectBrk: boolean | string | undefined;
@@ -165,6 +168,7 @@ interface SerializedConfig {
};
locators: {
testIdAttribute: string;
exact: boolean;
};
screenshotFailures: boolean;
providerOptions: {
@@ -172,9 +176,11 @@ interface SerializedConfig {
};
trace: BrowserTraceViewMode;
trackUnhandledErrors: boolean;
detailsPanelPosition: "right" | "bottom";
};
standalone: boolean;
logHeapUsage: boolean | undefined;
detectAsyncLeaks: boolean;
coverage: SerializedCoverageConfig;
benchmark: {
includeSamples: boolean;
@@ -182,23 +188,39 @@ interface SerializedConfig {
serializedDefines: string;
experimental: {
fsModuleCache: boolean;
printImportBreakdown: boolean | undefined;
importDurations: {
print: boolean | "on-warn";
limit: number;
failOnDanger: boolean;
thresholds: {
warn: number;
danger: number;
};
};
viteModuleRunner: boolean;
nodeLoader: boolean;
openTelemetry: {
enabled: boolean;
sdkPath?: string;
browserSdkPath?: string;
} | undefined;
};
tags: TestTagDefinition[];
tagsFilter: string[] | undefined;
strictTags: boolean;
slowTestThreshold: number | undefined;
isAgent: boolean;
}
interface SerializedCoverageConfig {
provider: "istanbul" | "v8" | "custom" | undefined;
reportsDirectory: string;
htmlReporter: {
subdir: string | undefined;
} | undefined;
htmlDir: string | undefined;
enabled: boolean;
customProviderModule: string | undefined;
}
interface SerializedRootConfig extends SerializedConfig {
projects: SerializedConfig[];
}
type RuntimeConfig = Pick<SerializedConfig, "allowOnly" | "testTimeout" | "hookTimeout" | "clearMocks" | "mockReset" | "restoreMocks" | "fakeTimers" | "maxConcurrency" | "expect" | "printConsoleTrace"> & {
sequence?: {
hooks?: SequenceHooks;
@@ -207,4 +229,4 @@ type RuntimeConfig = Pick<SerializedConfig, "allowOnly" | "testTimeout" | "hookT
type RuntimeOptions = Partial<RuntimeConfig>;
type BrowserTraceViewMode = "on" | "off" | "on-first-retry" | "on-all-retries" | "retain-on-failure";
export type { BrowserTraceViewMode as B, FakeTimerInstallOpts as F, RuntimeOptions as R, SerializedConfig as S, SerializedCoverageConfig as a, RuntimeConfig as b };
export type { BrowserTraceViewMode as B, FakeTimerInstallOpts as F, RuntimeOptions as R, SerializedConfig as S, SerializedCoverageConfig as a, SerializedRootConfig as b, RuntimeConfig as c };
@@ -3,8 +3,9 @@ import { relative } from 'node:path';
import { Writable } from 'node:stream';
import { getSafeTimers } from '@vitest/utils/timers';
import c from 'tinyrainbow';
import { R as RealDate } from './date.Bq6ZW5rf.js';
import { g as getWorkerState } from './utils.DvEY5TfP.js';
import { R as RealDate } from './rpc.MzXet3jl.js';
import { g as getWorkerState } from './utils.BX5Fg8C4.js';
import './index.Chj8NDwU.js';
const UNKNOWN_TEST_ID = "__vitest__unknown_test__";
function getTaskIdByStack(root) {
@@ -30,7 +30,9 @@ const globalApis = [
"beforeEach",
"afterEach",
"onTestFinished",
"onTestFailed"
"onTestFailed",
"aroundEach",
"aroundAll"
];
export { API_PATH as A, defaultPort as a, defaultInspectPort as b, configFiles as c, defaultBrowserPort as d, globalApis as g };
export { API_PATH as A, defaultInspectPort as a, defaultPort as b, configFiles as c, defaultBrowserPort as d, globalApis as g };
@@ -8,7 +8,10 @@ async function resolveCoverageProviderModule(options, loader) {
if (provider === "v8" || provider === "istanbul") {
let builtInModule = CoverageProviderMap[provider];
if (provider === "v8" && loader.isBrowser) builtInModule += "/browser";
const { default: coverageModule } = await loader.import(builtInModule);
const { default: coverageModule } = loader.isBrowser ? await loader.import(builtInModule) : await import(
/* @vite-ignore */
builtInModule
);
if (!coverageModule) throw new Error(`Failed to load ${CoverageProviderMap[provider]}. Default export is missing.`);
return coverageModule;
}
File diff suppressed because it is too large Load Diff
@@ -1,11 +1,11 @@
import { existsSync, writeFileSync, readFileSync } from 'node:fs';
import { mkdir, writeFile } from 'node:fs/promises';
import { resolve, dirname, relative } from 'node:path';
import { detectPackageManager, installPackage } from './index.D3XRDfWc.js';
import { p as prompt, a as any } from './index.D4KonVSU.js';
import { detectPackageManager, installPackage } from './index.CMESou6r.js';
import { p as prompt, a as any } from './index.og1WyBLx.js';
import { x } from 'tinyexec';
import c from 'tinyrainbow';
import { c as configFiles } from './constants.D_Q9UYh-.js';
import { c as configFiles } from './constants.CPYnjOGj.js';
import 'node:process';
import 'node:module';
import 'node:url';
@@ -226,6 +226,37 @@ import { expect, test } from 'vitest'
import { render } from 'vitest-browser-qwik'
import HelloWorld from './HelloWorld.tsx'
test('renders name', async () => {
const { getByText } = render(<HelloWorld name="Vitest" />)
await expect.element(getByText('Hello Vitest!')).toBeInTheDocument()
})
`
};
const preactExample = {
name: "HelloWorld.jsx",
js: `
export default function HelloWorld({ name }) {
return (
<div>
<h1>Hello {name}!</h1>
</div>
)
}
`,
ts: `
export default function HelloWorld({ name }: { name: string }) {
return (
<div>
<h1>Hello {name}!</h1>
</div>
)
}
`,
test: `
import { expect, test } from 'vitest'
import { render } from 'vitest-browser-preact'
import HelloWorld from './HelloWorld.<EXT>x'
test('renders name', async () => {
const { getByText } = render(<HelloWorld name="Vitest" />)
await expect.element(getByText('Hello Vitest!')).toBeInTheDocument()
@@ -276,7 +307,7 @@ function getExampleTest(framework) {
...jsxExample,
test: jsxExample.test.replace("@testing-library/jsx", `@testing-library/${framework}`)
};
case "preact":
case "preact": return preactExample;
case "react": return {
...jsxExample,
test: jsxExample.test.replace("@testing-library/jsx", `vitest-browser-${framework}`)
-73
View File
@@ -1,73 +0,0 @@
/* Ported from https://github.com/boblauer/MockDate/blob/master/src/mockdate.ts */
/*
The MIT License (MIT)
Copyright (c) 2014 Bob Lauer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
const RealDate = Date;
let now = null;
class MockDate extends RealDate {
constructor(y, m, d, h, M, s, ms) {
super();
let date;
switch (arguments.length) {
case 0:
if (now !== null) date = new RealDate(now.valueOf());
else date = new RealDate();
break;
case 1:
date = new RealDate(y);
break;
default:
d = typeof d === "undefined" ? 1 : d;
h = h || 0;
M = M || 0;
s = s || 0;
ms = ms || 0;
date = new RealDate(y, m, d, h, M, s, ms);
break;
}
Object.setPrototypeOf(date, MockDate.prototype);
return date;
}
}
MockDate.UTC = RealDate.UTC;
MockDate.now = function() {
return new MockDate().valueOf();
};
MockDate.parse = function(dateString) {
return RealDate.parse(dateString);
};
MockDate.toString = function() {
return RealDate.toString();
};
function mockDate(date) {
const dateObj = new RealDate(date.valueOf());
if (Number.isNaN(dateObj.getTime())) throw new TypeError(`mockdate: The time set is an invalid date: ${date}`);
// @ts-expect-error global
globalThis.Date = MockDate;
now = dateObj.valueOf();
}
function resetDate() {
globalThis.Date = RealDate;
}
export { RealDate as R, mockDate as m, resetDate as r };
@@ -1,6 +1,6 @@
import nodeos__default from 'node:os';
import './env.D4Lgay0q.js';
import { isCI } from 'std-env';
import { isCI, isAgent } from 'std-env';
const defaultInclude = ["**/*.{test,spec}.?(c|m)[jt]s?(x)"];
const defaultExclude = ["**/node_modules/**", "**/.git/**"];
@@ -21,14 +21,22 @@ const coverageConfigDefaults = {
exclude: [],
reportOnFailure: false,
reporter: [
["text", {}],
["html", {}],
["clover", {}],
["json", {}]
"text",
"html",
"clover",
"json"
],
allowExternal: false,
excludeAfterRemap: false,
processingConcurrency: Math.min(20, nodeos__default.availableParallelism?.() ?? nodeos__default.cpus().length)
processingConcurrency: Math.min(20, nodeos__default.availableParallelism?.() ?? nodeos__default.cpus().length),
ignoreClassMethods: [],
skipFull: false,
watermarks: {
statements: [50, 80],
functions: [50, 80],
branches: [50, 80],
lines: [50, 80]
}
};
const fakeTimersDefaults = {
loopLimit: 1e4,
@@ -37,7 +45,7 @@ const fakeTimersDefaults = {
const configDefaults = Object.freeze({
allowOnly: !isCI,
isolate: true,
watch: !isCI && process.stdin.isTTY,
watch: !isCI && process.stdin.isTTY && !isAgent,
globals: false,
environment: "node",
clearMocks: false,
@@ -68,7 +76,8 @@ const configDefaults = Object.freeze({
exclude: defaultExclude
},
slowTestThreshold: 300,
disableConsoleIntercept: false
disableConsoleIntercept: false,
detectAsyncLeaks: false
});
export { coverageConfigDefaults as a, defaultInclude as b, configDefaults as c, defaultExclude as d, benchmarkConfigDefaults as e };
-71
View File
@@ -1,71 +0,0 @@
import { resolve } from 'pathe';
import { x } from 'tinyexec';
class VitestGit {
root;
constructor(cwd) {
this.cwd = cwd;
}
async resolveFilesWithGitCommand(args) {
let result;
try {
result = await x("git", args, { nodeOptions: { cwd: this.root } });
} catch (e) {
e.message = e.stderr;
throw e;
}
return result.stdout.split("\n").filter((s) => s !== "").map((changedPath) => resolve(this.root, changedPath));
}
async findChangedFiles(options) {
const root = await this.getRoot(this.cwd);
if (!root) return null;
this.root = root;
const changedSince = options.changedSince;
if (typeof changedSince === "string") {
const [committed, staged, unstaged] = await Promise.all([
this.getFilesSince(changedSince),
this.getStagedFiles(),
this.getUnstagedFiles()
]);
return [
...committed,
...staged,
...unstaged
];
}
const [staged, unstaged] = await Promise.all([this.getStagedFiles(), this.getUnstagedFiles()]);
return [...staged, ...unstaged];
}
getFilesSince(hash) {
return this.resolveFilesWithGitCommand([
"diff",
"--name-only",
`${hash}...HEAD`
]);
}
getStagedFiles() {
return this.resolveFilesWithGitCommand([
"diff",
"--cached",
"--name-only"
]);
}
getUnstagedFiles() {
return this.resolveFilesWithGitCommand([
"ls-files",
"--other",
"--modified",
"--exclude-standard"
]);
}
async getRoot(cwd) {
const args = ["rev-parse", "--show-cdup"];
try {
return resolve(cwd, (await x("git", args, { nodeOptions: { cwd } })).stdout.trim());
} catch {
return null;
}
}
}
export { VitestGit };
@@ -1,8 +1,9 @@
import { PromisifyAssertion, Tester, ExpectStatic } from '@vitest/expect';
import { Plugin } from '@vitest/pretty-format';
import { Test } from '@vitest/runner';
import { SnapshotState } from '@vitest/snapshot';
import { B as BenchmarkResult } from './benchmark.d.DAaHLpsq.js';
import { U as UserConsoleLog } from './rpc.d.RH3apGEf.js';
import { U as UserConsoleLog } from './traces.d.D2T_R8rx.js';
interface SnapshotMatcher<T> {
<U extends { [P in keyof T] : any }>(snapshot: Partial<U>, hint?: string): void;
@@ -16,6 +17,7 @@ declare module "@vitest/expect" {
interface MatcherState {
environment: string;
snapshotState: SnapshotState;
task?: Readonly<Test>;
}
interface ExpectPollOptions {
interval?: number;
@@ -84,7 +86,6 @@ declare module "@vitest/runner" {
interface TaskMeta {
typecheck?: boolean;
benchmark?: boolean;
failScreenshotPath?: string;
}
interface File {
prepareDuration?: number;
@@ -1,22 +1,23 @@
import { g as globalApis } from './constants.D_Q9UYh-.js';
import { i as index } from './index.Z5E_ObnR.js';
import './vi.2VT5v0um.js';
import '@vitest/expect';
import { g as globalApis } from './constants.CPYnjOGj.js';
import { i as index } from './index.DdgEv5B1.js';
import './test.DNmyFkvJ.js';
import '@vitest/runner';
import './utils.DvEY5TfP.js';
import '@vitest/utils/timers';
import '@vitest/runner/utils';
import '@vitest/snapshot';
import '@vitest/utils/error';
import '@vitest/utils/helpers';
import '@vitest/utils/timers';
import './benchmark.CX_oY03V.js';
import '@vitest/runner/utils';
import './utils.BX5Fg8C4.js';
import '@vitest/expect';
import '@vitest/utils/error';
import 'pathe';
import '@vitest/spy';
import '@vitest/utils/offset';
import '@vitest/utils/source-map';
import './_commonjsHelpers.D26ty3Ew.js';
import './date.Bq6ZW5rf.js';
import './benchmark.B3N2zMcH.js';
import './rpc.MzXet3jl.js';
import './index.Chj8NDwU.js';
import '@vitest/snapshot';
import './evaluatedModules.Dg1zASAC.js';
import 'pathe';
import 'vite/module-runner';
import 'expect-type';
@@ -1,27 +1,13 @@
import fs, { statSync, realpathSync, existsSync, promises, readdirSync, writeFileSync } from 'node:fs';
import path, { win32, dirname, join } from 'node:path';
import { slash, shuffle, toArray } from '@vitest/utils/helpers';
import { isAbsolute, resolve, relative, normalize } from 'pathe';
import pm from 'picomatch';
import { glob } from 'tinyglobby';
import c from 'tinyrainbow';
import { c as configDefaults, e as benchmarkConfigDefaults, a as coverageConfigDefaults } from './defaults.BOqNVLsY.js';
import crypto from 'node:crypto';
import { fileURLToPath as fileURLToPath$1, pathToFileURL as pathToFileURL$1, URL as URL$1 } from 'node:url';
import fs, { statSync, realpathSync } from 'node:fs';
import { builtinModules, createRequire } from 'node:module';
import path, { win32, dirname, join } from 'node:path';
import process$1 from 'node:process';
import fs$1 from 'node:fs/promises';
import { fileURLToPath as fileURLToPath$1, pathToFileURL as pathToFileURL$1, URL as URL$1 } from 'node:url';
import { isAbsolute } from 'pathe';
import assert from 'node:assert';
import v8 from 'node:v8';
import { format, inspect } from 'node:util';
import { mergeConfig } from 'vite';
import { c as configFiles, d as defaultBrowserPort, b as defaultInspectPort, a as defaultPort } from './constants.D_Q9UYh-.js';
import './env.D4Lgay0q.js';
import nodeos__default from 'node:os';
import { isCI, provider } from 'std-env';
import { r as resolveCoverageProviderModule } from './coverage.D_JHT54q.js';
const hash = crypto.hash ?? ((algorithm, data, outputEncoding) => crypto.createHash(algorithm).update(data).digest(outputEncoding));
const JOIN_LEADING_SLASH_RE = /^\.?\//;
function withTrailingSlash(input = "", respectQueryAndFragment) {
@@ -2349,944 +2335,4 @@ const isPackageListed = quansync(function* (name, cwd) {
});
isPackageListed.sync;
function getWorkersCountByPercentage(percent) {
const maxWorkersCount = nodeos__default.availableParallelism?.() ?? nodeos__default.cpus().length;
const workersCountByPercentage = Math.round(Number.parseInt(percent) / 100 * maxWorkersCount);
return Math.max(1, Math.min(maxWorkersCount, workersCountByPercentage));
}
class BaseSequencer {
ctx;
constructor(ctx) {
this.ctx = ctx;
}
// async so it can be extended by other sequelizers
async shard(files) {
const { config } = this.ctx;
const { index, count } = config.shard;
const [shardStart, shardEnd] = this.calculateShardRange(files.length, index, count);
return [...files].map((spec) => {
const specPath = resolve(slash(config.root), slash(spec.moduleId))?.slice(config.root.length);
return {
spec,
hash: hash("sha1", specPath, "hex")
};
}).sort((a, b) => a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0).slice(shardStart, shardEnd).map(({ spec }) => spec);
}
// async so it can be extended by other sequelizers
async sort(files) {
const cache = this.ctx.cache;
return [...files].sort((a, b) => {
// "sequence.groupOrder" is higher priority
const groupOrderDiff = a.project.config.sequence.groupOrder - b.project.config.sequence.groupOrder;
if (groupOrderDiff !== 0) return groupOrderDiff;
// Projects run sequential
if (a.project.name !== b.project.name) return a.project.name < b.project.name ? -1 : 1;
// Isolated run first
if (a.project.config.isolate && !b.project.config.isolate) return -1;
if (!a.project.config.isolate && b.project.config.isolate) return 1;
const keyA = `${a.project.name}:${relative(this.ctx.config.root, a.moduleId)}`;
const keyB = `${b.project.name}:${relative(this.ctx.config.root, b.moduleId)}`;
const aState = cache.getFileTestResults(keyA);
const bState = cache.getFileTestResults(keyB);
if (!aState || !bState) {
const statsA = cache.getFileStats(keyA);
const statsB = cache.getFileStats(keyB);
// run unknown first
if (!statsA || !statsB) return !statsA && statsB ? -1 : !statsB && statsA ? 1 : 0;
// run larger files first
return statsB.size - statsA.size;
}
// run failed first
if (aState.failed && !bState.failed) return -1;
if (!aState.failed && bState.failed) return 1;
// run longer first
return bState.duration - aState.duration;
});
}
// Calculate distributed shard range [start, end] distributed equally
calculateShardRange(filesCount, index, count) {
const baseShardSize = Math.floor(filesCount / count);
const remainderTestFilesCount = filesCount % count;
if (remainderTestFilesCount >= index) {
const shardSize = baseShardSize + 1;
return [shardSize * (index - 1), shardSize * index];
}
const shardStart = remainderTestFilesCount * (baseShardSize + 1) + (index - remainderTestFilesCount - 1) * baseShardSize;
return [shardStart, shardStart + baseShardSize];
}
}
class RandomSequencer extends BaseSequencer {
async sort(files) {
const { sequence } = this.ctx.config;
return shuffle(files, sequence.seed);
}
}
function resolvePath(path, root) {
return normalize(/* @__PURE__ */ resolveModule(path, { paths: [root] }) ?? resolve(root, path));
}
function parseInspector(inspect) {
if (typeof inspect === "boolean" || inspect === void 0) return {};
if (typeof inspect === "number") return { port: inspect };
if (inspect.match(/https?:\//)) throw new Error(`Inspector host cannot be a URL. Use "host:port" instead of "${inspect}"`);
const [host, port] = inspect.split(":");
if (!port) return { host };
return {
host,
port: Number(port) || defaultInspectPort
};
}
function resolveApiServerConfig(options, defaultPort) {
let api;
if (options.ui && !options.api) api = { port: defaultPort };
else if (options.api === true) api = { port: defaultPort };
else if (typeof options.api === "number") api = { port: options.api };
if (typeof options.api === "object") if (api) {
if (options.api.port) api.port = options.api.port;
if (options.api.strictPort) api.strictPort = options.api.strictPort;
if (options.api.host) api.host = options.api.host;
} else api = { ...options.api };
if (api) {
if (!api.port && !api.middlewareMode) api.port = defaultPort;
} else api = { middlewareMode: true };
return api;
}
function resolveInlineWorkerOption(value) {
if (typeof value === "string" && value.trim().endsWith("%")) return getWorkersCountByPercentage(value);
else return Number(value);
}
function resolveConfig$1(vitest, options, viteConfig) {
const mode = vitest.mode;
const logger = vitest.logger;
if (options.dom) {
if (viteConfig.test?.environment != null && viteConfig.test.environment !== "happy-dom") logger.console.warn(c.yellow(`${c.inverse(c.yellow(" Vitest "))} Your config.test.environment ("${viteConfig.test.environment}") conflicts with --dom flag ("happy-dom"), ignoring "${viteConfig.test.environment}"`));
options.environment = "happy-dom";
}
const resolved = {
...configDefaults,
...options,
root: viteConfig.root,
mode
};
if (options.pool && typeof options.pool !== "string") {
resolved.pool = options.pool.name;
resolved.poolRunner = options.pool;
}
if ("poolOptions" in resolved) logger.deprecate("`test.poolOptions` was removed in Vitest 4. All previous `poolOptions` are now top-level options. Please, refer to the migration guide: https://vitest.dev/guide/migration#pool-rework");
resolved.pool ??= "forks";
resolved.project = toArray(resolved.project);
resolved.provide ??= {};
resolved.name = typeof options.name === "string" ? options.name : options.name?.label || "";
resolved.color = typeof options.name !== "string" ? options.name?.color : void 0;
if (resolved.environment === "browser") throw new Error(`Looks like you set "test.environment" to "browser". To enable Browser Mode, use "test.browser.enabled" instead.`);
const inspector = resolved.inspect || resolved.inspectBrk;
resolved.inspector = {
...resolved.inspector,
...parseInspector(inspector),
enabled: !!inspector,
waitForDebugger: options.inspector?.waitForDebugger ?? !!resolved.inspectBrk
};
if (viteConfig.base !== "/") resolved.base = viteConfig.base;
resolved.clearScreen = resolved.clearScreen ?? viteConfig.clearScreen ?? true;
if (options.shard) {
if (resolved.watch) throw new Error("You cannot use --shard option with enabled watch");
const [indexString, countString] = options.shard.split("/");
const index = Math.abs(Number.parseInt(indexString, 10));
const count = Math.abs(Number.parseInt(countString, 10));
if (Number.isNaN(count) || count <= 0) throw new Error("--shard <count> must be a positive number");
if (Number.isNaN(index) || index <= 0 || index > count) throw new Error("--shard <index> must be a positive number less then <count>");
resolved.shard = {
index,
count
};
}
if (resolved.standalone && !resolved.watch) throw new Error(`Vitest standalone mode requires --watch`);
if (resolved.mergeReports && resolved.watch) throw new Error(`Cannot merge reports with --watch enabled`);
if (resolved.maxWorkers) resolved.maxWorkers = resolveInlineWorkerOption(resolved.maxWorkers);
if (!(options.fileParallelism ?? mode !== "benchmark"))
// ignore user config, parallelism cannot be implemented without limiting workers
resolved.maxWorkers = 1;
if (resolved.maxConcurrency === 0) {
logger.console.warn(c.yellow(`The option "maxConcurrency" cannot be set to 0. Using default value ${configDefaults.maxConcurrency} instead.`));
resolved.maxConcurrency = configDefaults.maxConcurrency;
}
if (resolved.inspect || resolved.inspectBrk) {
if (resolved.maxWorkers !== 1) {
const inspectOption = `--inspect${resolved.inspectBrk ? "-brk" : ""}`;
throw new Error(`You cannot use ${inspectOption} without "--no-file-parallelism"`);
}
}
// apply browser CLI options only if the config already has the browser config and not disabled manually
if (vitest._cliOptions.browser && resolved.browser && (resolved.browser.enabled !== false || vitest._cliOptions.browser.enabled)) resolved.browser = mergeConfig(resolved.browser, vitest._cliOptions.browser);
resolved.browser ??= {};
const browser = resolved.browser;
if (browser.enabled) {
const instances = browser.instances;
if (!browser.instances) browser.instances = [];
// use `chromium` by default when the preview provider is specified
// for a smoother experience. if chromium is not available, it will
// open the default browser anyway
if (!browser.instances.length && browser.provider?.name === "preview") browser.instances = [{ browser: "chromium" }];
if (browser.name && instances?.length) {
// --browser=chromium filters configs to a single one
browser.instances = browser.instances.filter((instance) => instance.browser === browser.name);
// if `instances` were defined, but now they are empty,
// let's throw an error because the filter is invalid
if (!browser.instances.length) throw new Error([`"browser.instances" was set in the config, but the array is empty. Define at least one browser config.`, ` The "browser.name" was set to "${browser.name}" which filtered all configs (${instances.map((c) => c.browser).join(", ")}). Did you mean to use another name?`].join(""));
}
}
const containsChromium = hasBrowserChromium(vitest, resolved);
const hasOnlyChromium = hasOnlyBrowserChromium(vitest, resolved);
// Browser-mode "Chromium" only features:
if (browser.enabled && (!containsChromium || !hasOnlyChromium)) {
const browserConfig = `
{
browser: {
provider: ${browser.provider?.name || "preview"}(),
instances: [
${(browser.instances || []).map((i) => `{ browser: '${i.browser}' }`).join(",\n ")}
],
},
}
`.trim();
const preferredProvider = !browser.provider?.name || browser.provider.name === "preview" ? "playwright" : browser.provider.name;
const correctExample = `
{
browser: {
provider: ${preferredProvider}(),
instances: [
{ browser: '${preferredProvider === "playwright" ? "chromium" : "chrome"}' }
],
},
}
`.trim();
// requires all projects to be chromium
if (!hasOnlyChromium && resolved.coverage.enabled && resolved.coverage.provider === "v8") {
const coverageExample = `
{
coverage: {
provider: 'istanbul',
},
}
`.trim();
throw new Error(`@vitest/coverage-v8 does not work with\n${browserConfig}\n\nUse either:\n${correctExample}\n\n...or change your coverage provider to:\n${coverageExample}\n`);
}
// ignores non-chromium browsers when there is at least one chromium project
if (!containsChromium && (resolved.inspect || resolved.inspectBrk)) {
const inspectOption = `--inspect${resolved.inspectBrk ? "-brk" : ""}`;
throw new Error(`${inspectOption} does not work with\n${browserConfig}\n\nUse either:\n${correctExample}\n\n...or disable ${inspectOption}\n`);
}
}
resolved.coverage.reporter = resolveCoverageReporters(resolved.coverage.reporter);
if (resolved.coverage.enabled && resolved.coverage.reportsDirectory) {
const reportsDirectory = resolve(resolved.root, resolved.coverage.reportsDirectory);
if (reportsDirectory === resolved.root || reportsDirectory === process.cwd()) throw new Error(`You cannot set "coverage.reportsDirectory" as ${reportsDirectory}. Vitest needs to be able to remove this directory before test run`);
}
if (resolved.coverage.enabled && resolved.coverage.provider === "custom" && resolved.coverage.customProviderModule) resolved.coverage.customProviderModule = resolvePath(resolved.coverage.customProviderModule, resolved.root);
resolved.expect ??= {};
resolved.deps ??= {};
resolved.deps.moduleDirectories ??= [];
resolved.deps.optimizer ??= {};
resolved.deps.optimizer.ssr ??= {};
resolved.deps.optimizer.ssr.enabled ??= false;
resolved.deps.optimizer.client ??= {};
resolved.deps.optimizer.client.enabled ??= false;
resolved.deps.web ??= {};
resolved.deps.web.transformAssets ??= true;
resolved.deps.web.transformCss ??= true;
resolved.deps.web.transformGlobPattern ??= [];
resolved.setupFiles = toArray(resolved.setupFiles || []).map((file) => resolvePath(file, resolved.root));
resolved.globalSetup = toArray(resolved.globalSetup || []).map((file) => resolvePath(file, resolved.root));
// Add hard-coded default coverage exclusions. These cannot be overidden by user config.
// Override original exclude array for cases where user re-uses same object in test.exclude.
resolved.coverage.exclude = [
...resolved.coverage.exclude,
...resolved.setupFiles.map((file) => `${resolved.coverage.allowExternal ? "**/" : ""}${relative(resolved.root, file)}`),
...resolved.include,
resolved.config && slash(resolved.config),
...configFiles,
"**/virtual:*",
"**/__x00__*",
"**/node_modules/**"
].filter((pattern) => typeof pattern === "string");
resolved.forceRerunTriggers = [...resolved.forceRerunTriggers, ...resolved.setupFiles];
if (resolved.cliExclude) resolved.exclude.push(...resolved.cliExclude);
if (resolved.runner) resolved.runner = resolvePath(resolved.runner, resolved.root);
resolved.attachmentsDir = resolve(resolved.root, resolved.attachmentsDir ?? ".vitest-attachments");
if (resolved.snapshotEnvironment) resolved.snapshotEnvironment = resolvePath(resolved.snapshotEnvironment, resolved.root);
resolved.testNamePattern = resolved.testNamePattern ? resolved.testNamePattern instanceof RegExp ? resolved.testNamePattern : new RegExp(resolved.testNamePattern) : void 0;
if (resolved.snapshotFormat && "plugins" in resolved.snapshotFormat) {
resolved.snapshotFormat.plugins = [];
// TODO: support it via separate config (like DiffOptions) or via `Function.toString()`
if (typeof resolved.snapshotFormat.compareKeys === "function") throw new TypeError(`"snapshotFormat.compareKeys" function is not supported.`);
}
const UPDATE_SNAPSHOT = resolved.update || process.env.UPDATE_SNAPSHOT;
resolved.snapshotOptions = {
expand: resolved.expandSnapshotDiff ?? false,
snapshotFormat: resolved.snapshotFormat || {},
updateSnapshot: isCI && !UPDATE_SNAPSHOT ? "none" : UPDATE_SNAPSHOT ? "all" : "new",
resolveSnapshotPath: options.resolveSnapshotPath,
snapshotEnvironment: null
};
resolved.snapshotSerializers ??= [];
resolved.snapshotSerializers = resolved.snapshotSerializers.map((file) => resolvePath(file, resolved.root));
resolved.forceRerunTriggers.push(...resolved.snapshotSerializers);
if (options.resolveSnapshotPath) delete resolved.resolveSnapshotPath;
resolved.execArgv ??= [];
resolved.pool ??= "threads";
if (resolved.pool === "vmForks" || resolved.pool === "vmThreads" || resolved.pool === "typescript") resolved.isolate = false;
if (process.env.VITEST_MAX_WORKERS) resolved.maxWorkers = Number.parseInt(process.env.VITEST_MAX_WORKERS);
if (mode === "benchmark") {
resolved.benchmark = {
...benchmarkConfigDefaults,
...resolved.benchmark
};
// override test config
resolved.coverage.enabled = false;
resolved.typecheck.enabled = false;
resolved.include = resolved.benchmark.include;
resolved.exclude = resolved.benchmark.exclude;
resolved.includeSource = resolved.benchmark.includeSource;
const reporters = Array.from(new Set([...toArray(resolved.benchmark.reporters), ...toArray(options.reporter)])).filter(Boolean);
if (reporters.length) resolved.benchmark.reporters = reporters;
else resolved.benchmark.reporters = ["default"];
if (options.outputFile) resolved.benchmark.outputFile = options.outputFile;
// --compare from cli
if (options.compare) resolved.benchmark.compare = options.compare;
if (options.outputJson) resolved.benchmark.outputJson = options.outputJson;
}
if (typeof resolved.diff === "string") {
resolved.diff = resolvePath(resolved.diff, resolved.root);
resolved.forceRerunTriggers.push(resolved.diff);
}
resolved.api = {
...resolveApiServerConfig(options, defaultPort),
token: crypto.randomUUID()
};
if (options.related) resolved.related = toArray(options.related).map((file) => resolve(resolved.root, file));
/*
* Reporters can be defined in many different ways:
* { reporter: 'json' }
* { reporter: { onFinish() { method() } } }
* { reporter: ['json', { onFinish() { method() } }] }
* { reporter: [[ 'json' ]] }
* { reporter: [[ 'json' ], 'html'] }
* { reporter: [[ 'json', { outputFile: 'test.json' } ], 'html'] }
*/
if (options.reporters) if (!Array.isArray(options.reporters))
// Reporter name, e.g. { reporters: 'json' }
if (typeof options.reporters === "string") resolved.reporters = [[options.reporters, {}]];
else resolved.reporters = [options.reporters];
else {
resolved.reporters = [];
for (const reporter of options.reporters) if (Array.isArray(reporter))
// Reporter with options, e.g. { reporters: [ [ 'json', { outputFile: 'test.json' } ] ] }
resolved.reporters.push([reporter[0], reporter[1] || {}]);
else if (typeof reporter === "string")
// Reporter name in array, e.g. { reporters: ["html", "json"]}
resolved.reporters.push([reporter, {}]);
else
// Inline reporter, e.g. { reporter: [{ onFinish() { method() } }] }
resolved.reporters.push(reporter);
}
if (mode !== "benchmark") {
// @ts-expect-error "reporter" is from CLI, should be absolute to the running directory
// it is passed down as "vitest --reporter ../reporter.js"
const reportersFromCLI = resolved.reporter;
const cliReporters = toArray(reportersFromCLI || []).map((reporter) => {
// ./reporter.js || ../reporter.js, but not .reporters/reporter.js
if (/^\.\.?\//.test(reporter)) return resolve(process.cwd(), reporter);
return reporter;
});
if (cliReporters.length) {
// When CLI reporters are specified, preserve options from config file
const configReportersMap = /* @__PURE__ */ new Map();
// Build a map of reporter names to their options from the config
for (const reporter of resolved.reporters) if (Array.isArray(reporter)) {
const [reporterName, reporterOptions] = reporter;
if (typeof reporterName === "string") configReportersMap.set(reporterName, reporterOptions);
}
resolved.reporters = Array.from(new Set(toArray(cliReporters))).filter(Boolean).map((reporter) => [reporter, configReportersMap.get(reporter) || {}]);
}
}
if (!resolved.reporters.length) {
resolved.reporters.push(["default", {}]);
// also enable github-actions reporter as a default
if (process.env.GITHUB_ACTIONS === "true") resolved.reporters.push(["github-actions", {}]);
}
if (resolved.changed) resolved.passWithNoTests ??= true;
resolved.css ??= {};
if (typeof resolved.css === "object") {
resolved.css.modules ??= {};
resolved.css.modules.classNameStrategy ??= "stable";
}
if (resolved.cache !== false) {
if (resolved.cache && typeof resolved.cache.dir === "string") vitest.logger.deprecate(`"cache.dir" is deprecated, use Vite's "cacheDir" instead if you want to change the cache director. Note caches will be written to "cacheDir\/vitest"`);
resolved.cache = { dir: viteConfig.cacheDir };
}
resolved.sequence ??= {};
if (resolved.sequence.shuffle && typeof resolved.sequence.shuffle === "object") {
const { files, tests } = resolved.sequence.shuffle;
resolved.sequence.sequencer ??= files ? RandomSequencer : BaseSequencer;
resolved.sequence.shuffle = tests;
}
if (!resolved.sequence?.sequencer)
// CLI flag has higher priority
resolved.sequence.sequencer = resolved.sequence.shuffle ? RandomSequencer : BaseSequencer;
resolved.sequence.groupOrder ??= 0;
resolved.sequence.hooks ??= "stack";
if (resolved.sequence.sequencer === RandomSequencer) resolved.sequence.seed ??= Date.now();
resolved.typecheck = {
...configDefaults.typecheck,
...resolved.typecheck
};
resolved.typecheck ??= {};
resolved.typecheck.enabled ??= false;
if (resolved.typecheck.enabled) logger.console.warn(c.yellow("Testing types with tsc and vue-tsc is an experimental feature.\nBreaking changes might not follow SemVer, please pin Vitest's version when using it."));
resolved.browser.enabled ??= false;
resolved.browser.headless ??= isCI;
resolved.browser.isolate ??= resolved.isolate ?? true;
resolved.browser.fileParallelism ??= options.fileParallelism ?? mode !== "benchmark";
// disable in headless mode by default, and if CI is detected
resolved.browser.ui ??= resolved.browser.headless === true ? false : !isCI;
resolved.browser.commands ??= {};
if (resolved.browser.screenshotDirectory) resolved.browser.screenshotDirectory = resolve(resolved.root, resolved.browser.screenshotDirectory);
if (resolved.inspector.enabled) resolved.browser.trackUnhandledErrors ??= false;
resolved.browser.viewport ??= {};
resolved.browser.viewport.width ??= 414;
resolved.browser.viewport.height ??= 896;
resolved.browser.locators ??= {};
resolved.browser.locators.testIdAttribute ??= "data-testid";
if (typeof resolved.browser.provider === "string") {
const source = `@vitest/browser-${resolved.browser.provider}`;
throw new TypeError(`The \`browser.provider\` configuration was changed to accept a factory instead of a string. Add an import of "${resolved.browser.provider}" from "${source}" instead. See: https://vitest.dev/config/browser/provider`);
}
const isPreview = resolved.browser.provider?.name === "preview";
if (!isPreview && resolved.browser.enabled && provider === "stackblitz") throw new Error(`stackblitz environment does not support the ${resolved.browser.provider?.name} provider. Please, use "@vitest/browser-preview" instead.`);
if (isPreview && resolved.browser.screenshotFailures === true) {
console.warn(c.yellow([
`Browser provider "preview" doesn't support screenshots, `,
`so "browser.screenshotFailures" option is forcefully disabled. `,
`Set "browser.screenshotFailures" to false or remove it from the config to suppress this warning.`
].join("")));
resolved.browser.screenshotFailures = false;
} else resolved.browser.screenshotFailures ??= !isPreview && !resolved.browser.ui;
if (resolved.browser.provider && resolved.browser.provider.options == null) resolved.browser.provider.options = {};
resolved.browser.api = resolveApiServerConfig(resolved.browser, defaultBrowserPort) || { port: defaultBrowserPort };
// enable includeTaskLocation by default in UI mode
if (resolved.browser.enabled) {
if (resolved.browser.ui) resolved.includeTaskLocation ??= true;
} else if (resolved.ui) resolved.includeTaskLocation ??= true;
if (typeof resolved.browser.trace === "string" || !resolved.browser.trace) resolved.browser.trace = { mode: resolved.browser.trace || "off" };
if (resolved.browser.trace.tracesDir != null) resolved.browser.trace.tracesDir = resolvePath(resolved.browser.trace.tracesDir, resolved.root);
if (toArray(resolved.reporters).some((reporter) => {
if (Array.isArray(reporter)) return reporter[0] === "html";
return false;
})) resolved.includeTaskLocation ??= true;
resolved.server ??= {};
resolved.server.deps ??= {};
if (resolved.server.debug?.dump || process.env.VITEST_DEBUG_DUMP) {
const userFolder = resolved.server.debug?.dump || process.env.VITEST_DEBUG_DUMP;
resolved.dumpDir = resolve(resolved.root, typeof userFolder === "string" && userFolder !== "true" ? userFolder : ".vitest-dump", resolved.name || "root");
}
resolved.testTimeout ??= resolved.browser.enabled ? 15e3 : 5e3;
resolved.hookTimeout ??= resolved.browser.enabled ? 3e4 : 1e4;
resolved.experimental ??= {};
if (resolved.experimental.openTelemetry?.sdkPath) {
const sdkPath = resolve(resolved.root, resolved.experimental.openTelemetry.sdkPath);
resolved.experimental.openTelemetry.sdkPath = pathToFileURL$1(sdkPath).toString();
}
if (resolved.experimental.openTelemetry?.browserSdkPath) {
const browserSdkPath = resolve(resolved.root, resolved.experimental.openTelemetry.browserSdkPath);
resolved.experimental.openTelemetry.browserSdkPath = browserSdkPath;
}
if (resolved.experimental.fsModuleCachePath) resolved.experimental.fsModuleCachePath = resolve(resolved.root, resolved.experimental.fsModuleCachePath);
return resolved;
}
function isBrowserEnabled(config) {
return Boolean(config.browser?.enabled);
}
function resolveCoverageReporters(configReporters) {
// E.g. { reporter: "html" }
if (!Array.isArray(configReporters)) return [[configReporters, {}]];
const resolvedReporters = [];
for (const reporter of configReporters) if (Array.isArray(reporter))
// E.g. { reporter: [ ["html", { skipEmpty: true }], ["lcov"], ["json", { file: "map.json" }] ]}
resolvedReporters.push([reporter[0], reporter[1] || {}]);
else
// E.g. { reporter: ["html", "json"]}
resolvedReporters.push([reporter, {}]);
return resolvedReporters;
}
function isChromiumName(provider, name) {
if (provider === "playwright") return name === "chromium";
return name === "chrome" || name === "edge";
}
function hasBrowserChromium(vitest, config) {
const browser = config.browser;
if (!browser || !browser.provider || browser.provider.name === "preview" || !browser.enabled) return false;
if (browser.name) return isChromiumName(browser.provider.name, browser.name);
if (!browser.instances) return false;
return browser.instances.some((instance) => {
const name = instance.name || (config.name ? `${config.name} (${instance.browser})` : instance.browser);
// browser config is filtered out
if (!vitest.matchesProjectFilter(name)) return false;
return isChromiumName(browser.provider.name, instance.browser);
});
}
function hasOnlyBrowserChromium(vitest, config) {
const browser = config.browser;
if (!browser || !browser.provider || browser.provider.name === "preview" || !browser.enabled) return false;
if (browser.name) return isChromiumName(browser.provider.name, browser.name);
if (!browser.instances) return false;
return browser.instances.every((instance) => {
const name = instance.name || (config.name ? `${config.name} (${instance.browser})` : instance.browser);
// browser config is filtered out
if (!vitest.matchesProjectFilter(name)) return true;
return isChromiumName(browser.provider.name, instance.browser);
});
}
const THRESHOLD_KEYS = [
"lines",
"functions",
"statements",
"branches"
];
const GLOBAL_THRESHOLDS_KEY = "global";
const DEFAULT_PROJECT = Symbol.for("default-project");
let uniqueId = 0;
async function getCoverageProvider(options, loader) {
const coverageModule = await resolveCoverageProviderModule(options, loader);
if (coverageModule) return coverageModule.getProvider();
return null;
}
class BaseCoverageProvider {
ctx;
name;
version;
options;
globCache = /* @__PURE__ */ new Map();
coverageFiles = /* @__PURE__ */ new Map();
pendingPromises = [];
coverageFilesDirectory;
roots = [];
_initialize(ctx) {
this.ctx = ctx;
if (ctx.version !== this.version) ctx.logger.warn(c.yellow(`Loaded ${c.inverse(c.yellow(` vitest@${ctx.version} `))} and ${c.inverse(c.yellow(` @vitest/coverage-${this.name}@${this.version} `))}.
Running mixed versions is not supported and may lead into bugs
Update your dependencies and make sure the versions match.`));
const config = ctx._coverageOptions;
this.options = {
...coverageConfigDefaults,
...config,
provider: this.name,
reportsDirectory: resolve(ctx.config.root, config.reportsDirectory || coverageConfigDefaults.reportsDirectory),
reporter: resolveCoverageReporters(config.reporter || coverageConfigDefaults.reporter),
thresholds: config.thresholds && {
...config.thresholds,
lines: config.thresholds["100"] ? 100 : config.thresholds.lines,
branches: config.thresholds["100"] ? 100 : config.thresholds.branches,
functions: config.thresholds["100"] ? 100 : config.thresholds.functions,
statements: config.thresholds["100"] ? 100 : config.thresholds.statements
}
};
const shard = this.ctx.config.shard;
const tempDirectory = `.tmp${shard ? `-${shard.index}-${shard.count}` : ""}`;
this.coverageFilesDirectory = resolve(this.options.reportsDirectory, tempDirectory);
// If --project filter is set pick only roots of resolved projects
this.roots = ctx.config.project?.length ? [...new Set(ctx.projects.map((project) => project.config.root))] : [ctx.config.root];
}
/**
* Check if file matches `coverage.include` but not `coverage.exclude`
*/
isIncluded(_filename, root) {
const roots = root ? [root] : this.roots;
const filename = slash(_filename);
const cacheHit = this.globCache.get(filename);
if (cacheHit !== void 0) return cacheHit;
// File outside project root with default allowExternal
if (this.options.allowExternal === false && roots.every((root) => !filename.startsWith(root))) {
this.globCache.set(filename, false);
return false;
}
// By default `coverage.include` matches all files, except "coverage.exclude"
const glob = this.options.include || "**";
const included = pm.isMatch(filename, glob, {
contains: true,
dot: true,
ignore: this.options.exclude
});
this.globCache.set(filename, included);
return included;
}
async getUntestedFilesByRoot(testedFiles, include, root) {
let includedFiles = await glob(include, {
cwd: root,
ignore: [...this.options.exclude, ...testedFiles.map((file) => slash(file))],
absolute: true,
dot: true,
onlyFiles: true
});
// Run again through picomatch as tinyglobby's exclude pattern is different ({ "exclude": ["math"] } should ignore "src/math.ts")
includedFiles = includedFiles.filter((file) => this.isIncluded(file, root));
if (this.ctx.config.changed) includedFiles = (this.ctx.config.related || []).filter((file) => includedFiles.includes(file));
return includedFiles.map((file) => slash(path.resolve(root, file)));
}
async getUntestedFiles(testedFiles) {
if (this.options.include == null) return [];
const rootMapper = this.getUntestedFilesByRoot.bind(this, testedFiles, this.options.include);
return (await Promise.all(this.roots.map(rootMapper))).flatMap((files) => files);
}
createCoverageMap() {
throw new Error("BaseReporter's createCoverageMap was not overwritten");
}
async generateReports(_, __) {
throw new Error("BaseReporter's generateReports was not overwritten");
}
async parseConfigModule(_) {
throw new Error("BaseReporter's parseConfigModule was not overwritten");
}
resolveOptions() {
return this.options;
}
async clean(clean = true) {
if (clean && existsSync(this.options.reportsDirectory)) await promises.rm(this.options.reportsDirectory, {
recursive: true,
force: true,
maxRetries: 10
});
if (existsSync(this.coverageFilesDirectory)) await promises.rm(this.coverageFilesDirectory, {
recursive: true,
force: true,
maxRetries: 10
});
await promises.mkdir(this.coverageFilesDirectory, { recursive: true });
this.coverageFiles = /* @__PURE__ */ new Map();
this.pendingPromises = [];
}
onAfterSuiteRun({ coverage, environment, projectName, testFiles }) {
if (!coverage) return;
let entry = this.coverageFiles.get(projectName || DEFAULT_PROJECT);
if (!entry) {
entry = {};
this.coverageFiles.set(projectName || DEFAULT_PROJECT, entry);
}
const testFilenames = testFiles.join();
const filename = resolve(this.coverageFilesDirectory, `coverage-${uniqueId++}.json`);
entry[environment] ??= {};
// If there's a result from previous run, overwrite it
entry[environment][testFilenames] = filename;
const promise = promises.writeFile(filename, JSON.stringify(coverage), "utf-8");
this.pendingPromises.push(promise);
}
async readCoverageFiles({ onFileRead, onFinished, onDebug }) {
let index = 0;
const total = this.pendingPromises.length;
await Promise.all(this.pendingPromises);
this.pendingPromises = [];
for (const [projectName, coveragePerProject] of this.coverageFiles.entries()) for (const [environment, coverageByTestfiles] of Object.entries(coveragePerProject)) {
const filenames = Object.values(coverageByTestfiles);
const project = this.ctx.getProjectByName(projectName);
for (const chunk of this.toSlices(filenames, this.options.processingConcurrency)) {
if (onDebug.enabled) {
index += chunk.length;
onDebug(`Reading coverage results ${index}/${total}`);
}
await Promise.all(chunk.map(async (filename) => {
const contents = await promises.readFile(filename, "utf-8");
onFileRead(JSON.parse(contents));
}));
}
await onFinished(project, environment);
}
}
async cleanAfterRun() {
this.coverageFiles = /* @__PURE__ */ new Map();
await promises.rm(this.coverageFilesDirectory, { recursive: true });
// Remove empty reports directory, e.g. when only text-reporter is used
if (readdirSync(this.options.reportsDirectory).length === 0) await promises.rm(this.options.reportsDirectory, { recursive: true });
}
async onTestFailure() {
if (!this.options.reportOnFailure) await this.cleanAfterRun();
}
async reportCoverage(coverageMap, { allTestsRun }) {
await this.generateReports(coverageMap || this.createCoverageMap(), allTestsRun);
if (!(!this.options.cleanOnRerun && this.ctx.config.watch)) await this.cleanAfterRun();
}
async reportThresholds(coverageMap, allTestsRun) {
const resolvedThresholds = this.resolveThresholds(coverageMap);
this.checkThresholds(resolvedThresholds);
if (this.options.thresholds?.autoUpdate && allTestsRun) {
if (!this.ctx.vite.config.configFile) throw new Error("Missing configurationFile. The \"coverage.thresholds.autoUpdate\" can only be enabled when configuration file is used.");
const configFilePath = this.ctx.vite.config.configFile;
const configModule = await this.parseConfigModule(configFilePath);
await this.updateThresholds({
thresholds: resolvedThresholds,
configurationFile: configModule,
onUpdate: () => writeFileSync(configFilePath, configModule.generate().code, "utf-8")
});
}
}
/**
* Constructs collected coverage and users' threshold options into separate sets
* where each threshold set holds their own coverage maps. Threshold set is either
* for specific files defined by glob pattern or global for all other files.
*/
resolveThresholds(coverageMap) {
const resolvedThresholds = [];
const files = coverageMap.files();
const globalCoverageMap = this.createCoverageMap();
for (const key of Object.keys(this.options.thresholds)) {
if (key === "perFile" || key === "autoUpdate" || key === "100" || THRESHOLD_KEYS.includes(key)) continue;
const glob = key;
const globThresholds = resolveGlobThresholds(this.options.thresholds[glob]);
const globCoverageMap = this.createCoverageMap();
const matcher = pm(glob);
const matchingFiles = files.filter((file) => matcher(relative(this.ctx.config.root, file)));
for (const file of matchingFiles) {
const fileCoverage = coverageMap.fileCoverageFor(file);
globCoverageMap.addFileCoverage(fileCoverage);
}
resolvedThresholds.push({
name: glob,
coverageMap: globCoverageMap,
thresholds: globThresholds
});
}
// Global threshold is for all files, even if they are included by glob patterns
for (const file of files) {
const fileCoverage = coverageMap.fileCoverageFor(file);
globalCoverageMap.addFileCoverage(fileCoverage);
}
resolvedThresholds.unshift({
name: GLOBAL_THRESHOLDS_KEY,
coverageMap: globalCoverageMap,
thresholds: {
branches: this.options.thresholds?.branches,
functions: this.options.thresholds?.functions,
lines: this.options.thresholds?.lines,
statements: this.options.thresholds?.statements
}
});
return resolvedThresholds;
}
/**
* Check collected coverage against configured thresholds. Sets exit code to 1 when thresholds not reached.
*/
checkThresholds(allThresholds) {
for (const { coverageMap, thresholds, name } of allThresholds) {
if (thresholds.branches === void 0 && thresholds.functions === void 0 && thresholds.lines === void 0 && thresholds.statements === void 0) continue;
// Construct list of coverage summaries where thresholds are compared against
const summaries = this.options.thresholds?.perFile ? coverageMap.files().map((file) => ({
file,
summary: coverageMap.fileCoverageFor(file).toSummary()
})) : [{
file: null,
summary: coverageMap.getCoverageSummary()
}];
// Check thresholds of each summary
for (const { summary, file } of summaries) for (const thresholdKey of THRESHOLD_KEYS) {
const threshold = thresholds[thresholdKey];
if (threshold === void 0) continue;
/**
* Positive thresholds are treated as minimum coverage percentages (X means: X% of lines must be covered),
* while negative thresholds are treated as maximum uncovered counts (-X means: X lines may be uncovered).
*/
if (threshold >= 0) {
const coverage = summary.data[thresholdKey].pct;
if (coverage < threshold) {
process.exitCode = 1;
/**
* Generate error message based on perFile flag:
* - ERROR: Coverage for statements (33.33%) does not meet threshold (85%) for src/math.ts
* - ERROR: Coverage for statements (50%) does not meet global threshold (85%)
*/
let errorMessage = `ERROR: Coverage for ${thresholdKey} (${coverage}%) does not meet ${name === GLOBAL_THRESHOLDS_KEY ? name : `"${name}"`} threshold (${threshold}%)`;
if (this.options.thresholds?.perFile && file) errorMessage += ` for ${relative("./", file).replace(/\\/g, "/")}`;
this.ctx.logger.error(errorMessage);
}
} else {
const uncovered = summary.data[thresholdKey].total - summary.data[thresholdKey].covered;
const absoluteThreshold = threshold * -1;
if (uncovered > absoluteThreshold) {
process.exitCode = 1;
/**
* Generate error message based on perFile flag:
* - ERROR: Uncovered statements (33) exceed threshold (30) for src/math.ts
* - ERROR: Uncovered statements (33) exceed global threshold (30)
*/
let errorMessage = `ERROR: Uncovered ${thresholdKey} (${uncovered}) exceed ${name === GLOBAL_THRESHOLDS_KEY ? name : `"${name}"`} threshold (${absoluteThreshold})`;
if (this.options.thresholds?.perFile && file) errorMessage += ` for ${relative("./", file).replace(/\\/g, "/")}`;
this.ctx.logger.error(errorMessage);
}
}
}
}
}
/**
* Check if current coverage is above configured thresholds and bump the thresholds if needed
*/
async updateThresholds({ thresholds: allThresholds, onUpdate, configurationFile }) {
let updatedThresholds = false;
const config = resolveConfig(configurationFile);
assertConfigurationModule(config);
for (const { coverageMap, thresholds, name } of allThresholds) {
const summaries = this.options.thresholds?.perFile ? coverageMap.files().map((file) => coverageMap.fileCoverageFor(file).toSummary()) : [coverageMap.getCoverageSummary()];
const thresholdsToUpdate = [];
for (const key of THRESHOLD_KEYS) {
const threshold = thresholds[key] ?? 100;
/**
* Positive thresholds are treated as minimum coverage percentages (X means: X% of lines must be covered),
* while negative thresholds are treated as maximum uncovered counts (-X means: X lines may be uncovered).
*/
if (threshold >= 0) {
const actual = Math.min(...summaries.map((summary) => summary[key].pct));
if (actual > threshold) thresholdsToUpdate.push([key, actual]);
} else {
const absoluteThreshold = threshold * -1;
const actual = Math.max(...summaries.map((summary) => summary[key].total - summary[key].covered));
if (actual < absoluteThreshold) {
// If everything was covered, set new threshold to 100% (since a threshold of 0 would be considered as 0%)
const updatedThreshold = actual === 0 ? 100 : actual * -1;
thresholdsToUpdate.push([key, updatedThreshold]);
}
}
}
if (thresholdsToUpdate.length === 0) continue;
updatedThresholds = true;
const thresholdFormatter = typeof this.options.thresholds?.autoUpdate === "function" ? this.options.thresholds?.autoUpdate : (value) => value;
for (const [threshold, newValue] of thresholdsToUpdate) {
const formattedValue = thresholdFormatter(newValue);
if (name === GLOBAL_THRESHOLDS_KEY) config.test.coverage.thresholds[threshold] = formattedValue;
else {
const glob = config.test.coverage.thresholds[name];
glob[threshold] = formattedValue;
}
}
}
if (updatedThresholds) {
this.ctx.logger.log("Updating thresholds to configuration file. You may want to push with updated coverage thresholds.");
onUpdate();
}
}
async mergeReports(coverageMaps) {
const coverageMap = this.createCoverageMap();
for (const coverage of coverageMaps) coverageMap.merge(coverage);
await this.generateReports(coverageMap, true);
}
hasTerminalReporter(reporters) {
return reporters.some(([reporter]) => reporter === "text" || reporter === "text-summary" || reporter === "text-lcov" || reporter === "teamcity");
}
toSlices(array, size) {
return array.reduce((chunks, item) => {
const index = Math.max(0, chunks.length - 1);
const lastChunk = chunks[index] || [];
chunks[index] = lastChunk;
if (lastChunk.length >= size) chunks.push([item]);
else lastChunk.push(item);
return chunks;
}, []);
}
createUncoveredFileTransformer(ctx) {
const servers = [...ctx.projects.map((project) => ({
root: project.config.root,
isBrowserEnabled: project.isBrowserEnabled(),
vite: project.vite
})), (
// Check core last as it will match all files anyway
{
root: ctx.config.root,
vite: ctx.vite,
isBrowserEnabled: ctx.getRootProject().isBrowserEnabled()
})];
return async function transformFile(filename) {
let lastError;
for (const { root, vite, isBrowserEnabled } of servers) {
// On Windows root doesn't start with "/" while filenames do
if (!filename.startsWith(root) && !filename.startsWith(`/${root}`)) continue;
if (isBrowserEnabled) {
const result = await vite.environments.client.transformRequest(filename).catch(() => null);
if (result) return result;
}
try {
return await vite.environments.ssr.transformRequest(filename);
} catch (error) {
lastError = error;
}
}
// All vite-node servers failed to transform the file
throw lastError;
};
}
}
/**
* Narrow down `unknown` glob thresholds to resolved ones
*/
function resolveGlobThresholds(thresholds) {
if (!thresholds || typeof thresholds !== "object") return {};
if (100 in thresholds && thresholds[100] === true) return {
lines: 100,
branches: 100,
functions: 100,
statements: 100
};
return {
lines: "lines" in thresholds && typeof thresholds.lines === "number" ? thresholds.lines : void 0,
branches: "branches" in thresholds && typeof thresholds.branches === "number" ? thresholds.branches : void 0,
functions: "functions" in thresholds && typeof thresholds.functions === "number" ? thresholds.functions : void 0,
statements: "statements" in thresholds && typeof thresholds.statements === "number" ? thresholds.statements : void 0
};
}
function assertConfigurationModule(config) {
try {
// @ts-expect-error -- Intentional unsafe null pointer check as wrapped in try-catch
if (typeof config.test.coverage.thresholds !== "object") throw new TypeError("Expected config.test.coverage.thresholds to be an object");
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Unable to parse thresholds from configuration file: ${message}`);
}
}
function resolveConfig(configModule) {
const mod = configModule.exports.default;
try {
// Check for "export default { test: {...} }"
if (mod.$type === "object") return mod;
// "export default defineConfig(...)"
let config = resolveDefineConfig(mod);
if (config) return config;
// "export default mergeConfig(..., defineConfig(...))"
if (mod.$type === "function-call" && mod.$callee === "mergeConfig") {
config = resolveMergeConfig(mod);
if (config) return config;
}
} catch (error) {
// Reduce magicast's verbose errors to readable ones
throw new Error(error instanceof Error ? error.message : String(error));
}
throw new Error("Failed to update coverage thresholds. Configuration file is too complex.");
}
function resolveDefineConfig(mod) {
if (mod.$type === "function-call" && mod.$callee === "defineConfig") {
// "export default defineConfig({ test: {...} })"
if (mod.$args[0].$type === "object") return mod.$args[0];
if (mod.$args[0].$type === "arrow-function-expression") {
if (mod.$args[0].$body.$type === "object")
// "export default defineConfig(() => ({ test: {...} }))"
return mod.$args[0].$body;
// "export default defineConfig(() => mergeConfig({...}, ...))"
const config = resolveMergeConfig(mod.$args[0].$body);
if (config) return config;
}
}
}
function resolveMergeConfig(mod) {
if (mod.$type === "function-call" && mod.$callee === "mergeConfig") for (const arg of mod.$args) {
const config = resolveDefineConfig(arg);
if (config) return config;
}
}
export { BaseCoverageProvider as B, RandomSequencer as R, resolveApiServerConfig as a, BaseSequencer as b, isBrowserEnabled as c, resolveModule as d, getCoverageProvider as g, hash as h, isPackageExists as i, resolveConfig$1 as r };
export { isPackageExists as i, resolveModule as r };
-231
View File
@@ -1,231 +0,0 @@
import fs from 'node:fs';
import { getTasks, getFullName, getTests } from '@vitest/runner/utils';
import * as pathe from 'pathe';
import c from 'tinyrainbow';
import { g as getStateSymbol, t as truncateString, F as F_RIGHT, D as DefaultReporter, f as formatProjectName, s as separator } from './index.M8mOzt4Y.js';
import { stripVTControlCharacters } from 'node:util';
import { notNullish } from '@vitest/utils/helpers';
function createBenchmarkJsonReport(files) {
const report = { files: [] };
for (const file of files) {
const groups = [];
for (const task of getTasks(file)) if (task?.type === "suite") {
const benchmarks = [];
for (const t of task.tasks) {
const benchmark = t.meta.benchmark && t.result?.benchmark;
if (benchmark) benchmarks.push({
id: t.id,
...benchmark,
samples: []
});
}
if (benchmarks.length) groups.push({
fullName: getFullName(task, " > "),
benchmarks
});
}
report.files.push({
filepath: file.filepath,
groups
});
}
return report;
}
function flattenFormattedBenchmarkReport(report) {
const flat = {};
for (const file of report.files) for (const group of file.groups) for (const t of group.benchmarks) flat[t.id] = t;
return flat;
}
const outputMap = /* @__PURE__ */ new WeakMap();
function formatNumber(number) {
const res = String(number.toFixed(number < 100 ? 4 : 2)).split(".");
return res[0].replace(/(?=(?:\d{3})+$)\B/g, ",") + (res[1] ? `.${res[1]}` : "");
}
const tableHead = [
"name",
"hz",
"min",
"max",
"mean",
"p75",
"p99",
"p995",
"p999",
"rme",
"samples"
];
function renderBenchmarkItems(result) {
return [
result.name,
formatNumber(result.hz || 0),
formatNumber(result.min || 0),
formatNumber(result.max || 0),
formatNumber(result.mean || 0),
formatNumber(result.p75 || 0),
formatNumber(result.p99 || 0),
formatNumber(result.p995 || 0),
formatNumber(result.p999 || 0),
`±${(result.rme || 0).toFixed(2)}%`,
(result.sampleCount || 0).toString()
];
}
function computeColumnWidths(results) {
const rows = [tableHead, ...results.map((v) => renderBenchmarkItems(v))];
return Array.from(tableHead, (_, i) => Math.max(...rows.map((row) => stripVTControlCharacters(row[i]).length)));
}
function padRow(row, widths) {
return row.map((v, i) => i ? v.padStart(widths[i], " ") : v.padEnd(widths[i], " "));
}
function renderTableHead(widths) {
return " ".repeat(3) + padRow(tableHead, widths).map(c.bold).join(" ");
}
function renderBenchmark(result, widths) {
const padded = padRow(renderBenchmarkItems(result), widths);
return [
padded[0],
c.blue(padded[1]),
c.cyan(padded[2]),
c.cyan(padded[3]),
c.cyan(padded[4]),
c.cyan(padded[5]),
c.cyan(padded[6]),
c.cyan(padded[7]),
c.cyan(padded[8]),
c.dim(padded[9]),
c.dim(padded[10])
].join(" ");
}
function renderTable(options) {
const output = [];
const benchMap = {};
for (const task of options.tasks) if (task.meta.benchmark && task.result?.benchmark) benchMap[task.id] = {
current: task.result.benchmark,
baseline: options.compare?.[task.id]
};
const benchCount = Object.entries(benchMap).length;
const columnWidths = computeColumnWidths(Object.values(benchMap).flatMap((v) => [v.current, v.baseline]).filter(notNullish));
let idx = 0;
const padding = " ".repeat(1 );
for (const task of options.tasks) {
const duration = task.result?.duration;
const bench = benchMap[task.id];
let prefix = "";
if (idx === 0 && task.meta?.benchmark) prefix += `${renderTableHead(columnWidths)}\n${padding}`;
prefix += ` ${getStateSymbol(task)} `;
let suffix = "";
if (task.type === "suite") suffix += c.dim(` (${getTests(task).length})`);
if (task.mode === "skip" || task.mode === "todo") suffix += c.dim(c.gray(" [skipped]"));
if (duration != null) {
const color = duration > options.slowTestThreshold ? c.yellow : c.green;
suffix += color(` ${Math.round(duration)}${c.dim("ms")}`);
}
if (options.showHeap && task.result?.heap != null) suffix += c.magenta(` ${Math.floor(task.result.heap / 1024 / 1024)} MB heap used`);
if (bench) {
let body = renderBenchmark(bench.current, columnWidths);
if (options.compare && bench.baseline) {
if (bench.current.hz) {
const diff = bench.current.hz / bench.baseline.hz;
const diffFixed = diff.toFixed(2);
if (diffFixed === "1.0.0") body += c.gray(` [${diffFixed}x]`);
if (diff > 1) body += c.blue(` [${diffFixed}x] ⇑`);
else body += c.red(` [${diffFixed}x] ⇓`);
}
output.push(padding + prefix + body + suffix);
const bodyBaseline = renderBenchmark(bench.baseline, columnWidths);
output.push(`${padding} ${bodyBaseline} ${c.dim("(baseline)")}`);
} else {
if (bench.current.rank === 1 && benchCount > 1) body += c.bold(c.green(" fastest"));
if (bench.current.rank === benchCount && benchCount > 2) body += c.bold(c.gray(" slowest"));
output.push(padding + prefix + body + suffix);
}
} else output.push(padding + prefix + task.name + suffix);
if (task.result?.state !== "pass" && outputMap.get(task) != null) {
let data = outputMap.get(task);
if (typeof data === "string") {
data = stripVTControlCharacters(data.trim().split("\n").filter(Boolean).pop());
if (data === "") data = void 0;
}
if (data != null) {
const out = ` ${" ".repeat(options.level)}${F_RIGHT} ${data}`;
output.push(c.gray(truncateString(out, options.columns)));
}
}
idx++;
}
return output.filter(Boolean).join("\n");
}
class BenchmarkReporter extends DefaultReporter {
compare;
async onInit(ctx) {
super.onInit(ctx);
if (this.ctx.config.benchmark?.compare) {
const compareFile = pathe.resolve(this.ctx.config.root, this.ctx.config.benchmark?.compare);
try {
this.compare = flattenFormattedBenchmarkReport(JSON.parse(await fs.promises.readFile(compareFile, "utf-8")));
} catch (e) {
this.error(`Failed to read '${compareFile}'`, e);
}
}
}
onTaskUpdate(packs) {
for (const pack of packs) {
const task = this.ctx.state.idMap.get(pack[0]);
if (task?.type === "suite" && task.result?.state !== "run") task.tasks.filter((task) => task.result?.benchmark).sort((benchA, benchB) => benchA.result.benchmark.mean - benchB.result.benchmark.mean).forEach((bench, idx) => {
bench.result.benchmark.rank = Number(idx) + 1;
});
}
}
onTestSuiteResult(testSuite) {
super.onTestSuiteResult(testSuite);
this.printSuiteTable(testSuite);
}
printTestModule(testModule) {
this.printSuiteTable(testModule);
}
printSuiteTable(testTask) {
const state = testTask.state();
if (state === "pending" || state === "queued") return;
const benches = testTask.task.tasks.filter((t) => t.meta.benchmark);
const duration = testTask.task.result?.duration || 0;
if (benches.length > 0 && benches.every((t) => t.result?.state !== "run" && t.result?.state !== "queued")) {
let title = `\n ${getStateSymbol(testTask.task)} ${formatProjectName(testTask.project)}${getFullName(testTask.task, separator)}`;
if (duration != null && duration > this.ctx.config.slowTestThreshold) title += c.yellow(` ${Math.round(duration)}${c.dim("ms")}`);
this.log(title);
this.log(renderTable({
tasks: benches,
level: 1,
columns: this.ctx.logger.getColumns(),
compare: this.compare,
showHeap: this.ctx.config.logHeapUsage,
slowTestThreshold: this.ctx.config.slowTestThreshold
}));
}
}
async onTestRunEnd(testModules, unhandledErrors, reason) {
super.onTestRunEnd(testModules, unhandledErrors, reason);
// write output for future comparison
let outputFile = this.ctx.config.benchmark?.outputJson;
if (outputFile) {
outputFile = pathe.resolve(this.ctx.config.root, outputFile);
const outputDirectory = pathe.dirname(outputFile);
if (!fs.existsSync(outputDirectory)) await fs.promises.mkdir(outputDirectory, { recursive: true });
const output = createBenchmarkJsonReport(testModules.map((t) => t.task.file));
await fs.promises.writeFile(outputFile, JSON.stringify(output, null, 2));
this.log(`Benchmark report written to ${outputFile}`);
}
}
}
class VerboseBenchmarkReporter extends BenchmarkReporter {
verbose = true;
}
const BenchmarkReportsMap = {
default: BenchmarkReporter,
verbose: VerboseBenchmarkReporter
};
export { BenchmarkReporter as B, VerboseBenchmarkReporter as V, BenchmarkReportsMap as a };
@@ -209,5 +209,30 @@ async function installPackage(names, options = {}) {
}
);
}
async function uninstallPackage(names, options = {}) {
const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm";
const [agent] = detectedAgent.split("@");
if (!Array.isArray(names))
names = [names];
const args = options.additionalArgs || [];
if (agent === "pnpm" && existsSync(resolve(options.cwd ?? process.cwd(), "pnpm-workspace.yaml")))
args.unshift("-w");
return x(
agent,
[
agent === "yarn" ? "remove" : "uninstall",
options.dev ? "-D" : "",
...args,
...names
].filter(Boolean),
{
nodeOptions: {
stdio: options.silent ? "ignore" : "inherit",
cwd: options.cwd
},
throwOnError: true
}
);
}
export { detectPackageManager, installPackage };
export { detectPackageManager, installPackage, uninstallPackage };
@@ -1,4 +1,4 @@
import { URL } from 'node:url';
import { URL as URL$1 } from 'node:url';
import { Console } from 'node:console';
// SEE https://github.com/jsdom/jsdom/blob/master/lib/jsdom/living/interfaces.js
@@ -254,11 +254,11 @@ function populateGlobal(global, win, options = {}) {
const { bindFunctions = false } = options;
const keys = getWindowKeys(global, win, options.additionalKeys);
const originals = /* @__PURE__ */ new Map();
const overridenKeys = new Set([...KEYS, ...options.additionalKeys || []]);
const overriddenKeys = new Set([...KEYS, ...options.additionalKeys || []]);
const overrideObject = /* @__PURE__ */ new Map();
for (const key of keys) {
const boundFunction = bindFunctions && typeof win[key] === "function" && !isClassLikeName(key) && win[key].bind(win);
if (overridenKeys.has(key) && key in global) originals.set(key, global[key]);
if (overriddenKeys.has(key) && key in global) originals.set(key, global[key]);
Object.defineProperty(global, key, {
get() {
if (overrideObject.has(key)) return overrideObject.get(key);
@@ -537,7 +537,7 @@ var jsdom = {
}
};
function createCompatRequest(utils) {
return class Request extends NodeRequest_ {
class Request extends NodeRequest_ {
constructor(...args) {
const [input, init] = args;
if (init?.body != null) {
@@ -550,21 +550,23 @@ function createCompatRequest(utils) {
static [Symbol.hasInstance](instance) {
return instance instanceof NodeRequest_;
}
};
}
return Request;
}
function createJSDOMCompatURL(utils) {
return class URL$1 extends URL {
class URL extends URL$1 {
static createObjectURL(blob) {
if (blob instanceof utils.window.Blob) {
const compatBlob = utils.makeCompatBlob(blob);
return URL.createObjectURL(compatBlob);
return URL$1.createObjectURL(compatBlob);
}
return URL.createObjectURL(blob);
return URL$1.createObjectURL(blob);
}
static [Symbol.hasInstance](instance) {
return instance instanceof URL;
return instance instanceof URL$1;
}
};
}
return URL;
}
function createCompatUtils(window) {
// this returns a hidden Symbol(impl)
@@ -1,25 +1,99 @@
import { chai } from '@vitest/expect';
import { l as loadDiffConfig, b as loadSnapshotSerializers, t as takeCoverageInsideWorker } from './setup-common.Cm-kSBVi.js';
import { r as rpc } from './rpc.BoxB0q7B.js';
import { g as getWorkerState } from './utils.DvEY5TfP.js';
import { V as VitestTestRunner, N as NodeBenchmarkRunner } from './test.B8ej_ZHS.js';
import { createHook } from 'node:async_hooks';
import { l as loadDiffConfig, a as loadSnapshotSerializers, t as takeCoverageInsideWorker } from './setup-common.DYx3LtFI.js';
import { r as rpc } from './rpc.MzXet3jl.js';
import { g as getWorkerState } from './utils.BX5Fg8C4.js';
import { T as TestRunner, N as NodeBenchmarkRunner } from './test.DNmyFkvJ.js';
function setupChaiConfig(config) {
Object.assign(chai.config, config);
}
async function resolveSnapshotEnvironment(config, executor) {
async function resolveSnapshotEnvironment(config, moduleRunner) {
if (!config.snapshotEnvironment) {
const { VitestNodeSnapshotEnvironment } = await import('./node.Ce0vMQM7.js');
const { VitestNodeSnapshotEnvironment } = await import('./node.COQbm6gK.js');
return new VitestNodeSnapshotEnvironment();
}
const mod = await executor.import(config.snapshotEnvironment);
const mod = await moduleRunner.import(config.snapshotEnvironment);
if (typeof mod.default !== "object" || !mod.default) throw new Error("Snapshot environment module must have a default export object with a shape of `SnapshotEnvironment`");
return mod.default;
}
const IGNORED_TYPES = new Set([
"DNSCHANNEL",
"ELDHISTOGRAM",
"PerformanceObserver",
"RANDOMBYTESREQUEST",
"SIGNREQUEST",
"STREAM_END_OF_STREAM",
"TCPWRAP",
"TIMERWRAP",
"TLSWRAP",
"ZLIB"
]);
function detectAsyncLeaks(testFile, projectName) {
const resources = /* @__PURE__ */ new Map();
const hook = createHook({
init(asyncId, type, triggerAsyncId, resource) {
if (IGNORED_TYPES.has(type)) return;
let stack = "";
const limit = Error.stackTraceLimit;
// VitestModuleEvaluator's async wrapper of node:vm causes out-of-bound stack traces, simply skip it.
// Crash fixed in https://github.com/vitejs/vite/pull/21585
try {
Error.stackTraceLimit = 100;
stack = (/* @__PURE__ */ new Error("VITEST_DETECT_ASYNC_LEAKS")).stack || "";
} catch {
return;
} finally {
Error.stackTraceLimit = limit;
}
if (!stack.includes(testFile)) {
const trigger = resources.get(triggerAsyncId);
if (!trigger) return;
stack = trigger.stack;
}
let isActive = isActiveDefault;
if ("hasRef" in resource) {
const ref = new WeakRef(resource);
isActive = () => ref.deref()?.hasRef() ?? false;
}
resources.set(asyncId, {
type,
stack,
projectName,
filename: testFile,
isActive
});
},
destroy(asyncId) {
if (resources.get(asyncId)?.type !== "PROMISE") resources.delete(asyncId);
},
promiseResolve(asyncId) {
resources.delete(asyncId);
}
});
hook.enable();
return async function collect() {
await Promise.resolve(setImmediate);
hook.disable();
const leaks = [];
for (const resource of resources.values()) if (resource.isActive()) leaks.push({
stack: resource.stack,
type: resource.type,
filename: resource.filename,
projectName: resource.projectName
});
resources.clear();
return leaks;
};
}
function isActiveDefault() {
return true;
}
async function getTestRunnerConstructor(config, moduleRunner) {
if (!config.runner) return config.mode === "test" ? VitestTestRunner : NodeBenchmarkRunner;
if (!config.runner) return config.mode === "test" ? TestRunner : NodeBenchmarkRunner;
const mod = await moduleRunner.import(config.runner);
if (!mod.default && typeof mod.default !== "function") throw new Error(`Runner must export a default function, but got ${typeof mod.default} imported from ${config.runner}`);
return mod.default;
@@ -78,6 +152,18 @@ async function resolveTestRunner(config, moduleRunner, traces) {
state.durations.prepare = 0;
state.durations.environment = 0;
});
// Strip function conditions from retry config before sending via RPC
// Functions cannot be cloned by structured clone algorithm
const sanitizeRetryConditions = (task) => {
if (task.retry && typeof task.retry === "object" && typeof task.retry.condition === "function")
// Remove function condition - it can't be serialized
task.retry = {
...task.retry,
condition: void 0
};
if (task.tasks) task.tasks.forEach(sanitizeRetryConditions);
};
files.forEach(sanitizeRetryConditions);
rpc().onCollected(files);
await originalOnCollected?.call(testRunner, files);
};
@@ -106,4 +192,4 @@ async function resolveTestRunner(config, moduleRunner, traces) {
return testRunner;
}
export { resolveSnapshotEnvironment as a, resolveTestRunner as r, setupChaiConfig as s };
export { resolveSnapshotEnvironment as a, detectAsyncLeaks as d, resolveTestRunner as r, setupChaiConfig as s };
@@ -1,17 +1,22 @@
import { b as assert, c as createExpect, g as globalExpect, i as inject, s as should, v as vi, d as vitest } from './vi.2VT5v0um.js';
import { b as bench } from './benchmark.B3N2zMcH.js';
import { v as vi, N as NodeBenchmarkRunner, S as Snapshots, T as TestRunner, a as assert, c as createExpect, g as globalExpect, i as inject, s as should, b as vitest } from './test.DNmyFkvJ.js';
import { b as bench } from './benchmark.CX_oY03V.js';
import { V as VitestEvaluatedModules } from './evaluatedModules.Dg1zASAC.js';
import { expectTypeOf } from 'expect-type';
import { afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, recordArtifact, suite, test } from '@vitest/runner';
import { afterAll, afterEach, aroundAll, aroundEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, recordArtifact, suite, test } from '@vitest/runner';
import { chai } from '@vitest/expect';
const assertType = function assertType() {};
var index = /*#__PURE__*/Object.freeze({
__proto__: null,
BenchmarkRunner: NodeBenchmarkRunner,
EvaluatedModules: VitestEvaluatedModules,
Snapshots: Snapshots,
TestRunner: TestRunner,
afterAll: afterAll,
afterEach: afterEach,
aroundAll: aroundAll,
aroundEach: aroundEach,
assert: assert,
assertType: assertType,
beforeAll: beforeAll,
File diff suppressed because it is too large Load Diff
@@ -1,4 +1,4 @@
import { resolve, isAbsolute, dirname, join } from 'node:path';
import { isAbsolute, resolve, dirname, join } from 'node:path';
import { existsSync } from 'node:fs';
import 'node:module';
import 'node:url';
@@ -6,6 +6,21 @@ import { g as getDefaultExportFromCjs } from './_commonjsHelpers.D26ty3Ew.js';
import require$$0 from 'readline';
import require$$0$1 from 'events';
function _mergeNamespaces(n, m) {
m.forEach(function (e) {
e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
if (k !== 'default' && !(k in n)) {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
});
return Object.freeze(n);
}
/**
* Resolve an absolute path from {@link root}, but only
* if {@link input} isn't already absolute.
@@ -6335,9 +6350,9 @@ function requirePrompts () {
var promptsExports = requirePrompts();
var prompt = /*@__PURE__*/getDefaultExportFromCjs(promptsExports);
var index = /*#__PURE__*/Object.freeze({
var index = /*#__PURE__*/_mergeNamespaces({
__proto__: null,
default: prompt
});
}, [promptsExports]);
export { any as a, index as i, prompt as p };
@@ -1,4 +1,4 @@
import { i as init } from './init.B6MLFIaN.js';
import { i as init } from './init.d4hAcNdp.js';
if (!process.send) throw new Error("Expected worker to be run in node:child_process");
// Store globals in case tests overwrite them
@@ -1,5 +1,5 @@
import { isMainThread, parentPort } from 'node:worker_threads';
import { i as init } from './init.B6MLFIaN.js';
import { i as init } from './init.d4hAcNdp.js';
if (isMainThread || !parentPort) throw new Error("Expected worker to be run in node:worker_threads");
function workerInit(options) {
@@ -2,15 +2,18 @@ import { readFileSync } from 'node:fs';
import { isBuiltin } from 'node:module';
import { pathToFileURL } from 'node:url';
import { resolve } from 'pathe';
import { ModuleRunner } from 'vite/module-runner';
import { b as VitestTransport } from './startModuleRunner.DEj0jb3e.js';
import { e as environments } from './index.CyBMJtT7.js';
import { ModuleRunner, EvaluatedModules } from 'vite/module-runner';
import { b as VitestTransport } from './startVitestModuleRunner.CCBQZ9DQ.js';
import { e as environments } from './index.DC7d2Pf8.js';
import { serializeValue } from '@vitest/utils/serialize';
import { serializeError } from '@vitest/utils/error';
import { T as Traces } from './traces.CCmnQaNT.js';
import { o as onCancel, a as rpcDone, c as createRuntimeRpc } from './rpc.BoxB0q7B.js';
import { disableDefaultColors } from 'tinyrainbow';
import { T as Traces } from './traces.DT5aQ62U.js';
import { o as onCancel, a as rpcDone, c as createRuntimeRpc } from './rpc.MzXet3jl.js';
import { createStackString, parseStacktrace } from '@vitest/utils/source-map';
import { s as setupInspect } from './inspector.CvyFGlXm.js';
import { V as VitestEvaluatedModules } from './evaluatedModules.Dg1zASAC.js';
import { E as EnvironmentTeardownError } from './utils.BX5Fg8C4.js';
function isBuiltinEnvironment(env) {
return env in environments;
@@ -40,17 +43,17 @@ function createEnvironmentLoader(root, rpc) {
async resolveId(id, importer) {
return rpc.resolve(id, importer, "__vitest__");
}
})
}, new EvaluatedModules(), /* @__PURE__ */ new WeakMap())
});
_loaders.set(root, moduleRunner);
}
return _loaders.get(root);
}
async function loadEnvironment(name, root, rpc, traces) {
if (isBuiltinEnvironment(name)) return { environment: environments[name] };
const loader = createEnvironmentLoader(root, rpc);
const packageId = name[0] === "." || name[0] === "/" ? resolve(root, name) : (await traces.$("vitest.runtime.environment.resolve", () => rpc.resolve(`vitest-environment-${name}`, void 0, "__vitest__")))?.id ?? resolve(root, name);
const pkg = await traces.$("vitest.runtime.environment.import", () => loader.import(packageId));
async function loadNativeEnvironment(name, root, traces) {
const packageId = name[0] === "." || name[0] === "/" ? pathToFileURL(resolve(root, name)).toString() : import.meta.resolve(`vitest-environment-${name}`, pathToFileURL(root).toString());
return resolveEnvironmentFromModule(name, packageId, await traces.$("vitest.runtime.environment.import", () => import(packageId)));
}
function resolveEnvironmentFromModule(name, packageId, pkg) {
if (!pkg || !pkg.default || typeof pkg.default !== "object") throw new TypeError(`Environment "${name}" is not a valid environment. Path "${packageId}" should export default object with a "setup" or/and "setupVM" method.`);
const environment = pkg.default;
if (environment.transformMode != null && environment.transformMode !== "web" && environment.transformMode !== "ssr") throw new TypeError(`Environment "${name}" is not a valid environment. Path "${packageId}" should export default object with a "transformMode" method equal to "ssr" or "web", received "${environment.transformMode}".`);
@@ -59,8 +62,15 @@ async function loadEnvironment(name, root, rpc, traces) {
// keep for backwards compat
environment.viteEnvironment ??= environment.transformMode === "ssr" ? "ssr" : "client";
}
return environment;
}
async function loadEnvironment(name, root, rpc, traces, viteModuleRunner) {
if (isBuiltinEnvironment(name)) return { environment: environments[name] };
if (!viteModuleRunner) return { environment: await loadNativeEnvironment(name, root, traces) };
const loader = createEnvironmentLoader(root, rpc);
const packageId = name[0] === "." || name[0] === "/" ? resolve(root, name) : (await traces.$("vitest.runtime.environment.resolve", () => rpc.resolve(`vitest-environment-${name}`, void 0, "__vitest__")))?.id ?? resolve(root, name);
return {
environment,
environment: resolveEnvironmentFromModule(name, packageId, await traces.$("vitest.runtime.environment.import", () => loader.import(packageId))),
loader
};
}
@@ -80,6 +90,36 @@ function emitModuleRunner(moduleRunner) {
moduleRunnerListeners.forEach((l) => l(moduleRunner));
}
// Store globals in case tests overwrite them
const processListeners = process.listeners.bind(process);
const processOn = process.on.bind(process);
const processOff = process.off.bind(process);
const dispose = [];
function listenForErrors(state) {
dispose.forEach((fn) => fn());
dispose.length = 0;
function catchError(err, type, event) {
const worker = state();
// if there is another listener, assume that it's handled by user code
// one is Vitest's own listener
if (processListeners(event).length > 1) return;
const error = serializeValue(err);
if (typeof error === "object" && error != null) {
error.VITEST_TEST_NAME = worker.current?.type === "test" ? worker.current.name : void 0;
if (worker.filepath) error.VITEST_TEST_PATH = worker.filepath;
}
state().rpc.onUnhandledError(error, type);
}
const uncaughtException = (e) => catchError(e, "Uncaught Exception", "uncaughtException");
const unhandledRejection = (e) => catchError(e, "Unhandled Rejection", "unhandledRejection");
processOn("uncaughtException", uncaughtException);
processOn("unhandledRejection", unhandledRejection);
dispose.push(() => {
processOff("uncaughtException", uncaughtException);
processOff("unhandledRejection", unhandledRejection);
});
}
const resolvingModules = /* @__PURE__ */ new Set();
async function execute(method, ctx, worker, traces) {
const prepareStart = performance.now();
@@ -90,7 +130,7 @@ async function execute(method, ctx, worker, traces) {
// do not close the RPC channel so that we can get the error messages sent to the main thread
cleanups.push(async () => {
await Promise.all(rpc.$rejectPendingCalls(({ method, reject }) => {
reject(/* @__PURE__ */ new Error(`[vitest-worker]: Closing rpc while "${method}" was pending`));
reject(new EnvironmentTeardownError(`[vitest-worker]: Closing rpc while "${method}" was pending`));
}));
});
const state = {
@@ -176,6 +216,7 @@ function init(worker) {
process.env.VITEST_POOL_ID = String(message.poolId);
process.env.VITEST_WORKER_ID = String(message.workerId);
reportMemory = message.options.reportMemory;
if (message.context.config.isAgent) disableDefaultColors();
traces ??= await new Traces({
enabled: message.traces.enabled,
sdkPath: message.traces.sdkPath
@@ -331,4 +372,4 @@ function getFilesWithLocations(files) {
});
}
export { emitModuleRunner as e, init as i, loadEnvironment as l };
export { listenForErrors as a, emitModuleRunner as e, init as i, loadEnvironment as l };
+148
View File
@@ -0,0 +1,148 @@
import module$1, { isBuiltin } from 'node:module';
import { fileURLToPath } from 'node:url';
import { MessageChannel } from 'node:worker_threads';
import { initSyntaxLexers, hoistMocks } from '@vitest/mocker/transforms';
import { cleanUrl } from '@vitest/utils/helpers';
import { p as parse } from './acorn.B2iPLyUM.js';
import MagicString from 'magic-string';
import { resolve } from 'pathe';
import c from 'tinyrainbow';
import { distDir } from '../path.js';
import { t as toBuiltin } from './modules.BJuCwlRJ.js';
import 'node:path';
const NOW_LENGTH = Date.now().toString().length;
const REGEXP_VITEST = new RegExp(`%3Fvitest=\\d{${NOW_LENGTH}}`);
const REGEXP_MOCK_ACTUAL = /\?mock=actual/;
async function setupNodeLoaderHooks(worker) {
if (module$1.setSourceMapsSupport) module$1.setSourceMapsSupport(true);
else if (process.setSourceMapsEnabled) process.setSourceMapsEnabled(true);
if (worker.config.experimental.nodeLoader !== false) await initSyntaxLexers();
if (typeof module$1.registerHooks === "function") module$1.registerHooks({
resolve(specifier, context, nextResolve) {
if (specifier.includes("mock=actual")) {
// url is already resolved by `importActual`
const moduleId = specifier.replace(REGEXP_MOCK_ACTUAL, "");
const builtin = isBuiltin(moduleId);
return {
url: builtin ? toBuiltin(moduleId) : moduleId,
format: builtin ? "builtin" : void 0,
shortCircuit: true
};
}
const isVitest = specifier.includes("%3Fvitest=");
const result = nextResolve(isVitest ? specifier.replace(REGEXP_VITEST, "") : specifier, context);
// avoid tracking /node_modules/ module graph for performance reasons
if (context.parentURL && result.url && !result.url.includes("/node_modules/")) worker.rpc.ensureModuleGraphEntry(result.url, context.parentURL).catch(() => {
// ignore errors
});
// this is require for in-source tests to be invalidated if
// one of the files already imported it in --maxWorkers=1 --no-isolate
if (isVitest) result.url = `${result.url}?vitest=${Date.now()}`;
if (worker.config.experimental.nodeLoader === false || !context.parentURL || result.url.includes(distDir) || context.parentURL?.toString().includes(distDir)) return result;
const mockedResult = getNativeMocker()?.resolveMockedModule(result.url, context.parentURL);
if (mockedResult != null) return mockedResult;
return result;
},
load: worker.config.experimental.nodeLoader === false ? void 0 : createLoadHook()
});
else if (module$1.register) {
if (worker.config.experimental.nodeLoader !== false) console.warn(`${c.bgYellow(" WARNING ")} "module.registerHooks" is not supported in Node.js ${process.version}. This means that some features like module mocking or in-source testing are not supported. Upgrade your Node.js version to at least 22.15 or disable "experimental.nodeLoader" flag manually.\n`);
const { port1, port2 } = new MessageChannel();
port1.unref();
port2.unref();
port1.on("message", (data) => {
if (!data || typeof data !== "object") return;
switch (data.event) {
case "register-module-graph-entry": {
const { url, parentURL } = data;
worker.rpc.ensureModuleGraphEntry(url, parentURL);
return;
}
default: console.error("Unknown message event:", data.event);
}
});
/** Registers {@link file://./../nodejsWorkerLoader.ts} */
module$1.register("#nodejs-worker-loader", {
parentURL: import.meta.url,
data: { port: port2 },
transferList: [port2]
});
} else if (!process.versions.deno && !process.versions.bun) console.warn("\"module.registerHooks\" and \"module.register\" are not supported. Some Vitest features may not work. Please, use Node.js 18.19.0 or higher.");
}
function replaceInSourceMarker(url, source, ms) {
const re = /import\.meta\.vitest/g;
let match;
let overridden = false;
// eslint-disable-next-line no-cond-assign
while (match = re.exec(source)) {
const { index, "0": code } = match;
overridden = true;
// should it support process.vitest for CJS modules?
ms().overwrite(index, index + code.length, "IMPORT_META_TEST()");
}
if (overridden) {
const filename = resolve(fileURLToPath(url));
// appending instead of prepending because functions are hoisted and we don't change the offset
ms().append(`;\nfunction IMPORT_META_TEST() { return typeof __vitest_worker__ !== 'undefined' && __vitest_worker__.filepath === "${filename.replace(/"/g, "\\\"")}" ? __vitest_index__ : undefined; }`);
}
}
const ignoreFormats = new Set([
"addon",
"builtin",
"wasm"
]);
function createLoadHook(_worker) {
return (url, context, nextLoad) => {
const result = url.includes("mock=") && isBuiltin(cleanUrl(url)) ? { format: "commonjs" } : nextLoad(url, context);
if (result.format && ignoreFormats.has(result.format) || url.includes(distDir)) return result;
const mocker = getNativeMocker();
mocker?.checkCircularManualMock(url);
if (url.includes("mock=automock") || url.includes("mock=autospy")) {
const automockedResult = mocker?.loadAutomock(url, result);
if (automockedResult != null) return automockedResult;
return result;
}
if (url.includes("mock=manual")) {
const mockedResult = mocker?.loadManualMock(url, result);
if (mockedResult != null) return mockedResult;
return result;
}
// ignore non-vitest modules for performance reasons,
// vi.hoisted and vi.mock won't work outside of test files or setup files
if (!result.source || !url.includes("vitest=")) return result;
const filename = url.startsWith("file://") ? fileURLToPath(url) : url;
const source = result.source.toString();
const transformedCode = result.format?.includes("typescript") ? module$1.stripTypeScriptTypes(source) : source;
let _ms;
const ms = () => _ms || (_ms = new MagicString(source));
if (source.includes("import.meta.vitest")) replaceInSourceMarker(url, source, ms);
hoistMocks(transformedCode, filename, (code) => parse(code, {
ecmaVersion: "latest",
sourceType: result.format === "module" || result.format === "module-typescript" || result.format === "typescript" ? "module" : "script"
}), {
magicString: ms,
globalThisAccessor: "\"__vitest_mocker__\""
});
let code;
if (_ms) code = `${_ms.toString()}\n//# sourceMappingURL=${genSourceMapUrl(_ms.generateMap({
hires: "boundary",
source: filename
}))}`;
else code = source;
return {
format: result.format,
shortCircuit: true,
source: code
};
};
}
function genSourceMapUrl(map) {
if (typeof map !== "string") map = JSON.stringify(map);
return `data:application/json;base64,${Buffer.from(map).toString("base64")}`;
}
function getNativeMocker() {
return typeof __vitest_mocker__ !== "undefined" ? __vitest_mocker__ : void 0;
}
export { setupNodeLoaderHooks };
+206
View File
@@ -0,0 +1,206 @@
import module$1, { isBuiltin } from 'node:module';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { automockModule, createManualModuleSource, collectModuleExports } from '@vitest/mocker/transforms';
import { cleanUrl, createDefer } from '@vitest/utils/helpers';
import { p as parse } from './acorn.B2iPLyUM.js';
import { isAbsolute } from 'pathe';
import { t as toBuiltin } from './modules.BJuCwlRJ.js';
import { B as BareModuleMocker, n as normalizeModuleId } from './startVitestModuleRunner.CCBQZ9DQ.js';
import 'node:fs';
import './utils.BX5Fg8C4.js';
import '@vitest/utils/timers';
import '../path.js';
import 'node:path';
import '../module-evaluator.js';
import 'node:vm';
import 'vite/module-runner';
import './traces.DT5aQ62U.js';
import '@vitest/mocker';
import '@vitest/mocker/redirect';
class NativeModuleMocker extends BareModuleMocker {
wrapDynamicImport(moduleFactory) {
if (typeof moduleFactory === "function") return new Promise((resolve, reject) => {
this.resolveMocks().finally(() => {
moduleFactory().then(resolve, reject);
});
});
return moduleFactory;
}
resolveMockedModule(url, parentURL) {
// don't mock modules inside of packages because there is
// a high chance that it uses `require` which is not mockable
// because we use top-level await in "manual" mocks.
// for the sake of consistency we don't support mocking anything at all
if (parentURL.includes("/node_modules/")) return;
const moduleId = normalizeModuleId(url.startsWith("file://") ? fileURLToPath(url) : url);
const mockedModule = this.getDependencyMock(moduleId);
if (!mockedModule) return;
if (mockedModule.type === "redirect") return {
url: pathToFileURL(mockedModule.redirect).toString(),
shortCircuit: true
};
if (mockedModule.type === "automock" || mockedModule.type === "autospy") return {
url: injectQuery(url, parentURL, `mock=${mockedModule.type}`),
shortCircuit: true
};
if (mockedModule.type === "manual") return {
url: injectQuery(url, parentURL, "mock=manual"),
shortCircuit: true
};
}
loadAutomock(url, result) {
const moduleId = cleanUrl(normalizeModuleId(url.startsWith("file://") ? fileURLToPath(url) : url));
let source;
if (isBuiltin(moduleId)) {
const builtinModule = getBuiltinModule(moduleId);
const exports$1 = Object.keys(builtinModule);
source = `
import * as builtinModule from '${toBuiltin(moduleId)}?mock=actual'
${exports$1.map((key, index) => {
return `
const __${index} = builtinModule["${key}"]
export { __${index} as "${key}" }
`;
}).join("")}`;
} else source = result.source?.toString();
if (source == null) return;
const mockType = url.includes("mock=automock") ? "automock" : "autospy";
const transformedCode = transformCode(source, result.format || "module", moduleId);
try {
const ms = automockModule(transformedCode, mockType, (code) => parse(code, {
sourceType: "module",
ecmaVersion: "latest"
}), { id: moduleId });
return {
format: "module",
source: `${ms.toString()}\n//# sourceMappingURL=${genSourceMapUrl(ms.generateMap({
hires: "boundary",
source: moduleId
}))}`,
shortCircuit: true
};
} catch (cause) {
throw new Error(`Cannot automock '${url}' because it failed to parse.`, { cause });
}
}
loadManualMock(url, result) {
const moduleId = cleanUrl(normalizeModuleId(url.startsWith("file://") ? fileURLToPath(url) : url));
// should not be possible
if (this.getDependencyMock(moduleId)?.type !== "manual") {
console.warn(`Vitest detected unregistered manual mock ${moduleId}. This is a bug in Vitest. Please, open a new issue with reproduction.`);
return;
}
if (isBuiltin(moduleId)) {
const builtinModule = getBuiltinModule(toBuiltin(moduleId));
return {
format: "module",
source: createManualModuleSource(moduleId, Object.keys(builtinModule)),
shortCircuit: true
};
}
if (!result.source) return;
const transformedCode = transformCode(result.source.toString(), result.format || "module", moduleId);
if (transformedCode == null) return;
const format = result.format?.startsWith("module") ? "module" : "commonjs";
try {
return {
format: "module",
source: createManualModuleSource(moduleId, collectModuleExports(moduleId, transformedCode, format)),
shortCircuit: true
};
} catch (cause) {
throw new Error(`Failed to mock '${url}'. See the cause for more information.`, { cause });
}
}
processedModules = /* @__PURE__ */ new Map();
checkCircularManualMock(url) {
const id = cleanUrl(normalizeModuleId(url.startsWith("file://") ? fileURLToPath(url) : url));
this.processedModules.set(id, (this.processedModules.get(id) ?? 0) + 1);
// the module is mocked and requested a second time, let's resolve
// the factory function that will redefine the exports later
if (this.originalModulePromises.has(id)) {
const factoryPromise = this.factoryPromises.get(id);
this.originalModulePromises.get(id)?.resolve({ __factoryPromise: factoryPromise });
}
}
originalModulePromises = /* @__PURE__ */ new Map();
factoryPromises = /* @__PURE__ */ new Map();
// potential performance improvement:
// store by URL, not ids, no need to call url.*to* methods and normalizeModuleId
getFactoryModule(id) {
const mock = this.getMockerRegistry().getById(id);
if (!mock || mock.type !== "manual") throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`);
const mockResult = mock.resolve();
if (mockResult instanceof Promise) {
// to avoid circular dependency, we resolve this function as {__factoryPromise} in `checkCircularManualMock`
// when it's requested the second time. then the exports are exposed as `undefined`,
// but later redefined when the promise is actually resolved
const promise = createDefer();
promise.finally(() => {
this.originalModulePromises.delete(id);
});
mockResult.then(promise.resolve, promise.reject).finally(() => {
this.factoryPromises.delete(id);
});
this.factoryPromises.set(id, mockResult);
this.originalModulePromises.set(id, promise);
// Node.js on windows processes all the files first, and then runs them
// unlike Node.js logic on Mac and Unix where it also runs the code while evaluating
// So on Linux/Mac this `if` won't be hit because `checkCircularManualMock` will resolve it
// And on Windows, the `checkCircularManualMock` will never have `originalModulePromises`
// because `getFactoryModule` is not called until the evaluation phase
// But if we track how many times the module was transformed,
// we can deduce when to return `__factoryPromise` to support circular modules
if ((this.processedModules.get(id) ?? 0) > 1) {
this.processedModules.set(id, (this.processedModules.get(id) ?? 1) - 1);
promise.resolve({ __factoryPromise: mockResult });
}
return promise;
}
return mockResult;
}
importActual(rawId, importer) {
const resolvedId = import.meta.resolve(rawId, pathToFileURL(importer).toString());
const url = new URL(resolvedId);
url.searchParams.set("mock", "actual");
return import(url.toString());
}
importMock(rawId, importer) {
const resolvedId = import.meta.resolve(rawId, pathToFileURL(importer).toString());
// file is already mocked
if (resolvedId.includes("mock=")) return import(resolvedId);
const filename = fileURLToPath(resolvedId);
const external = !isAbsolute(filename) || this.isModuleDirectory(resolvedId) ? normalizeModuleId(rawId) : null;
// file is not mocked, automock or redirect it
const redirect = this.findMockRedirect(filename, external);
if (redirect) return import(pathToFileURL(redirect).toString());
const url = new URL(resolvedId);
url.searchParams.set("mock", "automock");
return import(url.toString());
}
}
const replacePercentageRE = /%/g;
function injectQuery(url, importer, queryToInject) {
const { search, hash } = new URL(url.replace(replacePercentageRE, "%25"), importer);
return `${cleanUrl(url)}?${queryToInject}${search ? `&${search.slice(1)}` : ""}${hash ?? ""}`;
}
let __require;
function getBuiltinModule(moduleId) {
__require ??= module$1.createRequire(import.meta.url);
return __require(`${moduleId}?mock=actual`);
}
function genSourceMapUrl(map) {
if (typeof map !== "string") map = JSON.stringify(map);
return `data:application/json;base64,${Buffer.from(map).toString("base64")}`;
}
function transformCode(code, format, filename) {
if (format.includes("typescript")) {
if (!module$1.stripTypeScriptTypes) throw new Error(`Cannot parse '${filename}' because "module.stripTypeScriptTypes" is not supported. Module mocking requires Node.js 22.15 or higher. This is NOT a bug of Vitest.`);
return module$1.stripTypeScriptTypes(code);
}
return code;
}
export { NativeModuleMocker };
+36
View File
@@ -0,0 +1,36 @@
import { pathToFileURL } from 'node:url';
import { r as resolveModule } from './index.BCY_7LL2.js';
import { resolve } from 'pathe';
import { ModuleRunner } from 'vite/module-runner';
class NativeModuleRunner extends ModuleRunner {
/**
* @internal
*/
mocker;
constructor(root, mocker) {
super({
hmr: false,
sourcemapInterceptor: false,
transport: { invoke() {
throw new Error("Unexpected `invoke`");
} }
});
this.root = root;
this.mocker = mocker;
if (mocker) Object.defineProperty(globalThis, "__vitest_mocker__", {
configurable: true,
writable: true,
value: mocker
});
}
async import(moduleId) {
const path = resolveModule(moduleId, { paths: [this.root] }) ?? resolve(this.root, moduleId);
// resolveModule doesn't keep the query params, so we need to add them back
let queryParams = "";
if (moduleId.includes("?") && !path.includes("?")) queryParams = moduleId.slice(moduleId.indexOf("?"));
return import(pathToFileURL(path + queryParams).toString());
}
}
export { NativeModuleRunner as N };
@@ -1,5 +1,5 @@
import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment';
import { g as getWorkerState } from './utils.DvEY5TfP.js';
import { g as getWorkerState } from './utils.BX5Fg8C4.js';
import '@vitest/utils/timers';
class VitestNodeSnapshotEnvironment extends NodeSnapshotEnvironment {
@@ -1,5 +1,5 @@
import { DevEnvironment } from 'vite';
import { V as Vitest, T as TestProject, b as TestProjectConfiguration } from './reporters.d.CWXNI2jG.js';
import { V as Vitest, T as TestProject, a as TestProjectConfiguration } from './reporters.d.DtoKVV2s.js';
/**
* Generate a unique cache identifier.
@@ -1,27 +1,26 @@
import { TaskMeta, Suite, File, TestAnnotation, TestArtifact, ImportDuration, Test, Task, TaskResultPack, FileSpecification, CancelReason, SequenceSetupFiles, SequenceHooks } from '@vitest/runner';
import { TaskMeta, Suite, File, SerializableRetry, TestAnnotation, TestArtifact, ImportDuration, Test, Task, TaskResultPack, FileSpecification, CancelReason, SequenceSetupFiles, SequenceHooks, TestTagDefinition } from '@vitest/runner';
import { TestError, SerializedError, Arrayable, ParsedStack, Awaitable } from '@vitest/utils';
import { A as AfterSuiteRunMeta, U as UserConsoleLog, P as ProvidedContext, L as LabelColor } from './rpc.d.RH3apGEf.js';
import { a as AfterSuiteRunMeta, U as UserConsoleLog, A as AsyncLeak, P as ProvidedContext, O as OTELCarrier, L as LabelColor } from './traces.d.D2T_R8rx.js';
import { Writable } from 'node:stream';
import { DevEnvironment, TransformResult as TransformResult$1, ViteDevServer, Plugin, UserConfig as UserConfig$1, DepOptimizationConfig, ServerOptions, ConfigEnv, AliasOptions } from 'vite';
import { S as SerializedTestSpecification, c as SourceModuleDiagnostic, B as BrowserTesterOptions } from './browser.d.ChKACdzH.js';
import { MockedModule } from '@vitest/mocker';
import { StackTraceParserOptions } from '@vitest/utils/source-map';
import { BrowserCommands } from 'vitest/browser';
import { B as BrowserTraceViewMode, S as SerializedConfig, F as FakeTimerInstallOpts } from './config.d.Cy95HiCx.js';
import { b as SerializedRootConfig, B as BrowserTraceViewMode, S as SerializedConfig, F as FakeTimerInstallOpts } from './config.d.A1h_Y6Jt.js';
import { S as SerializedTestSpecification, c as SourceModuleDiagnostic, B as BrowserTesterOptions } from './browser.d.BcoexmFG.js';
import { PrettyFormatOptions } from '@vitest/pretty-format';
import { SnapshotSummary, SnapshotStateOptions } from '@vitest/snapshot';
import { SerializedDiffOptions } from '@vitest/utils/diff';
import { chai } from '@vitest/expect';
import { happyDomTypes, jsdomTypes } from 'vitest/optional-types.js';
import { c as ContextTestEnvironment, d as WorkerExecuteContext, e as WorkerTestEnvironment } from './worker.d.Dyxm8DEL.js';
import { O as OTELCarrier } from './traces.d.402V_yFI.js';
import { c as ContextTestEnvironment, d as WorkerExecuteContext, e as WorkerTestEnvironment } from './worker.d.ZpHpO4yb.js';
import { B as BenchmarkResult } from './benchmark.d.DAaHLpsq.js';
import { MockedModule } from '@vitest/mocker';
import { StackTraceParserOptions } from '@vitest/utils/source-map';
import { CDPSession, BrowserCommands } from 'vitest/browser';
import { a as RuntimeCoverageProviderModule } from './coverage.d.BZtK59WP.js';
import { SnapshotManager } from '@vitest/snapshot/manager';
import { Console } from 'node:console';
import { Stats } from 'node:fs';
type ChaiConfig = Omit<Partial<typeof chai.config>, "useProxy" | "proxyExcludedKeys">;
type ChaiConfig = Omit<Partial<typeof chai.config>, "useProxy" | "proxyExcludedKeys" | "deepEqual">;
type HappyDOMOptions = Omit<NonNullable<ConstructorParameters<typeof happyDomTypes.Window>[0]>, "console">;
@@ -72,6 +71,52 @@ interface ConstructorOptionsOverride {
resources?: "usable";
}
interface TestSpecificationOptions {
testNamePattern?: RegExp;
testIds?: string[];
testLines?: number[];
testTagsFilter?: string[];
}
declare class TestSpecification {
/**
* The task id associated with the test module.
*/
readonly taskId: string;
/**
* The test project that the module belongs to.
*/
readonly project: TestProject;
/**
* The id of the module in the Vite module graph. It is usually an absolute file path.
*/
readonly moduleId: string;
/**
* The current test pool. It's possible to have multiple pools in a single test project with `typecheck.enabled`.
*/
readonly pool: Pool;
/**
* Line numbers of the test locations to run.
*/
testLines: number[] | undefined;
/**
* Regular expression pattern to filter test names.
*/
testNamePattern: RegExp | undefined;
/**
* The ids of tasks inside of this specification to run.
*/
testIds: string[] | undefined;
/**
* The tags of tests to run.
*/
testTagsFilter: string[] | undefined;
/**
* Test module associated with the specification. This will be `undefined` if tests have not been run yet.
*/
get testModule(): TestModule | undefined;
toJSON(): SerializedTestSpecification;
}
declare class ReportedTaskImplementation {
/**
* The project associated with the test or suite.
@@ -120,6 +165,10 @@ declare class TestCase extends ReportedTaskImplementation {
*/
readonly parent: TestSuite | TestModule;
/**
* Tags associated with the test.
*/
readonly tags: string[];
/**
* Full name of the test including all parent suites separated with `>`.
*/
get fullName(): string;
@@ -146,6 +195,10 @@ declare class TestCase extends ReportedTaskImplementation {
* Diagnostic is only available after the test has finished.
*/
diagnostic(): TestDiagnostic | undefined;
/**
* Returns a new test specification that can be used to filter or run this specific test case.
*/
toTestSpecification(): TestSpecification;
}
declare class TestCollection {
#private;
@@ -231,6 +284,10 @@ declare class TestSuite extends SuiteImplementation {
*/
state(): TestSuiteState;
/**
* Returns a new test specification that can be used to filter or run this specific test suite.
*/
toTestSpecification(): TestSpecification;
/**
* Full name of the suite including all parent suites separated with `>`.
*/
get fullName(): string;
@@ -255,6 +312,10 @@ declare class TestModule extends SuiteImplementation {
*/
readonly relativeModuleId: string;
/**
* Returns a new test specification that can be used to filter or run this specific test module.
*/
toTestSpecification(testCases?: TestCase[]): TestSpecification;
/**
* Checks the running state of the test file.
*/
state(): TestModuleState;
@@ -278,8 +339,13 @@ interface TaskOptions {
readonly fails: boolean | undefined;
readonly concurrent: boolean | undefined;
readonly shuffle: boolean | undefined;
readonly retry: number | undefined;
readonly retry: SerializableRetry | undefined;
readonly repeats: number | undefined;
readonly tags: string[] | undefined;
/**
* Only tests have a `timeout` option.
*/
readonly timeout: number | undefined;
readonly mode: "run" | "only" | "skip" | "todo";
}
type TestSuiteState = "skipped" | "pending" | "failed" | "passed";
@@ -402,36 +468,6 @@ declare function experimental_getRunnerTask(entity: TestSuite): Suite;
declare function experimental_getRunnerTask(entity: TestModule): File;
declare function experimental_getRunnerTask(entity: TestCase | TestSuite | TestModule): Suite | File | Test;
declare class TestSpecification {
/**
* The task ID associated with the test module.
*/
readonly taskId: string;
/**
* The test project that the module belongs to.
*/
readonly project: TestProject;
/**
* The ID of the module in the Vite module graph. It is usually an absolute file path.
*/
readonly moduleId: string;
/**
* The current test pool. It's possible to have multiple pools in a single test project with `poolMatchGlob` and `typecheck.enabled`.
* @experimental In Vitest 4, the project will only support a single pool and this property will be removed.
*/
readonly pool: Pool;
/**
* Line numbers of the test locations to run.
*/
readonly testLines: number[] | undefined;
constructor(project: TestProject, moduleId: string, pool: Pool, testLines?: number[] | undefined);
/**
* Test module associated with the specification.
*/
get testModule(): TestModule | undefined;
toJSON(): SerializedTestSpecification;
}
interface CoverageSummaryData {
lines: Totals;
statements: Totals;
@@ -623,7 +659,9 @@ interface CoverageProvider {
clean: (clean?: boolean) => void | Promise<void>;
/** Called with coverage results after a single test file has been run */
onAfterSuiteRun: (meta: AfterSuiteRunMeta) => void | Promise<void>;
/** Callback called when test run fails */
/** Callback called when test run starts */
onTestRunStart?: () => void | Promise<void>;
/** Callback called when test run fails due to test failures */
onTestFailure?: () => void | Promise<void>;
/** Callback to generate final coverage results */
generateCoverage: (reportContext: ReportContext) => CoverageResults | Promise<CoverageResults>;
@@ -654,27 +692,19 @@ interface CoverageProviderModule extends RuntimeCoverageProviderModule {
}
type CoverageReporter = keyof ReportOptions | (string & {});
type CoverageReporterWithOptions<ReporterName extends CoverageReporter = CoverageReporter> = ReporterName extends keyof ReportOptions ? ReportOptions[ReporterName] extends never ? [ReporterName, object] : [ReporterName, Partial<ReportOptions[ReporterName]>] : [ReporterName, Record<string, unknown>];
type CoverageProviderName = "v8" | "istanbul" | "custom" | undefined;
type CoverageOptions<T extends CoverageProviderName = CoverageProviderName> = T extends "istanbul" ? {
provider: T;
} & CoverageIstanbulOptions : T extends "v8" ? {
/** Fields that have default values. Internally these will always be defined. */
type FieldsWithDefaultValues = "provider" | "enabled" | "clean" | "cleanOnRerun" | "reportsDirectory" | "exclude" | "reportOnFailure" | "allowExternal" | "processingConcurrency" | "reporter" | "excludeAfterRemap" | "ignoreClassMethods" | "skipFull" | "watermarks";
type ResolvedCoverageOptions = CoverageOptions & Required<Pick<CoverageOptions, FieldsWithDefaultValues>> & {
reporter: CoverageReporterWithOptions[];
htmlDir?: string;
};
interface CoverageOptions {
/**
* Provider to use for coverage collection.
* Coverage provider to use.
*
* @default 'v8'
*/
provider: T;
} & CoverageV8Options : T extends "custom" ? {
provider: T;
} & CustomProviderOptions : {
provider?: T;
} & CoverageV8Options;
/** Fields that have default values. Internally these will always be defined. */
type FieldsWithDefaultValues = "enabled" | "clean" | "cleanOnRerun" | "reportsDirectory" | "exclude" | "reportOnFailure" | "allowExternal" | "processingConcurrency";
type ResolvedCoverageOptions<T extends CoverageProviderName = CoverageProviderName> = CoverageOptions<T> & Required<Pick<CoverageOptions<T>, FieldsWithDefaultValues>> & {
reporter: CoverageReporterWithOptions[];
};
interface BaseCoverageOptions {
provider?: "v8" | "istanbul" | "custom";
/**
* Enables coverage collection. Can be overridden using `--coverage` CLI option.
*
@@ -795,12 +825,48 @@ interface BaseCoverageOptions {
* @default []
*/
ignoreClassMethods?: string[];
}
interface CoverageIstanbulOptions extends BaseCoverageOptions {}
interface CoverageV8Options extends BaseCoverageOptions {}
interface CustomProviderOptions extends Pick<BaseCoverageOptions, FieldsWithDefaultValues> {
/** Name of the module or path to a file to load the custom provider from */
customProviderModule: string;
/**
* Custom instrumenter factory to use instead of the default `istanbul-lib-instrument`.
*
* The factory receives the same runtime coverage options Vitest passes to its
* built-in Istanbul instrumenter and must return an object implementing the
* `CoverageInstrumenter` interface.
*
* This allows using faster instrumenters (e.g., oxc-coverage-instrument, SWC) while
* keeping the Istanbul coverage pipeline for collection, merging, and reporting.
*
* @example
* ```ts
* import { defineConfig } from 'vitest/config'
* import { createOxcInstrumenter } from 'oxc-coverage-instrument/vitest'
*
* export default defineConfig({
* test: {
* coverage: {
* provider: 'istanbul',
* instrumenter: options => createOxcInstrumenter(options),
* }
* }
* })
*
* @experimental
*/
instrumenter?: (options: InstrumenterOptions) => CoverageInstrumenter;
/**
* Directory of HTML coverage output to be served in UI mode and HTML reporter.
* This is automatically configured for builtin reporter with html output (`html`, `html-spa`, and `lcov` reporters).
* Use this option to override with custom coverage reporting location.
*/
htmlDir?: string;
/**
* Collect coverage only for files changed since a specified commit or branch.
* Inherits the default value from `test.changed`.
*/
changed?: boolean | string;
/**
* Name of the module or path to a file to load the custom provider from
*/
customProviderModule?: string;
}
interface Thresholds {
/** Set global thresholds to `100` */
@@ -823,12 +889,56 @@ interface Thresholds {
/** Thresholds for lines */
lines?: number;
}
/**
* Options passed to the custom instrumenter factory.
*/
interface InstrumenterOptions {
/** Global variable name that Vitest uses to store coverage data at runtime. */
coverageVariable: string;
/** Global scope where the coverage variable is attached at runtime. */
coverageGlobalScope: string;
/** Whether the coverage global scope should be resolved through an evaluated function. */
coverageGlobalScopeFunc: boolean;
/** Class method names to exclude from function coverage. */
ignoreClassMethods: string[];
}
/**
* Interface for custom coverage instrumenters.
*
* Matches the subset of istanbul-lib-instrument's `Instrumenter` that Vitest
* actually uses. Implement this to plug in a faster instrumenter while keeping
* the Istanbul coverage pipeline for collection, merging, and reporting.
*/
interface CoverageInstrumenter {
/** Instrument source code synchronously. Returns the instrumented code string. */
instrumentSync: (code: string, filename: string, inputSourceMap?: any) => string;
/** Get the source map of the last instrumented file. */
lastSourceMap: () => any;
/** Get the Istanbul-compatible file coverage object of the last instrumented file. */
lastFileCoverage: () => any;
}
/** @deprecated Use `CoverageOptions` instead */
interface CoverageV8Options extends CoverageOptions {}
/** @deprecated Use `CoverageOptions` instead */
interface CoverageIstanbulOptions extends CoverageOptions {}
/** @deprecated Use `CoverageOptions` instead */
interface BaseCoverageOptions extends CoverageOptions {}
/** @deprecated Use `CoverageOptions` instead */
interface CustomProviderOptions extends CoverageOptions {}
interface TestRunResult {
testModules: TestModule[];
unhandledErrors: unknown[];
}
interface VCSProviderOptions {
root: string;
changedSince?: string | boolean;
}
interface VCSProvider {
findChangedFiles(options: VCSProviderOptions): Promise<string[]>;
}
declare class TypeCheckError extends Error {
message: string;
stacks: ParsedStack[];
@@ -865,6 +975,8 @@ declare class Logger {
deprecate(message: string): void;
clearHighlightCache(filename?: string): void;
highlight(filename: string, source: string): string;
printNoTestTagsFound(): void;
printTags(): void;
printNoTestFound(filters?: string[]): void;
printBanner(): void;
printBrowserBanner(project: TestProject): void;
@@ -931,7 +1043,6 @@ interface Reporter {
/**
* Called when the project initiated the browser instance.
* project.browser will always be defined.
* @experimental
*/
onBrowserInit?: (project: TestProject) => Awaitable<void>;
onTestRemoved?: (trigger?: string) => Awaitable<void>;
@@ -1029,6 +1140,7 @@ declare class StateManager {
idMap: Map<string, Task>;
taskFileMap: WeakMap<Task, File>;
errorsSet: Set<unknown>;
leakSet: Set<AsyncLeak>;
reportedTasksMap: WeakMap<Task, TestModule | TestCase | TestSuite>;
blobs?: MergedBlobs;
transformTime: number;
@@ -1047,6 +1159,7 @@ declare class StateManager {
onUnhandledError?: OnUnhandledErrorCallback;
});
catchError(error: unknown, type: string): void;
catchLeaks(leaks: AsyncLeak[]): void;
clearErrors(): void;
getUnhandledErrors(): unknown[];
getPaths(): string[];
@@ -1081,6 +1194,7 @@ declare class VitestWatcher {
readonly changedTests: Set<string>;
private readonly _onRerun;
constructor(vitest: Vitest);
close(): void;
unregisterWatcher: () => void;
registerWatcher(): this;
private scheduleRerun;
@@ -1145,11 +1259,17 @@ declare class Vitest {
* Vitest behaviour.
*/
readonly watcher: VitestWatcher;
/**
* The version control system provider used to detect changed files.
* This is used with the `--changed` flag to determine which test files to run.
* By default, Vitest uses Git. You can provide a custom implementation via
* `experimental.vcsProvider` in your config.
*/
vcs: VCSProvider;
private isFirstRun;
private restartsCount;
private readonly specifications;
private pool;
private _config?;
private _vite?;
private _state?;
private _cache?;
@@ -1183,6 +1303,7 @@ declare class Vitest {
* Test results and test file stats cache. Primarily used by the sequencer to sort tests.
*/
get cache(): VitestCache;
listTags(): Promise<void>;
enableCoverage(): Promise<void>;
disableCoverage(): void;
private clearAllCachePaths;
@@ -1205,6 +1326,7 @@ declare class Vitest {
* Return project that has the root (or "global") config.
*/
getRootProject(): TestProject;
get serializedRootConfig(): SerializedRootConfig;
getProjectByName(name: string): TestProject;
/**
* Import a file using Vite module runner. The file will be transformed by Vite and executed in a separate context.
@@ -1235,7 +1357,10 @@ declare class Vitest {
* Returns the seed, if tests are running in a random order.
*/
getSeed(): number | null;
collect(filters?: string[]): Promise<TestRunResult>;
collect(filters?: string[], options?: {
staticParse?: boolean;
staticParseConcurrency?: number;
}): Promise<TestRunResult>;
/**
* Returns the list of test files that match the config and filters.
* @param filters String filters to match the test files
@@ -1251,10 +1376,14 @@ declare class Vitest {
*/
start(filters?: string[]): Promise<TestRunResult>;
/**
* @deprecated use `standalone()` instead
*/
init(): Promise<void>;
/**
* Initialize reporters and the coverage provider. This method doesn't run any tests.
* If the `--watch` flag is provided, Vitest will still run changed tests even if this method was not called.
*/
init(): Promise<void>;
standalone(): Promise<void>;
/**
* If there is a test run happening, returns a promise that will
* resolve when the test run is finished.
@@ -1278,6 +1407,12 @@ declare class Vitest {
*/
runTestSpecifications(specifications: TestSpecification[], allTestsRun?: boolean): Promise<TestRunResult>;
/**
* Runs tests for the given file paths. This does not trigger `onWatcher*` events.
* @param filepaths A list of file paths to run tests for.
* @param allTestsRun Indicates whether all tests were run. This only matters for coverage.
*/
runTestFiles(filepaths: string[], allTestsRun?: boolean): Promise<TestRunResult>;
/**
* Rerun files and trigger `onWatcherRerun`, `onWatcherStart` and `onTestsRerun` events.
* @param specifications A list of specifications to run.
* @param allTestsRun Indicates whether all tests were run. This only matters for coverage.
@@ -1390,12 +1525,6 @@ declare class Vitest {
type OnServerRestartHandler = (reason?: string) => Promise<void> | void;
type OnTestsRerunHandler = (testFiles: TestSpecification[]) => Promise<void> | void;
interface CDPSession {
send: (method: string, params?: Record<string, unknown>) => Promise<unknown>;
on: (event: string, listener: (...args: unknown[]) => void) => void;
once: (event: string, listener: (...args: unknown[]) => void) => void;
off: (event: string, listener: (...args: unknown[]) => void) => void;
}
interface BrowserModuleMocker {
register: (sessionId: string, module: MockedModule) => Promise<void>;
delete: (sessionId: string, url: string) => Promise<void>;
@@ -1428,7 +1557,9 @@ interface BrowserProvider {
*/
supportsParallelism: boolean;
getCommandsContext: (sessionId: string) => Record<string, unknown>;
openPage: (sessionId: string, url: string) => Promise<void>;
openPage: (sessionId: string, url: string, options: {
parallel: boolean;
}) => Promise<void>;
getCDPSession?: (sessionId: string) => Promise<CDPSession>;
close: () => Awaitable<void>;
}
@@ -1503,6 +1634,13 @@ interface BrowserConfigOptions {
*/
ui?: boolean;
/**
* Default position for the details panel in browser mode
* 'right' shows the details panel on the right side (horizontal split)
* 'bottom' shows the details panel at the bottom (vertical split)
* @default 'right'
*/
detailsPanelPosition?: "right" | "bottom";
/**
* Default viewport size
*/
viewport?: {
@@ -1526,6 +1664,11 @@ interface BrowserConfigOptions {
* @default 'data-testid'
*/
testIdAttribute?: string;
/**
* Should locators match the text exactly by default
* @default false
*/
exact?: boolean;
};
/**
* Generate traces that can be viewed on https://trace.playwright.dev/
@@ -1597,7 +1740,7 @@ interface BrowserConfigOptions {
/**
* Enables tracking uncaught errors and exceptions so they can be reported by Vitest.
*
* If you need to hide certain errors, it is recommended to use [`onUnhandledError`](https://vitest.dev/config/#onunhandlederror) option instead.
* If you need to hide certain errors, it is recommended to use [`onUnhandledError`](https://vitest.dev/config/onunhandlederror) option instead.
*
* Disabling this will completely remove all Vitest error handlers, which can help debugging with the "Pause on exceptions" checkbox turned on.
* @default true
@@ -1613,7 +1756,9 @@ interface BrowserCommandContext {
}
interface BrowserServerStateSession {
project: TestProject;
otelCarrier?: OTELCarrier;
connected: () => void;
ready: () => void;
fail: (v: Error) => void;
}
interface BrowserOrchestrator {
@@ -1689,12 +1834,14 @@ interface ResolvedBrowserOptions extends BrowserConfigOptions {
screenshotFailures: boolean;
locators: {
testIdAttribute: string;
exact: boolean;
};
trace: {
mode: BrowserTraceViewMode;
tracesDir?: string;
screenshots?: boolean;
snapshots?: boolean;
sources?: boolean;
};
}
type ToMatchScreenshotResolvePath = (data: {
@@ -1742,12 +1889,12 @@ type ToMatchScreenshotResolvePath = (data: {
screenshotDirectory: string;
/**
* Absolute path to the project's
* {@linkcode https://vitest.dev/config/#root|root}.
* {@linkcode https://vitest.dev/config/root|root}.
*/
root: string;
/**
* Path to the test file, relative to the project's
* {@linkcode https://vitest.dev/config/#root|root}.
* {@linkcode https://vitest.dev/config/root|root}.
*/
testFileDirectory: string;
/**
@@ -1761,10 +1908,16 @@ type ToMatchScreenshotResolvePath = (data: {
testName: string;
/**
* The value provided to
* {@linkcode https://vitest.dev/config/#attachmentsdir|attachmentsDir},
* {@linkcode https://vitest.dev/config/attachmentsdir|attachmentsDir},
* if none is provided, its default value.
*/
attachmentsDir: string;
/**
* The {@linkcode https://vitest.dev/api/advanced/test-project|TestProject} the test belongs to.
*
* @experimental
*/
project: TestProject;
}) => string;
interface ToMatchScreenshotOptions {
/**
@@ -1800,7 +1953,6 @@ declare class TestProject {
* Temporary directory for the project. This is unique for each project. Vitest stores transformed content here.
*/
readonly tmpDir: string;
/** @inetrnal */ testFilesList: string[] | null;
private runner;
private closingPromise;
private typecheckFilesList;
@@ -1825,7 +1977,7 @@ declare class TestProject {
* Creates a new test specification. Specifications describe how to run tests.
* @param moduleId The file path
*/
createSpecification(moduleId: string, locations?: number[] | undefined, pool?: string): TestSpecification;
createSpecification(moduleId: string, locationsOrOptions?: number[] | TestSpecificationOptions | undefined, pool?: string): TestSpecification;
toJSON(): SerializedTestProject;
/**
* Vite's dev server instance. Every workspace project has its own server.
@@ -1995,6 +2147,7 @@ type WorkerResponse = {
interface BaseOptions {
isTTY?: boolean;
silent?: boolean | "passed-only";
}
declare abstract class BaseReporter implements Reporter {
start: number;
@@ -2005,6 +2158,7 @@ declare abstract class BaseReporter implements Reporter {
ctx: Vitest;
renderSucceed: boolean;
protected verbose: boolean;
protected silent?: boolean | "passed-only";
private _filesInWatchMode;
private _timeStart;
constructor(options?: BaseOptions);
@@ -2017,7 +2171,7 @@ declare abstract class BaseReporter implements Reporter {
onTestCaseResult(testCase: TestCase): void;
onTestSuiteResult(testSuite: TestSuite): void;
onTestModuleEnd(testModule: TestModule): void;
private logFailedTask;
protected logFailedTask(task: Task): void;
protected printTestModule(testModule: TestModule): void;
protected printTestCase(moduleState: TestModuleState, test: TestCase): void;
private getModuleLog;
@@ -2037,11 +2191,12 @@ declare abstract class BaseReporter implements Reporter {
shouldLog(log: UserConsoleLog, taskState?: TestResult["state"]): boolean;
onServerRestart(reason?: string): void;
reportSummary(files: File[], errors: unknown[]): void;
reportTestSummary(files: File[], errors: unknown[]): void;
private printImportsBreakdown;
reportTestSummary(files: File[], errors: unknown[], leakCount: number): void;
private reportImportDurations;
private importDurationTime;
private ellipsisPath;
private printErrorsSummary;
private printLeaksSummary;
reportBenchmarkSummary(files: File[]): void;
private printTaskErrors;
}
@@ -2071,10 +2226,58 @@ interface GithubActionsReporterOptions {
* @default true
*/
displayAnnotations?: boolean;
/**
* Configuration for the GitHub Actions Job Summary.
*
* When enabled, a markdown summary of test results is written to the path specified by `outputPath`.
*/
jobSummary?: Partial<JobSummaryOptions>;
}
interface JobSummaryOptions {
/**
* Whether to generate the summary.
*
* @default true
*/
enabled: boolean;
/**
* File path to write the summary to.
*
* @default process.env.GITHUB_STEP_SUMMARY
*/
outputPath: string | undefined;
/**
* Configuration for generating permalink URLs to source files in the GitHub repository.
*
* When all three values are available (either from this config or the defaults picked from environment variables), test names in the summary will link to the relevant source lines.
*/
fileLinks: {
/**
* The GitHub repository in `owner/repo` format.
*
* @default process.env.GITHUB_REPOSITORY
*/
repository?: string | undefined;
/**
* The commit SHA to use in permalink URLs.
*
* @default process.env.GITHUB_SHA
*/
commitHash?: string | undefined;
/**
* The absolute path to the root of the repository on disk.
*
* This value is used to compute relative file paths for the permalink URLs.
*
* @default process.env.GITHUB_WORKSPACE
*/
workspacePath?: string | undefined;
};
}
type ResolvedOptions = Required<GithubActionsReporterOptions>;
declare class GithubActionsReporter implements Reporter {
ctx: Vitest;
options: GithubActionsReporterOptions;
options: ResolvedOptions;
constructor(options?: GithubActionsReporterOptions);
onInit(ctx: Vitest): void;
onTestCaseAnnotate(testCase: TestCase, annotation: TestAnnotation): void;
@@ -2100,6 +2303,7 @@ interface JsonAssertionResult {
duration?: Milliseconds | null;
failureMessages: Array<string> | null;
location?: Callsite | null;
tags: string[];
}
interface JsonTestResult {
message: string;
@@ -2127,6 +2331,8 @@ interface JsonTestResults {
}
interface JsonOptions {
outputFile?: string;
/** @experimental */
filterMeta?: (key: string, value: unknown) => unknown;
}
declare class JsonReporter implements Reporter {
start: number;
@@ -2166,6 +2372,10 @@ interface JUnitOptions {
* @default false
*/
addFileAttribute?: boolean;
/**
* Hostname to use in the report. By default, it uses os.hostname()
*/
hostname?: string;
}
declare class JUnitReporter implements Reporter {
private ctx;
@@ -2189,6 +2399,7 @@ declare class DotReporter extends BaseReporter {
private finishedTests;
onInit(ctx: Vitest): void;
printTestModule(): void;
onTestRunStart(_specifications: ReadonlyArray<TestSpecification>): void;
onWatcherRerun(files: string[], trigger?: string): void;
onTestRunEnd(testModules: ReadonlyArray<TestModule>, unhandledErrors: ReadonlyArray<SerializedError>, reason: TestRunEndReason): void;
onTestModuleCollected(module: TestModule): void;
@@ -2204,6 +2415,14 @@ declare class HangingProcessReporter implements Reporter {
onProcessTimeout(): void;
}
declare class MinimalReporter extends DefaultReporter {
renderSucceed: boolean;
constructor(options?: DefaultReporterOptions);
onTestRunStart(specifications: ReadonlyArray<TestSpecification>): void;
protected printTestModule(testModule: TestModule): void;
protected printTestCase(moduleState: TestModuleState, test: TestCase): void;
}
declare class TapReporter implements Reporter {
protected ctx: Vitest;
private logger;
@@ -2267,6 +2486,8 @@ type BenchmarkBuiltinReporters = keyof typeof BenchmarkReportsMap;
declare const ReportersMap: {
default: typeof DefaultReporter;
agent: typeof MinimalReporter;
minimal: typeof MinimalReporter;
blob: typeof BlobReporter;
verbose: typeof VerboseReporter;
dot: typeof DotReporter;
@@ -2281,6 +2502,8 @@ declare const ReportersMap: {
type BuiltinReporters = keyof typeof ReportersMap;
interface BuiltinReporterOptions {
"default": DefaultReporterOptions;
"minimal": DefaultReporterOptions;
"agent": DefaultReporterOptions;
"verbose": DefaultReporterOptions;
"dot": BaseOptions;
"tree": BaseOptions;
@@ -2325,12 +2548,12 @@ interface BenchmarkUserOptions {
*/
includeSource?: string[];
/**
* Custom reporter for output. Can contain one or more built-in report names, reporter instances,
* and/or paths to custom reporters
* Custom reporters to use for output. Can contain one or more built-in reporter names, reporter instances,
* and/or paths to custom reporter files to import.
*
* @default ['default']
*/
reporters?: Arrayable<BenchmarkBuiltinReporters | Reporter>;
reporters?: Arrayable<BenchmarkBuiltinReporters | Reporter | (string & {})>;
/**
* @deprecated Use `benchmark.outputJson` instead
*/
@@ -2354,7 +2577,22 @@ interface BenchmarkUserOptions {
type BuiltinEnvironment = "node" | "jsdom" | "happy-dom" | "edge-runtime";
type VitestEnvironment = BuiltinEnvironment | (string & Record<never, never>);
type CSSModuleScopeStrategy = "stable" | "scoped" | "non-scoped";
type ApiConfig = Pick<ServerOptions, "port" | "strictPort" | "host" | "middlewareMode">;
type ApiConfig = Pick<ServerOptions, "port" | "strictPort" | "host" | "middlewareMode"> & {
/**
* Allow any write operations from the API server.
*
* @default true if `api.host` is exposed to network, false otherwise
*/
allowWrite?: boolean;
/**
* Allow running test files via the API.
* If `api.host` is exposed to network and `allowWrite` is true,
* anyone connected to the API server can run arbitrary code on your machine.
*
* @default true if `api.host` is exposed to network, false otherwise
*/
allowExec?: boolean;
};
interface EnvironmentOptions {
/**
* jsdom options.
@@ -2624,7 +2862,7 @@ interface InlineConfig {
*
* @default false
*/
update?: boolean;
update?: boolean | "all" | "new" | "none";
/**
* Watch mode
*
@@ -2638,10 +2876,10 @@ interface InlineConfig {
*/
root?: string;
/**
* Custom reporter for output. Can contain one or more built-in report names, reporter instances,
* Custom reporter for output. Can contain one or more built-in reporter names, reporter instances,
* and/or paths to custom reporters.
*
* @default []
* @default ['default'] (or ['default', 'github-actions'] when `process.env.GITHUB_ACTIONS === 'true'`)
*/
reporters?: Arrayable<ReporterName | InlineReporter> | ((ReporterName | InlineReporter) | [ReporterName] | ReporterWithOptions)[];
/**
@@ -2707,7 +2945,7 @@ interface InlineConfig {
*/
coverage?: CoverageOptions;
/**
* run test names with the specified pattern
* Run test names with the specified pattern
*/
testNamePattern?: string | RegExp;
/**
@@ -2804,6 +3042,12 @@ interface InlineConfig {
*/
logHeapUsage?: boolean;
/**
* Detect asynchronous resources leaking from the test file.
*
* @default false
*/
detectAsyncLeaks?: boolean;
/**
* Custom environment variables assigned to `process.env` before running tests.
*/
env?: Partial<NodeJS.ProcessEnv>;
@@ -2976,11 +3220,17 @@ interface InlineConfig {
*/
bail?: number;
/**
* Retry the test specific number of times if it fails.
* Retry configuration for tests.
* - If a number, specifies how many times to retry failed tests
* - If an object, allows fine-grained retry control
*
* @default 0
* ⚠️ WARNING: Function form is NOT supported in a config file
* because configurations are serialized when passed to worker threads.
* Use the function form only in test files directly.
*
* @default 0 // Don't retry
*/
retry?: number;
retry?: SerializableRetry;
/**
* Show full diff when snapshot fails instead of a patch.
*/
@@ -3037,12 +3287,89 @@ interface InlineConfig {
browserSdkPath?: string;
};
/**
* Show imports (top 10) that take a long time.
* Configure import duration collection and display.
*
* Enabling this will also show a breakdown by default in UI, but you can always press a button to toggle it.
* The `limit` option controls how many imports to collect and display.
* The `print` option controls CLI terminal output.
* UI can always toggle the breakdown display regardless of `print` setting.
*/
printImportBreakdown?: boolean;
importDurations?: {
/**
* When to print import breakdown to CLI terminal after tests finish.
* - `true`: Always print
* - `false`: Never print (default)
* - `'on-warn'`: Print only when any import exceeds the warn threshold
* @default false
*/
print?: boolean | "on-warn";
/**
* Maximum number of imports to collect and display.
* @default 0 (or 10 if `print` or UI is enabled)
*/
limit?: number;
/**
* Fail the test run if any import exceeds the danger threshold.
* When failing, the breakdown is always printed regardless of `print` setting.
* @default false
*/
failOnDanger?: boolean;
/**
* Duration thresholds in milliseconds for coloring and warnings.
*/
thresholds?: {
/**
* Warning threshold - imports exceeding this are shown in yellow/orange.
* @default 100
*/
warn?: number;
/**
* Danger threshold - imports exceeding this are shown in red.
* @default 500
*/
danger?: number;
};
};
/**
* Controls whether Vitest uses Vite's module runner to run the code or fallback to the native `import`.
*
* If Node.js cannot process the code, consider registering [module loader](https://nodejs.org/api/module.html#customization-hooks) via `execArgv`.
* @default true
*/
viteModuleRunner?: boolean;
/**
* If module runner is disabled, Vitest uses a module loader to transform files to support
* `import.meta.vitest` and `vi.mock`.
*
* If you don't use these features, you can disable this.
*
* This option only affects `loader.load` method, Vitest always defines a `loader.resolve` to populate the module graph.
*/
nodeLoader?: boolean;
/**
* Custom provider for detecting changed files. Used with the `--changed` flag
* to determine which files have been modified.
*
* By default, Vitest uses Git to detect changed files. You can provide a custom
* implementation of the `VCSProvider` interface to use a different version control system.
*/
vcsProvider?: VCSProvider | string;
/**
* Parse test specifications before running them.
* This will apply `.only` flag and test name pattern across all files without running them.
*/
preParse?: boolean;
};
/**
* Define tags available in your test files.
*
* If test defines a tag that is not listed here, an error will be thrown.
*/
tags?: TestTagDefinition[];
/**
* Should Vitest throw an error if test has a tag that is not defined in the config.
* @default true
*/
strictTags?: boolean;
}
interface TypecheckConfig {
/**
@@ -3163,11 +3490,20 @@ interface UserConfig extends InlineConfig {
* @experimental
*/
clearCache?: boolean;
/**
* Tags expression to filter tests to run. Multiple filters will be applied using AND logic.
* @see {@link https://vitest.dev/guide/test-tags#syntax}
*/
tagsFilter?: string[];
/**
* Log all available tags instead of running tests.
*/
listTags?: boolean | "json";
}
type OnUnhandledErrorCallback = (error: (TestError | Error) & {
type: string;
}) => boolean | void;
interface ResolvedConfig extends Omit<Required<UserConfig>, "project" | "config" | "filters" | "browser" | "coverage" | "testNamePattern" | "related" | "api" | "reporters" | "resolveSnapshotPath" | "benchmark" | "shard" | "cache" | "sequence" | "typecheck" | "runner" | "pool" | "cliExclude" | "diff" | "setupFiles" | "snapshotEnvironment" | "bail" | "name" | "vmMemoryLimit" | "fileParallelism"> {
interface ResolvedConfig extends Omit<Required<UserConfig>, "project" | "config" | "filters" | "browser" | "coverage" | "testNamePattern" | "related" | "api" | "reporters" | "resolveSnapshotPath" | "benchmark" | "shard" | "cache" | "sequence" | "typecheck" | "runner" | "pool" | "cliExclude" | "diff" | "setupFiles" | "snapshotEnvironment" | "bail" | "name" | "vmMemoryLimit" | "fileParallelism" | "tagsFilter"> {
mode: VitestRunMode;
name: ProjectName["label"];
color?: ProjectName["color"];
@@ -3220,8 +3556,20 @@ interface ResolvedConfig extends Omit<Required<UserConfig>, "project" | "config"
maxWorkers: number;
vmMemoryLimit?: UserConfig["vmMemoryLimit"];
dumpDir?: string;
tagsFilter?: string[];
experimental: Omit<Required<UserConfig>["experimental"], "importDurations"> & {
importDurations: {
print: boolean | "on-warn";
limit: number;
failOnDanger: boolean;
thresholds: {
warn: number;
danger: number;
};
};
};
}
type NonProjectOptions = "shard" | "watch" | "run" | "cache" | "update" | "reporters" | "outputFile" | "teardownTimeout" | "silent" | "forceRerunTriggers" | "testNamePattern" | "ui" | "open" | "uiBase" | "snapshotFormat" | "resolveSnapshotPath" | "passWithNoTests" | "onConsoleLog" | "onStackTrace" | "dangerouslyIgnoreUnhandledErrors" | "slowTestThreshold" | "inspect" | "inspectBrk" | "coverage" | "watchTriggerPatterns";
type NonProjectOptions = "shard" | "watch" | "run" | "cache" | "update" | "reporters" | "outputFile" | "teardownTimeout" | "silent" | "forceRerunTriggers" | "testNamePattern" | "ui" | "open" | "uiBase" | "snapshotFormat" | "resolveSnapshotPath" | "passWithNoTests" | "onConsoleLog" | "onStackTrace" | "dangerouslyIgnoreUnhandledErrors" | "slowTestThreshold" | "inspect" | "inspectBrk" | "coverage" | "watchTriggerPatterns" | "tagsFilter";
interface ServerDepsOptions {
/**
* Externalize means that Vite will bpass the package to native Node.
@@ -3267,5 +3615,5 @@ type TestProjectInlineConfiguration = (UserWorkspaceConfig & {
});
type TestProjectConfiguration = string | TestProjectInlineConfiguration | Promise<UserWorkspaceConfig> | UserProjectConfigFn;
export { CoverageMap as C, TestSuite as K, Logger as L, experimental_getRunnerTask as Q, TestProject as T, Vitest as V, BenchmarkReporter as aE, BenchmarkReportsMap as aF, DefaultReporter as aG, DotReporter as aH, GithubActionsReporter as aI, HangingProcessReporter as aJ, JsonReporter as aK, JUnitReporter as aL, ReportersMap as aM, TapFlatReporter as aN, TapReporter as aO, VerboseBenchmarkReporter as aP, VerboseReporter as aQ, BaseReporter as aR, TestSpecification as k, VitestPackageInstaller as p, TestCase as v, TestCollection as w, TestModule as y };
export type { BrowserCommand as $, ApiConfig as A, TestResult as B, TestResultFailed as D, TestResultPassed as E, TestResultSkipped as F, TestState as G, HTMLOptions as H, InlineConfig as I, JsonOptions as J, ModuleDiagnostic as M, TestSuiteState as N, OnServerRestartHandler as O, PoolWorker as P, ResolvedCoverageOptions as R, SerializedTestProject as S, UserWorkspaceConfig as U, WatcherTriggerPattern as W, TestSequencerConstructor as X, BenchmarkUserOptions as Y, BrowserBuiltinProvider as Z, _BrowserNames as _, ReportContext as a, BrowserCommandContext as a0, BrowserConfigOptions as a1, BrowserInstanceOption as a2, BrowserModuleMocker as a3, BrowserOrchestrator as a4, BrowserProvider as a5, BrowserProviderOption as a6, BrowserScript as a7, BrowserServerFactory as a8, BrowserServerOptions as a9, TestRunResult as aA, ReportedHookContext as aB, Reporter as aC, TestRunEndReason as aD, BenchmarkBuiltinReporters as aS, BuiltinReporterOptions as aT, BuiltinReporters as aU, JsonAssertionResult as aV, JsonTestResult as aW, JsonTestResults as aX, BrowserServerState as aa, BrowserServerStateSession as ab, CDPSession as ac, ParentProjectBrowser as ad, ProjectBrowser as ae, ResolvedBrowserOptions as af, ToMatchScreenshotComparators as ag, ToMatchScreenshotOptions as ah, BuiltinEnvironment as ai, CSSModuleScopeStrategy as aj, DepsOptimizationOptions as ak, EnvironmentOptions as al, Pool as am, ProjectConfig as an, ResolvedProjectConfig as ao, ResolveSnapshotPathHandler as ap, ResolveSnapshotPathHandlerContext as aq, TypecheckConfig as ar, VitestEnvironment as as, BaseCoverageOptions as at, CoverageIstanbulOptions as au, CoverageOptions as av, CoverageProvider as aw, CoverageProviderModule as ax, CoverageReporter as ay, CustomProviderOptions as az, TestProjectConfiguration as b, CoverageV8Options as c, UserProjectConfigFn as d, UserProjectConfigExport as e, UserConfig as f, TestProjectInlineConfiguration as g, ResolvedConfig as h, VitestRunMode as i, VitestOptions as j, PoolOptions as l, WorkerRequest as m, TestSequencer as n, OnTestsRerunHandler as o, PoolRunnerInitializer as q, PoolTask as r, WorkerResponse as s, JUnitOptions as t, TaskOptions as u, TestDiagnostic as x, TestModuleState as z };
export { Logger as L, MinimalReporter as M, TestProject as T, Vitest as V, CoverageMap as a$, DefaultReporter as a0, DotReporter as a2, GithubActionsReporter as a4, HangingProcessReporter as a6, JUnitReporter as a9, TestCase as aB, TestCollection as aC, TestModule as aE, TestSuite as aP, VerboseBenchmarkReporter as aU, VerboseReporter as aV, VitestPackageInstaller as aX, experimental_getRunnerTask as a_, JsonReporter as ac, ReportersMap as ar, TapFlatReporter as ay, TapReporter as az, TestSpecification as h, BaseReporter as l, BenchmarkReporter as n, BenchmarkReportsMap as o };
export type { CustomProviderOptions as $, ApiConfig as A, BaseCoverageOptions as B, CoverageOptions as C, BrowserServerFactory as D, BrowserServerOptions as E, FieldsWithDefaultValues as F, BrowserServerState as G, BrowserServerStateSession as H, InlineConfig as I, BuiltinEnvironment as J, BuiltinReporterOptions as K, BuiltinReporters as N, CSSModuleScopeStrategy as O, PoolWorker as P, CoverageInstrumenter as Q, ResolvedConfig as R, CoverageIstanbulOptions as S, UserWorkspaceConfig as U, WatcherTriggerPattern as W, CoverageProvider as X, CoverageProviderModule as Y, CoverageReporter as Z, CoverageV8Options as _, TestProjectConfiguration as a, DepsOptimizationOptions as a1, EnvironmentOptions as a3, HTMLOptions as a5, InstrumenterOptions as a7, JUnitOptions as a8, TaskOptions as aA, TestDiagnostic as aD, TestModuleState as aF, TestResult as aG, TestResultFailed as aH, TestResultPassed as aI, TestResultSkipped as aJ, TestRunEndReason as aK, TestRunResult as aL, TestSequencerConstructor as aM, TestSpecificationOptions as aN, TestState as aO, TestSuiteState as aQ, ToMatchScreenshotComparators as aR, ToMatchScreenshotOptions as aS, TypecheckConfig as aT, VitestEnvironment as aW, WorkerResponse as aY, _BrowserNames as aZ, JsonAssertionResult as aa, JsonOptions as ab, JsonTestResult as ad, JsonTestResults as ae, ModuleDiagnostic as af, OnServerRestartHandler as ag, OnTestsRerunHandler as ah, ParentProjectBrowser as ai, Pool as aj, PoolRunnerInitializer as ak, PoolTask as al, ProjectBrowser as am, ProjectConfig as an, ReportContext as ao, ReportedHookContext as ap, Reporter as aq, ResolveSnapshotPathHandler as as, ResolveSnapshotPathHandlerContext as at, ResolvedBrowserOptions as au, ResolvedCoverageOptions as av, ResolvedProjectConfig as aw, SerializedTestProject as ax, UserProjectConfigFn as b, UserProjectConfigExport as c, TestProjectInlineConfiguration as d, UserConfig as e, VitestRunMode as f, VitestOptions as g, PoolOptions as i, WorkerRequest as j, TestSequencer as k, BenchmarkBuiltinReporters as m, BenchmarkUserOptions as p, BrowserBuiltinProvider as q, BrowserCommand as r, BrowserCommandContext as s, BrowserConfigOptions as t, BrowserInstanceOption as u, BrowserModuleMocker as v, BrowserOrchestrator as w, BrowserProvider as x, BrowserProviderOption as y, BrowserScript as z };
-76
View File
@@ -1,76 +0,0 @@
import { getSafeTimers } from '@vitest/utils/timers';
import { c as createBirpc } from './index.Chj8NDwU.js';
import { g as getWorkerState } from './utils.DvEY5TfP.js';
const { get } = Reflect;
function withSafeTimers(fn) {
const { setTimeout, clearTimeout, nextTick, setImmediate, clearImmediate } = getSafeTimers();
const currentSetTimeout = globalThis.setTimeout;
const currentClearTimeout = globalThis.clearTimeout;
const currentSetImmediate = globalThis.setImmediate;
const currentClearImmediate = globalThis.clearImmediate;
const currentNextTick = globalThis.process?.nextTick;
try {
globalThis.setTimeout = setTimeout;
globalThis.clearTimeout = clearTimeout;
if (setImmediate) globalThis.setImmediate = setImmediate;
if (clearImmediate) globalThis.clearImmediate = clearImmediate;
if (globalThis.process && nextTick) globalThis.process.nextTick = nextTick;
return fn();
} finally {
globalThis.setTimeout = currentSetTimeout;
globalThis.clearTimeout = currentClearTimeout;
globalThis.setImmediate = currentSetImmediate;
globalThis.clearImmediate = currentClearImmediate;
if (globalThis.process && nextTick) nextTick(() => {
globalThis.process.nextTick = currentNextTick;
});
}
}
const promises = /* @__PURE__ */ new Set();
async function rpcDone() {
if (!promises.size) return;
const awaitable = Array.from(promises);
return Promise.all(awaitable);
}
const onCancelCallbacks = [];
function onCancel(callback) {
onCancelCallbacks.push(callback);
}
function createRuntimeRpc(options) {
return createSafeRpc(createBirpc({ async onCancel(reason) {
await Promise.all(onCancelCallbacks.map((fn) => fn(reason)));
} }, {
eventNames: [
"onUserConsoleLog",
"onCollected",
"onCancel"
],
timeout: -1,
...options
}));
}
function createSafeRpc(rpc) {
return new Proxy(rpc, { get(target, p, handler) {
// keep $rejectPendingCalls as sync function
if (p === "$rejectPendingCalls") return rpc.$rejectPendingCalls;
const sendCall = get(target, p, handler);
const safeSendCall = (...args) => withSafeTimers(async () => {
const result = sendCall(...args);
promises.add(result);
try {
return await result;
} finally {
promises.delete(result);
}
});
safeSendCall.asEvent = sendCall.asEvent;
return safeSendCall;
} });
}
function rpc() {
const { rpc } = getWorkerState();
return rpc;
}
export { rpcDone as a, createRuntimeRpc as c, onCancel as o, rpc as r };
+144
View File
@@ -0,0 +1,144 @@
import { getSafeTimers } from '@vitest/utils/timers';
import { c as createBirpc } from './index.Chj8NDwU.js';
import { g as getWorkerState } from './utils.BX5Fg8C4.js';
/* Ported from https://github.com/boblauer/MockDate/blob/master/src/mockdate.ts */
/*
The MIT License (MIT)
Copyright (c) 2014 Bob Lauer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
const RealDate = Date;
let now = null;
class MockDate extends RealDate {
constructor(y, m, d, h, M, s, ms) {
super();
let date;
switch (arguments.length) {
case 0:
if (now !== null) date = new RealDate(now.valueOf());
else date = new RealDate();
break;
case 1:
date = new RealDate(y);
break;
default:
d = typeof d === "undefined" ? 1 : d;
h = h || 0;
M = M || 0;
s = s || 0;
ms = ms || 0;
date = new RealDate(y, m, d, h, M, s, ms);
break;
}
Object.setPrototypeOf(date, MockDate.prototype);
return date;
}
}
MockDate.UTC = RealDate.UTC;
MockDate.now = function() {
return new MockDate().valueOf();
};
MockDate.parse = function(dateString) {
return RealDate.parse(dateString);
};
MockDate.toString = function() {
return RealDate.toString();
};
function mockDate(date) {
const dateObj = new RealDate(date.valueOf());
if (Number.isNaN(dateObj.getTime())) throw new TypeError(`mockdate: The time set is an invalid date: ${date}`);
// @ts-expect-error global
globalThis.Date = MockDate;
now = dateObj.valueOf();
}
function resetDate() {
globalThis.Date = RealDate;
}
const { get } = Reflect;
function withSafeTimers(fn) {
const { setTimeout, clearTimeout, nextTick, setImmediate, clearImmediate } = getSafeTimers();
const currentSetTimeout = globalThis.setTimeout;
const currentClearTimeout = globalThis.clearTimeout;
const currentSetImmediate = globalThis.setImmediate;
const currentClearImmediate = globalThis.clearImmediate;
const currentNextTick = globalThis.process?.nextTick;
try {
globalThis.setTimeout = setTimeout;
globalThis.clearTimeout = clearTimeout;
if (setImmediate) globalThis.setImmediate = setImmediate;
if (clearImmediate) globalThis.clearImmediate = clearImmediate;
if (globalThis.process && nextTick) globalThis.process.nextTick = nextTick;
return fn();
} finally {
globalThis.setTimeout = currentSetTimeout;
globalThis.clearTimeout = currentClearTimeout;
globalThis.setImmediate = currentSetImmediate;
globalThis.clearImmediate = currentClearImmediate;
if (globalThis.process && nextTick) nextTick(() => {
globalThis.process.nextTick = currentNextTick;
});
}
}
const promises = /* @__PURE__ */ new Set();
async function rpcDone() {
if (!promises.size) return;
const awaitable = Array.from(promises);
return Promise.all(awaitable);
}
const onCancelCallbacks = [];
function onCancel(callback) {
onCancelCallbacks.push(callback);
}
function createRuntimeRpc(options) {
return createSafeRpc(createBirpc({ async onCancel(reason) {
await Promise.all(onCancelCallbacks.map((fn) => fn(reason)));
} }, {
eventNames: ["onCancel"],
timeout: -1,
...options
}));
}
function createSafeRpc(rpc) {
return new Proxy(rpc, { get(target, p, handler) {
// keep $rejectPendingCalls as sync function
if (p === "$rejectPendingCalls") return rpc.$rejectPendingCalls;
const sendCall = get(target, p, handler);
const safeSendCall = (...args) => withSafeTimers(async () => {
const result = sendCall(...args);
promises.add(result);
try {
return await result;
} finally {
promises.delete(result);
}
});
safeSendCall.asEvent = sendCall.asEvent;
return safeSendCall;
} });
}
function rpc() {
const { rpc } = getWorkerState();
return rpc;
}
export { RealDate as R, rpcDone as a, resetDate as b, createRuntimeRpc as c, mockDate as m, onCancel as o, rpc as r };
@@ -1,43 +1,7 @@
import { CancelReason, File, TestArtifact, TaskResultPack, TaskEventPack } from '@vitest/runner';
import { File, TestArtifact, TaskResultPack, TaskEventPack, CancelReason } from '@vitest/runner';
import { SnapshotResult } from '@vitest/snapshot';
import { FetchFunctionOptions, FetchResult } from 'vite/module-runner';
import { O as OTELCarrier } from './traces.d.402V_yFI.js';
interface AfterSuiteRunMeta {
coverage?: unknown;
testFiles: string[];
environment: string;
projectName?: string;
}
interface UserConsoleLog {
content: string;
origin?: string;
browser?: boolean;
type: "stdout" | "stderr";
taskId?: string;
time: number;
size: number;
}
interface ModuleGraphData {
graph: Record<string, string[]>;
externalized: string[];
inlined: string[];
}
interface ProvidedContext {}
interface ResolveFunctionResult {
id: string;
file: string;
url: string;
}
interface FetchCachedFileSystemResult {
cached: true;
tmp: string;
id: string;
file: string | null;
url: string;
invalidate: boolean;
}
type LabelColor = "black" | "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "white";
import { O as OTELCarrier, F as FetchCachedFileSystemResult, R as ResolveFunctionResult, U as UserConsoleLog, A as AsyncLeak, a as AfterSuiteRunMeta } from './traces.d.D2T_R8rx.js';
interface RuntimeRPC {
fetch: (id: string, importer: string | undefined, environment: string, options?: FetchFunctionOptions, otelCarrier?: OTELCarrier) => Promise<FetchResult | FetchCachedFileSystemResult>;
@@ -47,6 +11,7 @@ interface RuntimeRPC {
}>;
onUserConsoleLog: (log: UserConsoleLog) => void;
onUnhandledError: (err: unknown, type: string) => void;
onAsyncLeaks: (leak: AsyncLeak[]) => void;
onQueued: (file: File) => void;
onCollected: (files: File[]) => Promise<void>;
onAfterSuiteRun: (meta: AfterSuiteRunMeta) => void;
@@ -56,9 +21,10 @@ interface RuntimeRPC {
getCountOfFailedTests: () => number;
snapshotSaved: (snapshot: SnapshotResult) => void;
resolveSnapshotPath: (testPath: string) => string;
ensureModuleGraphEntry: (id: string, importer: string) => void;
}
interface RunnerRPC {
onCancel: (reason: CancelReason) => void;
}
export type { AfterSuiteRunMeta as A, LabelColor as L, ModuleGraphData as M, ProvidedContext as P, RuntimeRPC as R, UserConsoleLog as U, RunnerRPC as a };
export type { RuntimeRPC as R, RunnerRPC as a };
@@ -1,7 +1,7 @@
import { r as resolveCoverageProviderModule } from './coverage.D_JHT54q.js';
import { r as resolveCoverageProviderModule } from './coverage.CTzCuANN.js';
import { addSerializer } from '@vitest/snapshot';
import { setSafeTimers } from '@vitest/utils/timers';
import { g as getWorkerState } from './utils.DvEY5TfP.js';
import { g as getWorkerState } from './utils.BX5Fg8C4.js';
async function startCoverageInsideWorker(options, loader, runtimeOptions) {
const coverageModule = await resolveCoverageProviderModule(options, loader);
@@ -26,7 +26,7 @@ async function setupCommonEnv(config) {
if (globalSetup) return;
globalSetup = true;
setSafeTimers();
if (config.globals) (await import('./globals.DOayXfHP.js')).registerApiGlobally();
if (config.globals) (await import('./globals.Dj1TGiMC.js')).registerApiGlobally();
}
function setupDefines(config) {
for (const key in config.defines) globalThis[key] = config.defines[key];
@@ -57,4 +57,4 @@ async function loadSnapshotSerializers(config, moduleRunner) {
}))).forEach((serializer) => addSerializer(serializer));
}
export { stopCoverageInsideWorker as a, loadSnapshotSerializers as b, setupCommonEnv as c, loadDiffConfig as l, startCoverageInsideWorker as s, takeCoverageInsideWorker as t };
export { loadSnapshotSerializers as a, startCoverageInsideWorker as b, stopCoverageInsideWorker as c, loadDiffConfig as l, setupCommonEnv as s, takeCoverageInsideWorker as t };
@@ -1,249 +1,29 @@
import fs from 'node:fs';
import { isBareImport } from '@vitest/utils/helpers';
import { i as isBuiltin, a as isBrowserExternal, t as toBuiltin } from './modules.BJuCwlRJ.js';
import { E as EnvironmentTeardownError, a as getSafeWorkerState } from './utils.BX5Fg8C4.js';
import { pathToFileURL } from 'node:url';
import { normalize as normalize$1, join as join$1 } from 'pathe';
import { normalize, join } from 'pathe';
import { distDir } from '../path.js';
import { serializeValue } from '@vitest/utils/serialize';
import { VitestModuleEvaluator, unwrapId } from '../module-evaluator.js';
import { resolve as resolve$1, isAbsolute as isAbsolute$1 } from 'node:path';
import { isAbsolute, resolve } from 'node:path';
import vm from 'node:vm';
import { MockerRegistry, mockObject, RedirectedModule, AutomockedModule } from '@vitest/mocker';
import nodeModule from 'node:module';
import { findMockRedirect } from '@vitest/mocker/redirect';
import * as viteModuleRunner from 'vite/module-runner';
import { T as Traces } from './traces.CCmnQaNT.js';
import { T as Traces } from './traces.DT5aQ62U.js';
class VitestTransport {
constructor(options) {
this.options = options;
}
async invoke(event) {
if (event.type !== "custom") return { error: /* @__PURE__ */ new Error(`Vitest Module Runner doesn't support Vite HMR events.`) };
if (event.event !== "vite:invoke") return { error: /* @__PURE__ */ new Error(`Vitest Module Runner doesn't support ${event.event} event.`) };
const { name, data } = event.data;
if (name === "getBuiltins")
// we return an empty array here to avoid client-side builtin check,
// as we need builtins to go through `fetchModule`
return { result: [] };
if (name !== "fetchModule") return { error: /* @__PURE__ */ new Error(`Unknown method: ${name}. Expected "fetchModule".`) };
try {
return { result: await this.options.fetchModule(...data) };
} catch (error) {
return { error };
}
}
}
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
function normalizeWindowsPath(input = "") {
if (!input) return input;
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
}
const _UNC_REGEX = /^[/\\]{2}/;
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
const _EXTNAME_RE = /.(\.[^./]+|\.)$/;
const normalize = function(path) {
if (path.length === 0) return ".";
path = normalizeWindowsPath(path);
const isUNCPath = path.match(_UNC_REGEX);
const isPathAbsolute = isAbsolute(path);
const trailingSeparator = path[path.length - 1] === "/";
path = normalizeString(path, !isPathAbsolute);
if (path.length === 0) {
if (isPathAbsolute) return "/";
return trailingSeparator ? "./" : ".";
}
if (trailingSeparator) path += "/";
if (_DRIVE_LETTER_RE.test(path)) path += "/";
if (isUNCPath) {
if (!isPathAbsolute) return `//./${path}`;
return `//${path}`;
}
return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
};
const join = function(...segments) {
let path = "";
for (const seg of segments) {
if (!seg) continue;
if (path.length > 0) {
const pathTrailing = path[path.length - 1] === "/";
const segLeading = seg[0] === "/";
if (pathTrailing && segLeading) path += seg.slice(1);
else path += pathTrailing || segLeading ? seg : `/${seg}`;
} else path += seg;
}
return normalize(path);
};
function cwd$1() {
if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
return "/";
}
const resolve = function(...arguments_) {
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
let resolvedPath = "";
let resolvedAbsolute = false;
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
const path = index >= 0 ? arguments_[index] : cwd$1();
if (!path || path.length === 0) continue;
resolvedPath = `${path}/${resolvedPath}`;
resolvedAbsolute = isAbsolute(path);
}
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
return resolvedPath.length > 0 ? resolvedPath : ".";
};
function normalizeString(path, allowAboveRoot) {
let res = "";
let lastSegmentLength = 0;
let lastSlash = -1;
let dots = 0;
let char = null;
for (let index = 0; index <= path.length; ++index) {
if (index < path.length) char = path[index];
else if (char === "/") break;
else char = "/";
if (char === "/") {
if (lastSlash === index - 1 || dots === 1);
else if (dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
if (res.length > 2) {
const lastSlashIndex = res.lastIndexOf("/");
if (lastSlashIndex === -1) {
res = "";
lastSegmentLength = 0;
} else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
}
lastSlash = index;
dots = 0;
continue;
} else if (res.length > 0) {
res = "";
lastSegmentLength = 0;
lastSlash = index;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
res += res.length > 0 ? "/.." : "..";
lastSegmentLength = 2;
}
} else {
if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
else res = path.slice(lastSlash + 1, index);
lastSegmentLength = index - lastSlash - 1;
}
lastSlash = index;
dots = 0;
} else if (char === "." && dots !== -1) ++dots;
else dots = -1;
}
return res;
}
const isAbsolute = function(p) {
return _IS_ABSOLUTE_RE.test(p);
};
const extname = function(p) {
if (p === "..") return "";
const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
return match && match[1] || "";
};
const dirname = function(p) {
const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
return segments.join("/") || (isAbsolute(p) ? "/" : ".");
};
const basename = function(p, extension) {
const segments = normalizeWindowsPath(p).split("/");
let lastSegment = "";
for (let i = segments.length - 1; i >= 0; i--) {
const val = segments[i];
if (val) {
lastSegment = val;
break;
}
}
return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
};
const { existsSync, readdirSync, statSync } = fs;
function findMockRedirect(root, mockPath, external) {
const path = external || mockPath;
// it's a node_module alias
// all mocks should be inside <root>/__mocks__
if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) {
const mockFolder = join(root, "__mocks__", dirname(path));
if (!existsSync(mockFolder)) return null;
const baseOriginal = basename(path);
function findFile(mockFolder, baseOriginal) {
const files = readdirSync(mockFolder);
for (const file of files) if (basename(file, extname(file)) === baseOriginal) {
const path = resolve(mockFolder, file);
// if the same name, return the file
if (statSync(path).isFile()) return path;
else {
// find folder/index.{js,ts}
const indexFile = findFile(path, "index");
if (indexFile) return indexFile;
}
}
return null;
}
return findFile(mockFolder, baseOriginal);
}
const fullPath = resolve(dirname(path), "__mocks__", basename(path));
return existsSync(fullPath) ? fullPath : null;
}
const builtins = new Set([
...nodeModule.builtinModules,
"assert/strict",
"diagnostics_channel",
"dns/promises",
"fs/promises",
"path/posix",
"path/win32",
"readline/promises",
"stream/consumers",
"stream/promises",
"stream/web",
"timers/promises",
"util/types",
"wasi"
]);
// https://nodejs.org/api/modules.html#built-in-modules-with-mandatory-node-prefix
const prefixedBuiltins$1 = new Set([
"node:sea",
"node:sqlite",
"node:test",
"node:test/reporters"
]);
const NODE_BUILTIN_NAMESPACE = "node:";
function isNodeBuiltin(id) {
// Added in v18.6.0
if (nodeModule.isBuiltin) return nodeModule.isBuiltin(id);
if (prefixedBuiltins$1.has(id)) return true;
return builtins.has(id.startsWith(NODE_BUILTIN_NAMESPACE) ? id.slice(5) : id);
}
const spyModulePath = resolve$1(distDir, "spy.js");
class VitestMocker {
class BareModuleMocker {
static pendingIds = [];
spyModule;
primitives;
filterPublicKeys;
registries = /* @__PURE__ */ new Map();
mockContext = { callstack: null };
_otel;
constructor(moduleRunner, options) {
this.moduleRunner = moduleRunner;
constructor(options) {
this.options = options;
const context = this.options.context;
this._otel = options.traces;
if (context) this.primitives = vm.runInContext("({ Object, Error, Function, RegExp, Symbol, Array, Map })", context);
else this.primitives = {
this.primitives = {
Object,
Error,
Function,
@@ -253,37 +33,13 @@ class VitestMocker {
Map
};
if (options.spyModule) this.spyModule = options.spyModule;
const Symbol = this.primitives.Symbol;
this.filterPublicKeys = [
"__esModule",
Symbol.asyncIterator,
Symbol.hasInstance,
Symbol.isConcatSpreadable,
Symbol.iterator,
Symbol.match,
Symbol.matchAll,
Symbol.replace,
Symbol.search,
Symbol.split,
Symbol.species,
Symbol.toPrimitive,
Symbol.toStringTag,
Symbol.unscopables
];
}
get root() {
return this.options.root;
}
get evaluatedModules() {
return this.moduleRunner.evaluatedModules;
}
get moduleDirectories() {
return this.options.moduleDirectories || [];
}
async initializeSpyModule() {
if (this.spyModule) return;
this.spyModule = await this.moduleRunner.import(spyModulePath);
}
getMockerRegistry() {
const suite = this.getSuiteFilepath();
if (!this.registries.has(suite)) this.registries.set(suite, new MockerRegistry());
@@ -292,13 +48,8 @@ class VitestMocker {
reset() {
this.registries.clear();
}
invalidateModuleById(id) {
const mockId = this.getMockPath(id);
const node = this.evaluatedModules.getModuleById(mockId);
if (node) {
this.evaluatedModules.invalidateModule(node);
node.mockedExports = void 0;
}
invalidateModuleById(_id) {
// implemented by mockers that control the module runner
}
isModuleDirectory(path) {
return this.moduleDirectories.some((dir) => path.includes(dir));
@@ -335,7 +86,7 @@ class VitestMocker {
}
// external is node_module or unresolved module
// for example, some people mock "vscode" and don't have it installed
const external = !isAbsolute$1(result.file) || this.isModuleDirectory(result.file) ? normalizeModuleId(rawId) : null;
const external = !isAbsolute(result.file) || this.isModuleDirectory(result.file) ? normalizeModuleId(rawId) : null;
const id = normalizeModuleId(result.id);
span.setAttributes({
"vitest.module.id": id,
@@ -350,13 +101,205 @@ class VitestMocker {
});
}
async resolveMocks() {
if (!VitestMocker.pendingIds.length) return;
await Promise.all(VitestMocker.pendingIds.map(async (mock) => {
if (!BareModuleMocker.pendingIds.length) return;
const resolveMock = async (mock) => {
const { id, url, external } = await this.resolveId(mock.id, mock.importer);
if (mock.action === "unmock") this.unmockPath(id);
if (mock.action === "mock") this.mockPath(mock.id, id, url, external, mock.type, mock.factory);
}));
VitestMocker.pendingIds = [];
};
// group consecutive mocks of the same action type together,
// resolve in parallel inside each group, but run groups sequentially
// to preserve mock/unmock ordering
const groups = groupByConsecutiveAction(BareModuleMocker.pendingIds);
for (const group of groups) await Promise.all(group.map(resolveMock));
BareModuleMocker.pendingIds = [];
}
// public method to avoid circular dependency
getMockContext() {
return this.mockContext;
}
// path used to store mocked dependencies
getMockPath(dep) {
return `mock:${dep}`;
}
getDependencyMock(id) {
return this.getMockerRegistry().getById(fixLeadingSlashes(id));
}
getDependencyMockByUrl(url) {
return this.getMockerRegistry().get(url);
}
findMockRedirect(mockPath, external) {
return findMockRedirect(this.root, mockPath, external);
}
mockObject(object, mockExportsOrModuleType, moduleType) {
let mockExports;
if (mockExportsOrModuleType === "automock" || mockExportsOrModuleType === "autospy") {
moduleType = mockExportsOrModuleType;
mockExports = void 0;
} else mockExports = mockExportsOrModuleType;
moduleType ??= "automock";
const createMockInstance = this.spyModule?.createMockInstance;
if (!createMockInstance) throw this.createError("[vitest] `spyModule` is not defined. This is a Vitest error. Please open a new issue with reproduction.");
return mockObject({
globalConstructors: this.primitives,
createMockInstance,
type: moduleType
}, object, mockExports);
}
unmockPath(id) {
this.getMockerRegistry().deleteById(id);
this.invalidateModuleById(id);
}
mockPath(originalId, id, url, external, mockType, factory) {
const registry = this.getMockerRegistry();
if (mockType === "manual") registry.register("manual", originalId, id, url, factory);
else if (mockType === "autospy") registry.register("autospy", originalId, id, url);
else {
const redirect = this.findMockRedirect(id, external);
if (redirect) registry.register("redirect", originalId, id, url, redirect);
else registry.register("automock", originalId, id, url);
}
// every time the mock is registered, we remove the previous one from the cache
this.invalidateModuleById(id);
}
async importActual(_rawId, _importer, _callstack) {
throw new Error(`importActual is not implemented`);
}
async importMock(_rawId, _importer, _callstack) {
throw new Error(`importMock is not implemented`);
}
queueMock(id, importer, factoryOrOptions) {
const mockType = getMockType(factoryOrOptions);
BareModuleMocker.pendingIds.push({
action: "mock",
id,
importer,
factory: typeof factoryOrOptions === "function" ? factoryOrOptions : void 0,
type: mockType
});
}
queueUnmock(id, importer) {
BareModuleMocker.pendingIds.push({
action: "unmock",
id,
importer
});
}
}
function getMockType(factoryOrOptions) {
if (!factoryOrOptions) return "automock";
if (typeof factoryOrOptions === "function") return "manual";
return factoryOrOptions.spy ? "autospy" : "automock";
}
// unique id that is not available as "$bare_import" like "test"
// https://nodejs.org/api/modules.html#built-in-modules-with-mandatory-node-prefix
const prefixedBuiltins = new Set([
"node:sea",
"node:sqlite",
"node:test",
"node:test/reporters"
]);
const isWindows$1 = process.platform === "win32";
// transform file url to id
// virtual:custom -> virtual:custom
// \0custom -> \0custom
// /root/id -> /id
// /root/id.js -> /id.js
// C:/root/id.js -> /id.js
// C:\root\id.js -> /id.js
// TODO: expose this in vite/module-runner
function normalizeModuleId(file) {
if (prefixedBuiltins.has(file)) return file;
// if it's not in the root, keep it as a path, not a URL
return slash(file).replace(/^\/@fs\//, isWindows$1 ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/").replace(/^file:\//, "/");
}
const windowsSlashRE = /\\/g;
function slash(p) {
return p.replace(windowsSlashRE, "/");
}
function groupByConsecutiveAction(mocks) {
const groups = [];
for (const mock of mocks) {
const last = groups.at(-1);
if (last?.[0].action === mock.action) last.push(mock);
else groups.push([mock]);
}
return groups;
}
const multipleSlashRe = /^\/+/;
// module-runner incorrectly replaces file:///path with `///path`
function fixLeadingSlashes(id) {
if (id.startsWith("//")) return id.replace(multipleSlashRe, "/");
return id;
}
// copied from vite
// https://github.com/vitejs/vite/blob/4417b4f305623b2850bd6ae6553834c017694672/packages/vite/src/shared/utils.ts
// https://github.com/vitejs/vite/blob/4417b4f305623b2850bd6ae6553834c017694672/packages/vite/src/node/utils.ts
const postfixRE = /[?#].*$/;
const trailingSeparatorRE = /[?&]$/;
function cleanUrl(url) {
return url.replace(postfixRE, "");
}
function splitFileAndPostfix(path) {
const file = cleanUrl(path);
return {
file,
postfix: path.slice(file.length)
};
}
function injectQuery(url, queryToInject) {
const { file, postfix } = splitFileAndPostfix(url);
return `${file}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : postfix}`;
}
function removeQuery(url, queryToRemove) {
return url.replace(new RegExp(`([?&])${queryToRemove}(?:&|$)`), "$1").replace(trailingSeparatorRE, "");
}
const spyModulePath = resolve(distDir, "spy.js");
class VitestMocker extends BareModuleMocker {
filterPublicKeys;
constructor(moduleRunner, options) {
super(options);
this.moduleRunner = moduleRunner;
this.options = options;
const context = this.options.context;
if (context) this.primitives = vm.runInContext("({ Object, Error, Function, RegExp, Symbol, Array, Map })", context);
const Symbol = this.primitives.Symbol;
this.filterPublicKeys = [
"__esModule",
Symbol.asyncIterator,
Symbol.hasInstance,
Symbol.isConcatSpreadable,
Symbol.iterator,
Symbol.match,
Symbol.matchAll,
Symbol.replace,
Symbol.search,
Symbol.split,
Symbol.species,
Symbol.toPrimitive,
Symbol.toStringTag,
Symbol.unscopables
];
}
get evaluatedModules() {
return this.moduleRunner.evaluatedModules;
}
async initializeSpyModule() {
if (this.spyModule) return;
this.spyModule = await this.moduleRunner.import(spyModulePath);
}
reset() {
this.registries.clear();
}
invalidateModuleById(id) {
const mockId = this.getMockPath(id);
const node = this.evaluatedModules.getModuleById(mockId);
if (node) {
this.evaluatedModules.invalidateModule(node);
node.mockedExports = void 0;
}
}
ensureModule(id, url) {
const node = this.evaluatedModules.ensureModule(id, url);
@@ -396,48 +339,10 @@ If you need to partially mock a module, you can use "importOriginal" helper insi
node.exports = moduleExports;
return moduleExports;
}
// public method to avoid circular dependency
getMockContext() {
return this.mockContext;
}
// path used to store mocked dependencies
getMockPath(dep) {
return `mock:${dep}`;
}
getDependencyMock(id) {
return this.getMockerRegistry().getById(fixLeadingSlashes(id));
}
findMockRedirect(mockPath, external) {
return findMockRedirect(this.root, mockPath, external);
}
mockObject(object, mockExports = {}, behavior = "automock") {
const createMockInstance = this.spyModule?.createMockInstance;
if (!createMockInstance) throw this.createError("[vitest] `spyModule` is not defined. This is a Vitest error. Please open a new issue with reproduction.");
return mockObject({
globalConstructors: this.primitives,
createMockInstance,
type: behavior
}, object, mockExports);
}
unmockPath(id) {
this.getMockerRegistry().deleteById(id);
this.invalidateModuleById(id);
}
mockPath(originalId, id, url, external, mockType, factory) {
const registry = this.getMockerRegistry();
if (mockType === "manual") registry.register("manual", originalId, id, url, factory);
else if (mockType === "autospy") registry.register("autospy", originalId, id, url);
else {
const redirect = this.findMockRedirect(id, external);
if (redirect) registry.register("redirect", originalId, id, url, redirect);
else registry.register("automock", originalId, id, url);
}
// every time the mock is registered, we remove the previous one from the cache
this.invalidateModuleById(id);
}
async importActual(rawId, importer, callstack) {
const { url } = await this.resolveId(rawId, importer);
const node = await this.moduleRunner.fetchModule(url, importer);
const actualUrl = injectQuery(url, "_vitest_original");
const node = await this.moduleRunner.fetchModule(actualUrl, importer);
return await this.moduleRunner.cachedRequest(node.url, node, callstack || [importer], void 0, true);
}
async importMock(rawId, importer) {
@@ -511,61 +416,44 @@ If you need to partially mock a module, you can use "importOriginal" helper insi
if (!mock) return;
return this.requestWithMockedModule(url, evaluatedNode, callstack, mock);
}
queueMock(id, importer, factoryOrOptions) {
const mockType = getMockType(factoryOrOptions);
VitestMocker.pendingIds.push({
action: "mock",
id,
importer,
factory: typeof factoryOrOptions === "function" ? factoryOrOptions : void 0,
type: mockType
});
}
class VitestTransport {
constructor(options, evaluatedModules, callstacks) {
this.options = options;
this.evaluatedModules = evaluatedModules;
this.callstacks = callstacks;
}
queueUnmock(id, importer) {
VitestMocker.pendingIds.push({
action: "unmock",
id,
importer
});
async invoke(event) {
if (event.type !== "custom") return { error: /* @__PURE__ */ new Error(`Vitest Module Runner doesn't support Vite HMR events.`) };
if (event.event !== "vite:invoke") return { error: /* @__PURE__ */ new Error(`Vitest Module Runner doesn't support ${event.event} event.`) };
const { name, data } = event.data;
if (name === "getBuiltins")
// we return an empty array here to avoid client-side builtin check,
// as we need builtins to go through `fetchModule`
return { result: [] };
if (name !== "fetchModule") return { error: /* @__PURE__ */ new Error(`Unknown method: ${name}. Expected "fetchModule".`) };
try {
return { result: await this.options.fetchModule(...data) };
} catch (cause) {
if (cause instanceof EnvironmentTeardownError) {
const [id, importer] = data;
let message = `Cannot load '${id}'${importer ? ` imported from ${importer}` : ""} after the environment was torn down. This is not a bug in Vitest.`;
const moduleNode = importer ? this.evaluatedModules.getModuleById(importer) : void 0;
const callstack = moduleNode ? this.callstacks.get(moduleNode) : void 0;
if (callstack) message += ` The last recorded callstack:\n- ${[
...callstack,
importer,
id
].reverse().join("\n- ")}`;
const error = new EnvironmentTeardownError(message);
if (cause.stack) error.stack = cause.stack.replace(cause.message, error.message);
return { error };
}
return { error: cause };
}
}
}
function getMockType(factoryOrOptions) {
if (!factoryOrOptions) return "automock";
if (typeof factoryOrOptions === "function") return "manual";
return factoryOrOptions.spy ? "autospy" : "automock";
}
// unique id that is not available as "$bare_import" like "test"
// https://nodejs.org/api/modules.html#built-in-modules-with-mandatory-node-prefix
const prefixedBuiltins = new Set([
"node:sea",
"node:sqlite",
"node:test",
"node:test/reporters"
]);
const isWindows$1 = process.platform === "win32";
// transform file url to id
// virtual:custom -> virtual:custom
// \0custom -> \0custom
// /root/id -> /id
// /root/id.js -> /id.js
// C:/root/id.js -> /id.js
// C:\root\id.js -> /id.js
// TODO: expose this in vite/module-runner
function normalizeModuleId(file) {
if (prefixedBuiltins.has(file)) return file;
// if it's not in the root, keep it as a path, not a URL
return slash(file).replace(/^\/@fs\//, isWindows$1 ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/").replace(/^file:\//, "/");
}
const windowsSlashRE = /\\/g;
function slash(p) {
return p.replace(windowsSlashRE, "/");
}
const multipleSlashRe = /^\/+/;
// module-runner incorrectly replaces file:///path with `///path`
function fixLeadingSlashes(id) {
if (id.startsWith("//")) return id.replace(multipleSlashRe, "/");
return id;
}
const createNodeImportMeta = (modulePath) => {
if (!viteModuleRunner.createDefaultImportMeta) throw new Error(`createNodeImportMeta is not supported in this version of Vite.`);
@@ -589,10 +477,12 @@ class VitestModuleRunner extends viteModuleRunner.ModuleRunner {
mocker;
moduleExecutionInfo;
_otel;
_callstacks;
constructor(vitestOptions) {
const options = vitestOptions;
const transport = new VitestTransport(options.transport);
const evaluatedModules = options.evaluatedModules;
const callstacks = /* @__PURE__ */ new WeakMap();
const transport = new VitestTransport(options.transport, evaluatedModules, callstacks);
super({
transport,
hmr: false,
@@ -601,6 +491,7 @@ class VitestModuleRunner extends viteModuleRunner.ModuleRunner {
createImportMeta: vitestOptions.createImportMeta
}, options.evaluator);
this.vitestOptions = vitestOptions;
this._callstacks = callstacks;
this._otel = vitestOptions.traces || new Traces({ enabled: false });
this.moduleExecutionInfo = options.getWorkerState().moduleExecutionInfo;
this.mocker = options.mocker || new VitestMocker(this, {
@@ -629,7 +520,7 @@ class VitestModuleRunner extends viteModuleRunner.ModuleRunner {
* Vite checks that the module has exports emulating the Node.js behaviour,
* but Vitest is more relaxed.
*
* We should keep the Vite behavour when there is a `strict` flag.
* We should keep the Vite behavior when there is a `strict` flag.
* @internal
*/
processImport(exports$1) {
@@ -658,10 +549,24 @@ class VitestModuleRunner extends viteModuleRunner.ModuleRunner {
* @internal
*/
async cachedRequest(url, mod, callstack = [], metadata, ignoreMock = false) {
// Track for a better error message if dynamic import is not resolved properly
this._callstacks.set(mod, callstack);
if (ignoreMock) return this._cachedRequest(url, mod, callstack, metadata);
let mocked;
if (mod.meta && "mockedModule" in mod.meta) mocked = await this.mocker.requestWithMockedModule(url, mod, callstack, mod.meta.mockedModule);
else mocked = await this.mocker.mockedRequest(url, mod, callstack);
if (mod.meta && "mockedModule" in mod.meta) {
const mockedModule = mod.meta.mockedModule;
const mockId = this.mocker.getMockPath(mod.id);
// bypass mock and force "importActual" behavior when:
// - mock was removed by doUnmock (stale mockedModule in meta)
// - self-import: mock factory/file is importing the module it's mocking
const isStale = !this.mocker.getDependencyMock(mod.id);
const isSelfImport = callstack.includes(mockId) || callstack.includes(url) || "redirect" in mockedModule && callstack.includes(mockedModule.redirect);
if (isStale || isSelfImport) {
const node = await this.fetchModule(injectQuery(url, "_vitest_original"));
return this._cachedRequest(node.url, node, callstack, metadata);
}
mocked = await this.mocker.requestWithMockedModule(url, mod, callstack, mockedModule);
} else mocked = await this.mocker.mockedRequest(url, mod, callstack);
if (typeof mocked === "string") {
const node = await this.fetchModule(mocked);
return this._cachedRequest(mocked, node, callstack, metadata);
@@ -684,7 +589,7 @@ class VitestModuleRunner extends viteModuleRunner.ModuleRunner {
}
const bareVitestRegexp = /^@?vitest(?:\/|$)/;
const normalizedDistDir = normalize$1(distDir);
const normalizedDistDir = normalize(distDir);
const relativeIds = {};
const externalizeMap = /* @__PURE__ */ new Map();
// all Vitest imports always need to be externalized
@@ -707,7 +612,7 @@ function getCachedVitestImport(id, state) {
};
}
if (relativeRoot && relativeRoot !== "/" && id.startsWith(relativeRoot)) {
const externalize = pathToFileURL(join$1(root, id)).toString();
const externalize = pathToFileURL(join(root, id)).toString();
externalizeMap.set(id, externalize);
return {
externalize,
@@ -724,48 +629,14 @@ function getCachedVitestImport(id, state) {
return null;
}
// Store globals in case tests overwrite them
const processListeners = process.listeners.bind(process);
const processOn = process.on.bind(process);
const processOff = process.off.bind(process);
const dispose = [];
function listenForErrors(state) {
dispose.forEach((fn) => fn());
dispose.length = 0;
function catchError(err, type, event) {
const worker = state();
// if there is another listener, assume that it's handled by user code
// one is Vitest's own listener
if (processListeners(event).length > 1) return;
const error = serializeValue(err);
if (typeof error === "object" && error != null) {
error.VITEST_TEST_NAME = worker.current?.type === "test" ? worker.current.name : void 0;
if (worker.filepath) error.VITEST_TEST_PATH = worker.filepath;
}
state().rpc.onUnhandledError(error, type);
}
const uncaughtException = (e) => catchError(e, "Uncaught Exception", "uncaughtException");
const unhandledRejection = (e) => catchError(e, "Unhandled Rejection", "unhandledRejection");
processOn("uncaughtException", uncaughtException);
processOn("unhandledRejection", unhandledRejection);
dispose.push(() => {
processOff("uncaughtException", uncaughtException);
processOff("unhandledRejection", unhandledRejection);
});
}
const { readFileSync } = fs;
const VITEST_VM_CONTEXT_SYMBOL = "__vitest_vm_context__";
const cwd = process.cwd();
const isWindows = process.platform === "win32";
function startVitestModuleRunner(options) {
const traces = options.traces;
const state = () => globalThis.__vitest_worker__ || options.state;
const state = () => getSafeWorkerState() || options.state;
const rpc = () => state().rpc;
process.exit = (code = process.exitCode || 0) => {
throw new Error(`process.exit unexpectedly called with "${code}"`);
};
listenForErrors(state);
const environment = () => {
const environment = state().environment;
return environment.viteEnvironment || environment.name;
@@ -804,19 +675,25 @@ function startVitestModuleRunner(options) {
}
const vitest = getCachedVitestImport(id, state);
if (vitest) return vitest;
// strip _vitest_original query added by importActual so that
// the plugin pipeline sees the original import id (e.g. virtual modules's load hook)
const isImportActual = id.includes("_vitest_original");
if (isImportActual) id = removeQuery(id, "_vitest_original");
const rawId = unwrapId(id);
resolvingModules.add(rawId);
try {
if (VitestMocker.pendingIds.length) await moduleRunner.mocker.resolveMocks();
const resolvedMock = moduleRunner.mocker.getDependencyMock(rawId);
if (resolvedMock?.type === "manual" || resolvedMock?.type === "redirect") return {
code: "",
file: null,
id,
url: id,
invalidate: false,
mockedModule: resolvedMock
};
if (!isImportActual) {
const resolvedMock = moduleRunner.mocker.getDependencyMockByUrl(id);
if (resolvedMock?.type === "manual" || resolvedMock?.type === "redirect") return {
code: "",
file: null,
id: resolvedMock.id,
url: resolvedMock.url,
invalidate: false,
mockedModule: resolvedMock
};
}
if (isBuiltin(rawId)) return {
externalize: rawId,
type: "builtin"
@@ -827,7 +704,7 @@ function startVitestModuleRunner(options) {
};
// if module is invalidated, the worker will be recreated,
// so cached is always true in a single worker
if (options?.cached) return { cache: true };
if (!isImportActual && options?.cached) return { cache: true };
const otelCarrier = traces?.getContextCarrier();
const result = await rpc().fetch(id, importer, environment(), options, otelCarrier);
if ("cached" in result) return {
@@ -838,7 +715,7 @@ function startVitestModuleRunner(options) {
} catch (cause) {
// rethrow vite error if it cannot load the module because it's not resolved
if (typeof cause === "object" && cause != null && cause.code === "ERR_LOAD_URL" || typeof cause?.message === "string" && cause.message.includes("Failed to load url") || typeof cause?.message === "string" && cause.message.startsWith("Cannot find module '")) {
const error = new Error(`Cannot find ${isBareImport(id) ? "package" : "module"} '${id}'${importer ? ` imported from '${importer}'` : ""}`, { cause });
const error = new Error(`Cannot find ${isBareImport(id) ? "package" : "module"} '${id}'${importer ? ` imported from ${importer}` : ""}`, { cause });
error.code = "ERR_MODULE_NOT_FOUND";
throw error;
}
@@ -858,4 +735,4 @@ function startVitestModuleRunner(options) {
return moduleRunner;
}
export { VitestModuleRunner as V, VITEST_VM_CONTEXT_SYMBOL as a, VitestTransport as b, createNodeImportMeta as c, startVitestModuleRunner as s };
export { BareModuleMocker as B, VITEST_VM_CONTEXT_SYMBOL as V, VitestModuleRunner as a, VitestTransport as b, createNodeImportMeta as c, normalizeModuleId as n, startVitestModuleRunner as s };
@@ -1,5 +1,5 @@
import { Test } from '@vitest/runner';
import { c as BenchmarkAPI, a as BenchFunction } from './benchmark.d.DAaHLpsq.js';
import { a as BenchFunction, c as BenchmarkAPI } from './benchmark.d.DAaHLpsq.js';
import { Options } from 'tinybench';
import '@vitest/runner/utils';
-254
View File
@@ -1,254 +0,0 @@
import { updateTask } from '@vitest/runner';
import { createDefer } from '@vitest/utils/helpers';
import { getSafeTimers } from '@vitest/utils/timers';
import { a as getBenchOptions, g as getBenchFn } from './benchmark.B3N2zMcH.js';
import { g as getWorkerState } from './utils.DvEY5TfP.js';
import { setState, GLOBAL_EXPECT, getState } from '@vitest/expect';
import { getTests, getNames, getTestName } from '@vitest/runner/utils';
import { processError } from '@vitest/utils/error';
import { normalize } from 'pathe';
import { a as getSnapshotClient, i as inject, c as createExpect, v as vi } from './vi.2VT5v0um.js';
import { r as rpc } from './rpc.BoxB0q7B.js';
function createBenchmarkResult(name) {
return {
name,
rank: 0,
rme: 0,
samples: []
};
}
const benchmarkTasks = /* @__PURE__ */ new WeakMap();
async function runBenchmarkSuite(suite, runner) {
const { Task, Bench } = await runner.importTinybench();
const start = performance.now();
const benchmarkGroup = [];
const benchmarkSuiteGroup = [];
for (const task of suite.tasks) {
if (task.mode !== "run" && task.mode !== "queued") continue;
if (task.meta?.benchmark) benchmarkGroup.push(task);
else if (task.type === "suite") benchmarkSuiteGroup.push(task);
}
// run sub suites sequentially
for (const subSuite of benchmarkSuiteGroup) await runBenchmarkSuite(subSuite, runner);
if (benchmarkGroup.length) {
const defer = createDefer();
suite.result = {
state: "run",
startTime: start,
benchmark: createBenchmarkResult(suite.name)
};
updateTask$1("suite-prepare", suite);
const addBenchTaskListener = (task, benchmark) => {
task.addEventListener("complete", (e) => {
const taskRes = e.task.result;
const result = benchmark.result.benchmark;
benchmark.result.state = "pass";
Object.assign(result, taskRes);
// compute extra stats and free raw samples as early as possible
const samples = result.samples;
result.sampleCount = samples.length;
result.median = samples.length % 2 ? samples[Math.floor(samples.length / 2)] : (samples[samples.length / 2] + samples[samples.length / 2 - 1]) / 2;
if (!runner.config.benchmark?.includeSamples) result.samples.length = 0;
updateTask$1("test-finished", benchmark);
}, { once: true });
task.addEventListener("error", (e) => {
const task = e.task;
defer.reject(benchmark ? task.result.error : e);
}, { once: true });
};
benchmarkGroup.forEach((benchmark) => {
const benchmarkInstance = new Bench(getBenchOptions(benchmark));
const benchmarkFn = getBenchFn(benchmark);
benchmark.result = {
state: "run",
startTime: start,
benchmark: createBenchmarkResult(benchmark.name)
};
const task = new Task(benchmarkInstance, benchmark.name, benchmarkFn);
benchmarkTasks.set(benchmark, task);
addBenchTaskListener(task, benchmark);
});
const { setTimeout } = getSafeTimers();
const tasks = [];
for (const benchmark of benchmarkGroup) {
const task = benchmarkTasks.get(benchmark);
updateTask$1("test-prepare", benchmark);
await task.warmup();
tasks.push([await new Promise((resolve) => setTimeout(async () => {
resolve(await task.run());
})), benchmark]);
}
suite.result.duration = performance.now() - start;
suite.result.state = "pass";
updateTask$1("suite-finished", suite);
defer.resolve(null);
await defer;
}
function updateTask$1(event, task) {
updateTask(event, task, runner);
}
}
class NodeBenchmarkRunner {
moduleRunner;
constructor(config) {
this.config = config;
}
async importTinybench() {
return await import('tinybench');
}
importFile(filepath, source) {
if (source === "setup") {
const moduleNode = getWorkerState().evaluatedModules.getModuleById(filepath);
if (moduleNode) getWorkerState().evaluatedModules.invalidateModule(moduleNode);
}
return this.moduleRunner.import(filepath);
}
async runSuite(suite) {
await runBenchmarkSuite(suite, this);
}
async runTask() {
throw new Error("`test()` and `it()` is only available in test mode.");
}
}
// worker context is shared between all tests
const workerContext = Object.create(null);
class VitestTestRunner {
snapshotClient = getSnapshotClient();
workerState = getWorkerState();
moduleRunner;
cancelRun = false;
assertionsErrors = /* @__PURE__ */ new WeakMap();
pool = this.workerState.ctx.pool;
_otel;
viteEnvironment;
constructor(config) {
this.config = config;
const environment = this.workerState.environment;
this.viteEnvironment = environment.viteEnvironment || environment.name;
}
importFile(filepath, source) {
if (source === "setup") {
const moduleNode = this.workerState.evaluatedModules.getModuleById(filepath);
if (moduleNode) this.workerState.evaluatedModules.invalidateModule(moduleNode);
}
return this._otel.$(`vitest.module.import_${source === "setup" ? "setup" : "spec"}`, { attributes: { "code.file.path": filepath } }, () => this.moduleRunner.import(filepath));
}
onCollectStart(file) {
this.workerState.current = file;
}
onCleanupWorkerContext(listener) {
this.workerState.onCleanup(listener);
}
onAfterRunFiles() {
this.snapshotClient.clear();
this.workerState.current = void 0;
}
getWorkerContext() {
return workerContext;
}
async onAfterRunSuite(suite) {
if (this.config.logHeapUsage && typeof process !== "undefined") suite.result.heap = process.memoryUsage().heapUsed;
if (suite.mode !== "skip" && "filepath" in suite) {
// mark snapshots in skipped tests as not obsolete
for (const test of getTests(suite)) if (test.mode === "skip") {
const name = getNames(test).slice(1).join(" > ");
this.snapshotClient.skipTest(suite.file.filepath, name);
}
const result = await this.snapshotClient.finish(suite.file.filepath);
if (this.workerState.config.snapshotOptions.updateSnapshot === "none" && result.unchecked) {
let message = `Obsolete snapshots found when no snapshot update is expected.\n`;
for (const key of result.uncheckedKeys) message += `· ${key}\n`;
suite.result.errors ??= [];
suite.result.errors.push(processError(new Error(message)));
suite.result.state = "fail";
}
await rpc().snapshotSaved(result);
}
this.workerState.current = suite.suite || suite.file;
}
onAfterRunTask(test) {
if (this.config.logHeapUsage && typeof process !== "undefined") test.result.heap = process.memoryUsage().heapUsed;
this.workerState.current = test.suite || test.file;
}
cancel(_reason) {
this.cancelRun = true;
}
injectValue(key) {
// inject has a very limiting type controlled by ProvidedContext
// some tests override it which causes the build to fail
return inject(key);
}
async onBeforeRunTask(test) {
if (this.cancelRun) test.mode = "skip";
if (test.mode !== "run" && test.mode !== "queued") return;
this.workerState.current = test;
}
async onBeforeRunSuite(suite) {
if (this.cancelRun) suite.mode = "skip";
// initialize snapshot state before running file suite
if (suite.mode !== "skip" && "filepath" in suite) await this.snapshotClient.setup(suite.file.filepath, this.workerState.config.snapshotOptions);
this.workerState.current = suite;
}
onBeforeTryTask(test) {
clearModuleMocks(this.config);
this.snapshotClient.clearTest(test.file.filepath, test.id);
setState({
assertionCalls: 0,
isExpectingAssertions: false,
isExpectingAssertionsError: null,
expectedAssertionsNumber: null,
expectedAssertionsNumberErrorGen: null,
currentTestName: getTestName(test),
snapshotState: this.snapshotClient.getSnapshotState(test.file.filepath)
}, globalThis[GLOBAL_EXPECT]);
}
onAfterTryTask(test) {
const { assertionCalls, expectedAssertionsNumber, expectedAssertionsNumberErrorGen, isExpectingAssertions, isExpectingAssertionsError } = test.context._local ? test.context.expect.getState() : getState(globalThis[GLOBAL_EXPECT]);
if (expectedAssertionsNumber !== null && assertionCalls !== expectedAssertionsNumber) throw expectedAssertionsNumberErrorGen();
if (isExpectingAssertions === true && assertionCalls === 0) throw isExpectingAssertionsError;
if (this.config.expect.requireAssertions && assertionCalls === 0) throw this.assertionsErrors.get(test);
}
extendTaskContext(context) {
// create error during the test initialization so we have a nice stack trace
if (this.config.expect.requireAssertions) this.assertionsErrors.set(context.task, /* @__PURE__ */ new Error("expected any number of assertion, but got none"));
let _expect;
Object.defineProperty(context, "expect", { get() {
if (!_expect) _expect = createExpect(context.task);
return _expect;
} });
Object.defineProperty(context, "_local", { get() {
return _expect != null;
} });
return context;
}
getImportDurations() {
const importDurations = {};
const entries = this.workerState.moduleExecutionInfo?.entries() || [];
for (const [filepath, { duration, selfTime, external, importer }] of entries) importDurations[normalize(filepath)] = {
selfTime,
totalTime: duration,
external,
importer
};
return importDurations;
}
trace = (name, attributes, cb) => {
const options = typeof attributes === "object" ? { attributes } : {};
return this._otel.$(`vitest.test.runner.${name}`, options, cb || attributes);
};
__setTraces(traces) {
this._otel = traces;
}
}
function clearModuleMocks(config) {
const { clearMocks, mockReset, restoreMocks, unstubEnvs, unstubGlobals } = config;
if (restoreMocks) vi.restoreAllMocks();
if (mockReset) vi.resetAllMocks();
if (clearMocks) vi.clearAllMocks();
if (unstubEnvs) vi.unstubAllEnvs();
if (unstubGlobals) vi.unstubAllGlobals();
}
export { NodeBenchmarkRunner as N, VitestTestRunner as V };
File diff suppressed because it is too large Load Diff
@@ -130,7 +130,7 @@ class Traces {
}
throw error;
} finally {
// end sync callbcak
// end sync callback
if (!(result instanceof Promise)) span.end();
}
}
-18
View File
@@ -1,18 +0,0 @@
interface OTELCarrier {
traceparent?: string;
tracestate?: string;
}
interface TracesOptions {
enabled: boolean;
watchMode?: boolean;
sdkPath?: string;
tracerName?: string;
}
declare class Traces {
#private;
constructor(options: TracesOptions);
isEnabled(): boolean;
}
export { Traces as T };
export type { OTELCarrier as O };
+60
View File
@@ -0,0 +1,60 @@
interface AfterSuiteRunMeta {
coverage?: unknown;
testFiles: string[];
environment: string;
projectName?: string;
}
interface UserConsoleLog {
content: string;
origin?: string;
browser?: boolean;
type: "stdout" | "stderr";
taskId?: string;
time: number;
size: number;
}
interface ModuleGraphData {
graph: Record<string, string[]>;
externalized: string[];
inlined: string[];
}
interface ProvidedContext {}
interface ResolveFunctionResult {
id: string;
file: string;
url: string;
}
interface FetchCachedFileSystemResult {
cached: true;
tmp: string;
id: string;
file: string | null;
url: string;
invalidate: boolean;
}
type LabelColor = "black" | "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "white";
interface AsyncLeak {
filename: string;
projectName: string;
stack: string;
type: string;
}
interface OTELCarrier {
traceparent?: string;
tracestate?: string;
}
interface TracesOptions {
enabled: boolean;
watchMode?: boolean;
sdkPath?: string;
tracerName?: string;
}
declare class Traces {
#private;
constructor(options: TracesOptions);
isEnabled(): boolean;
}
export { Traces as T };
export type { AsyncLeak as A, FetchCachedFileSystemResult as F, LabelColor as L, ModuleGraphData as M, OTELCarrier as O, ProvidedContext as P, ResolveFunctionResult as R, UserConsoleLog as U, AfterSuiteRunMeta as a };
+189
View File
@@ -0,0 +1,189 @@
import { stripVTControlCharacters } from 'node:util';
import { slash } from '@vitest/utils/helpers';
import { isAbsolute, relative, dirname, basename } from 'pathe';
import c from 'tinyrainbow';
const F_RIGHT = "→";
const F_DOWN = "↓";
const F_DOWN_RIGHT = "↳";
const F_POINTER = "❯";
const F_DOT = "·";
const F_CHECK = "✓";
const F_CROSS = "×";
const F_LONG_DASH = "⎯";
const F_TODO = "□";
const F_TREE_NODE_MIDDLE = "├──";
const F_TREE_NODE_END = "└──";
const pointer = c.yellow(F_POINTER);
const skipped = c.dim(c.gray(F_DOWN));
const todo = c.dim(c.gray(F_TODO));
const benchmarkPass = c.green(F_DOT);
const testPass = c.green(F_CHECK);
const taskFail = c.red(F_CROSS);
const suiteFail = c.red(F_POINTER);
const pending = c.gray("·");
const separator = c.dim(" > ");
const labelDefaultColors = [
c.bgYellow,
c.bgCyan,
c.bgGreen,
c.bgMagenta
];
function getCols(delta = 0) {
let length = process.stdout?.columns;
if (!length || Number.isNaN(length)) length = 30;
return Math.max(length + delta, 0);
}
function errorBanner(message) {
return divider(c.bold(c.bgRed(` ${message} `)), null, null, c.red);
}
function divider(text, left, right, color) {
const cols = getCols();
const c = color || ((text) => text);
if (text) {
const textLength = stripVTControlCharacters(text).length;
if (left == null && right != null) left = cols - textLength - right;
else {
left = left ?? Math.floor((cols - textLength) / 2);
right = cols - textLength - left;
}
left = Math.max(0, left);
right = Math.max(0, right);
return `${c(F_LONG_DASH.repeat(left))}${text}${c(F_LONG_DASH.repeat(right))}`;
}
return F_LONG_DASH.repeat(cols);
}
function formatTestPath(root, path) {
if (isAbsolute(path)) path = relative(root, path);
const dir = dirname(path);
const ext = path.match(/(\.(spec|test)\.[cm]?[tj]sx?)$/)?.[0] || "";
const base = basename(path, ext);
return slash(c.dim(`${dir}/`) + c.bold(base)) + c.dim(ext);
}
function renderSnapshotSummary(rootDir, snapshots) {
const summary = [];
if (snapshots.added) summary.push(c.bold(c.green(`${snapshots.added} written`)));
if (snapshots.unmatched) summary.push(c.bold(c.red(`${snapshots.unmatched} failed`)));
if (snapshots.updated) summary.push(c.bold(c.green(`${snapshots.updated} updated `)));
if (snapshots.filesRemoved) if (snapshots.didUpdate) summary.push(c.bold(c.green(`${snapshots.filesRemoved} files removed `)));
else summary.push(c.bold(c.yellow(`${snapshots.filesRemoved} files obsolete `)));
if (snapshots.filesRemovedList && snapshots.filesRemovedList.length) {
const [head, ...tail] = snapshots.filesRemovedList;
summary.push(`${c.gray(F_DOWN_RIGHT)} ${formatTestPath(rootDir, head)}`);
tail.forEach((key) => {
summary.push(` ${c.gray(F_DOT)} ${formatTestPath(rootDir, key)}`);
});
}
if (snapshots.unchecked) {
if (snapshots.didUpdate) summary.push(c.bold(c.green(`${snapshots.unchecked} removed`)));
else summary.push(c.bold(c.yellow(`${snapshots.unchecked} obsolete`)));
snapshots.uncheckedKeysByFile.forEach((uncheckedFile) => {
summary.push(`${c.gray(F_DOWN_RIGHT)} ${formatTestPath(rootDir, uncheckedFile.filePath)}`);
uncheckedFile.keys.forEach((key) => summary.push(` ${c.gray(F_DOT)} ${key}`));
});
}
return summary;
}
function countTestErrors(tasks) {
return tasks.reduce((c, i) => c + (i.result?.errors?.length || 0), 0);
}
function getStateString(tasks, name = "tests", showTotal = true) {
if (tasks.length === 0) return c.dim(`no ${name}`);
const passed = tasks.reduce((acc, i) => {
// Exclude expected failures from passed count
if (i.result?.state === "pass" && i.type === "test" && i.fails) return acc;
return i.result?.state === "pass" ? acc + 1 : acc;
}, 0);
const failed = tasks.reduce((acc, i) => i.result?.state === "fail" ? acc + 1 : acc, 0);
const skipped = tasks.reduce((acc, i) => i.mode === "skip" ? acc + 1 : acc, 0);
const todo = tasks.reduce((acc, i) => i.mode === "todo" ? acc + 1 : acc, 0);
const expectedFail = tasks.reduce((acc, i) => {
// Count tests that are marked as .fails and passed (which means they failed as expected)
if (i.result?.state === "pass" && i.type === "test" && i.fails) return acc + 1;
return acc;
}, 0);
return [
failed ? c.bold(c.red(`${failed} failed`)) : null,
passed ? c.bold(c.green(`${passed} passed`)) : null,
expectedFail ? c.cyan(`${expectedFail} expected fail`) : null,
skipped ? c.yellow(`${skipped} skipped`) : null,
todo ? c.gray(`${todo} todo`) : null
].filter(Boolean).join(c.dim(" | ")) + (showTotal ? c.gray(` (${tasks.length})`) : "");
}
function getStateSymbol(task) {
if (task.mode === "todo") return todo;
if (task.mode === "skip") return skipped;
if (!task.result) return pending;
if (task.result.state === "run" || task.result.state === "queued") {
if (task.type === "suite") return pointer;
}
if (task.result.state === "pass") return task.meta?.benchmark ? benchmarkPass : testPass;
if (task.result.state === "fail") return task.type === "suite" ? suiteFail : taskFail;
return " ";
}
function formatTimeString(date) {
return date.toTimeString().split(" ")[0];
}
function formatTime(time) {
if (time > 1e3) return `${(time / 1e3).toFixed(2)}s`;
return `${Math.round(time)}ms`;
}
function formatProjectName(project, suffix = " ") {
if (!project?.name) return "";
if (!c.isColorSupported) return `|${project.name}|${suffix}`;
let background = project.color && c[`bg${capitalize(project.color)}`];
if (!background) background = labelDefaultColors[project.name.split("").reduce((acc, v, idx) => acc + v.charCodeAt(0) + idx, 0) % labelDefaultColors.length];
return c.black(background(` ${project.name} `)) + suffix;
}
function withLabel(color, label, message) {
const bgColor = `bg${color.charAt(0).toUpperCase()}${color.slice(1)}`;
return `${c.bold(c.black(c[bgColor](` ${label} `)))} ${message ? c[color](message) : ""}`;
}
function padSummaryTitle(str) {
return c.dim(`${str.padStart(11)} `);
}
function truncateString(text, maxLength) {
const plainText = stripVTControlCharacters(text);
if (plainText.length <= maxLength) return text;
return `${plainText.slice(0, maxLength - 1)}…`;
}
function capitalize(text) {
return `${text[0].toUpperCase()}${text.slice(1)}`;
}
/**
* Returns the singular or plural form of a word based on the count.
*/
function noun(count, singular, plural) {
if (count === 1) return singular;
return plural;
}
var utils = /*#__PURE__*/Object.freeze({
__proto__: null,
benchmarkPass: benchmarkPass,
countTestErrors: countTestErrors,
divider: divider,
errorBanner: errorBanner,
formatProjectName: formatProjectName,
formatTestPath: formatTestPath,
formatTime: formatTime,
formatTimeString: formatTimeString,
getStateString: getStateString,
getStateSymbol: getStateSymbol,
noun: noun,
padSummaryTitle: padSummaryTitle,
pending: pending,
pointer: pointer,
renderSnapshotSummary: renderSnapshotSummary,
separator: separator,
skipped: skipped,
suiteFail: suiteFail,
taskFail: taskFail,
testPass: testPass,
todo: todo,
truncateString: truncateString,
withLabel: withLabel
});
export { F_POINTER as F, taskFail as a, F_CHECK as b, F_DOWN_RIGHT as c, divider as d, errorBanner as e, formatTimeString as f, formatProjectName as g, getStateSymbol as h, getStateString as i, formatTime as j, countTestErrors as k, F_TREE_NODE_END as l, F_TREE_NODE_MIDDLE as m, noun as n, F_RIGHT as o, padSummaryTitle as p, renderSnapshotSummary as r, separator as s, truncateString as t, utils as u, withLabel as w };
@@ -1,12 +1,19 @@
import { getSafeTimers } from '@vitest/utils/timers';
const NAME_WORKER_STATE = "__vitest_worker__";
class EnvironmentTeardownError extends Error {
name = "EnvironmentTeardownError";
}
function getWorkerState() {
// @ts-expect-error untyped global
const workerState = globalThis[NAME_WORKER_STATE];
if (!workerState) throw new Error("Vitest failed to access its internal state.\n\nOne of the following is possible:\n- \"vitest\" is imported directly without running \"vitest\" command\n- \"vitest\" is imported inside \"globalSetup\" (to fix this, use \"setupFiles\" instead, because \"globalSetup\" runs in a different context)\n- \"vitest\" is imported inside Vite / Vitest config file\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n");
return workerState;
}
function getSafeWorkerState() {
// @ts-expect-error untyped global
return globalThis[NAME_WORKER_STATE];
}
function provideWorkerState(context, state) {
Object.defineProperty(context, NAME_WORKER_STATE, {
value: state,
@@ -49,4 +56,4 @@ async function waitForImportsToResolve() {
await waitForImportsToResolve();
}
export { getWorkerState as g, isChildProcess as i, provideWorkerState as p, resetModules as r, waitForImportsToResolve as w };
export { EnvironmentTeardownError as E, getSafeWorkerState as a, getWorkerState as g, isChildProcess as i, provideWorkerState as p, resetModules as r, waitForImportsToResolve as w };
@@ -1,18 +1,18 @@
import { fileURLToPath, pathToFileURL } from 'node:url';
import vm, { isContext, runInContext } from 'node:vm';
import { dirname, basename, extname, normalize, resolve } from 'pathe';
import { l as loadEnvironment, e as emitModuleRunner } from './init.B6MLFIaN.js';
import { l as loadEnvironment, a as listenForErrors, e as emitModuleRunner } from './init.d4hAcNdp.js';
import { distDir } from '../path.js';
import { createCustomConsole } from './console.Cf-YriPC.js';
import { createCustomConsole } from './console.3WNpx0tS.js';
import fs from 'node:fs';
import { createRequire, Module, isBuiltin } from 'node:module';
import { toArray, isBareImport } from '@vitest/utils/helpers';
import { toArray, splitFileAndPostfix, isBareImport } from '@vitest/utils/helpers';
import { findNearestPackageData } from '@vitest/utils/resolver';
import { dirname as dirname$1 } from 'node:path';
import { CSS_LANGS_RE, KNOWN_ASSET_RE } from '@vitest/utils/constants';
import { getDefaultRequestStubs } from '../module-evaluator.js';
import { s as startVitestModuleRunner, c as createNodeImportMeta, a as VITEST_VM_CONTEXT_SYMBOL } from './startModuleRunner.DEj0jb3e.js';
import { p as provideWorkerState } from './utils.DvEY5TfP.js';
import { s as startVitestModuleRunner, V as VITEST_VM_CONTEXT_SYMBOL, c as createNodeImportMeta } from './startVitestModuleRunner.CCBQZ9DQ.js';
import { p as provideWorkerState } from './utils.BX5Fg8C4.js';
function interopCommonJsModule(interopDefault, mod) {
if (isPrimitive(mod) || Array.isArray(mod) || mod instanceof Promise) return {
@@ -174,15 +174,27 @@ class CommonjsExecutor {
const code = this.fs.readFile(filename);
m.exports = JSON.parse(code);
};
static cjsConditions;
static getCjsConditions() {
if (!CommonjsExecutor.cjsConditions) CommonjsExecutor.cjsConditions = parseCjsConditions(process.execArgv, process.env.NODE_OPTIONS);
return CommonjsExecutor.cjsConditions;
}
createRequire = (filename) => {
const _require = createRequire(filename);
const resolve = (id, options) => {
return _require.resolve(id, {
...options,
conditions: CommonjsExecutor.getCjsConditions()
});
};
const require = ((id) => {
const resolved = _require.resolve(id);
const resolved = resolve(id);
if (extname(resolved) === ".node" || isBuiltin(resolved)) return this.requireCoreModule(resolved);
const module = new this.Module(resolved);
return this.loadCommonJSModule(module, resolved);
});
require.resolve = _require.resolve;
require.resolve = resolve;
require.resolve.paths = _require.resolve.paths;
Object.defineProperty(require, "extensions", {
get: () => this.extensions,
set: () => {},
@@ -315,6 +327,27 @@ class CommonjsExecutor {
return moduleExports;
}
}
// The "module-sync" exports condition (added in Node 22.12/20.19 when
// require(esm) was unflagged) can resolve to ESM files that our CJS
// vm.Script executor cannot handle. We exclude it by passing explicit
// CJS conditions to require.resolve (Node 22.12+).
// Must be a Set because Node's internal resolver calls conditions.has().
// User-specified --conditions/-C flags are respected, except module-sync.
function parseCjsConditions(execArgv, nodeOptions) {
const conditions = [
"node",
"require",
"node-addons"
];
const args = [...execArgv, ...nodeOptions?.split(/\s+/) ?? []];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
const eqMatch = arg.match(/^(?:--conditions|-C)=(.+)$/);
if (eqMatch) conditions.push(eqMatch[1]);
else if ((arg === "--conditions" || arg === "-C") && i + 1 < args.length) conditions.push(args[++i]);
}
return new Set(conditions.filter((c) => c !== "module-sync"));
}
const dataURIRegex = /^data:(?<mime>text\/javascript|application\/json|application\/wasm)(?:;(?<encoding>charset=utf-8|base64))?,(?<code>.*)$/;
class EsmExecutor {
@@ -584,7 +617,8 @@ class ExternalModulesExecutor {
url: identifier,
path: identifier
};
const extension = extname(identifier);
const { file, postfix } = splitFileAndPostfix(identifier);
const extension = extname(file);
if (extension === ".node" || isBuiltin(identifier)) return {
type: "builtin",
url: identifier,
@@ -596,8 +630,8 @@ class ExternalModulesExecutor {
path: identifier
};
const isFileUrl = identifier.startsWith("file://");
const pathUrl = isFileUrl ? fileURLToPath(identifier.split("?")[0]) : identifier;
const fileUrl = isFileUrl ? identifier : pathToFileURL(pathUrl).toString();
const pathUrl = isFileUrl ? fileURLToPath(file) : file;
const fileUrl = isFileUrl ? identifier : `${pathToFileURL(file)}${postfix}`;
let type;
if (this.vite.canResolve(fileUrl)) type = "vite";
else if (extension === ".mjs") type = "module";
@@ -674,7 +708,7 @@ const packageCache = /* @__PURE__ */ new Map();
async function runVmTests(method, state, traces) {
const { ctx, rpc } = state;
const beforeEnvironmentTime = performance.now();
const { environment } = await loadEnvironment(ctx.environment.name, ctx.config.root, rpc, traces);
const { environment } = await loadEnvironment(ctx.environment.name, ctx.config.root, rpc, traces, true);
state.environment = environment;
if (!environment.setupVM) {
const envName = ctx.environment.name;
@@ -708,6 +742,10 @@ async function runVmTests(method, state, traces) {
transform: rpc.transform,
viteClientModule: stubs["/@vite/client"]
});
process.exit = (code = process.exitCode || 0) => {
throw new Error(`process.exit unexpectedly called with "${code}"`);
};
listenForErrors(() => state);
const moduleRunner = startVitestModuleRunner({
context,
evaluatedModules: state.evaluatedModules,
@@ -740,5 +778,8 @@ async function runVmTests(method, state, traces) {
await traces.$("vitest.runtime.environment.teardown", () => vm.teardown?.());
}
}
function setupVmWorker(context) {
if (context.config.experimental.viteModuleRunner === false) throw new Error(`Pool "${context.pool}" cannot run with "experimental.viteModuleRunner: false". Please, use "threads" or "forks" instead.`);
}
export { runVmTests as r };
export { runVmTests as r, setupVmWorker as s };
@@ -1,8 +1,8 @@
import { FileSpecification, Task, CancelReason } from '@vitest/runner';
import { EvaluatedModules } from 'vite/module-runner';
import { S as SerializedConfig } from './config.d.Cy95HiCx.js';
import { S as SerializedConfig } from './config.d.A1h_Y6Jt.js';
import { E as Environment } from './environment.d.CrsxCzP1.js';
import { R as RuntimeRPC, a as RunnerRPC } from './rpc.d.RH3apGEf.js';
import { R as RuntimeRPC, a as RunnerRPC } from './rpc.d.B_8sPU0w.js';
//#region src/messages.d.ts
declare const TYPE_REQUEST: "q";
+3 -20
View File
@@ -1,28 +1,11 @@
import { c as createCLI } from './chunks/cac.DVeoLl0M.js';
import { c as createCLI } from './chunks/cac.D3xHeqeL.js';
import '@vitest/utils/helpers';
import 'events';
import 'pathe';
import 'tinyrainbow';
import './chunks/constants.D_Q9UYh-.js';
import './chunks/index.M8mOzt4Y.js';
import 'node:fs';
import 'node:fs/promises';
import 'node:perf_hooks';
import '@vitest/runner/utils';
import '@vitest/utils/source-map';
import './chunks/env.D4Lgay0q.js';
import 'std-env';
import 'node:util';
import 'node:console';
import 'node:stream';
import '@vitest/utils/display';
import 'node:os';
import 'tinyexec';
import './path.js';
import 'node:path';
import 'node:url';
import 'vite';
import '@vitest/utils/offset';
import 'node:module';
import './chunks/constants.CPYnjOGj.js';
import 'node:assert';
createCLI().parse();
+16 -7
View File
@@ -24,14 +24,22 @@ const coverageConfigDefaults = {
exclude: [],
reportOnFailure: false,
reporter: [
["text", {}],
["html", {}],
["clover", {}],
["json", {}]
"text",
"html",
"clover",
"json"
],
allowExternal: false,
excludeAfterRemap: false,
processingConcurrency: Math.min(20, os.availableParallelism?.() ?? os.cpus().length)
processingConcurrency: Math.min(20, os.availableParallelism?.() ?? os.cpus().length),
ignoreClassMethods: [],
skipFull: false,
watermarks: {
statements: [50, 80],
functions: [50, 80],
branches: [50, 80],
lines: [50, 80]
}
};
const fakeTimersDefaults = {
loopLimit: 1e4,
@@ -40,7 +48,7 @@ const fakeTimersDefaults = {
const configDefaults = Object.freeze({
allowOnly: !stdEnv.isCI,
isolate: true,
watch: !stdEnv.isCI && process.stdin.isTTY,
watch: !stdEnv.isCI && process.stdin.isTTY && !stdEnv.isAgent,
globals: false,
environment: "node",
clearMocks: false,
@@ -71,7 +79,8 @@ const configDefaults = Object.freeze({
exclude: defaultExclude
},
slowTestThreshold: 300,
disableConsoleIntercept: false
disableConsoleIntercept: false,
detectAsyncLeaks: false
});
function defineConfig(config) {
+18 -17
View File
@@ -1,22 +1,19 @@
import { HookHandler, ConfigEnv, UserConfig } from 'vite';
import { HookHandler, UserConfig, ConfigEnv } from 'vite';
export { ConfigEnv, Plugin, UserConfig as ViteUserConfig, mergeConfig } from 'vite';
import { I as InlineConfig, c as CoverageV8Options, R as ResolvedCoverageOptions, U as UserWorkspaceConfig, d as UserProjectConfigFn, e as UserProjectConfigExport } from './chunks/reporters.d.CWXNI2jG.js';
export { b as TestProjectConfiguration, g as TestProjectInlineConfiguration, f as TestUserConfig, W as WatcherTriggerPattern } from './chunks/reporters.d.CWXNI2jG.js';
import { V as VitestPluginContext } from './chunks/plugin.d.CtqpEehP.js';
import { F as FakeTimerInstallOpts } from './chunks/config.d.Cy95HiCx.js';
import '@vitest/runner';
import { I as InlineConfig, C as CoverageOptions, F as FieldsWithDefaultValues, U as UserWorkspaceConfig, b as UserProjectConfigFn, c as UserProjectConfigExport } from './chunks/reporters.d.DtoKVV2s.js';
export { a as TestProjectConfiguration, d as TestProjectInlineConfiguration, e as TestUserConfig, W as WatcherTriggerPattern } from './chunks/reporters.d.DtoKVV2s.js';
import { V as VitestPluginContext } from './chunks/plugin.d.DwFIiJ7i.js';
import { F as FakeTimerInstallOpts } from './chunks/config.d.A1h_Y6Jt.js';
export { TestTagDefinition } from '@vitest/runner';
import '@vitest/utils';
import './chunks/rpc.d.RH3apGEf.js';
import '@vitest/snapshot';
import 'vite/module-runner';
import './chunks/traces.d.402V_yFI.js';
import './chunks/traces.d.D2T_R8rx.js';
import 'node:stream';
import './chunks/browser.d.ChKACdzH.js';
import './chunks/worker.d.Dyxm8DEL.js';
import './chunks/browser.d.BcoexmFG.js';
import './chunks/worker.d.ZpHpO4yb.js';
import 'vite/module-runner';
import './chunks/environment.d.CrsxCzP1.js';
import '@vitest/mocker';
import '@vitest/utils/source-map';
import 'vitest/browser';
import './chunks/rpc.d.B_8sPU0w.js';
import '@vitest/snapshot';
import '@vitest/pretty-format';
import '@vitest/utils/diff';
import '@vitest/expect';
@@ -24,6 +21,9 @@ import 'vitest/optional-types.js';
import './chunks/benchmark.d.DAaHLpsq.js';
import '@vitest/runner/utils';
import 'tinybench';
import '@vitest/mocker';
import '@vitest/utils/source-map';
import 'vitest/browser';
import './chunks/coverage.d.BZtK59WP.js';
import '@vitest/snapshot/manager';
import 'node:console';
@@ -46,7 +46,7 @@ declare const defaultBrowserPort = 63315;
declare const defaultInclude: string[];
declare const defaultExclude: string[];
declare const coverageConfigDefaults: ResolvedCoverageOptions;
declare const coverageConfigDefaults: Required<Pick<CoverageOptions, FieldsWithDefaultValues>>;
declare const configDefaults: Readonly<{
allowOnly: boolean;
isolate: boolean;
@@ -73,7 +73,7 @@ declare const configDefaults: Readonly<{
css: {
include: never[];
};
coverage: CoverageV8Options;
coverage: CoverageOptions;
fakeTimers: FakeTimerInstallOpts;
maxConcurrency: number;
dangerouslyIgnoreUnhandledErrors: boolean;
@@ -84,6 +84,7 @@ declare const configDefaults: Readonly<{
};
slowTestThreshold: number;
disableConsoleIntercept: boolean;
detectAsyncLeaks: boolean;
}>;
type ViteUserConfigFnObject = (env: ConfigEnv) => UserConfig;
+2 -2
View File
@@ -1,6 +1,6 @@
export { c as configDefaults, a as coverageConfigDefaults, d as defaultExclude, b as defaultInclude } from './chunks/defaults.BOqNVLsY.js';
export { c as configDefaults, a as coverageConfigDefaults, d as defaultExclude, b as defaultInclude } from './chunks/defaults.9aQKnqFk.js';
export { mergeConfig } from 'vite';
export { d as defaultBrowserPort } from './chunks/constants.D_Q9UYh-.js';
export { d as defaultBrowserPort } from './chunks/constants.CPYnjOGj.js';
import 'node:os';
import './chunks/env.D4Lgay0q.js';
import 'std-env';
+18 -13
View File
@@ -1,26 +1,26 @@
import { R as ResolvedCoverageOptions, V as Vitest, C as CoverageMap, a as ReportContext } from './chunks/reporters.d.CWXNI2jG.js';
import { V as Vitest, av as ResolvedCoverageOptions, a$ as CoverageMap, ao as ReportContext, T as TestProject } from './chunks/reporters.d.DtoKVV2s.js';
import { TransformResult } from 'vite';
import { A as AfterSuiteRunMeta } from './chunks/rpc.d.RH3apGEf.js';
import { a as AfterSuiteRunMeta } from './chunks/traces.d.D2T_R8rx.js';
import '@vitest/runner';
import '@vitest/utils';
import 'node:stream';
import './chunks/browser.d.ChKACdzH.js';
import './chunks/traces.d.402V_yFI.js';
import './chunks/worker.d.Dyxm8DEL.js';
import 'vite/module-runner';
import './chunks/config.d.Cy95HiCx.js';
import './chunks/config.d.A1h_Y6Jt.js';
import '@vitest/pretty-format';
import '@vitest/snapshot';
import '@vitest/utils/diff';
import './chunks/browser.d.BcoexmFG.js';
import './chunks/worker.d.ZpHpO4yb.js';
import 'vite/module-runner';
import './chunks/environment.d.CrsxCzP1.js';
import '@vitest/mocker';
import '@vitest/utils/source-map';
import 'vitest/browser';
import './chunks/rpc.d.B_8sPU0w.js';
import '@vitest/expect';
import 'vitest/optional-types.js';
import './chunks/benchmark.d.DAaHLpsq.js';
import '@vitest/runner/utils';
import 'tinybench';
import '@vitest/mocker';
import '@vitest/utils/source-map';
import 'vitest/browser';
import './chunks/coverage.d.BZtK59WP.js';
import '@vitest/snapshot/manager';
import 'node:console';
@@ -51,16 +51,18 @@ interface ResolvedThreshold {
type CoverageFiles = Map<NonNullable<AfterSuiteRunMeta["projectName"]> | symbol, Record<AfterSuiteRunMeta["environment"], {
[TestFilenames: string]: string;
}>>;
declare class BaseCoverageProvider<Options extends ResolvedCoverageOptions<"istanbul" | "v8">> {
declare class BaseCoverageProvider {
ctx: Vitest;
readonly name: "v8" | "istanbul";
version: string;
options: Options;
options: ResolvedCoverageOptions;
globCache: Map<string, boolean>;
autoUpdateMarker: string;
coverageFiles: CoverageFiles;
pendingPromises: Promise<void>[];
coverageFilesDirectory: string;
roots: string[];
changedFiles?: string[];
_initialize(ctx: Vitest): void;
/**
* Check if file matches `coverage.include` but not `coverage.exclude`
@@ -75,8 +77,9 @@ declare class BaseCoverageProvider<Options extends ResolvedCoverageOptions<"ista
code: string;
};
}>;
resolveOptions(): Options;
resolveOptions(): ResolvedCoverageOptions;
clean(clean?: boolean): Promise<void>;
private normalizeCoverageFileError;
onAfterSuiteRun({ coverage, environment, projectName, testFiles }: AfterSuiteRunMeta): void;
readCoverageFiles<CoverageType>({ onFileRead, onFinished, onDebug }: {
/** Callback invoked with a single coverage result */
@@ -88,6 +91,7 @@ declare class BaseCoverageProvider<Options extends ResolvedCoverageOptions<"ista
};
}): Promise<void>;
cleanAfterRun(): Promise<void>;
onTestRunStart(): Promise<void>;
onTestFailure(): Promise<void>;
reportCoverage(coverageMap: unknown, { allTestsRun }: ReportContext): Promise<void>;
reportThresholds(coverageMap: CoverageMap, allTestsRun: boolean | undefined): Promise<void>;
@@ -112,6 +116,7 @@ declare class BaseCoverageProvider<Options extends ResolvedCoverageOptions<"ista
mergeReports(coverageMaps: unknown[]): Promise<void>;
hasTerminalReporter(reporters: ResolvedCoverageOptions["reporter"]): boolean;
toSlices<T>(array: T[], size: number): T[][];
transformFile(url: string, project: TestProject, viteEnvironment: string): Promise<TransformResult | null | undefined>;
createUncoveredFileTransformer(ctx: Vitest): (filename: string) => Promise<TransformResult | null | undefined>;
}
+10 -6
View File
@@ -1,23 +1,27 @@
export { B as BaseCoverageProvider } from './chunks/coverage.AVPTjMgw.js';
export { B as BaseCoverageProvider } from './chunks/coverage.DM_a_rWm.js';
import 'node:fs';
import 'node:module';
import 'node:path';
import 'node:url';
import '@vitest/utils/helpers';
import 'pathe';
import 'picomatch';
import 'tinyglobby';
import 'tinyrainbow';
import './chunks/defaults.BOqNVLsY.js';
import './chunks/defaults.9aQKnqFk.js';
import 'node:os';
import './chunks/env.D4Lgay0q.js';
import 'std-env';
import 'node:crypto';
import 'node:url';
import 'node:module';
import './chunks/index.BCY_7LL2.js';
import 'node:process';
import 'node:fs/promises';
import 'node:assert';
import 'node:v8';
import 'node:util';
import 'vite';
import './chunks/constants.D_Q9UYh-.js';
import './chunks/coverage.D_JHT54q.js';
import './chunks/constants.CPYnjOGj.js';
import './chunks/utils.BS4fH3nR.js';
import './chunks/coverage.CTzCuANN.js';
console.warn("Importing from \"vitest/coverage\" is deprecated since Vitest 4.1. Please use \"vitest/node\" instead.");
+3 -1
View File
@@ -1,3 +1,5 @@
export { e as builtinEnvironments, p as populateGlobal } from './chunks/index.CyBMJtT7.js';
export { e as builtinEnvironments, p as populateGlobal } from './chunks/index.DC7d2Pf8.js';
import 'node:url';
import 'node:console';
console.warn("Importing from \"vitest/environments\" is deprecated since Vitest 4.1. Please use \"vitest/runtime\" instead.");
+163 -31
View File
@@ -1,28 +1,32 @@
import { M as ModuleDefinitionDurationsDiagnostic, U as UntrackedModuleDefinitionDiagnostic, S as SerializedTestSpecification, a as ModuleDefinitionDiagnostic, b as ModuleDefinitionLocation, c as SourceModuleDiagnostic, d as SourceModuleLocations } from './chunks/browser.d.ChKACdzH.js';
export { B as BrowserTesterOptions } from './chunks/browser.d.ChKACdzH.js';
import './chunks/global.d.B15mdLcR.js';
import { M as ModuleDefinitionDurationsDiagnostic, U as UntrackedModuleDefinitionDiagnostic, S as SerializedTestSpecification, a as ModuleDefinitionDiagnostic, b as ModuleDefinitionLocation, c as SourceModuleDiagnostic, d as SourceModuleLocations } from './chunks/browser.d.BcoexmFG.js';
export { B as BrowserTesterOptions } from './chunks/browser.d.BcoexmFG.js';
import './chunks/global.d.DVsSRdQ5.js';
import { File, TestAnnotation, TestArtifact, TaskResultPack, TaskEventPack, Test, TaskPopulated } from '@vitest/runner';
export { CancelReason, ImportDuration, OnTestFailedHandler, OnTestFinishedHandler, RunMode, Task as RunnerTask, TaskBase as RunnerTaskBase, TaskEventPack as RunnerTaskEventPack, TaskResult as RunnerTaskResult, TaskResultPack as RunnerTaskResultPack, Test as RunnerTestCase, File as RunnerTestFile, Suite as RunnerTestSuite, SuiteAPI, SuiteCollector, SuiteFactory, TaskCustomOptions, TaskMeta, TaskState, TestAPI, TestAnnotation, TestAnnotationArtifact, TestArtifact, TestArtifactBase, TestArtifactLocation, TestArtifactRegistry, TestAttachment, TestContext, TestFunction, TestOptions, afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, recordArtifact, suite, test } from '@vitest/runner';
export { CancelReason, ImportDuration, OnTestFailedHandler, OnTestFinishedHandler, RunMode, Task as RunnerTask, TaskBase as RunnerTaskBase, TaskEventPack as RunnerTaskEventPack, TaskResult as RunnerTaskResult, TaskResultPack as RunnerTaskResultPack, Test as RunnerTestCase, File as RunnerTestFile, Suite as RunnerTestSuite, SuiteAPI, SuiteCollector, SuiteFactory, SuiteOptions, TaskCustomOptions, TaskMeta, TaskState, TestAPI, TestAnnotation, TestAnnotationArtifact, TestArtifact, TestArtifactBase, TestArtifactLocation, TestArtifactRegistry, TestAttachment, TestContext, TestFunction, TestOptions, VitestRunnerConfig as TestRunnerConfig, TestTags, VitestRunner as VitestTestRunner, afterAll, afterEach, aroundAll, aroundEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, recordArtifact, suite, test } from '@vitest/runner';
import { Awaitable } from '@vitest/utils';
export { ParsedStack, SerializedError, TestError } from '@vitest/utils';
import { b as BirpcReturn } from './chunks/worker.d.Dyxm8DEL.js';
export { C as ContextRPC, c as ContextTestEnvironment, T as TestExecutionMethod, W as WorkerGlobalState } from './chunks/worker.d.Dyxm8DEL.js';
import { S as SerializedConfig, F as FakeTimerInstallOpts, R as RuntimeOptions } from './chunks/config.d.Cy95HiCx.js';
export { b as RuntimeConfig, a as SerializedCoverageConfig } from './chunks/config.d.Cy95HiCx.js';
import { U as UserConsoleLog, L as LabelColor, M as ModuleGraphData, P as ProvidedContext } from './chunks/rpc.d.RH3apGEf.js';
export { A as AfterSuiteRunMeta, a as RunnerRPC, R as RuntimeRPC } from './chunks/rpc.d.RH3apGEf.js';
import { ExpectStatic } from '@vitest/expect';
export { Assertion, AsymmetricMatchersContaining, DeeplyAllowMatchers, ExpectPollOptions, ExpectStatic, JestAssertion, Matchers, chai } from '@vitest/expect';
import { b as BirpcReturn } from './chunks/worker.d.ZpHpO4yb.js';
export { C as ContextRPC, c as ContextTestEnvironment, T as TestExecutionMethod, W as WorkerGlobalState } from './chunks/worker.d.ZpHpO4yb.js';
import { b as SerializedRootConfig, F as FakeTimerInstallOpts, R as RuntimeOptions } from './chunks/config.d.A1h_Y6Jt.js';
export { c as RuntimeConfig, S as SerializedConfig, a as SerializedCoverageConfig } from './chunks/config.d.A1h_Y6Jt.js';
import { U as UserConsoleLog, L as LabelColor, M as ModuleGraphData, P as ProvidedContext } from './chunks/traces.d.D2T_R8rx.js';
export { a as AfterSuiteRunMeta } from './chunks/traces.d.D2T_R8rx.js';
import { ExpectStatic, MatcherState, SyncExpectationResult, AsyncExpectationResult, ExpectationResult } from '@vitest/expect';
export { Assertion, AsymmetricMatchersContaining, DeeplyAllowMatchers, ExpectPollOptions, ExpectStatic, JestAssertion, RawMatcherFn as Matcher, ExpectationResult as MatcherResult, MatcherState, Matchers, chai } from '@vitest/expect';
import { DomainSnapshotAdapter } from '@vitest/snapshot';
export { SnapshotData, SnapshotMatchOptions, SnapshotResult, SnapshotSerializer, SnapshotStateOptions, SnapshotSummary, SnapshotUpdateState, UncheckedSnapshot } from '@vitest/snapshot';
import { spyOn, fn, MaybeMockedDeep, MaybeMocked, MaybePartiallyMocked, MaybePartiallyMockedDeep, MockInstance } from '@vitest/spy';
export { Mock, MockContext, MockInstance, MockResult, MockResultIncomplete, MockResultReturn, MockResultThrow, MockSettledResult, MockSettledResultFulfilled, MockSettledResultIncomplete, MockSettledResultRejected, Mocked, MockedClass, MockedFunction, MockedObject } from '@vitest/spy';
export { b as bench } from './chunks/suite.d.BJWk38HB.js';
import { Disposable } from 'vitest/optional-runtime-types.js';
import { ModuleMockFactoryWithHelper, ModuleMockOptions } from '@vitest/mocker';
export { b as bench } from './chunks/suite.d.udJtyAgw.js';
export { V as EvaluatedModules } from './chunks/evaluatedModules.d.BxJ5omdx.js';
export { NodeBenchmarkRunner as BenchmarkRunner, VitestTestRunner as TestRunner } from './runners.js';
export { a as BenchFunction, b as Benchmark, c as BenchmarkAPI, B as BenchmarkResult } from './chunks/benchmark.d.DAaHLpsq.js';
export { ExpectTypeOf, expectTypeOf } from 'expect-type';
export { SnapshotData, SnapshotMatchOptions, SnapshotResult, SnapshotSerializer, SnapshotStateOptions, SnapshotSummary, SnapshotUpdateState, UncheckedSnapshot } from '@vitest/snapshot';
export { a as RunnerRPC, R as RuntimeRPC } from './chunks/rpc.d.B_8sPU0w.js';
export { DiffOptions } from '@vitest/utils/diff';
export { Bench as BenchFactory, Options as BenchOptions, Task as BenchTask, TaskResult as BenchTaskResult } from 'tinybench';
import './chunks/traces.d.402V_yFI.js';
import '@vitest/pretty-format';
import 'vite/module-runner';
import './chunks/environment.d.CrsxCzP1.js';
@@ -55,11 +59,13 @@ interface TransformResultWithSource {
untrackedModules?: UntrackedModuleDefinitionDiagnostic[];
}
interface WebSocketHandlers {
onTaskUpdate: (packs: TaskResultPack[], events: TaskEventPack[]) => void;
getFiles: () => File[];
getTestFiles: () => Promise<SerializedTestSpecification[]>;
getPaths: () => string[];
getConfig: () => SerializedConfig;
getConfig: () => SerializedRootConfig;
/**
* @deprecated Use `getConfig().projects` instead.
*/
getResolvedProjectLabels: () => {
name: string;
color?: LabelColor;
@@ -98,11 +104,93 @@ declare const should: () => Chai.Should;
*/
declare function inject<T extends keyof ProvidedContext & string>(key: T): ProvidedContext[T];
type Promisable<T> = T | Promise<T>;
type MockFactoryWithHelper<M = unknown> = (importOriginal: <T extends M = M>() => Promise<T>) => Promisable<Partial<M>>;
interface MockOptions {
spy?: boolean;
}
/**
* Composable snapshot matcher helpers for building custom snapshot matchers
* with `expect.extend`.
*
* @experimental
* @see https://vitest.dev/guide/snapshot.html#custom-snapshot-matchers
*/
declare const Snapshots: {
/**
* Composable for building custom snapshot matchers via `expect.extend`.
* Call with `this` bound to the matcher state. Returns `{ pass, message }`
* compatible with the custom matcher return contract.
*
* @example
* ```ts
* import { Snapshots } from 'vitest/runtime'
*
* expect.extend({
* toMatchTrimmedSnapshot(received: string) {
* return Snapshots.toMatchSnapshot.call(this, received.slice(0, 10))
* },
* })
* ```
*
* @experimental
* @see https://vitest.dev/guide/snapshot.html#custom-snapshot-matchers
*/
toMatchSnapshot(this: MatcherState, received: unknown, propertiesOrHint?: object | string, hint?: string): SyncExpectationResult;
/**
* Composable for building custom inline snapshot matchers via `expect.extend`.
* Call with `this` bound to the matcher state. Returns `{ pass, message }`
* compatible with the custom matcher return contract.
*
* @example
* ```ts
* import { Snapshots } from 'vitest/runtime'
*
* expect.extend({
* toMatchTrimmedInlineSnapshot(received: string, inlineSnapshot?: string) {
* return Snapshots.toMatchInlineSnapshot.call(this, received.slice(0, 10), inlineSnapshot)
* },
* })
* ```
*
* @experimental
* @see https://vitest.dev/guide/snapshot.html#custom-snapshot-matchers
*/
toMatchInlineSnapshot(this: MatcherState, received: unknown, propertiesOrInlineSnapshot?: object | string, inlineSnapshotOrHint?: string, hint?: string): SyncExpectationResult;
/**
* Composable for building custom file snapshot matchers via `expect.extend`.
* Call with `this` bound to the matcher state. Returns a `Promise<{ pass, message }>`
* compatible with the custom matcher return contract.
*
* @example
* ```ts
* import { Snapshots } from 'vitest/runtime'
*
* expect.extend({
* async toMatchTrimmedFileSnapshot(received: string, file: string) {
* return Snapshots.toMatchFileSnapshot.call(this, received.slice(0, 10), file)
* },
* })
* ```
*
* @experimental
* @see https://vitest.dev/guide/snapshot.html#custom-snapshot-matchers
*/
toMatchFileSnapshot(this: MatcherState, received: unknown, filepath: string, hint?: string): AsyncExpectationResult;
/**
* Composable for building custom domain-based snapshot matchers via `expect.extend`.
*
* Call this from a matcher and pass the domain adapter that defines capture,
* rendering, parsing, and semantic matching behavior.
*
* @experimental
*/
toMatchDomainSnapshot(this: MatcherState, domain: DomainSnapshotAdapter<any, any>, received: unknown): ExpectationResult;
/**
* Composable for building custom domain-based inline snapshot matchers via `expect.extend`.
*
* Call this from a matcher and pass the domain adapter that defines capture,
* rendering, parsing, and semantic matching behavior.
*
* @experimental
*/
toMatchDomainInlineSnapshot(this: MatcherState, domain: DomainSnapshotAdapter<any, any>, received: unknown, inlineSnapshot?: string): ExpectationResult;
};
type WaitForCallback<T> = () => T | Promise<T>;
interface WaitForOptions {
@@ -149,12 +237,12 @@ interface VitestUtils {
runOnlyPendingTimersAsync: () => Promise<VitestUtils>;
/**
* This method will invoke every initiated timer until the timer queue is empty. It means that every timer called during `runAllTimers` will be fired.
* If you have an infinite interval, it will throw after 10,000 tries (can be configured with [`fakeTimers.loopLimit`](https://vitest.dev/config/#faketimers-looplimit)).
* If you have an infinite interval, it will throw after 10,000 tries (can be configured with [`fakeTimers.loopLimit`](https://vitest.dev/config/faketimers#faketimers-looplimit)).
*/
runAllTimers: () => VitestUtils;
/**
* This method will asynchronously invoke every initiated timer until the timer queue is empty. It means that every timer called during `runAllTimersAsync` will be fired even asynchronous timers.
* If you have an infinite interval, it will throw after 10 000 tries (can be configured with [`fakeTimers.loopLimit`](https://vitest.dev/config/#faketimers-looplimit)).
* If you have an infinite interval, it will throw after 10 000 tries (can be configured with [`fakeTimers.loopLimit`](https://vitest.dev/config/faketimers#faketimers-looplimit)).
*/
runAllTimersAsync: () => Promise<VitestUtils>;
/**
@@ -203,6 +291,15 @@ interface VitestUtils {
*/
clearAllTimers: () => VitestUtils;
/**
* Controls how fake timers are advanced.
* @param mode The mode to use for advancing timers.
* - `manual`: The default behavior. Timers will only advance when you call one of `vi.advanceTimers...()` methods.
* - `nextTimerAsync`: Timers will be advanced automatically to the next available timer after each macrotask.
* - `interval`: Timers are advanced automatically by a specified interval.
* @param interval The interval in milliseconds to use when `mode` is `'interval'`.
*/
setTimerTickMode: ((mode: "manual" | "nextTimerAsync") => VitestUtils) & ((mode: "interval", interval?: number) => VitestUtils);
/**
* Creates a spy on a method or getter/setter of an object similar to [`vi.fn()`](https://vitest.dev/api/vi#vi-fn). It returns a [mock function](https://vitest.dev/api/mock).
* @example
* ```ts
@@ -261,6 +358,39 @@ interface VitestUtils {
*/
waitFor: typeof waitFor;
/**
* Wraps a function to create an assertion helper. When an assertion fails inside the helper,
* the error stack trace will point to where the helper was called, not inside the helper itself.
* Works with both synchronous and asynchronous functions, and supports `expect.soft()`.
*
* @example
* ```ts
* const myEqual = vi.defineHelper((x, y) => {
* expect(x).toEqual(y)
* })
*
* test('example', () => {
* myEqual('left', 'right') // Error points to this line
* })
* ```
* Example output:
* ```
* FAIL example.test.ts > example
* AssertionError: expected 'left' to deeply equal 'right'
*
* Expected: "right"
* Received: "left"
*
* ❯ example.test.ts:6:3
* 4| test('example', () => {
* 5| myEqual('left', 'right')
* | ^
* 6| })
* ```
* @param fn The assertion function to wrap
* @returns A wrapped function with the same signature
*/
defineHelper: <F extends (...args: any) => any>(fn: F) => F;
/**
* This is similar to [`vi.waitFor`](https://vitest.dev/api/vi#vi-waitfor), but if the callback throws any errors, execution is immediately interrupted and an error message is received.
*
* If the callback returns a falsy value, the next check will continue until a truthy value is returned. This is useful when you need to wait for something to exist before taking the next step.
@@ -296,8 +426,8 @@ interface VitestUtils {
* @param path Path to the module. Can be aliased, if your Vitest config supports it
* @param factory Mocked module factory. The result of this function will be an exports object
*/
mock(path: string, factory?: MockFactoryWithHelper | MockOptions): void;
mock<T>(module: Promise<T>, factory?: MockFactoryWithHelper<T> | MockOptions): void;
mock(path: string, factory?: ModuleMockFactoryWithHelper | ModuleMockOptions): void;
mock<T>(module: Promise<T>, factory?: ModuleMockFactoryWithHelper<T> | ModuleMockOptions): void;
/**
* Removes module from mocked registry. All calls to import will return the original module even if it was mocked before.
*
@@ -314,9 +444,11 @@ interface VitestUtils {
* Mocking algorithm is described in [documentation](https://vitest.dev/guide/mocking/modules).
* @param path Path to the module. Can be aliased, if your Vitest config supports it
* @param factory Mocked module factory. The result of this function will be an exports object
*
* @returns A disposable object that calls {@link doUnmock()} when disposed
*/
doMock(path: string, factory?: MockFactoryWithHelper | MockOptions): void;
doMock<T>(module: Promise<T>, factory?: MockFactoryWithHelper<T> | MockOptions): void;
doMock(path: string, factory?: ModuleMockFactoryWithHelper | ModuleMockOptions): Disposable;
doMock<T>(module: Promise<T>, factory?: ModuleMockFactoryWithHelper<T> | ModuleMockOptions): Disposable;
/**
* Removes module from mocked registry. All subsequent calls to import will return original module.
*
@@ -387,12 +519,12 @@ interface VitestUtils {
* @param value - The object to be mocked
* @returns A deeply mocked version of the input object
*/
mockObject: <T>(value: T, options?: MockOptions) => MaybeMockedDeep<T>;
mockObject: <T>(value: T, options?: ModuleMockOptions) => MaybeMockedDeep<T>;
/**
* Type helper for TypeScript. Just returns the object that was passed.
*
* When `partial` is `true` it will expect a `Partial<T>` as a return value. By default, this will only make TypeScript believe that
* the first level values are mocked. You can pass down `{ deep: true }` as a second argument to tell TypeScript that the whole object is mocked, if it actually is.
* the first level values are mocked. You can pass down `{ partial: true, deep: true }` to make nested objects also partial recursively.
* @example
* ```ts
* import example from './example.js'
@@ -506,5 +638,5 @@ declare namespace Experimental {
export { ModuleDefinitionDiagnostic, ModuleDefinitionDurationsDiagnostic, ModuleDefinitionLocation, SourceModuleDiagnostic, SourceModuleLocations, UntrackedModuleDefinitionDiagnostic };
}
export { Experimental, LabelColor, ModuleGraphData, ProvidedContext, SerializedConfig, SerializedTestSpecification, UserConsoleLog, assert, assertType, createExpect, globalExpect as expect, inject, should, vi, vitest };
export { Experimental, LabelColor, ModuleGraphData, ProvidedContext, SerializedRootConfig, SerializedTestSpecification, Snapshots, UserConsoleLog, assert, assertType, createExpect, globalExpect as expect, inject, should, vi, vitest };
export type { AssertType, BrowserUI, ExternalResult, TransformResultWithSource, VitestUtils, WebSocketEvents, WebSocketHandlers, WebSocketRPC };
+12 -11
View File
@@ -1,20 +1,21 @@
export { b as assert, c as createExpect, g as expect, i as inject, s as should, v as vi, d as vitest } from './chunks/vi.2VT5v0um.js';
export { b as bench } from './chunks/benchmark.B3N2zMcH.js';
export { N as BenchmarkRunner, S as Snapshots, T as TestRunner, a as assert, c as createExpect, g as expect, i as inject, s as should, v as vi, b as vitest } from './chunks/test.DNmyFkvJ.js';
export { b as bench } from './chunks/benchmark.CX_oY03V.js';
export { V as EvaluatedModules } from './chunks/evaluatedModules.Dg1zASAC.js';
export { a as assertType } from './chunks/index.Z5E_ObnR.js';
export { a as assertType } from './chunks/index.DdgEv5B1.js';
export { expectTypeOf } from 'expect-type';
export { afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, recordArtifact, suite, test } from '@vitest/runner';
export { afterAll, afterEach, aroundAll, aroundEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, recordArtifact, suite, test } from '@vitest/runner';
export { chai } from '@vitest/expect';
import './chunks/utils.DvEY5TfP.js';
import '@vitest/utils/timers';
import '@vitest/runner/utils';
import '@vitest/snapshot';
import '@vitest/utils/error';
import '@vitest/utils/helpers';
import '@vitest/utils/timers';
import './chunks/utils.BX5Fg8C4.js';
import '@vitest/runner/utils';
import '@vitest/utils/error';
import 'pathe';
import '@vitest/spy';
import '@vitest/utils/offset';
import '@vitest/utils/source-map';
import './chunks/_commonjsHelpers.D26ty3Ew.js';
import './chunks/date.Bq6ZW5rf.js';
import 'pathe';
import './chunks/rpc.MzXet3jl.js';
import './chunks/index.Chj8NDwU.js';
import '@vitest/snapshot';
import 'vite/module-runner';
-1
View File
@@ -1 +0,0 @@
export * from '@vitest/mocker';
-1
View File
@@ -1 +0,0 @@
export * from '@vitest/mocker';
+12 -2
View File
@@ -1,10 +1,10 @@
import { ModuleEvaluator, ModuleRunnerImportMeta, ModuleRunnerContext, EvaluatedModuleNode } from 'vite/module-runner';
import { V as VitestEvaluatedModules } from './chunks/evaluatedModules.d.BxJ5omdx.js';
import vm from 'node:vm';
import { R as RuntimeRPC } from './chunks/rpc.d.RH3apGEf.js';
import { R as RuntimeRPC } from './chunks/rpc.d.B_8sPU0w.js';
import '@vitest/runner';
import '@vitest/snapshot';
import './chunks/traces.d.402V_yFI.js';
import './chunks/traces.d.D2T_R8rx.js';
type ModuleExecutionInfo = Map<string, ModuleExecutionInfoEntry>;
interface ModuleExecutionInfoEntry {
@@ -82,6 +82,15 @@ declare module "vite/module-runner" {
}
}
declare module "vite/module-runner" {
interface EvaluatedModuleNode {
/**
* @internal
*/
mockedExports?: Record<string, any>;
}
}
interface VitestVmOptions {
context: vm.Context;
externalModulesExecutor: ExternalModulesExecutor;
@@ -110,6 +119,7 @@ declare class VitestModuleEvaluator implements ModuleEvaluator {
private convertIdToImportUrl;
runExternalModule(id: string): Promise<any>;
runInlinedModule(context: ModuleRunnerContext, code: string, module: Readonly<EvaluatedModuleNode>): Promise<any>;
private _createCJSGlobals;
private _runInlinedModule;
private createRequire;
private shouldInterop;
+45 -28
View File
@@ -2,7 +2,7 @@ import { isBuiltin, createRequire } from 'node:module';
import { pathToFileURL, fileURLToPath } from 'node:url';
import vm from 'node:vm';
import { ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey } from 'vite/module-runner';
import { T as Traces } from './chunks/traces.CCmnQaNT.js';
import { T as Traces } from './chunks/traces.DT5aQ62U.js';
const performanceNow = performance.now.bind(performance);
class ModuleDebug {
@@ -60,7 +60,7 @@ class VitestModuleEvaluator {
convertIdToImportUrl(id) {
// TODO: vitest returns paths for external modules, but Vite returns file://
// REMOVE WHEN VITE 6 SUPPORT IS OVER
// unfortunetly, there is a bug in Vite where ID is resolved incorrectly, so we can't return files until the fix is merged
// unfortunately, there is a bug in Vite where ID is resolved incorrectly, so we can't return files until the fix is merged
// https://github.com/vitejs/vite/pull/20449
if (!isWindows || isBuiltin(id) || /^(?:node:|data:|http:|https:|file:)/.test(id)) return id;
const [filepath, query] = id.split("?");
@@ -106,8 +106,7 @@ class VitestModuleEvaluator {
async runInlinedModule(context, code, module) {
return this._otel.$("vitest.module.inline", (span) => this._runInlinedModule(context, code, module, span));
}
async _runInlinedModule(context, code, module, span) {
context.__vite_ssr_import_meta__.env = this.env;
_createCJSGlobals(context, module, span) {
const { Reflect, Proxy, Object } = this.primitives;
const exportsObject = context[ssrModuleExportsKey];
const SYMBOL_NOT_DEFINED = Symbol("not defined");
@@ -143,46 +142,57 @@ class VitestModuleEvaluator {
return true;
}
});
const moduleProxy = {
set exports(value) {
span.addEvent("`module.exports` is assigned directly, copying all properties to `exports`");
exportAll(cjsExports, value);
exportsObject.default = value;
moduleExports = value;
return {
exports: cjsExports,
module: {
set exports(value) {
span.addEvent("`module.exports` is assigned directly, copying all properties to `exports`");
exportAll(cjsExports, value);
exportsObject.default = value;
moduleExports = value;
},
get exports() {
return cjsExports;
}
},
get exports() {
return cjsExports;
}
require: this.createRequire(context[ssrImportMetaKey].url),
__filename: context[ssrImportMetaKey].filename,
__dirname: context[ssrImportMetaKey].dirname
};
}
async _runInlinedModule(context, code, module, span) {
const meta = context[ssrImportMetaKey];
meta.env = this.env;
if (this.options.getCurrentTestFilepath?.() === module.file) {
const globalNamespace = this.vm?.context || globalThis;
Object.defineProperty(meta, "vitest", { get: () => globalNamespace.__vitest_index__ });
}
const filename = meta.filename;
const dirname = meta.dirname;
span.setAttributes({ "code.file.path": filename });
const require = this.createRequire(meta.url);
span.setAttribute("code.file.path", meta.filename);
const argumentsList = [
ssrModuleExportsKey,
ssrImportMetaKey,
ssrImportKey,
ssrDynamicImportKey,
ssrExportAllKey,
"__vite_ssr_exportName__",
"__vite_ssr_exportName__"
];
const cjsGlobals = this._createCJSGlobals(context, module, span);
argumentsList.push(
// TODO@discuss deprecate in Vitest 5, remove in Vitest 6(?)
// backwards compat for vite-node
"__filename",
"__dirname",
"module",
"exports",
"require"
];
);
if (this.compiledFunctionArgumentsNames) argumentsList.push(...this.compiledFunctionArgumentsNames);
span.setAttribute("vitest.module.arguments", argumentsList);
// add 'use strict' since ESM enables it by default
const codeDefinition = `'use strict';async (${argumentsList.join(",")})=>{{`;
const wrappedCode = `${codeDefinition}${code}\n}}`;
const options = {
filename: module.id,
filename: module.id.startsWith("mock:") ? module.id.slice(5) : module.id,
lineOffset: 0,
columnOffset: -codeDefinition.length
};
@@ -200,16 +210,16 @@ class VitestModuleEvaluator {
context[ssrDynamicImportKey],
context[ssrExportAllKey],
// vite 7 support, remove when vite 7+ is supported
context.__vite_ssr_exportName__ || ((name, getter) => Object.defineProperty(exportsObject, name, {
context.__vite_ssr_exportName__ || ((name, getter) => Object.defineProperty(context[ssrModuleExportsKey], name, {
enumerable: true,
configurable: true,
get: getter
})),
filename,
dirname,
moduleProxy,
cjsExports,
require,
cjsGlobals.__filename,
cjsGlobals.__dirname,
cjsGlobals.module,
cjsGlobals.exports,
cjsGlobals.require,
...this.compiledFunctionArgumentsValues
);
} finally {
@@ -218,8 +228,15 @@ class VitestModuleEvaluator {
this.options.moduleExecutionInfo?.set(options.filename, finishModuleExecutionInfo());
}
}
createRequire(filename) {
return this.vm ? this.vm.externalModulesExecutor.createRequire(filename) : createRequire(filename);
createRequire(url) {
if (url.startsWith("data:")) {
const _require = (id) => {
throw new SyntaxError(`require() is not supported in virtual modules. Trying to call require("${id}") in ${url}`);
};
_require.resolve = _require;
return _require;
}
return this.vm ? this.vm.externalModulesExecutor.createRequire(url) : createRequire(url);
}
shouldInterop(path, mod) {
if (this.options.interopDefault === false) return false;
-17
View File
@@ -1,17 +0,0 @@
export { VitestModuleEvaluator } from './module-evaluator.js';
export { a as VITEST_VM_CONTEXT_SYMBOL, V as VitestModuleRunner, s as startVitestModuleRunner } from './chunks/startModuleRunner.DEj0jb3e.js';
export { g as getWorkerState } from './chunks/utils.DvEY5TfP.js';
import 'node:module';
import 'node:url';
import 'node:vm';
import 'vite/module-runner';
import './chunks/traces.CCmnQaNT.js';
import 'node:fs';
import '@vitest/utils/helpers';
import './chunks/modules.BJuCwlRJ.js';
import 'pathe';
import './path.js';
import 'node:path';
import '@vitest/utils/serialize';
import '@vitest/mocker';
import '@vitest/utils/timers';
+29 -15
View File
@@ -3,25 +3,24 @@ import { InlineConfig, UserConfig as UserConfig$1, Plugin, ResolvedConfig as Res
export { vite as Vite };
export { esbuildVersion, isCSSRequest, isFileLoadingAllowed, parseAst, parseAstAsync, rollupVersion, version as viteVersion } from 'vite';
import { IncomingMessage } from 'node:http';
import { h as ResolvedConfig, f as UserConfig, i as VitestRunMode, j as VitestOptions, V as Vitest, A as ApiConfig, k as TestSpecification, T as TestProject, P as PoolWorker, l as PoolOptions, m as WorkerRequest, n as TestSequencer, L as Logger } from './chunks/reporters.d.CWXNI2jG.js';
export { at as BaseCoverageOptions, Y as BenchmarkUserOptions, Z as BrowserBuiltinProvider, $ as BrowserCommand, a0 as BrowserCommandContext, a1 as BrowserConfigOptions, a2 as BrowserInstanceOption, a3 as BrowserModuleMocker, a4 as BrowserOrchestrator, a5 as BrowserProvider, a6 as BrowserProviderOption, a7 as BrowserScript, a8 as BrowserServerFactory, a9 as BrowserServerOptions, aa as BrowserServerState, ab as BrowserServerStateSession, ai as BuiltinEnvironment, ac as CDPSession, aj as CSSModuleScopeStrategy, au as CoverageIstanbulOptions, av as CoverageOptions, aw as CoverageProvider, ax as CoverageProviderModule, ay as CoverageReporter, c as CoverageV8Options, az as CustomProviderOptions, ak as DepsOptimizationOptions, al as EnvironmentOptions, H as HTMLOptions, I as InlineConfig, t as JUnitOptions, J as JsonOptions, M as ModuleDiagnostic, O as OnServerRestartHandler, o as OnTestsRerunHandler, ad as ParentProjectBrowser, am as Pool, q as PoolRunnerInitializer, r as PoolTask, ae as ProjectBrowser, an as ProjectConfig, a as ReportContext, aB as ReportedHookContext, aC as Reporter, ap as ResolveSnapshotPathHandler, aq as ResolveSnapshotPathHandlerContext, af as ResolvedBrowserOptions, R as ResolvedCoverageOptions, ao as ResolvedProjectConfig, S as SerializedTestProject, u as TaskOptions, v as TestCase, w as TestCollection, x as TestDiagnostic, y as TestModule, z as TestModuleState, B as TestResult, D as TestResultFailed, E as TestResultPassed, F as TestResultSkipped, aD as TestRunEndReason, aA as TestRunResult, X as TestSequencerConstructor, G as TestState, K as TestSuite, N as TestSuiteState, ag as ToMatchScreenshotComparators, ah as ToMatchScreenshotOptions, ar as TypecheckConfig, U as UserWorkspaceConfig, as as VitestEnvironment, p as VitestPackageInstaller, W as WatcherTriggerPattern, s as WorkerResponse, _ as _BrowserNames, Q as experimental_getRunnerTask } from './chunks/reporters.d.CWXNI2jG.js';
export { C as CacheKeyIdGenerator, a as CacheKeyIdGeneratorContext, V as VitestPluginContext } from './chunks/plugin.d.CtqpEehP.js';
import { R as ResolvedConfig, e as UserConfig, f as VitestRunMode, g as VitestOptions, V as Vitest, A as ApiConfig, L as Logger, h as TestSpecification, T as TestProject, P as PoolWorker, i as PoolOptions, j as WorkerRequest, k as TestSequencer } from './chunks/reporters.d.DtoKVV2s.js';
export { M as AgentReporter, B as BaseCoverageOptions, l as BaseReporter, m as BenchmarkBuiltinReporters, n as BenchmarkReporter, o as BenchmarkReportsMap, p as BenchmarkUserOptions, q as BrowserBuiltinProvider, r as BrowserCommand, s as BrowserCommandContext, t as BrowserConfigOptions, u as BrowserInstanceOption, v as BrowserModuleMocker, w as BrowserOrchestrator, x as BrowserProvider, y as BrowserProviderOption, z as BrowserScript, D as BrowserServerFactory, E as BrowserServerOptions, G as BrowserServerState, H as BrowserServerStateSession, J as BuiltinEnvironment, K as BuiltinReporterOptions, N as BuiltinReporters, O as CSSModuleScopeStrategy, Q as CoverageInstrumenter, S as CoverageIstanbulOptions, C as CoverageOptions, X as CoverageProvider, Y as CoverageProviderModule, Z as CoverageReporter, _ as CoverageV8Options, $ as CustomProviderOptions, a0 as DefaultReporter, a1 as DepsOptimizationOptions, a2 as DotReporter, a3 as EnvironmentOptions, a4 as GithubActionsReporter, a5 as HTMLOptions, a6 as HangingProcessReporter, I as InlineConfig, a7 as InstrumenterOptions, a8 as JUnitOptions, a9 as JUnitReporter, aa as JsonAssertionResult, ab as JsonOptions, ac as JsonReporter, ad as JsonTestResult, ae as JsonTestResults, M as MinimalReporter, af as ModuleDiagnostic, ag as OnServerRestartHandler, ah as OnTestsRerunHandler, ai as ParentProjectBrowser, aj as Pool, ak as PoolRunnerInitializer, al as PoolTask, am as ProjectBrowser, an as ProjectConfig, ao as ReportContext, ap as ReportedHookContext, aq as Reporter, ar as ReportersMap, as as ResolveSnapshotPathHandler, at as ResolveSnapshotPathHandlerContext, au as ResolvedBrowserOptions, av as ResolvedCoverageOptions, aw as ResolvedProjectConfig, ax as SerializedTestProject, ay as TapFlatReporter, az as TapReporter, aA as TaskOptions, aB as TestCase, aC as TestCollection, aD as TestDiagnostic, aE as TestModule, aF as TestModuleState, aG as TestResult, aH as TestResultFailed, aI as TestResultPassed, aJ as TestResultSkipped, aK as TestRunEndReason, aL as TestRunResult, aM as TestSequencerConstructor, aN as TestSpecificationOptions, aO as TestState, aP as TestSuite, aQ as TestSuiteState, aR as ToMatchScreenshotComparators, aS as ToMatchScreenshotOptions, aT as TypecheckConfig, U as UserWorkspaceConfig, aU as VerboseBenchmarkReporter, aV as VerboseReporter, aW as VitestEnvironment, aX as VitestPackageInstaller, W as WatcherTriggerPattern, aY as WorkerResponse, aZ as _BrowserNames, a_ as experimental_getRunnerTask } from './chunks/reporters.d.DtoKVV2s.js';
export { C as CacheKeyIdGenerator, a as CacheKeyIdGeneratorContext, V as VitestPluginContext } from './chunks/plugin.d.DwFIiJ7i.js';
export { BaseCoverageProvider } from './coverage.js';
import { Awaitable } from '@vitest/utils';
export { SerializedError } from '@vitest/utils';
import { R as RuntimeRPC } from './chunks/rpc.d.RH3apGEf.js';
import { R as RuntimeRPC } from './chunks/rpc.d.B_8sPU0w.js';
import { Writable } from 'node:stream';
import { C as ContextRPC } from './chunks/worker.d.Dyxm8DEL.js';
export { T as TestExecutionType } from './chunks/worker.d.Dyxm8DEL.js';
import { C as ContextRPC } from './chunks/worker.d.ZpHpO4yb.js';
export { T as TestExecutionType } from './chunks/worker.d.ZpHpO4yb.js';
import { Debugger } from 'obug';
import './chunks/global.d.B15mdLcR.js';
import './chunks/global.d.DVsSRdQ5.js';
export { Task as RunnerTask, TaskResult as RunnerTaskResult, TaskResultPack as RunnerTaskResultPack, Test as RunnerTestCase, File as RunnerTestFile, Suite as RunnerTestSuite, SequenceHooks, SequenceSetupFiles } from '@vitest/runner';
export { b as RuntimeConfig } from './chunks/config.d.Cy95HiCx.js';
export { c as RuntimeConfig } from './chunks/config.d.A1h_Y6Jt.js';
export { generateFileHash } from '@vitest/runner/utils';
import './chunks/browser.d.ChKACdzH.js';
import './chunks/traces.d.402V_yFI.js';
import '@vitest/mocker';
import '@vitest/utils/source-map';
import 'vitest/browser';
export { CDPSession } from 'vitest/browser';
import './chunks/traces.d.D2T_R8rx.js';
import './chunks/browser.d.BcoexmFG.js';
import '@vitest/pretty-format';
import '@vitest/snapshot';
import '@vitest/utils/diff';
@@ -29,6 +28,8 @@ import '@vitest/expect';
import 'vitest/optional-types.js';
import './chunks/benchmark.d.DAaHLpsq.js';
import 'tinybench';
import '@vitest/mocker';
import '@vitest/utils/source-map';
import './chunks/coverage.d.BZtK59WP.js';
import '@vitest/snapshot/manager';
import 'node:console';
@@ -82,7 +83,17 @@ interface CliOptions extends UserConfig {
*/
filesOnly?: boolean;
/**
* Override vite config's configLoader from cli.
* Parse files statically instead of running them to collect tests
* @experimental
*/
staticParse?: boolean;
/**
* How many tests to process at the same time
* @experimental
*/
staticParseConcurrency?: number;
/**
* Override vite config's configLoader from CLI.
* Use `bundle` to bundle the config with esbuild or `runner` (experimental) to process it on the fly (default: `bundle`).
* This is only available with **vite version 6.1.0** and above.
* @experimental
@@ -106,7 +117,10 @@ declare function parseCLI(argv: string | string[], config?: CliParseOptions): {
options: CliOptions;
};
declare function resolveApiServerConfig<Options extends ApiConfig & Omit<UserConfig, "expect">>(options: Options, defaultPort: number): ApiConfig | undefined;
/**
* @deprecated Internal function
*/
declare function resolveApiServerConfig<Options extends ApiConfig & Omit<UserConfig, "expect">>(options: Options, defaultPort: number, parentApi?: ApiConfig, logger?: Logger): ApiConfig | undefined;
declare function createVitest(mode: VitestRunMode, options: CliOptions, viteOverrides?: UserConfig$1, vitestOptions?: VitestOptions): Promise<Vitest>;
+43 -41
View File
@@ -1,37 +1,53 @@
import * as vite from 'vite';
import { resolveConfig as resolveConfig$1, mergeConfig } from 'vite';
export { esbuildVersion, isCSSRequest, isFileLoadingAllowed, parseAst, parseAstAsync, rollupVersion, version as viteVersion } from 'vite';
import { V as Vitest, a as VitestPlugin } from './chunks/cli-api.B7PN_QUv.js';
export { f as ForksPoolWorker, G as GitNotFoundError, F as TestsNotFoundError, T as ThreadsPoolWorker, h as TypecheckPoolWorker, b as VitestPackageInstaller, j as VmForksPoolWorker, k as VmThreadsPoolWorker, p as createDebugger, d as createMethodsRPC, o as createViteLogger, c as createVitest, e as escapeTestName, l as experimental_getRunnerTask, g as getFilePoolName, n as isFileServingAllowed, i as isValidApiRequest, m as registerConsoleShortcuts, r as resolveFsAllow, s as startVitest } from './chunks/cli-api.B7PN_QUv.js';
export { p as parseCLI } from './chunks/cac.DVeoLl0M.js';
import { r as resolveConfig$2 } from './chunks/coverage.AVPTjMgw.js';
export { b as BaseSequencer, a as resolveApiServerConfig } from './chunks/coverage.AVPTjMgw.js';
import { V as Vitest, a as VitestPlugin } from './chunks/cli-api.24X8XwN1.js';
export { F as ForksPoolWorker, G as GitNotFoundError, b as TestsNotFoundError, T as ThreadsPoolWorker, c as TypecheckPoolWorker, d as VitestPackageInstaller, e as VmForksPoolWorker, f as VmThreadsPoolWorker, g as createDebugger, h as createMethodsRPC, i as createViteLogger, j as createVitest, k as escapeTestName, l as experimental_getRunnerTask, m as getFilePoolName, n as isFileServingAllowed, o as isValidApiRequest, r as registerConsoleShortcuts, p as resolveFsAllow, s as startVitest } from './chunks/cli-api.24X8XwN1.js';
export { p as parseCLI } from './chunks/cac.D3xHeqeL.js';
import { r as resolveConfig$2 } from './chunks/coverage.DM_a_rWm.js';
export { B as BaseCoverageProvider, a as BaseSequencer, b as resolveApiServerConfig } from './chunks/coverage.DM_a_rWm.js';
import { slash, deepClone } from '@vitest/utils/helpers';
import { a as any } from './chunks/index.D4KonVSU.js';
import { a as any } from './chunks/index.og1WyBLx.js';
import { resolve } from 'pathe';
import { c as configFiles } from './chunks/constants.D_Q9UYh-.js';
import { c as configFiles } from './chunks/constants.CPYnjOGj.js';
export { M as AgentReporter, B as BenchmarkReporter, a as BenchmarkReportsMap, D as DefaultReporter, b as DotReporter, G as GithubActionsReporter, H as HangingProcessReporter, J as JUnitReporter, c as JsonReporter, M as MinimalReporter, R as ReportersMap, T as TapFlatReporter, d as TapReporter, V as VerboseBenchmarkReporter, e as VerboseReporter } from './chunks/index.UpGiHP7g.js';
export { distDir, rootDir } from './path.js';
export { generateFileHash } from '@vitest/runner/utils';
import 'node:fs';
import './chunks/coverage.D_JHT54q.js';
import './chunks/coverage.CTzCuANN.js';
import 'node:path';
import './chunks/index.BCY_7LL2.js';
import 'node:module';
import 'node:process';
import 'node:fs/promises';
import 'node:url';
import 'node:assert';
import 'node:v8';
import 'node:util';
import 'node:os';
import '@vitest/snapshot/manager';
import 'node:perf_hooks';
import './chunks/index.Chj8NDwU.js';
import './chunks/index.M8mOzt4Y.js';
import 'node:fs/promises';
import '@vitest/utils/source-map';
import '@vitest/utils/serialize';
import './chunks/nativeModuleRunner.BIakptoF.js';
import 'vite/module-runner';
import './chunks/traces.DT5aQ62U.js';
import 'obug';
import 'tinyrainbow';
import '#module-evaluator';
import 'node:console';
import './chunks/_commonjsHelpers.D26ty3Ew.js';
import './chunks/utils.BS4fH3nR.js';
import './chunks/env.D4Lgay0q.js';
import 'std-env';
import 'node:util';
import 'node:console';
import 'node:stream';
import '@vitest/utils/display';
import 'tinyexec';
import '@vitest/utils/offset';
import 'node:module';
import 'node:tty';
import 'node:crypto';
import 'node:events';
import './chunks/index.Chj8NDwU.js';
import './chunks/modules.BJuCwlRJ.js';
import 'node:child_process';
import 'node:worker_threads';
import 'picomatch';
import 'tinyglobby';
import 'node:perf_hooks';
import 'events';
import 'https';
import 'http';
@@ -42,34 +58,20 @@ import 'stream';
import 'url';
import 'zlib';
import 'buffer';
import './chunks/_commonjsHelpers.D26ty3Ew.js';
import 'node:crypto';
import './chunks/traces.CCmnQaNT.js';
import 'obug';
import '#module-evaluator';
import 'vite/module-runner';
import '@vitest/utils/highlight';
import 'node:url';
import 'node:tty';
import 'node:events';
import './chunks/modules.BJuCwlRJ.js';
import 'node:child_process';
import 'node:worker_threads';
import 'picomatch';
import 'tinyglobby';
import './chunks/defaults.9aQKnqFk.js';
import 'magic-string';
import '@vitest/mocker/node';
import './chunks/defaults.BOqNVLsY.js';
import '@vitest/utils/constants';
import '@vitest/utils/resolver';
import 'es-module-lexer';
import './chunks/index.C5r1PdPD.js';
import 'node:assert';
import '@vitest/utils/serialize';
import '@vitest/utils/source-map';
import '@vitest/utils/source-map/node';
import 'tinyexec';
import 'node:readline';
import 'node:process';
import 'node:v8';
import 'readline';
import 'node:stream';
import '@vitest/utils/display';
import '@vitest/utils/offset';
// this is only exported as a public function and not used inside vitest
async function resolveConfig(options = {}, viteOverrides = {}) {
+41
View File
@@ -0,0 +1,41 @@
import { isBuiltin } from 'node:module';
let port;
const initialize = async ({ port: _port, time: _time }) => {
port = _port;
};
const NOW_LENGTH = Date.now().toString().length;
const REGEXP_VITEST = new RegExp(`%3Fvitest=\\d{${NOW_LENGTH}}`);
const REGEXP_MOCK_ACTUAL = /\?mock=actual/;
const resolve = (specifier, context, defaultResolve) => {
if (specifier.includes("mock=actual")) {
// url is already resolved by `importActual`
const moduleId = specifier.replace(REGEXP_MOCK_ACTUAL, "");
return {
url: moduleId,
format: isBuiltin(moduleId) ? "builtin" : void 0,
shortCircuit: true
};
}
const isVitest = specifier.includes("%3Fvitest=");
const result = defaultResolve(isVitest ? specifier.replace(REGEXP_VITEST, "") : specifier, context);
if (!port || !context?.parentURL) return result;
if (typeof result === "object" && "then" in result) return result.then((resolved) => {
ensureModuleGraphEntry(resolved.url, context.parentURL);
if (isVitest) resolved.url = `${resolved.url}?vitest=${Date.now()}`;
return resolved;
});
if (isVitest) result.url = `${result.url}?vitest=${Date.now()}`;
ensureModuleGraphEntry(result.url, context.parentURL);
return result;
};
function ensureModuleGraphEntry(url, parentURL) {
if (url.includes("/node_modules/")) return;
port.postMessage({
event: "register-module-graph-entry",
url,
parentURL
});
}
export { initialize, resolve };
+11 -11
View File
@@ -1,26 +1,26 @@
export { aR as BaseReporter, aS as BenchmarkBuiltinReporters, aE as BenchmarkReporter, aF as BenchmarkReportsMap, aT as BuiltinReporterOptions, aU as BuiltinReporters, aG as DefaultReporter, aH as DotReporter, aI as GithubActionsReporter, aJ as HangingProcessReporter, aL as JUnitReporter, aV as JsonAssertionResult, aK as JsonReporter, aW as JsonTestResult, aX as JsonTestResults, aB as ReportedHookContext, aC as Reporter, aM as ReportersMap, aN as TapFlatReporter, aO as TapReporter, aD as TestRunEndReason, aP as VerboseBenchmarkReporter, aQ as VerboseReporter } from './chunks/reporters.d.CWXNI2jG.js';
export { M as AgentReporter, l as BaseReporter, m as BenchmarkBuiltinReporters, n as BenchmarkReporter, o as BenchmarkReportsMap, K as BuiltinReporterOptions, N as BuiltinReporters, a0 as DefaultReporter, a2 as DotReporter, a4 as GithubActionsReporter, a6 as HangingProcessReporter, a9 as JUnitReporter, aa as JsonAssertionResult, ac as JsonReporter, ad as JsonTestResult, ae as JsonTestResults, M as MinimalReporter, ap as ReportedHookContext, aq as Reporter, ar as ReportersMap, ay as TapFlatReporter, az as TapReporter, aK as TestRunEndReason, aU as VerboseBenchmarkReporter, aV as VerboseReporter } from './chunks/reporters.d.DtoKVV2s.js';
import '@vitest/runner';
import '@vitest/utils';
import './chunks/rpc.d.RH3apGEf.js';
import '@vitest/snapshot';
import 'vite/module-runner';
import './chunks/traces.d.402V_yFI.js';
import './chunks/traces.d.D2T_R8rx.js';
import 'node:stream';
import 'vite';
import './chunks/browser.d.ChKACdzH.js';
import './chunks/worker.d.Dyxm8DEL.js';
import './chunks/config.d.Cy95HiCx.js';
import './chunks/config.d.A1h_Y6Jt.js';
import '@vitest/pretty-format';
import '@vitest/snapshot';
import '@vitest/utils/diff';
import './chunks/browser.d.BcoexmFG.js';
import './chunks/worker.d.ZpHpO4yb.js';
import 'vite/module-runner';
import './chunks/environment.d.CrsxCzP1.js';
import '@vitest/mocker';
import '@vitest/utils/source-map';
import 'vitest/browser';
import './chunks/rpc.d.B_8sPU0w.js';
import '@vitest/expect';
import 'vitest/optional-types.js';
import './chunks/benchmark.d.DAaHLpsq.js';
import '@vitest/runner/utils';
import 'tinybench';
import '@vitest/mocker';
import '@vitest/utils/source-map';
import 'vitest/browser';
import './chunks/coverage.d.BZtK59WP.js';
import '@vitest/snapshot/manager';
import 'node:console';
+10 -8
View File
@@ -1,16 +1,16 @@
export { D as DefaultReporter, a as DotReporter, G as GithubActionsReporter, H as HangingProcessReporter, b as JUnitReporter, J as JsonReporter, R as ReportersMap, T as TapFlatReporter, c as TapReporter, V as VerboseReporter } from './chunks/index.M8mOzt4Y.js';
export { B as BenchmarkReporter, a as BenchmarkReportsMap, V as VerboseBenchmarkReporter } from './chunks/index.C5r1PdPD.js';
export { M as AgentReporter, B as BenchmarkReporter, a as BenchmarkReportsMap, D as DefaultReporter, b as DotReporter, G as GithubActionsReporter, H as HangingProcessReporter, J as JUnitReporter, c as JsonReporter, M as MinimalReporter, R as ReportersMap, T as TapFlatReporter, d as TapReporter, V as VerboseBenchmarkReporter, e as VerboseReporter } from './chunks/index.UpGiHP7g.js';
import 'node:fs';
import 'node:fs/promises';
import 'pathe';
import 'node:perf_hooks';
import '@vitest/runner/utils';
import '@vitest/utils/helpers';
import '@vitest/utils/source-map';
import 'pathe';
import 'tinyrainbow';
import './chunks/utils.BS4fH3nR.js';
import 'node:util';
import '@vitest/utils/helpers';
import 'node:fs/promises';
import 'node:perf_hooks';
import '@vitest/utils/source-map';
import './chunks/env.D4Lgay0q.js';
import 'std-env';
import 'node:util';
import 'node:console';
import 'node:stream';
import '@vitest/utils/display';
@@ -22,3 +22,5 @@ import 'node:url';
import 'vite';
import '@vitest/utils/offset';
import 'node:module';
console.warn("Importing from \"vitest/reporters\" is deprecated since Vitest 4.1. Please use \"vitest/node\" instead.");
+26 -6
View File
@@ -1,11 +1,14 @@
import * as tinybench from 'tinybench';
import { VitestRunner, VitestRunnerImportSource, Suite, File, Task, CancelReason, Test, TestContext, ImportDuration } from '@vitest/runner';
import { VitestRunner, VitestRunnerImportSource, Suite, File, Task, CancelReason, Test, TestContext, ImportDuration, createTaskCollector, getCurrentSuite, getCurrentTest, getHooks, getFn } from '@vitest/runner';
export { VitestRunner } from '@vitest/runner';
import { S as SerializedConfig } from './chunks/config.d.Cy95HiCx.js';
import { T as Traces } from './chunks/traces.d.402V_yFI.js';
import { S as SerializedConfig } from './chunks/config.d.A1h_Y6Jt.js';
import { T as Traces } from './chunks/traces.d.D2T_R8rx.js';
import { createChainable, matchesTags } from '@vitest/runner/utils';
import { g as getBenchFn, a as getBenchOptions } from './chunks/suite.d.udJtyAgw.js';
import '@vitest/pretty-format';
import '@vitest/snapshot';
import '@vitest/utils/diff';
import './chunks/benchmark.d.DAaHLpsq.js';
declare class NodeBenchmarkRunner implements VitestRunner {
config: SerializedConfig;
@@ -17,7 +20,7 @@ declare class NodeBenchmarkRunner implements VitestRunner {
runTask(): Promise<void>;
}
declare class VitestTestRunner implements VitestRunner {
declare class TestRunner implements VitestRunner {
config: SerializedConfig;
private snapshotClient;
private workerState;
@@ -27,12 +30,12 @@ declare class VitestTestRunner implements VitestRunner {
pool: string;
private _otel;
viteEnvironment: string;
private viteModuleRunner;
constructor(config: SerializedConfig);
importFile(filepath: string, source: VitestRunnerImportSource): unknown;
onCollectStart(file: File): void;
onCleanupWorkerContext(listener: () => unknown): void;
onAfterRunFiles(): void;
getWorkerContext(): Record<string, unknown>;
onAfterRunSuite(suite: Suite): Promise<void>;
onAfterRunTask(test: Task): void;
cancel(_reason: CancelReason): void;
@@ -45,6 +48,23 @@ declare class VitestTestRunner implements VitestRunner {
getImportDurations(): Record<string, ImportDuration>;
trace: <T>(name: string, attributes: Record<string, any> | (() => T), cb?: () => T) => T;
__setTraces(traces: Traces): void;
static createTaskCollector: typeof createTaskCollector;
static getCurrentSuite: typeof getCurrentSuite;
static getCurrentTest: typeof getCurrentTest;
static createChainable: typeof createChainable;
static getSuiteHooks: typeof getHooks;
static getTestFn: typeof getFn;
static setSuiteHooks: typeof getHooks;
static setTestFn: typeof getFn;
static matchesTags: typeof matchesTags;
/**
* @deprecated
*/
static getBenchFn: typeof getBenchFn;
/**
* @deprecated
*/
static getBenchOptions: typeof getBenchOptions;
}
export { NodeBenchmarkRunner, VitestTestRunner };
export { NodeBenchmarkRunner, TestRunner as VitestTestRunner };
+7 -7
View File
@@ -1,19 +1,19 @@
export { N as NodeBenchmarkRunner, V as VitestTestRunner } from './chunks/test.B8ej_ZHS.js';
export { N as NodeBenchmarkRunner, T as VitestTestRunner } from './chunks/test.DNmyFkvJ.js';
import '@vitest/runner';
import '@vitest/utils/helpers';
import '@vitest/utils/timers';
import './chunks/benchmark.B3N2zMcH.js';
import './chunks/benchmark.CX_oY03V.js';
import '@vitest/runner/utils';
import './chunks/utils.DvEY5TfP.js';
import './chunks/utils.BX5Fg8C4.js';
import '@vitest/expect';
import '@vitest/utils/error';
import 'pathe';
import './chunks/vi.2VT5v0um.js';
import '@vitest/snapshot';
import '@vitest/spy';
import '@vitest/utils/offset';
import '@vitest/utils/source-map';
import './chunks/_commonjsHelpers.D26ty3Ew.js';
import './chunks/date.Bq6ZW5rf.js';
import './chunks/rpc.BoxB0q7B.js';
import './chunks/rpc.MzXet3jl.js';
import './chunks/index.Chj8NDwU.js';
import '@vitest/snapshot';
console.warn("Importing from \"vitest/runners\" is deprecated since Vitest 4.1. Please use \"vitest\" instead.");
+6
View File
@@ -0,0 +1,6 @@
export { builtinEnvironments, populateGlobal } from './environments.js';
export { VitestSnapshotEnvironment } from './snapshot.js';
export { E as Environment, a as EnvironmentReturn, V as VmEnvironmentReturn } from './chunks/environment.d.CrsxCzP1.js';
export { VitestRunner, VitestRunnerConfig } from '@vitest/runner';
export { SnapshotEnvironment } from '@vitest/snapshot/environment';
import '@vitest/utils';
+35
View File
@@ -0,0 +1,35 @@
import { VitestModuleEvaluator } from './module-evaluator.js';
import { V as VITEST_VM_CONTEXT_SYMBOL, s as startVitestModuleRunner, a as VitestModuleRunner } from './chunks/startVitestModuleRunner.CCBQZ9DQ.js';
import { g as getWorkerState } from './chunks/utils.BX5Fg8C4.js';
export { e as builtinEnvironments, p as populateGlobal } from './chunks/index.DC7d2Pf8.js';
export { VitestNodeSnapshotEnvironment as VitestSnapshotEnvironment } from './chunks/node.COQbm6gK.js';
import 'node:module';
import 'node:url';
import 'node:vm';
import 'vite/module-runner';
import './chunks/traces.DT5aQ62U.js';
import 'node:fs';
import '@vitest/utils/helpers';
import './chunks/modules.BJuCwlRJ.js';
import 'pathe';
import './path.js';
import 'node:path';
import '@vitest/mocker';
import '@vitest/mocker/redirect';
import '@vitest/utils/timers';
import 'node:console';
import '@vitest/snapshot/environment';
/**
* @internal
*/
const __INTERNAL = {
VitestModuleEvaluator,
VitestModuleRunner,
startVitestModuleRunner,
VITEST_VM_CONTEXT_SYMBOL,
getWorkerState
};
// #endregion
export { __INTERNAL };
+4 -2
View File
@@ -1,4 +1,6 @@
export { VitestNodeSnapshotEnvironment as VitestSnapshotEnvironment } from './chunks/node.Ce0vMQM7.js';
export { VitestNodeSnapshotEnvironment as VitestSnapshotEnvironment } from './chunks/node.COQbm6gK.js';
import '@vitest/snapshot/environment';
import './chunks/utils.DvEY5TfP.js';
import './chunks/utils.BX5Fg8C4.js';
import '@vitest/utils/timers';
console.warn("Importing from \"vitest/snapshot\" is deprecated since Vitest 4.1. Please use \"vitest/runtime\" instead.");
+1 -1
View File
@@ -1,4 +1,4 @@
export { g as getBenchFn, a as getBenchOptions } from './chunks/suite.d.BJWk38HB.js';
export { g as getBenchFn, a as getBenchOptions } from './chunks/suite.d.udJtyAgw.js';
export { VitestRunner, VitestRunnerConfig, createTaskCollector, getCurrentSuite, getCurrentTest, getFn, getHooks, setFn, setHooks } from '@vitest/runner';
export { createChainable } from '@vitest/runner/utils';
import './chunks/benchmark.d.DAaHLpsq.js';
+4 -2
View File
@@ -1,6 +1,8 @@
export { g as getBenchFn, a as getBenchOptions } from './chunks/benchmark.B3N2zMcH.js';
export { g as getBenchFn, a as getBenchOptions } from './chunks/benchmark.CX_oY03V.js';
export { createTaskCollector, getCurrentSuite, getCurrentTest, getFn, getHooks, setFn, setHooks } from '@vitest/runner';
export { createChainable } from '@vitest/runner/utils';
import '@vitest/utils/helpers';
import './chunks/utils.DvEY5TfP.js';
import './chunks/utils.BX5Fg8C4.js';
import '@vitest/utils/timers';
console.warn("Importing from \"vitest/suite\" is deprecated since Vitest 4.1. Please use static methods of \"TestRunner\" from the \"vitest\" entry point instead: e.g., `TestRunner.getCurrentTest()`.");
+7 -7
View File
@@ -1,17 +1,17 @@
import { W as WorkerGlobalState, a as WorkerSetupContext, B as BirpcOptions } from './chunks/worker.d.Dyxm8DEL.js';
import { T as Traces } from './chunks/traces.d.402V_yFI.js';
import { W as WorkerGlobalState, a as WorkerSetupContext, B as BirpcOptions } from './chunks/worker.d.ZpHpO4yb.js';
import { T as Traces } from './chunks/traces.d.D2T_R8rx.js';
import { Awaitable } from '@vitest/utils';
import { ModuleRunner } from 'vite/module-runner';
import { R as RuntimeRPC } from './chunks/rpc.d.RH3apGEf.js';
import { R as RuntimeRPC } from './chunks/rpc.d.B_8sPU0w.js';
import '@vitest/runner';
import './chunks/config.d.Cy95HiCx.js';
import './chunks/config.d.A1h_Y6Jt.js';
import '@vitest/pretty-format';
import '@vitest/snapshot';
import '@vitest/utils/diff';
import './chunks/environment.d.CrsxCzP1.js';
/** @experimental */
declare function setupEnvironment(context: WorkerSetupContext): Promise<() => Promise<void>>;
declare function setupBaseEnvironment(context: WorkerSetupContext): Promise<() => Promise<void>>;
/** @experimental */
declare function runBaseTests(method: "run" | "collect", state: WorkerGlobalState, traces: Traces): Promise<void>;
@@ -20,7 +20,7 @@ interface VitestWorker extends WorkerRpcOptions {
runTests: (state: WorkerGlobalState, traces: Traces) => Awaitable<unknown>;
collectTests: (state: WorkerGlobalState, traces: Traces) => Awaitable<unknown>;
onModuleRunner?: (moduleRunner: ModuleRunner) => Awaitable<unknown>;
setup?: (context: WorkerSetupContext) => Promise<() => Promise<unknown>>;
setup?: (context: WorkerSetupContext) => void | Promise<() => Promise<unknown>>;
}
interface Options extends VitestWorker {
@@ -29,4 +29,4 @@ interface Options extends VitestWorker {
/** @experimental */
declare function init(worker: Options): void;
export { init, runBaseTests, setupEnvironment };
export { init, runBaseTests, setupBaseEnvironment as setupEnvironment };
+30 -23
View File
@@ -1,48 +1,55 @@
export { r as runBaseTests, s as setupEnvironment } from './chunks/base.CJ0Y4ePK.js';
export { i as init } from './chunks/init.B6MLFIaN.js';
export { r as runBaseTests, s as setupEnvironment } from './chunks/base.BE3cXZj3.js';
export { i as init } from './chunks/init.d4hAcNdp.js';
import 'node:vm';
import '@vitest/spy';
import './chunks/index.6Qv1eEA6.js';
import './chunks/index.DXx9Dtk7.js';
import '@vitest/expect';
import './chunks/setup-common.Cm-kSBVi.js';
import './chunks/coverage.D_JHT54q.js';
import 'node:async_hooks';
import './chunks/setup-common.DYx3LtFI.js';
import './chunks/coverage.CTzCuANN.js';
import '@vitest/snapshot';
import '@vitest/utils/timers';
import './chunks/utils.DvEY5TfP.js';
import './chunks/rpc.BoxB0q7B.js';
import './chunks/utils.BX5Fg8C4.js';
import './chunks/rpc.MzXet3jl.js';
import './chunks/index.Chj8NDwU.js';
import './chunks/test.B8ej_ZHS.js';
import './chunks/test.DNmyFkvJ.js';
import '@vitest/runner';
import '@vitest/utils/helpers';
import './chunks/benchmark.B3N2zMcH.js';
import './chunks/benchmark.CX_oY03V.js';
import '@vitest/runner/utils';
import '@vitest/utils/error';
import 'pathe';
import './chunks/vi.2VT5v0um.js';
import '@vitest/utils/offset';
import '@vitest/utils/source-map';
import './chunks/_commonjsHelpers.D26ty3Ew.js';
import './chunks/date.Bq6ZW5rf.js';
import './chunks/evaluatedModules.Dg1zASAC.js';
import 'vite/module-runner';
import './chunks/startModuleRunner.DEj0jb3e.js';
import 'node:fs';
import './chunks/modules.BJuCwlRJ.js';
import 'node:module';
import './chunks/nativeModuleRunner.BIakptoF.js';
import 'node:url';
import './path.js';
import './chunks/index.BCY_7LL2.js';
import 'node:fs';
import 'node:module';
import 'node:path';
import '@vitest/utils/serialize';
import 'node:process';
import 'node:fs/promises';
import 'node:assert';
import 'node:v8';
import 'node:util';
import 'vite/module-runner';
import './chunks/traces.DT5aQ62U.js';
import './chunks/evaluatedModules.Dg1zASAC.js';
import './chunks/startVitestModuleRunner.CCBQZ9DQ.js';
import './chunks/modules.BJuCwlRJ.js';
import './path.js';
import './module-evaluator.js';
import './chunks/traces.CCmnQaNT.js';
import '@vitest/mocker';
import '@vitest/mocker/redirect';
import 'node:perf_hooks';
import './chunks/inspector.CvyFGlXm.js';
import 'node:timers';
import 'node:timers/promises';
import 'node:util';
import '@vitest/utils/constants';
import './chunks/index.Z5E_ObnR.js';
import './chunks/index.DdgEv5B1.js';
import 'expect-type';
import './chunks/index.CyBMJtT7.js';
import './chunks/index.DC7d2Pf8.js';
import 'node:console';
import '@vitest/utils/serialize';
import 'tinyrainbow';
+26 -19
View File
@@ -1,54 +1,61 @@
import { r as runBaseTests, s as setupEnvironment } from '../chunks/base.CJ0Y4ePK.js';
import { w as workerInit } from '../chunks/init-forks._y3TW739.js';
import { r as runBaseTests, s as setupBaseEnvironment } from '../chunks/base.BE3cXZj3.js';
import { w as workerInit } from '../chunks/init-forks.B4VBaxRV.js';
import 'node:vm';
import '@vitest/spy';
import '../chunks/index.6Qv1eEA6.js';
import '../chunks/index.DXx9Dtk7.js';
import '@vitest/expect';
import '../chunks/setup-common.Cm-kSBVi.js';
import '../chunks/coverage.D_JHT54q.js';
import 'node:async_hooks';
import '../chunks/setup-common.DYx3LtFI.js';
import '../chunks/coverage.CTzCuANN.js';
import '@vitest/snapshot';
import '@vitest/utils/timers';
import '../chunks/utils.DvEY5TfP.js';
import '../chunks/rpc.BoxB0q7B.js';
import '../chunks/utils.BX5Fg8C4.js';
import '../chunks/rpc.MzXet3jl.js';
import '../chunks/index.Chj8NDwU.js';
import '../chunks/test.B8ej_ZHS.js';
import '../chunks/test.DNmyFkvJ.js';
import '@vitest/runner';
import '@vitest/utils/helpers';
import '../chunks/benchmark.B3N2zMcH.js';
import '../chunks/benchmark.CX_oY03V.js';
import '@vitest/runner/utils';
import '@vitest/utils/error';
import 'pathe';
import '../chunks/vi.2VT5v0um.js';
import '@vitest/utils/offset';
import '@vitest/utils/source-map';
import '../chunks/_commonjsHelpers.D26ty3Ew.js';
import '../chunks/date.Bq6ZW5rf.js';
import '../chunks/init.B6MLFIaN.js';
import '../chunks/init.d4hAcNdp.js';
import 'node:fs';
import 'node:module';
import 'node:url';
import 'vite/module-runner';
import '../chunks/startModuleRunner.DEj0jb3e.js';
import '../chunks/startVitestModuleRunner.CCBQZ9DQ.js';
import '../chunks/modules.BJuCwlRJ.js';
import '../path.js';
import 'node:path';
import '@vitest/utils/serialize';
import '../module-evaluator.js';
import '../chunks/traces.CCmnQaNT.js';
import '../chunks/traces.DT5aQ62U.js';
import '@vitest/mocker';
import '../chunks/index.CyBMJtT7.js';
import '@vitest/mocker/redirect';
import '../chunks/index.DC7d2Pf8.js';
import 'node:console';
import '@vitest/utils/serialize';
import 'tinyrainbow';
import '../chunks/inspector.CvyFGlXm.js';
import '../chunks/evaluatedModules.Dg1zASAC.js';
import '../chunks/nativeModuleRunner.BIakptoF.js';
import '../chunks/index.BCY_7LL2.js';
import 'node:process';
import 'node:fs/promises';
import 'node:assert';
import 'node:v8';
import 'node:util';
import 'node:perf_hooks';
import 'node:timers';
import 'node:timers/promises';
import 'node:util';
import '@vitest/utils/constants';
import '../chunks/index.Z5E_ObnR.js';
import '../chunks/index.DdgEv5B1.js';
import 'expect-type';
workerInit({
runTests: runBaseTests,
setup: setupEnvironment
setup: setupBaseEnvironment
});
+19 -17
View File
@@ -5,33 +5,32 @@ import timersPromises from 'node:timers/promises';
import util from 'node:util';
import { startTests, collectTests } from '@vitest/runner';
import { KNOWN_ASSET_TYPES } from '@vitest/utils/constants';
import { s as setupChaiConfig, r as resolveTestRunner, a as resolveSnapshotEnvironment } from '../chunks/index.6Qv1eEA6.js';
import { c as setupCommonEnv, s as startCoverageInsideWorker, a as stopCoverageInsideWorker } from '../chunks/setup-common.Cm-kSBVi.js';
import { i as index } from '../chunks/index.Z5E_ObnR.js';
import { s as setupChaiConfig, r as resolveTestRunner, a as resolveSnapshotEnvironment, d as detectAsyncLeaks } from '../chunks/index.DXx9Dtk7.js';
import { s as setupCommonEnv, b as startCoverageInsideWorker, c as stopCoverageInsideWorker } from '../chunks/setup-common.DYx3LtFI.js';
import { i as index } from '../chunks/index.DdgEv5B1.js';
import { c as closeInspector } from '../chunks/inspector.CvyFGlXm.js';
import { g as getWorkerState } from '../chunks/utils.DvEY5TfP.js';
import { g as globalExpect } from '../chunks/vi.2VT5v0um.js';
import { g as getWorkerState } from '../chunks/utils.BX5Fg8C4.js';
import { g as globalExpect } from '../chunks/test.DNmyFkvJ.js';
import '@vitest/expect';
import '../chunks/rpc.BoxB0q7B.js';
import 'node:async_hooks';
import '../chunks/rpc.MzXet3jl.js';
import '@vitest/utils/timers';
import '../chunks/index.Chj8NDwU.js';
import '../chunks/test.B8ej_ZHS.js';
import '@vitest/utils/helpers';
import '../chunks/benchmark.B3N2zMcH.js';
import '@vitest/runner/utils';
import '@vitest/utils/error';
import 'pathe';
import '../chunks/coverage.D_JHT54q.js';
import '../chunks/coverage.CTzCuANN.js';
import '@vitest/snapshot';
import '../chunks/benchmark.CX_oY03V.js';
import '@vitest/runner/utils';
import '@vitest/utils/helpers';
import '../chunks/evaluatedModules.Dg1zASAC.js';
import 'pathe';
import 'vite/module-runner';
import 'expect-type';
import 'node:url';
import '@vitest/utils/error';
import '@vitest/spy';
import '@vitest/utils/offset';
import '@vitest/utils/source-map';
import '../chunks/_commonjsHelpers.D26ty3Ew.js';
import '../chunks/date.Bq6ZW5rf.js';
async function run(method, files, config, moduleRunner, traces) {
const workerState = getWorkerState();
@@ -65,7 +64,6 @@ async function run(method, files, config, moduleRunner, traces) {
if (config.chaiConfig) setupChaiConfig(config.chaiConfig);
const [testRunner, snapshotEnvironment] = await Promise.all([traces.$("vitest.runtime.runner", () => resolveTestRunner(config, moduleRunner, traces)), traces.$("vitest.runtime.snapshot.environment", () => resolveSnapshotEnvironment(config, moduleRunner))]);
config.snapshotOptions.snapshotEnvironment = snapshotEnvironment;
testRunner.getWorkerContext = void 0;
workerState.onCancel((reason) => {
closeInspector(config);
testRunner.cancel?.(reason);
@@ -75,8 +73,12 @@ async function run(method, files, config, moduleRunner, traces) {
await traces.$(`vitest.test.runner.${method}`, async () => {
for (const file of files) {
workerState.filepath = file.filepath;
if (method === "run") await traces.$(`vitest.test.runner.${method}.module`, { attributes: { "code.file.path": file.filepath } }, () => startTests([file], testRunner));
else await traces.$(`vitest.test.runner.${method}.module`, { attributes: { "code.file.path": file.filepath } }, () => collectTests([file], testRunner));
if (method === "run") {
const collectAsyncLeaks = config.detectAsyncLeaks ? detectAsyncLeaks(file.filepath, workerState.ctx.projectName) : void 0;
await traces.$(`vitest.test.runner.${method}.module`, { attributes: { "code.file.path": file.filepath } }, () => startTests([file], testRunner));
const leaks = await collectAsyncLeaks?.();
if (leaks?.length) workerState.rpc.onAsyncLeaks(leaks);
} else await traces.$(`vitest.test.runner.${method}.module`, { attributes: { "code.file.path": file.filepath } }, () => collectTests([file], testRunner));
// reset after tests, because user might call `vi.setConfig` in setupFile
vi.resetConfig();
// mocks should not affect different files
+26 -19
View File
@@ -1,55 +1,62 @@
import { s as setupEnvironment, r as runBaseTests } from '../chunks/base.CJ0Y4ePK.js';
import { w as workerInit } from '../chunks/init-threads.DBO2kn-p.js';
import { s as setupBaseEnvironment, r as runBaseTests } from '../chunks/base.BE3cXZj3.js';
import { w as workerInit } from '../chunks/init-threads.C_ClEpAf.js';
import 'node:vm';
import '@vitest/spy';
import '../chunks/index.6Qv1eEA6.js';
import '../chunks/index.DXx9Dtk7.js';
import '@vitest/expect';
import '../chunks/setup-common.Cm-kSBVi.js';
import '../chunks/coverage.D_JHT54q.js';
import 'node:async_hooks';
import '../chunks/setup-common.DYx3LtFI.js';
import '../chunks/coverage.CTzCuANN.js';
import '@vitest/snapshot';
import '@vitest/utils/timers';
import '../chunks/utils.DvEY5TfP.js';
import '../chunks/rpc.BoxB0q7B.js';
import '../chunks/utils.BX5Fg8C4.js';
import '../chunks/rpc.MzXet3jl.js';
import '../chunks/index.Chj8NDwU.js';
import '../chunks/test.B8ej_ZHS.js';
import '../chunks/test.DNmyFkvJ.js';
import '@vitest/runner';
import '@vitest/utils/helpers';
import '../chunks/benchmark.B3N2zMcH.js';
import '../chunks/benchmark.CX_oY03V.js';
import '@vitest/runner/utils';
import '@vitest/utils/error';
import 'pathe';
import '../chunks/vi.2VT5v0um.js';
import '@vitest/utils/offset';
import '@vitest/utils/source-map';
import '../chunks/_commonjsHelpers.D26ty3Ew.js';
import '../chunks/date.Bq6ZW5rf.js';
import '../chunks/init.B6MLFIaN.js';
import '../chunks/init.d4hAcNdp.js';
import 'node:fs';
import 'node:module';
import 'node:url';
import 'vite/module-runner';
import '../chunks/startModuleRunner.DEj0jb3e.js';
import '../chunks/startVitestModuleRunner.CCBQZ9DQ.js';
import '../chunks/modules.BJuCwlRJ.js';
import '../path.js';
import 'node:path';
import '@vitest/utils/serialize';
import '../module-evaluator.js';
import '../chunks/traces.CCmnQaNT.js';
import '../chunks/traces.DT5aQ62U.js';
import '@vitest/mocker';
import '../chunks/index.CyBMJtT7.js';
import '@vitest/mocker/redirect';
import '../chunks/index.DC7d2Pf8.js';
import 'node:console';
import '@vitest/utils/serialize';
import 'tinyrainbow';
import '../chunks/inspector.CvyFGlXm.js';
import '../chunks/evaluatedModules.Dg1zASAC.js';
import '../chunks/nativeModuleRunner.BIakptoF.js';
import '../chunks/index.BCY_7LL2.js';
import 'node:process';
import 'node:fs/promises';
import 'node:assert';
import 'node:v8';
import 'node:util';
import 'node:perf_hooks';
import 'node:timers';
import 'node:timers/promises';
import 'node:util';
import '@vitest/utils/constants';
import '../chunks/index.Z5E_ObnR.js';
import '../chunks/index.DdgEv5B1.js';
import 'expect-type';
import 'node:worker_threads';
workerInit({
runTests: runBaseTests,
setup: setupEnvironment
setup: setupBaseEnvironment
});
+17 -14
View File
@@ -1,36 +1,39 @@
import { w as workerInit } from '../chunks/init-forks._y3TW739.js';
import { r as runVmTests } from '../chunks/vm.D3epNOPZ.js';
import '../chunks/init.B6MLFIaN.js';
import { w as workerInit } from '../chunks/init-forks.B4VBaxRV.js';
import { r as runVmTests, s as setupVmWorker } from '../chunks/vm.B2aHeaNw.js';
import '../chunks/init.d4hAcNdp.js';
import 'node:fs';
import 'node:module';
import 'node:url';
import 'pathe';
import 'vite/module-runner';
import '../chunks/startModuleRunner.DEj0jb3e.js';
import '../chunks/startVitestModuleRunner.CCBQZ9DQ.js';
import '@vitest/utils/helpers';
import '../chunks/modules.BJuCwlRJ.js';
import '../chunks/utils.BX5Fg8C4.js';
import '@vitest/utils/timers';
import '../path.js';
import 'node:path';
import '@vitest/utils/serialize';
import '../module-evaluator.js';
import 'node:vm';
import '../chunks/traces.CCmnQaNT.js';
import '../chunks/traces.DT5aQ62U.js';
import '@vitest/mocker';
import '../chunks/index.CyBMJtT7.js';
import '@vitest/mocker/redirect';
import '../chunks/index.DC7d2Pf8.js';
import 'node:console';
import '@vitest/utils/serialize';
import '@vitest/utils/error';
import '../chunks/rpc.BoxB0q7B.js';
import '@vitest/utils/timers';
import 'tinyrainbow';
import '../chunks/rpc.MzXet3jl.js';
import '../chunks/index.Chj8NDwU.js';
import '../chunks/utils.DvEY5TfP.js';
import '@vitest/utils/source-map';
import '../chunks/inspector.CvyFGlXm.js';
import '../chunks/evaluatedModules.Dg1zASAC.js';
import '../chunks/console.Cf-YriPC.js';
import '../chunks/console.3WNpx0tS.js';
import 'node:stream';
import 'tinyrainbow';
import '../chunks/date.Bq6ZW5rf.js';
import '@vitest/utils/resolver';
import '@vitest/utils/constants';
workerInit({ runTests: runVmTests });
workerInit({
runTests: runVmTests,
setup: setupVmWorker
});
+17 -14
View File
@@ -1,37 +1,40 @@
import { w as workerInit } from '../chunks/init-threads.DBO2kn-p.js';
import { r as runVmTests } from '../chunks/vm.D3epNOPZ.js';
import { w as workerInit } from '../chunks/init-threads.C_ClEpAf.js';
import { s as setupVmWorker, r as runVmTests } from '../chunks/vm.B2aHeaNw.js';
import 'node:worker_threads';
import '../chunks/init.B6MLFIaN.js';
import '../chunks/init.d4hAcNdp.js';
import 'node:fs';
import 'node:module';
import 'node:url';
import 'pathe';
import 'vite/module-runner';
import '../chunks/startModuleRunner.DEj0jb3e.js';
import '../chunks/startVitestModuleRunner.CCBQZ9DQ.js';
import '@vitest/utils/helpers';
import '../chunks/modules.BJuCwlRJ.js';
import '../chunks/utils.BX5Fg8C4.js';
import '@vitest/utils/timers';
import '../path.js';
import 'node:path';
import '@vitest/utils/serialize';
import '../module-evaluator.js';
import 'node:vm';
import '../chunks/traces.CCmnQaNT.js';
import '../chunks/traces.DT5aQ62U.js';
import '@vitest/mocker';
import '../chunks/index.CyBMJtT7.js';
import '@vitest/mocker/redirect';
import '../chunks/index.DC7d2Pf8.js';
import 'node:console';
import '@vitest/utils/serialize';
import '@vitest/utils/error';
import '../chunks/rpc.BoxB0q7B.js';
import '@vitest/utils/timers';
import 'tinyrainbow';
import '../chunks/rpc.MzXet3jl.js';
import '../chunks/index.Chj8NDwU.js';
import '../chunks/utils.DvEY5TfP.js';
import '@vitest/utils/source-map';
import '../chunks/inspector.CvyFGlXm.js';
import '../chunks/evaluatedModules.Dg1zASAC.js';
import '../chunks/console.Cf-YriPC.js';
import '../chunks/console.3WNpx0tS.js';
import 'node:stream';
import 'tinyrainbow';
import '../chunks/date.Bq6ZW5rf.js';
import '@vitest/utils/resolver';
import '@vitest/utils/constants';
workerInit({ runTests: runVmTests });
workerInit({
runTests: runVmTests,
setup: setupVmWorker
});