wip:milestone 0 fixes
Some checks failed
CI/CD Pipeline / unit-tests (push) Failing after 1m16s
CI/CD Pipeline / integration-tests (push) Failing after 2m32s
CI/CD Pipeline / lint (push) Successful in 5m22s
CI/CD Pipeline / e2e-tests (push) Has been skipped
CI/CD Pipeline / build (push) Has been skipped

This commit is contained in:
2026-03-15 12:35:42 +02:00
parent 6708cf28a7
commit cffdf8af86
61266 changed files with 4511646 additions and 1938 deletions

View File

@@ -0,0 +1,7 @@
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
export { commonjsGlobal as c, getDefaultExportFromCjs as g };

View File

@@ -0,0 +1,119 @@
import '@vitest/utils';
function collectOwnProperties(obj, collector) {
const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
Object.getOwnPropertyNames(obj).forEach(collect);
Object.getOwnPropertySymbols(obj).forEach(collect);
}
function groupBy(collection, iteratee) {
return collection.reduce((acc, item) => {
const key = iteratee(item);
acc[key] || (acc[key] = []);
acc[key].push(item);
return acc;
}, {});
}
function isPrimitive(value) {
return value === null || typeof value !== "function" && typeof value !== "object";
}
function getAllMockableProperties(obj, isModule, constructors) {
const {
Map,
Object: Object2,
Function,
RegExp: RegExp2,
Array: Array2
} = constructors;
const allProps = new Map();
let curr = obj;
do {
if (curr === Object2.prototype || curr === Function.prototype || curr === RegExp2.prototype)
break;
collectOwnProperties(curr, (key) => {
const descriptor = Object2.getOwnPropertyDescriptor(curr, key);
if (descriptor)
allProps.set(key, { key, descriptor });
});
} while (curr = Object2.getPrototypeOf(curr));
if (isModule && !allProps.has("default") && "default" in obj) {
const descriptor = Object2.getOwnPropertyDescriptor(obj, "default");
if (descriptor)
allProps.set("default", { key: "default", descriptor });
}
return Array2.from(allProps.values());
}
function slash(str) {
return str.replace(/\\/g, "/");
}
function noop() {
}
function toArray(array) {
if (array === null || array === void 0)
array = [];
if (Array.isArray(array))
return array;
return [array];
}
function toString(v) {
return Object.prototype.toString.call(v);
}
function isPlainObject(val) {
return toString(val) === "[object Object]" && (!val.constructor || val.constructor.name === "Object");
}
function deepMerge(target, ...sources) {
if (!sources.length)
return target;
const source = sources.shift();
if (source === void 0)
return target;
if (isMergeableObject(target) && isMergeableObject(source)) {
Object.keys(source).forEach((key) => {
if (isMergeableObject(source[key])) {
if (!target[key])
target[key] = {};
deepMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
});
}
return deepMerge(target, ...sources);
}
function isMergeableObject(item) {
return isPlainObject(item) && !Array.isArray(item);
}
function stdout() {
return console._stdout || process.stdout;
}
class AggregateErrorPonyfill extends Error {
errors;
constructor(errors, message = "") {
super(message);
this.errors = [...errors];
}
}
function isChildProcess() {
return typeof process !== "undefined" && !!process.send;
}
function setProcessTitle(title) {
try {
process.title = `node (${title})`;
} catch {
}
}
function escapeRegExp(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function wildcardPatternToRegExp(pattern) {
return new RegExp(`^${pattern.split("*").map(escapeRegExp).join(".*")}$`, "i");
}
const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
function nanoid(size = 21) {
let id = "";
let i = size;
while (i--)
id += urlAlphabet[Math.random() * 64 | 0];
return id;
}
export { AggregateErrorPonyfill as A, slash as a, isPrimitive as b, groupBy as c, deepMerge as d, nanoid as e, stdout as f, getAllMockableProperties as g, isChildProcess as i, noop as n, setProcessTitle as s, toArray as t, wildcardPatternToRegExp as w };

View File

@@ -0,0 +1,38 @@
import { ModuleCacheMap } from 'vite-node/client';
import { p as provideWorkerState } from './global.CkGT_TMy.js';
import { g as getDefaultRequestStubs, s as startVitestExecutor } from './execute.fL3szUAI.js';
let _viteNode;
const moduleCache = new ModuleCacheMap();
const mockMap = /* @__PURE__ */ new Map();
async function startViteNode(options) {
if (_viteNode)
return _viteNode;
_viteNode = await startVitestExecutor(options);
return _viteNode;
}
async function runBaseTests(state) {
const { ctx } = state;
state.moduleCache = moduleCache;
state.mockMap = mockMap;
provideWorkerState(globalThis, state);
if (ctx.invalidates) {
ctx.invalidates.forEach((fsPath) => {
moduleCache.delete(fsPath);
moduleCache.delete(`mock:${fsPath}`);
});
}
ctx.files.forEach((i) => state.moduleCache.delete(i));
const [executor, { run }] = await Promise.all([
startViteNode({ state, requestStubs: getDefaultRequestStubs() }),
import('../chunks/runtime-runBaseTests.oAvMKtQC.js')
]);
await run(
ctx.files,
ctx.config,
{ environment: state.environment, options: ctx.environment.options },
executor
);
}
export { runBaseTests as r };

View File

@@ -0,0 +1,41 @@
import { getCurrentSuite } from '@vitest/runner';
import { createChainable } from '@vitest/runner/utils';
import { noop } from '@vitest/utils';
import { i as isRunningInBenchmark } from './index.SMVOaj7F.js';
const benchFns = /* @__PURE__ */ new WeakMap();
const benchOptsMap = /* @__PURE__ */ new WeakMap();
function getBenchOptions(key) {
return benchOptsMap.get(key);
}
function getBenchFn(key) {
return benchFns.get(key);
}
const bench = createBenchmark(
function(name, fn = noop, options = {}) {
if (!isRunningInBenchmark())
throw new Error("`bench()` is only available in benchmark mode.");
const task = getCurrentSuite().task(formatName(name), {
...this,
meta: {
benchmark: true
}
});
benchFns.set(task, fn);
benchOptsMap.set(task, options);
}
);
function createBenchmark(fn) {
const benchmark = createChainable(
["skip", "only", "todo"],
fn
);
benchmark.skipIf = (condition) => condition ? benchmark.skip : benchmark;
benchmark.runIf = (condition) => condition ? benchmark : benchmark.skip;
return benchmark;
}
function formatName(name) {
return typeof name === "string" ? name : name instanceof Function ? name.name || "<anonymous>" : String(name);
}
export { getBenchOptions as a, bench as b, getBenchFn as g };

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,65 @@
const defaultPort = 51204;
const defaultBrowserPort = 63315;
const defaultInspectPort = 9229;
const EXIT_CODE_RESTART = 43;
const API_PATH = "/__vitest_api__";
const extraInlineDeps = [
/^(?!.*(?:node_modules)).*\.mjs$/,
/^(?!.*(?:node_modules)).*\.cjs\.js$/,
// Vite client
/vite\w*\/dist\/client\/env.mjs/,
// Nuxt
"@nuxt/test-utils"
];
const CONFIG_NAMES = [
"vitest.config",
"vite.config"
];
const WORKSPACES_NAMES = [
"vitest.workspace",
"vitest.projects"
];
const CONFIG_EXTENSIONS = [
".ts",
".mts",
".cts",
".js",
".mjs",
".cjs"
];
const configFiles = CONFIG_NAMES.flatMap(
(name) => CONFIG_EXTENSIONS.map((ext) => name + ext)
);
const WORKSPACES_EXTENSIONS = [
...CONFIG_EXTENSIONS,
".json"
];
const workspacesFiles = WORKSPACES_NAMES.flatMap(
(name) => WORKSPACES_EXTENSIONS.map((ext) => name + ext)
);
const globalApis = [
// suite
"suite",
"test",
"describe",
"it",
// chai
"chai",
"expect",
"assert",
// typecheck
"expectTypeOf",
"assertType",
// utils
"vitest",
"vi",
// hooks
"beforeAll",
"afterAll",
"beforeEach",
"afterEach",
"onTestFinished",
"onTestFailed"
];
export { API_PATH as A, CONFIG_NAMES as C, EXIT_CODE_RESTART as E, defaultBrowserPort as a, defaultInspectPort as b, configFiles as c, defaultPort as d, extraInlineDeps as e, globalApis as g, workspacesFiles as w };

View File

@@ -0,0 +1,53 @@
const CoverageProviderMap = {
v8: "@vitest/coverage-v8",
istanbul: "@vitest/coverage-istanbul"
};
async function resolveCoverageProviderModule(options, loader) {
if (!(options == null ? void 0 : options.enabled) || !options.provider)
return null;
const provider = options.provider;
if (provider === "v8" || provider === "istanbul") {
const { default: coverageModule } = await loader.executeId(CoverageProviderMap[provider]);
if (!coverageModule)
throw new Error(`Failed to load ${CoverageProviderMap[provider]}. Default export is missing.`);
return coverageModule;
}
let customProviderModule;
try {
customProviderModule = await loader.executeId(options.customProviderModule);
} catch (error) {
throw new Error(`Failed to load custom CoverageProviderModule from ${options.customProviderModule}`, { cause: error });
}
if (customProviderModule.default == null)
throw new Error(`Custom CoverageProviderModule loaded from ${options.customProviderModule} was not the default export`);
return customProviderModule.default;
}
async function getCoverageProvider(options, loader) {
const coverageModule = await resolveCoverageProviderModule(options, loader);
if (coverageModule)
return coverageModule.getProvider();
return null;
}
async function startCoverageInsideWorker(options, loader) {
var _a;
const coverageModule = await resolveCoverageProviderModule(options, loader);
if (coverageModule)
return (_a = coverageModule.startCoverage) == null ? void 0 : _a.call(coverageModule);
return null;
}
async function takeCoverageInsideWorker(options, loader) {
var _a;
const coverageModule = await resolveCoverageProviderModule(options, loader);
if (coverageModule)
return (_a = coverageModule.takeCoverage) == null ? void 0 : _a.call(coverageModule);
return null;
}
async function stopCoverageInsideWorker(options, loader) {
var _a;
const coverageModule = await resolveCoverageProviderModule(options, loader);
if (coverageModule)
return (_a = coverageModule.stopCoverage) == null ? void 0 : _a.call(coverageModule);
return null;
}
export { CoverageProviderMap as C, startCoverageInsideWorker as a, getCoverageProvider as g, stopCoverageInsideWorker as s, takeCoverageInsideWorker as t };

View File

@@ -0,0 +1,51 @@
const RealDate = Date;
let now = null;
class MockDate extends RealDate {
constructor(y, m, d, h, M, s, ms) {
super();
let date;
switch (arguments.length) {
case 0:
if (now !== null)
date = new RealDate(now.valueOf());
else
date = new RealDate();
break;
case 1:
date = new RealDate(y);
break;
default:
d = typeof d === "undefined" ? 1 : d;
h = h || 0;
M = M || 0;
s = s || 0;
ms = ms || 0;
date = new RealDate(y, m, d, h, M, s, ms);
break;
}
Object.setPrototypeOf(date, MockDate.prototype);
return date;
}
}
MockDate.UTC = RealDate.UTC;
MockDate.now = function() {
return new MockDate().valueOf();
};
MockDate.parse = function(dateString) {
return RealDate.parse(dateString);
};
MockDate.toString = function() {
return RealDate.toString();
};
function mockDate(date) {
const dateObj = new RealDate(date.valueOf());
if (Number.isNaN(dateObj.getTime()))
throw new TypeError(`mockdate: The time set is an invalid date: ${date}`);
globalThis.Date = MockDate;
now = dateObj.valueOf();
}
function resetDate() {
globalThis.Date = RealDate;
}
export { RealDate as R, mockDate as m, resetDate as r };

View File

@@ -0,0 +1,7 @@
import 'std-env';
var _a;
const isNode = typeof process < "u" && typeof process.stdout < "u" && !((_a = process.versions) == null ? void 0 : _a.deno) && !globalThis.window;
const isWindows = isNode && process.platform === "win32";
export { isWindows as a, isNode as i };

View File

@@ -0,0 +1,594 @@
import vm from 'node:vm';
import { pathToFileURL } from 'node:url';
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { ViteNodeRunner, DEFAULT_REQUEST_STUBS } from 'vite-node/client';
import { isNodeBuiltin, isInternalRequest, toFilePath, isPrimitive } from 'vite-node/utils';
import { resolve, isAbsolute, dirname, join, basename, extname, normalize, relative } from 'pathe';
import { processError } from '@vitest/utils/error';
import { distDir } from '../path.js';
import { highlight, getType } from '@vitest/utils';
import { g as getAllMockableProperties } from './base.5NT-gWu5.js';
const spyModulePath = resolve(distDir, "spy.js");
class RefTracker {
idMap = /* @__PURE__ */ new Map();
mockedValueMap = /* @__PURE__ */ new Map();
getId(value) {
return this.idMap.get(value);
}
getMockedValue(id) {
return this.mockedValueMap.get(id);
}
track(originalValue, mockedValue) {
const newId = this.idMap.size;
this.idMap.set(originalValue, newId);
this.mockedValueMap.set(newId, mockedValue);
return newId;
}
}
function isSpecialProp(prop, parentType) {
return parentType.includes("Function") && typeof prop === "string" && ["arguments", "callee", "caller", "length", "name"].includes(prop);
}
class VitestMocker {
constructor(executor) {
this.executor = executor;
const context = this.executor.options.context;
if (context)
this.primitives = vm.runInContext("({ Object, Error, Function, RegExp, Symbol, Array, Map })", context);
else
this.primitives = { Object, Error, Function, RegExp, Symbol: globalThis.Symbol, Array, Map };
const Symbol2 = this.primitives.Symbol;
this.filterPublicKeys = ["__esModule", Symbol2.asyncIterator, Symbol2.hasInstance, Symbol2.isConcatSpreadable, Symbol2.iterator, Symbol2.match, Symbol2.matchAll, Symbol2.replace, Symbol2.search, Symbol2.split, Symbol2.species, Symbol2.toPrimitive, Symbol2.toStringTag, Symbol2.unscopables];
}
static pendingIds = [];
spyModule;
resolveCache = /* @__PURE__ */ new Map();
primitives;
filterPublicKeys;
mockContext = {
callstack: null
};
get root() {
return this.executor.options.root;
}
get mockMap() {
return this.executor.options.mockMap;
}
get moduleCache() {
return this.executor.moduleCache;
}
get moduleDirectories() {
return this.executor.options.moduleDirectories || [];
}
async initializeSpyModule() {
this.spyModule = await this.executor.executeId(spyModulePath);
}
deleteCachedItem(id) {
const mockId = this.getMockPath(id);
if (this.moduleCache.has(mockId))
this.moduleCache.delete(mockId);
}
isAModuleDirectory(path) {
return this.moduleDirectories.some((dir) => path.includes(dir));
}
getSuiteFilepath() {
return this.executor.state.filepath || "global";
}
createError(message, codeFrame) {
const Error2 = this.primitives.Error;
const error = new Error2(message);
Object.assign(error, { codeFrame });
return error;
}
getMocks() {
const suite = this.getSuiteFilepath();
const suiteMocks = this.mockMap.get(suite);
const globalMocks = this.mockMap.get("global");
return {
...globalMocks,
...suiteMocks
};
}
async resolvePath(rawId, importer) {
let id;
let fsPath;
try {
[id, fsPath] = await this.executor.originalResolveUrl(rawId, importer);
} catch (error) {
if (error.code === "ERR_MODULE_NOT_FOUND") {
const { id: unresolvedId } = error[Symbol.for("vitest.error.not_found.data")];
id = unresolvedId;
fsPath = unresolvedId;
} else {
throw error;
}
}
const external = !isAbsolute(fsPath) || this.isAModuleDirectory(fsPath) ? rawId : null;
return {
id,
fsPath,
external
};
}
async resolveMocks() {
if (!VitestMocker.pendingIds.length)
return;
await Promise.all(VitestMocker.pendingIds.map(async (mock) => {
const { fsPath, external } = await this.resolvePath(mock.id, mock.importer);
if (mock.type === "unmock")
this.unmockPath(fsPath);
if (mock.type === "mock")
this.mockPath(mock.id, fsPath, external, mock.factory);
}));
VitestMocker.pendingIds = [];
}
async callFunctionMock(dep, mock) {
var _a, _b;
const cached = (_a = this.moduleCache.get(dep)) == null ? void 0 : _a.exports;
if (cached)
return cached;
let exports;
try {
exports = await mock();
} catch (err) {
const vitestError = this.createError(
'[vitest] There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/vi.html#vi-mock'
);
vitestError.cause = err;
throw vitestError;
}
const filepath = dep.slice(5);
const mockpath = ((_b = this.resolveCache.get(this.getSuiteFilepath())) == null ? void 0 : _b[filepath]) || filepath;
if (exports === null || typeof exports !== "object")
throw this.createError(`[vitest] vi.mock("${mockpath}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`);
const moduleExports = new Proxy(exports, {
get: (target, prop) => {
const val = target[prop];
if (prop === "then") {
if (target instanceof Promise)
return target.then.bind(target);
} else if (!(prop in target)) {
if (this.filterPublicKeys.includes(prop))
return void 0;
throw this.createError(
`[vitest] No "${String(prop)}" export is defined on the "${mockpath}" mock. Did you forget to return it from "vi.mock"?
If you need to partially mock a module, you can use "importOriginal" helper inside:
`,
highlight(`vi.mock("${mockpath}", async (importOriginal) => {
const actual = await importOriginal()
return {
...actual,
// your mocked methods
}
})`)
);
}
return val;
}
});
this.moduleCache.set(dep, { exports: moduleExports });
return moduleExports;
}
getMockContext() {
return this.mockContext;
}
getMockPath(dep) {
return `mock:${dep}`;
}
getDependencyMock(id) {
return this.getMocks()[id];
}
normalizePath(path) {
return this.moduleCache.normalizePath(path);
}
resolveMockPath(mockPath, external) {
const path = external || mockPath;
if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) {
const mockDirname = dirname(path);
const mockFolder = join(this.root, "__mocks__", mockDirname);
if (!existsSync(mockFolder))
return null;
const files = readdirSync(mockFolder);
const baseOriginal = basename(path);
for (const file of files) {
const baseFile = basename(file, extname(file));
if (baseFile === baseOriginal)
return resolve(mockFolder, file);
}
return null;
}
const dir = dirname(path);
const baseId = basename(path);
const fullPath = resolve(dir, "__mocks__", baseId);
return existsSync(fullPath) ? fullPath : null;
}
mockObject(object, mockExports = {}) {
const finalizers = new Array();
const refs = new RefTracker();
const define = (container, key, value) => {
try {
container[key] = value;
return true;
} catch {
return false;
}
};
const mockPropertiesOf = (container, newContainer) => {
const containerType = getType(container);
const isModule = containerType === "Module" || !!container.__esModule;
for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, this.primitives)) {
if (!isModule && descriptor.get) {
try {
Object.defineProperty(newContainer, property, descriptor);
} catch (error) {
}
continue;
}
if (isSpecialProp(property, containerType))
continue;
const value = container[property];
const refId = refs.getId(value);
if (refId !== void 0) {
finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId)));
continue;
}
const type = getType(value);
if (Array.isArray(value)) {
define(newContainer, property, []);
continue;
}
const isFunction = type.includes("Function") && typeof value === "function";
if ((!isFunction || value.__isMockFunction) && type !== "Object" && type !== "Module") {
define(newContainer, property, value);
continue;
}
if (!define(newContainer, property, isFunction ? value : {}))
continue;
if (isFunction) {
let mockFunction2 = function() {
if (this instanceof newContainer[property]) {
for (const { key, descriptor: descriptor2 } of getAllMockableProperties(this, false, primitives)) {
if (descriptor2.get)
continue;
const value2 = this[key];
const type2 = getType(value2);
const isFunction2 = type2.includes("Function") && typeof value2 === "function";
if (isFunction2) {
const original = this[key];
const mock2 = spyModule.spyOn(this, key).mockImplementation(original);
mock2.mockRestore = () => {
mock2.mockReset();
mock2.mockImplementation(original);
return mock2;
};
}
}
}
};
if (!this.spyModule)
throw this.createError("[vitest] `spyModule` is not defined. This is Vitest error. Please open a new issue with reproduction.");
const spyModule = this.spyModule;
const primitives = this.primitives;
const mock = spyModule.spyOn(newContainer, property).mockImplementation(mockFunction2);
mock.mockRestore = () => {
mock.mockReset();
mock.mockImplementation(mockFunction2);
return mock;
};
Object.defineProperty(newContainer[property], "length", { value: 0 });
}
refs.track(value, newContainer[property]);
mockPropertiesOf(value, newContainer[property]);
}
};
const mockedObject = mockExports;
mockPropertiesOf(object, mockedObject);
for (const finalizer of finalizers)
finalizer();
return mockedObject;
}
unmockPath(path) {
const suitefile = this.getSuiteFilepath();
const id = this.normalizePath(path);
const mock = this.mockMap.get(suitefile);
if (mock && id in mock)
delete mock[id];
this.deleteCachedItem(id);
}
mockPath(originalId, path, external, factory) {
const id = this.normalizePath(path);
const suitefile = this.getSuiteFilepath();
const mocks = this.mockMap.get(suitefile) || {};
const resolves = this.resolveCache.get(suitefile) || {};
mocks[id] = factory || this.resolveMockPath(path, external);
resolves[id] = originalId;
this.mockMap.set(suitefile, mocks);
this.resolveCache.set(suitefile, resolves);
this.deleteCachedItem(id);
}
async importActual(rawId, importer, callstack) {
const { id, fsPath } = await this.resolvePath(rawId, importer);
const result = await this.executor.cachedRequest(id, fsPath, callstack || [importer]);
return result;
}
async importMock(rawId, importee) {
const { id, fsPath, external } = await this.resolvePath(rawId, importee);
const normalizedId = this.normalizePath(fsPath);
let mock = this.getDependencyMock(normalizedId);
if (mock === void 0)
mock = this.resolveMockPath(fsPath, external);
if (mock === null) {
const mod = await this.executor.cachedRequest(id, fsPath, [importee]);
return this.mockObject(mod);
}
if (typeof mock === "function")
return this.callFunctionMock(fsPath, mock);
return this.executor.dependencyRequest(mock, mock, [importee]);
}
async requestWithMock(url, callstack) {
const id = this.normalizePath(url);
const mock = this.getDependencyMock(id);
const mockPath = this.getMockPath(id);
if (mock === null) {
const cache = this.moduleCache.get(mockPath);
if (cache.exports)
return cache.exports;
const exports = {};
this.moduleCache.set(mockPath, { exports });
const mod = await this.executor.directRequest(url, url, callstack);
this.mockObject(mod, exports);
return exports;
}
if (typeof mock === "function" && !callstack.includes(mockPath) && !callstack.includes(url)) {
try {
callstack.push(mockPath);
this.mockContext.callstack = callstack;
return await this.callFunctionMock(mockPath, mock);
} finally {
this.mockContext.callstack = null;
const indexMock = callstack.indexOf(mockPath);
callstack.splice(indexMock, 1);
}
}
if (typeof mock === "string" && !callstack.includes(mock))
return mock;
}
queueMock(id, importer, factory, throwIfCached = false) {
VitestMocker.pendingIds.push({ type: "mock", id, importer, factory, throwIfCached });
}
queueUnmock(id, importer, throwIfCached = false) {
VitestMocker.pendingIds.push({ type: "unmock", id, importer, throwIfCached });
}
}
async function createVitestExecutor(options) {
const runner = new VitestExecutor(options);
await runner.executeId("/@vite/env");
await runner.mocker.initializeSpyModule();
return runner;
}
const externalizeMap = /* @__PURE__ */ new Map();
const bareVitestRegexp = /^@?vitest(\/|$)/;
const dispose = [];
function listenForErrors(state) {
dispose.forEach((fn) => fn());
dispose.length = 0;
function catchError(err, type) {
var _a;
const worker = state();
const error = processError(err);
if (!isPrimitive(error)) {
error.VITEST_TEST_NAME = (_a = worker.current) == null ? void 0 : _a.name;
if (worker.filepath)
error.VITEST_TEST_PATH = relative(state().config.root, worker.filepath);
error.VITEST_AFTER_ENV_TEARDOWN = worker.environmentTeardownRun;
}
state().rpc.onUnhandledError(error, type);
}
const uncaughtException = (e) => catchError(e, "Uncaught Exception");
const unhandledRejection = (e) => catchError(e, "Unhandled Rejection");
process.on("uncaughtException", uncaughtException);
process.on("unhandledRejection", unhandledRejection);
dispose.push(() => {
process.off("uncaughtException", uncaughtException);
process.off("unhandledRejection", unhandledRejection);
});
}
async function startVitestExecutor(options) {
const state = () => globalThis.__vitest_worker__ || options.state;
const rpc = () => state().rpc;
process.exit = (code = process.exitCode || 0) => {
throw new Error(`process.exit unexpectedly called with "${code}"`);
};
listenForErrors(state);
const getTransformMode = () => {
return state().environment.transformMode ?? "ssr";
};
return await createVitestExecutor({
async fetchModule(id) {
if (externalizeMap.has(id))
return { externalize: externalizeMap.get(id) };
if (id.includes(distDir)) {
const { path } = toFilePath(id, state().config.root);
const externalize = pathToFileURL(path).toString();
externalizeMap.set(id, externalize);
return { externalize };
}
if (bareVitestRegexp.test(id)) {
externalizeMap.set(id, id);
return { externalize: id };
}
const result = await rpc().fetch(id, getTransformMode());
if (result.id && !result.externalize) {
const code = readFileSync(result.id, "utf-8");
return { code };
}
return result;
},
resolveId(id, importer) {
return rpc().resolveId(id, importer, getTransformMode());
},
get moduleCache() {
return state().moduleCache;
},
get mockMap() {
return state().mockMap;
},
get interopDefault() {
return state().config.deps.interopDefault;
},
get moduleDirectories() {
return state().config.deps.moduleDirectories;
},
get root() {
return state().config.root;
},
get base() {
return state().config.base;
},
...options
});
}
function updateStyle(id, css) {
if (typeof document === "undefined")
return;
const element = document.querySelector(`[data-vite-dev-id="${id}"]`);
if (element) {
element.textContent = css;
return;
}
const head = document.querySelector("head");
const style = document.createElement("style");
style.setAttribute("type", "text/css");
style.setAttribute("data-vite-dev-id", id);
style.textContent = css;
head == null ? void 0 : head.appendChild(style);
}
function removeStyle(id) {
if (typeof document === "undefined")
return;
const sheet = document.querySelector(`[data-vite-dev-id="${id}"]`);
if (sheet)
document.head.removeChild(sheet);
}
function getDefaultRequestStubs(context) {
if (!context) {
const clientStub2 = { ...DEFAULT_REQUEST_STUBS["@vite/client"], updateStyle, removeStyle };
return {
"/@vite/client": clientStub2,
"@vite/client": clientStub2
};
}
const clientStub = vm.runInContext(
`(defaultClient) => ({ ...defaultClient, updateStyle: ${updateStyle.toString()}, removeStyle: ${removeStyle.toString()} })`,
context
)(DEFAULT_REQUEST_STUBS["@vite/client"]);
return {
"/@vite/client": clientStub,
"@vite/client": clientStub
};
}
class VitestExecutor extends ViteNodeRunner {
constructor(options) {
super({
...options,
// interop is done inside the external executor instead
interopDefault: options.context ? false : options.interopDefault
});
this.options = options;
this.mocker = new VitestMocker(this);
if (!options.context) {
Object.defineProperty(globalThis, "__vitest_mocker__", {
value: this.mocker,
writable: true,
configurable: true
});
this.primitives = { Object, Reflect, Symbol };
} else if (options.externalModulesExecutor) {
this.primitives = vm.runInContext("({ Object, Reflect, Symbol })", options.context);
this.externalModules = options.externalModulesExecutor;
} else {
throw new Error("When context is provided, externalModulesExecutor must be provided as well.");
}
}
mocker;
externalModules;
primitives;
getContextPrimitives() {
return this.primitives;
}
get state() {
return globalThis.__vitest_worker__ || this.options.state;
}
shouldResolveId(id, _importee) {
var _a;
if (isInternalRequest(id) || id.startsWith("data:"))
return false;
const transformMode = ((_a = this.state.environment) == null ? void 0 : _a.transformMode) ?? "ssr";
return transformMode === "ssr" ? !isNodeBuiltin(id) : !id.startsWith("node:");
}
async originalResolveUrl(id, importer) {
return super.resolveUrl(id, importer);
}
async resolveUrl(id, importer) {
if (VitestMocker.pendingIds.length)
await this.mocker.resolveMocks();
if (importer && importer.startsWith("mock:"))
importer = importer.slice(5);
try {
return await super.resolveUrl(id, importer);
} catch (error) {
if (error.code === "ERR_MODULE_NOT_FOUND") {
const { id: id2 } = error[Symbol.for("vitest.error.not_found.data")];
const path = this.mocker.normalizePath(id2);
const mock = this.mocker.getDependencyMock(path);
if (mock !== void 0)
return [id2, id2];
}
throw error;
}
}
async runModule(context, transformed) {
const vmContext = this.options.context;
if (!vmContext || !this.externalModules)
return super.runModule(context, transformed);
const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
const code = `${codeDefinition}${transformed}
}}`;
const options = {
filename: context.__filename,
lineOffset: 0,
columnOffset: -codeDefinition.length
};
const fn = vm.runInContext(code, vmContext, {
...options,
// if we encountered an import, it's not inlined
importModuleDynamically: this.externalModules.importModuleDynamically
});
await fn(...Object.values(context));
}
async importExternalModule(path) {
if (this.externalModules)
return this.externalModules.import(path);
return super.importExternalModule(path);
}
async dependencyRequest(id, fsPath, callstack) {
const mocked = await this.mocker.requestWithMock(fsPath, callstack);
if (typeof mocked === "string")
return super.dependencyRequest(mocked, mocked, callstack);
if (mocked && typeof mocked === "object")
return mocked;
return super.dependencyRequest(id, fsPath, callstack);
}
prepareContext(context) {
if (this.state.filepath && normalize(this.state.filepath) === normalize(context.__filename)) {
const globalNamespace = this.options.context || globalThis;
Object.defineProperty(context.__vite_ssr_import_meta__, "vitest", { get: () => globalNamespace.__vitest_index__ });
}
if (this.options.context && this.externalModules)
context.require = this.externalModules.createRequire(context.__filename);
return context;
}
}
export { VitestExecutor as V, getDefaultRequestStubs as g, startVitestExecutor as s };

View File

@@ -0,0 +1,23 @@
function getWorkerState() {
const workerState = globalThis.__vitest_worker__;
if (!workerState) {
const errorMsg = 'Vitest failed to access its internal state.\n\nOne of the following is possible:\n- "vitest" is imported directly without running "vitest" command\n- "vitest" is imported inside "globalSetup" (to fix this, use "setupFiles" instead, because "globalSetup" runs in a different context)\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n';
throw new Error(errorMsg);
}
return workerState;
}
function provideWorkerState(context, state) {
Object.defineProperty(context, "__vitest_worker__", {
value: state,
configurable: true,
writable: true,
enumerable: false
});
return state;
}
function getCurrentEnvironment() {
const state = getWorkerState();
return state == null ? void 0 : state.environment.name;
}
export { getCurrentEnvironment as a, getWorkerState as g, provideWorkerState as p };

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,99 @@
const DEFAULT_TIMEOUT = 6e4;
function defaultSerialize(i) {
return i;
}
const defaultDeserialize = defaultSerialize;
const { clearTimeout, setTimeout } = globalThis;
const random = Math.random.bind(Math);
function createBirpc(functions, options) {
const {
post,
on,
eventNames = [],
serialize = defaultSerialize,
deserialize = defaultDeserialize,
resolver,
timeout = DEFAULT_TIMEOUT
} = options;
const rpcPromiseMap = /* @__PURE__ */ new Map();
let _promise;
const rpc = new Proxy({}, {
get(_, method) {
if (method === "$functions")
return functions;
const sendEvent = (...args) => {
post(serialize({ m: method, a: args, t: "q" }));
};
if (eventNames.includes(method)) {
sendEvent.asEvent = sendEvent;
return sendEvent;
}
const sendCall = async (...args) => {
await _promise;
return new Promise((resolve, reject) => {
const id = nanoid();
let timeoutId;
if (timeout >= 0) {
timeoutId = setTimeout(() => {
try {
options.onTimeoutError?.(method, args);
throw new Error(`[birpc] timeout on calling "${method}"`);
} catch (e) {
reject(e);
}
rpcPromiseMap.delete(id);
}, timeout).unref?.();
}
rpcPromiseMap.set(id, { resolve, reject, timeoutId });
post(serialize({ m: method, a: args, i: id, t: "q" }));
});
};
sendCall.asEvent = sendEvent;
return sendCall;
}
});
_promise = on(async (data, ...extra) => {
const msg = deserialize(data);
if (msg.t === "q") {
const { m: method, a: args } = msg;
let result, error;
const fn = resolver ? resolver(method, functions[method]) : functions[method];
if (!fn) {
error = new Error(`[birpc] function "${method}" not found`);
} else {
try {
result = await fn.apply(rpc, args);
} catch (e) {
error = e;
}
}
if (msg.i) {
if (error && options.onError)
options.onError(error, method, args);
post(serialize({ t: "s", i: msg.i, r: result, e: error }), ...extra);
}
} else {
const { i: ack, r: result, e: error } = msg;
const promise = rpcPromiseMap.get(ack);
if (promise) {
clearTimeout(promise.timeoutId);
if (error)
promise.reject(error);
else
promise.resolve(result);
}
rpcPromiseMap.delete(ack);
}
});
return rpc;
}
const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
function nanoid(size = 21) {
let id = "";
let i = size;
while (i--)
id += urlAlphabet[random() * 64 | 0];
return id;
}
export { createBirpc as c };

View File

@@ -0,0 +1,99 @@
import * as chai from 'chai';
import { resolve } from 'pathe';
import { distDir } from '../path.js';
import { g as getWorkerState } from './global.CkGT_TMy.js';
import { r as rpc } from './rpc.joBhAkyK.js';
import { t as takeCoverageInsideWorker } from './coverage.E7sG1b3r.js';
import { l as loadDiffConfig, a as loadSnapshotSerializers } from './setup-common.8nJLd4ay.js';
function setupChaiConfig(config) {
Object.assign(chai.config, config);
}
async function resolveSnapshotEnvironment(config, executor) {
if (!config.snapshotEnvironment) {
const { VitestNodeSnapshotEnvironment } = await import('../chunks/environments-node.vcoXCoKs.js');
return new VitestNodeSnapshotEnvironment();
}
const mod = await executor.executeId(config.snapshotEnvironment);
if (typeof mod.default !== "object" || !mod.default)
throw new Error("Snapshot environment module must have a default export object with a shape of `SnapshotEnvironment`");
return mod.default;
}
const runnersFile = resolve(distDir, "runners.js");
async function getTestRunnerConstructor(config, executor) {
if (!config.runner) {
const { VitestTestRunner, NodeBenchmarkRunner } = await executor.executeFile(runnersFile);
return config.mode === "test" ? VitestTestRunner : NodeBenchmarkRunner;
}
const mod = await executor.executeId(config.runner);
if (!mod.default && typeof mod.default !== "function")
throw new Error(`Runner must export a default function, but got ${typeof mod.default} imported from ${config.runner}`);
return mod.default;
}
async function resolveTestRunner(config, executor) {
const TestRunner = await getTestRunnerConstructor(config, executor);
const testRunner = new TestRunner(config);
Object.defineProperty(testRunner, "__vitest_executor", {
value: executor,
enumerable: false,
configurable: false
});
if (!testRunner.config)
testRunner.config = config;
if (!testRunner.importFile)
throw new Error('Runner must implement "importFile" method.');
const [diffOptions] = await Promise.all([
loadDiffConfig(config, executor),
loadSnapshotSerializers(config, executor)
]);
testRunner.config.diffOptions = diffOptions;
const originalOnTaskUpdate = testRunner.onTaskUpdate;
testRunner.onTaskUpdate = async (task) => {
const p = rpc().onTaskUpdate(task);
await (originalOnTaskUpdate == null ? void 0 : originalOnTaskUpdate.call(testRunner, task));
return p;
};
const originalOnCollected = testRunner.onCollected;
testRunner.onCollected = async (files) => {
const state = getWorkerState();
files.forEach((file) => {
file.prepareDuration = state.durations.prepare;
file.environmentLoad = state.durations.environment;
state.durations.prepare = 0;
state.durations.environment = 0;
});
rpc().onCollected(files);
await (originalOnCollected == null ? void 0 : originalOnCollected.call(testRunner, files));
};
const originalOnAfterRun = testRunner.onAfterRunFiles;
testRunner.onAfterRunFiles = async (files) => {
const state = getWorkerState();
const coverage = await takeCoverageInsideWorker(config.coverage, executor);
if (coverage) {
rpc().onAfterSuiteRun({
coverage,
transformMode: state.environment.transformMode,
projectName: state.ctx.projectName
});
}
await (originalOnAfterRun == null ? void 0 : originalOnAfterRun.call(testRunner, files));
};
const originalOnAfterRunTask = testRunner.onAfterRunTask;
testRunner.onAfterRunTask = async (test) => {
var _a, _b;
if (config.bail && ((_a = test.result) == null ? void 0 : _a.state) === "fail") {
const previousFailures = await rpc().getCountOfFailedTests();
const currentFailures = 1 + previousFailures;
if (currentFailures >= config.bail) {
rpc().onCancel("test-failure");
(_b = testRunner.onCancel) == null ? void 0 : _b.call(testRunner, "test-failure");
}
}
await (originalOnAfterRunTask == null ? void 0 : originalOnAfterRunTask.call(testRunner, test));
};
return testRunner;
}
export { resolveSnapshotEnvironment as a, resolveTestRunner as r, setupChaiConfig as s };

View File

@@ -0,0 +1,678 @@
import { Console } from 'node:console';
const denyList = /* @__PURE__ */ new Set([
"GLOBAL",
"root",
"global",
"Buffer",
"ArrayBuffer",
"Uint8Array"
]);
const nodeGlobals = new Map(
Object.getOwnPropertyNames(globalThis).filter((global) => !denyList.has(global)).map((nodeGlobalsKey) => {
const descriptor = Object.getOwnPropertyDescriptor(
globalThis,
nodeGlobalsKey
);
if (!descriptor) {
throw new Error(
`No property descriptor for ${nodeGlobalsKey}, this is a bug in Vitest.`
);
}
return [nodeGlobalsKey, descriptor];
})
);
var node = {
name: "node",
transformMode: "ssr",
// this is largely copied from jest's node environment
async setupVM() {
const vm = await import('node:vm');
let context = vm.createContext();
let global = vm.runInContext(
"this",
context
);
const contextGlobals = new Set(Object.getOwnPropertyNames(global));
for (const [nodeGlobalsKey, descriptor] of nodeGlobals) {
if (!contextGlobals.has(nodeGlobalsKey)) {
if (descriptor.configurable) {
Object.defineProperty(global, nodeGlobalsKey, {
configurable: true,
enumerable: descriptor.enumerable,
get() {
const val = globalThis[nodeGlobalsKey];
Object.defineProperty(global, nodeGlobalsKey, {
configurable: true,
enumerable: descriptor.enumerable,
value: val,
writable: descriptor.writable === true || nodeGlobalsKey === "performance"
});
return val;
},
set(val) {
Object.defineProperty(global, nodeGlobalsKey, {
configurable: true,
enumerable: descriptor.enumerable,
value: val,
writable: true
});
}
});
} else if ("value" in descriptor) {
Object.defineProperty(global, nodeGlobalsKey, {
configurable: false,
enumerable: descriptor.enumerable,
value: descriptor.value,
writable: descriptor.writable
});
} else {
Object.defineProperty(global, nodeGlobalsKey, {
configurable: false,
enumerable: descriptor.enumerable,
get: descriptor.get,
set: descriptor.set
});
}
}
}
global.global = global;
global.Buffer = Buffer;
global.ArrayBuffer = ArrayBuffer;
global.Uint8Array = Uint8Array;
return {
getVmContext() {
return context;
},
teardown() {
context = void 0;
global = void 0;
}
};
},
async setup(global) {
global.console.Console = Console;
return {
teardown(global2) {
delete global2.console.Console;
}
};
}
};
const LIVING_KEYS = [
"DOMException",
"URL",
"URLSearchParams",
"EventTarget",
"NamedNodeMap",
"Node",
"Attr",
"Element",
"DocumentFragment",
"DOMImplementation",
"Document",
"XMLDocument",
"CharacterData",
"Text",
"CDATASection",
"ProcessingInstruction",
"Comment",
"DocumentType",
"NodeList",
"RadioNodeList",
"HTMLCollection",
"HTMLOptionsCollection",
"DOMStringMap",
"DOMTokenList",
"StyleSheetList",
"HTMLElement",
"HTMLHeadElement",
"HTMLTitleElement",
"HTMLBaseElement",
"HTMLLinkElement",
"HTMLMetaElement",
"HTMLStyleElement",
"HTMLBodyElement",
"HTMLHeadingElement",
"HTMLParagraphElement",
"HTMLHRElement",
"HTMLPreElement",
"HTMLUListElement",
"HTMLOListElement",
"HTMLLIElement",
"HTMLMenuElement",
"HTMLDListElement",
"HTMLDivElement",
"HTMLAnchorElement",
"HTMLAreaElement",
"HTMLBRElement",
"HTMLButtonElement",
"HTMLCanvasElement",
"HTMLDataElement",
"HTMLDataListElement",
"HTMLDetailsElement",
"HTMLDialogElement",
"HTMLDirectoryElement",
"HTMLFieldSetElement",
"HTMLFontElement",
"HTMLFormElement",
"HTMLHtmlElement",
"HTMLImageElement",
"HTMLInputElement",
"HTMLLabelElement",
"HTMLLegendElement",
"HTMLMapElement",
"HTMLMarqueeElement",
"HTMLMediaElement",
"HTMLMeterElement",
"HTMLModElement",
"HTMLOptGroupElement",
"HTMLOptionElement",
"HTMLOutputElement",
"HTMLPictureElement",
"HTMLProgressElement",
"HTMLQuoteElement",
"HTMLScriptElement",
"HTMLSelectElement",
"HTMLSlotElement",
"HTMLSourceElement",
"HTMLSpanElement",
"HTMLTableCaptionElement",
"HTMLTableCellElement",
"HTMLTableColElement",
"HTMLTableElement",
"HTMLTimeElement",
"HTMLTableRowElement",
"HTMLTableSectionElement",
"HTMLTemplateElement",
"HTMLTextAreaElement",
"HTMLUnknownElement",
"HTMLFrameElement",
"HTMLFrameSetElement",
"HTMLIFrameElement",
"HTMLEmbedElement",
"HTMLObjectElement",
"HTMLParamElement",
"HTMLVideoElement",
"HTMLAudioElement",
"HTMLTrackElement",
"HTMLFormControlsCollection",
"SVGElement",
"SVGGraphicsElement",
"SVGSVGElement",
"SVGTitleElement",
"SVGAnimatedString",
"SVGNumber",
"SVGStringList",
"Event",
"CloseEvent",
"CustomEvent",
"MessageEvent",
"ErrorEvent",
"HashChangeEvent",
"PopStateEvent",
"StorageEvent",
"ProgressEvent",
"PageTransitionEvent",
"SubmitEvent",
"UIEvent",
"FocusEvent",
"InputEvent",
"MouseEvent",
"KeyboardEvent",
"TouchEvent",
"CompositionEvent",
"WheelEvent",
"BarProp",
"External",
"Location",
"History",
"Screen",
"Crypto",
"Performance",
"Navigator",
"PluginArray",
"MimeTypeArray",
"Plugin",
"MimeType",
"FileReader",
"Blob",
"File",
"FileList",
"ValidityState",
"DOMParser",
"XMLSerializer",
"FormData",
"XMLHttpRequestEventTarget",
"XMLHttpRequestUpload",
"XMLHttpRequest",
"WebSocket",
"NodeFilter",
"NodeIterator",
"TreeWalker",
"AbstractRange",
"Range",
"StaticRange",
"Selection",
"Storage",
"CustomElementRegistry",
"ShadowRoot",
"MutationObserver",
"MutationRecord",
"Headers",
"AbortController",
"AbortSignal",
"Uint8Array",
"Uint16Array",
"Uint32Array",
"Uint8ClampedArray",
"Int8Array",
"Int16Array",
"Int32Array",
"Float32Array",
"Float64Array",
"ArrayBuffer",
"DOMRectReadOnly",
"DOMRect",
// not specified in docs, but is available
"Image",
"Audio",
"Option",
"CSS"
];
const OTHER_KEYS = [
"addEventListener",
"alert",
// 'atob',
"blur",
// 'btoa',
"cancelAnimationFrame",
/* 'clearInterval', */
/* 'clearTimeout', */
"close",
"confirm",
/* 'console', */
"createPopup",
"dispatchEvent",
"document",
"focus",
"frames",
"getComputedStyle",
"history",
"innerHeight",
"innerWidth",
"length",
"location",
"matchMedia",
"moveBy",
"moveTo",
"name",
"navigator",
"open",
"outerHeight",
"outerWidth",
"pageXOffset",
"pageYOffset",
"parent",
"postMessage",
"print",
"prompt",
"removeEventListener",
"requestAnimationFrame",
"resizeBy",
"resizeTo",
"screen",
"screenLeft",
"screenTop",
"screenX",
"screenY",
"scroll",
"scrollBy",
"scrollLeft",
"scrollTo",
"scrollTop",
"scrollX",
"scrollY",
"self",
/* 'setInterval', */
/* 'setTimeout', */
"stop",
/* 'toString', */
"top",
"Window",
"window"
];
const KEYS = LIVING_KEYS.concat(OTHER_KEYS);
const skipKeys = [
"window",
"self",
"top",
"parent"
];
function getWindowKeys(global, win, additionalKeys = []) {
const keysArray = [...additionalKeys, ...KEYS];
const keys = new Set(keysArray.concat(Object.getOwnPropertyNames(win)).filter((k) => {
if (skipKeys.includes(k))
return false;
if (k in global)
return keysArray.includes(k);
return true;
}));
return keys;
}
function isClassLikeName(name) {
return name[0] === name[0].toUpperCase();
}
function populateGlobal(global, win, options = {}) {
const { bindFunctions = false } = options;
const keys = getWindowKeys(global, win, options.additionalKeys);
const originals = /* @__PURE__ */ new Map();
const overrideObject = /* @__PURE__ */ new Map();
for (const key of keys) {
const boundFunction = bindFunctions && typeof win[key] === "function" && !isClassLikeName(key) && win[key].bind(win);
if (KEYS.includes(key) && key in global)
originals.set(key, global[key]);
Object.defineProperty(global, key, {
get() {
if (overrideObject.has(key))
return overrideObject.get(key);
if (boundFunction)
return boundFunction;
return win[key];
},
set(v) {
overrideObject.set(key, v);
},
configurable: true
});
}
global.window = global;
global.self = global;
global.top = global;
global.parent = global;
if (global.global)
global.global = global;
if (global.document && global.document.defaultView) {
Object.defineProperty(global.document, "defaultView", {
get: () => global,
enumerable: true,
configurable: true
});
}
skipKeys.forEach((k) => keys.add(k));
return {
keys,
skipKeys,
originals
};
}
function catchWindowErrors(window) {
let userErrorListenerCount = 0;
function throwUnhandlerError(e) {
if (userErrorListenerCount === 0 && e.error != null)
process.emit("uncaughtException", e.error);
}
const addEventListener = window.addEventListener.bind(window);
const removeEventListener = window.removeEventListener.bind(window);
window.addEventListener("error", throwUnhandlerError);
window.addEventListener = function(...args) {
if (args[0] === "error")
userErrorListenerCount++;
return addEventListener.apply(this, args);
};
window.removeEventListener = function(...args) {
if (args[0] === "error" && userErrorListenerCount)
userErrorListenerCount--;
return removeEventListener.apply(this, args);
};
return function clearErrorHandlers() {
window.removeEventListener("error", throwUnhandlerError);
};
}
var jsdom = {
name: "jsdom",
transformMode: "web",
async setupVM({ jsdom = {} }) {
const {
CookieJar,
JSDOM,
ResourceLoader,
VirtualConsole
} = await import('jsdom');
const {
html = "<!DOCTYPE html>",
userAgent,
url = "http://localhost:3000",
contentType = "text/html",
pretendToBeVisual = true,
includeNodeLocations = false,
runScripts = "dangerously",
resources,
console = false,
cookieJar = false,
...restOptions
} = jsdom;
let dom = new JSDOM(
html,
{
pretendToBeVisual,
resources: resources ?? (userAgent ? new ResourceLoader({ userAgent }) : void 0),
runScripts,
url,
virtualConsole: console && globalThis.console ? new VirtualConsole().sendTo(globalThis.console) : void 0,
cookieJar: cookieJar ? new CookieJar() : void 0,
includeNodeLocations,
contentType,
userAgent,
...restOptions
}
);
const clearWindowErrors = catchWindowErrors(dom.window);
dom.window.Buffer = Buffer;
dom.window.jsdom = dom;
const globalNames = [
"structuredClone",
"fetch",
"Request",
"Response",
"BroadcastChannel",
"MessageChannel",
"MessagePort",
"TextEncoder",
"TextDecoder"
];
for (const name of globalNames) {
const value = globalThis[name];
if (typeof value !== "undefined" && typeof dom.window[name] === "undefined")
dom.window[name] = value;
}
return {
getVmContext() {
return dom.getInternalVMContext();
},
teardown() {
clearWindowErrors();
dom.window.close();
dom = void 0;
}
};
},
async setup(global, { jsdom = {} }) {
const {
CookieJar,
JSDOM,
ResourceLoader,
VirtualConsole
} = await import('jsdom');
const {
html = "<!DOCTYPE html>",
userAgent,
url = "http://localhost:3000",
contentType = "text/html",
pretendToBeVisual = true,
includeNodeLocations = false,
runScripts = "dangerously",
resources,
console = false,
cookieJar = false,
...restOptions
} = jsdom;
const dom = new JSDOM(
html,
{
pretendToBeVisual,
resources: resources ?? (userAgent ? new ResourceLoader({ userAgent }) : void 0),
runScripts,
url,
virtualConsole: console && global.console ? new VirtualConsole().sendTo(global.console) : void 0,
cookieJar: cookieJar ? new CookieJar() : void 0,
includeNodeLocations,
contentType,
userAgent,
...restOptions
}
);
const { keys, originals } = populateGlobal(global, dom.window, { bindFunctions: true });
const clearWindowErrors = catchWindowErrors(global);
global.jsdom = dom;
return {
teardown(global2) {
clearWindowErrors();
dom.window.close();
delete global2.jsdom;
keys.forEach((key) => delete global2[key]);
originals.forEach((v, k) => global2[k] = v);
}
};
}
};
async function teardownWindow(win) {
if (win.close && win.happyDOM.abort) {
await win.happyDOM.abort();
win.close();
} else {
win.happyDOM.cancelAsync();
}
}
var happy = {
name: "happy-dom",
transformMode: "web",
async setupVM({ happyDOM = {} }) {
const { Window } = await import('happy-dom');
let win = new Window({
...happyDOM,
console: console && globalThis.console ? globalThis.console : void 0,
url: happyDOM.url || "http://localhost:3000",
settings: {
...happyDOM.settings,
disableErrorCapturing: true
}
});
win.Buffer = Buffer;
if (typeof structuredClone !== "undefined" && !win.structuredClone)
win.structuredClone = structuredClone;
return {
getVmContext() {
return win;
},
async teardown() {
await teardownWindow(win);
win = void 0;
}
};
},
async setup(global, { happyDOM = {} }) {
const { Window, GlobalWindow } = await import('happy-dom');
const win = new (GlobalWindow || Window)({
...happyDOM,
console: console && global.console ? global.console : void 0,
url: happyDOM.url || "http://localhost:3000",
settings: {
...happyDOM.settings,
disableErrorCapturing: true
}
});
const { keys, originals } = populateGlobal(global, win, {
bindFunctions: true,
// jsdom doesn't support Request and Response, but happy-dom does
additionalKeys: ["Request", "Response"]
});
return {
async teardown(global2) {
await teardownWindow(win);
keys.forEach((key) => delete global2[key]);
originals.forEach((v, k) => global2[k] = v);
}
};
}
};
var edge = {
name: "edge-runtime",
transformMode: "ssr",
async setupVM() {
const { EdgeVM } = await import('@edge-runtime/vm');
const vm = new EdgeVM({
extend: (context) => {
context.global = context;
context.Buffer = Buffer;
return context;
}
});
return {
getVmContext() {
return vm.context;
},
teardown() {
}
};
},
async setup(global) {
const { EdgeVM } = await import('@edge-runtime/vm');
const vm = new EdgeVM({
extend: (context) => {
context.global = context;
context.Buffer = Buffer;
KEYS.forEach((key) => {
if (key in global)
context[key] = global[key];
});
return context;
}
});
const { keys, originals } = populateGlobal(global, vm.context, { bindFunctions: true });
return {
teardown(global2) {
keys.forEach((key) => delete global2[key]);
originals.forEach((v, k) => global2[k] = v);
}
};
}
};
const environments = {
node,
jsdom,
"happy-dom": happy,
"edge-runtime": edge
};
const envPackageNames = {
"jsdom": "jsdom",
"happy-dom": "happy-dom",
"edge-runtime": "@edge-runtime/vm"
};
function getEnvPackageName(env) {
if (env === "node")
return null;
if (env in envPackageNames)
return envPackageNames[env];
if (env[0] === "." || env[0] === "/")
return null;
return `vitest-environment-${env}`;
}
export { environments as e, getEnvPackageName as g, populateGlobal as p };

View File

@@ -0,0 +1,22 @@
import { relative } from 'pathe';
import '@vitest/runner/utils';
import '@vitest/utils';
import { g as getWorkerState } from './global.CkGT_TMy.js';
import './env.AtSIuHFg.js';
function getRunMode() {
return getWorkerState().config.mode;
}
function isRunningInBenchmark() {
return getRunMode() === "benchmark";
}
const relativePath = relative;
function removeUndefinedValues(obj) {
for (const key in Object.keys(obj)) {
if (obj[key] === void 0)
delete obj[key];
}
return obj;
}
export { removeUndefinedValues as a, isRunningInBenchmark as i, relativePath as r };

View File

@@ -0,0 +1,129 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, suite, test } from '@vitest/runner';
import { b as bench } from './benchmark.yGkUTKnC.js';
import { i as isFirstRun, a as runOnce } from './run-once.Olz_Zkd8.js';
import { c as createExpect, a as globalExpect, v as vi, b as vitest } from './vi.YFlodzP_.js';
import { g as getWorkerState } from './global.CkGT_TMy.js';
import * as chai from 'chai';
import { assert, should } from 'chai';
function getRunningMode() {
return process.env.VITEST_MODE === "WATCH" ? "watch" : "run";
}
function isWatchMode() {
return getRunningMode() === "watch";
}
function inject(key) {
const workerState = getWorkerState();
return workerState.providedContext[key];
}
var dist = {};
(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.expectTypeOf = void 0;
const fn = () => true;
/**
* Similar to Jest's `expect`, but with type-awareness.
* Gives you access to a number of type-matchers that let you make assertions about the
* form of a reference or generic type parameter.
*
* @example
* import {foo, bar} from '../foo'
* import {expectTypeOf} from 'expect-type'
*
* test('foo types', () => {
* // make sure `foo` has type {a: number}
* expectTypeOf(foo).toMatchTypeOf({a: 1})
* expectTypeOf(foo).toHaveProperty('a').toBeNumber()
*
* // make sure `bar` is a function taking a string:
* expectTypeOf(bar).parameter(0).toBeString()
* expectTypeOf(bar).returns.not.toBeAny()
* })
*
* @description
* See the [full docs](https://npmjs.com/package/expect-type#documentation) for lots more examples.
*/
const expectTypeOf = (_actual) => {
const nonFunctionProperties = [
'parameters',
'returns',
'resolves',
'not',
'items',
'constructorParameters',
'thisParameter',
'instance',
'guards',
'asserts',
'branded',
];
const obj = {
/* eslint-disable mmkal/@typescript-eslint/no-unsafe-assignment */
toBeAny: fn,
toBeUnknown: fn,
toBeNever: fn,
toBeFunction: fn,
toBeObject: fn,
toBeArray: fn,
toBeString: fn,
toBeNumber: fn,
toBeBoolean: fn,
toBeVoid: fn,
toBeSymbol: fn,
toBeNull: fn,
toBeUndefined: fn,
toBeNullable: fn,
toMatchTypeOf: fn,
toEqualTypeOf: fn,
toBeCallableWith: fn,
toBeConstructibleWith: fn,
/* eslint-enable mmkal/@typescript-eslint/no-unsafe-assignment */
extract: exports.expectTypeOf,
exclude: exports.expectTypeOf,
toHaveProperty: exports.expectTypeOf,
parameter: exports.expectTypeOf,
};
const getterProperties = nonFunctionProperties;
getterProperties.forEach((prop) => Object.defineProperty(obj, prop, { get: () => (0, exports.expectTypeOf)({}) }));
return obj;
};
exports.expectTypeOf = expectTypeOf;
} (dist));
function noop() {
}
const assertType = noop;
var VitestIndex = /*#__PURE__*/Object.freeze({
__proto__: null,
afterAll: afterAll,
afterEach: afterEach,
assert: assert,
assertType: assertType,
beforeAll: beforeAll,
beforeEach: beforeEach,
bench: bench,
chai: chai,
createExpect: createExpect,
describe: describe,
expect: globalExpect,
expectTypeOf: dist.expectTypeOf,
getRunningMode: getRunningMode,
inject: inject,
isFirstRun: isFirstRun,
isWatchMode: isWatchMode,
it: it,
onTestFailed: onTestFailed,
onTestFinished: onTestFinished,
runOnce: runOnce,
should: should,
suite: suite,
test: test,
vi: vi,
vitest: vitest
});
export { VitestIndex as V, isWatchMode as a, assertType as b, dist as d, getRunningMode as g, inject as i };

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,54 @@
import { createRequire } from 'node:module';
const __require = createRequire(import.meta.url);
let inspector;
let session;
function setupInspect(ctx) {
const config = ctx.config;
const isEnabled = config.inspector.enabled;
if (isEnabled) {
inspector = __require("node:inspector");
const isOpen = inspector.url() !== void 0;
if (!isOpen) {
inspector.open(
config.inspector.port,
config.inspector.host,
config.inspector.waitForDebugger
);
if (config.inspectBrk) {
const firstTestFile = ctx.files[0];
if (firstTestFile) {
session = new inspector.Session();
session.connect();
session.post("Debugger.enable");
session.post("Debugger.setBreakpointByUrl", {
lineNumber: 0,
url: new URL(firstTestFile, import.meta.url).href
});
}
}
}
}
const keepOpen = shouldKeepOpen(config);
return function cleanup() {
if (isEnabled && !keepOpen && inspector) {
inspector.close();
session == null ? void 0 : session.disconnect();
}
};
}
function closeInspector(config) {
const keepOpen = shouldKeepOpen(config);
if (inspector && !keepOpen) {
inspector.close();
session == null ? void 0 : session.disconnect();
}
}
function shouldKeepOpen(config) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const isIsolatedSingleThread = config.pool === "threads" && ((_b = (_a = config.poolOptions) == null ? void 0 : _a.threads) == null ? void 0 : _b.isolate) === false && ((_d = (_c = config.poolOptions) == null ? void 0 : _c.threads) == null ? void 0 : _d.singleThread);
const isIsolatedSingleFork = config.pool === "forks" && ((_f = (_e = config.poolOptions) == null ? void 0 : _e.forks) == null ? void 0 : _f.isolate) === false && ((_h = (_g = config.poolOptions) == null ? void 0 : _g.forks) == null ? void 0 : _h.singleFork);
return config.watch && (isIsolatedSingleFork || isIsolatedSingleThread);
}
export { closeInspector as c, setupInspect as s };

View File

@@ -0,0 +1,94 @@
import { getSafeTimers } from '@vitest/utils';
import { c as createBirpc } from './index.8bPxjt7g.js';
import { g as getWorkerState } from './global.CkGT_TMy.js';
const { get } = Reflect;
function withSafeTimers(fn) {
var _a;
const { setTimeout, clearTimeout, nextTick, setImmediate, clearImmediate } = getSafeTimers();
const currentSetTimeout = globalThis.setTimeout;
const currentClearTimeout = globalThis.clearTimeout;
const currentSetImmediate = globalThis.setImmediate;
const currentClearImmediate = globalThis.clearImmediate;
const currentNextTick = (_a = globalThis.process) == null ? void 0 : _a.nextTick;
try {
globalThis.setTimeout = setTimeout;
globalThis.clearTimeout = clearTimeout;
globalThis.setImmediate = setImmediate;
globalThis.clearImmediate = clearImmediate;
if (globalThis.process)
globalThis.process.nextTick = nextTick;
const result = fn();
return result;
} finally {
globalThis.setTimeout = currentSetTimeout;
globalThis.clearTimeout = currentClearTimeout;
globalThis.setImmediate = currentSetImmediate;
globalThis.clearImmediate = currentClearImmediate;
if (globalThis.process) {
nextTick(() => {
globalThis.process.nextTick = currentNextTick;
});
}
}
}
const promises = /* @__PURE__ */ new Set();
async function rpcDone() {
if (!promises.size)
return;
const awaitable = Array.from(promises);
return Promise.all(awaitable);
}
function createRuntimeRpc(options) {
let setCancel = (_reason) => {
};
const onCancel = new Promise((resolve) => {
setCancel = resolve;
});
const rpc2 = createSafeRpc(createBirpc(
{
onCancel: setCancel
},
{
eventNames: ["onUserConsoleLog", "onFinished", "onCollected", "onCancel"],
onTimeoutError(functionName, args) {
var _a;
let message = `[vitest-worker]: Timeout calling "${functionName}"`;
if (functionName === "fetch" || functionName === "transform" || functionName === "resolveId")
message += ` with "${JSON.stringify(args)}"`;
if (functionName === "onUnhandledError")
message += ` with "${((_a = args[0]) == null ? void 0 : _a.message) || args[0]}"`;
throw new Error(message);
},
...options
}
));
return {
rpc: rpc2,
onCancel
};
}
function createSafeRpc(rpc2) {
return new Proxy(rpc2, {
get(target, p, handler) {
const sendCall = get(target, p, handler);
const safeSendCall = (...args) => withSafeTimers(async () => {
const result = sendCall(...args);
promises.add(result);
try {
return await result;
} finally {
promises.delete(result);
}
});
safeSendCall.asEvent = sendCall.asEvent;
return safeSendCall;
}
});
}
function rpc() {
const { rpc: rpc2 } = getWorkerState();
return rpc2;
}
export { rpcDone as a, createRuntimeRpc as c, rpc as r };

View File

@@ -0,0 +1,27 @@
import { g as getWorkerState } from './global.CkGT_TMy.js';
const filesCount = /* @__PURE__ */ new Map();
const cache = /* @__PURE__ */ new Map();
function runOnce(fn, key) {
const filepath = getWorkerState().filepath || "__unknown_files__";
if (!key) {
filesCount.set(filepath, (filesCount.get(filepath) || 0) + 1);
key = String(filesCount.get(filepath));
}
const id = `${filepath}:${key}`;
if (!cache.has(id))
cache.set(id, fn());
return cache.get(id);
}
function isFirstRun() {
let firstRun = false;
runOnce(() => {
firstRun = true;
}, "__vitest_first_run__");
return firstRun;
}
function resetRunOnceCounter() {
filesCount.clear();
}
export { runOnce as a, isFirstRun as i, resetRunOnceCounter as r };

View File

@@ -0,0 +1,55 @@
import { setSafeTimers } from '@vitest/utils';
import { addSerializer } from '@vitest/snapshot';
import { r as resetRunOnceCounter } from './run-once.Olz_Zkd8.js';
let globalSetup = false;
async function setupCommonEnv(config) {
resetRunOnceCounter();
setupDefines(config.defines);
setupEnv(config.env);
if (globalSetup)
return;
globalSetup = true;
setSafeTimers();
if (config.globals)
(await import('../chunks/integrations-globals.kw4co3rx.js')).registerApiGlobally();
}
function setupDefines(defines) {
for (const key in defines)
globalThis[key] = defines[key];
}
function setupEnv(env) {
if (typeof process === "undefined")
return;
const { PROD, DEV, ...restEnvs } = env;
process.env.PROD = PROD ? "1" : "";
process.env.DEV = DEV ? "1" : "";
for (const key in restEnvs)
process.env[key] = env[key];
}
async function loadDiffConfig(config, executor) {
if (typeof config.diff !== "string")
return;
const diffModule = await executor.executeId(config.diff);
if (diffModule && typeof diffModule.default === "object" && diffModule.default != null)
return diffModule.default;
else
throw new Error(`invalid diff config file ${config.diff}. Must have a default export with config object`);
}
async function loadSnapshotSerializers(config, executor) {
const files = config.snapshotSerializers;
const snapshotSerializers = await Promise.all(
files.map(async (file) => {
const mo = await executor.executeId(file);
if (!mo || typeof mo.default !== "object" || mo.default === null)
throw new Error(`invalid snapshot serializer file ${file}. Must export a default object`);
const config2 = mo.default;
if (typeof config2.test !== "function" || typeof config2.serialize !== "function" && typeof config2.print !== "function")
throw new Error(`invalid snapshot serializer in ${file}. Must have a 'test' method along with either a 'serialize' or 'print' method.`);
return config2;
})
);
snapshotSerializers.forEach((serializer) => addSerializer(serializer));
}
export { loadSnapshotSerializers as a, loadDiffConfig as l, setupCommonEnv as s };

View File

@@ -0,0 +1,14 @@
import { getNames, getTests } from '@vitest/runner/utils';
import '@vitest/utils';
function hasFailedSnapshot(suite) {
return getTests(suite).some((s) => {
var _a, _b;
return (_b = (_a = s.result) == null ? void 0 : _a.errors) == null ? void 0 : _b.some((e) => typeof (e == null ? void 0 : e.message) === "string" && e.message.match(/Snapshot .* mismatched/));
});
}
function getFullName(task, separator = " > ") {
return getNames(task).join(separator);
}
export { getFullName as g, hasFailedSnapshot as h };

View File

@@ -0,0 +1,49 @@
import { parseRegexp } from '@vitest/utils';
var _a, _b;
const REGEXP_WRAP_PREFIX = "$$vitest:";
const processSend = (_a = process.send) == null ? void 0 : _a.bind(process);
const processOn = (_b = process.on) == null ? void 0 : _b.bind(process);
function createThreadsRpcOptions({ port }) {
return {
post: (v) => {
port.postMessage(v);
},
on: (fn) => {
port.addListener("message", fn);
}
};
}
function createForksRpcOptions(nodeV8) {
return {
serialize: nodeV8.serialize,
deserialize: (v) => nodeV8.deserialize(Buffer.from(v)),
post(v) {
processSend(v);
},
on(fn) {
processOn("message", (message, ...extras) => {
if (message == null ? void 0 : message.__tinypool_worker_message__)
return;
return fn(message, ...extras);
});
}
};
}
function unwrapSerializableConfig(config) {
if (config.testNamePattern && typeof config.testNamePattern === "string") {
const testNamePattern = config.testNamePattern;
if (testNamePattern.startsWith(REGEXP_WRAP_PREFIX))
config.testNamePattern = parseRegexp(testNamePattern.slice(REGEXP_WRAP_PREFIX.length));
}
if (config.defines && Array.isArray(config.defines.keys) && config.defines.original) {
const { keys, original } = config.defines;
const defines = {};
for (const key of keys)
defines[key] = original[key];
config.defines = defines;
}
return config;
}
export { createThreadsRpcOptions as a, createForksRpcOptions as c, unwrapSerializableConfig as u };

View File

@@ -0,0 +1,217 @@
import { isAbsolute, relative, dirname, basename } from 'pathe';
import c from 'picocolors';
import { a as slash } from './base.5NT-gWu5.js';
const F_RIGHT = "\u2192";
const F_DOWN = "\u2193";
const F_DOWN_RIGHT = "\u21B3";
const F_POINTER = "\u276F";
const F_DOT = "\xB7";
const F_CHECK = "\u2713";
const F_CROSS = "\xD7";
const F_LONG_DASH = "\u23AF";
function ansiRegex({onlyFirst = false} = {}) {
const pattern = [
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
].join('|');
return new RegExp(pattern, onlyFirst ? undefined : 'g');
}
const regex = ansiRegex();
function stripAnsi(string) {
if (typeof string !== 'string') {
throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
}
// Even though the regex is global, we don't need to reset the `.lastIndex`
// because unlike `.exec()` and `.test()`, `.replace()` does it automatically
// and doing it manually has a performance penalty.
return string.replace(regex, '');
}
const spinnerMap = /* @__PURE__ */ new WeakMap();
const hookSpinnerMap = /* @__PURE__ */ new WeakMap();
const pointer = c.yellow(F_POINTER);
const skipped = c.dim(c.gray(F_DOWN));
function getCols(delta = 0) {
var _a;
let length = (_a = process.stdout) == null ? void 0 : _a.columns;
if (!length || Number.isNaN(length))
length = 30;
return Math.max(length + delta, 0);
}
function divider(text, left, right) {
const cols = getCols();
if (text) {
const textLength = stripAnsi(text).length;
if (left == null && right != null) {
left = cols - textLength - right;
} else {
left = left ?? Math.floor((cols - textLength) / 2);
right = cols - textLength - left;
}
left = Math.max(0, left);
right = Math.max(0, right);
return `${F_LONG_DASH.repeat(left)}${text}${F_LONG_DASH.repeat(right)}`;
}
return F_LONG_DASH.repeat(cols);
}
function formatTestPath(root, path) {
var _a;
if (isAbsolute(path))
path = relative(root, path);
const dir = dirname(path);
const ext = ((_a = path.match(/(\.(spec|test)\.[cm]?[tj]sx?)$/)) == null ? void 0 : _a[0]) || "";
const base = basename(path, ext);
return slash(c.dim(`${dir}/`) + c.bold(base)) + c.dim(ext);
}
function renderSnapshotSummary(rootDir, snapshots) {
const summary = [];
if (snapshots.added)
summary.push(c.bold(c.green(`${snapshots.added} written`)));
if (snapshots.unmatched)
summary.push(c.bold(c.red(`${snapshots.unmatched} failed`)));
if (snapshots.updated)
summary.push(c.bold(c.green(`${snapshots.updated} updated `)));
if (snapshots.filesRemoved) {
if (snapshots.didUpdate)
summary.push(c.bold(c.green(`${snapshots.filesRemoved} files removed `)));
else
summary.push(c.bold(c.yellow(`${snapshots.filesRemoved} files obsolete `)));
}
if (snapshots.filesRemovedList && snapshots.filesRemovedList.length) {
const [head, ...tail] = snapshots.filesRemovedList;
summary.push(`${c.gray(F_DOWN_RIGHT)} ${formatTestPath(rootDir, head)}`);
tail.forEach((key) => {
summary.push(` ${c.gray(F_DOT)} ${formatTestPath(rootDir, key)}`);
});
}
if (snapshots.unchecked) {
if (snapshots.didUpdate)
summary.push(c.bold(c.green(`${snapshots.unchecked} removed`)));
else
summary.push(c.bold(c.yellow(`${snapshots.unchecked} obsolete`)));
snapshots.uncheckedKeysByFile.forEach((uncheckedFile) => {
summary.push(`${c.gray(F_DOWN_RIGHT)} ${formatTestPath(rootDir, uncheckedFile.filePath)}`);
uncheckedFile.keys.forEach((key) => summary.push(` ${c.gray(F_DOT)} ${key}`));
});
}
return summary;
}
function countTestErrors(tasks) {
return tasks.reduce((c2, i) => {
var _a, _b;
return c2 + (((_b = (_a = i.result) == null ? void 0 : _a.errors) == null ? void 0 : _b.length) || 0);
}, 0);
}
function getStateString(tasks, name = "tests", showTotal = true) {
if (tasks.length === 0)
return c.dim(`no ${name}`);
const passed = tasks.filter((i) => {
var _a;
return ((_a = i.result) == null ? void 0 : _a.state) === "pass";
});
const failed = tasks.filter((i) => {
var _a;
return ((_a = i.result) == null ? void 0 : _a.state) === "fail";
});
const skipped2 = tasks.filter((i) => i.mode === "skip");
const todo = tasks.filter((i) => i.mode === "todo");
return [
failed.length ? c.bold(c.red(`${failed.length} failed`)) : null,
passed.length ? c.bold(c.green(`${passed.length} passed`)) : null,
skipped2.length ? c.yellow(`${skipped2.length} skipped`) : null,
todo.length ? c.gray(`${todo.length} todo`) : null
].filter(Boolean).join(c.dim(" | ")) + (showTotal ? c.gray(` (${tasks.length})`) : "");
}
function getStateSymbol(task) {
var _a;
if (task.mode === "skip" || task.mode === "todo")
return skipped;
if (!task.result)
return c.gray("\xB7");
if (task.result.state === "run") {
if (task.type === "suite")
return pointer;
let spinner = spinnerMap.get(task);
if (!spinner) {
spinner = elegantSpinner();
spinnerMap.set(task, spinner);
}
return c.yellow(spinner());
}
if (task.result.state === "pass") {
return ((_a = task.meta) == null ? void 0 : _a.benchmark) ? c.green(F_DOT) : c.green(F_CHECK);
}
if (task.result.state === "fail") {
return task.type === "suite" ? pointer : c.red(F_CROSS);
}
return " ";
}
function getHookStateSymbol(task, hookName) {
var _a, _b;
const state = (_b = (_a = task.result) == null ? void 0 : _a.hooks) == null ? void 0 : _b[hookName];
if (state && state === "run") {
let spinnerMap2 = hookSpinnerMap.get(task);
if (!spinnerMap2) {
spinnerMap2 = /* @__PURE__ */ new Map();
hookSpinnerMap.set(task, spinnerMap2);
}
let spinner = spinnerMap2.get(hookName);
if (!spinner) {
spinner = elegantSpinner();
spinnerMap2.set(hookName, spinner);
}
return c.yellow(spinner());
}
}
const spinnerFrames = process.platform === "win32" ? ["-", "\\", "|", "/"] : ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
function elegantSpinner() {
let index = 0;
return () => {
index = ++index % spinnerFrames.length;
return spinnerFrames[index];
};
}
function formatTimeString(date) {
return date.toTimeString().split(" ")[0];
}
function formatProjectName(name, suffix = " ") {
if (!name)
return "";
const index = name.split("").reduce((acc, v, idx) => acc + v.charCodeAt(0) + idx, 0);
const colors = [
c.blue,
c.yellow,
c.cyan,
c.green,
c.magenta
];
return colors[index % colors.length](`|${name}|`) + suffix;
}
var utils = /*#__PURE__*/Object.freeze({
__proto__: null,
countTestErrors: countTestErrors,
divider: divider,
elegantSpinner: elegantSpinner,
formatProjectName: formatProjectName,
formatTestPath: formatTestPath,
formatTimeString: formatTimeString,
getCols: getCols,
getHookStateSymbol: getHookStateSymbol,
getStateString: getStateString,
getStateSymbol: getStateSymbol,
hookSpinnerMap: hookSpinnerMap,
pointer: pointer,
renderSnapshotSummary: renderSnapshotSummary,
skipped: skipped,
spinnerFrames: spinnerFrames,
spinnerMap: spinnerMap
});
export { F_RIGHT as F, getStateString as a, formatTimeString as b, countTestErrors as c, divider as d, getCols as e, formatProjectName as f, getStateSymbol as g, getHookStateSymbol as h, F_POINTER as i, pointer as p, renderSnapshotSummary as r, stripAnsi as s, utils as u };

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,815 @@
import vm, { isContext } from 'node:vm';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dirname, basename, extname, normalize, join, resolve } from 'pathe';
import { createCustomConsole } from '../chunks/runtime-console.EO5ha7qv.js';
import { g as getDefaultRequestStubs, s as startVitestExecutor } from './execute.fL3szUAI.js';
import { distDir } from '../path.js';
import { dirname as dirname$1 } from 'node:path';
import { statSync, existsSync, readFileSync } from 'node:fs';
import { isNodeBuiltin, isPrimitive, toArray, getCachedData, setCacheData } from 'vite-node/utils';
import { createRequire, Module } from 'node:module';
import { CSS_LANGS_RE, KNOWN_ASSET_RE } from 'vite-node/constants';
import '@vitest/runner/utils';
import '@vitest/utils';
import { p as provideWorkerState } from './global.CkGT_TMy.js';
import './env.AtSIuHFg.js';
const _require = createRequire(import.meta.url);
const requiresCache = /* @__PURE__ */ new WeakMap();
class CommonjsExecutor {
context;
requireCache = /* @__PURE__ */ new Map();
publicRequireCache = this.createProxyCache();
moduleCache = /* @__PURE__ */ new Map();
builtinCache = /* @__PURE__ */ Object.create(null);
extensions = /* @__PURE__ */ Object.create(null);
fs;
Module;
constructor(options) {
this.context = options.context;
this.fs = options.fileMap;
const primitives = vm.runInContext("({ Object, Array, Error })", this.context);
const executor = this;
this.Module = class Module$1 {
exports;
isPreloading = false;
id;
filename;
loaded;
parent;
children = [];
path;
paths = [];
constructor(id = "", parent) {
this.exports = primitives.Object.create(Object.prototype);
this.path = dirname(id);
this.id = id;
this.filename = id;
this.loaded = false;
this.parent = parent;
}
get require() {
const require = requiresCache.get(this);
if (require)
return require;
const _require2 = Module$1.createRequire(this.id);
requiresCache.set(this, _require2);
return _require2;
}
static register = () => {
throw new Error(`[vitest] "register" is not available when running in Vitest.`);
};
_compile(code, filename) {
const cjsModule = Module$1.wrap(code);
const script = new vm.Script(cjsModule, {
filename,
importModuleDynamically: options.importModuleDynamically
});
script.identifier = filename;
const fn = script.runInContext(executor.context);
const __dirname = dirname(filename);
executor.requireCache.set(filename, this);
try {
fn(this.exports, this.require, this, filename, __dirname);
return this.exports;
} finally {
this.loaded = true;
}
}
// exposed for external use, Node.js does the opposite
static _load = (request, parent, _isMain) => {
const require = Module$1.createRequire((parent == null ? void 0 : parent.filename) ?? request);
return require(request);
};
static wrap = (script) => {
return Module$1.wrapper[0] + script + Module$1.wrapper[1];
};
static wrapper = new primitives.Array(
"(function (exports, require, module, __filename, __dirname) { ",
"\n});"
);
static builtinModules = Module.builtinModules;
static findSourceMap = Module.findSourceMap;
static SourceMap = Module.SourceMap;
static syncBuiltinESMExports = Module.syncBuiltinESMExports;
static _cache = executor.moduleCache;
static _extensions = executor.extensions;
static createRequire = (filename) => {
return executor.createRequire(filename);
};
static runMain = () => {
throw new primitives.Error('[vitest] "runMain" is not implemented.');
};
// @ts-expect-error not typed
static _resolveFilename = Module._resolveFilename;
// @ts-expect-error not typed
static _findPath = Module._findPath;
// @ts-expect-error not typed
static _initPaths = Module._initPaths;
// @ts-expect-error not typed
static _preloadModules = Module._preloadModules;
// @ts-expect-error not typed
static _resolveLookupPaths = Module._resolveLookupPaths;
// @ts-expect-error not typed
static globalPaths = Module.globalPaths;
static isBuiltin = Module.isBuiltin;
static Module = Module$1;
};
this.extensions[".js"] = this.requireJs;
this.extensions[".json"] = this.requireJson;
}
requireJs = (m, filename) => {
const content = this.fs.readFile(filename);
m._compile(content, filename);
};
requireJson = (m, filename) => {
const code = this.fs.readFile(filename);
m.exports = JSON.parse(code);
};
createRequire = (filename) => {
const _require2 = createRequire(filename);
const require = (id) => {
const resolved = _require2.resolve(id);
const ext = extname(resolved);
if (ext === ".node" || isNodeBuiltin(resolved))
return this.requireCoreModule(resolved);
const module = new this.Module(resolved);
return this.loadCommonJSModule(module, resolved);
};
require.resolve = _require2.resolve;
Object.defineProperty(require, "extensions", {
get: () => this.extensions,
set: () => {
},
configurable: true
});
require.main = void 0;
require.cache = this.publicRequireCache;
return require;
};
createProxyCache() {
return new Proxy(/* @__PURE__ */ Object.create(null), {
defineProperty: () => true,
deleteProperty: () => true,
set: () => true,
get: (_, key) => this.requireCache.get(key),
has: (_, key) => this.requireCache.has(key),
ownKeys: () => Array.from(this.requireCache.keys()),
getOwnPropertyDescriptor() {
return {
configurable: true,
enumerable: true
};
}
});
}
// very naive implementation for Node.js require
loadCommonJSModule(module, filename) {
const cached = this.requireCache.get(filename);
if (cached)
return cached.exports;
const extension = this.findLongestRegisteredExtension(filename);
const loader = this.extensions[extension] || this.extensions[".js"];
loader(module, filename);
return module.exports;
}
findLongestRegisteredExtension(filename) {
const name = basename(filename);
let currentExtension;
let index;
let startIndex = 0;
while ((index = name.indexOf(".", startIndex)) !== -1) {
startIndex = index + 1;
if (index === 0)
continue;
currentExtension = name.slice(index);
if (this.extensions[currentExtension])
return currentExtension;
}
return ".js";
}
require(identifier) {
const ext = extname(identifier);
if (ext === ".node" || isNodeBuiltin(identifier))
return this.requireCoreModule(identifier);
const module = new this.Module(identifier);
return this.loadCommonJSModule(module, identifier);
}
requireCoreModule(identifier) {
const normalized = identifier.replace(/^node:/, "");
if (this.builtinCache[normalized])
return this.builtinCache[normalized].exports;
const moduleExports = _require(identifier);
if (identifier === "node:module" || identifier === "module") {
const module = new this.Module("/module.js");
module.exports = this.Module;
this.builtinCache[normalized] = module;
return module.exports;
}
this.builtinCache[normalized] = _require.cache[normalized];
return moduleExports;
}
}
function interopCommonJsModule(interopDefault, mod) {
if (isPrimitive(mod) || Array.isArray(mod) || mod instanceof Promise) {
return {
keys: [],
moduleExports: {},
defaultExport: mod
};
}
if (interopDefault !== false && "__esModule" in mod && !isPrimitive(mod.default)) {
const defaultKets = Object.keys(mod.default);
const moduleKeys = Object.keys(mod);
const allKeys = /* @__PURE__ */ new Set([...defaultKets, ...moduleKeys]);
allKeys.delete("default");
return {
keys: Array.from(allKeys),
moduleExports: new Proxy(mod, {
get(mod2, prop) {
var _a;
return mod2[prop] ?? ((_a = mod2.default) == null ? void 0 : _a[prop]);
}
}),
defaultExport: mod
};
}
return {
keys: Object.keys(mod).filter((key) => key !== "default"),
moduleExports: mod,
defaultExport: mod
};
}
const SyntheticModule$1 = vm.SyntheticModule;
const SourceTextModule = vm.SourceTextModule;
var __defProp$1 = Object.defineProperty;
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField$1 = (obj, key, value) => {
__defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
var __accessCheck$1 = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet$1 = (obj, member, getter) => {
__accessCheck$1(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd$1 = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var _httpIp;
const dataURIRegex = /^data:(?<mime>text\/javascript|application\/json|application\/wasm)(?:;(?<encoding>charset=utf-8|base64))?,(?<code>.*)$/;
class EsmExecutor {
constructor(executor, options) {
this.executor = executor;
__publicField$1(this, "moduleCache", /* @__PURE__ */ new Map());
__publicField$1(this, "esmLinkMap", /* @__PURE__ */ new WeakMap());
__publicField$1(this, "context");
__privateAdd$1(this, _httpIp, IPnumber("127.0.0.0"));
this.context = options.context;
}
async evaluateModule(m) {
if (m.status === "unlinked") {
this.esmLinkMap.set(
m,
m.link((identifier, referencer) => this.executor.resolveModule(identifier, referencer.identifier))
);
}
await this.esmLinkMap.get(m);
if (m.status === "linked")
await m.evaluate();
return m;
}
async createEsModule(fileUrl, getCode) {
const cached = this.moduleCache.get(fileUrl);
if (cached)
return cached;
const code = await getCode();
if (fileUrl.endsWith(".json")) {
const m2 = new SyntheticModule$1(
["default"],
() => {
const result = JSON.parse(code);
m2.setExport("default", result);
}
);
this.moduleCache.set(fileUrl, m2);
return m2;
}
const m = new SourceTextModule(
code,
{
identifier: fileUrl,
context: this.context,
importModuleDynamically: this.executor.importModuleDynamically,
initializeImportMeta: (meta, mod) => {
meta.url = mod.identifier;
if (mod.identifier.startsWith("file:")) {
const filename = fileURLToPath(mod.identifier);
meta.filename = filename;
meta.dirname = dirname$1(filename);
}
meta.resolve = (specifier, importer) => {
return this.executor.resolve(specifier, importer != null ? importer.toString() : mod.identifier);
};
}
}
);
this.moduleCache.set(fileUrl, m);
return m;
}
async createWebAssemblyModule(fileUrl, getCode) {
const cached = this.moduleCache.get(fileUrl);
if (cached)
return cached;
const m = this.loadWebAssemblyModule(getCode(), fileUrl);
this.moduleCache.set(fileUrl, m);
return m;
}
async createNetworkModule(fileUrl) {
if (fileUrl.startsWith("http:")) {
const url = new URL(fileUrl);
if (url.hostname !== "localhost" && url.hostname !== "::1" && (IPnumber(url.hostname) & IPmask(8)) !== __privateGet$1(this, _httpIp)) {
throw new Error(
// we don't know the importer, so it's undefined (the same happens in --pool=threads)
`import of '${fileUrl}' by undefined is not supported: http can only be used to load local resources (use https instead).`
);
}
}
return this.createEsModule(fileUrl, () => fetch(fileUrl).then((r) => r.text()));
}
async loadWebAssemblyModule(source, identifier) {
const cached = this.moduleCache.get(identifier);
if (cached)
return cached;
const wasmModule = await WebAssembly.compile(source);
const exports = WebAssembly.Module.exports(wasmModule);
const imports = WebAssembly.Module.imports(wasmModule);
const moduleLookup = {};
for (const { module } of imports) {
if (moduleLookup[module] === void 0) {
moduleLookup[module] = await this.executor.resolveModule(
module,
identifier
);
}
}
const syntheticModule = new SyntheticModule$1(
exports.map(({ name }) => name),
async () => {
const importsObject = {};
for (const { module, name } of imports) {
if (!importsObject[module])
importsObject[module] = {};
await this.evaluateModule(moduleLookup[module]);
importsObject[module][name] = moduleLookup[module].namespace[name];
}
const wasmInstance = new WebAssembly.Instance(
wasmModule,
importsObject
);
for (const { name } of exports)
syntheticModule.setExport(name, wasmInstance.exports[name]);
},
{ context: this.context, identifier }
);
return syntheticModule;
}
cacheModule(identifier, module) {
this.moduleCache.set(identifier, module);
}
resolveCachedModule(identifier) {
return this.moduleCache.get(identifier);
}
async createDataModule(identifier) {
const cached = this.moduleCache.get(identifier);
if (cached)
return cached;
const match = identifier.match(dataURIRegex);
if (!match || !match.groups)
throw new Error("Invalid data URI");
const mime = match.groups.mime;
const encoding = match.groups.encoding;
if (mime === "application/wasm") {
if (!encoding)
throw new Error("Missing data URI encoding");
if (encoding !== "base64")
throw new Error(`Invalid data URI encoding: ${encoding}`);
const module = this.loadWebAssemblyModule(
Buffer.from(match.groups.code, "base64"),
identifier
);
this.moduleCache.set(identifier, module);
return module;
}
let code = match.groups.code;
if (!encoding || encoding === "charset=utf-8")
code = decodeURIComponent(code);
else if (encoding === "base64")
code = Buffer.from(code, "base64").toString();
else
throw new Error(`Invalid data URI encoding: ${encoding}`);
if (mime === "application/json") {
const module = new SyntheticModule$1(
["default"],
() => {
const obj = JSON.parse(code);
module.setExport("default", obj);
},
{ context: this.context, identifier }
);
this.moduleCache.set(identifier, module);
return module;
}
return this.createEsModule(identifier, () => code);
}
}
_httpIp = new WeakMap();
function IPnumber(address) {
const ip = address.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
if (ip)
return (+ip[1] << 24) + (+ip[2] << 16) + (+ip[3] << 8) + +ip[4];
throw new Error(`Expected IP address, received ${address}`);
}
function IPmask(maskSize) {
return -1 << 32 - maskSize;
}
const CLIENT_ID = "/@vite/client";
const CLIENT_FILE = pathToFileURL(CLIENT_ID).href;
class ViteExecutor {
constructor(options) {
this.options = options;
this.esm = options.esmExecutor;
}
esm;
resolve = (identifier, parent) => {
if (identifier === CLIENT_ID) {
if (this.workerState.environment.transformMode === "web")
return identifier;
const packageName = this.getPackageName(parent);
throw new Error(
`[vitest] Vitest cannot handle ${CLIENT_ID} imported in ${parent} when running in SSR environment. Add "${packageName}" to "ssr.noExternal" if you are using Vite SSR, or to "server.deps.inline" if you are using Vite Node.`
);
}
};
get workerState() {
return this.options.context.__vitest_worker__;
}
getPackageName(modulePath) {
const path = normalize(modulePath);
let name = path.split("/node_modules/").pop() || "";
if (name == null ? void 0 : name.startsWith("@"))
name = name.split("/").slice(0, 2).join("/");
else
name = name.split("/")[0];
return name;
}
async createViteModule(fileUrl) {
if (fileUrl === CLIENT_FILE)
return this.createViteClientModule();
const cached = this.esm.resolveCachedModule(fileUrl);
if (cached)
return cached;
return this.esm.createEsModule(fileUrl, async () => {
const result = await this.options.transform(fileUrl, "web");
if (!result.code)
throw new Error(`[vitest] Failed to transform ${fileUrl}. Does the file exist?`);
return result.code;
});
}
createViteClientModule() {
const identifier = CLIENT_ID;
const cached = this.esm.resolveCachedModule(identifier);
if (cached)
return cached;
const stub = this.options.viteClientModule;
const moduleKeys = Object.keys(stub);
const module = new SyntheticModule$1(
moduleKeys,
() => {
moduleKeys.forEach((key) => {
module.setExport(key, stub[key]);
});
},
{ context: this.options.context, identifier }
);
this.esm.cacheModule(identifier, module);
return module;
}
canResolve = (fileUrl) => {
var _a;
const transformMode = this.workerState.environment.transformMode;
if (transformMode !== "web")
return false;
if (fileUrl === CLIENT_FILE)
return true;
const config = ((_a = this.workerState.config.deps) == null ? void 0 : _a.web) || {};
const [modulePath] = fileUrl.split("?");
if (config.transformCss && CSS_LANGS_RE.test(modulePath))
return true;
if (config.transformAssets && KNOWN_ASSET_RE.test(modulePath))
return true;
if (toArray(config.transformGlobPattern).some((pattern) => pattern.test(modulePath)))
return true;
return false;
};
}
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
var _networkSupported;
const SyntheticModule = vm.SyntheticModule;
const nativeResolve = import.meta.resolve;
class ExternalModulesExecutor {
constructor(options) {
this.options = options;
__publicField(this, "cjs");
__publicField(this, "esm");
__publicField(this, "vite");
__publicField(this, "context");
__publicField(this, "fs");
__publicField(this, "resolvers", []);
__privateAdd(this, _networkSupported, null);
// dynamic import can be used in both ESM and CJS, so we have it in the executor
__publicField(this, "importModuleDynamically", async (specifier, referencer) => {
const module = await this.resolveModule(specifier, referencer.identifier);
return this.esm.evaluateModule(module);
});
__publicField(this, "resolveModule", async (specifier, referencer) => {
let identifier = this.resolve(specifier, referencer);
if (identifier instanceof Promise)
identifier = await identifier;
return await this.createModule(identifier);
});
this.context = options.context;
this.fs = options.fileMap;
this.esm = new EsmExecutor(this, {
context: this.context
});
this.cjs = new CommonjsExecutor({
context: this.context,
importModuleDynamically: this.importModuleDynamically,
fileMap: options.fileMap
});
this.vite = new ViteExecutor({
esmExecutor: this.esm,
context: this.context,
transform: options.transform,
viteClientModule: options.viteClientModule
});
this.resolvers = [this.vite.resolve];
}
async import(identifier) {
const module = await this.createModule(identifier);
await this.esm.evaluateModule(module);
return module.namespace;
}
require(identifier) {
return this.cjs.require(identifier);
}
createRequire(identifier) {
return this.cjs.createRequire(identifier);
}
resolve(specifier, parent) {
for (const resolver of this.resolvers) {
const id = resolver(specifier, parent);
if (id)
return id;
}
return nativeResolve(specifier, parent);
}
findNearestPackageData(basedir) {
var _a;
const originalBasedir = basedir;
const packageCache = this.options.packageCache;
while (basedir) {
const cached = getCachedData(packageCache, basedir, originalBasedir);
if (cached)
return cached;
const pkgPath = join(basedir, "package.json");
try {
if ((_a = statSync(pkgPath, { throwIfNoEntry: false })) == null ? void 0 : _a.isFile()) {
const pkgData = JSON.parse(this.fs.readFile(pkgPath));
if (packageCache)
setCacheData(packageCache, pkgData, basedir, originalBasedir);
return pkgData;
}
} catch {
}
const nextBasedir = dirname$1(basedir);
if (nextBasedir === basedir)
break;
basedir = nextBasedir;
}
return {};
}
wrapCoreSynteticModule(identifier, exports) {
const moduleKeys = Object.keys(exports);
const m = new SyntheticModule(
[...moduleKeys, "default"],
() => {
for (const key of moduleKeys)
m.setExport(key, exports[key]);
m.setExport("default", exports);
},
{
context: this.context,
identifier
}
);
return m;
}
wrapCommonJsSynteticModule(identifier, exports) {
const { keys, moduleExports, defaultExport } = interopCommonJsModule(this.options.interopDefault, exports);
const m = new SyntheticModule(
[...keys, "default"],
() => {
for (const key of keys)
m.setExport(key, moduleExports[key]);
m.setExport("default", defaultExport);
},
{
context: this.context,
identifier
}
);
return m;
}
getModuleInformation(identifier) {
if (identifier.startsWith("data:"))
return { type: "data", url: identifier, path: identifier };
const extension = extname(identifier);
if (extension === ".node" || isNodeBuiltin(identifier))
return { type: "builtin", url: identifier, path: identifier };
if (this.isNetworkSupported && (identifier.startsWith("http:") || identifier.startsWith("https:")))
return { type: "network", url: identifier, path: identifier };
const isFileUrl = identifier.startsWith("file://");
const pathUrl = isFileUrl ? fileURLToPath(identifier.split("?")[0]) : identifier;
const fileUrl = isFileUrl ? identifier : pathToFileURL(pathUrl).toString();
let type;
if (this.vite.canResolve(fileUrl)) {
type = "vite";
} else if (extension === ".mjs") {
type = "module";
} else if (extension === ".cjs") {
type = "commonjs";
} else if (extension === ".wasm") {
type = "wasm";
} else {
const pkgData = this.findNearestPackageData(normalize(pathUrl));
type = pkgData.type === "module" ? "module" : "commonjs";
}
return { type, path: pathUrl, url: fileUrl };
}
async createModule(identifier) {
const { type, url, path } = this.getModuleInformation(identifier);
if ((type === "module" || type === "commonjs" || type === "wasm") && !existsSync(path)) {
const error = new Error(`Cannot find module '${path}'`);
error.code = "ERR_MODULE_NOT_FOUND";
throw error;
}
switch (type) {
case "data":
return this.esm.createDataModule(identifier);
case "builtin": {
const exports = this.require(identifier);
return this.wrapCoreSynteticModule(identifier, exports);
}
case "vite":
return await this.vite.createViteModule(url);
case "wasm":
return await this.esm.createWebAssemblyModule(url, () => this.fs.readBuffer(path));
case "module":
return await this.esm.createEsModule(url, () => this.fs.readFile(path));
case "commonjs": {
const exports = this.require(path);
return this.wrapCommonJsSynteticModule(identifier, exports);
}
case "network": {
return this.esm.createNetworkModule(url);
}
default: {
const _deadend = type;
return _deadend;
}
}
}
get isNetworkSupported() {
var _a;
if (__privateGet(this, _networkSupported) == null) {
if (process.execArgv.includes("--experimental-network-imports"))
__privateSet(this, _networkSupported, true);
else if ((_a = process.env.NODE_OPTIONS) == null ? void 0 : _a.includes("--experimental-network-imports"))
__privateSet(this, _networkSupported, true);
else
__privateSet(this, _networkSupported, false);
}
return __privateGet(this, _networkSupported);
}
}
_networkSupported = new WeakMap();
class FileMap {
fsCache = /* @__PURE__ */ new Map();
fsBufferCache = /* @__PURE__ */ new Map();
readFile(path) {
const cached = this.fsCache.get(path);
if (cached)
return cached;
const source = readFileSync(path, "utf-8");
this.fsCache.set(path, source);
return source;
}
readBuffer(path) {
const cached = this.fsBufferCache.get(path);
if (cached)
return cached;
const buffer = readFileSync(path);
this.fsBufferCache.set(path, buffer);
return buffer;
}
}
const entryFile = pathToFileURL(resolve(distDir, "workers/runVmTests.js")).href;
const fileMap = new FileMap();
const packageCache = /* @__PURE__ */ new Map();
async function runVmTests(state) {
var _a;
const { environment, ctx, rpc } = state;
if (!environment.setupVM) {
const envName = ctx.environment.name;
const packageId = envName[0] === "." ? envName : `vitest-environment-${envName}`;
throw new TypeError(
`Environment "${ctx.environment.name}" is not a valid environment. Path "${packageId}" doesn't support vm environment because it doesn't provide "setupVM" method.`
);
}
const vm = await environment.setupVM(ctx.environment.options || ctx.config.environmentOptions || {});
state.durations.environment = performance.now() - state.durations.environment;
process.env.VITEST_VM_POOL = "1";
if (!vm.getVmContext)
throw new TypeError(`Environment ${environment.name} doesn't provide "getVmContext" method. It should return a context created by "vm.createContext" method.`);
const context = vm.getVmContext();
if (!isContext(context))
throw new TypeError(`Environment ${environment.name} doesn't provide a valid context. It should be created by "vm.createContext" method.`);
provideWorkerState(context, state);
context.process = process;
context.global = context;
context.console = state.config.disableConsoleIntercept ? console : createCustomConsole();
context.setImmediate = setImmediate;
context.clearImmediate = clearImmediate;
const stubs = getDefaultRequestStubs(context);
const externalModulesExecutor = new ExternalModulesExecutor({
context,
fileMap,
packageCache,
transform: rpc.transform,
viteClientModule: stubs["/@vite/client"]
});
const executor = await startVitestExecutor({
context,
moduleCache: state.moduleCache,
mockMap: state.mockMap,
state,
externalModulesExecutor,
requestStubs: stubs
});
context.__vitest_mocker__ = executor.mocker;
const { run } = await executor.importExternalModule(entryFile);
try {
await run(ctx.files, ctx.config, executor);
} finally {
await ((_a = vm.teardown) == null ? void 0 : _a.call(vm));
state.environmentTeardownRun = true;
}
}
export { runVmTests as r };