Socket
Socket
Sign inDemoInstall

vitest

Package Overview
Dependencies
Maintainers
3
Versions
372
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vitest - npm Package Compare versions

Comparing version 0.34.6 to 1.0.1

dist/chunks/api-setup.jHV5vgr2.js

5

dist/browser.d.ts

@@ -1,3 +0,3 @@

export { startTests } from '@vitest/runner';
import { R as ResolvedConfig, e as CoverageOptions, f as CoverageProvider, g as CoverageProviderModule } from './reporters-5f784f42.js';
export { processError, startTests } from '@vitest/runner';
import { R as ResolvedConfig, b as CoverageOptions, c as CoverageProvider, d as CoverageProviderModule } from './reporters-LLiOBu3g.js';
import { VitestExecutor } from './execute.js';

@@ -15,3 +15,2 @@ import 'vite';

import 'node:worker_threads';
import 'rollup';
import 'node:fs';

@@ -18,0 +17,0 @@ import 'chai';

10

dist/browser.js

@@ -1,6 +0,6 @@

export { startTests } from '@vitest/runner';
export { processError, startTests } from '@vitest/runner';
import { setSafeTimers } from '@vitest/utils';
import { a as resetRunOnceCounter } from './vendor-run-once.3e5ef7d7.js';
export { g as getCoverageProvider, s as startCoverageInsideWorker, a as stopCoverageInsideWorker, t as takeCoverageInsideWorker } from './vendor-coverage.78040316.js';
import './vendor-global.97e4527c.js';
import { a as resetRunOnceCounter } from './vendor/run-once.X3E7xx3F.js';
export { g as getCoverageProvider, s as startCoverageInsideWorker, a as stopCoverageInsideWorker, t as takeCoverageInsideWorker } from './vendor/coverage.v6aD8iAh.js';
import './vendor/global.L7JRz1qU.js';

@@ -16,3 +16,3 @@ let globalSetup = false;

if (config.globals)
(await import('./chunk-integrations-globals.5afac659.js')).registerApiGlobally();
(await import('./chunks/integrations-globals.eip0xL77.js')).registerApiGlobally();
}

@@ -19,0 +19,0 @@ function setupDefines(defines) {

import { performance } from 'node:perf_hooks';
import v8 from 'node:v8';
import { c as createBirpc } from './vendor-index.b271ebe4.js';
import { c as createBirpc } from './vendor/index.cAUulNDf.js';
import { parseRegexp } from '@vitest/utils';
import { l as loadEnvironment } from './vendor-environments.7aba93d9.js';
import { s as startViteNode, m as moduleCache, a as mockMap } from './vendor-execute.07d1a420.js';
import { r as rpcDone, c as createSafeRpc } from './vendor-rpc.cbd8e972.js';
import { s as setupInspect } from './vendor-inspector.47fc8cbb.js';
import { workerId } from 'tinypool';
import { l as loadEnvironment } from './vendor/loader.w8KTtIkD.js';
import { s as startViteNode, m as moduleCache, a as mockMap } from './vendor/execute.ILey0jnF.js';
import { r as rpcDone, c as createSafeRpc } from './vendor/rpc.Bl-ysZIr.js';
import { s as setupInspect } from './vendor/inspector.lFAeuaAt.js';
import 'pathe';
import './vendor-index.0b5b3600.js';
import 'acorn';
import 'node:module';
import 'node:fs';
import 'node:url';
import 'node:assert';
import 'node:process';
import 'node:path';
import 'node:util';
import 'vite-node/client';
import './vendor/environments.hTqxBFDN.js';
import 'node:console';
import 'local-pkg';
import 'node:url';
import 'node:vm';
import 'vite-node/utils';
import '@vitest/utils/error';
import './vendor-paths.84fc7a99.js';
import './vendor-global.97e4527c.js';
import './vendor-base.9c08bbd0.js';
import './paths.js';
import 'node:fs';
import './vendor/base._79unx2z.js';
import 'node:path';
import 'node:module';
import 'vite-node/constants';
import './vendor/global.L7JRz1qU.js';
try {
process.title = `node (vitest ${workerId})`;
} catch {
}
async function init(ctx) {
const { config } = ctx;
process.env.VITEST_WORKER_ID = "1";
process.env.VITEST_POOL_ID = "1";
const { config, workerId: workerId$1, providedContext } = ctx;
process.env.VITEST_WORKER_ID = String(workerId$1);
process.env.VITEST_POOL_ID = String(workerId);
let setCancel = (_reason) => {

@@ -52,3 +53,7 @@ };

on(fn) {
process.on("message", fn);
process.on("message", (message, ...extras) => {
if (message == null ? void 0 : message.__tinypool_worker_message__)
return;
return fn(message, ...extras);
});
}

@@ -75,5 +80,12 @@ }

},
rpc
rpc,
providedContext,
isChildProcess: true
};
globalThis.__vitest_worker__ = state;
Object.defineProperty(globalThis, "__vitest_worker__", {
value: state,
configurable: true,
writable: true,
enumerable: false
});
if (ctx.invalidates) {

@@ -100,2 +112,4 @@ ctx.invalidates.forEach((fsPath) => {

async function run(ctx) {
const exit = process.exit;
ctx.config = unwrapConfig(ctx.config);
const inspectorCleanup = setupInspect(ctx.config);

@@ -111,16 +125,6 @@ try {

inspectorCleanup();
process.exit = exit;
}
}
const procesExit = process.exit;
process.on("message", async (message) => {
if (typeof message === "object" && message.command === "start") {
try {
message.config = unwrapConfig(message.config);
await run(message);
} finally {
procesExit();
}
}
});
export { run };
import { fileURLToPath } from 'node:url';
import c from 'picocolors';
import { e as execa } from './vendor-index.85fc950a.js';
import { E as EXIT_CODE_RESTART } from './vendor-constants.538d9b49.js';
import 'node:buffer';
import 'node:path';
import 'node:child_process';
import 'node:process';
import './vendor-_commonjsHelpers.7d1333e8.js';
import 'child_process';
import 'path';
import 'fs';
import 'node:os';
import 'assert';
import 'events';
import 'node:fs';
import 'buffer';
import 'stream';
import 'util';
import 'node:util';
import { execa } from 'execa';
import { E as EXIT_CODE_RESTART } from './vendor/constants.WSvnD_fn.js';

@@ -22,0 +6,0 @@ const ENTRY = new URL("./cli.js", import.meta.url);

import { normalize } from 'pathe';
import cac from 'cac';
import c from 'picocolors';
import { v as version, s as startVitest } from './vendor-node.a7c48fe1.js';
import './vendor-index.29282562.js';
import { d as divider } from './vendor-reporters.f6975b8d.js';
import { t as toArray } from './vendor-base.9c08bbd0.js';
import { v as version, s as startVitest } from './vendor/node.mLeBfrTn.js';
import './vendor/index.XU72Rmy8.js';
import { d as divider } from './vendor/reporters.pr8MinP9.js';
import { t as toArray } from './vendor/base._79unx2z.js';
import 'vite';

@@ -13,6 +13,7 @@ import 'node:path';

import 'node:fs';
import './vendor-constants.538d9b49.js';
import './vendor-_commonjsHelpers.7d1333e8.js';
import './vendor/constants.WSvnD_fn.js';
import './vendor/_commonjsHelpers.jjO7Zipk.js';
import 'os';
import 'path';
import './vendor/index.xL8XjTLv.js';
import 'util';

@@ -26,41 +27,37 @@ import 'stream';

import 'vite-node/server';
import './vendor-coverage.78040316.js';
import './vendor-paths.84fc7a99.js';
import './vendor/coverage.v6aD8iAh.js';
import './paths.js';
import 'node:v8';
import 'node:child_process';
import './vendor-index.b271ebe4.js';
import 'node:worker_threads';
import 'node:os';
import 'node:events';
import 'tinypool';
import './vendor/index.cAUulNDf.js';
import 'node:worker_threads';
import '@vitest/utils';
import 'node:fs/promises';
import 'node:perf_hooks';
import 'execa';
import '@vitest/utils/source-map';
import 'local-pkg';
import 'std-env';
import 'node:crypto';
import './vendor-index.85fc950a.js';
import 'node:buffer';
import 'child_process';
import 'assert';
import 'buffer';
import 'node:util';
import '@vitest/utils/source-map';
import 'node:fs/promises';
import 'module';
import 'acorn';
import 'acorn-walk';
import '@vitest/runner/utils';
import 'node:crypto';
import 'assert';
import 'magic-string';
import 'strip-literal';
import './vendor-environments.7aba93d9.js';
import './vendor-index.0b5b3600.js';
import 'node:module';
import 'node:assert';
import './vendor/environments.hTqxBFDN.js';
import 'node:console';
import 'node:readline';
import 'readline';
import './vendor-global.97e4527c.js';
import 'node:perf_hooks';
import './vendor-tasks.f9d75aed.js';
import './vendor/global.L7JRz1qU.js';
import './chunks/runtime-console.hf2msWA9.js';
import 'node:stream';
import './vendor/date.Ns1pGd_X.js';
import './vendor/tasks.IknbGB2n.js';
import 'node:module';
const cli = cac("vitest");
cli.version(version).option("-r, --root <path>", "Root path").option("-c, --config <path>", "Path to config file").option("-u, --update", "Update snapshot").option("-w, --watch", "Enable watch mode").option("-t, --testNamePattern <pattern>", "Run tests with full names matching the specified regexp pattern").option("--dir <path>", "Base directory to scan for the test files").option("--ui", "Enable UI").option("--open", "Open UI automatically (default: !process.env.CI))").option("--api [api]", "Serve API, available options: --api.port <port>, --api.host [host] and --api.strictPort").option("--threads", "Enabled threads (default: true)").option("--single-thread", "Run tests inside a single thread, requires --threads (default: false)").option("--experimental-vm-threads", "Run tests in a worker pool using VM isolation (default: false)").option("--experimental-vm-worker-memory-limit", "Set the maximum allowed memory for a worker. When reached, a new worker will be created instead").option("--silent", "Silent console output from tests").option("--hideSkippedTests", "Hide logs for skipped tests").option("--isolate", "Isolate environment for each test file (default: true)").option("--reporter <name>", "Specify reporters").option("--outputFile <filename/-s>", "Write test results to a file when supporter reporter is also specified, use cac's dot notation for individual outputs of multiple reporters").option("--coverage", "Enable coverage report").option("--run", "Disable watch mode").option("--mode <name>", "Override Vite mode (default: test)").option("--globals", "Inject apis globally").option("--dom", "Mock browser api with happy-dom").option("--browser [options]", "Run tests in the browser (default: false)").option("--environment <env>", "Specify runner environment, if not running in the browser (default: node)").option("--passWithNoTests", "Pass when no tests found").option("--logHeapUsage", "Show the size of heap for each test").option("--allowOnly", "Allow tests and suites that are marked as only (default: !process.env.CI)").option("--dangerouslyIgnoreUnhandledErrors", "Ignore any unhandled errors that occur").option("--shard <shard>", "Test suite shard to execute in a format of <index>/<count>").option("--changed [since]", "Run tests that are affected by the changed files (default: false)").option("--sequence <options>", "Define in what order to run tests (use --sequence.shuffle to run tests in random order, use --sequence.concurrent to run tests in parallel)").option("--segfaultRetry <times>", "Return tests on segment fault (default: 0)", { default: 0 }).option("--no-color", "Removes colors from the console output").option("--inspect", "Enable Node.js inspector").option("--inspect-brk", "Enable Node.js inspector with break").option("--test-timeout <time>", "Default timeout of a test in milliseconds (default: 5000)").option("--bail <number>", "Stop test execution when given number of tests have failed", { default: 0 }).option("--retry <times>", "Retry the test specific number of times if it fails", { default: 0 }).option("--diff <path>", "Path to a diff config that will be used to generate diff interface").help();
cli.version(version).option("-r, --root <path>", "Root path").option("-c, --config <path>", "Path to config file").option("-u, --update", "Update snapshot").option("-w, --watch", "Enable watch mode").option("-t, --testNamePattern <pattern>", "Run tests with full names matching the specified regexp pattern").option("--dir <path>", "Base directory to scan for the test files").option("--ui", "Enable UI").option("--open", "Open UI automatically (default: !process.env.CI))").option("--api [api]", "Serve API, available options: --api.port <port>, --api.host [host] and --api.strictPort").option("--silent", "Silent console output from tests").option("--hideSkippedTests", "Hide logs for skipped tests").option("--reporter <name>", "Specify reporters").option("--outputFile <filename/-s>", "Write test results to a file when supporter reporter is also specified, use cac's dot notation for individual outputs of multiple reporters").option("--coverage", "Enable coverage report").option("--run", "Disable watch mode").option("--mode <name>", "Override Vite mode (default: test)").option("--globals", "Inject apis globally").option("--dom", "Mock browser API with happy-dom").option("--browser [options]", "Run tests in the browser (default: false)").option("--pool <pool>", "Specify pool, if not running in the browser (default: threads)").option("--poolOptions <options>", "Specify pool options").option("--poolOptions.threads.isolate", "Isolate tests in threads pool (default: true)").option("--poolOptions.forks.isolate", "Isolate tests in forks pool (default: true)").option("--environment <env>", "Specify runner environment, if not running in the browser (default: node)").option("--passWithNoTests", "Pass when no tests found").option("--logHeapUsage", "Show the size of heap for each test").option("--allowOnly", "Allow tests and suites that are marked as only (default: !process.env.CI)").option("--dangerouslyIgnoreUnhandledErrors", "Ignore any unhandled errors that occur").option("--shard <shard>", "Test suite shard to execute in a format of <index>/<count>").option("--changed [since]", "Run tests that are affected by the changed files (default: false)").option("--sequence <options>", "Define in what order to run tests (use --sequence.shuffle to run tests in random order, use --sequence.concurrent to run tests in parallel)").option("--segfaultRetry <times>", "Return tests on segment fault (default: 0)", { default: 0 }).option("--no-color", "Removes colors from the console output").option("--inspect", "Enable Node.js inspector").option("--inspect-brk", "Enable Node.js inspector with break").option("--test-timeout <time>", "Default timeout of a test in milliseconds (default: 5000)").option("--bail <number>", "Stop test execution when given number of tests have failed (default: 0)").option("--retry <times>", "Retry the test specific number of times if it fails (default: 0)").option("--diff <path>", "Path to a diff config that will be used to generate diff interface").option("--expand-snapshot-diff", "Show full diff when snapshot fails").option("--typecheck [options]", "Custom options for typecheck pool").option("--typecheck.enabled", "Enable typechecking alongside tests (default: false)").option("--typecheck.only", "Run only typecheck tests. This automatically enables typecheck (default: false)").option("--project <name>", "The name of the project to run if you are using Vitest workspace feature. This can be repeated for multiple projects: --project=1 --project=2").help();
cli.command("run [...filters]").action(run);

@@ -71,3 +68,5 @@ cli.command("related [...filters]").action(runRelated);

cli.command("bench [...filters]").action(benchmark);
cli.command("typecheck [...filters]").action(typecheck);
cli.command("typecheck [...filters]").action(() => {
throw new Error(`Running typecheck via "typecheck" command is removed. Please use "--typecheck" to run your regular tests alongside typechecking, or "--typecheck.only" to run only typecheck tests.`);
});
cli.command("[...filters]").action((filters, options) => start("test", filters, options));

@@ -105,9 +104,5 @@ try {

async function benchmark(cliFilters, options) {
console.warn(c.yellow("Benchmarking is an experimental feature.\nBreaking changes might not follow semver, please pin Vitest's version when using it."));
console.warn(c.yellow("Benchmarking is an experimental feature.\nBreaking changes might not follow SemVer, please pin Vitest's version when using it."));
await start("benchmark", cliFilters, options);
}
async function typecheck(cliFilters = [], options = {}) {
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."));
await start("typecheck", cliFilters, options);
}
function normalizeCliOptions(argv) {

@@ -139,2 +134,6 @@ if (argv.root)

try {
process.title = "node (vitest)";
} catch {
}
try {
const ctx = await startVitest(mode, cliFilters.map(normalize), normalizeCliOptions(options));

@@ -141,0 +140,0 @@ if (!(ctx == null ? void 0 : ctx.shouldKeepServer()))

import { UserConfig as UserConfig$1, ConfigEnv } from 'vite';
export { ConfigEnv, UserConfig, mergeConfig } from 'vite';
import { a as ResolvedCoverageOptions, U as UserConfig, C as CoverageV8Options, P as ProjectConfig } from './reporters-5f784f42.js';
import { a as ResolvedCoverageOptions, U as UserConfig, C as CoverageV8Options, P as ProjectConfig } from './reporters-LLiOBu3g.js';
import '@vitest/runner';

@@ -15,3 +15,2 @@ import 'vite-node';

import 'node:worker_threads';
import 'rollup';
import 'node:fs';

@@ -28,3 +27,3 @@ import 'chai';

environment: "node";
threads: boolean;
pool: "threads";
clearMocks: boolean;

@@ -38,3 +37,2 @@ restoreMocks: boolean;

teardownTimeout: number;
isolate: boolean;
watchExclude: string[];

@@ -84,9 +82,7 @@ forceRerunTriggers: string[];

declare function defineConfig(config: UserConfigExport): UserConfigExport;
declare function defineProject(config: UserProjectConfigExport): UserProjectConfigExport;
declare function defineWorkspace(config: (string | (UserProjectConfigExport & {
declare function defineProject<T extends UserProjectConfigExport>(config: T): T;
declare function defineWorkspace<T extends (string | (UserProjectConfigExport & {
extends?: string;
}))[]): (string | (UserProjectConfigExport & {
extends?: string | undefined;
}))[];
}))[]>(config: T): T;
export { UserConfigExport, UserConfigFn, UserConfigFnObject, UserConfigFnPromise, UserProjectConfigExport, UserProjectConfigFn, UserWorkspaceConfig, configDefaults, coverageConfigDefaults, defaultExclude, defaultInclude, defineConfig, defineProject, defineWorkspace };
export { type UserConfigExport, type UserConfigFn, type UserConfigFnObject, type UserConfigFnPromise, type UserProjectConfigExport, type UserProjectConfigFn, type UserWorkspaceConfig, configDefaults, coverageConfigDefaults, defaultExclude, defaultInclude, defineConfig, defineProject, defineWorkspace };

@@ -0,7 +1,9 @@

import os from 'node:os';
import { isCI } from 'std-env';
export { mergeConfig } from 'vite';
var _a;
typeof process < "u" && typeof process.stdout < "u" && !((_a = process.versions) == null ? void 0 : _a.deno) && !globalThis.window;
var _a$1;
typeof process < "u" && typeof process.stdout < "u" && !((_a$1 = process.versions) == null ? void 0 : _a$1.deno) && !globalThis.window;
var _a, _b;
const defaultInclude = ["**/*.{test,spec}.?(c|m)[jt]s?(x)"];

@@ -12,2 +14,3 @@ const defaultExclude = ["**/node_modules/**", "**/dist/**", "**/cypress/**", "**/.{idea,git,cache,output,temp}/**", "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build}.config.*"];

"dist/**",
"**/[.]**",
"packages/*/test?(s)/**",

@@ -30,2 +33,3 @@ "**/*.d.ts",

enabled: false,
all: true,
clean: true,

@@ -37,4 +41,5 @@ cleanOnRerun: true,

reporter: [["text", {}], ["html", {}], ["clover", {}], ["json", {}]],
extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte"],
allowExternal: false
extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte", ".marko"],
allowExternal: false,
processingConcurrency: Math.min(20, ((_b = (_a = os).availableParallelism) == null ? void 0 : _b.call(_a)) ?? os.cpus().length)
};

@@ -59,3 +64,3 @@ const fakeTimersDefaults = {

environment: "node",
threads: true,
pool: "threads",
clearMocks: false,

@@ -69,3 +74,2 @@ restoreMocks: false,

teardownTimeout: 1e4,
isolate: true,
watchExclude: ["**/node_modules/**", "**/dist/**"],

@@ -83,3 +87,3 @@ forceRerunTriggers: [

uiBase: "/__vitest__/",
open: true,
open: !isCI,
css: {

@@ -86,0 +90,0 @@ include: []

@@ -1,2 +0,2 @@

import { B as BaseCoverageOptions, a as ResolvedCoverageOptions } from './reporters-5f784f42.js';
import { B as BaseCoverageOptions, a as ResolvedCoverageOptions } from './reporters-LLiOBu3g.js';
import 'vite';

@@ -14,12 +14,5 @@ import '@vitest/runner';

import 'node:worker_threads';
import 'rollup';
import 'node:fs';
import 'chai';
// Type definitions for istanbul-lib-coverage 2.0
// Project: https://istanbul.js.org, https://github.com/istanbuljs/istanbuljs
// Definitions by: Jason Cheatham <https://github.com/jason0x43>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
interface CoverageSummaryData {

@@ -130,2 +123,7 @@ lines: Totals;

type Threshold = 'lines' | 'functions' | 'statements' | 'branches';
interface ResolvedThreshold {
coverageMap: CoverageMap;
name: string;
thresholds: Partial<Record<Threshold, number | undefined>>;
}
declare class BaseCoverageProvider {

@@ -135,17 +133,28 @@ /**

*/
updateThresholds({ configurationFile, coverageMap, thresholds, perFile }: {
coverageMap: CoverageMap;
thresholds: Record<Threshold, number | undefined>;
updateThresholds({ thresholds: allThresholds, perFile, configurationFile }: {
thresholds: ResolvedThreshold[];
perFile?: boolean;
configurationFile?: string;
configurationFile: {
read(): unknown;
write(): void;
};
}): void;
/**
* Checked collected coverage against configured thresholds. Sets exit code to 1 when thresholds not reached.
* Check collected coverage against configured thresholds. Sets exit code to 1 when thresholds not reached.
*/
checkThresholds({ coverageMap, thresholds, perFile }: {
coverageMap: CoverageMap;
thresholds: Record<Threshold, number | undefined>;
checkThresholds({ thresholds: allThresholds, perFile }: {
thresholds: ResolvedThreshold[];
perFile?: boolean;
}): void;
/**
* 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, thresholds, createCoverageMap }: {
coverageMap: CoverageMap;
thresholds: NonNullable<BaseCoverageOptions['thresholds']>;
createCoverageMap: () => CoverageMap;
}): ResolvedThreshold[];
/**
* Resolve reporters from various configuration options

@@ -152,0 +161,0 @@ */

@@ -1,5 +0,9 @@

import { readFileSync, writeFileSync } from 'node:fs';
import { relative } from 'pathe';
import { m as mm } from './vendor/index.xL8XjTLv.js';
import './vendor/_commonjsHelpers.jjO7Zipk.js';
import 'util';
import 'path';
const THRESHOLD_KEYS = ["lines", "functions", "statements", "branches"];
const GLOBAL_THRESHOLDS_KEY = "global";
class BaseCoverageProvider {

@@ -9,56 +13,58 @@ /**

*/
updateThresholds({ configurationFile, coverageMap, thresholds, perFile }) {
if (!configurationFile)
throw new Error('Missing configurationFile. The "coverage.thresholdAutoUpdate" can only be enabled when configuration file is used.');
const summaries = perFile ? coverageMap.files().map((file) => coverageMap.fileCoverageFor(file).toSummary()) : [coverageMap.getCoverageSummary()];
const thresholdsToUpdate = [];
for (const key of THRESHOLD_KEYS) {
const threshold = thresholds[key] || 100;
const actual = Math.min(...summaries.map((summary) => summary[key].pct));
if (actual > threshold)
thresholdsToUpdate.push([key, actual]);
updateThresholds({ thresholds: allThresholds, perFile, configurationFile }) {
let updatedThresholds = false;
const config = configurationFile.read();
assertConfigurationModule(config);
for (const { coverageMap, thresholds, name } of allThresholds) {
const summaries = perFile ? coverageMap.files().map((file) => coverageMap.fileCoverageFor(file).toSummary()) : [coverageMap.getCoverageSummary()];
const thresholdsToUpdate = [];
for (const key of THRESHOLD_KEYS) {
const threshold = thresholds[key] ?? 100;
const actual = Math.min(...summaries.map((summary) => summary[key].pct));
if (actual > threshold)
thresholdsToUpdate.push([key, actual]);
}
if (thresholdsToUpdate.length === 0)
continue;
updatedThresholds = true;
for (const [threshold, newValue] of thresholdsToUpdate) {
if (name === GLOBAL_THRESHOLDS_KEY) {
config.test.coverage.thresholds[threshold] = newValue;
} else {
const glob = config.test.coverage.thresholds[name];
glob[threshold] = newValue;
}
}
}
if (thresholdsToUpdate.length === 0)
return;
const originalConfig = readFileSync(configurationFile, "utf8");
let updatedConfig = originalConfig;
for (const [threshold, newValue] of thresholdsToUpdate) {
const previousThreshold = (thresholds[threshold] || 100).toString();
const pattern = new RegExp(`(${threshold}\\s*:\\s*)${previousThreshold.replace(".", "\\.")}`);
const matches = originalConfig.match(pattern);
if (matches)
updatedConfig = updatedConfig.replace(matches[0], matches[1] + newValue);
else
console.error(`Unable to update coverage threshold ${threshold}. No threshold found using pattern ${pattern}`);
}
if (updatedConfig !== originalConfig) {
if (updatedThresholds) {
console.log("Updating thresholds to configuration file. You may want to push with updated coverage thresholds.");
writeFileSync(configurationFile, updatedConfig, "utf-8");
configurationFile.write();
}
}
/**
* Checked collected coverage against configured thresholds. Sets exit code to 1 when thresholds not reached.
* Check collected coverage against configured thresholds. Sets exit code to 1 when thresholds not reached.
*/
checkThresholds({ coverageMap, thresholds, perFile }) {
const summaries = perFile ? coverageMap.files().map((file) => ({
file,
summary: coverageMap.fileCoverageFor(file).toSummary()
})) : [{
file: null,
summary: coverageMap.getCoverageSummary()
}];
for (const { summary, file } of summaries) {
for (const thresholdKey of ["lines", "functions", "statements", "branches"]) {
const threshold = thresholds[thresholdKey];
if (threshold !== void 0) {
const coverage = summary.data[thresholdKey].pct;
if (coverage < threshold) {
process.exitCode = 1;
let errorMessage = `ERROR: Coverage for ${thresholdKey} (${coverage}%) does not meet`;
if (!perFile)
errorMessage += " global";
errorMessage += ` threshold (${threshold}%)`;
if (perFile && file)
errorMessage += ` for ${relative("./", file).replace(/\\/g, "/")}`;
console.error(errorMessage);
checkThresholds({ thresholds: allThresholds, perFile }) {
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;
const summaries = perFile ? coverageMap.files().map((file) => ({
file,
summary: coverageMap.fileCoverageFor(file).toSummary()
})) : [{
file: null,
summary: coverageMap.getCoverageSummary()
}];
for (const { summary, file } of summaries) {
for (const thresholdKey of ["lines", "functions", "statements", "branches"]) {
const threshold = thresholds[thresholdKey];
if (threshold !== void 0) {
const coverage = summary.data[thresholdKey].pct;
if (coverage < threshold) {
process.exitCode = 1;
let errorMessage = `ERROR: Coverage for ${thresholdKey} (${coverage}%) does not meet ${name === GLOBAL_THRESHOLDS_KEY ? name : `"${name}"`} threshold (${threshold}%)`;
if (perFile && file)
errorMessage += ` for ${relative("./", file).replace(/\\/g, "/")}`;
console.error(errorMessage);
}
}

@@ -70,2 +76,46 @@ }

/**
* 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, thresholds, createCoverageMap }) {
const resolvedThresholds = [];
const files = coverageMap.files();
const filesMatchedByGlobs = [];
const globalCoverageMap = createCoverageMap();
for (const key of Object.keys(thresholds)) {
if (key === "perFile" || key === "autoUpdate" || key === "100" || THRESHOLD_KEYS.includes(key))
continue;
const glob = key;
const globThresholds = resolveGlobThresholds(thresholds[glob]);
const globCoverageMap = createCoverageMap();
const matchingFiles = files.filter((file) => mm.isMatch(file, glob));
filesMatchedByGlobs.push(...matchingFiles);
for (const file of matchingFiles) {
const fileCoverage = coverageMap.fileCoverageFor(file);
globCoverageMap.addFileCoverage(fileCoverage);
}
resolvedThresholds.push({
name: glob,
coverageMap: globCoverageMap,
thresholds: globThresholds
});
}
for (const file of files.filter((file2) => !filesMatchedByGlobs.includes(file2))) {
const fileCoverage = coverageMap.fileCoverageFor(file);
globalCoverageMap.addFileCoverage(fileCoverage);
}
resolvedThresholds.unshift({
name: GLOBAL_THRESHOLDS_KEY,
coverageMap: globalCoverageMap,
thresholds: {
branches: thresholds.branches,
functions: thresholds.functions,
lines: thresholds.lines,
statements: thresholds.statements
}
});
return resolvedThresholds;
}
/**
* Resolve reporters from various configuration options

@@ -87,3 +137,22 @@ */

}
function resolveGlobThresholds(thresholds) {
if (!thresholds || typeof thresholds !== "object")
return {};
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 {
if (typeof config.test.coverage.thresholds !== "object")
throw new Error("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}`);
}
}
export { BaseCoverageProvider };
import { isatty } from 'node:tty';
import { createRequire } from 'node:module';
import util from 'node:util';
import timers from 'node:timers';
import { performance } from 'node:perf_hooks';
import { startTests } from '@vitest/runner';
import { setupColors, createColors } from '@vitest/utils';
import { V as VitestSnapshotEnvironment, s as setupChaiConfig, r as resolveTestRunner } from './vendor-index.3e351f42.js';
import { s as startCoverageInsideWorker, a as stopCoverageInsideWorker } from './vendor-coverage.78040316.js';
import { g as getWorkerState } from './vendor-global.97e4527c.js';
import { i as index } from './vendor-index.7646b3af.js';
import { V as VitestSnapshotEnvironment, s as setupChaiConfig, r as resolveTestRunner } from './vendor/index.h0j9y5vy.js';
import { s as startCoverageInsideWorker, a as stopCoverageInsideWorker } from './vendor/coverage.v6aD8iAh.js';
import { g as getWorkerState } from './vendor/global.L7JRz1qU.js';
import { i as index } from './vendor/index.VL3WbvjT.js';
import { setupCommonEnv } from './browser.js';

@@ -14,19 +16,19 @@ import 'chai';

import 'pathe';
import './vendor-paths.84fc7a99.js';
import './paths.js';
import 'node:url';
import './vendor-rpc.cbd8e972.js';
import './vendor-vi.6873a1c1.js';
import './vendor/rpc.Bl-ysZIr.js';
import './vendor/benchmark.WVm6DARl.js';
import '@vitest/runner/utils';
import './vendor-index.29282562.js';
import './vendor/index.XU72Rmy8.js';
import 'std-env';
import './vendor-_commonjsHelpers.7d1333e8.js';
import './vendor/run-once.X3E7xx3F.js';
import './vendor/vi.JXuS6emb.js';
import './vendor/_commonjsHelpers.jjO7Zipk.js';
import '@vitest/expect';
import '@vitest/snapshot';
import '@vitest/utils/error';
import './vendor-tasks.f9d75aed.js';
import './vendor/tasks.IknbGB2n.js';
import '@vitest/utils/source-map';
import 'util';
import './vendor-date.6e993429.js';
import './vendor/date.Ns1pGd_X.js';
import '@vitest/spy';
import './vendor-run-once.3e5ef7d7.js';

@@ -49,2 +51,6 @@ async function run(files, config, executor) {

}
globalThis.__vitest_required__ = {
util,
timers
};
await startCoverageInsideWorker(config.coverage, executor);

@@ -51,0 +57,0 @@ if (config.chaiConfig)

import { performance } from 'node:perf_hooks';
import { startTests } from '@vitest/runner';
import './vendor-index.29282562.js';
import { d as globalExpect, r as resetModules, v as vi } from './vendor-vi.6873a1c1.js';
import { s as startCoverageInsideWorker, a as stopCoverageInsideWorker } from './vendor-coverage.78040316.js';
import { V as VitestSnapshotEnvironment, s as setupChaiConfig, r as resolveTestRunner } from './vendor-index.3e351f42.js';
import './vendor/index.XU72Rmy8.js';
import { a as globalExpect, r as resetModules, v as vi } from './vendor/vi.JXuS6emb.js';
import { s as startCoverageInsideWorker, a as stopCoverageInsideWorker } from './vendor/coverage.v6aD8iAh.js';
import { V as VitestSnapshotEnvironment, s as setupChaiConfig, r as resolveTestRunner } from './vendor/index.h0j9y5vy.js';
import { createRequire } from 'node:module';
import util from 'node:util';
import timers from 'node:timers';
import { isatty } from 'node:tty';
import { installSourcemapsSupport } from 'vite-node/source-map';
import { setupColors, createColors, getSafeTimers } from '@vitest/utils';
import { i as index } from './vendor-index.7646b3af.js';
import { i as index } from './vendor/index.VL3WbvjT.js';
import { setupCommonEnv } from './browser.js';
import { g as getWorkerState } from './vendor-global.97e4527c.js';
import { g as getWorkerState } from './vendor/global.L7JRz1qU.js';
import 'pathe';

@@ -18,16 +20,16 @@ import 'std-env';

import 'chai';
import './vendor-_commonjsHelpers.7d1333e8.js';
import './vendor/_commonjsHelpers.jjO7Zipk.js';
import '@vitest/expect';
import '@vitest/snapshot';
import '@vitest/utils/error';
import './vendor-tasks.f9d75aed.js';
import './vendor/tasks.IknbGB2n.js';
import '@vitest/utils/source-map';
import 'util';
import './vendor-date.6e993429.js';
import './vendor/date.Ns1pGd_X.js';
import '@vitest/spy';
import '@vitest/snapshot/environment';
import './vendor-paths.84fc7a99.js';
import './paths.js';
import 'node:url';
import './vendor-rpc.cbd8e972.js';
import './vendor-run-once.3e5ef7d7.js';
import './vendor/rpc.Bl-ysZIr.js';
import './vendor/benchmark.WVm6DARl.js';
import './vendor/run-once.X3E7xx3F.js';

@@ -58,2 +60,6 @@ let globalSetup = false;

}
globalThis.__vitest_required__ = {
util,
timers
};
installSourcemapsSupport({

@@ -65,3 +71,3 @@ getSourceMap: (source) => state.moduleCache.getSourceMap(source)

async function setupConsoleLogSpy(state) {
const { createCustomConsole } = await import('./chunk-runtime-console.ea222ffb.js');
const { createCustomConsole } = await import('./chunks/runtime-console.hf2msWA9.js');
globalThis.console = createCustomConsole(state);

@@ -99,5 +105,8 @@ }

await withEnv(environment, environment.options || config.environmentOptions || {}, async () => {
var _a, _b, _c, _d;
workerState.durations.environment = performance.now() - workerState.durations.environment;
for (const file of files) {
if (config.isolate) {
const isIsolatedThreads = config.pool === "threads" && (((_b = (_a = config.poolOptions) == null ? void 0 : _a.threads) == null ? void 0 : _b.isolate) ?? true);
const isIsolatedForks = config.pool === "forks" && (((_d = (_c = config.poolOptions) == null ? void 0 : _c.forks) == null ? void 0 : _d.isolate) ?? true);
if (isIsolatedThreads || isIsolatedForks) {
workerState.mockMap.clear();

@@ -104,0 +113,0 @@ resetModules(workerState.moduleCache, true);

@@ -1,2 +0,2 @@

import { E as Environment } from './reporters-5f784f42.js';
import { E as Environment } from './reporters-LLiOBu3g.js';
import 'vite';

@@ -14,3 +14,2 @@ import '@vitest/runner';

import 'node:worker_threads';
import 'rollup';
import 'node:fs';

@@ -17,0 +16,0 @@ import 'chai';

@@ -1,15 +0,3 @@

export { e as builtinEnvironments, p as populateGlobal } from './vendor-environments.7aba93d9.js';
import 'pathe';
import './vendor-index.0b5b3600.js';
import 'acorn';
import 'node:module';
import 'node:fs';
import 'node:url';
import 'node:assert';
import 'node:process';
import 'node:path';
import 'node:v8';
import 'node:util';
import 'vite-node/client';
export { e as builtinEnvironments, p as populateGlobal } from './vendor/environments.hTqxBFDN.js';
import 'node:console';
import 'local-pkg';
import vm from 'node:vm';
import { ViteNodeRunner } from 'vite-node/client';
import { ViteNodeRunnerOptions } from 'vite-node';
import { ag as PendingSuiteMock, ah as MockFactory, Z as WorkerGlobalState, ai as MockMap, K as RuntimeRPC } from './reporters-5f784f42.js';
import { am as PendingSuiteMock, an as MockFactory, ao as MockMap, a2 as WorkerGlobalState, g as RuntimeRPC } from './reporters-LLiOBu3g.js';
import 'vite';

@@ -15,3 +15,2 @@ import '@vitest/runner';

import 'node:worker_threads';
import 'rollup';
import 'node:fs';

@@ -130,3 +129,3 @@ import 'chai';

};
get state(): WorkerGlobalState;
get state(): any;
shouldResolveId(id: string, _importee?: string | undefined): boolean;

@@ -133,0 +132,0 @@ originalResolveUrl(id: string, importer?: string): Promise<[url: string, fsPath: string]>;

@@ -1,2 +0,2 @@

export { V as VitestExecutor } from './vendor-execute.07d1a420.js';
export { V as VitestExecutor } from './vendor/execute.ILey0jnF.js';
import 'node:url';

@@ -8,9 +8,8 @@ import 'node:vm';

import '@vitest/utils/error';
import './vendor-paths.84fc7a99.js';
import './vendor-global.97e4527c.js';
import './paths.js';
import 'node:fs';
import '@vitest/utils';
import './vendor-base.9c08bbd0.js';
import './vendor/base._79unx2z.js';
import 'node:path';
import 'node:module';
import 'vite-node/constants';

@@ -1,9 +0,10 @@

import { Test, File, TaskResultPack, CancelReason } from '@vitest/runner';
export { DoneCallback, File, HookCleanupCallback, HookListener, OnTestFailedHandler, RunMode, RuntimeContext, SequenceHooks, SequenceSetupFiles, Suite, SuiteAPI, SuiteCollector, SuiteFactory, SuiteHooks, Task, TaskBase, TaskMeta, TaskResult, TaskResultPack, TaskState, Test, TestAPI, TestContext, TestFunction, TestOptions, afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, suite, test } from '@vitest/runner';
import { h as BenchmarkAPI, F as FakeTimerInstallOpts, M as MockFactoryWithHelper, i as RuntimeConfig, A as AfterSuiteRunMeta, j as UserConsoleLog, R as ResolvedConfig, k as ModuleGraphData, l as Reporter } from './reporters-5f784f42.js';
export { x as ApiConfig, a1 as ArgumentsType, a0 as Arrayable, _ as Awaitable, B as BaseCoverageOptions, af as BenchFunction, ad as Benchmark, ae as BenchmarkResult, ac as BenchmarkUserOptions, t as BuiltinEnvironment, w as CSSModuleScopeStrategy, o as CollectLineNumbers, p as CollectLines, a3 as Constructable, r as Context, Q as ContextRPC, N as ContextTestEnvironment, aa as CoverageIstanbulOptions, e as CoverageOptions, f as CoverageProvider, g as CoverageProviderModule, a9 as CoverageReporter, C as CoverageV8Options, ab as CustomProviderOptions, D as DepsOptimizationOptions, E as Environment, y as EnvironmentOptions, a5 as EnvironmentReturn, H as HappyDOMOptions, I as InlineConfig, J as JSDOMOptions, a4 as ModuleCache, a2 as MutableArray, $ as Nullable, a7 as OnServerRestartHandler, P as ProjectConfig, m as RawErrsMap, a8 as ReportContext, X as ResolveIdFunction, a as ResolvedCoverageOptions, O as ResolvedTestEnvironment, q as RootAndTarget, L as RunnerRPC, K as RuntimeRPC, z as TransformModePatterns, n as TscErrorInfo, G as TypecheckConfig, U as UserConfig, b as Vitest, u as VitestEnvironment, v as VitestPool, V as VitestRunMode, a6 as VmEnvironmentReturn, S as WorkerContext, Z as WorkerGlobalState, Y as WorkerRPC } from './reporters-5f784f42.js';
import { TaskPopulated, File, TaskResultPack, CancelReason } from '@vitest/runner';
export { Custom, DoneCallback, ExtendedContext, File, HookCleanupCallback, HookListener, OnTestFailedHandler, RunMode, RuntimeContext, SequenceHooks, SequenceSetupFiles, Suite, SuiteAPI, SuiteCollector, SuiteFactory, SuiteHooks, Task, TaskBase, TaskContext, TaskCustomOptions, TaskMeta, TaskResult, TaskResultPack, TaskState, Test, TestAPI, TestContext, TestFunction, TestOptions, afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, suite, test } from '@vitest/runner';
export { b as bench } from './suite-SvxfaIxW.js';
import { ExpectStatic } from '@vitest/expect';
export { Assertion, AsymmetricMatchersContaining, ExpectStatic, JestAssertion } from '@vitest/expect';
import { spyOn, fn, MaybeMockedDeep, MaybeMocked, MaybePartiallyMocked, MaybePartiallyMockedDeep, EnhancedSpy } from '@vitest/spy';
export { EnhancedSpy, Mock, MockContext, MockInstance, Mocked, MockedClass, MockedFunction, MockedObject, SpyInstance } from '@vitest/spy';
import { F as FakeTimerInstallOpts, M as MockFactoryWithHelper, n as RuntimeConfig, f as ProvidedContext, A as AfterSuiteRunMeta, o as UserConsoleLog, R as ResolvedConfig, p as ModuleGraphData, q as Reporter } from './reporters-LLiOBu3g.js';
export { K as ApiConfig, a6 as ArgumentsType, a5 as Arrayable, a3 as Awaitable, B as BaseCoverageOptions, ak as BenchFunction, ai as Benchmark, al as BenchmarkAPI, aj as BenchmarkResult, ah as BenchmarkUserOptions, D as BuiltinEnvironment, I as CSSModuleScopeStrategy, u as CollectLineNumbers, v as CollectLines, a8 as Constructable, x as Context, _ as ContextRPC, Y as ContextTestEnvironment, af as CoverageIstanbulOptions, b as CoverageOptions, c as CoverageProvider, d as CoverageProviderModule, ae as CoverageReporter, C as CoverageV8Options, ag as CustomProviderOptions, N as DepsOptimizationOptions, E as Environment, L as EnvironmentOptions, aa as EnvironmentReturn, H as HappyDOMOptions, Q as InlineConfig, J as JSDOMOptions, a9 as ModuleCache, a7 as MutableArray, a4 as Nullable, ac as OnServerRestartHandler, y as Pool, z as PoolOptions, P as ProjectConfig, r as RawErrsMap, ad as ReportContext, a0 as ResolveIdFunction, a as ResolvedCoverageOptions, Z as ResolvedTestEnvironment, w as RootAndTarget, X as RunnerRPC, g as RuntimeRPC, O as TransformModePatterns, t as TscErrorInfo, S as TypecheckConfig, U as UserConfig, e as Vitest, G as VitestEnvironment, V as VitestRunMode, ab as VmEnvironmentReturn, $ as WorkerContext, a2 as WorkerGlobalState, a1 as WorkerRPC } from './reporters-LLiOBu3g.js';
import { spyOn, fn, MaybeMockedDeep, MaybeMocked, MaybePartiallyMocked, MaybePartiallyMockedDeep, MockInstance } from '@vitest/spy';
export { Mock, MockContext, MockInstance, Mocked, MockedClass, MockedFunction, MockedObject, SpyInstance } from '@vitest/spy';
export { SnapshotEnvironment } from '@vitest/snapshot/environment';

@@ -20,4 +21,4 @@ import { SnapshotResult } from '@vitest/snapshot';

export { Bench as BenchFactory, Options as BenchOptions, Task as BenchTask, TaskResult as BenchTaskResult } from 'tinybench';
import '@vitest/runner/utils';
import 'vite-node';
import '@vitest/runner/utils';
import 'vite-node/client';

@@ -27,3 +28,2 @@ import '@vitest/snapshot/manager';

import 'node:worker_threads';
import 'rollup';
import 'node:fs';

@@ -39,2 +39,15 @@

declare type IsUnknown<T> = [unknown] extends [T] ? Not<IsAny<T>> : false;
declare type PrintType<T> = IsUnknown<T> extends true ? 'unknown' : IsNever<T> extends true ? 'never' : IsAny<T> extends true ? never : boolean extends T ? 'boolean' : T extends boolean ? `literal boolean: ${T}` : string extends T ? 'string' : T extends string ? `literal string: ${T}` : number extends T ? 'number' : T extends number ? `literal number: ${T}` : T extends null ? 'null' : T extends undefined ? 'undefined' : T extends (...args: any[]) => any ? 'function' : '...';
/** Subjective "useful" keys from a type. For objects it's just `keyof` but for tuples/arrays it's the number keys
* @example
* UsefulKeys<{a: 1; b: 2}> // 'a' | 'b'
* UsefulKeys<['a', 'b']> // '0' | '1'
* UsefulKeys<string[]> // number
*/
declare type UsefulKeys<T> = T extends any[] ? {
[K in keyof T]: K;
}[number] : keyof T;
declare type MismatchInfo<Actual, Expected> = And<[Extends<PrintType<Actual>, '...'>, Not<IsAny<Actual>>]> extends true ? And<[Extends<any[], Actual>, Extends<any[], Expected>]> extends true ? Array<MismatchInfo<Extract<Actual, any[]>[number], Extract<Expected, any[]>[number]>> : {
[K in UsefulKeys<Actual> | UsefulKeys<Expected>]: MismatchInfo<K extends keyof Actual ? Actual[K] : never, K extends keyof Expected ? Expected[K] : never>;
} : StrictEqualUsingBranding<Actual, Expected> extends true ? Actual : `Expected: ${PrintType<Expected>}, Actual: ${PrintType<Exclude<Actual, Expected>>}`;
/**

@@ -47,2 +60,5 @@ * Recursively walk a type and replace it with a branded type related to the original. This is useful for

* - `{ a?: string }` vs `{ a: string | undefined }`
*
* Note: not very performant for complex types - this should only be used when you know you need it. If doing
* an equality check, it's almost always better to use `StrictEqualUsingTSInternalIdenticalToOperator`.
*/

@@ -67,2 +83,3 @@ declare type DeepBrand<T> = IsNever<T> extends true ? {

this: DeepBrand<ThisParameterType<T>>;
props: DeepBrand<Omit<T, keyof Function>>;
} : T extends any[] ? {

@@ -95,39 +112,158 @@ type: 'array';

declare type ReadonlyEquivalent<X, Y> = Extends<(<T>() => T extends X ? true : false), (<T>() => T extends Y ? true : false)>;
/** Returns true if `L extends R`. Explicitly checks for `never` since that can give unexpected results. */
declare type Extends<L, R> = IsNever<L> extends true ? IsNever<R> : [L] extends [R] ? true : false;
declare type StrictExtends<L, R> = Extends<DeepBrand<L>, DeepBrand<R>>;
declare type StrictEqual<L, R> = (<T>() => T extends (L & T) | T ? true : false) extends <T>() => T extends (R & T) | T ? true : false ? IsNever<L> extends IsNever<R> ? true : false : false;
declare type Equal<Left, Right, Branded = true> = Branded extends true ? And<[StrictExtends<Left, Right>, StrictExtends<Right, Left>]> : StrictEqual<Left, Right>;
declare type ExtendsUsingBranding<L, R> = Extends<DeepBrand<L>, DeepBrand<R>>;
declare type ExtendsExcludingAnyOrNever<L, R> = IsAny<L> extends true ? IsAny<R> : Extends<L, R>;
declare type StrictEqualUsingTSInternalIdenticalToOperator<L, R> = (<T>() => T extends (L & T) | T ? true : false) extends <T>() => T extends (R & T) | T ? true : false ? IsNever<L> extends IsNever<R> ? true : false : false;
declare type StrictEqualUsingBranding<Left, Right> = And<[
ExtendsUsingBranding<Left, Right>,
ExtendsUsingBranding<Right, Left>
]>;
declare type Params<Actual> = Actual extends (...args: infer P) => any ? P : never;
declare type ConstructorParams<Actual> = Actual extends new (...args: infer P) => any ? Actual extends new () => any ? P | [] : P : never;
declare type MismatchArgs<ActualResult extends boolean, ExpectedResult extends boolean> = Eq<ActualResult, ExpectedResult> extends true ? [] : [never];
interface ExpectTypeOfOptions {
declare const mismatch: unique symbol;
declare type Mismatch = {
[mismatch]: 'mismatch';
};
/** A type which should match anything passed as a value but *doesn't* match `Mismatch` - helps TypeScript select the right overload for `toEqualTypeOf` and `toMatchTypeOf`. */
declare const avalue: unique symbol;
declare type AValue = {
[avalue]?: undefined;
} | string | number | boolean | symbol | bigint | null | undefined | void;
declare type MismatchArgs<ActualResult extends boolean, ExpectedResult extends boolean> = Eq<ActualResult, ExpectedResult> extends true ? [] : [Mismatch];
declare const inverted: unique symbol;
declare type Inverted<T> = {
[inverted]: T;
};
declare const expectNull: unique symbol;
declare type ExpectNull<T> = {
[expectNull]: T;
result: ExtendsExcludingAnyOrNever<T, null>;
};
declare const expectUndefined: unique symbol;
declare type ExpectUndefined<T> = {
[expectUndefined]: T;
result: ExtendsExcludingAnyOrNever<T, undefined>;
};
declare const expectNumber: unique symbol;
declare type ExpectNumber<T> = {
[expectNumber]: T;
result: ExtendsExcludingAnyOrNever<T, number>;
};
declare const expectString: unique symbol;
declare type ExpectString<T> = {
[expectString]: T;
result: ExtendsExcludingAnyOrNever<T, string>;
};
declare const expectBoolean: unique symbol;
declare type ExpectBoolean<T> = {
[expectBoolean]: T;
result: ExtendsExcludingAnyOrNever<T, boolean>;
};
declare const expectVoid: unique symbol;
declare type ExpectVoid<T> = {
[expectVoid]: T;
result: ExtendsExcludingAnyOrNever<T, void>;
};
declare const expectFunction: unique symbol;
declare type ExpectFunction<T> = {
[expectFunction]: T;
result: ExtendsExcludingAnyOrNever<T, (...args: any[]) => any>;
};
declare const expectObject: unique symbol;
declare type ExpectObject<T> = {
[expectObject]: T;
result: ExtendsExcludingAnyOrNever<T, object>;
};
declare const expectArray: unique symbol;
declare type ExpectArray<T> = {
[expectArray]: T;
result: ExtendsExcludingAnyOrNever<T, any[]>;
};
declare const expectSymbol: unique symbol;
declare type ExpectSymbol<T> = {
[expectSymbol]: T;
result: ExtendsExcludingAnyOrNever<T, symbol>;
};
declare const expectAny: unique symbol;
declare type ExpectAny<T> = {
[expectAny]: T;
result: IsAny<T>;
};
declare const expectUnknown: unique symbol;
declare type ExpectUnknown<T> = {
[expectUnknown]: T;
result: IsUnknown<T>;
};
declare const expectNever: unique symbol;
declare type ExpectNever<T> = {
[expectNever]: T;
result: IsNever<T>;
};
declare const expectNullable: unique symbol;
declare type ExpectNullable<T> = {
[expectNullable]: T;
result: Not<StrictEqualUsingBranding<T, NonNullable<T>>>;
};
declare type Scolder<Expecter extends {
result: boolean;
}, Options extends {
positive: boolean;
branded: boolean;
}
interface ExpectTypeOf<Actual, Options extends ExpectTypeOfOptions> {
toBeAny: (...MISMATCH: MismatchArgs<IsAny<Actual>, Options['positive']>) => true;
toBeUnknown: (...MISMATCH: MismatchArgs<IsUnknown<Actual>, Options['positive']>) => true;
toBeNever: (...MISMATCH: MismatchArgs<IsNever<Actual>, Options['positive']>) => true;
toBeFunction: (...MISMATCH: MismatchArgs<Extends<Actual, (...args: any[]) => any>, Options['positive']>) => true;
toBeObject: (...MISMATCH: MismatchArgs<Extends<Actual, object>, Options['positive']>) => true;
toBeArray: (...MISMATCH: MismatchArgs<Extends<Actual, any[]>, Options['positive']>) => true;
toBeNumber: (...MISMATCH: MismatchArgs<Extends<Actual, number>, Options['positive']>) => true;
toBeString: (...MISMATCH: MismatchArgs<Extends<Actual, string>, Options['positive']>) => true;
toBeBoolean: (...MISMATCH: MismatchArgs<Extends<Actual, boolean>, Options['positive']>) => true;
toBeVoid: (...MISMATCH: MismatchArgs<Extends<Actual, void>, Options['positive']>) => true;
toBeSymbol: (...MISMATCH: MismatchArgs<Extends<Actual, symbol>, Options['positive']>) => true;
toBeNull: (...MISMATCH: MismatchArgs<Extends<Actual, null>, Options['positive']>) => true;
toBeUndefined: (...MISMATCH: MismatchArgs<Extends<Actual, undefined>, Options['positive']>) => true;
toBeNullable: (...MISMATCH: MismatchArgs<Not<Equal<Actual, NonNullable<Actual>, Options['branded']>>, Options['positive']>) => true;
}> = Expecter['result'] extends Options['positive'] ? () => true : Options['positive'] extends true ? Expecter : Inverted<Expecter>;
interface PositiveExpectTypeOf<Actual> extends BaseExpectTypeOf<Actual, {
positive: true;
branded: false;
}> {
toEqualTypeOf: {
<Expected extends StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected> extends true ? unknown : MismatchInfo<Actual, Expected>>(value: Expected & AValue, // reason for `& AValue`: make sure this is only the selected overload when the end-user passes a value for an inferred typearg. The `Mismatch` type does match `AValue`.
...MISMATCH: MismatchArgs<StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected>, true>): true;
<Expected extends StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected> extends true ? unknown : MismatchInfo<Actual, Expected>>(...MISMATCH: MismatchArgs<StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected>, true>): true;
};
toMatchTypeOf: {
<Expected>(...MISMATCH: MismatchArgs<Extends<Actual, Expected>, Options['positive']>): true;
<Expected>(expected: Expected, ...MISMATCH: MismatchArgs<Extends<Actual, Expected>, Options['positive']>): true;
<Expected extends Extends<Actual, Expected> extends true ? unknown : MismatchInfo<Actual, Expected>>(value: Expected & AValue, // reason for `& AValue`: make sure this is only the selected overload when the end-user passes a value for an inferred typearg. The `Mismatch` type does match `AValue`.
...MISMATCH: MismatchArgs<Extends<Actual, Expected>, true>): true;
<Expected extends Extends<Actual, Expected> extends true ? unknown : MismatchInfo<Actual, Expected>>(...MISMATCH: MismatchArgs<Extends<Actual, Expected>, true>): true;
};
toHaveProperty: <K extends keyof Actual>(key: K, ...MISMATCH: MismatchArgs<Extends<K, keyof Actual>, true>) => K extends keyof Actual ? PositiveExpectTypeOf<Actual[K]> : true;
not: NegativeExpectTypeOf<Actual>;
branded: {
toEqualTypeOf: <Expected extends StrictEqualUsingBranding<Actual, Expected> extends true ? unknown : MismatchInfo<Actual, Expected>>(...MISMATCH: MismatchArgs<StrictEqualUsingBranding<Actual, Expected>, true>) => true;
};
}
interface NegativeExpectTypeOf<Actual> extends BaseExpectTypeOf<Actual, {
positive: false;
}> {
toEqualTypeOf: {
<Expected>(...MISMATCH: MismatchArgs<Equal<Actual, Expected, Options['branded']>, Options['positive']>): true;
<Expected>(expected: Expected, ...MISMATCH: MismatchArgs<Equal<Actual, Expected, Options['branded']>, Options['positive']>): true;
<Expected>(value: Expected & AValue, ...MISMATCH: MismatchArgs<StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected>, false>): true;
<Expected>(...MISMATCH: MismatchArgs<StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected>, false>): true;
};
toMatchTypeOf: {
<Expected>(value: Expected & AValue, // reason for `& AValue`: make sure this is only the selected overload when the end-user passes a value for an inferred typearg. The `Mismatch` type does match `AValue`.
...MISMATCH: MismatchArgs<Extends<Actual, Expected>, false>): true;
<Expected>(...MISMATCH: MismatchArgs<Extends<Actual, Expected>, false>): true;
};
toHaveProperty: <K extends string | number | symbol>(key: K, ...MISMATCH: MismatchArgs<Extends<K, keyof Actual>, false>) => true;
}
declare type ExpectTypeOf<Actual, Options extends {
positive: boolean;
}> = Options['positive'] extends true ? PositiveExpectTypeOf<Actual> : NegativeExpectTypeOf<Actual>;
interface BaseExpectTypeOf<Actual, Options extends {
positive: boolean;
}> {
toBeAny: Scolder<ExpectAny<Actual>, Options>;
toBeUnknown: Scolder<ExpectUnknown<Actual>, Options>;
toBeNever: Scolder<ExpectNever<Actual>, Options>;
toBeFunction: Scolder<ExpectFunction<Actual>, Options>;
toBeObject: Scolder<ExpectObject<Actual>, Options>;
toBeArray: Scolder<ExpectArray<Actual>, Options>;
toBeNumber: Scolder<ExpectNumber<Actual>, Options>;
toBeString: Scolder<ExpectString<Actual>, Options>;
toBeBoolean: Scolder<ExpectBoolean<Actual>, Options>;
toBeVoid: Scolder<ExpectVoid<Actual>, Options>;
toBeSymbol: Scolder<ExpectSymbol<Actual>, Options>;
toBeNull: Scolder<ExpectNull<Actual>, Options>;
toBeUndefined: Scolder<ExpectUndefined<Actual>, Options>;
toBeNullable: Scolder<ExpectNullable<Actual>, Options>;
toBeCallableWith: Options['positive'] extends true ? (...args: Params<Actual>) => true : never;
toBeConstructibleWith: Options['positive'] extends true ? (...args: ConstructorParams<Actual>) => true : never;
toHaveProperty: <K extends string>(key: K, ...MISMATCH: MismatchArgs<Extends<K, keyof Actual>, Options['positive']>) => K extends keyof Actual ? ExpectTypeOf<Actual[K], Options> : true;
extract: <V>(v?: V) => ExpectTypeOf<Extract<Actual, V>, Options>;

@@ -145,10 +281,2 @@ exclude: <V>(v?: V) => ExpectTypeOf<Exclude<Actual, V>, Options>;

asserts: Actual extends (v: any, ...args: any[]) => asserts v is infer T ? unknown extends T ? never : ExpectTypeOf<T, Options> : never;
branded: Omit<ExpectTypeOf<Actual, {
positive: Options['positive'];
branded: true;
}>, 'branded'>;
not: Omit<ExpectTypeOf<Actual, {
positive: Not<Options['positive']>;
branded: Options['branded'];
}>, 'not'>;
}

@@ -194,4 +322,2 @@ declare type _ExpectTypeOf = {

declare const bench: BenchmarkAPI;
/**

@@ -201,3 +327,3 @@ * This utils allows computational intensive tasks to only be ran once

*
* Currently only works with `isolate: false`
* Currently only works with `poolOptions.<pool>.isolate: false`
*

@@ -217,3 +343,3 @@ * @experimental

declare function createExpect(test?: Test): ExpectStatic;
declare function createExpect(test?: TaskPopulated): ExpectStatic;
declare const globalExpect: ExpectStatic;

@@ -238,50 +364,194 @@

}
declare function waitUntil<T>(callback: WaitUntilCallback<T>, options?: number | WaitUntilOptions): Promise<T>;
type Truthy<T> = T extends false | '' | 0 | null | undefined ? never : T;
declare function waitUntil<T>(callback: WaitUntilCallback<T>, options?: number | WaitUntilOptions): Promise<Truthy<T>>;
type ESModuleExports = Record<string, unknown>;
interface VitestUtils {
/**
* Checks if fake timers are enabled.
*/
isFakeTimers(): boolean;
useFakeTimers(config?: FakeTimerInstallOpts): this;
useRealTimers(): this;
runOnlyPendingTimers(): this;
runOnlyPendingTimersAsync(): Promise<this>;
runAllTimers(): this;
runAllTimersAsync(): Promise<this>;
runAllTicks(): this;
advanceTimersByTime(ms: number): this;
advanceTimersByTimeAsync(ms: number): Promise<this>;
advanceTimersToNextTimer(): this;
advanceTimersToNextTimerAsync(): Promise<this>;
/**
* This method wraps all further calls to timers until [`vi.useRealTimers()`](https://vitest.dev/api/vi#vi-userealtimers) is called.
*/
useFakeTimers(config?: FakeTimerInstallOpts): VitestUtils;
/**
* Restores mocked timers to their original implementations. All timers that were scheduled before will be discarded.
*/
useRealTimers(): VitestUtils;
/**
* This method will call every timer that was initiated after [`vi.useFakeTimers`](https://vitest.dev/api/vi#vi-usefaketimers) call.
* It will not fire any timer that was initiated during its call.
*/
runOnlyPendingTimers(): VitestUtils;
/**
* This method will asynchronously call every timer that was initiated after [`vi.useFakeTimers`](https://vitest.dev/api/vi#vi-usefaketimers) call, even asynchronous ones.
* It will not fire any timer that was initiated during its call.
*/
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)).
*/
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)).
*/
runAllTimersAsync(): Promise<VitestUtils>;
/**
* Calls every microtask that was queued by `process.nextTick`. This will also run all microtasks scheduled by themselves.
*/
runAllTicks(): VitestUtils;
/**
* This method will invoke every initiated timer until the specified number of milliseconds is passed or the queue is empty - whatever comes first.
*/
advanceTimersByTime(ms: number): VitestUtils;
/**
* This method will invoke every initiated timer until the specified number of milliseconds is passed or the queue is empty - whatever comes first. This will include and await asynchronously set timers.
*/
advanceTimersByTimeAsync(ms: number): Promise<VitestUtils>;
/**
* Will call next available timer. Useful to make assertions between each timer call. You can chain call it to manage timers by yourself.
*/
advanceTimersToNextTimer(): VitestUtils;
/**
* Will call next available timer and wait until it's resolved if it was set asynchronously. Useful to make assertions between each timer call.
*/
advanceTimersToNextTimerAsync(): Promise<VitestUtils>;
/**
* Get the number of waiting timers.
*/
getTimerCount(): number;
setSystemTime(time: number | string | Date): this;
/**
* If fake timers are enabled, this method simulates a user changing the system clock (will affect date related API like `hrtime`, `performance.now` or `new Date()`) - however, it will not fire any timers.
* If fake timers are not enabled, this method will only mock `Date.*` and `new Date()` calls.
*/
setSystemTime(time: number | string | Date): VitestUtils;
/**
* Returns mocked current date that was set using `setSystemTime`. If date is not mocked the method will return `null`.
*/
getMockedSystemTime(): Date | null;
/**
* When using `vi.useFakeTimers`, `Date.now` calls are mocked. If you need to get real time in milliseconds, you can call this function.
*/
getRealSystemTime(): number;
clearAllTimers(): this;
/**
* Removes all timers that are scheduled to run. These timers will never run in the future.
*/
clearAllTimers(): 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
* const cart = {
* getApples: () => 42
* }
*
* const spy = vi.spyOn(cart, 'getApples').mockReturnValue(10)
*
* expect(cart.getApples()).toBe(10)
* expect(spy).toHaveBeenCalled()
* expect(spy).toHaveReturnedWith(10)
*/
spyOn: typeof spyOn;
/**
* Creates a spy on a function, though can be initiated without one. Every time a function is invoked, it stores its call arguments, returns, and instances. Also, you can manipulate its behavior with [methods](https://vitest.dev/api/mock).
*
* If no function is given, mock will return `undefined`, when invoked.
*
* @example
* const getApples = vi.fn(() => 0)
*
* getApples()
*
* expect(getApples).toHaveBeenCalled()
* expect(getApples).toHaveReturnedWith(0)
*
* getApples.mockReturnValueOnce(5)
*
* expect(getApples()).toBe(5)
* expect(getApples).toHaveNthReturnedWith(2, 5)
*/
fn: typeof fn;
/**
* Wait for the callback to execute successfully. If the callback throws an error or returns a rejected promise it will continue to wait until it succeeds or times out.
*
* This is very useful when you need to wait for some asynchronous action to complete, for example, when you start a server and need to wait for it to start.
*
* @example
* const server = createServer()
*
* await vi.waitFor(
* () => {
* if (!server.isReady)
* throw new Error('Server not started')
*
* console.log('Server started')
* }, {
* timeout: 500, // default is 1000
* interval: 20, // default is 50
* }
* )
*/
waitFor: typeof waitFor;
/**
* 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.
*
* @example
* const element = await vi.waitUntil(
* () => document.querySelector('.element'),
* {
* timeout: 500, // default is 1000
* interval: 20, // default is 50
* }
* )
*
* // do something with the element
* expect(element.querySelector('.element-child')).toBeTruthy()
*/
waitUntil: typeof waitUntil;
/**
* Run the factory before imports are evaluated. You can return a value from the factory
* to reuse it inside your `vi.mock` factory and tests.
* to reuse it inside your [`vi.mock`](https://vitest.dev/api/vi#vi-mock) factory and tests.
*
* If used with [`vi.mock`](https://vitest.dev/api/vi#vi-mock), both will be hoisted in the order they are defined in.
*/
hoisted<T>(factory: () => T): T;
/**
* Makes all `imports` to passed module to be mocked.
* - If there is a factory, will return it's result. The call to `vi.mock` is hoisted to the top of the file,
* so you don't have access to variables declared in the global file scope, if you didn't put them before imports!
* - If `__mocks__` folder with file of the same name exist, all imports will
* return it.
* - If there is no `__mocks__` folder or a file with the same name inside, will call original
* module and mock it.
* @param path Path to the module. Can be aliased, if your config supports it
* @param factory Factory for the mocked module. Has the highest priority.
* Mocks every import call to the module even if it was already statically imported.
*
* The call to `vi.mock` is hoisted to the top of the file, so you don't have access to variables declared in the global file scope
* unless they are defined with [`vi.hoisted`](https://vitest.dev/api/vi#vi-hoisted) before this call.
*
* 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
*/
mock(path: string, factory?: MockFactoryWithHelper): void;
/**
* Removes module from mocked registry. All subsequent calls to import will
* return original module even if it was mocked.
* @param path Path to the module. Can be aliased, if your config supports it
* Removes module from mocked registry. All calls to import will return the original module even if it was mocked before.
*
* This call is hoisted to the top of the file, so it will only unmock modules that were defined in `setupFiles`, for example.
* @param path Path to the module. Can be aliased, if your Vitest config supports it
*/
unmock(path: string): void;
doMock(path: string, factory?: () => any): void;
/**
* Mocks every subsequent [dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) call.
*
* Unlike [`vi.mock`](https://vitest.dev/api/vi#vi-mock), this method will not mock statically imported modules because it is not hoisted to the top of the file.
*
* 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
*/
doMock(path: string, factory?: MockFactoryWithHelper): void;
/**
* Removes module from mocked registry. All subsequent calls to import will return original module.
*
* Unlike [`vi.unmock`](https://vitest.dev/api/vi#vi-unmock), this method is not hoisted to the top of the file.
* @param path Path to the module. Can be aliased, if your Vitest config supports it
*/
doUnmock(path: string): void;

@@ -292,4 +562,4 @@ /**

* @example
* vi.mock('./example', async () => {
* const axios = await vi.importActual('./example')
* vi.mock('./example.js', async () => {
* const axios = await vi.importActual<typeof import('./example.js')>('./example.js')
*

@@ -299,26 +569,28 @@ * return { ...axios, get: vi.fn() }

* @param path Path to the module. Can be aliased, if your config supports it
* @returns Actual module without spies
*/
importActual<T = unknown>(path: string): Promise<T>;
importActual<T = ESModuleExports>(path: string): Promise<T>;
/**
* Imports a module with all of its properties and nested properties mocked.
* For the rules applied, see docs.
*
* Mocking algorithm is described in [documentation](https://vitest.dev/guide/mocking#modules).
* @example
* const example = await vi.importMock<typeof import('./example.js')>('./example.js')
* example.calc.mockReturnValue(10)
* expect(example.calc()).toBe(10)
* @param path Path to the module. Can be aliased, if your config supports it
* @returns Fully mocked module
*/
importMock<T>(path: string): Promise<MaybeMockedDeep<T>>;
importMock<T = ESModuleExports>(path: string): Promise<MaybeMockedDeep<T>>;
/**
* Type helpers for TypeScript. In reality just returns the object that was passed.
* 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.
* 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.
* @example
* import example from './example'
* vi.mock('./example')
* import example from './example.js'
* vi.mock('./example.js')
*
* test('1+1 equals 2' async () => {
* vi.mocked(example.calc).mockRestore()
*
* const res = example.calc(1, '+', 1)
*
* expect(res).toBe(2)
* test('1 + 1 equals 10' async () => {
* vi.mocked(example.calc).mockReturnValue(10)
* expect(example.calc(1, '+', 1)).toBe(10)
* })

@@ -348,7 +620,23 @@ * @param item Anything that can be mocked

mocked<T>(item: T): MaybeMocked<T>;
isMockFunction(fn: any): fn is EnhancedSpy;
clearAllMocks(): this;
resetAllMocks(): this;
restoreAllMocks(): this;
/**
* Checks that a given parameter is a mock function. If you are using TypeScript, it will also narrow down its type.
*/
isMockFunction(fn: any): fn is MockInstance;
/**
* Calls [`.mockClear()`](https://vitest.dev/api/mock#mockclear) on every mocked function. This will only empty `.mock` state, it will not reset implementation.
*
* It is useful if you need to clean up mock between different assertions.
*/
clearAllMocks(): VitestUtils;
/**
* Calls [`.mockReset()`](https://vitest.dev/api/mock#mockreset) on every mocked function. This will empty `.mock` state, reset "once" implementations and force the base implementation to return `undefined` when invoked.
*
* This is useful when you want to completely reset a mock to the default state.
*/
resetAllMocks(): VitestUtils;
/**
* Calls [`.mockRestore()`](https://vitest.dev/api/mock#mockrestore) on every mocked function. This will restore all original implementations.
*/
restoreAllMocks(): VitestUtils;
/**
* Makes value available on global namespace.

@@ -358,3 +646,3 @@ * Useful, if you want to have global variables available, like `IntersectionObserver`.

*/
stubGlobal(name: string | symbol | number, value: unknown): this;
stubGlobal(name: string | symbol | number, value: unknown): VitestUtils;
/**

@@ -364,13 +652,19 @@ * Changes the value of `import.meta.env` and `process.env`.

*/
stubEnv(name: string, value: string): this;
stubEnv(name: string, value: string): VitestUtils;
/**
* Reset the value to original value that was available before first `vi.stubGlobal` was called.
*/
unstubAllGlobals(): this;
unstubAllGlobals(): VitestUtils;
/**
* Reset environmental variables to the ones that were available before first `vi.stubEnv` was called.
*/
unstubAllEnvs(): this;
resetModules(): this;
unstubAllEnvs(): VitestUtils;
/**
* Resets modules registry by clearing the cache of all modules. This allows modules to be reevaluated when reimported.
* Top-level imports cannot be re-evaluated. Might be useful to isolate modules where local state conflicts between tests.
*
* This method does not reset mocks registry. To clear mocks registry, use [`vi.unmock`](https://vitest.dev/api/vi#vi-unmock) or [`vi.doUnmock`](https://vitest.dev/api/vi#vi-dounmock).
*/
resetModules(): VitestUtils;
/**
* Wait for all imports to load. Useful, if you have a synchronous call that starts

@@ -396,2 +690,8 @@ * importing a module that you cannot await otherwise.

/**
* Gives access to injected context provided from the main thread.
* This usually returns a value provided by `globalSetup` or an external library.
*/
declare function inject<T extends keyof ProvidedContext>(key: T): ProvidedContext[T];
interface TransformResultWithSource extends TransformResult {

@@ -401,2 +701,3 @@ source?: string;

interface WebSocketHandlers {
onUnhandledError(error: unknown, type: string): Promise<void>;
onCollected(files?: File[]): Promise<void>;

@@ -424,2 +725,3 @@ onTaskUpdate(packs: TaskResultPack[]): void;

updateSnapshot(file?: File): Promise<void>;
getProvidedContext(): ProvidedContext;
}

@@ -430,2 +732,2 @@ interface WebSocketEvents extends Pick<Reporter, 'onCollected' | 'onFinished' | 'onTaskUpdate' | 'onUserConsoleLog' | 'onPathsCollected'> {

export { AfterSuiteRunMeta, AssertType, BenchmarkAPI, ExpectTypeOf, ModuleGraphData, Reporter, ResolvedConfig, RuntimeConfig, TransformResultWithSource, UserConsoleLog, WebSocketEvents, WebSocketHandlers, assertType, bench, createExpect, globalExpect as expect, expectTypeOf, getRunningMode, isFirstRun, isWatchMode, runOnce, vi, vitest };
export { AfterSuiteRunMeta, type AssertType, type ExpectTypeOf, ModuleGraphData, ProvidedContext, Reporter, ResolvedConfig, RuntimeConfig, type TransformResultWithSource, UserConsoleLog, type VitestUtils, type WebSocketEvents, type WebSocketHandlers, assertType, createExpect, globalExpect as expect, expectTypeOf, getRunningMode, inject, isFirstRun, isWatchMode, runOnce, vi, vitest };
export { afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, suite, test } from '@vitest/runner';
export { e as bench, c as createExpect, d as expect, v as vi, f as vitest } from './vendor-vi.6873a1c1.js';
export { i as isFirstRun, r as runOnce } from './vendor-run-once.3e5ef7d7.js';
import { d as dist } from './vendor-index.7646b3af.js';
export { b as assertType, g as getRunningMode, a as isWatchMode } from './vendor-index.7646b3af.js';
export { b as bench } from './vendor/benchmark.WVm6DARl.js';
export { i as isFirstRun, r as runOnce } from './vendor/run-once.X3E7xx3F.js';
export { c as createExpect, a as expect, v as vi, b as vitest } from './vendor/vi.JXuS6emb.js';
import { d as dist } from './vendor/index.VL3WbvjT.js';
export { c as assertType, g as getRunningMode, a as inject, b as isWatchMode } from './vendor/index.VL3WbvjT.js';
import * as chai from 'chai';

@@ -11,14 +12,13 @@ export { chai };

import '@vitest/utils';
import './vendor-index.29282562.js';
import './vendor/index.XU72Rmy8.js';
import 'pathe';
import 'std-env';
import './vendor-global.97e4527c.js';
import './vendor-_commonjsHelpers.7d1333e8.js';
import './vendor/global.L7JRz1qU.js';
import './vendor/_commonjsHelpers.jjO7Zipk.js';
import '@vitest/expect';
import '@vitest/snapshot';
import '@vitest/utils/error';
import './vendor-tasks.f9d75aed.js';
import './vendor/tasks.IknbGB2n.js';
import '@vitest/utils/source-map';
import 'util';
import './vendor-date.6e993429.js';
import './vendor/date.Ns1pGd_X.js';
import '@vitest/spy';

@@ -25,0 +25,0 @@

@@ -1,3 +0,3 @@

import { V as VitestRunMode, U as UserConfig, b as Vitest, T as TestSequencer, W as WorkspaceSpec } from './reporters-5f784f42.js';
export { d as TestSequencerConstructor, c as VitestWorkspace, s as startVitest } from './reporters-5f784f42.js';
import { V as VitestRunMode, U as UserConfig, e as Vitest, R as ResolvedConfig, f as ProvidedContext, W as WorkspaceProject, g as RuntimeRPC, T as TestSequencer, h as WorkspaceSpec } from './reporters-LLiOBu3g.js';
export { l as BrowserProvider, k as BrowserProviderInitializationOptions, m as BrowserProviderOptions, i as ProcessPool, j as TestSequencerConstructor, s as startVitest } from './reporters-LLiOBu3g.js';
import { UserConfig as UserConfig$1, Plugin } from 'vite';

@@ -15,3 +15,2 @@ import '@vitest/runner';

import 'node:worker_threads';
import 'rollup';
import 'node:fs';

@@ -26,2 +25,9 @@ import 'chai';

interface GlobalSetupContext {
config: ResolvedConfig;
provide<T extends keyof ProvidedContext>(key: T, value: ProvidedContext[T]): void;
}
declare function createMethodsRPC(project: WorkspaceProject): RuntimeRPC;
declare class BaseSequencer implements TestSequencer {

@@ -34,2 +40,2 @@ protected ctx: Vitest;

export { BaseSequencer, TestSequencer, Vitest, VitestPlugin, WorkspaceSpec, createVitest, registerConsoleShortcuts };
export { BaseSequencer, type GlobalSetupContext, TestSequencer, Vitest, VitestPlugin, WorkspaceProject, WorkspaceSpec, createMethodsRPC, createVitest, registerConsoleShortcuts };

@@ -1,2 +0,2 @@

export { B as BaseSequencer, V as VitestPlugin, c as createVitest, r as registerConsoleShortcuts, s as startVitest } from './vendor-node.a7c48fe1.js';
export { B as BaseSequencer, V as VitestPlugin, a as createMethodsRPC, c as createVitest, r as registerConsoleShortcuts, s as startVitest } from './vendor/node.mLeBfrTn.js';
import 'pathe';

@@ -8,6 +8,7 @@ import 'vite';

import 'node:fs';
import './vendor-constants.538d9b49.js';
import './vendor-_commonjsHelpers.7d1333e8.js';
import './vendor/constants.WSvnD_fn.js';
import './vendor/_commonjsHelpers.jjO7Zipk.js';
import 'os';
import 'path';
import './vendor/index.xL8XjTLv.js';
import 'util';

@@ -22,40 +23,36 @@ import 'stream';

import 'vite-node/server';
import './vendor-index.29282562.js';
import './vendor/index.XU72Rmy8.js';
import 'std-env';
import '@vitest/runner/utils';
import '@vitest/utils';
import './vendor-global.97e4527c.js';
import './vendor-coverage.78040316.js';
import './vendor-paths.84fc7a99.js';
import './vendor/global.L7JRz1qU.js';
import './vendor/coverage.v6aD8iAh.js';
import './paths.js';
import 'node:v8';
import 'node:child_process';
import './vendor-index.b271ebe4.js';
import './vendor-base.9c08bbd0.js';
import 'node:worker_threads';
import 'node:os';
import 'node:events';
import 'tinypool';
import 'local-pkg';
import './vendor-reporters.f6975b8d.js';
import './vendor/index.cAUulNDf.js';
import './vendor/base._79unx2z.js';
import 'node:worker_threads';
import 'node:fs/promises';
import 'node:perf_hooks';
import './vendor-tasks.f9d75aed.js';
import 'execa';
import '@vitest/utils/source-map';
import 'local-pkg';
import 'module';
import 'acorn-walk';
import './vendor/reporters.pr8MinP9.js';
import './chunks/runtime-console.hf2msWA9.js';
import 'node:stream';
import 'node:console';
import './vendor/date.Ns1pGd_X.js';
import './vendor/tasks.IknbGB2n.js';
import 'node:module';
import 'node:crypto';
import './vendor-index.85fc950a.js';
import 'node:buffer';
import 'child_process';
import 'assert';
import 'buffer';
import 'node:util';
import 'node:fs/promises';
import 'module';
import 'acorn';
import 'acorn-walk';
import 'magic-string';
import 'strip-literal';
import './vendor-environments.7aba93d9.js';
import './vendor-index.0b5b3600.js';
import 'node:assert';
import 'node:console';
import './vendor/environments.hTqxBFDN.js';
import 'node:readline';
import 'readline';

@@ -1,2 +0,2 @@

export { as as BaseReporter, ak as BasicReporter, aw as BenchmarkBuiltinReporters, av as BenchmarkReportsMap, au as BuiltinReporters, aj as DefaultReporter, al as DotReporter, ar as HangingProcessReporter, ap as JUnitReporter, am as JsonReporter, l as Reporter, at as ReportersMap, aq as TapFlatReporter, ao as TapReporter, an as VerboseReporter } from './reporters-5f784f42.js';
export { ay as BaseReporter, aq as BasicReporter, aC as BenchmarkBuiltinReporters, aB as BenchmarkReportsMap, aA as BuiltinReporters, ap as DefaultReporter, ar as DotReporter, ax as HangingProcessReporter, av as JUnitReporter, as as JsonReporter, q as Reporter, az as ReportersMap, aw as TapFlatReporter, au as TapReporter, at as VerboseReporter } from './reporters-LLiOBu3g.js';
import 'vite';

@@ -14,4 +14,3 @@ import '@vitest/runner';

import 'node:worker_threads';
import 'rollup';
import 'node:fs';
import 'chai';

@@ -1,5 +0,5 @@

export { f as BasicReporter, B as BenchmarkReportsMap, D as DefaultReporter, g as DotReporter, H as HangingProcessReporter, h as JUnitReporter, J as JsonReporter, R as ReportersMap, i as TapFlatReporter, T as TapReporter, V as VerboseReporter } from './vendor-reporters.f6975b8d.js';
export { f as BasicReporter, B as BenchmarkReportsMap, D as DefaultReporter, g as DotReporter, H as HangingProcessReporter, h as JUnitReporter, J as JsonReporter, R as ReportersMap, i as TapFlatReporter, T as TapReporter, V as VerboseReporter } from './vendor/reporters.pr8MinP9.js';
import 'node:perf_hooks';
import 'picocolors';
import './vendor-index.29282562.js';
import './vendor/index.XU72Rmy8.js';
import 'pathe';

@@ -9,6 +9,10 @@ import 'std-env';

import '@vitest/utils';
import './vendor-global.97e4527c.js';
import './vendor-base.9c08bbd0.js';
import './vendor-tasks.f9d75aed.js';
import './vendor-_commonjsHelpers.7d1333e8.js';
import './vendor/global.L7JRz1qU.js';
import './chunks/runtime-console.hf2msWA9.js';
import 'node:stream';
import 'node:console';
import 'node:path';
import './vendor/date.Ns1pGd_X.js';
import './vendor/base._79unx2z.js';
import './vendor/tasks.IknbGB2n.js';
import 'node:fs';

@@ -15,0 +19,0 @@ import '@vitest/utils/source-map';

@@ -1,3 +0,4 @@

import { VitestRunner, VitestRunnerImportSource, Suite, Test, CancelReason, TestContext } from '@vitest/runner';
import { R as ResolvedConfig } from './reporters-5f784f42.js';
import { VitestRunner, VitestRunnerImportSource, Suite, Test, CancelReason, Custom, TaskContext, ExtendedContext } from '@vitest/runner';
import { R as ResolvedConfig } from './reporters-LLiOBu3g.js';
import * as tinybench from 'tinybench';
import 'vite';

@@ -9,3 +10,2 @@ import 'vite-node';

import '@vitest/utils';
import 'tinybench';
import 'vite-node/client';

@@ -15,3 +15,2 @@ import '@vitest/snapshot/manager';

import 'node:worker_threads';
import 'rollup';
import 'node:fs';

@@ -28,12 +27,12 @@ import 'chai';

importFile(filepath: string, source: VitestRunnerImportSource): unknown;
onBeforeRun(): void;
onAfterRun(): Promise<void>;
onBeforeRunFiles(): void;
onAfterRunFiles(): Promise<void>;
onAfterRunSuite(suite: Suite): void;
onAfterRunTest(test: Test): void;
onAfterRunTask(test: Test): void;
onCancel(_reason: CancelReason): void;
onBeforeRunTest(test: Test): Promise<void>;
onBeforeRunTask(test: Test): Promise<void>;
onBeforeRunSuite(suite: Suite): void;
onBeforeTryTest(test: Test): void;
onAfterTryTest(test: Test): void;
extendTestContext(context: TestContext): TestContext;
onBeforeTryTask(test: Test): void;
onAfterTryTask(test: Test): void;
extendTaskContext<T extends Test | Custom>(context: TaskContext<T>): ExtendedContext<T>;
}

@@ -45,7 +44,8 @@

constructor(config: ResolvedConfig);
importTinybench(): Promise<typeof tinybench>;
importFile(filepath: string, source: VitestRunnerImportSource): unknown;
runSuite(suite: Suite): Promise<void>;
runTest(): Promise<void>;
runTask(): Promise<void>;
}
export { NodeBenchmarkRunner, VitestTestRunner };
import { setState, GLOBAL_EXPECT, getState } from '@vitest/expect';
import { g as getSnapshotClient, c as createExpect, v as vi, a as getBenchOptions, b as getBenchFn } from './vendor-vi.6873a1c1.js';
import './vendor-index.29282562.js';
import { a as rpc } from './vendor-rpc.cbd8e972.js';
import { g as getFullName } from './vendor-tasks.f9d75aed.js';
import { g as getWorkerState } from './vendor-global.97e4527c.js';
import { g as getSnapshotClient, c as createExpect, v as vi } from './vendor/vi.JXuS6emb.js';
import './vendor/index.XU72Rmy8.js';
import { a as rpc } from './vendor/rpc.Bl-ysZIr.js';
import { g as getFullName } from './vendor/tasks.IknbGB2n.js';
import { g as getWorkerState } from './vendor/global.L7JRz1qU.js';
import { getNames } from '@vitest/runner/utils';
import { performance } from 'node:perf_hooks';
import { updateTask } from '@vitest/runner';
import { createDefer, getSafeTimers } from '@vitest/utils';
import { a as getBenchOptions, g as getBenchFn } from './vendor/benchmark.WVm6DARl.js';
import 'chai';
import './vendor-_commonjsHelpers.7d1333e8.js';
import './vendor/_commonjsHelpers.jjO7Zipk.js';
import '@vitest/snapshot';
import '@vitest/utils/error';
import '@vitest/utils/source-map';
import 'util';
import './vendor-date.6e993429.js';
import './vendor/date.Ns1pGd_X.js';
import '@vitest/spy';

@@ -35,7 +34,7 @@ import 'pathe';

}
onBeforeRun() {
onBeforeRunFiles() {
this.snapshotClient.clear();
}
async onAfterRun() {
const result = await this.snapshotClient.resetCurrent();
async onAfterRunFiles() {
const result = await this.snapshotClient.finishCurrentRun();
if (result)

@@ -48,3 +47,3 @@ await rpc().snapshotSaved(result);

}
onAfterRunTest(test) {
onAfterRunTask(test) {
this.snapshotClient.clearTest();

@@ -58,3 +57,3 @@ if (this.config.logHeapUsage && typeof process !== "undefined")

}
async onBeforeRunTest(test) {
async onBeforeRunTask(test) {
const name = getNames(test).slice(1).join(" > ");

@@ -68,3 +67,3 @@ if (this.cancelRun)

clearModuleMocks(this.config);
await this.snapshotClient.setTest(test.file.filepath, name, this.workerState.config.snapshotOptions);
await this.snapshotClient.startCurrentRun(test.file.filepath, name, this.workerState.config.snapshotOptions);
this.workerState.current = test;

@@ -76,3 +75,3 @@ }

}
onBeforeTryTest(test) {
onBeforeTryTask(test) {
var _a;

@@ -90,3 +89,3 @@ setState({

}
onAfterTryTest(test) {
onAfterTryTask(test) {
const {

@@ -105,3 +104,3 @@ assertionCalls,

}
extendTestContext(context) {
extendTaskContext(context) {
let _expect;

@@ -111,3 +110,3 @@ Object.defineProperty(context, "expect", {

if (!_expect)
_expect = createExpect(context.meta);
_expect = createExpect(context.task);
return _expect;

@@ -138,7 +137,2 @@ }

async function importTinybench() {
if (!globalThis.EventTarget)
await import('./vendor-index.98139333.js').then(function (n) { return n.i; });
return await import('tinybench');
}
function createBenchmarkResult(name) {

@@ -155,3 +149,3 @@ return {

var _a;
const { Task, Bench } = await importTinybench();
const { Task, Bench } = await runner.importTinybench();
const start = performance.now();

@@ -172,3 +166,2 @@ const benchmarkGroup = [];

const defer = createDefer();
const benchmarkMap = {};
suite.result = {

@@ -180,3 +173,20 @@ state: "run",

updateTask$1(suite);
benchmarkGroup.forEach((benchmark, idx) => {
const addBenchTaskListener = (task, benchmark) => {
task.addEventListener("complete", (e) => {
const task2 = e.task;
const taskRes = task2.result;
const result = benchmark.result.benchmark;
Object.assign(result, taskRes);
updateTask$1(benchmark);
}, {
once: true
});
task.addEventListener("error", (e) => {
const task2 = e.task;
defer.reject(benchmark ? task2.result.error : e);
}, {
once: true
});
};
benchmarkGroup.forEach((benchmark) => {
const options = getBenchOptions(benchmark);

@@ -190,26 +200,8 @@ const benchmarkInstance = new Bench(options);

};
const id = idx.toString();
benchmarkMap[id] = benchmark;
const task = new Task(benchmarkInstance, id, benchmarkFn);
const task = new Task(benchmarkInstance, benchmark.name, benchmarkFn);
benchmarkTasks.set(benchmark, task);
addBenchTaskListener(task, benchmark);
updateTask$1(benchmark);
});
benchmarkGroup.forEach((benchmark) => {
const task = benchmarkTasks.get(benchmark);
task.addEventListener("complete", (e) => {
const task2 = e.task;
const _benchmark = benchmarkMap[task2.name || ""];
if (_benchmark) {
const taskRes = task2.result;
const result = _benchmark.result.benchmark;
Object.assign(result, taskRes);
updateTask$1(_benchmark);
}
});
task.addEventListener("error", (e) => {
const task2 = e.task;
const _benchmark = benchmarkMap[task2.name || ""];
defer.reject(_benchmark ? task2.result.error : e);
});
});
const { setTimeout } = getSafeTimers();
const tasks = [];

@@ -219,11 +211,12 @@ for (const benchmark of benchmarkGroup) {

await task.warmup();
const { setTimeout } = getSafeTimers();
tasks.push(await new Promise((resolve) => setTimeout(async () => {
resolve(await task.run());
})));
tasks.push([
await new Promise((resolve) => setTimeout(async () => {
resolve(await task.run());
})),
benchmark
]);
}
suite.result.duration = performance.now() - start;
suite.result.state = "pass";
tasks.sort((a, b) => a.result.mean - b.result.mean).forEach((cycle, idx) => {
const benchmark = benchmarkMap[cycle.name || ""];
tasks.sort(([taskA], [taskB]) => taskA.result.mean - taskB.result.mean).forEach(([, benchmark], idx) => {
benchmark.result.state = "pass";

@@ -249,2 +242,5 @@ if (benchmark) {

__vitest_executor;
async importTinybench() {
return await import('tinybench');
}
importFile(filepath, source) {

@@ -258,3 +254,3 @@ if (source === "setup")

}
async runTest() {
async runTask() {
throw new Error("`test()` and `it()` is only available in test mode.");

@@ -261,0 +257,0 @@ }

@@ -1,3 +0,16 @@

export { getCurrentSuite, getFn, setFn } from '@vitest/runner';
export { createTaskCollector, getCurrentSuite, getFn, setFn } from '@vitest/runner';
export { createChainable } from '@vitest/runner/utils';
export { g as getBenchFn, a as getBenchOptions } from './suite-SvxfaIxW.js';
import './reporters-LLiOBu3g.js';
import 'vite';
import 'vite-node';
import '@vitest/snapshot';
import '@vitest/expect';
import '@vitest/utils';
import 'tinybench';
import 'vite-node/client';
import '@vitest/snapshot/manager';
import 'vite-node/server';
import 'node:worker_threads';
import 'node:fs';
import 'chai';

@@ -1,2 +0,8 @@

export { getCurrentSuite, getFn, setFn } from '@vitest/runner';
export { createTaskCollector, getCurrentSuite, getFn, setFn } from '@vitest/runner';
export { createChainable } from '@vitest/runner/utils';
export { g as getBenchFn, a as getBenchOptions } from './vendor/benchmark.WVm6DARl.js';
import '@vitest/utils';
import './vendor/index.XU72Rmy8.js';
import 'pathe';
import 'std-env';
import './vendor/global.L7JRz1qU.js';

@@ -6,19 +6,11 @@ import { pathToFileURL } from 'node:url';

import { workerId } from 'tinypool';
import { c as createBirpc } from './vendor-index.b271ebe4.js';
import { c as createBirpc } from './vendor/index.cAUulNDf.js';
import { resolve } from 'pathe';
import { installSourcemapsSupport } from 'vite-node/source-map';
import { d as distDir } from './vendor-paths.84fc7a99.js';
import { l as loadEnvironment } from './vendor-environments.7aba93d9.js';
import { b as startVitestExecutor } from './vendor-execute.07d1a420.js';
import { createCustomConsole } from './chunk-runtime-console.ea222ffb.js';
import { c as createSafeRpc } from './vendor-rpc.cbd8e972.js';
import './vendor-index.0b5b3600.js';
import 'acorn';
import 'node:module';
import 'node:fs';
import 'node:assert';
import 'node:process';
import 'node:path';
import 'node:v8';
import 'node:util';
import { distDir } from './paths.js';
import { l as loadEnvironment } from './vendor/loader.w8KTtIkD.js';
import { b as startVitestExecutor } from './vendor/execute.ILey0jnF.js';
import { createCustomConsole } from './chunks/runtime-console.hf2msWA9.js';
import { c as createSafeRpc } from './vendor/rpc.Bl-ysZIr.js';
import './vendor/environments.hTqxBFDN.js';
import 'node:console';

@@ -28,8 +20,11 @@ import 'local-pkg';

import '@vitest/utils/error';
import './vendor-global.97e4527c.js';
import 'node:fs';
import '@vitest/utils';
import './vendor-base.9c08bbd0.js';
import './vendor/base._79unx2z.js';
import 'node:path';
import 'node:module';
import 'vite-node/constants';
import 'node:stream';
import './vendor-date.6e993429.js';
import './vendor/date.Ns1pGd_X.js';
import './vendor/global.L7JRz1qU.js';

@@ -41,3 +36,3 @@ const entryFile = pathToFileURL(resolve(distDir, "entry-vm.js")).href;

const mockMap = /* @__PURE__ */ new Map();
const { config, port } = ctx;
const { config, port, providedContext } = ctx;
let setCancel = (_reason) => {

@@ -85,3 +80,4 @@ };

},
rpc
rpc,
providedContext
};

@@ -101,3 +97,8 @@ installSourcemapsSupport({

throw new TypeError(`Environment ${ctx.environment.name} doesn't provide a valid context. It should be created by "vm.createContext" method.`);
context.__vitest_worker__ = state;
Object.defineProperty(context, "__vitest_worker__", {
value: state,
configurable: true,
writable: true,
enumerable: false
});
context.process = process;

@@ -104,0 +105,0 @@ context.global = context;

import { performance } from 'node:perf_hooks';
import { c as createBirpc } from './vendor-index.b271ebe4.js';
import { c as createBirpc } from './vendor/index.cAUulNDf.js';
import { workerId } from 'tinypool';
import { g as getWorkerState } from './vendor-global.97e4527c.js';
import { l as loadEnvironment } from './vendor-environments.7aba93d9.js';
import { s as startViteNode, m as moduleCache, a as mockMap } from './vendor-execute.07d1a420.js';
import { s as setupInspect } from './vendor-inspector.47fc8cbb.js';
import { r as rpcDone, c as createSafeRpc } from './vendor-rpc.cbd8e972.js';
import { g as getWorkerState } from './vendor/global.L7JRz1qU.js';
import { l as loadEnvironment } from './vendor/loader.w8KTtIkD.js';
import { s as startViteNode, m as moduleCache, a as mockMap } from './vendor/execute.ILey0jnF.js';
import { s as setupInspect } from './vendor/inspector.lFAeuaAt.js';
import { r as rpcDone, c as createSafeRpc } from './vendor/rpc.Bl-ysZIr.js';
import 'pathe';
import './vendor-index.0b5b3600.js';
import 'acorn';
import 'node:module';
import 'node:fs';
import 'node:url';
import 'node:assert';
import 'node:process';
import 'node:path';
import 'node:v8';
import 'node:util';
import 'vite-node/client';
import './vendor/environments.hTqxBFDN.js';
import 'node:console';
import 'local-pkg';
import 'node:url';
import 'node:vm';
import 'vite-node/utils';
import '@vitest/utils/error';
import './vendor-paths.84fc7a99.js';
import './paths.js';
import 'node:fs';
import '@vitest/utils';
import './vendor-base.9c08bbd0.js';
import './vendor/base._79unx2z.js';
import 'node:path';
import 'node:module';
import 'vite-node/constants';
async function init(ctx) {
if (typeof __vitest_worker__ !== "undefined" && ctx.config.threads && ctx.config.isolate)
var _a, _b;
const isInitialized = typeof __vitest_worker__ !== "undefined";
const isIsolatedThreads = ctx.config.pool === "threads" && (((_b = (_a = ctx.config.poolOptions) == null ? void 0 : _a.threads) == null ? void 0 : _b.isolate) ?? true);
if (isInitialized && isIsolatedThreads)
throw new Error(`worker for ${ctx.files.join(",")} already initialized by ${getWorkerState().ctx.files.join(",")}. This is probably an internal bug of Vitest.`);
const { config, port, workerId: workerId$1 } = ctx;
const { config, port, workerId: workerId$1, providedContext } = ctx;
process.env.VITEST_WORKER_ID = String(workerId$1);

@@ -74,5 +72,11 @@ process.env.VITEST_POOL_ID = String(workerId);

},
rpc
rpc,
providedContext
};
globalThis.__vitest_worker__ = state;
Object.defineProperty(globalThis, "__vitest_worker__", {
value: state,
configurable: true,
writable: true,
enumerable: false
});
if (ctx.invalidates) {

@@ -79,0 +83,0 @@ ctx.invalidates.forEach((fsPath) => {

{
"name": "vitest",
"type": "module",
"version": "0.34.6",
"description": "A blazing fast unit test framework powered by Vite",
"version": "1.0.1",
"description": "Next generation testing framework powered by Vite",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",

@@ -28,9 +28,9 @@ "license": "MIT",

".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./index.d.cts",
"default": "./index.cjs"
},
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}

@@ -45,29 +45,32 @@ },

},
"./import-meta": {
"types": "./import-meta.d.ts"
},
"./node": {
"types": "./dist/node.d.ts",
"import": "./dist/node.js"
"default": "./dist/node.js"
},
"./execute": {
"types": "./dist/execute.d.ts",
"import": "./dist/execute.js"
"default": "./dist/execute.js"
},
"./browser": {
"types": "./dist/browser.d.ts",
"import": "./dist/browser.js"
"default": "./dist/browser.js"
},
"./runners": {
"types": "./dist/runners.d.ts",
"import": "./dist/runners.js"
"default": "./dist/runners.js"
},
"./suite": {
"types": "./dist/suite.d.ts",
"import": "./dist/suite.js"
"default": "./dist/suite.js"
},
"./environments": {
"types": "./dist/environments.d.ts",
"import": "./dist/environments.js"
"default": "./dist/environments.js"
},
"./utils": {
"types": "./dist/utils.d.ts",
"import": "./dist/utils.js"
"default": "./dist/utils.js"
},

@@ -77,11 +80,11 @@ "./config": {

"require": "./dist/config.cjs",
"import": "./dist/config.js"
"default": "./dist/config.js"
},
"./coverage": {
"types": "./coverage.d.ts",
"import": "./dist/coverage.js"
"default": "./dist/coverage.js"
},
"./reporters": {
"types": "./dist/reporters.d.ts",
"import": "./dist/reporters.js"
"default": "./dist/reporters.js"
}

@@ -96,23 +99,24 @@ },

"files": [
"dist",
"bin",
"*.cjs",
"*.d.cts",
"*.d.ts",
"*.d.cts",
"*.mjs",
"*.cjs"
"bin",
"dist"
],
"engines": {
"node": ">=v14.18.0"
"node": "^18.0.0 || >=20.0.0"
},
"peerDependencies": {
"@edge-runtime/vm": "*",
"@vitest/browser": "*",
"@vitest/ui": "*",
"@types/node": "^18.0.0 || >=20.0.0",
"@vitest/browser": "^1.0.0",
"@vitest/ui": "^1.0.0",
"happy-dom": "*",
"jsdom": "*",
"playwright": "*",
"safaridriver": "*",
"webdriverio": "*"
"jsdom": "*"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
},
"@vitest/ui": {

@@ -130,11 +134,2 @@ "optional": true

},
"webdriverio": {
"optional": true
},
"safaridriver": {
"optional": true
},
"playwright": {
"optional": true
},
"@edge-runtime/vm": {

@@ -145,26 +140,23 @@ "optional": true

"dependencies": {
"@types/chai": "^4.3.5",
"@types/chai-subset": "^1.3.3",
"@types/node": "*",
"acorn": "^8.9.0",
"acorn-walk": "^8.2.0",
"acorn-walk": "^8.3.0",
"cac": "^6.7.14",
"chai": "^4.3.10",
"debug": "^4.3.4",
"local-pkg": "^0.4.3",
"magic-string": "^0.30.1",
"execa": "^8.0.1",
"local-pkg": "^0.5.0",
"magic-string": "^0.30.5",
"pathe": "^1.1.1",
"picocolors": "^1.0.0",
"std-env": "^3.3.3",
"strip-literal": "^1.0.1",
"tinybench": "^2.5.0",
"tinypool": "^0.7.0",
"vite": "^3.1.0 || ^4.0.0 || ^5.0.0-0",
"std-env": "^3.5.0",
"strip-literal": "^1.3.0",
"tinybench": "^2.5.1",
"tinypool": "^0.8.1",
"vite": "^5.0.0-beta.19 || ^5.0.0",
"why-is-node-running": "^2.2.2",
"@vitest/runner": "0.34.6",
"@vitest/utils": "0.34.6",
"vite-node": "0.34.6",
"@vitest/expect": "0.34.6",
"@vitest/snapshot": "0.34.6",
"@vitest/spy": "0.34.6"
"@vitest/expect": "1.0.1",
"@vitest/snapshot": "1.0.1",
"@vitest/spy": "1.0.1",
"@vitest/runner": "1.0.1",
"@vitest/utils": "1.0.1",
"vite-node": "1.0.1"
},

@@ -174,36 +166,28 @@ "devDependencies": {

"@antfu/install-pkg": "^0.1.1",
"@edge-runtime/vm": "3.0.3",
"@sinonjs/fake-timers": "^11.0.0",
"@types/diff": "^5.0.3",
"@types/estree": "^1.0.1",
"@types/istanbul-lib-coverage": "^2.0.4",
"@types/istanbul-reports": "^3.0.1",
"@types/jsdom": "^21.1.1",
"@types/micromatch": "^4.0.2",
"@types/prompts": "^2.4.4",
"@types/sinonjs__fake-timers": "^8.1.2",
"birpc": "0.2.12",
"@edge-runtime/vm": "^3.1.7",
"@sinonjs/fake-timers": "11.1.0",
"@types/estree": "^1.0.5",
"@types/istanbul-lib-coverage": "^2.0.6",
"@types/istanbul-reports": "^3.0.4",
"@types/jsdom": "^21.1.6",
"@types/micromatch": "^4.0.6",
"@types/prompts": "^2.4.8",
"@types/sinonjs__fake-timers": "^8.1.5",
"birpc": "0.2.14",
"chai-subset": "^1.6.0",
"cli-truncate": "^3.1.0",
"event-target-polyfill": "^0.0.3",
"execa": "^7.1.1",
"expect-type": "^0.16.0",
"fast-glob": "^3.3.0",
"cli-truncate": "^4.0.0",
"expect-type": "^0.17.3",
"fast-glob": "^3.3.2",
"find-up": "^6.3.0",
"flatted": "^3.2.7",
"get-tsconfig": "^4.6.2",
"happy-dom": "^9.20.3",
"jsdom": "^22.1.0",
"log-update": "^5.0.1",
"flatted": "^3.2.9",
"get-tsconfig": "^4.7.2",
"happy-dom": "^12.10.3",
"jsdom": "^23.0.1",
"log-update": "^6.0.0",
"micromatch": "^4.0.5",
"mlly": "^1.4.0",
"p-limit": "^4.0.0",
"pkg-types": "^1.0.3",
"playwright": "^1.35.1",
"pretty-format": "^29.5.0",
"p-limit": "^5.0.0",
"pretty-format": "^29.7.0",
"prompts": "^2.4.2",
"safaridriver": "^0.0.5",
"strip-ansi": "^7.1.0",
"webdriverio": "^8.11.2",
"ws": "^8.13.0"
"ws": "^8.14.2"
},

@@ -210,0 +194,0 @@ "scripts": {

@@ -5,4 +5,4 @@ # vitest

A blazing fast unit test framework powered by Vite.
Next generation testing framework powered by Vite.
[GitHub](https://github.com/vitest-dev/vitest) | [Documentation](https://vitest.dev/)

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc