first commit
This commit is contained in:
commit
eb2f504652
32490 changed files with 5731109 additions and 0 deletions
17
node_modules/vitest/dist/browser.d.ts
generated
vendored
Normal file
17
node_modules/vitest/dist/browser.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
export { A as AssertType, E as EnhancedSpy, q as ExpectTypeOf, x as Mock, y as MockContext, w as MockInstance, z as Mocked, B as MockedClass, u as MockedFunction, v as MockedObject, S as SpyInstance, j as afterAll, l as afterEach, r as assertType, h as beforeAll, k as beforeEach, n as createExpect, e as describe, m as expect, p as expectTypeOf, i as it, o as onTestFailed, d as suite, t as test } from './index-5aad25c1.js';
|
||||
import { b as ResolvedConfig } from './types-71ccd11d.js';
|
||||
export { a1 as AfterSuiteRunMeta, A as ApiConfig, a7 as ArgumentsType, a6 as Arrayable, a4 as Awaitable, ap as BaseCoverageOptions, av as BenchFunction, at as Benchmark, aw as BenchmarkAPI, au as BenchmarkResult, as as BenchmarkUserOptions, B as BuiltinEnvironment, i as CSSModuleScopeStrategy, C as CollectLineNumbers, f as CollectLines, ab as Constructable, h as Context, ar as CoverageC8Options, aq as CoverageIstanbulOptions, an as CoverageOptions, ak as CoverageProvider, al as CoverageProviderModule, am as CoverageReporter, a9 as DeepMerge, D as DoneCallback, ae as Environment, E as EnvironmentOptions, ad as EnvironmentReturn, ai as ErrorWithDiff, a as File, x as HookCleanupCallback, H as HookListener, I as InlineConfig, J as JSDOMOptions, a8 as MergeInsertions, ac as ModuleCache, M as ModuleGraphData, aa as MutableArray, a5 as Nullable, aj as OnServerRestartHandler, O as OnTestFailedHandler, ah as ParsedStack, ag as Position, d as RawErrsMap, c as Reporter, a0 as ResolveIdFunction, b as ResolvedConfig, ao as ResolvedCoverageOptions, g as RootAndTarget, l as RunMode, R as RuntimeConfig, K as RuntimeContext, S as SequenceHooks, P as SnapshotData, X as SnapshotMatchOptions, Y as SnapshotResult, W as SnapshotStateOptions, _ as SnapshotSummary, Q as SnapshotUpdateState, p as Suite, w as SuiteAPI, z as SuiteCollector, G as SuiteFactory, y as SuiteHooks, s as Task, n as TaskBase, o as TaskResult, T as TaskResultPack, m as TaskState, q as Test, v as TestAPI, L as TestContext, t as TestFunction, u as TestOptions, e as TscErrorInfo, r as TypeCheck, k as TypecheckConfig, Z as UncheckedSnapshot, U as UserConfig, af as UserConsoleLog, N as Vitest, V as VitestEnvironment, j as VitestRunMode, $ as WorkerContext, a3 as WorkerGlobalState, a2 as WorkerRPC } from './types-71ccd11d.js';
|
||||
import * as chai from 'chai';
|
||||
export { chai };
|
||||
export { assert, should } from 'chai';
|
||||
export { Bench as BenchFactory, Options as BenchOptions, Task as BenchTask, TaskResult as BenchTaskResult } from 'tinybench';
|
||||
import 'tinyspy';
|
||||
import 'vite';
|
||||
import 'fs';
|
||||
import 'worker_threads';
|
||||
|
||||
declare function startTests(paths: string[], config: ResolvedConfig): Promise<void>;
|
||||
|
||||
declare function setupGlobalEnv(config: ResolvedConfig): Promise<void>;
|
||||
|
||||
export { setupGlobalEnv, startTests };
|
||||
33
node_modules/vitest/dist/browser.js
generated
vendored
Normal file
33
node_modules/vitest/dist/browser.js
generated
vendored
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
export { c as createExpect, d as describe, e as expect, i as it, s as suite, t as test } from './chunk-runtime-chain.f86e5250.js';
|
||||
import { e as dist } from './chunk-runtime-test-state.3f86f48f.js';
|
||||
export { a as afterAll, d as afterEach, f as assertType, b as beforeAll, c as beforeEach, o as onTestFailed } from './chunk-runtime-test-state.3f86f48f.js';
|
||||
export { a as setupGlobalEnv, s as startTests } from './chunk-runtime-setup.5398e2c4.js';
|
||||
import * as chai from 'chai';
|
||||
export { chai };
|
||||
export { assert, should } from 'chai';
|
||||
import 'util';
|
||||
import './chunk-typecheck-constants.ed987901.js';
|
||||
import 'path';
|
||||
import './chunk-utils-env.03f840f2.js';
|
||||
import 'tty';
|
||||
import 'url';
|
||||
import 'local-pkg';
|
||||
import './vendor-_commonjsHelpers.addc3445.js';
|
||||
import './chunk-runtime-rpc.42aebbb9.js';
|
||||
import './chunk-utils-timers.793fd179.js';
|
||||
import 'fs';
|
||||
import './chunk-utils-source-map.29ff1088.js';
|
||||
import './spy.js';
|
||||
import 'tinyspy';
|
||||
import 'perf_hooks';
|
||||
import './chunk-integrations-coverage.befed097.js';
|
||||
import './chunk-runtime-error.616e92ca.js';
|
||||
import './vendor-source-map-support.1ce17397.js';
|
||||
import 'source-map';
|
||||
import './chunk-env-node.67948209.js';
|
||||
import 'console';
|
||||
|
||||
|
||||
|
||||
var expectTypeOf = dist.expectTypeOf;
|
||||
export { expectTypeOf };
|
||||
4580
node_modules/vitest/dist/chunk-api-setup.dc71e384.js
generated
vendored
Normal file
4580
node_modules/vitest/dist/chunk-api-setup.dc71e384.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
401
node_modules/vitest/dist/chunk-env-node.67948209.js
generated
vendored
Normal file
401
node_modules/vitest/dist/chunk-env-node.67948209.js
generated
vendored
Normal file
|
|
@ -0,0 +1,401 @@
|
|||
import { Console } from 'console';
|
||||
import { importModule } from 'local-pkg';
|
||||
|
||||
var node = {
|
||||
name: "node",
|
||||
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",
|
||||
"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",
|
||||
"ArrayBuffer",
|
||||
"Image",
|
||||
"Audio",
|
||||
"Option"
|
||||
];
|
||||
const OTHER_KEYS = [
|
||||
"addEventListener",
|
||||
"alert",
|
||||
"atob",
|
||||
"blur",
|
||||
"btoa",
|
||||
"cancelAnimationFrame",
|
||||
"close",
|
||||
"confirm",
|
||||
"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",
|
||||
"stop",
|
||||
"top",
|
||||
"Window",
|
||||
"window"
|
||||
];
|
||||
const KEYS = LIVING_KEYS.concat(OTHER_KEYS);
|
||||
|
||||
const skipKeys = [
|
||||
"window",
|
||||
"self",
|
||||
"top",
|
||||
"parent"
|
||||
];
|
||||
function getWindowKeys(global, win) {
|
||||
const keys = new Set(KEYS.concat(Object.getOwnPropertyNames(win)).filter((k) => {
|
||||
if (skipKeys.includes(k))
|
||||
return false;
|
||||
if (k in global)
|
||||
return KEYS.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);
|
||||
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;
|
||||
skipKeys.forEach((k) => keys.add(k));
|
||||
return {
|
||||
keys,
|
||||
skipKeys,
|
||||
originals
|
||||
};
|
||||
}
|
||||
|
||||
var jsdom = {
|
||||
name: "jsdom",
|
||||
async setup(global, { jsdom = {} }) {
|
||||
const {
|
||||
CookieJar,
|
||||
JSDOM,
|
||||
ResourceLoader,
|
||||
VirtualConsole
|
||||
} = await importModule("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 });
|
||||
return {
|
||||
teardown(global2) {
|
||||
keys.forEach((key) => delete global2[key]);
|
||||
originals.forEach((v, k) => global2[k] = v);
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
var happy = {
|
||||
name: "happy-dom",
|
||||
async setup(global) {
|
||||
const { Window, GlobalWindow } = await importModule("happy-dom");
|
||||
const win = new (GlobalWindow || Window)();
|
||||
const { keys, originals } = populateGlobal(global, win, { bindFunctions: true });
|
||||
return {
|
||||
teardown(global2) {
|
||||
win.happyDOM.cancelAsync();
|
||||
keys.forEach((key) => delete global2[key]);
|
||||
originals.forEach((v, k) => global2[k] = v);
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
var edge = {
|
||||
name: "edge-runtime",
|
||||
async setup(global) {
|
||||
const { EdgeVM } = await importModule("@edge-runtime/vm");
|
||||
const vm = new EdgeVM({
|
||||
extend: (context) => {
|
||||
context.global = context;
|
||||
context.Buffer = Buffer;
|
||||
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 envs = Object.keys(environments);
|
||||
const envPackageNames = {
|
||||
"jsdom": "jsdom",
|
||||
"happy-dom": "happy-dom",
|
||||
"edge-runtime": "@edge-runtime/vm"
|
||||
};
|
||||
const getEnvPackageName = (env) => {
|
||||
if (env === "node")
|
||||
return null;
|
||||
if (env in envPackageNames)
|
||||
return envPackageNames[env];
|
||||
return `vitest-environment-${env}`;
|
||||
};
|
||||
|
||||
export { envs as a, environments as e, getEnvPackageName as g, populateGlobal as p };
|
||||
1677
node_modules/vitest/dist/chunk-install-pkg.579a5a27.js
generated
vendored
Normal file
1677
node_modules/vitest/dist/chunk-install-pkg.579a5a27.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
222
node_modules/vitest/dist/chunk-integrations-coverage.befed097.js
generated
vendored
Normal file
222
node_modules/vitest/dist/chunk-integrations-coverage.befed097.js
generated
vendored
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
import { importModule } from 'local-pkg';
|
||||
|
||||
/*
|
||||
How it works:
|
||||
`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.
|
||||
*/
|
||||
|
||||
class Node {
|
||||
value;
|
||||
next;
|
||||
|
||||
constructor(value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
class Queue {
|
||||
#head;
|
||||
#tail;
|
||||
#size;
|
||||
|
||||
constructor() {
|
||||
this.clear();
|
||||
}
|
||||
|
||||
enqueue(value) {
|
||||
const node = new Node(value);
|
||||
|
||||
if (this.#head) {
|
||||
this.#tail.next = node;
|
||||
this.#tail = node;
|
||||
} else {
|
||||
this.#head = node;
|
||||
this.#tail = node;
|
||||
}
|
||||
|
||||
this.#size++;
|
||||
}
|
||||
|
||||
dequeue() {
|
||||
const current = this.#head;
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.#head = this.#head.next;
|
||||
this.#size--;
|
||||
return current.value;
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.#head = undefined;
|
||||
this.#tail = undefined;
|
||||
this.#size = 0;
|
||||
}
|
||||
|
||||
get size() {
|
||||
return this.#size;
|
||||
}
|
||||
|
||||
* [Symbol.iterator]() {
|
||||
let current = this.#head;
|
||||
|
||||
while (current) {
|
||||
yield current.value;
|
||||
current = current.next;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function pLimit(concurrency) {
|
||||
if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
|
||||
throw new TypeError('Expected `concurrency` to be a number from 1 and up');
|
||||
}
|
||||
|
||||
const queue = new Queue();
|
||||
let activeCount = 0;
|
||||
|
||||
const next = () => {
|
||||
activeCount--;
|
||||
|
||||
if (queue.size > 0) {
|
||||
queue.dequeue()();
|
||||
}
|
||||
};
|
||||
|
||||
const run = async (fn, resolve, args) => {
|
||||
activeCount++;
|
||||
|
||||
const result = (async () => fn(...args))();
|
||||
|
||||
resolve(result);
|
||||
|
||||
try {
|
||||
await result;
|
||||
} catch {}
|
||||
|
||||
next();
|
||||
};
|
||||
|
||||
const enqueue = (fn, resolve, args) => {
|
||||
queue.enqueue(run.bind(undefined, fn, resolve, args));
|
||||
|
||||
(async () => {
|
||||
// This function needs to wait until the next microtask before comparing
|
||||
// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
|
||||
// when the run function is dequeued and called. The comparison in the if-statement
|
||||
// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
|
||||
await Promise.resolve();
|
||||
|
||||
if (activeCount < concurrency && queue.size > 0) {
|
||||
queue.dequeue()();
|
||||
}
|
||||
})();
|
||||
};
|
||||
|
||||
const generator = (fn, ...args) => new Promise(resolve => {
|
||||
enqueue(fn, resolve, args);
|
||||
});
|
||||
|
||||
Object.defineProperties(generator, {
|
||||
activeCount: {
|
||||
get: () => activeCount,
|
||||
},
|
||||
pendingCount: {
|
||||
get: () => queue.size,
|
||||
},
|
||||
clearQueue: {
|
||||
value: () => {
|
||||
queue.clear();
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return generator;
|
||||
}
|
||||
|
||||
const CoverageProviderMap = {
|
||||
c8: "@vitest/coverage-c8",
|
||||
istanbul: "@vitest/coverage-istanbul"
|
||||
};
|
||||
async function resolveCoverageProvider(provider) {
|
||||
if (typeof provider === "string") {
|
||||
const pkg = CoverageProviderMap[provider];
|
||||
if (!pkg)
|
||||
throw new Error(`Unknown coverage provider: ${provider}`);
|
||||
return await importModule(pkg);
|
||||
} else {
|
||||
return provider;
|
||||
}
|
||||
}
|
||||
async function getCoverageProvider(options) {
|
||||
if ((options == null ? void 0 : options.enabled) && (options == null ? void 0 : options.provider)) {
|
||||
const { getProvider } = await resolveCoverageProvider(options.provider);
|
||||
return await getProvider();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
async function takeCoverageInsideWorker(options) {
|
||||
if (options.enabled && options.provider) {
|
||||
const { takeCoverage } = await resolveCoverageProvider(options.provider);
|
||||
return await (takeCoverage == null ? void 0 : takeCoverage());
|
||||
}
|
||||
}
|
||||
|
||||
function interpretTaskModes(suite, namePattern, onlyMode, parentIsOnly, allowOnly) {
|
||||
const suiteIsOnly = parentIsOnly || suite.mode === "only";
|
||||
suite.tasks.forEach((t) => {
|
||||
const includeTask = suiteIsOnly || t.mode === "only";
|
||||
if (onlyMode) {
|
||||
if (t.type === "suite" && (includeTask || someTasksAreOnly(t))) {
|
||||
if (t.mode === "only") {
|
||||
checkAllowOnly(t, allowOnly);
|
||||
t.mode = "run";
|
||||
}
|
||||
} else if (t.mode === "run" && !includeTask) {
|
||||
t.mode = "skip";
|
||||
} else if (t.mode === "only") {
|
||||
checkAllowOnly(t, allowOnly);
|
||||
t.mode = "run";
|
||||
}
|
||||
}
|
||||
if (t.type === "test") {
|
||||
if (namePattern && !getTaskFullName(t).match(namePattern))
|
||||
t.mode = "skip";
|
||||
} else if (t.type === "suite") {
|
||||
if (t.mode === "skip")
|
||||
skipAllTasks(t);
|
||||
else
|
||||
interpretTaskModes(t, namePattern, onlyMode, includeTask, allowOnly);
|
||||
}
|
||||
});
|
||||
if (suite.mode === "run") {
|
||||
if (suite.tasks.length && suite.tasks.every((i) => i.mode !== "run"))
|
||||
suite.mode = "skip";
|
||||
}
|
||||
}
|
||||
function getTaskFullName(task) {
|
||||
return `${task.suite ? `${getTaskFullName(task.suite)} ` : ""}${task.name}`;
|
||||
}
|
||||
function someTasksAreOnly(suite) {
|
||||
return suite.tasks.some((t) => t.mode === "only" || t.type === "suite" && someTasksAreOnly(t));
|
||||
}
|
||||
function skipAllTasks(suite) {
|
||||
suite.tasks.forEach((t) => {
|
||||
if (t.mode === "run") {
|
||||
t.mode = "skip";
|
||||
if (t.type === "suite")
|
||||
skipAllTasks(t);
|
||||
}
|
||||
});
|
||||
}
|
||||
function checkAllowOnly(task, allowOnly) {
|
||||
if (allowOnly)
|
||||
return;
|
||||
task.result = {
|
||||
state: "fail",
|
||||
error: new Error("[Vitest] Unexpected .only modifier. Remove it or pass --allowOnly argument to bypass this error")
|
||||
};
|
||||
}
|
||||
|
||||
export { CoverageProviderMap as C, getCoverageProvider as g, interpretTaskModes as i, pLimit as p, someTasksAreOnly as s, takeCoverageInsideWorker as t };
|
||||
25
node_modules/vitest/dist/chunk-integrations-globals.4d261bb8.js
generated
vendored
Normal file
25
node_modules/vitest/dist/chunk-integrations-globals.4d261bb8.js
generated
vendored
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { m as globalApis } from './chunk-utils-env.03f840f2.js';
|
||||
import { i as index } from './chunk-runtime-test-state.3f86f48f.js';
|
||||
import 'tty';
|
||||
import 'url';
|
||||
import 'path';
|
||||
import './chunk-runtime-chain.f86e5250.js';
|
||||
import 'util';
|
||||
import 'chai';
|
||||
import './chunk-typecheck-constants.ed987901.js';
|
||||
import 'local-pkg';
|
||||
import './vendor-_commonjsHelpers.addc3445.js';
|
||||
import './chunk-runtime-rpc.42aebbb9.js';
|
||||
import './chunk-utils-timers.793fd179.js';
|
||||
import 'fs';
|
||||
import './chunk-utils-source-map.29ff1088.js';
|
||||
import './spy.js';
|
||||
import 'tinyspy';
|
||||
|
||||
function registerApiGlobally() {
|
||||
globalApis.forEach((api) => {
|
||||
globalThis[api] = index[api];
|
||||
});
|
||||
}
|
||||
|
||||
export { registerApiGlobally };
|
||||
1510
node_modules/vitest/dist/chunk-magic-string.3a794426.js
generated
vendored
Normal file
1510
node_modules/vitest/dist/chunk-magic-string.3a794426.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
83
node_modules/vitest/dist/chunk-node-git.5a1b1656.js
generated
vendored
Normal file
83
node_modules/vitest/dist/chunk-node-git.5a1b1656.js
generated
vendored
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
import { b as resolve } from './chunk-utils-env.03f840f2.js';
|
||||
import { e as execa } from './vendor-index.737c3cff.js';
|
||||
import 'tty';
|
||||
import 'url';
|
||||
import 'path';
|
||||
import 'buffer';
|
||||
import 'child_process';
|
||||
import 'process';
|
||||
import './vendor-index.e1d4cf84.js';
|
||||
import './vendor-_commonjsHelpers.addc3445.js';
|
||||
import 'fs';
|
||||
import 'assert';
|
||||
import 'events';
|
||||
import 'stream';
|
||||
import 'util';
|
||||
import 'os';
|
||||
|
||||
class VitestGit {
|
||||
constructor(cwd) {
|
||||
this.cwd = cwd;
|
||||
}
|
||||
async resolveFilesWithGitCommand(args) {
|
||||
let result;
|
||||
try {
|
||||
result = await execa("git", args, { cwd: this.root });
|
||||
} catch (e) {
|
||||
e.message = e.stderr;
|
||||
throw e;
|
||||
}
|
||||
return result.stdout.split("\n").filter((s) => s !== "").map((changedPath) => resolve(this.root, changedPath));
|
||||
}
|
||||
async findChangedFiles(options) {
|
||||
const root = await this.getRoot(this.cwd);
|
||||
if (!root)
|
||||
return null;
|
||||
this.root = root;
|
||||
const changedSince = options.changedSince;
|
||||
if (typeof changedSince === "string") {
|
||||
const [committed, staged2, unstaged2] = await Promise.all([
|
||||
this.getFilesSince(changedSince),
|
||||
this.getStagedFiles(),
|
||||
this.getUnstagedFiles()
|
||||
]);
|
||||
return [...committed, ...staged2, ...unstaged2];
|
||||
}
|
||||
const [staged, unstaged] = await Promise.all([
|
||||
this.getStagedFiles(),
|
||||
this.getUnstagedFiles()
|
||||
]);
|
||||
return [...staged, ...unstaged];
|
||||
}
|
||||
getFilesSince(hash) {
|
||||
return this.resolveFilesWithGitCommand(
|
||||
["diff", "--name-only", `${hash}...HEAD`]
|
||||
);
|
||||
}
|
||||
getStagedFiles() {
|
||||
return this.resolveFilesWithGitCommand(
|
||||
["diff", "--cached", "--name-only"]
|
||||
);
|
||||
}
|
||||
getUnstagedFiles() {
|
||||
return this.resolveFilesWithGitCommand(
|
||||
[
|
||||
"ls-files",
|
||||
"--other",
|
||||
"--modified",
|
||||
"--exclude-standard"
|
||||
]
|
||||
);
|
||||
}
|
||||
async getRoot(cwd) {
|
||||
const options = ["rev-parse", "--show-cdup"];
|
||||
try {
|
||||
const result = await execa("git", options, { cwd });
|
||||
return resolve(cwd, result.stdout);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { VitestGit };
|
||||
2431
node_modules/vitest/dist/chunk-runtime-chain.f86e5250.js
generated
vendored
Normal file
2431
node_modules/vitest/dist/chunk-runtime-chain.f86e5250.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
142
node_modules/vitest/dist/chunk-runtime-error.616e92ca.js
generated
vendored
Normal file
142
node_modules/vitest/dist/chunk-runtime-error.616e92ca.js
generated
vendored
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
import util$1 from 'util';
|
||||
import { util } from 'chai';
|
||||
import { a as stringify } from './chunk-utils-timers.793fd179.js';
|
||||
import { w as deepClone, x as getType } from './chunk-typecheck-constants.ed987901.js';
|
||||
|
||||
const IS_RECORD_SYMBOL = "@@__IMMUTABLE_RECORD__@@";
|
||||
const IS_COLLECTION_SYMBOL = "@@__IMMUTABLE_ITERABLE__@@";
|
||||
const isImmutable = (v) => v && (v[IS_COLLECTION_SYMBOL] || v[IS_RECORD_SYMBOL]);
|
||||
const OBJECT_PROTO = Object.getPrototypeOf({});
|
||||
function getUnserializableMessage(err) {
|
||||
if (err instanceof Error)
|
||||
return `<unserializable>: ${err.message}`;
|
||||
if (typeof err === "string")
|
||||
return `<unserializable>: ${err}`;
|
||||
return "<unserializable>";
|
||||
}
|
||||
function serializeError(val, seen = /* @__PURE__ */ new WeakMap()) {
|
||||
if (!val || typeof val === "string")
|
||||
return val;
|
||||
if (typeof val === "function")
|
||||
return `Function<${val.name}>`;
|
||||
if (typeof val === "symbol")
|
||||
return val.toString();
|
||||
if (typeof val !== "object")
|
||||
return val;
|
||||
if (isImmutable(val))
|
||||
return serializeError(val.toJSON(), seen);
|
||||
if (val instanceof Promise || val.constructor && val.constructor.prototype === "AsyncFunction")
|
||||
return "Promise";
|
||||
if (typeof Element !== "undefined" && val instanceof Element)
|
||||
return val.tagName;
|
||||
if (typeof val.asymmetricMatch === "function")
|
||||
return `${val.toString()} ${util$1.format(val.sample)}`;
|
||||
if (seen.has(val))
|
||||
return seen.get(val);
|
||||
if (Array.isArray(val)) {
|
||||
const clone = new Array(val.length);
|
||||
seen.set(val, clone);
|
||||
val.forEach((e, i) => {
|
||||
try {
|
||||
clone[i] = serializeError(e, seen);
|
||||
} catch (err) {
|
||||
clone[i] = getUnserializableMessage(err);
|
||||
}
|
||||
});
|
||||
return clone;
|
||||
} else {
|
||||
const clone = /* @__PURE__ */ Object.create(null);
|
||||
seen.set(val, clone);
|
||||
let obj = val;
|
||||
while (obj && obj !== OBJECT_PROTO) {
|
||||
Object.getOwnPropertyNames(obj).forEach((key) => {
|
||||
if (key in clone)
|
||||
return;
|
||||
try {
|
||||
clone[key] = serializeError(val[key], seen);
|
||||
} catch (err) {
|
||||
delete clone[key];
|
||||
clone[key] = getUnserializableMessage(err);
|
||||
}
|
||||
});
|
||||
obj = Object.getPrototypeOf(obj);
|
||||
}
|
||||
return clone;
|
||||
}
|
||||
}
|
||||
function normalizeErrorMessage(message) {
|
||||
return message.replace(/__vite_ssr_import_\d+__\./g, "");
|
||||
}
|
||||
function processError(err) {
|
||||
if (!err || typeof err !== "object")
|
||||
return err;
|
||||
if (err.stack)
|
||||
err.stackStr = String(err.stack);
|
||||
if (err.name)
|
||||
err.nameStr = String(err.name);
|
||||
const clonedActual = deepClone(err.actual);
|
||||
const clonedExpected = deepClone(err.expected);
|
||||
const { replacedActual, replacedExpected } = replaceAsymmetricMatcher(clonedActual, clonedExpected);
|
||||
err.actual = replacedActual;
|
||||
err.expected = replacedExpected;
|
||||
if (typeof err.expected !== "string")
|
||||
err.expected = stringify(err.expected);
|
||||
if (typeof err.actual !== "string")
|
||||
err.actual = stringify(err.actual);
|
||||
try {
|
||||
if (typeof err.message === "string")
|
||||
err.message = normalizeErrorMessage(err.message);
|
||||
if (typeof err.cause === "object" && typeof err.cause.message === "string")
|
||||
err.cause.message = normalizeErrorMessage(err.cause.message);
|
||||
} catch {
|
||||
}
|
||||
try {
|
||||
return serializeError(err);
|
||||
} catch (e) {
|
||||
return serializeError(new Error(`Failed to fully serialize error: ${e == null ? void 0 : e.message}
|
||||
Inner error message: ${err == null ? void 0 : err.message}`));
|
||||
}
|
||||
}
|
||||
function isAsymmetricMatcher(data) {
|
||||
const type = getType(data);
|
||||
return type === "Object" && typeof data.asymmetricMatch === "function";
|
||||
}
|
||||
function isReplaceable(obj1, obj2) {
|
||||
const obj1Type = getType(obj1);
|
||||
const obj2Type = getType(obj2);
|
||||
return obj1Type === obj2Type && obj1Type === "Object";
|
||||
}
|
||||
function replaceAsymmetricMatcher(actual, expected, actualReplaced = /* @__PURE__ */ new WeakMap(), expectedReplaced = /* @__PURE__ */ new WeakMap()) {
|
||||
if (!isReplaceable(actual, expected))
|
||||
return { replacedActual: actual, replacedExpected: expected };
|
||||
if (actualReplaced.has(actual) || expectedReplaced.has(expected))
|
||||
return { replacedActual: actual, replacedExpected: expected };
|
||||
actualReplaced.set(actual, true);
|
||||
expectedReplaced.set(expected, true);
|
||||
util.getOwnEnumerableProperties(expected).forEach((key) => {
|
||||
const expectedValue = expected[key];
|
||||
const actualValue = actual[key];
|
||||
if (isAsymmetricMatcher(expectedValue)) {
|
||||
if (expectedValue.asymmetricMatch(actualValue))
|
||||
actual[key] = expectedValue;
|
||||
} else if (isAsymmetricMatcher(actualValue)) {
|
||||
if (actualValue.asymmetricMatch(expectedValue))
|
||||
expected[key] = actualValue;
|
||||
} else if (isReplaceable(actualValue, expectedValue)) {
|
||||
const replaced = replaceAsymmetricMatcher(
|
||||
actualValue,
|
||||
expectedValue,
|
||||
actualReplaced,
|
||||
expectedReplaced
|
||||
);
|
||||
actual[key] = replaced.replacedActual;
|
||||
expected[key] = replaced.replacedExpected;
|
||||
}
|
||||
});
|
||||
return {
|
||||
replacedActual: actual,
|
||||
replacedExpected: expected
|
||||
};
|
||||
}
|
||||
|
||||
export { processError as p };
|
||||
338
node_modules/vitest/dist/chunk-runtime-mocker.99b910d0.js
generated
vendored
Normal file
338
node_modules/vitest/dist/chunk-runtime-mocker.99b910d0.js
generated
vendored
Normal file
|
|
@ -0,0 +1,338 @@
|
|||
import { V as ViteNodeRunner } from './chunk-vite-node-source-map.b4ea5792.js';
|
||||
import { normalizePath } from 'vite';
|
||||
import { g as getWorkerState, J as mergeSlashes, s as slash, x as getType, K as getAllMockableProperties } from './chunk-typecheck-constants.ed987901.js';
|
||||
import { existsSync, readdirSync } from 'fs';
|
||||
import { c as normalizeRequestId, p as pathFromRoot, i as isNodeBuiltin } from './chunk-vite-node-utils.0e4a6a88.js';
|
||||
import { p as picocolors, d as dirname, j as join, c as basename, l as extname, b as resolve, e as distDir } from './chunk-utils-env.03f840f2.js';
|
||||
|
||||
class RefTracker {
|
||||
constructor() {
|
||||
this.idMap = /* @__PURE__ */ new Map();
|
||||
this.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);
|
||||
}
|
||||
const _VitestMocker = class {
|
||||
constructor(options, moduleCache, request) {
|
||||
this.options = options;
|
||||
this.moduleCache = moduleCache;
|
||||
this.request = request;
|
||||
this.resolveCache = /* @__PURE__ */ new Map();
|
||||
}
|
||||
get root() {
|
||||
return this.options.root;
|
||||
}
|
||||
get base() {
|
||||
return this.options.base;
|
||||
}
|
||||
get mockMap() {
|
||||
return this.options.mockMap;
|
||||
}
|
||||
getSuiteFilepath() {
|
||||
return getWorkerState().filepath || "global";
|
||||
}
|
||||
getMocks() {
|
||||
const suite = this.getSuiteFilepath();
|
||||
const suiteMocks = this.mockMap.get(suite);
|
||||
const globalMocks = this.mockMap.get("global");
|
||||
return {
|
||||
...globalMocks,
|
||||
...suiteMocks
|
||||
};
|
||||
}
|
||||
async resolvePath(id, importer) {
|
||||
const path = await this.options.resolveId(id, importer);
|
||||
const external = path == null || path.id.includes("/node_modules/") ? id : null;
|
||||
return {
|
||||
path: normalizeRequestId((path == null ? void 0 : path.id) || id),
|
||||
external
|
||||
};
|
||||
}
|
||||
async resolveMocks() {
|
||||
await Promise.all(_VitestMocker.pendingIds.map(async (mock) => {
|
||||
const { path, external } = await this.resolvePath(mock.id, mock.importer);
|
||||
if (mock.type === "unmock")
|
||||
this.unmockPath(path);
|
||||
if (mock.type === "mock")
|
||||
this.mockPath(mock.id, path, 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 = new Error(
|
||||
"[vitest] There was an error, when mocking a module. If you are using vi.mock, make sure you are not using top level variables inside, since this call is hoisted. Read more: https://vitest.dev/api/#vi-mock"
|
||||
);
|
||||
vitestError.cause = err;
|
||||
throw vitestError;
|
||||
}
|
||||
if (exports === null || typeof exports !== "object")
|
||||
throw new Error('[vitest] vi.mock(path: string, factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?');
|
||||
const filepath = dep.slice("mock:".length);
|
||||
const mockpath = ((_b = this.resolveCache.get(this.getSuiteFilepath())) == null ? void 0 : _b[filepath]) || filepath;
|
||||
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)) {
|
||||
throw new Error(
|
||||
`[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 "vi.importActual" inside:
|
||||
|
||||
${picocolors.exports.green(`vi.mock("${mockpath}", async () => {
|
||||
const actual = await vi.importActual("${mockpath}")
|
||||
return {
|
||||
...actual,
|
||||
// your mock
|
||||
},
|
||||
})`)}
|
||||
`
|
||||
);
|
||||
}
|
||||
return val;
|
||||
}
|
||||
});
|
||||
this.moduleCache.set(dep, { exports: moduleExports });
|
||||
return moduleExports;
|
||||
}
|
||||
getMockPath(dep) {
|
||||
return `mock:${dep}`;
|
||||
}
|
||||
getDependencyMock(id) {
|
||||
return this.getMocks()[id];
|
||||
}
|
||||
normalizePath(path) {
|
||||
return pathFromRoot(this.root, normalizeRequestId(path, this.base));
|
||||
}
|
||||
getFsPath(path, external) {
|
||||
if (external)
|
||||
return mergeSlashes(`/@fs/${path}`);
|
||||
return normalizeRequestId(path, this.base);
|
||||
}
|
||||
resolveMockPath(mockPath, external) {
|
||||
const path = normalizeRequestId(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 = {}) {
|
||||
if (!_VitestMocker.spyModule) {
|
||||
throw new Error(
|
||||
"Error: Spy module is not defined. This is likely an internal bug in Vitest. Please report it to https://github.com/vitest-dev/vitest/issues"
|
||||
);
|
||||
}
|
||||
const spyModule = _VitestMocker.spyModule;
|
||||
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)) {
|
||||
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) {
|
||||
spyModule.spyOn(newContainer, property).mockImplementation(() => void 0);
|
||||
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];
|
||||
const mockId = this.getMockPath(id);
|
||||
if (this.moduleCache.get(mockId))
|
||||
this.moduleCache.delete(mockId);
|
||||
}
|
||||
mockPath(originalId, path, external, factory) {
|
||||
const suitefile = this.getSuiteFilepath();
|
||||
const id = this.normalizePath(path);
|
||||
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);
|
||||
}
|
||||
async importActual(id, importer) {
|
||||
const { path, external } = await this.resolvePath(id, importer);
|
||||
const fsPath = this.getFsPath(path, external);
|
||||
const result = await this.request(fsPath);
|
||||
return result;
|
||||
}
|
||||
async importMock(id, importer) {
|
||||
const { path, external } = await this.resolvePath(id, importer);
|
||||
const fsPath = this.getFsPath(path, external);
|
||||
const normalizedId = this.normalizePath(fsPath);
|
||||
let mock = this.getDependencyMock(normalizedId);
|
||||
if (mock === void 0)
|
||||
mock = this.resolveMockPath(fsPath, external);
|
||||
if (mock === null) {
|
||||
await this.ensureSpy();
|
||||
const mod = await this.request(fsPath);
|
||||
return this.mockObject(mod);
|
||||
}
|
||||
if (typeof mock === "function")
|
||||
return this.callFunctionMock(fsPath, mock);
|
||||
return this.requestWithMock(mock);
|
||||
}
|
||||
async ensureSpy() {
|
||||
if (_VitestMocker.spyModule)
|
||||
return;
|
||||
_VitestMocker.spyModule = await this.request(`/@fs/${slash(resolve(distDir, "spy.js"))}`);
|
||||
}
|
||||
async requestWithMock(dep) {
|
||||
await Promise.all([
|
||||
this.ensureSpy(),
|
||||
this.resolveMocks()
|
||||
]);
|
||||
const id = this.normalizePath(dep);
|
||||
const mock = this.getDependencyMock(id);
|
||||
const callstack = this.request.callstack;
|
||||
const mockPath = this.getMockPath(id);
|
||||
if (mock === null) {
|
||||
const cache = this.moduleCache.get(mockPath);
|
||||
if (cache == null ? void 0 : cache.exports)
|
||||
return cache.exports;
|
||||
const exports = {};
|
||||
this.moduleCache.set(mockPath, { exports });
|
||||
const mod = await this.request(dep);
|
||||
this.mockObject(mod, exports);
|
||||
return exports;
|
||||
}
|
||||
if (typeof mock === "function" && !callstack.includes(mockPath)) {
|
||||
callstack.push(mockPath);
|
||||
const result = await this.callFunctionMock(mockPath, mock);
|
||||
const indexMock = callstack.indexOf(mockPath);
|
||||
callstack.splice(indexMock, 1);
|
||||
return result;
|
||||
}
|
||||
if (typeof mock === "string" && !callstack.includes(mock))
|
||||
dep = mock;
|
||||
return this.request(dep);
|
||||
}
|
||||
queueMock(id, importer, factory) {
|
||||
_VitestMocker.pendingIds.push({ type: "mock", id, importer, factory });
|
||||
}
|
||||
queueUnmock(id, importer) {
|
||||
_VitestMocker.pendingIds.push({ type: "unmock", id, importer });
|
||||
}
|
||||
};
|
||||
let VitestMocker = _VitestMocker;
|
||||
VitestMocker.pendingIds = [];
|
||||
|
||||
async function executeInViteNode(options) {
|
||||
const runner = new VitestRunner(options);
|
||||
await runner.executeId("/@vite/env");
|
||||
const result = [];
|
||||
for (const file of options.files)
|
||||
result.push(await runner.executeFile(file));
|
||||
return result;
|
||||
}
|
||||
class VitestRunner extends ViteNodeRunner {
|
||||
constructor(options) {
|
||||
super(options);
|
||||
this.options = options;
|
||||
}
|
||||
prepareContext(context) {
|
||||
const request = context.__vite_ssr_import__;
|
||||
const resolveId = context.__vitest_resolve_id__;
|
||||
const resolveUrl = async (dep) => {
|
||||
const [id, resolvedId] = await resolveId(dep);
|
||||
return resolvedId || id;
|
||||
};
|
||||
const mocker = new VitestMocker(this.options, this.moduleCache, request);
|
||||
const workerState = getWorkerState();
|
||||
if (workerState.filepath && normalizePath(workerState.filepath) === normalizePath(context.__filename)) {
|
||||
Object.defineProperty(context.__vite_ssr_import_meta__, "vitest", { get: () => globalThis.__vitest_index__ });
|
||||
}
|
||||
return Object.assign(context, {
|
||||
__vite_ssr_import__: async (dep) => mocker.requestWithMock(await resolveUrl(dep)),
|
||||
__vite_ssr_dynamic_import__: async (dep) => mocker.requestWithMock(await resolveUrl(dep)),
|
||||
__vitest_mocker__: mocker
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export { VitestRunner as V, executeInViteNode as e };
|
||||
30
node_modules/vitest/dist/chunk-runtime-rpc.42aebbb9.js
generated
vendored
Normal file
30
node_modules/vitest/dist/chunk-runtime-rpc.42aebbb9.js
generated
vendored
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { g as getWorkerState } from './chunk-typecheck-constants.ed987901.js';
|
||||
import { s as safeSetTimeout } from './chunk-utils-timers.793fd179.js';
|
||||
|
||||
const safeRandom = Math.random;
|
||||
function withSafeTimers(fn) {
|
||||
const currentSetTimeout = globalThis.setTimeout;
|
||||
const currentRandom = globalThis.Math.random;
|
||||
try {
|
||||
globalThis.setTimeout = safeSetTimeout;
|
||||
globalThis.Math.random = safeRandom;
|
||||
const result = fn();
|
||||
return result;
|
||||
} finally {
|
||||
globalThis.setTimeout = currentSetTimeout;
|
||||
globalThis.Math.random = currentRandom;
|
||||
}
|
||||
}
|
||||
const rpc = () => {
|
||||
const { rpc: rpc2 } = getWorkerState();
|
||||
return new Proxy(rpc2, {
|
||||
get(target, p, handler) {
|
||||
const sendCall = Reflect.get(target, p, handler);
|
||||
const safeSendCall = (...args) => withSafeTimers(() => sendCall(...args));
|
||||
safeSendCall.asEvent = sendCall.asEvent;
|
||||
return safeSendCall;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export { rpc as r };
|
||||
659
node_modules/vitest/dist/chunk-runtime-setup.5398e2c4.js
generated
vendored
Normal file
659
node_modules/vitest/dist/chunk-runtime-setup.5398e2c4.js
generated
vendored
Normal file
|
|
@ -0,0 +1,659 @@
|
|||
import { performance } from 'perf_hooks';
|
||||
import { s as someTasksAreOnly, i as interpretTaskModes, t as takeCoverageInsideWorker, p as pLimit } from './chunk-integrations-coverage.befed097.js';
|
||||
import { r as resetRunOnceCounter, i as index, v as vi, s as setCurrentTest } from './chunk-runtime-test-state.3f86f48f.js';
|
||||
import { g as getWorkerState, R as RealDate, t as toArray, k as relativePath, h as isRunningInBenchmark, p as partitionSuiteChildren, l as shuffle, q as hasTests, u as hasFailed, v as createDefer, e as getFullName } from './chunk-typecheck-constants.ed987901.js';
|
||||
import { f as clearCollectorContext, h as defaultSuite, j as setHooks, k as getHooks, l as collectorContext, m as getBenchOptions, n as getFn, o as setState, G as GLOBAL_EXPECT, p as getState } from './chunk-runtime-chain.f86e5250.js';
|
||||
import { r as rpc } from './chunk-runtime-rpc.42aebbb9.js';
|
||||
import { p as processError } from './chunk-runtime-error.616e92ca.js';
|
||||
import { s as sourceMapSupport } from './vendor-source-map-support.1ce17397.js';
|
||||
import { e as environments } from './chunk-env-node.67948209.js';
|
||||
import { i as isNode, a as isBrowser } from './chunk-utils-env.03f840f2.js';
|
||||
import { b as safeClearTimeout, s as safeSetTimeout } from './chunk-utils-timers.793fd179.js';
|
||||
|
||||
function installSourcemapsSupport(options) {
|
||||
sourceMapSupport.exports.install({
|
||||
environment: "node",
|
||||
handleUncaughtExceptions: false,
|
||||
retrieveSourceMap(source) {
|
||||
const map = options.getSourceMap(source);
|
||||
if (map) {
|
||||
return {
|
||||
url: source,
|
||||
map
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let globalSetup = false;
|
||||
async function setupGlobalEnv(config) {
|
||||
resetRunOnceCounter();
|
||||
Object.defineProperty(globalThis, "__vitest_index__", {
|
||||
value: index,
|
||||
enumerable: false
|
||||
});
|
||||
setupDefines(config.defines);
|
||||
if (globalSetup)
|
||||
return;
|
||||
globalSetup = true;
|
||||
if (isNode) {
|
||||
const state = getWorkerState();
|
||||
installSourcemapsSupport({
|
||||
getSourceMap: (source) => state.moduleCache.getSourceMap(source)
|
||||
});
|
||||
await setupConsoleLogSpy();
|
||||
}
|
||||
if (config.globals)
|
||||
(await import('./chunk-integrations-globals.4d261bb8.js')).registerApiGlobally();
|
||||
}
|
||||
function setupDefines(defines) {
|
||||
for (const key in defines)
|
||||
globalThis[key] = defines[key];
|
||||
}
|
||||
async function setupConsoleLogSpy() {
|
||||
const stdoutBuffer = /* @__PURE__ */ new Map();
|
||||
const stderrBuffer = /* @__PURE__ */ new Map();
|
||||
const timers = /* @__PURE__ */ new Map();
|
||||
const unknownTestId = "__vitest__unknown_test__";
|
||||
const { Writable } = await import('stream');
|
||||
const { Console } = await import('console');
|
||||
function schedule(taskId) {
|
||||
const timer = timers.get(taskId);
|
||||
const { stdoutTime, stderrTime } = timer;
|
||||
safeClearTimeout(timer.timer);
|
||||
timer.timer = safeSetTimeout(() => {
|
||||
if (stderrTime < stdoutTime) {
|
||||
sendStderr(taskId);
|
||||
sendStdout(taskId);
|
||||
} else {
|
||||
sendStdout(taskId);
|
||||
sendStderr(taskId);
|
||||
}
|
||||
});
|
||||
}
|
||||
function sendStdout(taskId) {
|
||||
const buffer = stdoutBuffer.get(taskId);
|
||||
if (!buffer)
|
||||
return;
|
||||
const content = buffer.map((i) => String(i)).join("");
|
||||
if (!content.trim())
|
||||
return;
|
||||
const timer = timers.get(taskId);
|
||||
rpc().onUserConsoleLog({
|
||||
type: "stdout",
|
||||
content,
|
||||
taskId,
|
||||
time: timer.stdoutTime || RealDate.now(),
|
||||
size: buffer.length
|
||||
});
|
||||
stdoutBuffer.set(taskId, []);
|
||||
timer.stdoutTime = 0;
|
||||
}
|
||||
function sendStderr(taskId) {
|
||||
const buffer = stderrBuffer.get(taskId);
|
||||
if (!buffer)
|
||||
return;
|
||||
const content = buffer.map((i) => String(i)).join("");
|
||||
if (!content.trim())
|
||||
return;
|
||||
const timer = timers.get(taskId);
|
||||
rpc().onUserConsoleLog({
|
||||
type: "stderr",
|
||||
content,
|
||||
taskId,
|
||||
time: timer.stderrTime || RealDate.now(),
|
||||
size: buffer.length
|
||||
});
|
||||
stderrBuffer.set(taskId, []);
|
||||
timer.stderrTime = 0;
|
||||
}
|
||||
const stdout = new Writable({
|
||||
write(data, encoding, callback) {
|
||||
var _a, _b;
|
||||
const id = ((_b = (_a = getWorkerState()) == null ? void 0 : _a.current) == null ? void 0 : _b.id) ?? unknownTestId;
|
||||
let timer = timers.get(id);
|
||||
if (timer) {
|
||||
timer.stdoutTime = timer.stdoutTime || RealDate.now();
|
||||
} else {
|
||||
timer = { stdoutTime: RealDate.now(), stderrTime: RealDate.now(), timer: 0 };
|
||||
timers.set(id, timer);
|
||||
}
|
||||
let buffer = stdoutBuffer.get(id);
|
||||
if (!buffer) {
|
||||
buffer = [];
|
||||
stdoutBuffer.set(id, buffer);
|
||||
}
|
||||
buffer.push(data);
|
||||
schedule(id);
|
||||
callback();
|
||||
}
|
||||
});
|
||||
const stderr = new Writable({
|
||||
write(data, encoding, callback) {
|
||||
var _a, _b;
|
||||
const id = ((_b = (_a = getWorkerState()) == null ? void 0 : _a.current) == null ? void 0 : _b.id) ?? unknownTestId;
|
||||
let timer = timers.get(id);
|
||||
if (timer) {
|
||||
timer.stderrTime = timer.stderrTime || RealDate.now();
|
||||
} else {
|
||||
timer = { stderrTime: RealDate.now(), stdoutTime: RealDate.now(), timer: 0 };
|
||||
timers.set(id, timer);
|
||||
}
|
||||
let buffer = stderrBuffer.get(id);
|
||||
if (!buffer) {
|
||||
buffer = [];
|
||||
stderrBuffer.set(id, buffer);
|
||||
}
|
||||
buffer.push(data);
|
||||
schedule(id);
|
||||
callback();
|
||||
}
|
||||
});
|
||||
globalThis.console = new Console({
|
||||
stdout,
|
||||
stderr,
|
||||
colorMode: true,
|
||||
groupIndentation: 2
|
||||
});
|
||||
}
|
||||
async function loadEnvironment(name) {
|
||||
const pkg = await import(`vitest-environment-${name}`);
|
||||
if (!pkg || !pkg.default || typeof pkg.default !== "object" || typeof pkg.default.setup !== "function") {
|
||||
throw new Error(
|
||||
`Environment "${name}" is not a valid environment. Package "vitest-environment-${name}" should have default export with "setup" method.`
|
||||
);
|
||||
}
|
||||
return pkg.default;
|
||||
}
|
||||
async function withEnv(name, options, fn) {
|
||||
const config = environments[name] || await loadEnvironment(name);
|
||||
const env = await config.setup(globalThis, options);
|
||||
try {
|
||||
await fn();
|
||||
} finally {
|
||||
await env.teardown(globalThis);
|
||||
}
|
||||
}
|
||||
async function runSetupFiles(config) {
|
||||
const files = toArray(config.setupFiles);
|
||||
await Promise.all(
|
||||
files.map(async (fsPath) => {
|
||||
getWorkerState().moduleCache.delete(fsPath);
|
||||
await import(fsPath);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const now$1 = Date.now;
|
||||
function hash(str) {
|
||||
let hash2 = 0;
|
||||
if (str.length === 0)
|
||||
return `${hash2}`;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const char = str.charCodeAt(i);
|
||||
hash2 = (hash2 << 5) - hash2 + char;
|
||||
hash2 = hash2 & hash2;
|
||||
}
|
||||
return `${hash2}`;
|
||||
}
|
||||
async function collectTests(paths, config) {
|
||||
const files = [];
|
||||
const browserHashMap = getWorkerState().browserHashMap;
|
||||
async function importFromBrowser(filepath) {
|
||||
const match = filepath.match(/^(\w:\/)/);
|
||||
const hash2 = browserHashMap.get(filepath);
|
||||
if (match)
|
||||
return await import(`/@fs/${filepath.slice(match[1].length)}?v=${hash2}`);
|
||||
else
|
||||
return await import(`${filepath}?v=${hash2}`);
|
||||
}
|
||||
for (const filepath of paths) {
|
||||
const path = relativePath(config.root, filepath);
|
||||
const file = {
|
||||
id: hash(path),
|
||||
name: path,
|
||||
type: "suite",
|
||||
mode: "run",
|
||||
filepath,
|
||||
tasks: []
|
||||
};
|
||||
clearCollectorContext();
|
||||
try {
|
||||
const setupStart = now$1();
|
||||
await runSetupFiles(config);
|
||||
const collectStart = now$1();
|
||||
file.setupDuration = collectStart - setupStart;
|
||||
if (config.browser && isBrowser)
|
||||
await importFromBrowser(filepath);
|
||||
else
|
||||
await import(filepath);
|
||||
const defaultTasks = await defaultSuite.collect(file);
|
||||
setHooks(file, getHooks(defaultTasks));
|
||||
for (const c of [...defaultTasks.tasks, ...collectorContext.tasks]) {
|
||||
if (c.type === "test") {
|
||||
file.tasks.push(c);
|
||||
} else if (c.type === "benchmark") {
|
||||
file.tasks.push(c);
|
||||
} else if (c.type === "suite") {
|
||||
file.tasks.push(c);
|
||||
} else if (c.type === "collector") {
|
||||
const suite = await c.collect(file);
|
||||
if (suite.name || suite.tasks.length)
|
||||
file.tasks.push(suite);
|
||||
}
|
||||
}
|
||||
file.collectDuration = now$1() - collectStart;
|
||||
} catch (e) {
|
||||
file.result = {
|
||||
state: "fail",
|
||||
error: processError(e)
|
||||
};
|
||||
if (config.browser)
|
||||
console.error(e);
|
||||
}
|
||||
calculateHash(file);
|
||||
const hasOnlyTasks = someTasksAreOnly(file);
|
||||
interpretTaskModes(file, config.testNamePattern, hasOnlyTasks, false, config.allowOnly);
|
||||
files.push(file);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
function calculateHash(parent) {
|
||||
parent.tasks.forEach((t, idx) => {
|
||||
t.id = `${parent.id}_${idx}`;
|
||||
if (t.type === "suite")
|
||||
calculateHash(t);
|
||||
});
|
||||
}
|
||||
|
||||
async function importTinybench() {
|
||||
if (!globalThis.EventTarget)
|
||||
await import('./vendor-index.534e612c.js').then(function (n) { return n.i; });
|
||||
return await import('tinybench');
|
||||
}
|
||||
const now = Date.now;
|
||||
function updateSuiteHookState(suite, name, state) {
|
||||
var _a;
|
||||
if (!suite.result)
|
||||
suite.result = { state: "run" };
|
||||
if (!((_a = suite.result) == null ? void 0 : _a.hooks))
|
||||
suite.result.hooks = {};
|
||||
const suiteHooks = suite.result.hooks;
|
||||
if (suiteHooks) {
|
||||
suiteHooks[name] = state;
|
||||
updateTask(suite);
|
||||
}
|
||||
}
|
||||
function getSuiteHooks(suite, name, sequence) {
|
||||
const hooks = getHooks(suite)[name];
|
||||
if (sequence === "stack" && (name === "afterAll" || name === "afterEach"))
|
||||
return hooks.slice().reverse();
|
||||
return hooks;
|
||||
}
|
||||
async function callSuiteHook(suite, currentTask, name, args) {
|
||||
const callbacks = [];
|
||||
if (name === "beforeEach" && suite.suite) {
|
||||
callbacks.push(
|
||||
...await callSuiteHook(suite.suite, currentTask, name, args)
|
||||
);
|
||||
}
|
||||
updateSuiteHookState(currentTask, name, "run");
|
||||
const state = getWorkerState();
|
||||
const sequence = state.config.sequence.hooks;
|
||||
const hooks = getSuiteHooks(suite, name, sequence);
|
||||
if (sequence === "parallel") {
|
||||
callbacks.push(...await Promise.all(hooks.map((fn) => fn(...args))));
|
||||
} else {
|
||||
for (const hook of hooks)
|
||||
callbacks.push(await hook(...args));
|
||||
}
|
||||
updateSuiteHookState(currentTask, name, "pass");
|
||||
if (name === "afterEach" && suite.suite) {
|
||||
callbacks.push(
|
||||
...await callSuiteHook(suite.suite, currentTask, name, args)
|
||||
);
|
||||
}
|
||||
return callbacks;
|
||||
}
|
||||
const packs = /* @__PURE__ */ new Map();
|
||||
let updateTimer;
|
||||
let previousUpdate;
|
||||
function updateTask(task) {
|
||||
packs.set(task.id, task.result);
|
||||
safeClearTimeout(updateTimer);
|
||||
updateTimer = safeSetTimeout(() => {
|
||||
previousUpdate = sendTasksUpdate();
|
||||
}, 10);
|
||||
}
|
||||
async function sendTasksUpdate() {
|
||||
safeClearTimeout(updateTimer);
|
||||
await previousUpdate;
|
||||
if (packs.size) {
|
||||
const p = rpc().onTaskUpdate(Array.from(packs));
|
||||
packs.clear();
|
||||
return p;
|
||||
}
|
||||
}
|
||||
const callCleanupHooks = async (cleanups) => {
|
||||
await Promise.all(cleanups.map(async (fn) => {
|
||||
if (typeof fn !== "function")
|
||||
return;
|
||||
await fn();
|
||||
}));
|
||||
};
|
||||
async function runTest(test) {
|
||||
var _a, _b, _c;
|
||||
if (test.mode !== "run") {
|
||||
const { getSnapshotClient } = await import('./chunk-runtime-chain.f86e5250.js').then(function (n) { return n.r; });
|
||||
getSnapshotClient().skipTestSnapshots(test);
|
||||
return;
|
||||
}
|
||||
if (((_a = test.result) == null ? void 0 : _a.state) === "fail") {
|
||||
updateTask(test);
|
||||
return;
|
||||
}
|
||||
const start = now();
|
||||
test.result = {
|
||||
state: "run",
|
||||
startTime: start
|
||||
};
|
||||
updateTask(test);
|
||||
clearModuleMocks();
|
||||
setCurrentTest(test);
|
||||
if (isNode) {
|
||||
const { getSnapshotClient } = await import('./chunk-runtime-chain.f86e5250.js').then(function (n) { return n.r; });
|
||||
await getSnapshotClient().setTest(test);
|
||||
}
|
||||
const workerState = getWorkerState();
|
||||
workerState.current = test;
|
||||
const retry = test.retry || 1;
|
||||
for (let retryCount = 0; retryCount < retry; retryCount++) {
|
||||
let beforeEachCleanups = [];
|
||||
try {
|
||||
setState({
|
||||
assertionCalls: 0,
|
||||
isExpectingAssertions: false,
|
||||
isExpectingAssertionsError: null,
|
||||
expectedAssertionsNumber: null,
|
||||
expectedAssertionsNumberErrorGen: null,
|
||||
testPath: (_b = test.suite.file) == null ? void 0 : _b.filepath,
|
||||
currentTestName: getFullName(test)
|
||||
}, globalThis[GLOBAL_EXPECT]);
|
||||
beforeEachCleanups = await callSuiteHook(test.suite, test, "beforeEach", [test.context, test.suite]);
|
||||
test.result.retryCount = retryCount;
|
||||
await getFn(test)();
|
||||
const {
|
||||
assertionCalls,
|
||||
expectedAssertionsNumber,
|
||||
expectedAssertionsNumberErrorGen,
|
||||
isExpectingAssertions,
|
||||
isExpectingAssertionsError
|
||||
} = test.context._local ? test.context.expect.getState() : getState(globalThis[GLOBAL_EXPECT]);
|
||||
if (expectedAssertionsNumber !== null && assertionCalls !== expectedAssertionsNumber)
|
||||
throw expectedAssertionsNumberErrorGen();
|
||||
if (isExpectingAssertions === true && assertionCalls === 0)
|
||||
throw isExpectingAssertionsError;
|
||||
test.result.state = "pass";
|
||||
} catch (e) {
|
||||
test.result.state = "fail";
|
||||
test.result.error = processError(e);
|
||||
}
|
||||
try {
|
||||
await callSuiteHook(test.suite, test, "afterEach", [test.context, test.suite]);
|
||||
await callCleanupHooks(beforeEachCleanups);
|
||||
} catch (e) {
|
||||
test.result.state = "fail";
|
||||
test.result.error = processError(e);
|
||||
}
|
||||
if (test.result.state === "pass")
|
||||
break;
|
||||
updateTask(test);
|
||||
}
|
||||
if (test.result.state === "fail")
|
||||
await Promise.all(((_c = test.onFailed) == null ? void 0 : _c.map((fn) => fn(test.result))) || []);
|
||||
if (test.fails) {
|
||||
if (test.result.state === "pass") {
|
||||
test.result.state = "fail";
|
||||
test.result.error = processError(new Error("Expect test to fail"));
|
||||
} else {
|
||||
test.result.state = "pass";
|
||||
test.result.error = void 0;
|
||||
}
|
||||
}
|
||||
if (isBrowser && test.result.error)
|
||||
console.error(test.result.error.message, test.result.error.stackStr);
|
||||
setCurrentTest(void 0);
|
||||
if (isNode) {
|
||||
const { getSnapshotClient } = await import('./chunk-runtime-chain.f86e5250.js').then(function (n) { return n.r; });
|
||||
getSnapshotClient().clearTest();
|
||||
}
|
||||
test.result.duration = now() - start;
|
||||
if (workerState.config.logHeapUsage && isNode)
|
||||
test.result.heap = process.memoryUsage().heapUsed;
|
||||
workerState.current = void 0;
|
||||
updateTask(test);
|
||||
}
|
||||
function markTasksAsSkipped(suite) {
|
||||
suite.tasks.forEach((t) => {
|
||||
t.mode = "skip";
|
||||
t.result = { ...t.result, state: "skip" };
|
||||
updateTask(t);
|
||||
if (t.type === "suite")
|
||||
markTasksAsSkipped(t);
|
||||
});
|
||||
}
|
||||
async function runSuite(suite) {
|
||||
var _a;
|
||||
if (((_a = suite.result) == null ? void 0 : _a.state) === "fail") {
|
||||
markTasksAsSkipped(suite);
|
||||
updateTask(suite);
|
||||
return;
|
||||
}
|
||||
const start = now();
|
||||
suite.result = {
|
||||
state: "run",
|
||||
startTime: start
|
||||
};
|
||||
updateTask(suite);
|
||||
const workerState = getWorkerState();
|
||||
if (suite.mode === "skip") {
|
||||
suite.result.state = "skip";
|
||||
} else if (suite.mode === "todo") {
|
||||
suite.result.state = "todo";
|
||||
} else {
|
||||
try {
|
||||
const beforeAllCleanups = await callSuiteHook(suite, suite, "beforeAll", [suite]);
|
||||
if (isRunningInBenchmark()) {
|
||||
await runBenchmarkSuite(suite);
|
||||
} else {
|
||||
for (let tasksGroup of partitionSuiteChildren(suite)) {
|
||||
if (tasksGroup[0].concurrent === true) {
|
||||
const mutex = pLimit(workerState.config.maxConcurrency);
|
||||
await Promise.all(tasksGroup.map((c) => mutex(() => runSuiteChild(c))));
|
||||
} else {
|
||||
const { sequence } = workerState.config;
|
||||
if (sequence.shuffle || suite.shuffle) {
|
||||
const suites = tasksGroup.filter((group) => group.type === "suite");
|
||||
const tests = tasksGroup.filter((group) => group.type === "test");
|
||||
const groups = shuffle([suites, tests], sequence.seed);
|
||||
tasksGroup = groups.flatMap((group) => shuffle(group, sequence.seed));
|
||||
}
|
||||
for (const c of tasksGroup)
|
||||
await runSuiteChild(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
await callSuiteHook(suite, suite, "afterAll", [suite]);
|
||||
await callCleanupHooks(beforeAllCleanups);
|
||||
} catch (e) {
|
||||
suite.result.state = "fail";
|
||||
suite.result.error = processError(e);
|
||||
}
|
||||
}
|
||||
suite.result.duration = now() - start;
|
||||
if (workerState.config.logHeapUsage && isNode)
|
||||
suite.result.heap = process.memoryUsage().heapUsed;
|
||||
if (suite.mode === "run") {
|
||||
if (!hasTests(suite)) {
|
||||
suite.result.state = "fail";
|
||||
if (!suite.result.error)
|
||||
suite.result.error = new Error(`No test found in suite ${suite.name}`);
|
||||
} else if (hasFailed(suite)) {
|
||||
suite.result.state = "fail";
|
||||
} else {
|
||||
suite.result.state = "pass";
|
||||
}
|
||||
}
|
||||
updateTask(suite);
|
||||
}
|
||||
function createBenchmarkResult(name) {
|
||||
return {
|
||||
name,
|
||||
rank: 0,
|
||||
rme: 0,
|
||||
samples: []
|
||||
};
|
||||
}
|
||||
async function runBenchmarkSuite(suite) {
|
||||
const { Task, Bench } = await importTinybench();
|
||||
const start = performance.now();
|
||||
const benchmarkGroup = [];
|
||||
const benchmarkSuiteGroup = [];
|
||||
for (const task of suite.tasks) {
|
||||
if (task.mode !== "run")
|
||||
continue;
|
||||
if (task.type === "benchmark")
|
||||
benchmarkGroup.push(task);
|
||||
else if (task.type === "suite")
|
||||
benchmarkSuiteGroup.push(task);
|
||||
}
|
||||
if (benchmarkSuiteGroup.length)
|
||||
await Promise.all(benchmarkSuiteGroup.map((subSuite) => runBenchmarkSuite(subSuite)));
|
||||
if (benchmarkGroup.length) {
|
||||
const defer = createDefer();
|
||||
const benchmarkMap = {};
|
||||
suite.result = {
|
||||
state: "run",
|
||||
startTime: start,
|
||||
benchmark: createBenchmarkResult(suite.name)
|
||||
};
|
||||
updateTask(suite);
|
||||
benchmarkGroup.forEach((benchmark, idx) => {
|
||||
const options = getBenchOptions(benchmark);
|
||||
const benchmarkInstance = new Bench(options);
|
||||
const benchmarkFn = getFn(benchmark);
|
||||
benchmark.result = {
|
||||
state: "run",
|
||||
startTime: start,
|
||||
benchmark: createBenchmarkResult(benchmark.name)
|
||||
};
|
||||
const id = idx.toString();
|
||||
benchmarkMap[id] = benchmark;
|
||||
const task = new Task(benchmarkInstance, id, benchmarkFn);
|
||||
benchmark.task = task;
|
||||
updateTask(benchmark);
|
||||
});
|
||||
benchmarkGroup.forEach((benchmark) => {
|
||||
benchmark.task.addEventListener("complete", (e) => {
|
||||
const task = e.task;
|
||||
const _benchmark = benchmarkMap[task.name || ""];
|
||||
if (_benchmark) {
|
||||
const taskRes = task.result;
|
||||
const result = _benchmark.result.benchmark;
|
||||
Object.assign(result, taskRes);
|
||||
updateTask(_benchmark);
|
||||
}
|
||||
});
|
||||
benchmark.task.addEventListener("error", (e) => {
|
||||
const task = e.task;
|
||||
const _benchmark = benchmarkMap[task.name || ""];
|
||||
defer.reject(_benchmark ? task.result.error : e);
|
||||
});
|
||||
});
|
||||
Promise.all(benchmarkGroup.map(async (benchmark) => {
|
||||
await benchmark.task.warmup();
|
||||
return await new Promise((resolve) => safeSetTimeout(async () => {
|
||||
resolve(await benchmark.task.run());
|
||||
}));
|
||||
})).then((tasks) => {
|
||||
suite.result.duration = performance.now() - start;
|
||||
suite.result.state = "pass";
|
||||
tasks.sort((a, b) => a.result.mean - b.result.mean).forEach((cycle, idx) => {
|
||||
const benchmark = benchmarkMap[cycle.name || ""];
|
||||
benchmark.result.state = "pass";
|
||||
if (benchmark) {
|
||||
const result = benchmark.result.benchmark;
|
||||
result.rank = Number(idx) + 1;
|
||||
updateTask(benchmark);
|
||||
}
|
||||
});
|
||||
updateTask(suite);
|
||||
defer.resolve(null);
|
||||
});
|
||||
await defer;
|
||||
}
|
||||
}
|
||||
async function runSuiteChild(c) {
|
||||
if (c.type === "test")
|
||||
return runTest(c);
|
||||
else if (c.type === "suite")
|
||||
return runSuite(c);
|
||||
}
|
||||
async function runSuites(suites) {
|
||||
for (const suite of suites)
|
||||
await runSuite(suite);
|
||||
}
|
||||
async function runFiles(files, config) {
|
||||
var _a;
|
||||
for (const file of files) {
|
||||
if (!file.tasks.length && !config.passWithNoTests) {
|
||||
if (!((_a = file.result) == null ? void 0 : _a.error)) {
|
||||
file.result = {
|
||||
state: "fail",
|
||||
error: new Error(`No test suite found in file ${file.filepath}`)
|
||||
};
|
||||
}
|
||||
}
|
||||
await runSuite(file);
|
||||
}
|
||||
}
|
||||
async function startTestsBrowser(paths, config) {
|
||||
if (isNode) {
|
||||
rpc().onPathsCollected(paths);
|
||||
} else {
|
||||
const files = await collectTests(paths, config);
|
||||
await rpc().onCollected(files);
|
||||
await runSuites(files);
|
||||
await sendTasksUpdate();
|
||||
}
|
||||
}
|
||||
async function startTestsNode(paths, config) {
|
||||
const files = await collectTests(paths, config);
|
||||
rpc().onCollected(files);
|
||||
const { getSnapshotClient } = await import('./chunk-runtime-chain.f86e5250.js').then(function (n) { return n.r; });
|
||||
getSnapshotClient().clear();
|
||||
await runFiles(files, config);
|
||||
const coverage = await takeCoverageInsideWorker(config.coverage);
|
||||
rpc().onAfterSuiteRun({ coverage });
|
||||
await getSnapshotClient().saveCurrent();
|
||||
await sendTasksUpdate();
|
||||
}
|
||||
async function startTests(paths, config) {
|
||||
if (config.browser)
|
||||
return startTestsBrowser(paths, config);
|
||||
else
|
||||
return startTestsNode(paths, config);
|
||||
}
|
||||
function clearModuleMocks() {
|
||||
const { clearMocks, mockReset, restoreMocks } = getWorkerState().config;
|
||||
if (restoreMocks)
|
||||
vi.restoreAllMocks();
|
||||
else if (mockReset)
|
||||
vi.resetAllMocks();
|
||||
else if (clearMocks)
|
||||
vi.clearAllMocks();
|
||||
}
|
||||
|
||||
export { setupGlobalEnv as a, startTests as s, withEnv as w };
|
||||
2984
node_modules/vitest/dist/chunk-runtime-test-state.3f86f48f.js
generated
vendored
Normal file
2984
node_modules/vitest/dist/chunk-runtime-test-state.3f86f48f.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
358
node_modules/vitest/dist/chunk-typecheck-constants.ed987901.js
generated
vendored
Normal file
358
node_modules/vitest/dist/chunk-typecheck-constants.ed987901.js
generated
vendored
Normal file
|
|
@ -0,0 +1,358 @@
|
|||
import { relative } from 'path';
|
||||
import { i as isNode, a as isBrowser, r as relative$1, p as picocolors, E as EXIT_CODE_RESTART } from './chunk-utils-env.03f840f2.js';
|
||||
import { isPackageExists } from 'local-pkg';
|
||||
|
||||
const TYPECHECK_SUITE = Symbol("vitest:typecheck-suite");
|
||||
|
||||
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;
|
||||
}
|
||||
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 (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;
|
||||
}
|
||||
|
||||
function isFinalObj(obj) {
|
||||
return obj === Object.prototype || obj === Function.prototype || obj === RegExp.prototype;
|
||||
}
|
||||
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 getAllMockableProperties(obj) {
|
||||
const allProps = /* @__PURE__ */ new Set();
|
||||
let curr = obj;
|
||||
do {
|
||||
if (isFinalObj(curr))
|
||||
break;
|
||||
collectOwnProperties(curr, (key) => {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(curr, key);
|
||||
if (descriptor)
|
||||
allProps.add({ key, descriptor });
|
||||
});
|
||||
} while (curr = Object.getPrototypeOf(curr));
|
||||
return Array.from(allProps);
|
||||
}
|
||||
function notNullish(v) {
|
||||
return v != null;
|
||||
}
|
||||
function slash(str) {
|
||||
return str.replace(/\\/g, "/");
|
||||
}
|
||||
function mergeSlashes(str) {
|
||||
return str.replace(/\/\//g, "/");
|
||||
}
|
||||
const noop = () => {
|
||||
};
|
||||
function getType(value) {
|
||||
return Object.prototype.toString.apply(value).slice(8, -1);
|
||||
}
|
||||
function getOwnProperties(obj) {
|
||||
const ownProps = /* @__PURE__ */ new Set();
|
||||
if (isFinalObj(obj))
|
||||
return [];
|
||||
collectOwnProperties(obj, ownProps);
|
||||
return Array.from(ownProps);
|
||||
}
|
||||
function deepClone(val) {
|
||||
const seen = /* @__PURE__ */ new WeakMap();
|
||||
return clone(val, seen);
|
||||
}
|
||||
function clone(val, seen) {
|
||||
let k, out;
|
||||
if (seen.has(val))
|
||||
return seen.get(val);
|
||||
if (Array.isArray(val)) {
|
||||
out = Array(k = val.length);
|
||||
seen.set(val, out);
|
||||
while (k--)
|
||||
out[k] = clone(val[k], seen);
|
||||
return out;
|
||||
}
|
||||
if (Object.prototype.toString.call(val) === "[object Object]") {
|
||||
out = Object.create(Object.getPrototypeOf(val));
|
||||
seen.set(val, out);
|
||||
const props = getOwnProperties(val);
|
||||
for (const k2 of props)
|
||||
out[k2] = clone(val[k2], seen);
|
||||
return out;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
function toArray(array) {
|
||||
if (array === null || array === void 0)
|
||||
array = [];
|
||||
if (Array.isArray(array))
|
||||
return array;
|
||||
return [array];
|
||||
}
|
||||
const toString = (v) => Object.prototype.toString.call(v);
|
||||
const isPlainObject = (val) => toString(val) === "[object Object]" && (!val.constructor || val.constructor.name === "Object");
|
||||
function isObject(item) {
|
||||
return item != null && typeof item === "object" && !Array.isArray(item);
|
||||
}
|
||||
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 assertTypes(value, name, types) {
|
||||
const receivedType = typeof value;
|
||||
const pass = types.includes(receivedType);
|
||||
if (!pass)
|
||||
throw new TypeError(`${name} value must be ${types.join(" or ")}, received "${receivedType}"`);
|
||||
}
|
||||
function stdout() {
|
||||
return console._stdout || process.stdout;
|
||||
}
|
||||
function random(seed) {
|
||||
const x = Math.sin(seed++) * 1e4;
|
||||
return x - Math.floor(x);
|
||||
}
|
||||
function shuffle(array, seed = RealDate.now()) {
|
||||
let length = array.length;
|
||||
while (length) {
|
||||
const index = Math.floor(random(seed) * length--);
|
||||
const previous = array[length];
|
||||
array[length] = array[index];
|
||||
array[index] = previous;
|
||||
++seed;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
function isAtomTest(s) {
|
||||
return s.type === "test" || s.type === "benchmark" || s.type === "typecheck";
|
||||
}
|
||||
function getTests(suite) {
|
||||
return toArray(suite).flatMap((s) => isAtomTest(s) ? [s] : s.tasks.flatMap((c) => isAtomTest(c) ? [c] : getTests(c)));
|
||||
}
|
||||
function isTypecheckTest(suite) {
|
||||
return TYPECHECK_SUITE in suite;
|
||||
}
|
||||
function getTypecheckTests(suite) {
|
||||
return toArray(suite).flatMap((s) => {
|
||||
if (s.type !== "suite")
|
||||
return [];
|
||||
return TYPECHECK_SUITE in s ? [s, ...getTypecheckTests(s.tasks)] : getTypecheckTests(s.tasks);
|
||||
});
|
||||
}
|
||||
function getSuites(suite) {
|
||||
return toArray(suite).flatMap((s) => s.type === "suite" ? [s, ...getSuites(s.tasks)] : []);
|
||||
}
|
||||
function hasTests(suite) {
|
||||
return toArray(suite).some((s) => s.tasks.some((c) => isAtomTest(c) || hasTests(c)));
|
||||
}
|
||||
function hasFailed(suite) {
|
||||
return toArray(suite).some((s) => {
|
||||
var _a;
|
||||
return ((_a = s.result) == null ? void 0 : _a.state) === "fail" || s.type === "suite" && hasFailed(s.tasks);
|
||||
});
|
||||
}
|
||||
function hasFailedSnapshot(suite) {
|
||||
return getTests(suite).some((s) => {
|
||||
var _a, _b;
|
||||
const message = (_b = (_a = s.result) == null ? void 0 : _a.error) == null ? void 0 : _b.message;
|
||||
return message == null ? void 0 : message.match(/Snapshot .* mismatched/);
|
||||
});
|
||||
}
|
||||
function getNames(task) {
|
||||
const names = [task.name];
|
||||
let current = task;
|
||||
while ((current == null ? void 0 : current.suite) || (current == null ? void 0 : current.file)) {
|
||||
current = current.suite || current.file;
|
||||
if (current == null ? void 0 : current.name)
|
||||
names.unshift(current.name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
function getWorkerState() {
|
||||
return globalThis.__vitest_worker__;
|
||||
}
|
||||
|
||||
const isWindows = isNode && process.platform === "win32";
|
||||
const getRunMode = () => getWorkerState().config.mode;
|
||||
const isRunningInTest = () => getRunMode() === "test";
|
||||
const isRunningInBenchmark = () => getRunMode() === "benchmark";
|
||||
const relativePath = isBrowser ? relative : relative$1;
|
||||
function partitionSuiteChildren(suite) {
|
||||
let tasksGroup = [];
|
||||
const tasksGroups = [];
|
||||
for (const c2 of suite.tasks) {
|
||||
if (tasksGroup.length === 0 || c2.concurrent === tasksGroup[0].concurrent) {
|
||||
tasksGroup.push(c2);
|
||||
} else {
|
||||
tasksGroups.push(tasksGroup);
|
||||
tasksGroup = [c2];
|
||||
}
|
||||
}
|
||||
if (tasksGroup.length > 0)
|
||||
tasksGroups.push(tasksGroup);
|
||||
return tasksGroups;
|
||||
}
|
||||
function resetModules(modules, resetMocks = false) {
|
||||
const skipPaths = [
|
||||
/\/vitest\/dist\//,
|
||||
/vitest-virtual-\w+\/dist/,
|
||||
/@vitest\/dist/,
|
||||
...!resetMocks ? [/^mock:/] : []
|
||||
];
|
||||
modules.forEach((_, path) => {
|
||||
if (skipPaths.some((re) => re.test(path)))
|
||||
return;
|
||||
modules.delete(path);
|
||||
});
|
||||
}
|
||||
function getFullName(task) {
|
||||
return getNames(task).join(picocolors.exports.dim(" > "));
|
||||
}
|
||||
function removeUndefinedValues(obj) {
|
||||
for (const key in Object.keys(obj)) {
|
||||
if (obj[key] === void 0)
|
||||
delete obj[key];
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
async function ensurePackageInstalled(dependency, root) {
|
||||
if (isPackageExists(dependency, { paths: [root] }))
|
||||
return true;
|
||||
const promptInstall = !process.env.CI && process.stdout.isTTY;
|
||||
process.stderr.write(picocolors.exports.red(`${picocolors.exports.inverse(picocolors.exports.red(" MISSING DEP "))} Can not find dependency '${dependency}'
|
||||
|
||||
`));
|
||||
if (!promptInstall)
|
||||
return false;
|
||||
const prompts = await import('./vendor-index.9f20a9be.js').then(function (n) { return n.i; });
|
||||
const { install } = await prompts.prompt({
|
||||
type: "confirm",
|
||||
name: "install",
|
||||
message: picocolors.exports.reset(`Do you want to install ${picocolors.exports.green(dependency)}?`)
|
||||
});
|
||||
if (install) {
|
||||
await (await import('./chunk-install-pkg.579a5a27.js')).installPackage(dependency, { dev: true });
|
||||
process.stderr.write(picocolors.exports.yellow(`
|
||||
Package ${dependency} installed, re-run the command to start.
|
||||
`));
|
||||
process.exit(EXIT_CODE_RESTART);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function getCallLastIndex(code) {
|
||||
let charIndex = -1;
|
||||
let inString = null;
|
||||
let startedBracers = 0;
|
||||
let endedBracers = 0;
|
||||
let beforeChar = null;
|
||||
while (charIndex <= code.length) {
|
||||
beforeChar = code[charIndex];
|
||||
charIndex++;
|
||||
const char = code[charIndex];
|
||||
const isCharString = char === '"' || char === "'" || char === "`";
|
||||
if (isCharString && beforeChar !== "\\") {
|
||||
if (inString === char)
|
||||
inString = null;
|
||||
else if (!inString)
|
||||
inString = char;
|
||||
}
|
||||
if (!inString) {
|
||||
if (char === "(")
|
||||
startedBracers++;
|
||||
if (char === ")")
|
||||
endedBracers++;
|
||||
}
|
||||
if (startedBracers && endedBracers && startedBracers === endedBracers)
|
||||
return charIndex;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
isNode ? relative$1 : relative;
|
||||
class AggregateErrorPonyfill extends Error {
|
||||
constructor(errors, message = "") {
|
||||
super(message);
|
||||
this.errors = [...errors];
|
||||
}
|
||||
}
|
||||
function createDefer() {
|
||||
let resolve2 = null;
|
||||
let reject = null;
|
||||
const p = new Promise((_resolve, _reject) => {
|
||||
resolve2 = _resolve;
|
||||
reject = _reject;
|
||||
});
|
||||
p.resolve = resolve2;
|
||||
p.reject = reject;
|
||||
return p;
|
||||
}
|
||||
function objectAttr(source, path, defaultValue = void 0) {
|
||||
const paths = path.replace(/\[(\d+)\]/g, ".$1").split(".");
|
||||
let result = source;
|
||||
for (const p of paths) {
|
||||
result = Object(result)[p];
|
||||
if (result === void 0)
|
||||
return defaultValue;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export { AggregateErrorPonyfill as A, hasFailedSnapshot as B, getTypecheckTests as C, getSuites as D, isTypecheckTest as E, deepMerge as F, removeUndefinedValues as G, isWindows as H, stdout as I, mergeSlashes as J, getAllMockableProperties as K, RealDate as R, TYPECHECK_SUITE as T, resetModules as a, getCallLastIndex as b, getNames as c, assertTypes as d, getFullName as e, isRunningInTest as f, getWorkerState as g, isRunningInBenchmark as h, isObject as i, notNullish as j, relativePath as k, shuffle as l, mockDate as m, noop as n, objectAttr as o, partitionSuiteChildren as p, hasTests as q, resetDate as r, slash as s, toArray as t, hasFailed as u, createDefer as v, deepClone as w, getType as x, ensurePackageInstalled as y, getTests as z };
|
||||
290
node_modules/vitest/dist/chunk-utils-env.03f840f2.js
generated
vendored
Normal file
290
node_modules/vitest/dist/chunk-utils-env.03f840f2.js
generated
vendored
Normal file
|
|
@ -0,0 +1,290 @@
|
|||
import require$$0 from 'tty';
|
||||
import url from 'url';
|
||||
import path from 'path';
|
||||
|
||||
var picocolors = {exports: {}};
|
||||
|
||||
let tty = require$$0;
|
||||
|
||||
let isColorSupported =
|
||||
!("NO_COLOR" in process.env || process.argv.includes("--no-color")) &&
|
||||
("FORCE_COLOR" in process.env ||
|
||||
process.argv.includes("--color") ||
|
||||
process.platform === "win32" ||
|
||||
(tty.isatty(1) && process.env.TERM !== "dumb") ||
|
||||
"CI" in process.env);
|
||||
|
||||
let formatter =
|
||||
(open, close, replace = open) =>
|
||||
input => {
|
||||
let string = "" + input;
|
||||
let index = string.indexOf(close, open.length);
|
||||
return ~index
|
||||
? open + replaceClose(string, close, replace, index) + close
|
||||
: open + string + close
|
||||
};
|
||||
|
||||
let replaceClose = (string, close, replace, index) => {
|
||||
let start = string.substring(0, index) + replace;
|
||||
let end = string.substring(index + close.length);
|
||||
let nextIndex = end.indexOf(close);
|
||||
return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
|
||||
};
|
||||
|
||||
let createColors = (enabled = isColorSupported) => ({
|
||||
isColorSupported: enabled,
|
||||
reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
|
||||
bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
|
||||
dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
|
||||
italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
|
||||
underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
|
||||
inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
|
||||
hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
|
||||
strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
|
||||
black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
|
||||
red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
|
||||
green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
|
||||
yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
|
||||
blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
|
||||
magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
|
||||
cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
|
||||
white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
|
||||
gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
|
||||
bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
|
||||
bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
|
||||
bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
|
||||
bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
|
||||
bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
|
||||
bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
|
||||
bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
|
||||
bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
|
||||
});
|
||||
|
||||
picocolors.exports = createColors();
|
||||
picocolors.exports.createColors = createColors;
|
||||
|
||||
function normalizeWindowsPath(input = "") {
|
||||
if (!input.includes("\\")) {
|
||||
return input;
|
||||
}
|
||||
return input.replace(/\\/g, "/");
|
||||
}
|
||||
|
||||
const _UNC_REGEX = /^[/][/]/;
|
||||
const _UNC_DRIVE_REGEX = /^[/][/]([.]{1,2}[/])?([a-zA-Z]):[/]/;
|
||||
const _IS_ABSOLUTE_RE = /^\/|^\\|^[a-zA-Z]:[/\\]/;
|
||||
const sep = "/";
|
||||
const delimiter = ":";
|
||||
const normalize = function(path2) {
|
||||
if (path2.length === 0) {
|
||||
return ".";
|
||||
}
|
||||
path2 = normalizeWindowsPath(path2);
|
||||
const isUNCPath = path2.match(_UNC_REGEX);
|
||||
const hasUNCDrive = isUNCPath && path2.match(_UNC_DRIVE_REGEX);
|
||||
const isPathAbsolute = isAbsolute(path2);
|
||||
const trailingSeparator = path2[path2.length - 1] === "/";
|
||||
path2 = normalizeString(path2, !isPathAbsolute);
|
||||
if (path2.length === 0) {
|
||||
if (isPathAbsolute) {
|
||||
return "/";
|
||||
}
|
||||
return trailingSeparator ? "./" : ".";
|
||||
}
|
||||
if (trailingSeparator) {
|
||||
path2 += "/";
|
||||
}
|
||||
if (isUNCPath) {
|
||||
if (hasUNCDrive) {
|
||||
return `//./${path2}`;
|
||||
}
|
||||
return `//${path2}`;
|
||||
}
|
||||
return isPathAbsolute && !isAbsolute(path2) ? `/${path2}` : path2;
|
||||
};
|
||||
const join = function(...args) {
|
||||
if (args.length === 0) {
|
||||
return ".";
|
||||
}
|
||||
let joined;
|
||||
for (let i = 0; i < args.length; ++i) {
|
||||
const arg = args[i];
|
||||
if (arg.length > 0) {
|
||||
if (joined === void 0) {
|
||||
joined = arg;
|
||||
} else {
|
||||
joined += `/${arg}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (joined === void 0) {
|
||||
return ".";
|
||||
}
|
||||
return normalize(joined);
|
||||
};
|
||||
const resolve = function(...args) {
|
||||
args = args.map((arg) => normalizeWindowsPath(arg));
|
||||
let resolvedPath = "";
|
||||
let resolvedAbsolute = false;
|
||||
for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
|
||||
const path2 = i >= 0 ? args[i] : process.cwd();
|
||||
if (path2.length === 0) {
|
||||
continue;
|
||||
}
|
||||
resolvedPath = `${path2}/${resolvedPath}`;
|
||||
resolvedAbsolute = isAbsolute(path2);
|
||||
}
|
||||
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
||||
if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
|
||||
return `/${resolvedPath}`;
|
||||
}
|
||||
return resolvedPath.length > 0 ? resolvedPath : ".";
|
||||
};
|
||||
function normalizeString(path2, allowAboveRoot) {
|
||||
let res = "";
|
||||
let lastSegmentLength = 0;
|
||||
let lastSlash = -1;
|
||||
let dots = 0;
|
||||
let char = null;
|
||||
for (let i = 0; i <= path2.length; ++i) {
|
||||
if (i < path2.length) {
|
||||
char = path2[i];
|
||||
} else if (char === "/") {
|
||||
break;
|
||||
} else {
|
||||
char = "/";
|
||||
}
|
||||
if (char === "/") {
|
||||
if (lastSlash === i - 1 || dots === 1) ; else if (dots === 2) {
|
||||
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
|
||||
if (res.length > 2) {
|
||||
const lastSlashIndex = res.lastIndexOf("/");
|
||||
if (lastSlashIndex === -1) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
} else {
|
||||
res = res.slice(0, lastSlashIndex);
|
||||
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
|
||||
}
|
||||
lastSlash = i;
|
||||
dots = 0;
|
||||
continue;
|
||||
} else if (res.length !== 0) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
lastSlash = i;
|
||||
dots = 0;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (allowAboveRoot) {
|
||||
res += res.length > 0 ? "/.." : "..";
|
||||
lastSegmentLength = 2;
|
||||
}
|
||||
} else {
|
||||
if (res.length > 0) {
|
||||
res += `/${path2.slice(lastSlash + 1, i)}`;
|
||||
} else {
|
||||
res = path2.slice(lastSlash + 1, i);
|
||||
}
|
||||
lastSegmentLength = i - lastSlash - 1;
|
||||
}
|
||||
lastSlash = i;
|
||||
dots = 0;
|
||||
} else if (char === "." && dots !== -1) {
|
||||
++dots;
|
||||
} else {
|
||||
dots = -1;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
const isAbsolute = function(p) {
|
||||
return _IS_ABSOLUTE_RE.test(p);
|
||||
};
|
||||
const toNamespacedPath = function(p) {
|
||||
return normalizeWindowsPath(p);
|
||||
};
|
||||
const extname = function(p) {
|
||||
return path.posix.extname(normalizeWindowsPath(p));
|
||||
};
|
||||
const relative = function(from, to) {
|
||||
return path.posix.relative(normalizeWindowsPath(from), normalizeWindowsPath(to));
|
||||
};
|
||||
const dirname = function(p) {
|
||||
return path.posix.dirname(normalizeWindowsPath(p));
|
||||
};
|
||||
const format = function(p) {
|
||||
return normalizeWindowsPath(path.posix.format(p));
|
||||
};
|
||||
const basename = function(p, ext) {
|
||||
return path.posix.basename(normalizeWindowsPath(p), ext);
|
||||
};
|
||||
const parse = function(p) {
|
||||
return path.posix.parse(normalizeWindowsPath(p));
|
||||
};
|
||||
|
||||
const _path = /*#__PURE__*/Object.freeze({
|
||||
__proto__: null,
|
||||
sep: sep,
|
||||
delimiter: delimiter,
|
||||
normalize: normalize,
|
||||
join: join,
|
||||
resolve: resolve,
|
||||
normalizeString: normalizeString,
|
||||
isAbsolute: isAbsolute,
|
||||
toNamespacedPath: toNamespacedPath,
|
||||
extname: extname,
|
||||
relative: relative,
|
||||
dirname: dirname,
|
||||
format: format,
|
||||
basename: basename,
|
||||
parse: parse
|
||||
});
|
||||
|
||||
({
|
||||
..._path
|
||||
});
|
||||
|
||||
var _a;
|
||||
const isNode = typeof process < "u" && typeof process.stdout < "u" && !((_a = process.versions) == null ? void 0 : _a.deno) && !globalThis.window;
|
||||
const isBrowser = typeof window !== "undefined";
|
||||
|
||||
const rootDir = isNode ? resolve(url.fileURLToPath(import.meta.url), "../../") : import.meta.url;
|
||||
const distDir = isNode ? resolve(url.fileURLToPath(import.meta.url), "../../dist") : import.meta.url;
|
||||
const defaultPort = 51204;
|
||||
const EXIT_CODE_RESTART = 43;
|
||||
const API_PATH = "/__vitest_api__";
|
||||
const configFiles = [
|
||||
"vitest.config.ts",
|
||||
"vitest.config.mts",
|
||||
"vitest.config.cts",
|
||||
"vitest.config.js",
|
||||
"vitest.config.mjs",
|
||||
"vitest.config.cjs",
|
||||
"vite.config.ts",
|
||||
"vite.config.mts",
|
||||
"vite.config.cts",
|
||||
"vite.config.js",
|
||||
"vite.config.mjs",
|
||||
"vite.config.cjs"
|
||||
];
|
||||
const globalApis = [
|
||||
"suite",
|
||||
"test",
|
||||
"describe",
|
||||
"it",
|
||||
"chai",
|
||||
"expect",
|
||||
"assert",
|
||||
"expectTypeOf",
|
||||
"assertType",
|
||||
"vitest",
|
||||
"vi",
|
||||
"beforeAll",
|
||||
"afterAll",
|
||||
"beforeEach",
|
||||
"afterEach"
|
||||
];
|
||||
|
||||
export { API_PATH as A, EXIT_CODE_RESTART as E, isBrowser as a, resolve as b, basename as c, dirname as d, distDir as e, rootDir as f, isAbsolute as g, configFiles as h, isNode as i, join as j, defaultPort as k, extname as l, globalApis as m, normalize as n, picocolors as p, relative as r, toNamespacedPath as t };
|
||||
92
node_modules/vitest/dist/chunk-utils-source-map.29ff1088.js
generated
vendored
Normal file
92
node_modules/vitest/dist/chunk-utils-source-map.29ff1088.js
generated
vendored
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
import { s as slash, j as notNullish } from './chunk-typecheck-constants.ed987901.js';
|
||||
|
||||
const lineSplitRE = /\r?\n/;
|
||||
const stackIgnorePatterns = [
|
||||
"node:internal",
|
||||
"/vitest/dist/",
|
||||
"/vite-node/dist",
|
||||
"/vite-node/src",
|
||||
"/vitest/src/",
|
||||
"/node_modules/chai/",
|
||||
"/node_modules/tinypool/",
|
||||
"/node_modules/tinyspy/"
|
||||
];
|
||||
function extractLocation(urlLike) {
|
||||
if (!urlLike.includes(":"))
|
||||
return [urlLike];
|
||||
const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/;
|
||||
const parts = regExp.exec(urlLike.replace(/[()]/g, ""));
|
||||
if (!parts)
|
||||
return [urlLike];
|
||||
return [parts[1], parts[2] || void 0, parts[3] || void 0];
|
||||
}
|
||||
function parseStacktrace(e, full = false) {
|
||||
if (!e)
|
||||
return [];
|
||||
if (e.stacks)
|
||||
return e.stacks;
|
||||
const stackStr = e.stack || e.stackStr || "";
|
||||
const stackFrames = stackStr.split("\n").map((raw) => {
|
||||
let line = raw.trim();
|
||||
if (line.includes("(eval "))
|
||||
line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, "");
|
||||
let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, "");
|
||||
const location = sanitizedLine.match(/ (\(.+\)$)/);
|
||||
sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine;
|
||||
const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine);
|
||||
let method = location && sanitizedLine || "";
|
||||
let file = url && ["eval", "<anonymous>"].includes(url) ? void 0 : url;
|
||||
if (!file || !lineNumber || !columnNumber)
|
||||
return null;
|
||||
if (method.startsWith("async "))
|
||||
method = method.slice(6);
|
||||
if (file.startsWith("file://"))
|
||||
file = file.slice(7);
|
||||
if (!full && stackIgnorePatterns.some((p) => file && file.includes(p)))
|
||||
return null;
|
||||
return {
|
||||
method,
|
||||
file: slash(file),
|
||||
line: parseInt(lineNumber),
|
||||
column: parseInt(columnNumber)
|
||||
};
|
||||
}).filter(notNullish);
|
||||
e.stacks = stackFrames;
|
||||
return stackFrames;
|
||||
}
|
||||
function posToNumber(source, pos) {
|
||||
if (typeof pos === "number")
|
||||
return pos;
|
||||
const lines = source.split(lineSplitRE);
|
||||
const { line, column } = pos;
|
||||
let start = 0;
|
||||
if (line > lines.length)
|
||||
return source.length;
|
||||
for (let i = 0; i < line - 1; i++)
|
||||
start += lines[i].length + 1;
|
||||
return start + column;
|
||||
}
|
||||
function numberToPos(source, offset) {
|
||||
if (typeof offset !== "number")
|
||||
return offset;
|
||||
if (offset > source.length) {
|
||||
throw new Error(
|
||||
`offset is longer than source length! offset ${offset} > length ${source.length}`
|
||||
);
|
||||
}
|
||||
const lines = source.split(lineSplitRE);
|
||||
let counted = 0;
|
||||
let line = 0;
|
||||
let column = 0;
|
||||
for (; line < lines.length; line++) {
|
||||
const lineLength = lines[line].length + 1;
|
||||
if (counted + lineLength >= offset) {
|
||||
column = offset - counted + 1;
|
||||
break;
|
||||
}
|
||||
counted += lineLength;
|
||||
}
|
||||
return { line: line + 1, column };
|
||||
}
|
||||
|
||||
export { posToNumber as a, lineSplitRE as l, numberToPos as n, parseStacktrace as p };
|
||||
4038
node_modules/vitest/dist/chunk-utils-timers.793fd179.js
generated
vendored
Normal file
4038
node_modules/vitest/dist/chunk-utils-timers.793fd179.js
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
11581
node_modules/vitest/dist/chunk-vite-node-externalize.b9495318.js
generated
vendored
Normal file
11581
node_modules/vitest/dist/chunk-vite-node-externalize.b9495318.js
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
446
node_modules/vitest/dist/chunk-vite-node-source-map.b4ea5792.js
generated
vendored
Normal file
446
node_modules/vitest/dist/chunk-vite-node-source-map.b4ea5792.js
generated
vendored
Normal file
|
|
@ -0,0 +1,446 @@
|
|||
import { createRequire } from 'module';
|
||||
import { pathToFileURL, fileURLToPath } from 'url';
|
||||
import vm from 'vm';
|
||||
import { b as resolve, d as dirname, g as isAbsolute, l as extname } from './chunk-utils-env.03f840f2.js';
|
||||
import { s as slash, c as normalizeRequestId, b as toFilePath, d as cleanUrl, e as isPrimitive, i as isNodeBuiltin, n as normalizeModuleId } from './chunk-vite-node-utils.0e4a6a88.js';
|
||||
import createDebug from 'debug';
|
||||
import './vendor-source-map-support.1ce17397.js';
|
||||
|
||||
let SOURCEMAPPING_URL = "sourceMa";
|
||||
SOURCEMAPPING_URL += "ppingURL";
|
||||
const VITE_NODE_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-node";
|
||||
const VITE_NODE_SOURCEMAPPING_URL = `${SOURCEMAPPING_URL}=data:application/json;charset=utf-8`;
|
||||
const VITE_NODE_SOURCEMAPPING_REGEXP = new RegExp(`//# ${VITE_NODE_SOURCEMAPPING_URL};base64,(.+)`);
|
||||
async function withInlineSourcemap(result) {
|
||||
const map = result.map;
|
||||
let code = result.code;
|
||||
if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE))
|
||||
return result;
|
||||
const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,(.+)`, "g");
|
||||
while (OTHER_SOURCE_MAP_REGEXP.test(code))
|
||||
code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
|
||||
const sourceMap = Buffer.from(JSON.stringify(map), "utf-8").toString("base64");
|
||||
result.code = `${code.trimEnd()}
|
||||
|
||||
${VITE_NODE_SOURCEMAPPING_SOURCE}
|
||||
//# ${VITE_NODE_SOURCEMAPPING_URL};base64,${sourceMap}
|
||||
`;
|
||||
return result;
|
||||
}
|
||||
function extractSourceMap(code) {
|
||||
var _a;
|
||||
const mapString = (_a = code.match(VITE_NODE_SOURCEMAPPING_REGEXP)) == null ? void 0 : _a[1];
|
||||
if (mapString)
|
||||
return JSON.parse(Buffer.from(mapString, "base64").toString("utf-8"));
|
||||
return null;
|
||||
}
|
||||
|
||||
const debugExecute = createDebug("vite-node:client:execute");
|
||||
const debugNative = createDebug("vite-node:client:native");
|
||||
const DEFAULT_REQUEST_STUBS = {
|
||||
"/@vite/client": {
|
||||
injectQuery: (id) => id,
|
||||
createHotContext() {
|
||||
return {
|
||||
accept: () => {
|
||||
},
|
||||
prune: () => {
|
||||
},
|
||||
dispose: () => {
|
||||
},
|
||||
decline: () => {
|
||||
},
|
||||
invalidate: () => {
|
||||
},
|
||||
on: () => {
|
||||
}
|
||||
};
|
||||
},
|
||||
updateStyle(id, css) {
|
||||
if (typeof document === "undefined")
|
||||
return;
|
||||
const element = document.getElementById(id);
|
||||
if (element)
|
||||
element.remove();
|
||||
const head = document.querySelector("head");
|
||||
const style = document.createElement("style");
|
||||
style.setAttribute("type", "text/css");
|
||||
style.id = id;
|
||||
style.innerHTML = css;
|
||||
head == null ? void 0 : head.appendChild(style);
|
||||
}
|
||||
}
|
||||
};
|
||||
class ModuleCacheMap extends Map {
|
||||
normalizePath(fsPath) {
|
||||
return normalizeModuleId(fsPath);
|
||||
}
|
||||
update(fsPath, mod) {
|
||||
fsPath = this.normalizePath(fsPath);
|
||||
if (!super.has(fsPath))
|
||||
super.set(fsPath, mod);
|
||||
else
|
||||
Object.assign(super.get(fsPath), mod);
|
||||
return this;
|
||||
}
|
||||
set(fsPath, mod) {
|
||||
fsPath = this.normalizePath(fsPath);
|
||||
return super.set(fsPath, mod);
|
||||
}
|
||||
get(fsPath) {
|
||||
fsPath = this.normalizePath(fsPath);
|
||||
if (!super.has(fsPath))
|
||||
super.set(fsPath, {});
|
||||
return super.get(fsPath);
|
||||
}
|
||||
delete(fsPath) {
|
||||
fsPath = this.normalizePath(fsPath);
|
||||
return super.delete(fsPath);
|
||||
}
|
||||
invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
|
||||
for (const _id of ids) {
|
||||
const id = this.normalizePath(_id);
|
||||
if (invalidated.has(id))
|
||||
continue;
|
||||
invalidated.add(id);
|
||||
const mod = super.get(id);
|
||||
if (mod == null ? void 0 : mod.importers)
|
||||
this.invalidateDepTree(mod.importers, invalidated);
|
||||
super.delete(id);
|
||||
}
|
||||
return invalidated;
|
||||
}
|
||||
invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
|
||||
for (const _id of ids) {
|
||||
const id = this.normalizePath(_id);
|
||||
if (invalidated.has(id))
|
||||
continue;
|
||||
invalidated.add(id);
|
||||
const subIds = Array.from(super.entries()).filter(([, mod]) => {
|
||||
var _a;
|
||||
return (_a = mod.importers) == null ? void 0 : _a.has(id);
|
||||
}).map(([key]) => key);
|
||||
subIds.length && this.invalidateSubDepTree(subIds, invalidated);
|
||||
super.delete(id);
|
||||
}
|
||||
return invalidated;
|
||||
}
|
||||
getSourceMap(id) {
|
||||
const cache = this.get(id);
|
||||
if (cache.map)
|
||||
return cache.map;
|
||||
const map = cache.code && extractSourceMap(cache.code);
|
||||
if (map) {
|
||||
cache.map = map;
|
||||
return map;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
class ViteNodeRunner {
|
||||
constructor(options) {
|
||||
this.options = options;
|
||||
this.root = options.root ?? process.cwd();
|
||||
this.moduleCache = options.moduleCache ?? new ModuleCacheMap();
|
||||
this.debug = options.debug ?? (typeof process !== "undefined" ? !!process.env.VITE_NODE_DEBUG_RUNNER : false);
|
||||
}
|
||||
async executeFile(file) {
|
||||
return await this.cachedRequest(`/@fs/${slash(resolve(file))}`, []);
|
||||
}
|
||||
async executeId(id) {
|
||||
return await this.cachedRequest(id, []);
|
||||
}
|
||||
getSourceMap(id) {
|
||||
return this.moduleCache.getSourceMap(id);
|
||||
}
|
||||
async cachedRequest(rawId, callstack) {
|
||||
const id = normalizeRequestId(rawId, this.options.base);
|
||||
const fsPath = toFilePath(id, this.root);
|
||||
const mod = this.moduleCache.get(fsPath);
|
||||
const importee = callstack[callstack.length - 1];
|
||||
if (!mod.importers)
|
||||
mod.importers = /* @__PURE__ */ new Set();
|
||||
if (importee)
|
||||
mod.importers.add(importee);
|
||||
if (callstack.includes(fsPath) && mod.exports)
|
||||
return mod.exports;
|
||||
if (mod.promise)
|
||||
return mod.promise;
|
||||
const promise = this.directRequest(id, fsPath, callstack);
|
||||
Object.assign(mod, { promise, evaluated: false });
|
||||
try {
|
||||
return await promise;
|
||||
} finally {
|
||||
mod.evaluated = true;
|
||||
}
|
||||
}
|
||||
async directRequest(id, fsPath, _callstack) {
|
||||
const callstack = [..._callstack, fsPath];
|
||||
let mod = this.moduleCache.get(fsPath);
|
||||
const request = async (dep2) => {
|
||||
var _a;
|
||||
const depFsPath = toFilePath(normalizeRequestId(dep2, this.options.base), this.root);
|
||||
const getStack = () => {
|
||||
return `stack:
|
||||
${[...callstack, depFsPath].reverse().map((p) => `- ${p}`).join("\n")}`;
|
||||
};
|
||||
let debugTimer;
|
||||
if (this.debug)
|
||||
debugTimer = setTimeout(() => console.warn(() => `module ${depFsPath} takes over 2s to load.
|
||||
${getStack()}`), 2e3);
|
||||
try {
|
||||
if (callstack.includes(depFsPath)) {
|
||||
const depExports = (_a = this.moduleCache.get(depFsPath)) == null ? void 0 : _a.exports;
|
||||
if (depExports)
|
||||
return depExports;
|
||||
throw new Error(`[vite-node] Failed to resolve circular dependency, ${getStack()}`);
|
||||
}
|
||||
return await this.cachedRequest(dep2, callstack);
|
||||
} finally {
|
||||
if (debugTimer)
|
||||
clearTimeout(debugTimer);
|
||||
}
|
||||
};
|
||||
Object.defineProperty(request, "callstack", { get: () => callstack });
|
||||
const resolveId = async (dep2, callstackPosition = 1) => {
|
||||
if (this.options.resolveId && this.shouldResolveId(dep2)) {
|
||||
let importer = callstack[callstack.length - callstackPosition];
|
||||
if (importer && !dep2.startsWith("."))
|
||||
importer = void 0;
|
||||
if (importer && importer.startsWith("mock:"))
|
||||
importer = importer.slice(5);
|
||||
const resolved = await this.options.resolveId(normalizeRequestId(dep2), importer);
|
||||
return [dep2, resolved == null ? void 0 : resolved.id];
|
||||
}
|
||||
return [dep2, void 0];
|
||||
};
|
||||
const [dep, resolvedId] = await resolveId(id, 2);
|
||||
const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS;
|
||||
if (id in requestStubs)
|
||||
return requestStubs[id];
|
||||
let { code: transformed, externalize } = await this.options.fetchModule(resolvedId || dep);
|
||||
if (resolvedId && !fsPath.includes("?") && fsPath !== resolvedId) {
|
||||
if (this.moduleCache.has(resolvedId)) {
|
||||
mod = this.moduleCache.get(resolvedId);
|
||||
this.moduleCache.set(fsPath, mod);
|
||||
if (mod.promise)
|
||||
return mod.promise;
|
||||
if (mod.exports)
|
||||
return mod.exports;
|
||||
} else {
|
||||
this.moduleCache.set(resolvedId, mod);
|
||||
}
|
||||
}
|
||||
if (externalize) {
|
||||
debugNative(externalize);
|
||||
const exports2 = await this.interopedImport(externalize);
|
||||
mod.exports = exports2;
|
||||
return exports2;
|
||||
}
|
||||
if (transformed == null)
|
||||
throw new Error(`[vite-node] Failed to load ${id}`);
|
||||
const file = cleanUrl(resolvedId || fsPath);
|
||||
const url = pathToFileURL(file).href;
|
||||
const meta = { url };
|
||||
const exports = /* @__PURE__ */ Object.create(null);
|
||||
Object.defineProperty(exports, Symbol.toStringTag, {
|
||||
value: "Module",
|
||||
enumerable: false,
|
||||
configurable: false
|
||||
});
|
||||
const cjsExports = new Proxy(exports, {
|
||||
set(_, p, value) {
|
||||
if (!Reflect.has(exports, "default"))
|
||||
exports.default = {};
|
||||
if (isPrimitive(exports.default)) {
|
||||
defineExport(exports, p, () => void 0);
|
||||
return true;
|
||||
}
|
||||
exports.default[p] = value;
|
||||
if (p !== "default")
|
||||
defineExport(exports, p, () => value);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
Object.assign(mod, { code: transformed, exports });
|
||||
const __filename = fileURLToPath(url);
|
||||
const moduleProxy = {
|
||||
set exports(value) {
|
||||
exportAll(cjsExports, value);
|
||||
exports.default = value;
|
||||
},
|
||||
get exports() {
|
||||
return cjsExports;
|
||||
}
|
||||
};
|
||||
let hotContext;
|
||||
if (this.options.createHotContext) {
|
||||
Object.defineProperty(meta, "hot", {
|
||||
enumerable: true,
|
||||
get: () => {
|
||||
var _a, _b;
|
||||
hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, `/@fs/${fsPath}`));
|
||||
return hotContext;
|
||||
}
|
||||
});
|
||||
}
|
||||
const context = this.prepareContext({
|
||||
__vite_ssr_import__: request,
|
||||
__vite_ssr_dynamic_import__: request,
|
||||
__vite_ssr_exports__: exports,
|
||||
__vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
|
||||
__vite_ssr_import_meta__: meta,
|
||||
__vitest_resolve_id__: resolveId,
|
||||
require: createRequire(url),
|
||||
exports: cjsExports,
|
||||
module: moduleProxy,
|
||||
__filename,
|
||||
__dirname: dirname(__filename)
|
||||
});
|
||||
debugExecute(__filename);
|
||||
if (transformed[0] === "#")
|
||||
transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length));
|
||||
const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
|
||||
const code = `${codeDefinition}${transformed}
|
||||
}}`;
|
||||
const fn = vm.runInThisContext(code, {
|
||||
filename: __filename,
|
||||
lineOffset: 0,
|
||||
columnOffset: -codeDefinition.length
|
||||
});
|
||||
await fn(...Object.values(context));
|
||||
return exports;
|
||||
}
|
||||
prepareContext(context) {
|
||||
return context;
|
||||
}
|
||||
shouldResolveId(dep) {
|
||||
if (isNodeBuiltin(dep) || dep in (this.options.requestStubs || DEFAULT_REQUEST_STUBS) || dep.startsWith("/@vite"))
|
||||
return false;
|
||||
return !isAbsolute(dep) || !extname(dep);
|
||||
}
|
||||
shouldInterop(path, mod) {
|
||||
if (this.options.interopDefault === false)
|
||||
return false;
|
||||
return !path.endsWith(".mjs") && "default" in mod;
|
||||
}
|
||||
async interopedImport(path) {
|
||||
const mod = await import(path);
|
||||
if (this.shouldInterop(path, mod)) {
|
||||
const tryDefault = this.hasNestedDefault(mod);
|
||||
return new Proxy(mod, {
|
||||
get: proxyMethod("get", tryDefault),
|
||||
set: proxyMethod("set", tryDefault),
|
||||
has: proxyMethod("has", tryDefault),
|
||||
deleteProperty: proxyMethod("deleteProperty", tryDefault)
|
||||
});
|
||||
}
|
||||
return mod;
|
||||
}
|
||||
hasNestedDefault(target) {
|
||||
return "__esModule" in target && target.__esModule && "default" in target.default;
|
||||
}
|
||||
}
|
||||
function proxyMethod(name, tryDefault) {
|
||||
return function(target, key, ...args) {
|
||||
const result = Reflect[name](target, key, ...args);
|
||||
if (isPrimitive(target.default))
|
||||
return result;
|
||||
if (tryDefault && key === "default" || typeof result === "undefined")
|
||||
return Reflect[name](target.default, key, ...args);
|
||||
return result;
|
||||
};
|
||||
}
|
||||
function defineExport(exports, key, value) {
|
||||
Object.defineProperty(exports, key, {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
get: value
|
||||
});
|
||||
}
|
||||
function exportAll(exports, sourceModule) {
|
||||
if (exports === sourceModule)
|
||||
return;
|
||||
if (isPrimitive(sourceModule) || Array.isArray(sourceModule))
|
||||
return;
|
||||
for (const key in sourceModule) {
|
||||
if (key !== "default") {
|
||||
try {
|
||||
defineExport(exports, key, () => sourceModule[key]);
|
||||
} catch (_err) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT = 6e4;
|
||||
function createBirpc(functions, options) {
|
||||
const {
|
||||
post,
|
||||
on,
|
||||
eventNames = [],
|
||||
serialize = (i) => i,
|
||||
deserialize = (i) => i,
|
||||
timeout = DEFAULT_TIMEOUT
|
||||
} = options;
|
||||
const rpcPromiseMap = /* @__PURE__ */ new Map();
|
||||
const rpc = new Proxy({}, {
|
||||
get(_, method) {
|
||||
const sendEvent = (...args) => {
|
||||
post(serialize({ m: method, a: args, t: "q" }));
|
||||
};
|
||||
if (eventNames.includes(method)) {
|
||||
sendEvent.asEvent = sendEvent;
|
||||
return sendEvent;
|
||||
}
|
||||
const sendCall = (...args) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = nanoid();
|
||||
rpcPromiseMap.set(id, { resolve, reject });
|
||||
post(serialize({ m: method, a: args, i: id, t: "q" }));
|
||||
if (timeout >= 0) {
|
||||
setTimeout(() => {
|
||||
reject(new Error(`[birpc] timeout on calling "${method}"`));
|
||||
rpcPromiseMap.delete(id);
|
||||
}, timeout);
|
||||
}
|
||||
});
|
||||
};
|
||||
sendCall.asEvent = sendEvent;
|
||||
return sendCall;
|
||||
}
|
||||
});
|
||||
on(async (data, ...extra) => {
|
||||
const msg = deserialize(data);
|
||||
if (msg.t === "q") {
|
||||
const { m: method, a: args } = msg;
|
||||
let result, error;
|
||||
try {
|
||||
result = await functions[method].apply(rpc, args);
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
if (msg.i)
|
||||
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 (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[Math.random() * 64 | 0];
|
||||
return id;
|
||||
}
|
||||
|
||||
export { ModuleCacheMap as M, ViteNodeRunner as V, createBirpc as c, withInlineSourcemap as w };
|
||||
1385
node_modules/vitest/dist/chunk-vite-node-utils.0e4a6a88.js
generated
vendored
Normal file
1385
node_modules/vitest/dist/chunk-vite-node-utils.0e4a6a88.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
133
node_modules/vitest/dist/cli-wrapper.js
generated
vendored
Normal file
133
node_modules/vitest/dist/cli-wrapper.js
generated
vendored
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
import { fileURLToPath } from 'url';
|
||||
import { p as picocolors, E as EXIT_CODE_RESTART } from './chunk-utils-env.03f840f2.js';
|
||||
import { e as execa } from './vendor-index.737c3cff.js';
|
||||
import 'tty';
|
||||
import 'path';
|
||||
import 'buffer';
|
||||
import 'child_process';
|
||||
import 'process';
|
||||
import './vendor-index.e1d4cf84.js';
|
||||
import './vendor-_commonjsHelpers.addc3445.js';
|
||||
import 'fs';
|
||||
import 'assert';
|
||||
import 'events';
|
||||
import 'stream';
|
||||
import 'util';
|
||||
import 'os';
|
||||
|
||||
const ENTRY = new URL("./cli.js", import.meta.url);
|
||||
const NODE_ARGS = [
|
||||
"--inspect",
|
||||
"--inspect-brk",
|
||||
"--trace-deprecation",
|
||||
"--experimental-wasm-threads",
|
||||
"--wasm-atomics-on-non-shared-memory"
|
||||
];
|
||||
const SegfaultErrors = [
|
||||
{
|
||||
trigger: "Check failed: result.second.",
|
||||
url: "https://github.com/nodejs/node/issues/43617"
|
||||
},
|
||||
{
|
||||
trigger: "FATAL ERROR: v8::FromJust Maybe value is Nothing.",
|
||||
url: "https://github.com/vitest-dev/vitest/issues/1191"
|
||||
},
|
||||
{
|
||||
trigger: "FATAL ERROR: v8::ToLocalChecked Empty MaybeLocal.",
|
||||
url: "https://github.com/nodejs/node/issues/42407"
|
||||
}
|
||||
];
|
||||
main();
|
||||
async function main() {
|
||||
var _a;
|
||||
let retries = 0;
|
||||
const args = process.argv.slice(2);
|
||||
if (process.env.VITEST_SEGFAULT_RETRY) {
|
||||
retries = +process.env.VITEST_SEGFAULT_RETRY;
|
||||
} else {
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i].startsWith("--segfault-retry=")) {
|
||||
retries = +args[i].split("=")[1];
|
||||
break;
|
||||
} else if (args[i] === "--segfault-retry" && ((_a = args[i + 1]) == null ? void 0 : _a.match(/^\d+$/))) {
|
||||
retries = +args[i + 1];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (retries <= 0) {
|
||||
await import('./cli.js');
|
||||
return;
|
||||
}
|
||||
const nodeArgs = [];
|
||||
const vitestArgs = [];
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
let matched = false;
|
||||
for (const nodeArg of NODE_ARGS) {
|
||||
if (args[i] === nodeArg || args[i].startsWith(`${nodeArg}=`)) {
|
||||
matched = true;
|
||||
nodeArgs.push(args[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!matched)
|
||||
vitestArgs.push(args[i]);
|
||||
}
|
||||
retries = Math.max(1, retries || 1);
|
||||
for (let i = 1; i <= retries; i++) {
|
||||
const result = await start(nodeArgs, vitestArgs);
|
||||
if (result === "restart") {
|
||||
i -= 1;
|
||||
continue;
|
||||
}
|
||||
if (i === 1 && retries === 1) {
|
||||
console.log(picocolors.exports.yellow(`It seems to be an upstream bug of Node.js. To improve the test stability,
|
||||
you could pass ${picocolors.exports.bold(picocolors.exports.green("--segfault-retry=3"))} or set env ${picocolors.exports.bold(picocolors.exports.green("VITEST_SEGFAULT_RETRY=3"))} to
|
||||
have Vitest auto retries on flaky segfaults.
|
||||
`));
|
||||
}
|
||||
if (i !== retries)
|
||||
console.log(`${picocolors.exports.inverse(picocolors.exports.bold(picocolors.exports.magenta(" Retrying ")))} vitest ${args.join(" ")} ${picocolors.exports.gray(`(${i + 1} of ${retries})`)}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
async function start(preArgs, postArgs) {
|
||||
var _a;
|
||||
const child = execa(
|
||||
"node",
|
||||
[
|
||||
...preArgs,
|
||||
fileURLToPath(ENTRY),
|
||||
...postArgs
|
||||
],
|
||||
{
|
||||
reject: false,
|
||||
stderr: "pipe",
|
||||
stdout: "inherit",
|
||||
stdin: "inherit",
|
||||
env: {
|
||||
...process.env,
|
||||
VITEST_CLI_WRAPPER: "true"
|
||||
}
|
||||
}
|
||||
);
|
||||
(_a = child.stderr) == null ? void 0 : _a.pipe(process.stderr);
|
||||
const { stderr = "" } = await child;
|
||||
if (child.exitCode === EXIT_CODE_RESTART)
|
||||
return "restart";
|
||||
for (const error of SegfaultErrors) {
|
||||
if (stderr.includes(error.trigger)) {
|
||||
if (process.env.GITHUB_ACTIONS)
|
||||
console.log(`::warning:: Segmentfault Error Detected: ${error.trigger}
|
||||
Refer to ${error.url}`);
|
||||
const RED_BLOCK = picocolors.exports.inverse(picocolors.exports.red(" "));
|
||||
console.log(`
|
||||
${picocolors.exports.inverse(picocolors.exports.bold(picocolors.exports.red(" Segmentfault Error Detected ")))}
|
||||
${RED_BLOCK} ${picocolors.exports.red(error.trigger)}
|
||||
${RED_BLOCK} ${picocolors.exports.red(`Refer to ${error.url}`)}
|
||||
`);
|
||||
return "error";
|
||||
}
|
||||
}
|
||||
process.exit(child.exitCode);
|
||||
}
|
||||
712
node_modules/vitest/dist/cli.js
generated
vendored
Normal file
712
node_modules/vitest/dist/cli.js
generated
vendored
Normal file
|
|
@ -0,0 +1,712 @@
|
|||
import { p as picocolors, n as normalize } from './chunk-utils-env.03f840f2.js';
|
||||
import { EventEmitter } from 'events';
|
||||
import { v as version, s as startVitest, d as divider } from './chunk-vite-node-externalize.b9495318.js';
|
||||
import 'tty';
|
||||
import 'url';
|
||||
import 'path';
|
||||
import './chunk-integrations-coverage.befed097.js';
|
||||
import 'local-pkg';
|
||||
import './chunk-env-node.67948209.js';
|
||||
import 'console';
|
||||
import './chunk-typecheck-constants.ed987901.js';
|
||||
import 'vite';
|
||||
import 'process';
|
||||
import 'fs';
|
||||
import 'os';
|
||||
import 'util';
|
||||
import 'stream';
|
||||
import './vendor-_commonjsHelpers.addc3445.js';
|
||||
import './chunk-vite-node-source-map.b4ea5792.js';
|
||||
import 'module';
|
||||
import 'vm';
|
||||
import './chunk-vite-node-utils.0e4a6a88.js';
|
||||
import 'acorn';
|
||||
import 'assert';
|
||||
import 'debug';
|
||||
import './vendor-source-map-support.1ce17397.js';
|
||||
import 'source-map';
|
||||
import 'perf_hooks';
|
||||
import 'fs/promises';
|
||||
import './vendor-index.737c3cff.js';
|
||||
import 'buffer';
|
||||
import 'child_process';
|
||||
import './vendor-index.e1d4cf84.js';
|
||||
import 'acorn-walk';
|
||||
import 'worker_threads';
|
||||
import 'tinypool';
|
||||
import './chunk-utils-timers.793fd179.js';
|
||||
import './chunk-utils-source-map.29ff1088.js';
|
||||
import 'crypto';
|
||||
import './vendor-index.9c919048.js';
|
||||
import './chunk-magic-string.3a794426.js';
|
||||
import 'strip-literal';
|
||||
import 'readline';
|
||||
import './vendor-index.9f20a9be.js';
|
||||
|
||||
function toArr(any) {
|
||||
return any == null ? [] : Array.isArray(any) ? any : [any];
|
||||
}
|
||||
|
||||
function toVal(out, key, val, opts) {
|
||||
var x, old=out[key], nxt=(
|
||||
!!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val))
|
||||
: typeof val === 'boolean' ? val
|
||||
: !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val))
|
||||
: (x = +val,x * 0 === 0) ? x : val
|
||||
);
|
||||
out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]);
|
||||
}
|
||||
|
||||
function mri2 (args, opts) {
|
||||
args = args || [];
|
||||
opts = opts || {};
|
||||
|
||||
var k, arr, arg, name, val, out={ _:[] };
|
||||
var i=0, j=0, idx=0, len=args.length;
|
||||
|
||||
const alibi = opts.alias !== void 0;
|
||||
const strict = opts.unknown !== void 0;
|
||||
const defaults = opts.default !== void 0;
|
||||
|
||||
opts.alias = opts.alias || {};
|
||||
opts.string = toArr(opts.string);
|
||||
opts.boolean = toArr(opts.boolean);
|
||||
|
||||
if (alibi) {
|
||||
for (k in opts.alias) {
|
||||
arr = opts.alias[k] = toArr(opts.alias[k]);
|
||||
for (i=0; i < arr.length; i++) {
|
||||
(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (i=opts.boolean.length; i-- > 0;) {
|
||||
arr = opts.alias[opts.boolean[i]] || [];
|
||||
for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]);
|
||||
}
|
||||
|
||||
for (i=opts.string.length; i-- > 0;) {
|
||||
arr = opts.alias[opts.string[i]] || [];
|
||||
for (j=arr.length; j-- > 0;) opts.string.push(arr[j]);
|
||||
}
|
||||
|
||||
if (defaults) {
|
||||
for (k in opts.default) {
|
||||
name = typeof opts.default[k];
|
||||
arr = opts.alias[k] = opts.alias[k] || [];
|
||||
if (opts[name] !== void 0) {
|
||||
opts[name].push(k);
|
||||
for (i=0; i < arr.length; i++) {
|
||||
opts[name].push(arr[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const keys = strict ? Object.keys(opts.alias) : [];
|
||||
|
||||
for (i=0; i < len; i++) {
|
||||
arg = args[i];
|
||||
|
||||
if (arg === '--') {
|
||||
out._ = out._.concat(args.slice(++i));
|
||||
break;
|
||||
}
|
||||
|
||||
for (j=0; j < arg.length; j++) {
|
||||
if (arg.charCodeAt(j) !== 45) break; // "-"
|
||||
}
|
||||
|
||||
if (j === 0) {
|
||||
out._.push(arg);
|
||||
} else if (arg.substring(j, j + 3) === 'no-') {
|
||||
name = arg.substring(j + 3);
|
||||
if (strict && !~keys.indexOf(name)) {
|
||||
return opts.unknown(arg);
|
||||
}
|
||||
out[name] = false;
|
||||
} else {
|
||||
for (idx=j+1; idx < arg.length; idx++) {
|
||||
if (arg.charCodeAt(idx) === 61) break; // "="
|
||||
}
|
||||
|
||||
name = arg.substring(j, idx);
|
||||
val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]);
|
||||
arr = (j === 2 ? [name] : name);
|
||||
|
||||
for (idx=0; idx < arr.length; idx++) {
|
||||
name = arr[idx];
|
||||
if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
|
||||
toVal(out, name, (idx + 1 < arr.length) || val, opts);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (defaults) {
|
||||
for (k in opts.default) {
|
||||
if (out[k] === void 0) {
|
||||
out[k] = opts.default[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (alibi) {
|
||||
for (k in out) {
|
||||
arr = opts.alias[k] || [];
|
||||
while (arr.length > 0) {
|
||||
out[arr.shift()] = out[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
const removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
|
||||
const findAllBrackets = (v) => {
|
||||
const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
|
||||
const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
|
||||
const res = [];
|
||||
const parse = (match) => {
|
||||
let variadic = false;
|
||||
let value = match[1];
|
||||
if (value.startsWith("...")) {
|
||||
value = value.slice(3);
|
||||
variadic = true;
|
||||
}
|
||||
return {
|
||||
required: match[0].startsWith("<"),
|
||||
value,
|
||||
variadic
|
||||
};
|
||||
};
|
||||
let angledMatch;
|
||||
while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
|
||||
res.push(parse(angledMatch));
|
||||
}
|
||||
let squareMatch;
|
||||
while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
|
||||
res.push(parse(squareMatch));
|
||||
}
|
||||
return res;
|
||||
};
|
||||
const getMriOptions = (options) => {
|
||||
const result = {alias: {}, boolean: []};
|
||||
for (const [index, option] of options.entries()) {
|
||||
if (option.names.length > 1) {
|
||||
result.alias[option.names[0]] = option.names.slice(1);
|
||||
}
|
||||
if (option.isBoolean) {
|
||||
if (option.negated) {
|
||||
const hasStringTypeOption = options.some((o, i) => {
|
||||
return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
|
||||
});
|
||||
if (!hasStringTypeOption) {
|
||||
result.boolean.push(option.names[0]);
|
||||
}
|
||||
} else {
|
||||
result.boolean.push(option.names[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
const findLongest = (arr) => {
|
||||
return arr.sort((a, b) => {
|
||||
return a.length > b.length ? -1 : 1;
|
||||
})[0];
|
||||
};
|
||||
const padRight = (str, length) => {
|
||||
return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
|
||||
};
|
||||
const camelcase = (input) => {
|
||||
return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
|
||||
return p1 + p2.toUpperCase();
|
||||
});
|
||||
};
|
||||
const setDotProp = (obj, keys, val) => {
|
||||
let i = 0;
|
||||
let length = keys.length;
|
||||
let t = obj;
|
||||
let x;
|
||||
for (; i < length; ++i) {
|
||||
x = t[keys[i]];
|
||||
t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
|
||||
}
|
||||
};
|
||||
const setByType = (obj, transforms) => {
|
||||
for (const key of Object.keys(transforms)) {
|
||||
const transform = transforms[key];
|
||||
if (transform.shouldTransform) {
|
||||
obj[key] = Array.prototype.concat.call([], obj[key]);
|
||||
if (typeof transform.transformFunction === "function") {
|
||||
obj[key] = obj[key].map(transform.transformFunction);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
const getFileName = (input) => {
|
||||
const m = /([^\\\/]+)$/.exec(input);
|
||||
return m ? m[1] : "";
|
||||
};
|
||||
const camelcaseOptionName = (name) => {
|
||||
return name.split(".").map((v, i) => {
|
||||
return i === 0 ? camelcase(v) : v;
|
||||
}).join(".");
|
||||
};
|
||||
class CACError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = this.constructor.name;
|
||||
if (typeof Error.captureStackTrace === "function") {
|
||||
Error.captureStackTrace(this, this.constructor);
|
||||
} else {
|
||||
this.stack = new Error(message).stack;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Option {
|
||||
constructor(rawName, description, config) {
|
||||
this.rawName = rawName;
|
||||
this.description = description;
|
||||
this.config = Object.assign({}, config);
|
||||
rawName = rawName.replace(/\.\*/g, "");
|
||||
this.negated = false;
|
||||
this.names = removeBrackets(rawName).split(",").map((v) => {
|
||||
let name = v.trim().replace(/^-{1,2}/, "");
|
||||
if (name.startsWith("no-")) {
|
||||
this.negated = true;
|
||||
name = name.replace(/^no-/, "");
|
||||
}
|
||||
return camelcaseOptionName(name);
|
||||
}).sort((a, b) => a.length > b.length ? 1 : -1);
|
||||
this.name = this.names[this.names.length - 1];
|
||||
if (this.negated && this.config.default == null) {
|
||||
this.config.default = true;
|
||||
}
|
||||
if (rawName.includes("<")) {
|
||||
this.required = true;
|
||||
} else if (rawName.includes("[")) {
|
||||
this.required = false;
|
||||
} else {
|
||||
this.isBoolean = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const processArgs = process.argv;
|
||||
const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
|
||||
|
||||
class Command {
|
||||
constructor(rawName, description, config = {}, cli) {
|
||||
this.rawName = rawName;
|
||||
this.description = description;
|
||||
this.config = config;
|
||||
this.cli = cli;
|
||||
this.options = [];
|
||||
this.aliasNames = [];
|
||||
this.name = removeBrackets(rawName);
|
||||
this.args = findAllBrackets(rawName);
|
||||
this.examples = [];
|
||||
}
|
||||
usage(text) {
|
||||
this.usageText = text;
|
||||
return this;
|
||||
}
|
||||
allowUnknownOptions() {
|
||||
this.config.allowUnknownOptions = true;
|
||||
return this;
|
||||
}
|
||||
ignoreOptionDefaultValue() {
|
||||
this.config.ignoreOptionDefaultValue = true;
|
||||
return this;
|
||||
}
|
||||
version(version, customFlags = "-v, --version") {
|
||||
this.versionNumber = version;
|
||||
this.option(customFlags, "Display version number");
|
||||
return this;
|
||||
}
|
||||
example(example) {
|
||||
this.examples.push(example);
|
||||
return this;
|
||||
}
|
||||
option(rawName, description, config) {
|
||||
const option = new Option(rawName, description, config);
|
||||
this.options.push(option);
|
||||
return this;
|
||||
}
|
||||
alias(name) {
|
||||
this.aliasNames.push(name);
|
||||
return this;
|
||||
}
|
||||
action(callback) {
|
||||
this.commandAction = callback;
|
||||
return this;
|
||||
}
|
||||
isMatched(name) {
|
||||
return this.name === name || this.aliasNames.includes(name);
|
||||
}
|
||||
get isDefaultCommand() {
|
||||
return this.name === "" || this.aliasNames.includes("!");
|
||||
}
|
||||
get isGlobalCommand() {
|
||||
return this instanceof GlobalCommand;
|
||||
}
|
||||
hasOption(name) {
|
||||
name = name.split(".")[0];
|
||||
return this.options.find((option) => {
|
||||
return option.names.includes(name);
|
||||
});
|
||||
}
|
||||
outputHelp() {
|
||||
const {name, commands} = this.cli;
|
||||
const {
|
||||
versionNumber,
|
||||
options: globalOptions,
|
||||
helpCallback
|
||||
} = this.cli.globalCommand;
|
||||
let sections = [
|
||||
{
|
||||
body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
|
||||
}
|
||||
];
|
||||
sections.push({
|
||||
title: "Usage",
|
||||
body: ` $ ${name} ${this.usageText || this.rawName}`
|
||||
});
|
||||
const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
|
||||
if (showCommands) {
|
||||
const longestCommandName = findLongest(commands.map((command) => command.rawName));
|
||||
sections.push({
|
||||
title: "Commands",
|
||||
body: commands.map((command) => {
|
||||
return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
|
||||
}).join("\n")
|
||||
});
|
||||
sections.push({
|
||||
title: `For more info, run any command with the \`--help\` flag`,
|
||||
body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
|
||||
});
|
||||
}
|
||||
let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
|
||||
if (!this.isGlobalCommand && !this.isDefaultCommand) {
|
||||
options = options.filter((option) => option.name !== "version");
|
||||
}
|
||||
if (options.length > 0) {
|
||||
const longestOptionName = findLongest(options.map((option) => option.rawName));
|
||||
sections.push({
|
||||
title: "Options",
|
||||
body: options.map((option) => {
|
||||
return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
|
||||
}).join("\n")
|
||||
});
|
||||
}
|
||||
if (this.examples.length > 0) {
|
||||
sections.push({
|
||||
title: "Examples",
|
||||
body: this.examples.map((example) => {
|
||||
if (typeof example === "function") {
|
||||
return example(name);
|
||||
}
|
||||
return example;
|
||||
}).join("\n")
|
||||
});
|
||||
}
|
||||
if (helpCallback) {
|
||||
sections = helpCallback(sections) || sections;
|
||||
}
|
||||
console.log(sections.map((section) => {
|
||||
return section.title ? `${section.title}:
|
||||
${section.body}` : section.body;
|
||||
}).join("\n\n"));
|
||||
}
|
||||
outputVersion() {
|
||||
const {name} = this.cli;
|
||||
const {versionNumber} = this.cli.globalCommand;
|
||||
if (versionNumber) {
|
||||
console.log(`${name}/${versionNumber} ${platformInfo}`);
|
||||
}
|
||||
}
|
||||
checkRequiredArgs() {
|
||||
const minimalArgsCount = this.args.filter((arg) => arg.required).length;
|
||||
if (this.cli.args.length < minimalArgsCount) {
|
||||
throw new CACError(`missing required args for command \`${this.rawName}\``);
|
||||
}
|
||||
}
|
||||
checkUnknownOptions() {
|
||||
const {options, globalCommand} = this.cli;
|
||||
if (!this.config.allowUnknownOptions) {
|
||||
for (const name of Object.keys(options)) {
|
||||
if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
|
||||
throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
checkOptionValue() {
|
||||
const {options: parsedOptions, globalCommand} = this.cli;
|
||||
const options = [...globalCommand.options, ...this.options];
|
||||
for (const option of options) {
|
||||
const value = parsedOptions[option.name.split(".")[0]];
|
||||
if (option.required) {
|
||||
const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
|
||||
if (value === true || value === false && !hasNegated) {
|
||||
throw new CACError(`option \`${option.rawName}\` value is missing`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
class GlobalCommand extends Command {
|
||||
constructor(cli) {
|
||||
super("@@global@@", "", {}, cli);
|
||||
}
|
||||
}
|
||||
|
||||
var __assign = Object.assign;
|
||||
class CAC extends EventEmitter {
|
||||
constructor(name = "") {
|
||||
super();
|
||||
this.name = name;
|
||||
this.commands = [];
|
||||
this.rawArgs = [];
|
||||
this.args = [];
|
||||
this.options = {};
|
||||
this.globalCommand = new GlobalCommand(this);
|
||||
this.globalCommand.usage("<command> [options]");
|
||||
}
|
||||
usage(text) {
|
||||
this.globalCommand.usage(text);
|
||||
return this;
|
||||
}
|
||||
command(rawName, description, config) {
|
||||
const command = new Command(rawName, description || "", config, this);
|
||||
command.globalCommand = this.globalCommand;
|
||||
this.commands.push(command);
|
||||
return command;
|
||||
}
|
||||
option(rawName, description, config) {
|
||||
this.globalCommand.option(rawName, description, config);
|
||||
return this;
|
||||
}
|
||||
help(callback) {
|
||||
this.globalCommand.option("-h, --help", "Display this message");
|
||||
this.globalCommand.helpCallback = callback;
|
||||
this.showHelpOnExit = true;
|
||||
return this;
|
||||
}
|
||||
version(version, customFlags = "-v, --version") {
|
||||
this.globalCommand.version(version, customFlags);
|
||||
this.showVersionOnExit = true;
|
||||
return this;
|
||||
}
|
||||
example(example) {
|
||||
this.globalCommand.example(example);
|
||||
return this;
|
||||
}
|
||||
outputHelp() {
|
||||
if (this.matchedCommand) {
|
||||
this.matchedCommand.outputHelp();
|
||||
} else {
|
||||
this.globalCommand.outputHelp();
|
||||
}
|
||||
}
|
||||
outputVersion() {
|
||||
this.globalCommand.outputVersion();
|
||||
}
|
||||
setParsedInfo({args, options}, matchedCommand, matchedCommandName) {
|
||||
this.args = args;
|
||||
this.options = options;
|
||||
if (matchedCommand) {
|
||||
this.matchedCommand = matchedCommand;
|
||||
}
|
||||
if (matchedCommandName) {
|
||||
this.matchedCommandName = matchedCommandName;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
unsetMatchedCommand() {
|
||||
this.matchedCommand = void 0;
|
||||
this.matchedCommandName = void 0;
|
||||
}
|
||||
parse(argv = processArgs, {
|
||||
run = true
|
||||
} = {}) {
|
||||
this.rawArgs = argv;
|
||||
if (!this.name) {
|
||||
this.name = argv[1] ? getFileName(argv[1]) : "cli";
|
||||
}
|
||||
let shouldParse = true;
|
||||
for (const command of this.commands) {
|
||||
const parsed = this.mri(argv.slice(2), command);
|
||||
const commandName = parsed.args[0];
|
||||
if (command.isMatched(commandName)) {
|
||||
shouldParse = false;
|
||||
const parsedInfo = __assign(__assign({}, parsed), {
|
||||
args: parsed.args.slice(1)
|
||||
});
|
||||
this.setParsedInfo(parsedInfo, command, commandName);
|
||||
this.emit(`command:${commandName}`, command);
|
||||
}
|
||||
}
|
||||
if (shouldParse) {
|
||||
for (const command of this.commands) {
|
||||
if (command.name === "") {
|
||||
shouldParse = false;
|
||||
const parsed = this.mri(argv.slice(2), command);
|
||||
this.setParsedInfo(parsed, command);
|
||||
this.emit(`command:!`, command);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (shouldParse) {
|
||||
const parsed = this.mri(argv.slice(2));
|
||||
this.setParsedInfo(parsed);
|
||||
}
|
||||
if (this.options.help && this.showHelpOnExit) {
|
||||
this.outputHelp();
|
||||
run = false;
|
||||
this.unsetMatchedCommand();
|
||||
}
|
||||
if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
|
||||
this.outputVersion();
|
||||
run = false;
|
||||
this.unsetMatchedCommand();
|
||||
}
|
||||
const parsedArgv = {args: this.args, options: this.options};
|
||||
if (run) {
|
||||
this.runMatchedCommand();
|
||||
}
|
||||
if (!this.matchedCommand && this.args[0]) {
|
||||
this.emit("command:*");
|
||||
}
|
||||
return parsedArgv;
|
||||
}
|
||||
mri(argv, command) {
|
||||
const cliOptions = [
|
||||
...this.globalCommand.options,
|
||||
...command ? command.options : []
|
||||
];
|
||||
const mriOptions = getMriOptions(cliOptions);
|
||||
let argsAfterDoubleDashes = [];
|
||||
const doubleDashesIndex = argv.indexOf("--");
|
||||
if (doubleDashesIndex > -1) {
|
||||
argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
|
||||
argv = argv.slice(0, doubleDashesIndex);
|
||||
}
|
||||
let parsed = mri2(argv, mriOptions);
|
||||
parsed = Object.keys(parsed).reduce((res, name) => {
|
||||
return __assign(__assign({}, res), {
|
||||
[camelcaseOptionName(name)]: parsed[name]
|
||||
});
|
||||
}, {_: []});
|
||||
const args = parsed._;
|
||||
const options = {
|
||||
"--": argsAfterDoubleDashes
|
||||
};
|
||||
const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
|
||||
let transforms = Object.create(null);
|
||||
for (const cliOption of cliOptions) {
|
||||
if (!ignoreDefault && cliOption.config.default !== void 0) {
|
||||
for (const name of cliOption.names) {
|
||||
options[name] = cliOption.config.default;
|
||||
}
|
||||
}
|
||||
if (Array.isArray(cliOption.config.type)) {
|
||||
if (transforms[cliOption.name] === void 0) {
|
||||
transforms[cliOption.name] = Object.create(null);
|
||||
transforms[cliOption.name]["shouldTransform"] = true;
|
||||
transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const key of Object.keys(parsed)) {
|
||||
if (key !== "_") {
|
||||
const keys = key.split(".");
|
||||
setDotProp(options, keys, parsed[key]);
|
||||
setByType(options, transforms);
|
||||
}
|
||||
}
|
||||
return {
|
||||
args,
|
||||
options
|
||||
};
|
||||
}
|
||||
runMatchedCommand() {
|
||||
const {args, options, matchedCommand: command} = this;
|
||||
if (!command || !command.commandAction)
|
||||
return;
|
||||
command.checkUnknownOptions();
|
||||
command.checkOptionValue();
|
||||
command.checkRequiredArgs();
|
||||
const actionArgs = [];
|
||||
command.args.forEach((arg, index) => {
|
||||
if (arg.variadic) {
|
||||
actionArgs.push(args.slice(index));
|
||||
} else {
|
||||
actionArgs.push(args[index]);
|
||||
}
|
||||
});
|
||||
actionArgs.push(options);
|
||||
return command.commandAction.apply(this, actionArgs);
|
||||
}
|
||||
}
|
||||
|
||||
const cac = (name = "") => new CAC(name);
|
||||
|
||||
const cli = cac("vitest");
|
||||
cli.version(version).option("-r, --root <path>", "root path").option("-c, --config <path>", "path to config file").option("-u, --update", "update snapshot").option("-w, --watch", "watch mode").option("-t, --testNamePattern <pattern>", "run tests with full names matching the specified pattern").option("--dir <path>", "base directory to scan for the test files").option("--ui", "enable UI").option("--open", "open UI automatically (default: !process.env.CI))").option("--api [api]", "serve API, available options: --api.port <port>, --api.host [host] and --api.strictPort").option("--threads", "enabled threads (default: true)").option("--silent", "silent console output from tests").option("--isolate", "isolate environment for each test file (default: true)").option("--reporter <name>", "reporter").option("--outputTruncateLength <length>", "diff output length (default: 80)").option("--outputDiffLines <lines>", "number of diff output lines (default: 15)").option("--outputFile <filename/-s>", "write test results to a file when the --reporter=json or --reporter=junit option is also specified, use cac's dot notation for individual outputs of multiple reporters").option("--coverage", "enable coverage report").option("--run", "do not watch").option("--mode <name>", "override Vite mode (default: test)").option("--globals", "inject apis globally").option("--dom", "mock browser api with happy-dom").option("--browser", "run tests in browser").option("--environment <env>", "runner environment (default: node)").option("--passWithNoTests", "pass when no tests found").option("--allowOnly", "Allow tests and suites that are marked as only (default: !process.env.CI)").option("--dangerouslyIgnoreUnhandledErrors", "Ignore any unhandled errors that occur").option("--shard <shard>", "Test suite shard to execute in a format of <index>/<count>").option("--changed [since]", "Run tests that are affected by the changed files (default: false)").option("--sequence <options>", "Define in what order to run tests (use --sequence.shuffle to run tests in random order)").option("--no-color", "Removes colors from the console output").option("--segfault-retry <times>", "Return tests on segment fault (default: 0)", { default: 0 }).option("--inspect", "Enable Node.js inspector").option("--inspect-brk", "Enable Node.js inspector with break").help();
|
||||
cli.command("run [...filters]").action(run);
|
||||
cli.command("related [...filters]").action(runRelated);
|
||||
cli.command("watch [...filters]").action(watch);
|
||||
cli.command("dev [...filters]").action(watch);
|
||||
cli.command("bench [...filters]").action(benchmark);
|
||||
cli.command("typecheck [...filters]").action(typecheck);
|
||||
cli.command("[...filters]").action((filters, options) => start("test", filters, options));
|
||||
cli.parse();
|
||||
async function runRelated(relatedFiles, argv) {
|
||||
argv.related = relatedFiles;
|
||||
argv.passWithNoTests ?? (argv.passWithNoTests = true);
|
||||
await start("test", [], argv);
|
||||
}
|
||||
async function watch(cliFilters, options) {
|
||||
options.watch = true;
|
||||
await start("test", cliFilters, options);
|
||||
}
|
||||
async function run(cliFilters, options) {
|
||||
options.run = true;
|
||||
await start("test", cliFilters, options);
|
||||
}
|
||||
async function benchmark(cliFilters, options) {
|
||||
console.warn(picocolors.exports.yellow("Benchmarking is an experimental feature.\nBreaking changes might not follow semver, please pin Vitest's version when using it."));
|
||||
await start("benchmark", cliFilters, options);
|
||||
}
|
||||
async function typecheck(cliFilters = [], options = {}) {
|
||||
console.warn(picocolors.exports.yellow("Testing types with tsc and vue-tsc is an experimental feature.\nBreaking changes might not follow semver, please pin Vitest's version when using it."));
|
||||
await start("typecheck", cliFilters, options);
|
||||
}
|
||||
function normalizeOptions(argv) {
|
||||
if (argv.root)
|
||||
argv.root = normalize(argv.root);
|
||||
if (argv.config)
|
||||
argv.config = normalize(argv.config);
|
||||
if (argv.dir)
|
||||
argv.dir = normalize(argv.dir);
|
||||
return argv;
|
||||
}
|
||||
async function start(mode, cliFilters, options) {
|
||||
try {
|
||||
const ctx = await startVitest(mode, cliFilters.map(normalize), normalizeOptions(options));
|
||||
if (!(ctx == null ? void 0 : ctx.config.watch))
|
||||
await (ctx == null ? void 0 : ctx.exit());
|
||||
return ctx;
|
||||
} catch (e) {
|
||||
console.error(`
|
||||
${picocolors.exports.red(divider(picocolors.exports.bold(picocolors.exports.inverse(" Unhandled Error "))))}`);
|
||||
console.error(e);
|
||||
console.error("\n\n");
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
96
node_modules/vitest/dist/config.cjs
generated
vendored
Normal file
96
node_modules/vitest/dist/config.cjs
generated
vendored
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
const defaultInclude = ["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"];
|
||||
const defaultExclude = ["**/node_modules/**", "**/dist/**", "**/cypress/**", "**/.{idea,git,cache,output,temp}/**", "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.*"];
|
||||
const defaultCoverageExcludes = [
|
||||
"coverage/**",
|
||||
"dist/**",
|
||||
"packages/*/test{,s}/**",
|
||||
"**/*.d.ts",
|
||||
"cypress/**",
|
||||
"test{,s}/**",
|
||||
"test{,-*}.{js,cjs,mjs,ts,tsx,jsx}",
|
||||
"**/*{.,-}test.{js,cjs,mjs,ts,tsx,jsx}",
|
||||
"**/*{.,-}spec.{js,cjs,mjs,ts,tsx,jsx}",
|
||||
"**/__tests__/**",
|
||||
"**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.*",
|
||||
"**/.{eslint,mocha,prettier}rc.{js,cjs,yml}"
|
||||
];
|
||||
const coverageConfigDefaults = {
|
||||
provider: "c8",
|
||||
enabled: false,
|
||||
clean: true,
|
||||
cleanOnRerun: false,
|
||||
reportsDirectory: "./coverage",
|
||||
excludeNodeModules: true,
|
||||
exclude: defaultCoverageExcludes,
|
||||
reporter: ["text", "html", "clover", "json"],
|
||||
allowExternal: false,
|
||||
extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte"]
|
||||
};
|
||||
const fakeTimersDefaults = {
|
||||
loopLimit: 1e4,
|
||||
shouldClearNativeTimers: true,
|
||||
toFake: [
|
||||
"setTimeout",
|
||||
"clearTimeout",
|
||||
"setInterval",
|
||||
"clearInterval",
|
||||
"setImmediate",
|
||||
"clearImmediate",
|
||||
"Date"
|
||||
]
|
||||
};
|
||||
const config = {
|
||||
allowOnly: !process.env.CI,
|
||||
watch: !process.env.CI,
|
||||
globals: false,
|
||||
environment: "node",
|
||||
threads: true,
|
||||
clearMocks: false,
|
||||
restoreMocks: false,
|
||||
mockReset: false,
|
||||
include: defaultInclude,
|
||||
exclude: defaultExclude,
|
||||
testTimeout: 5e3,
|
||||
hookTimeout: 1e4,
|
||||
teardownTimeout: 1e3,
|
||||
isolate: true,
|
||||
watchExclude: ["**/node_modules/**", "**/dist/**"],
|
||||
forceRerunTriggers: [
|
||||
"**/package.json/**",
|
||||
"**/{vitest,vite}.config.*/**"
|
||||
],
|
||||
update: false,
|
||||
reporters: [],
|
||||
silent: false,
|
||||
api: false,
|
||||
ui: false,
|
||||
uiBase: "/__vitest__/",
|
||||
open: true,
|
||||
css: {
|
||||
include: []
|
||||
},
|
||||
coverage: coverageConfigDefaults,
|
||||
fakeTimers: fakeTimersDefaults,
|
||||
maxConcurrency: 5,
|
||||
dangerouslyIgnoreUnhandledErrors: false,
|
||||
typecheck: {
|
||||
checker: "tsc",
|
||||
include: ["**/*.{test,spec}-d.{ts,js}"],
|
||||
exclude: defaultExclude
|
||||
},
|
||||
slowTestThreshold: 300
|
||||
};
|
||||
const configDefaults = Object.freeze(config);
|
||||
|
||||
function defineConfig(config) {
|
||||
return config;
|
||||
}
|
||||
|
||||
exports.configDefaults = configDefaults;
|
||||
exports.defaultExclude = defaultExclude;
|
||||
exports.defaultInclude = defaultInclude;
|
||||
exports.defineConfig = defineConfig;
|
||||
58
node_modules/vitest/dist/config.d.ts
generated
vendored
Normal file
58
node_modules/vitest/dist/config.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
import { UserConfig as UserConfig$2, ConfigEnv } from 'vite';
|
||||
export { ConfigEnv } from 'vite';
|
||||
import { U as UserConfig$1, ao as ResolvedCoverageOptions, F as FakeTimerInstallOpts } from './types-71ccd11d.js';
|
||||
import 'tinybench';
|
||||
import 'fs';
|
||||
import 'worker_threads';
|
||||
|
||||
declare const defaultInclude: string[];
|
||||
declare const defaultExclude: string[];
|
||||
declare const config: {
|
||||
allowOnly: boolean;
|
||||
watch: boolean;
|
||||
globals: boolean;
|
||||
environment: "node";
|
||||
threads: boolean;
|
||||
clearMocks: boolean;
|
||||
restoreMocks: boolean;
|
||||
mockReset: boolean;
|
||||
include: string[];
|
||||
exclude: string[];
|
||||
testTimeout: number;
|
||||
hookTimeout: number;
|
||||
teardownTimeout: number;
|
||||
isolate: boolean;
|
||||
watchExclude: string[];
|
||||
forceRerunTriggers: string[];
|
||||
update: boolean;
|
||||
reporters: never[];
|
||||
silent: boolean;
|
||||
api: boolean;
|
||||
ui: boolean;
|
||||
uiBase: string;
|
||||
open: boolean;
|
||||
css: {
|
||||
include: never[];
|
||||
};
|
||||
coverage: ResolvedCoverageOptions;
|
||||
fakeTimers: FakeTimerInstallOpts;
|
||||
maxConcurrency: number;
|
||||
dangerouslyIgnoreUnhandledErrors: boolean;
|
||||
typecheck: {
|
||||
checker: "tsc";
|
||||
include: string[];
|
||||
exclude: string[];
|
||||
};
|
||||
slowTestThreshold: number;
|
||||
};
|
||||
declare const configDefaults: Required<Pick<UserConfig$1, keyof typeof config>>;
|
||||
|
||||
interface UserConfig extends UserConfig$2 {
|
||||
test?: UserConfig$2['test'];
|
||||
}
|
||||
|
||||
type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise<UserConfig>;
|
||||
type UserConfigExport = UserConfig | Promise<UserConfig> | UserConfigFn;
|
||||
declare function defineConfig(config: UserConfigExport): UserConfigExport;
|
||||
|
||||
export { UserConfig, UserConfigExport, UserConfigFn, configDefaults, defaultExclude, defaultInclude, defineConfig };
|
||||
89
node_modules/vitest/dist/config.js
generated
vendored
Normal file
89
node_modules/vitest/dist/config.js
generated
vendored
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
const defaultInclude = ["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"];
|
||||
const defaultExclude = ["**/node_modules/**", "**/dist/**", "**/cypress/**", "**/.{idea,git,cache,output,temp}/**", "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.*"];
|
||||
const defaultCoverageExcludes = [
|
||||
"coverage/**",
|
||||
"dist/**",
|
||||
"packages/*/test{,s}/**",
|
||||
"**/*.d.ts",
|
||||
"cypress/**",
|
||||
"test{,s}/**",
|
||||
"test{,-*}.{js,cjs,mjs,ts,tsx,jsx}",
|
||||
"**/*{.,-}test.{js,cjs,mjs,ts,tsx,jsx}",
|
||||
"**/*{.,-}spec.{js,cjs,mjs,ts,tsx,jsx}",
|
||||
"**/__tests__/**",
|
||||
"**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.*",
|
||||
"**/.{eslint,mocha,prettier}rc.{js,cjs,yml}"
|
||||
];
|
||||
const coverageConfigDefaults = {
|
||||
provider: "c8",
|
||||
enabled: false,
|
||||
clean: true,
|
||||
cleanOnRerun: false,
|
||||
reportsDirectory: "./coverage",
|
||||
excludeNodeModules: true,
|
||||
exclude: defaultCoverageExcludes,
|
||||
reporter: ["text", "html", "clover", "json"],
|
||||
allowExternal: false,
|
||||
extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte"]
|
||||
};
|
||||
const fakeTimersDefaults = {
|
||||
loopLimit: 1e4,
|
||||
shouldClearNativeTimers: true,
|
||||
toFake: [
|
||||
"setTimeout",
|
||||
"clearTimeout",
|
||||
"setInterval",
|
||||
"clearInterval",
|
||||
"setImmediate",
|
||||
"clearImmediate",
|
||||
"Date"
|
||||
]
|
||||
};
|
||||
const config = {
|
||||
allowOnly: !process.env.CI,
|
||||
watch: !process.env.CI,
|
||||
globals: false,
|
||||
environment: "node",
|
||||
threads: true,
|
||||
clearMocks: false,
|
||||
restoreMocks: false,
|
||||
mockReset: false,
|
||||
include: defaultInclude,
|
||||
exclude: defaultExclude,
|
||||
testTimeout: 5e3,
|
||||
hookTimeout: 1e4,
|
||||
teardownTimeout: 1e3,
|
||||
isolate: true,
|
||||
watchExclude: ["**/node_modules/**", "**/dist/**"],
|
||||
forceRerunTriggers: [
|
||||
"**/package.json/**",
|
||||
"**/{vitest,vite}.config.*/**"
|
||||
],
|
||||
update: false,
|
||||
reporters: [],
|
||||
silent: false,
|
||||
api: false,
|
||||
ui: false,
|
||||
uiBase: "/__vitest__/",
|
||||
open: true,
|
||||
css: {
|
||||
include: []
|
||||
},
|
||||
coverage: coverageConfigDefaults,
|
||||
fakeTimers: fakeTimersDefaults,
|
||||
maxConcurrency: 5,
|
||||
dangerouslyIgnoreUnhandledErrors: false,
|
||||
typecheck: {
|
||||
checker: "tsc",
|
||||
include: ["**/*.{test,spec}-d.{ts,js}"],
|
||||
exclude: defaultExclude
|
||||
},
|
||||
slowTestThreshold: 300
|
||||
};
|
||||
const configDefaults = Object.freeze(config);
|
||||
|
||||
function defineConfig(config) {
|
||||
return config;
|
||||
}
|
||||
|
||||
export { configDefaults, defaultExclude, defaultInclude, defineConfig };
|
||||
84
node_modules/vitest/dist/entry.js
generated
vendored
Normal file
84
node_modules/vitest/dist/entry.js
generated
vendored
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import { promises } from 'fs';
|
||||
import { g as getWorkerState, a as resetModules } from './chunk-typecheck-constants.ed987901.js';
|
||||
import { v as vi } from './chunk-runtime-test-state.3f86f48f.js';
|
||||
import { a as envs } from './chunk-env-node.67948209.js';
|
||||
import { a as setupGlobalEnv, s as startTests, w as withEnv } from './chunk-runtime-setup.5398e2c4.js';
|
||||
import 'path';
|
||||
import './chunk-utils-env.03f840f2.js';
|
||||
import 'tty';
|
||||
import 'url';
|
||||
import 'local-pkg';
|
||||
import './chunk-runtime-chain.f86e5250.js';
|
||||
import 'util';
|
||||
import 'chai';
|
||||
import './vendor-_commonjsHelpers.addc3445.js';
|
||||
import './chunk-runtime-rpc.42aebbb9.js';
|
||||
import './chunk-utils-timers.793fd179.js';
|
||||
import './chunk-utils-source-map.29ff1088.js';
|
||||
import './spy.js';
|
||||
import 'tinyspy';
|
||||
import 'console';
|
||||
import 'perf_hooks';
|
||||
import './chunk-integrations-coverage.befed097.js';
|
||||
import './chunk-runtime-error.616e92ca.js';
|
||||
import './vendor-source-map-support.1ce17397.js';
|
||||
import 'source-map';
|
||||
|
||||
function groupBy(collection, iteratee) {
|
||||
return collection.reduce((acc, item) => {
|
||||
const key = iteratee(item);
|
||||
acc[key] || (acc[key] = []);
|
||||
acc[key].push(item);
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
async function run(files, config) {
|
||||
await setupGlobalEnv(config);
|
||||
const workerState = getWorkerState();
|
||||
if (config.browser) {
|
||||
workerState.mockMap.clear();
|
||||
await startTests(files, config);
|
||||
return;
|
||||
}
|
||||
const filesWithEnv = await Promise.all(files.map(async (file) => {
|
||||
var _a, _b;
|
||||
const code = await promises.readFile(file, "utf-8");
|
||||
const env = ((_a = code.match(/@(?:vitest|jest)-environment\s+?([\w-]+)\b/)) == null ? void 0 : _a[1]) || config.environment || "node";
|
||||
const envOptions = JSON.parse(((_b = code.match(/@(?:vitest|jest)-environment-options\s+?(.+)/)) == null ? void 0 : _b[1]) || "null");
|
||||
return {
|
||||
file,
|
||||
env,
|
||||
envOptions: envOptions ? { [env]: envOptions } : null
|
||||
};
|
||||
}));
|
||||
const filesByEnv = groupBy(filesWithEnv, ({ env }) => env);
|
||||
const orderedEnvs = envs.concat(
|
||||
Object.keys(filesByEnv).filter((env) => !envs.includes(env))
|
||||
);
|
||||
for (const env of orderedEnvs) {
|
||||
const environment = env;
|
||||
const files2 = filesByEnv[environment];
|
||||
if (!files2 || !files2.length)
|
||||
continue;
|
||||
const filesByOptions = groupBy(files2, ({ envOptions }) => JSON.stringify(envOptions));
|
||||
for (const options of Object.keys(filesByOptions)) {
|
||||
const files3 = filesByOptions[options];
|
||||
if (!files3 || !files3.length)
|
||||
continue;
|
||||
await withEnv(environment, files3[0].envOptions || config.environmentOptions || {}, async () => {
|
||||
for (const { file } of files3) {
|
||||
if (config.isolate) {
|
||||
workerState.mockMap.clear();
|
||||
resetModules(workerState.moduleCache, true);
|
||||
}
|
||||
workerState.filepath = file;
|
||||
await startTests([file], config);
|
||||
workerState.filepath = void 0;
|
||||
vi.resetConfig();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { run };
|
||||
23
node_modules/vitest/dist/environments.d.ts
generated
vendored
Normal file
23
node_modules/vitest/dist/environments.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { ae as Environment } from './types-71ccd11d.js';
|
||||
import 'vite';
|
||||
import 'tinybench';
|
||||
import 'fs';
|
||||
import 'worker_threads';
|
||||
|
||||
declare const environments: {
|
||||
node: Environment;
|
||||
jsdom: Environment;
|
||||
'happy-dom': Environment;
|
||||
'edge-runtime': Environment;
|
||||
};
|
||||
|
||||
interface PopulateOptions {
|
||||
bindFunctions?: boolean;
|
||||
}
|
||||
declare function populateGlobal(global: any, win: any, options?: PopulateOptions): {
|
||||
keys: Set<string>;
|
||||
skipKeys: string[];
|
||||
originals: Map<string | symbol, any>;
|
||||
};
|
||||
|
||||
export { environments as builtinEnvironments, populateGlobal };
|
||||
3
node_modules/vitest/dist/environments.js
generated
vendored
Normal file
3
node_modules/vitest/dist/environments.js
generated
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export { e as builtinEnvironments, p as populateGlobal } from './chunk-env-node.67948209.js';
|
||||
import 'console';
|
||||
import 'local-pkg';
|
||||
256
node_modules/vitest/dist/index-5aad25c1.d.ts
generated
vendored
Normal file
256
node_modules/vitest/dist/index-5aad25c1.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,256 @@
|
|||
import { SpyImpl } from 'tinyspy';
|
||||
import { w as SuiteAPI, v as TestAPI, aw as BenchmarkAPI, y as SuiteHooks, H as HookListener, L as TestContext, p as Suite, x as HookCleanupCallback, O as OnTestFailedHandler, q as Test } from './types-71ccd11d.js';
|
||||
|
||||
declare type Not<T extends boolean> = T extends true ? false : true;
|
||||
declare type And<Types extends boolean[]> = Types[number] extends true ? true : false;
|
||||
declare type Eq<Left extends boolean, Right extends boolean> = Left extends true ? Right : Not<Right>;
|
||||
declare const secret: unique symbol;
|
||||
declare type Secret = typeof secret;
|
||||
declare type IsNever<T> = [T] extends [never] ? true : false;
|
||||
declare type IsAny<T> = [T] extends [Secret] ? Not<IsNever<T>> : false;
|
||||
declare type IsUnknown<T> = [unknown] extends [T] ? Not<IsAny<T>> : false;
|
||||
/**
|
||||
* Recursively walk a type and replace it with a branded type related to the original. This is useful for
|
||||
* equality-checking stricter than `A extends B ? B extends A ? true : false : false`, because it detects
|
||||
* the difference between a few edge-case types that vanilla typescript doesn't by default:
|
||||
* - `any` vs `unknown`
|
||||
* - `{ readonly a: string }` vs `{ a: string }`
|
||||
* - `{ a?: string }` vs `{ a: string | undefined }`
|
||||
*/
|
||||
declare type DeepBrand<T> = IsNever<T> extends true ? {
|
||||
type: 'never';
|
||||
} : IsAny<T> extends true ? {
|
||||
type: 'any';
|
||||
} : IsUnknown<T> extends true ? {
|
||||
type: 'unknown';
|
||||
} : T extends string | number | boolean | symbol | bigint | null | undefined | void ? {
|
||||
type: 'primitive';
|
||||
value: T;
|
||||
} : T extends new (...args: any[]) => any ? {
|
||||
type: 'constructor';
|
||||
params: ConstructorParams<T>;
|
||||
instance: DeepBrand<InstanceType<Extract<T, new (...args: any) => any>>>;
|
||||
} : T extends (...args: infer P) => infer R ? {
|
||||
type: 'function';
|
||||
params: DeepBrand<P>;
|
||||
return: DeepBrand<R>;
|
||||
} : T extends any[] ? {
|
||||
type: 'array';
|
||||
items: {
|
||||
[K in keyof T]: T[K];
|
||||
};
|
||||
} : {
|
||||
type: 'object';
|
||||
properties: {
|
||||
[K in keyof T]: DeepBrand<T[K]>;
|
||||
};
|
||||
readonly: ReadonlyKeys<T>;
|
||||
required: RequiredKeys<T>;
|
||||
optional: OptionalKeys<T>;
|
||||
constructorParams: DeepBrand<ConstructorParams<T>>;
|
||||
};
|
||||
declare type RequiredKeys<T> = Extract<{
|
||||
[K in keyof T]-?: {} extends Pick<T, K> ? never : K;
|
||||
}[keyof T], keyof T>;
|
||||
declare type OptionalKeys<T> = Exclude<keyof T, RequiredKeys<T>>;
|
||||
declare type ReadonlyKeys<T> = Extract<{
|
||||
[K in keyof T]-?: ReadonlyEquivalent<{
|
||||
[_K in K]: T[K];
|
||||
}, {
|
||||
-readonly [_K in K]: T[K];
|
||||
}> extends true ? never : K;
|
||||
}[keyof T], keyof T>;
|
||||
declare type ReadonlyEquivalent<X, Y> = Extends<(<T>() => T extends X ? true : false), (<T>() => T extends Y ? true : false)>;
|
||||
declare type Extends<L, R> = IsNever<L> extends true ? IsNever<R> : [L] extends [R] ? true : false;
|
||||
declare type StrictExtends<L, R> = Extends<DeepBrand<L>, DeepBrand<R>>;
|
||||
declare type Equal<Left, Right> = And<[StrictExtends<Left, Right>, StrictExtends<Right, Left>]>;
|
||||
declare type Params<Actual> = Actual extends (...args: infer P) => any ? P : never;
|
||||
declare type ConstructorParams<Actual> = Actual extends new (...args: infer P) => any ? Actual extends new () => any ? P | [] : P : never;
|
||||
declare type MismatchArgs<B extends boolean, C extends boolean> = Eq<B, C> extends true ? [] : [never];
|
||||
interface ExpectTypeOf<Actual, B extends boolean> {
|
||||
toBeAny: (...MISMATCH: MismatchArgs<IsAny<Actual>, B>) => true;
|
||||
toBeUnknown: (...MISMATCH: MismatchArgs<IsUnknown<Actual>, B>) => true;
|
||||
toBeNever: (...MISMATCH: MismatchArgs<IsNever<Actual>, B>) => true;
|
||||
toBeFunction: (...MISMATCH: MismatchArgs<Extends<Actual, (...args: any[]) => any>, B>) => true;
|
||||
toBeObject: (...MISMATCH: MismatchArgs<Extends<Actual, object>, B>) => true;
|
||||
toBeArray: (...MISMATCH: MismatchArgs<Extends<Actual, any[]>, B>) => true;
|
||||
toBeNumber: (...MISMATCH: MismatchArgs<Extends<Actual, number>, B>) => true;
|
||||
toBeString: (...MISMATCH: MismatchArgs<Extends<Actual, string>, B>) => true;
|
||||
toBeBoolean: (...MISMATCH: MismatchArgs<Extends<Actual, boolean>, B>) => true;
|
||||
toBeVoid: (...MISMATCH: MismatchArgs<Extends<Actual, void>, B>) => true;
|
||||
toBeSymbol: (...MISMATCH: MismatchArgs<Extends<Actual, symbol>, B>) => true;
|
||||
toBeNull: (...MISMATCH: MismatchArgs<Extends<Actual, null>, B>) => true;
|
||||
toBeUndefined: (...MISMATCH: MismatchArgs<Extends<Actual, undefined>, B>) => true;
|
||||
toBeNullable: (...MISMATCH: MismatchArgs<Not<Equal<Actual, NonNullable<Actual>>>, B>) => true;
|
||||
toMatchTypeOf: {
|
||||
<Expected>(...MISMATCH: MismatchArgs<Extends<Actual, Expected>, B>): true;
|
||||
<Expected>(expected: Expected, ...MISMATCH: MismatchArgs<Extends<Actual, Expected>, B>): true;
|
||||
};
|
||||
toEqualTypeOf: {
|
||||
<Expected>(...MISMATCH: MismatchArgs<Equal<Actual, Expected>, B>): true;
|
||||
<Expected>(expected: Expected, ...MISMATCH: MismatchArgs<Equal<Actual, Expected>, B>): true;
|
||||
};
|
||||
toBeCallableWith: B extends true ? (...args: Params<Actual>) => true : never;
|
||||
toBeConstructibleWith: B extends true ? (...args: ConstructorParams<Actual>) => true : never;
|
||||
toHaveProperty: <K extends string>(key: K, ...MISMATCH: MismatchArgs<Extends<K, keyof Actual>, B>) => K extends keyof Actual ? ExpectTypeOf<Actual[K], B> : true;
|
||||
extract: <V>(v?: V) => ExpectTypeOf<Extract<Actual, V>, B>;
|
||||
exclude: <V>(v?: V) => ExpectTypeOf<Exclude<Actual, V>, B>;
|
||||
parameter: <K extends keyof Params<Actual>>(number: K) => ExpectTypeOf<Params<Actual>[K], B>;
|
||||
parameters: ExpectTypeOf<Params<Actual>, B>;
|
||||
constructorParameters: ExpectTypeOf<ConstructorParams<Actual>, B>;
|
||||
instance: Actual extends new (...args: any[]) => infer I ? ExpectTypeOf<I, B> : never;
|
||||
returns: Actual extends (...args: any[]) => infer R ? ExpectTypeOf<R, B> : never;
|
||||
resolves: Actual extends PromiseLike<infer R> ? ExpectTypeOf<R, B> : never;
|
||||
items: Actual extends ArrayLike<infer R> ? ExpectTypeOf<R, B> : never;
|
||||
guards: Actual extends (v: any, ...args: any[]) => v is infer T ? ExpectTypeOf<T, B> : never;
|
||||
asserts: Actual extends (v: any, ...args: any[]) => asserts v is infer T ? unknown extends T ? never : ExpectTypeOf<T, B> : never;
|
||||
not: ExpectTypeOf<Actual, Not<B>>;
|
||||
}
|
||||
declare type _ExpectTypeOf = {
|
||||
<Actual>(actual: Actual): ExpectTypeOf<Actual, true>;
|
||||
<Actual>(): ExpectTypeOf<Actual, 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.
|
||||
*/
|
||||
declare const expectTypeOf: _ExpectTypeOf;
|
||||
|
||||
interface AssertType {
|
||||
<T>(value: T): void;
|
||||
}
|
||||
declare const assertType: AssertType;
|
||||
|
||||
interface MockResultReturn<T> {
|
||||
type: 'return';
|
||||
value: T;
|
||||
}
|
||||
interface MockResultIncomplete {
|
||||
type: 'incomplete';
|
||||
value: undefined;
|
||||
}
|
||||
interface MockResultThrow {
|
||||
type: 'throw';
|
||||
value: any;
|
||||
}
|
||||
type MockResult<T> = MockResultReturn<T> | MockResultThrow | MockResultIncomplete;
|
||||
interface MockContext<TArgs, TReturns> {
|
||||
calls: TArgs[];
|
||||
instances: TReturns[];
|
||||
invocationCallOrder: number[];
|
||||
results: MockResult<TReturns>[];
|
||||
lastCall: TArgs | undefined;
|
||||
}
|
||||
type Procedure = (...args: any[]) => any;
|
||||
type Methods<T> = {
|
||||
[K in keyof T]: T[K] extends Procedure ? K : never;
|
||||
}[keyof T] & (string | symbol);
|
||||
type Properties<T> = {
|
||||
[K in keyof T]: T[K] extends Procedure ? never : K;
|
||||
}[keyof T] & (string | symbol);
|
||||
type Classes<T> = {
|
||||
[K in keyof T]: T[K] extends new (...args: any[]) => any ? K : never;
|
||||
}[keyof T] & (string | symbol);
|
||||
interface SpyInstance<TArgs extends any[] = any[], TReturns = any> {
|
||||
getMockName(): string;
|
||||
mockName(n: string): this;
|
||||
mock: MockContext<TArgs, TReturns>;
|
||||
mockClear(): this;
|
||||
mockReset(): this;
|
||||
mockRestore(): void;
|
||||
getMockImplementation(): ((...args: TArgs) => TReturns) | undefined;
|
||||
mockImplementation(fn: ((...args: TArgs) => TReturns) | (() => Promise<TReturns>)): this;
|
||||
mockImplementationOnce(fn: ((...args: TArgs) => TReturns) | (() => Promise<TReturns>)): this;
|
||||
mockReturnThis(): this;
|
||||
mockReturnValue(obj: TReturns): this;
|
||||
mockReturnValueOnce(obj: TReturns): this;
|
||||
mockResolvedValue(obj: Awaited<TReturns>): this;
|
||||
mockResolvedValueOnce(obj: Awaited<TReturns>): this;
|
||||
mockRejectedValue(obj: any): this;
|
||||
mockRejectedValueOnce(obj: any): this;
|
||||
}
|
||||
interface MockInstance<A extends any[] = any[], R = any> extends SpyInstance<A, R> {
|
||||
}
|
||||
interface Mock<TArgs extends any[] = any, TReturns = any> extends SpyInstance<TArgs, TReturns> {
|
||||
new (...args: TArgs): TReturns;
|
||||
(...args: TArgs): TReturns;
|
||||
}
|
||||
interface PartialMock<TArgs extends any[] = any, TReturns = any> extends SpyInstance<TArgs, Partial<TReturns>> {
|
||||
new (...args: TArgs): TReturns;
|
||||
(...args: TArgs): TReturns;
|
||||
}
|
||||
type MaybeMockedConstructor<T> = T extends new (...args: Array<any>) => infer R ? Mock<ConstructorParameters<T>, R> : T;
|
||||
type MockedFunction<T extends Procedure> = Mock<Parameters<T>, ReturnType<T>> & {
|
||||
[K in keyof T]: T[K];
|
||||
};
|
||||
type PartiallyMockedFunction<T extends Procedure> = PartialMock<Parameters<T>, ReturnType<T>> & {
|
||||
[K in keyof T]: T[K];
|
||||
};
|
||||
type MockedFunctionDeep<T extends Procedure> = Mock<Parameters<T>, ReturnType<T>> & MockedObjectDeep<T>;
|
||||
type PartiallyMockedFunctionDeep<T extends Procedure> = PartialMock<Parameters<T>, ReturnType<T>> & MockedObjectDeep<T>;
|
||||
type MockedObject<T> = MaybeMockedConstructor<T> & {
|
||||
[K in Methods<T>]: T[K] extends Procedure ? MockedFunction<T[K]> : T[K];
|
||||
} & {
|
||||
[K in Properties<T>]: T[K];
|
||||
};
|
||||
type MockedObjectDeep<T> = MaybeMockedConstructor<T> & {
|
||||
[K in Methods<T>]: T[K] extends Procedure ? MockedFunctionDeep<T[K]> : T[K];
|
||||
} & {
|
||||
[K in Properties<T>]: MaybeMockedDeep<T[K]>;
|
||||
};
|
||||
type MaybeMockedDeep<T> = T extends Procedure ? MockedFunctionDeep<T> : T extends object ? MockedObjectDeep<T> : T;
|
||||
type MaybePartiallyMockedDeep<T> = T extends Procedure ? PartiallyMockedFunctionDeep<T> : T extends object ? MockedObjectDeep<T> : T;
|
||||
type MaybeMocked<T> = T extends Procedure ? MockedFunction<T> : T extends object ? MockedObject<T> : T;
|
||||
type MaybePartiallyMocked<T> = T extends Procedure ? PartiallyMockedFunction<T> : T extends object ? MockedObject<T> : T;
|
||||
interface Constructable {
|
||||
new (...args: any[]): any;
|
||||
}
|
||||
type MockedClass<T extends Constructable> = MockInstance<T extends new (...args: infer P) => any ? P : never, InstanceType<T>> & {
|
||||
prototype: T extends {
|
||||
prototype: any;
|
||||
} ? Mocked<T['prototype']> : never;
|
||||
} & T;
|
||||
type Mocked<T> = {
|
||||
[P in keyof T]: T[P] extends (...args: infer Args) => infer Returns ? MockInstance<Args, Returns> : T[P] extends Constructable ? MockedClass<T[P]> : T[P];
|
||||
} & T;
|
||||
type EnhancedSpy<TArgs extends any[] = any[], TReturns = any> = SpyInstance<TArgs, TReturns> & SpyImpl<TArgs, TReturns>;
|
||||
declare function spyOn<T, S extends Properties<Required<T>>>(obj: T, methodName: S, accessType: 'get'): SpyInstance<[], T[S]>;
|
||||
declare function spyOn<T, G extends Properties<Required<T>>>(obj: T, methodName: G, accessType: 'set'): SpyInstance<[T[G]], void>;
|
||||
declare function spyOn<T, M extends (Methods<Required<T>> | Classes<Required<T>>)>(obj: T, methodName: M): Required<T>[M] extends (...args: infer A) => infer R | (new (...args: infer A) => infer R) ? SpyInstance<A, R> : never;
|
||||
declare function fn<TArgs extends any[] = any[], R = any>(): Mock<TArgs, R>;
|
||||
declare function fn<TArgs extends any[] = any[], R = any>(implementation: (...args: TArgs) => R): Mock<TArgs, R>;
|
||||
|
||||
declare const suite: SuiteAPI<{}>;
|
||||
declare const test: TestAPI<{}>;
|
||||
declare const bench: BenchmarkAPI;
|
||||
declare const describe: SuiteAPI<{}>;
|
||||
declare const it: TestAPI<{}>;
|
||||
|
||||
declare const beforeAll: (fn: SuiteHooks['beforeAll'][0], timeout?: number) => void;
|
||||
declare const afterAll: (fn: SuiteHooks['afterAll'][0], timeout?: number) => void;
|
||||
declare const beforeEach: <ExtraContext = {}>(fn: HookListener<[TestContext & ExtraContext, Suite], HookCleanupCallback>, timeout?: number) => void;
|
||||
declare const afterEach: <ExtraContext = {}>(fn: HookListener<[TestContext & ExtraContext, Suite], void>, timeout?: number) => void;
|
||||
declare const onTestFailed: (fn: OnTestFailedHandler) => void;
|
||||
|
||||
declare function createExpect(test?: Test): Vi.ExpectStatic;
|
||||
declare const globalExpect: Vi.ExpectStatic;
|
||||
|
||||
export { AssertType as A, MockedClass as B, EnhancedSpy as E, MaybeMockedDeep as M, SpyInstance as S, MaybeMocked as a, MaybePartiallyMocked as b, MaybePartiallyMockedDeep as c, suite as d, describe as e, fn as f, bench as g, beforeAll as h, it as i, afterAll as j, beforeEach as k, afterEach as l, globalExpect as m, createExpect as n, onTestFailed as o, expectTypeOf as p, ExpectTypeOf as q, assertType as r, spyOn as s, test as t, MockedFunction as u, MockedObject as v, MockInstance as w, Mock as x, MockContext as y, Mocked as z };
|
||||
189
node_modules/vitest/dist/index.d.ts
generated
vendored
Normal file
189
node_modules/vitest/dist/index.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
import { s as spyOn, f as fn, M as MaybeMockedDeep, a as MaybeMocked, b as MaybePartiallyMocked, c as MaybePartiallyMockedDeep, E as EnhancedSpy } from './index-5aad25c1.js';
|
||||
export { A as AssertType, E as EnhancedSpy, q as ExpectTypeOf, x as Mock, y as MockContext, w as MockInstance, z as Mocked, B as MockedClass, u as MockedFunction, v as MockedObject, S as SpyInstance, j as afterAll, l as afterEach, r as assertType, h as beforeAll, k as beforeEach, g as bench, n as createExpect, e as describe, m as expect, p as expectTypeOf, i as it, o as onTestFailed, d as suite, t as test } from './index-5aad25c1.js';
|
||||
import { D as DoneCallback, F as FakeTimerInstallOpts, R as RuntimeConfig, a as File, T as TaskResultPack, b as ResolvedConfig, M as ModuleGraphData, c as Reporter } from './types-71ccd11d.js';
|
||||
export { a1 as AfterSuiteRunMeta, A as ApiConfig, a7 as ArgumentsType, a6 as Arrayable, a4 as Awaitable, ap as BaseCoverageOptions, av as BenchFunction, at as Benchmark, aw as BenchmarkAPI, au as BenchmarkResult, as as BenchmarkUserOptions, B as BuiltinEnvironment, i as CSSModuleScopeStrategy, C as CollectLineNumbers, f as CollectLines, ab as Constructable, h as Context, ar as CoverageC8Options, aq as CoverageIstanbulOptions, an as CoverageOptions, ak as CoverageProvider, al as CoverageProviderModule, am as CoverageReporter, a9 as DeepMerge, D as DoneCallback, ae as Environment, E as EnvironmentOptions, ad as EnvironmentReturn, ai as ErrorWithDiff, a as File, x as HookCleanupCallback, H as HookListener, I as InlineConfig, J as JSDOMOptions, a8 as MergeInsertions, ac as ModuleCache, M as ModuleGraphData, aa as MutableArray, a5 as Nullable, aj as OnServerRestartHandler, O as OnTestFailedHandler, ah as ParsedStack, ag as Position, d as RawErrsMap, c as Reporter, a0 as ResolveIdFunction, b as ResolvedConfig, ao as ResolvedCoverageOptions, g as RootAndTarget, l as RunMode, R as RuntimeConfig, K as RuntimeContext, S as SequenceHooks, P as SnapshotData, X as SnapshotMatchOptions, Y as SnapshotResult, W as SnapshotStateOptions, _ as SnapshotSummary, Q as SnapshotUpdateState, p as Suite, w as SuiteAPI, z as SuiteCollector, G as SuiteFactory, y as SuiteHooks, s as Task, n as TaskBase, o as TaskResult, T as TaskResultPack, m as TaskState, q as Test, v as TestAPI, L as TestContext, t as TestFunction, u as TestOptions, e as TscErrorInfo, r as TypeCheck, k as TypecheckConfig, Z as UncheckedSnapshot, U as UserConfig, af as UserConsoleLog, N as Vitest, V as VitestEnvironment, j as VitestRunMode, $ as WorkerContext, a3 as WorkerGlobalState, a2 as WorkerRPC } from './types-71ccd11d.js';
|
||||
import { TransformResult } from 'vite';
|
||||
import * as chai from 'chai';
|
||||
export { chai };
|
||||
export { assert, should } from 'chai';
|
||||
export { Bench as BenchFactory, Options as BenchOptions, Task as BenchTask, TaskResult as BenchTaskResult } from 'tinybench';
|
||||
import 'tinyspy';
|
||||
import 'fs';
|
||||
import 'worker_threads';
|
||||
|
||||
/**
|
||||
* A simple wrapper for converting callback style to promise
|
||||
*/
|
||||
declare function withCallback(fn: (done: DoneCallback) => void): Promise<void>;
|
||||
|
||||
/**
|
||||
* This utils allows computational intensive tasks to only be ran once
|
||||
* across test reruns to improve the watch mode performance.
|
||||
*
|
||||
* Currently only works with `isolate: false`
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
declare function runOnce<T>(fn: (() => T), key?: string): T;
|
||||
/**
|
||||
* Get a boolean indicates whether the task is running in the first time.
|
||||
* Could only be `false` in watch mode.
|
||||
*
|
||||
* Currently only works with `isolate: false`
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
declare function isFirstRun(): boolean;
|
||||
|
||||
declare class VitestUtils {
|
||||
private _timers;
|
||||
private _mockedDate;
|
||||
private _mocker;
|
||||
constructor();
|
||||
useFakeTimers(config?: FakeTimerInstallOpts): this;
|
||||
useRealTimers(): this;
|
||||
runOnlyPendingTimers(): this;
|
||||
runAllTimers(): this;
|
||||
runAllTicks(): this;
|
||||
advanceTimersByTime(ms: number): this;
|
||||
advanceTimersToNextTimer(): this;
|
||||
getTimerCount(): number;
|
||||
setSystemTime(time: number | string | Date): this;
|
||||
getMockedSystemTime(): string | number | Date | null;
|
||||
getRealSystemTime(): number;
|
||||
clearAllTimers(): this;
|
||||
spyOn: typeof spyOn;
|
||||
fn: typeof fn;
|
||||
private getImporter;
|
||||
/**
|
||||
* Makes all `imports` to passed module to be mocked.
|
||||
* - If there is a factory, will return it's result. The call to `vi.mock` is hoisted to the top of the file,
|
||||
* so you don't have access to variables declared in the global file scope, if you didn't put them before imports!
|
||||
* - If `__mocks__` folder with file of the same name exist, all imports will
|
||||
* return it.
|
||||
* - If there is no `__mocks__` folder or a file with the same name inside, will call original
|
||||
* module and mock it.
|
||||
* @param path Path to the module. Can be aliased, if your config supports it
|
||||
* @param factory Factory for the mocked module. Has the highest priority.
|
||||
*/
|
||||
mock(path: string, factory?: () => any): void;
|
||||
/**
|
||||
* Removes module from mocked registry. All subsequent calls to import will
|
||||
* return original module even if it was mocked.
|
||||
* @param path Path to the module. Can be aliased, if your config supports it
|
||||
*/
|
||||
unmock(path: string): void;
|
||||
doMock(path: string, factory?: () => any): void;
|
||||
doUnmock(path: string): void;
|
||||
/**
|
||||
* Imports module, bypassing all checks if it should be mocked.
|
||||
* Can be useful if you want to mock module partially.
|
||||
* @example
|
||||
* vi.mock('./example', async () => {
|
||||
* const axios = await vi.importActual('./example')
|
||||
*
|
||||
* return { ...axios, get: vi.fn() }
|
||||
* })
|
||||
* @param path Path to the module. Can be aliased, if your config supports it
|
||||
* @returns Actual module without spies
|
||||
*/
|
||||
importActual<T>(path: string): Promise<T>;
|
||||
/**
|
||||
* Imports a module with all of its properties and nested properties mocked.
|
||||
* For the rules applied, see docs.
|
||||
* @param path Path to the module. Can be aliased, if your config supports it
|
||||
* @returns Fully mocked module
|
||||
*/
|
||||
importMock<T>(path: string): Promise<MaybeMockedDeep<T>>;
|
||||
/**
|
||||
* Type helpers for TypeScript. In reality just returns the object that was passed.
|
||||
*
|
||||
* When `partial` is `true` it will expect a `Partial<T>` as a return value.
|
||||
* @example
|
||||
* import example from './example'
|
||||
* vi.mock('./example')
|
||||
*
|
||||
* test('1+1 equals 2' async () => {
|
||||
* vi.mocked(example.calc).mockRestore()
|
||||
*
|
||||
* const res = example.calc(1, '+', 1)
|
||||
*
|
||||
* expect(res).toBe(2)
|
||||
* })
|
||||
* @param item Anything that can be mocked
|
||||
* @param deep If the object is deeply mocked
|
||||
* @param options If the object is partially or deeply mocked
|
||||
*/
|
||||
mocked<T>(item: T, deep?: false): MaybeMocked<T>;
|
||||
mocked<T>(item: T, deep: true): MaybeMockedDeep<T>;
|
||||
mocked<T>(item: T, options: {
|
||||
partial?: false;
|
||||
deep?: false;
|
||||
}): MaybeMocked<T>;
|
||||
mocked<T>(item: T, options: {
|
||||
partial?: false;
|
||||
deep: true;
|
||||
}): MaybeMockedDeep<T>;
|
||||
mocked<T>(item: T, options: {
|
||||
partial: true;
|
||||
deep?: false;
|
||||
}): MaybePartiallyMocked<T>;
|
||||
mocked<T>(item: T, options: {
|
||||
partial: true;
|
||||
deep: true;
|
||||
}): MaybePartiallyMockedDeep<T>;
|
||||
isMockFunction(fn: any): fn is EnhancedSpy;
|
||||
clearAllMocks(): this;
|
||||
resetAllMocks(): this;
|
||||
restoreAllMocks(): this;
|
||||
/**
|
||||
* Will put a value on global scope. Useful, if you are
|
||||
* using jsdom/happy-dom and want to mock global variables, like
|
||||
* `IntersectionObserver`.
|
||||
*/
|
||||
stubGlobal(name: string | symbol | number, value: any): this;
|
||||
resetModules(): this;
|
||||
/**
|
||||
* Wait for all imports to load.
|
||||
* Useful, if you have a synchronous call that starts
|
||||
* importing a module that you cannot wait otherwise.
|
||||
*/
|
||||
dynamicImportSettled(): Promise<void>;
|
||||
private _config;
|
||||
/**
|
||||
* Updates runtime config. You can only change values that are used when executing tests.
|
||||
*/
|
||||
setConfig(config: RuntimeConfig): void;
|
||||
/**
|
||||
* If config was changed with `vi.setConfig`, this will reset it to the original state.
|
||||
*/
|
||||
resetConfig(): void;
|
||||
}
|
||||
declare const vitest: VitestUtils;
|
||||
declare const vi: VitestUtils;
|
||||
|
||||
declare function getRunningMode(): "run" | "watch";
|
||||
declare function isWatchMode(): boolean;
|
||||
|
||||
interface TransformResultWithSource extends TransformResult {
|
||||
source?: string;
|
||||
}
|
||||
interface WebSocketHandlers {
|
||||
onWatcherStart: () => Promise<void>;
|
||||
onFinished(files?: File[]): Promise<void>;
|
||||
onCollected(files?: File[]): Promise<void>;
|
||||
onTaskUpdate(packs: TaskResultPack[]): void;
|
||||
getFiles(): File[];
|
||||
getPaths(): Promise<string[]>;
|
||||
getConfig(): ResolvedConfig;
|
||||
getModuleGraph(id: string): Promise<ModuleGraphData>;
|
||||
getTransformResult(id: string): Promise<TransformResultWithSource | undefined>;
|
||||
readFile(id: string): Promise<string>;
|
||||
writeFile(id: string, content: string): Promise<void>;
|
||||
rerun(files: string[]): Promise<void>;
|
||||
updateSnapshot(file?: File): Promise<void>;
|
||||
}
|
||||
interface WebSocketEvents extends Pick<Reporter, 'onCollected' | 'onFinished' | 'onTaskUpdate' | 'onUserConsoleLog' | 'onPathsCollected'> {
|
||||
}
|
||||
|
||||
export { TransformResultWithSource, WebSocketEvents, WebSocketHandlers, getRunningMode, isFirstRun, isWatchMode, runOnce, vi, vitest, withCallback };
|
||||
25
node_modules/vitest/dist/index.js
generated
vendored
Normal file
25
node_modules/vitest/dist/index.js
generated
vendored
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
export { b as bench, c as createExpect, d as describe, e as expect, i as it, s as suite, t as test } from './chunk-runtime-chain.f86e5250.js';
|
||||
import { e as dist } from './chunk-runtime-test-state.3f86f48f.js';
|
||||
export { a as afterAll, d as afterEach, f as assertType, b as beforeAll, c as beforeEach, k as getRunningMode, h as isFirstRun, l as isWatchMode, o as onTestFailed, g as runOnce, v as vi, j as vitest, w as withCallback } from './chunk-runtime-test-state.3f86f48f.js';
|
||||
import * as chai from 'chai';
|
||||
export { chai };
|
||||
export { assert, should } from 'chai';
|
||||
import 'util';
|
||||
import './chunk-typecheck-constants.ed987901.js';
|
||||
import 'path';
|
||||
import './chunk-utils-env.03f840f2.js';
|
||||
import 'tty';
|
||||
import 'url';
|
||||
import 'local-pkg';
|
||||
import './vendor-_commonjsHelpers.addc3445.js';
|
||||
import './chunk-runtime-rpc.42aebbb9.js';
|
||||
import './chunk-utils-timers.793fd179.js';
|
||||
import 'fs';
|
||||
import './chunk-utils-source-map.29ff1088.js';
|
||||
import './spy.js';
|
||||
import 'tinyspy';
|
||||
|
||||
|
||||
|
||||
var expectTypeOf = dist.expectTypeOf;
|
||||
export { expectTypeOf };
|
||||
93
node_modules/vitest/dist/loader.js
generated
vendored
Normal file
93
node_modules/vitest/dist/loader.js
generated
vendored
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import { pathToFileURL } from 'url';
|
||||
import { readFile } from 'fs/promises';
|
||||
import { i as isNodeBuiltin, n as normalizeModuleId, h as hasCJSSyntax } from './chunk-vite-node-utils.0e4a6a88.js';
|
||||
import { g as getWorkerState } from './chunk-typecheck-constants.ed987901.js';
|
||||
import 'fs';
|
||||
import './chunk-utils-env.03f840f2.js';
|
||||
import 'tty';
|
||||
import 'path';
|
||||
import 'acorn';
|
||||
import 'module';
|
||||
import 'assert';
|
||||
import 'util';
|
||||
import 'local-pkg';
|
||||
|
||||
var ModuleFormat = /* @__PURE__ */ ((ModuleFormat2) => {
|
||||
ModuleFormat2["Builtin"] = "builtin";
|
||||
ModuleFormat2["Commonjs"] = "commonjs";
|
||||
ModuleFormat2["Json"] = "json";
|
||||
ModuleFormat2["Module"] = "module";
|
||||
ModuleFormat2["Wasm"] = "wasm";
|
||||
return ModuleFormat2;
|
||||
})(ModuleFormat || {});
|
||||
|
||||
const ESM_RE = /([\s;}]|^)(import[\w,{}\s*]*from|import\s*['"*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
|
||||
function hasESMSyntax(code) {
|
||||
return ESM_RE.test(code);
|
||||
}
|
||||
const cache = /* @__PURE__ */ new Map();
|
||||
const getPotentialSource = async (filepath, result) => {
|
||||
var _a;
|
||||
if (!result.url.startsWith("file://") || result.format === "module")
|
||||
return null;
|
||||
let source = (_a = cache.get(result.url)) == null ? void 0 : _a.source;
|
||||
if (source == null)
|
||||
source = await readFile(filepath, "utf8");
|
||||
return source;
|
||||
};
|
||||
const detectESM = (url, source) => {
|
||||
const cached = cache.get(url);
|
||||
if (cached)
|
||||
return cached.isPseudoESM;
|
||||
if (!source)
|
||||
return false;
|
||||
return hasESMSyntax(source) && !hasCJSSyntax(source);
|
||||
};
|
||||
const resolve = async (url, context, next) => {
|
||||
const { parentURL } = context;
|
||||
const state = getWorkerState();
|
||||
const resolver = state == null ? void 0 : state.rpc.resolveId;
|
||||
if (!parentURL || isNodeBuiltin(url) || !resolver)
|
||||
return next(url, context, next);
|
||||
const id = normalizeModuleId(url);
|
||||
const importer = normalizeModuleId(parentURL);
|
||||
const resolved = await resolver(id, importer);
|
||||
let result;
|
||||
let filepath;
|
||||
if (resolved) {
|
||||
const resolvedUrl = pathToFileURL(resolved.id).toString();
|
||||
filepath = resolved.id;
|
||||
result = {
|
||||
url: resolvedUrl,
|
||||
shortCircuit: true
|
||||
};
|
||||
} else {
|
||||
const { url: resolvedUrl, format } = await next(url, context, next);
|
||||
filepath = new URL(resolvedUrl).pathname;
|
||||
result = {
|
||||
url: resolvedUrl,
|
||||
format,
|
||||
shortCircuit: true
|
||||
};
|
||||
}
|
||||
const source = await getPotentialSource(filepath, result);
|
||||
const isPseudoESM = detectESM(result.url, source);
|
||||
if (typeof source === "string")
|
||||
cache.set(result.url, { isPseudoESM, source });
|
||||
if (isPseudoESM)
|
||||
result.format = ModuleFormat.Module;
|
||||
return result;
|
||||
};
|
||||
const load = async (url, context, next) => {
|
||||
const result = await next(url, context, next);
|
||||
const cached = cache.get(url);
|
||||
if ((cached == null ? void 0 : cached.isPseudoESM) && result.format !== "module") {
|
||||
return {
|
||||
source: cached.source,
|
||||
format: ModuleFormat.Module
|
||||
};
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
export { load, resolve };
|
||||
71
node_modules/vitest/dist/node.d.ts
generated
vendored
Normal file
71
node_modules/vitest/dist/node.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import { j as VitestRunMode, U as UserConfig, N as Vitest, ax as ModuleCacheMap, ay as ViteNodeRunnerOptions, az as MockMap, aA as ViteNodeRunner, aB as TestSequencer } from './types-71ccd11d.js';
|
||||
export { aB as TestSequencer, aD as TestSequencerConstructor, N as Vitest, aC as startVitest } from './types-71ccd11d.js';
|
||||
import { UserConfig as UserConfig$1, Plugin } from 'vite';
|
||||
import 'tinybench';
|
||||
import 'fs';
|
||||
import 'worker_threads';
|
||||
|
||||
declare function createVitest(mode: VitestRunMode, options: UserConfig, viteOverrides?: UserConfig$1): Promise<Vitest>;
|
||||
|
||||
declare function VitestPlugin(options?: UserConfig, ctx?: Vitest): Promise<Plugin[]>;
|
||||
|
||||
type Key = string | symbol;
|
||||
interface ViteRunnerRequest {
|
||||
(dep: string): any;
|
||||
callstack: string[];
|
||||
}
|
||||
declare class VitestMocker {
|
||||
options: ExecuteOptions;
|
||||
private moduleCache;
|
||||
private request;
|
||||
private static pendingIds;
|
||||
private static spyModule?;
|
||||
private resolveCache;
|
||||
constructor(options: ExecuteOptions, moduleCache: ModuleCacheMap, request: ViteRunnerRequest);
|
||||
private get root();
|
||||
private get base();
|
||||
private get mockMap();
|
||||
getSuiteFilepath(): string;
|
||||
getMocks(): {
|
||||
[x: string]: string | (() => unknown) | null;
|
||||
};
|
||||
private resolvePath;
|
||||
private resolveMocks;
|
||||
private callFunctionMock;
|
||||
private getMockPath;
|
||||
getDependencyMock(id: string): string | (() => unknown) | null;
|
||||
normalizePath(path: string): string;
|
||||
getFsPath(path: string, external: string | null): string;
|
||||
resolveMockPath(mockPath: string, external: string | null): string | null;
|
||||
mockObject(object: Record<Key, any>, mockExports?: Record<Key, any>): Record<Key, any>;
|
||||
unmockPath(path: string): void;
|
||||
mockPath(originalId: string, path: string, external: string | null, factory?: () => any): void;
|
||||
importActual<T>(id: string, importer: string): Promise<T>;
|
||||
importMock(id: string, importer: string): Promise<any>;
|
||||
private ensureSpy;
|
||||
requestWithMock(dep: string): Promise<any>;
|
||||
queueMock(id: string, importer: string, factory?: () => unknown): void;
|
||||
queueUnmock(id: string, importer: string): void;
|
||||
}
|
||||
|
||||
interface ExecuteOptions extends ViteNodeRunnerOptions {
|
||||
mockMap: MockMap;
|
||||
}
|
||||
declare class VitestRunner extends ViteNodeRunner {
|
||||
options: ExecuteOptions;
|
||||
constructor(options: ExecuteOptions);
|
||||
prepareContext(context: Record<string, any>): Record<string, any> & {
|
||||
__vite_ssr_import__: (dep: string) => Promise<any>;
|
||||
__vite_ssr_dynamic_import__: (dep: string) => Promise<any>;
|
||||
__vitest_mocker__: VitestMocker;
|
||||
};
|
||||
}
|
||||
|
||||
declare class BaseSequencer implements TestSequencer {
|
||||
protected ctx: Vitest;
|
||||
constructor(ctx: Vitest);
|
||||
shard(files: string[]): Promise<string[]>;
|
||||
sort(files: string[]): Promise<string[]>;
|
||||
}
|
||||
|
||||
export { BaseSequencer, ExecuteOptions, VitestPlugin, VitestRunner, createVitest };
|
||||
45
node_modules/vitest/dist/node.js
generated
vendored
Normal file
45
node_modules/vitest/dist/node.js
generated
vendored
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
export { B as BaseSequencer, V as VitestPlugin, c as createVitest, s as startVitest } from './chunk-vite-node-externalize.b9495318.js';
|
||||
export { V as VitestRunner } from './chunk-runtime-mocker.99b910d0.js';
|
||||
import './chunk-utils-env.03f840f2.js';
|
||||
import 'tty';
|
||||
import 'url';
|
||||
import 'path';
|
||||
import './chunk-integrations-coverage.befed097.js';
|
||||
import 'local-pkg';
|
||||
import './chunk-env-node.67948209.js';
|
||||
import 'console';
|
||||
import './chunk-typecheck-constants.ed987901.js';
|
||||
import 'vite';
|
||||
import 'process';
|
||||
import 'fs';
|
||||
import 'os';
|
||||
import 'util';
|
||||
import 'stream';
|
||||
import 'events';
|
||||
import './vendor-_commonjsHelpers.addc3445.js';
|
||||
import './chunk-vite-node-source-map.b4ea5792.js';
|
||||
import 'module';
|
||||
import 'vm';
|
||||
import './chunk-vite-node-utils.0e4a6a88.js';
|
||||
import 'acorn';
|
||||
import 'assert';
|
||||
import 'debug';
|
||||
import './vendor-source-map-support.1ce17397.js';
|
||||
import 'source-map';
|
||||
import 'perf_hooks';
|
||||
import 'fs/promises';
|
||||
import './vendor-index.737c3cff.js';
|
||||
import 'buffer';
|
||||
import 'child_process';
|
||||
import './vendor-index.e1d4cf84.js';
|
||||
import 'acorn-walk';
|
||||
import 'worker_threads';
|
||||
import 'tinypool';
|
||||
import './chunk-utils-timers.793fd179.js';
|
||||
import './chunk-utils-source-map.29ff1088.js';
|
||||
import 'crypto';
|
||||
import './vendor-index.9c919048.js';
|
||||
import './chunk-magic-string.3a794426.js';
|
||||
import 'strip-literal';
|
||||
import 'readline';
|
||||
import './vendor-index.9f20a9be.js';
|
||||
102
node_modules/vitest/dist/spy.js
generated
vendored
Normal file
102
node_modules/vitest/dist/spy.js
generated
vendored
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import * as tinyspy from 'tinyspy';
|
||||
|
||||
const spies = /* @__PURE__ */ new Set();
|
||||
function isMockFunction(fn2) {
|
||||
return typeof fn2 === "function" && "_isMockFunction" in fn2 && fn2._isMockFunction;
|
||||
}
|
||||
function spyOn(obj, method, accessType) {
|
||||
const dictionary = {
|
||||
get: "getter",
|
||||
set: "setter"
|
||||
};
|
||||
const objMethod = accessType ? { [dictionary[accessType]]: method } : method;
|
||||
const stub = tinyspy.spyOn(obj, objMethod);
|
||||
return enhanceSpy(stub);
|
||||
}
|
||||
let callOrder = 0;
|
||||
function enhanceSpy(spy) {
|
||||
const stub = spy;
|
||||
let implementation;
|
||||
let instances = [];
|
||||
let invocations = [];
|
||||
const mockContext = {
|
||||
get calls() {
|
||||
return stub.calls;
|
||||
},
|
||||
get instances() {
|
||||
return instances;
|
||||
},
|
||||
get invocationCallOrder() {
|
||||
return invocations;
|
||||
},
|
||||
get results() {
|
||||
return stub.results.map(([callType, value]) => {
|
||||
const type = callType === "error" ? "throw" : "return";
|
||||
return { type, value };
|
||||
});
|
||||
},
|
||||
get lastCall() {
|
||||
return stub.calls[stub.calls.length - 1];
|
||||
}
|
||||
};
|
||||
let onceImplementations = [];
|
||||
let name = stub.name;
|
||||
stub.getMockName = () => name || "vi.fn()";
|
||||
stub.mockName = (n) => {
|
||||
name = n;
|
||||
return stub;
|
||||
};
|
||||
stub.mockClear = () => {
|
||||
stub.reset();
|
||||
instances = [];
|
||||
invocations = [];
|
||||
return stub;
|
||||
};
|
||||
stub.mockReset = () => {
|
||||
stub.mockClear();
|
||||
implementation = () => void 0;
|
||||
onceImplementations = [];
|
||||
return stub;
|
||||
};
|
||||
stub.mockRestore = () => {
|
||||
stub.mockReset();
|
||||
implementation = void 0;
|
||||
return stub;
|
||||
};
|
||||
stub.getMockImplementation = () => implementation;
|
||||
stub.mockImplementation = (fn2) => {
|
||||
implementation = fn2;
|
||||
return stub;
|
||||
};
|
||||
stub.mockImplementationOnce = (fn2) => {
|
||||
onceImplementations.push(fn2);
|
||||
return stub;
|
||||
};
|
||||
stub.mockReturnThis = () => stub.mockImplementation(function() {
|
||||
return this;
|
||||
});
|
||||
stub.mockReturnValue = (val) => stub.mockImplementation(() => val);
|
||||
stub.mockReturnValueOnce = (val) => stub.mockImplementationOnce(() => val);
|
||||
stub.mockResolvedValue = (val) => stub.mockImplementation(() => Promise.resolve(val));
|
||||
stub.mockResolvedValueOnce = (val) => stub.mockImplementationOnce(() => Promise.resolve(val));
|
||||
stub.mockRejectedValue = (val) => stub.mockImplementation(() => Promise.reject(val));
|
||||
stub.mockRejectedValueOnce = (val) => stub.mockImplementationOnce(() => Promise.reject(val));
|
||||
Object.defineProperty(stub, "mock", {
|
||||
get: () => mockContext
|
||||
});
|
||||
stub.willCall(function(...args) {
|
||||
instances.push(this);
|
||||
invocations.push(++callOrder);
|
||||
const impl = onceImplementations.shift() || implementation || stub.getOriginal() || (() => {
|
||||
});
|
||||
return impl.apply(this, args);
|
||||
});
|
||||
spies.add(stub);
|
||||
return stub;
|
||||
}
|
||||
function fn(implementation) {
|
||||
return enhanceSpy(tinyspy.spyOn({ fn: implementation || (() => {
|
||||
}) }, "fn"));
|
||||
}
|
||||
|
||||
export { fn, isMockFunction, spies, spyOn };
|
||||
16
node_modules/vitest/dist/suite.js
generated
vendored
Normal file
16
node_modules/vitest/dist/suite.js
generated
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import 'util';
|
||||
import 'chai';
|
||||
import './chunk-typecheck-constants.ed987901.js';
|
||||
export { b as bench, f as clearCollectorContext, q as createSuiteHooks, h as defaultSuite, d as describe, g as getCurrentSuite, i as it, s as suite, t as test } from './chunk-runtime-chain.f86e5250.js';
|
||||
import 'path';
|
||||
import './chunk-utils-env.03f840f2.js';
|
||||
import 'tty';
|
||||
import 'url';
|
||||
import 'local-pkg';
|
||||
import './vendor-_commonjsHelpers.addc3445.js';
|
||||
import './chunk-runtime-rpc.42aebbb9.js';
|
||||
import './chunk-utils-timers.793fd179.js';
|
||||
import 'fs';
|
||||
import './chunk-utils-source-map.29ff1088.js';
|
||||
import './spy.js';
|
||||
import 'tinyspy';
|
||||
2486
node_modules/vitest/dist/types-71ccd11d.d.ts
generated
vendored
Normal file
2486
node_modules/vitest/dist/types-71ccd11d.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
3
node_modules/vitest/dist/vendor-_commonjsHelpers.addc3445.js
generated
vendored
Normal file
3
node_modules/vitest/dist/vendor-_commonjsHelpers.addc3445.js
generated
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
||||
|
||||
export { commonjsGlobal as c };
|
||||
147
node_modules/vitest/dist/vendor-index.534e612c.js
generated
vendored
Normal file
147
node_modules/vitest/dist/vendor-index.534e612c.js
generated
vendored
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
import { c as commonjsGlobal } from './vendor-_commonjsHelpers.addc3445.js';
|
||||
|
||||
function _mergeNamespaces(n, m) {
|
||||
m.forEach(function (e) {
|
||||
e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
|
||||
if (k !== 'default' && !(k in n)) {
|
||||
var d = Object.getOwnPropertyDescriptor(e, k);
|
||||
Object.defineProperty(n, k, d.get ? d : {
|
||||
enumerable: true,
|
||||
get: function () { return e[k]; }
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
return Object.freeze(n);
|
||||
}
|
||||
|
||||
var eventTargetPolyfill = {};
|
||||
|
||||
const root =
|
||||
(typeof globalThis !== "undefined" && globalThis) ||
|
||||
(typeof self !== "undefined" && self) ||
|
||||
(typeof commonjsGlobal !== "undefined" && commonjsGlobal);
|
||||
|
||||
function isConstructor(fn) {
|
||||
try {
|
||||
new fn();
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof root.Event !== "function" || !isConstructor(root.Event)) {
|
||||
root.Event = (function () {
|
||||
function Event(type, options) {
|
||||
this.bubbles = !!options && !!options.bubbles;
|
||||
this.cancelable = !!options && !!options.cancelable;
|
||||
this.composed = !!options && !!options.composed;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
return Event;
|
||||
})();
|
||||
}
|
||||
|
||||
if (typeof root.EventTarget === "undefined" || !isConstructor(root.Event)) {
|
||||
root.EventTarget = (function () {
|
||||
function EventTarget() {
|
||||
this.__listeners = new Map();
|
||||
}
|
||||
|
||||
EventTarget.prototype = Object.create(Object.prototype);
|
||||
|
||||
EventTarget.prototype.addEventListener = function (
|
||||
type,
|
||||
listener,
|
||||
options
|
||||
) {
|
||||
if (arguments.length < 2) {
|
||||
throw new TypeError(
|
||||
`TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only ${arguments.length} present.`
|
||||
);
|
||||
}
|
||||
const __listeners = this.__listeners;
|
||||
const actualType = type.toString();
|
||||
if (!__listeners.has(actualType)) {
|
||||
__listeners.set(actualType, new Map());
|
||||
}
|
||||
const listenersForType = __listeners.get(actualType);
|
||||
if (!listenersForType.has(listener)) {
|
||||
// Any given listener is only registered once
|
||||
listenersForType.set(listener, options);
|
||||
}
|
||||
};
|
||||
|
||||
EventTarget.prototype.removeEventListener = function (
|
||||
type,
|
||||
listener,
|
||||
_options
|
||||
) {
|
||||
if (arguments.length < 2) {
|
||||
throw new TypeError(
|
||||
`TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only ${arguments.length} present.`
|
||||
);
|
||||
}
|
||||
const __listeners = this.__listeners;
|
||||
const actualType = type.toString();
|
||||
if (__listeners.has(actualType)) {
|
||||
const listenersForType = __listeners.get(actualType);
|
||||
if (listenersForType.has(listener)) {
|
||||
listenersForType.delete(listener);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
EventTarget.prototype.dispatchEvent = function (event) {
|
||||
if (!(event instanceof Event)) {
|
||||
throw new TypeError(
|
||||
`Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.`
|
||||
);
|
||||
}
|
||||
const type = event.type;
|
||||
const __listeners = this.__listeners;
|
||||
const listenersForType = __listeners.get(type);
|
||||
if (listenersForType) {
|
||||
for (const [listener, options] of listenersForType.entries()) {
|
||||
try {
|
||||
if (typeof listener === "function") {
|
||||
// Listener functions must be executed with the EventTarget as the `this` context.
|
||||
listener.call(this, event);
|
||||
} else if (listener && typeof listener.handleEvent === "function") {
|
||||
// Listener objects have their handleEvent method called, if they have one
|
||||
listener.handleEvent(event);
|
||||
}
|
||||
} catch (err) {
|
||||
// We need to report the error to the global error handling event,
|
||||
// but we do not want to break the loop that is executing the events.
|
||||
// Unfortunately, this is the best we can do, which isn't great, because the
|
||||
// native EventTarget will actually do this synchronously before moving to the next
|
||||
// event in the loop.
|
||||
setTimeout(() => {
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
if (options && options.once) {
|
||||
// If this was registered with { once: true }, we need
|
||||
// to remove it now.
|
||||
listenersForType.delete(listener);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Since there are no cancellable events on a base EventTarget,
|
||||
// this should always return true.
|
||||
return true;
|
||||
};
|
||||
|
||||
return EventTarget;
|
||||
})();
|
||||
}
|
||||
|
||||
var index = /*#__PURE__*/_mergeNamespaces({
|
||||
__proto__: null,
|
||||
'default': eventTargetPolyfill
|
||||
}, [eventTargetPolyfill]);
|
||||
|
||||
export { index as i };
|
||||
1070
node_modules/vitest/dist/vendor-index.737c3cff.js
generated
vendored
Normal file
1070
node_modules/vitest/dist/vendor-index.737c3cff.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
61
node_modules/vitest/dist/vendor-index.9c919048.js
generated
vendored
Normal file
61
node_modules/vitest/dist/vendor-index.9c919048.js
generated
vendored
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
var onetime$1 = {exports: {}};
|
||||
|
||||
var mimicFn$2 = {exports: {}};
|
||||
|
||||
const mimicFn$1 = (to, from) => {
|
||||
for (const prop of Reflect.ownKeys(from)) {
|
||||
Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
|
||||
}
|
||||
|
||||
return to;
|
||||
};
|
||||
|
||||
mimicFn$2.exports = mimicFn$1;
|
||||
// TODO: Remove this for the next major release
|
||||
mimicFn$2.exports.default = mimicFn$1;
|
||||
|
||||
const mimicFn = mimicFn$2.exports;
|
||||
|
||||
const calledFunctions = new WeakMap();
|
||||
|
||||
const onetime = (function_, options = {}) => {
|
||||
if (typeof function_ !== 'function') {
|
||||
throw new TypeError('Expected a function');
|
||||
}
|
||||
|
||||
let returnValue;
|
||||
let callCount = 0;
|
||||
const functionName = function_.displayName || function_.name || '<anonymous>';
|
||||
|
||||
const onetime = function (...arguments_) {
|
||||
calledFunctions.set(onetime, ++callCount);
|
||||
|
||||
if (callCount === 1) {
|
||||
returnValue = function_.apply(this, arguments_);
|
||||
function_ = null;
|
||||
} else if (options.throw === true) {
|
||||
throw new Error(`Function \`${functionName}\` can only be called once`);
|
||||
}
|
||||
|
||||
return returnValue;
|
||||
};
|
||||
|
||||
mimicFn(onetime, function_);
|
||||
calledFunctions.set(onetime, callCount);
|
||||
|
||||
return onetime;
|
||||
};
|
||||
|
||||
onetime$1.exports = onetime;
|
||||
// TODO: Remove this for the next major release
|
||||
onetime$1.exports.default = onetime;
|
||||
|
||||
onetime$1.exports.callCount = function_ => {
|
||||
if (!calledFunctions.has(function_)) {
|
||||
throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
|
||||
}
|
||||
|
||||
return calledFunctions.get(function_);
|
||||
};
|
||||
|
||||
export { onetime$1 as o };
|
||||
6291
node_modules/vitest/dist/vendor-index.9f20a9be.js
generated
vendored
Normal file
6291
node_modules/vitest/dist/vendor-index.9f20a9be.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
1065
node_modules/vitest/dist/vendor-index.e1d4cf84.js
generated
vendored
Normal file
1065
node_modules/vitest/dist/vendor-index.e1d4cf84.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
707
node_modules/vitest/dist/vendor-source-map-support.1ce17397.js
generated
vendored
Normal file
707
node_modules/vitest/dist/vendor-source-map-support.1ce17397.js
generated
vendored
Normal file
|
|
@ -0,0 +1,707 @@
|
|||
import require$$0 from 'source-map';
|
||||
import path from 'path';
|
||||
|
||||
var sourceMapSupport = {exports: {}};
|
||||
|
||||
/* eslint-disable node/no-deprecated-api */
|
||||
|
||||
var toString = Object.prototype.toString;
|
||||
|
||||
var isModern = (
|
||||
typeof Buffer !== 'undefined' &&
|
||||
typeof Buffer.alloc === 'function' &&
|
||||
typeof Buffer.allocUnsafe === 'function' &&
|
||||
typeof Buffer.from === 'function'
|
||||
);
|
||||
|
||||
function isArrayBuffer (input) {
|
||||
return toString.call(input).slice(8, -1) === 'ArrayBuffer'
|
||||
}
|
||||
|
||||
function fromArrayBuffer (obj, byteOffset, length) {
|
||||
byteOffset >>>= 0;
|
||||
|
||||
var maxLength = obj.byteLength - byteOffset;
|
||||
|
||||
if (maxLength < 0) {
|
||||
throw new RangeError("'offset' is out of bounds")
|
||||
}
|
||||
|
||||
if (length === undefined) {
|
||||
length = maxLength;
|
||||
} else {
|
||||
length >>>= 0;
|
||||
|
||||
if (length > maxLength) {
|
||||
throw new RangeError("'length' is out of bounds")
|
||||
}
|
||||
}
|
||||
|
||||
return isModern
|
||||
? Buffer.from(obj.slice(byteOffset, byteOffset + length))
|
||||
: new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
|
||||
}
|
||||
|
||||
function fromString (string, encoding) {
|
||||
if (typeof encoding !== 'string' || encoding === '') {
|
||||
encoding = 'utf8';
|
||||
}
|
||||
|
||||
if (!Buffer.isEncoding(encoding)) {
|
||||
throw new TypeError('"encoding" must be a valid string encoding')
|
||||
}
|
||||
|
||||
return isModern
|
||||
? Buffer.from(string, encoding)
|
||||
: new Buffer(string, encoding)
|
||||
}
|
||||
|
||||
function bufferFrom (value, encodingOrOffset, length) {
|
||||
if (typeof value === 'number') {
|
||||
throw new TypeError('"value" argument must not be a number')
|
||||
}
|
||||
|
||||
if (isArrayBuffer(value)) {
|
||||
return fromArrayBuffer(value, encodingOrOffset, length)
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
return fromString(value, encodingOrOffset)
|
||||
}
|
||||
|
||||
return isModern
|
||||
? Buffer.from(value)
|
||||
: new Buffer(value)
|
||||
}
|
||||
|
||||
var bufferFrom_1 = bufferFrom;
|
||||
|
||||
(function (module, exports) {
|
||||
var SourceMapConsumer = require$$0.SourceMapConsumer;
|
||||
var path$1 = path;
|
||||
|
||||
var fs;
|
||||
try {
|
||||
fs = require('fs');
|
||||
if (!fs.existsSync || !fs.readFileSync) {
|
||||
// fs doesn't have all methods we need
|
||||
fs = null;
|
||||
}
|
||||
} catch (err) {
|
||||
/* nop */
|
||||
}
|
||||
|
||||
var bufferFrom = bufferFrom_1;
|
||||
|
||||
/**
|
||||
* Requires a module which is protected against bundler minification.
|
||||
*
|
||||
* @param {NodeModule} mod
|
||||
* @param {string} request
|
||||
*/
|
||||
function dynamicRequire(mod, request) {
|
||||
return mod.require(request);
|
||||
}
|
||||
|
||||
// Only install once if called multiple times
|
||||
var errorFormatterInstalled = false;
|
||||
var uncaughtShimInstalled = false;
|
||||
|
||||
// If true, the caches are reset before a stack trace formatting operation
|
||||
var emptyCacheBetweenOperations = false;
|
||||
|
||||
// Supports {browser, node, auto}
|
||||
var environment = "auto";
|
||||
|
||||
// Maps a file path to a string containing the file contents
|
||||
var fileContentsCache = {};
|
||||
|
||||
// Maps a file path to a source map for that file
|
||||
var sourceMapCache = {};
|
||||
|
||||
// Regex for detecting source maps
|
||||
var reSourceMap = /^data:application\/json[^,]+base64,/;
|
||||
|
||||
// Priority list of retrieve handlers
|
||||
var retrieveFileHandlers = [];
|
||||
var retrieveMapHandlers = [];
|
||||
|
||||
function isInBrowser() {
|
||||
if (environment === "browser")
|
||||
return true;
|
||||
if (environment === "node")
|
||||
return false;
|
||||
return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer"));
|
||||
}
|
||||
|
||||
function hasGlobalProcessEventEmitter() {
|
||||
return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
|
||||
}
|
||||
|
||||
function globalProcessVersion() {
|
||||
if ((typeof process === 'object') && (process !== null)) {
|
||||
return process.version;
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function globalProcessStderr() {
|
||||
if ((typeof process === 'object') && (process !== null)) {
|
||||
return process.stderr;
|
||||
}
|
||||
}
|
||||
|
||||
function globalProcessExit(code) {
|
||||
if ((typeof process === 'object') && (process !== null) && (typeof process.exit === 'function')) {
|
||||
return process.exit(code);
|
||||
}
|
||||
}
|
||||
|
||||
function handlerExec(list) {
|
||||
return function(arg) {
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
var ret = list[i](arg);
|
||||
if (ret) {
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
}
|
||||
|
||||
var retrieveFile = handlerExec(retrieveFileHandlers);
|
||||
|
||||
retrieveFileHandlers.push(function(path) {
|
||||
// Trim the path to make sure there is no extra whitespace.
|
||||
path = path.trim();
|
||||
if (/^file:/.test(path)) {
|
||||
// existsSync/readFileSync can't handle file protocol, but once stripped, it works
|
||||
path = path.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) {
|
||||
return drive ?
|
||||
'' : // file:///C:/dir/file -> C:/dir/file
|
||||
'/'; // file:///root-dir/file -> /root-dir/file
|
||||
});
|
||||
}
|
||||
if (path in fileContentsCache) {
|
||||
return fileContentsCache[path];
|
||||
}
|
||||
|
||||
var contents = '';
|
||||
try {
|
||||
if (!fs) {
|
||||
// Use SJAX if we are in the browser
|
||||
var xhr = new XMLHttpRequest();
|
||||
console.trace('zdes');
|
||||
xhr.open('GET', path, /** async */ false);
|
||||
xhr.send(null);
|
||||
if (xhr.readyState === 4 && xhr.status === 200) {
|
||||
contents = xhr.responseText;
|
||||
}
|
||||
} else if (fs.existsSync(path)) {
|
||||
// Otherwise, use the filesystem
|
||||
contents = fs.readFileSync(path, 'utf8');
|
||||
}
|
||||
} catch (er) {
|
||||
/* ignore any errors */
|
||||
}
|
||||
|
||||
return fileContentsCache[path] = contents;
|
||||
});
|
||||
|
||||
// Support URLs relative to a directory, but be careful about a protocol prefix
|
||||
// in case we are in the browser (i.e. directories may start with "http://" or "file:///")
|
||||
function supportRelativeURL(file, url) {
|
||||
if (!file) return url;
|
||||
var dir = path$1.dirname(file);
|
||||
var match = /^\w+:\/\/[^\/]*/.exec(dir);
|
||||
var protocol = match ? match[0] : '';
|
||||
var startPath = dir.slice(protocol.length);
|
||||
if (protocol && /^\/\w\:/.test(startPath)) {
|
||||
// handle file:///C:/ paths
|
||||
protocol += '/';
|
||||
return protocol + path$1.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/');
|
||||
}
|
||||
return protocol + path$1.resolve(dir.slice(protocol.length), url);
|
||||
}
|
||||
|
||||
function retrieveSourceMapURL(source) {
|
||||
var fileData;
|
||||
|
||||
if (isInBrowser()) {
|
||||
try {
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('GET', source, false);
|
||||
xhr.send(null);
|
||||
fileData = xhr.readyState === 4 ? xhr.responseText : null;
|
||||
|
||||
// Support providing a sourceMappingURL via the SourceMap header
|
||||
var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
|
||||
xhr.getResponseHeader("X-SourceMap");
|
||||
if (sourceMapHeader) {
|
||||
return sourceMapHeader;
|
||||
}
|
||||
} catch (e) {
|
||||
}
|
||||
}
|
||||
|
||||
// Get the URL of the source map
|
||||
fileData = retrieveFile(source);
|
||||
var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
|
||||
// Keep executing the search to find the *last* sourceMappingURL to avoid
|
||||
// picking up sourceMappingURLs from comments, strings, etc.
|
||||
var lastMatch, match;
|
||||
while (match = re.exec(fileData)) lastMatch = match;
|
||||
if (!lastMatch) return null;
|
||||
return lastMatch[1];
|
||||
}
|
||||
// Can be overridden by the retrieveSourceMap option to install. Takes a
|
||||
// generated source filename; returns a {map, optional url} object, or null if
|
||||
// there is no source map. The map field may be either a string or the parsed
|
||||
// JSON object (ie, it must be a valid argument to the SourceMapConsumer
|
||||
// constructor).
|
||||
var retrieveSourceMap = handlerExec(retrieveMapHandlers);
|
||||
retrieveMapHandlers.push(function(source) {
|
||||
var sourceMappingURL = retrieveSourceMapURL(source);
|
||||
if (!sourceMappingURL) return null;
|
||||
|
||||
// Read the contents of the source map
|
||||
var sourceMapData;
|
||||
if (reSourceMap.test(sourceMappingURL)) {
|
||||
// Support source map URL as a data url
|
||||
var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
|
||||
sourceMapData = bufferFrom(rawData, "base64").toString();
|
||||
sourceMappingURL = source;
|
||||
} else {
|
||||
// Support source map URLs relative to the source URL
|
||||
sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
|
||||
sourceMapData = retrieveFile(sourceMappingURL);
|
||||
}
|
||||
|
||||
if (!sourceMapData) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
url: sourceMappingURL,
|
||||
map: sourceMapData
|
||||
};
|
||||
});
|
||||
|
||||
function mapSourcePosition(position) {
|
||||
var sourceMap = sourceMapCache[position.source];
|
||||
if (!sourceMap) {
|
||||
// Call the (overrideable) retrieveSourceMap function to get the source map.
|
||||
var urlAndMap = retrieveSourceMap(position.source);
|
||||
if (urlAndMap) {
|
||||
sourceMap = sourceMapCache[position.source] = {
|
||||
url: urlAndMap.url,
|
||||
map: new SourceMapConsumer(urlAndMap.map)
|
||||
};
|
||||
|
||||
// Load all sources stored inline with the source map into the file cache
|
||||
// to pretend like they are already loaded. They may not exist on disk.
|
||||
if (sourceMap.map.sourcesContent) {
|
||||
sourceMap.map.sources.forEach(function(source, i) {
|
||||
var contents = sourceMap.map.sourcesContent[i];
|
||||
if (contents) {
|
||||
var url = supportRelativeURL(sourceMap.url, source);
|
||||
fileContentsCache[url] = contents;
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
sourceMap = sourceMapCache[position.source] = {
|
||||
url: null,
|
||||
map: null
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the source URL relative to the URL of the source map
|
||||
if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') {
|
||||
var originalPosition = sourceMap.map.originalPositionFor(position);
|
||||
|
||||
// Only return the original position if a matching line was found. If no
|
||||
// matching line is found then we return position instead, which will cause
|
||||
// the stack trace to print the path and line for the compiled file. It is
|
||||
// better to give a precise location in the compiled file than a vague
|
||||
// location in the original file.
|
||||
if (originalPosition.source !== null) {
|
||||
originalPosition.source = supportRelativeURL(
|
||||
sourceMap.url, originalPosition.source);
|
||||
return originalPosition;
|
||||
}
|
||||
}
|
||||
|
||||
return position;
|
||||
}
|
||||
|
||||
// Parses code generated by FormatEvalOrigin(), a function inside V8:
|
||||
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js
|
||||
function mapEvalOrigin(origin) {
|
||||
// Most eval() calls are in this format
|
||||
var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
|
||||
if (match) {
|
||||
var position = mapSourcePosition({
|
||||
source: match[2],
|
||||
line: +match[3],
|
||||
column: match[4] - 1
|
||||
});
|
||||
return 'eval at ' + match[1] + ' (' + position.source + ':' +
|
||||
position.line + ':' + (position.column + 1) + ')';
|
||||
}
|
||||
|
||||
// Parse nested eval() calls using recursion
|
||||
match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
|
||||
if (match) {
|
||||
return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
|
||||
}
|
||||
|
||||
// Make sure we still return useful information if we didn't find anything
|
||||
return origin;
|
||||
}
|
||||
|
||||
// This is copied almost verbatim from the V8 source code at
|
||||
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
|
||||
// implementation of wrapCallSite() used to just forward to the actual source
|
||||
// code of CallSite.prototype.toString but unfortunately a new release of V8
|
||||
// did something to the prototype chain and broke the shim. The only fix I
|
||||
// could find was copy/paste.
|
||||
function CallSiteToString() {
|
||||
var fileName;
|
||||
var fileLocation = "";
|
||||
if (this.isNative()) {
|
||||
fileLocation = "native";
|
||||
} else {
|
||||
fileName = this.getScriptNameOrSourceURL();
|
||||
if (!fileName && this.isEval()) {
|
||||
fileLocation = this.getEvalOrigin();
|
||||
fileLocation += ", "; // Expecting source position to follow.
|
||||
}
|
||||
|
||||
if (fileName) {
|
||||
fileLocation += fileName;
|
||||
} else {
|
||||
// Source code does not originate from a file and is not native, but we
|
||||
// can still get the source position inside the source string, e.g. in
|
||||
// an eval string.
|
||||
fileLocation += "<anonymous>";
|
||||
}
|
||||
var lineNumber = this.getLineNumber();
|
||||
if (lineNumber != null) {
|
||||
fileLocation += ":" + lineNumber;
|
||||
var columnNumber = this.getColumnNumber();
|
||||
if (columnNumber) {
|
||||
fileLocation += ":" + columnNumber;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var line = "";
|
||||
var functionName = this.getFunctionName();
|
||||
var addSuffix = true;
|
||||
var isConstructor = this.isConstructor();
|
||||
var isMethodCall = !(this.isToplevel() || isConstructor);
|
||||
if (isMethodCall) {
|
||||
var typeName = this.getTypeName();
|
||||
// Fixes shim to be backward compatable with Node v0 to v4
|
||||
if (typeName === "[object Object]") {
|
||||
typeName = "null";
|
||||
}
|
||||
var methodName = this.getMethodName();
|
||||
if (functionName) {
|
||||
if (typeName && functionName.indexOf(typeName) != 0) {
|
||||
line += typeName + ".";
|
||||
}
|
||||
line += functionName;
|
||||
if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
|
||||
line += " [as " + methodName + "]";
|
||||
}
|
||||
} else {
|
||||
line += typeName + "." + (methodName || "<anonymous>");
|
||||
}
|
||||
} else if (isConstructor) {
|
||||
line += "new " + (functionName || "<anonymous>");
|
||||
} else if (functionName) {
|
||||
line += functionName;
|
||||
} else {
|
||||
line += fileLocation;
|
||||
addSuffix = false;
|
||||
}
|
||||
if (addSuffix) {
|
||||
line += " (" + fileLocation + ")";
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
function cloneCallSite(frame) {
|
||||
var object = {};
|
||||
Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
|
||||
object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
|
||||
});
|
||||
object.toString = CallSiteToString;
|
||||
return object;
|
||||
}
|
||||
|
||||
function wrapCallSite(frame, state) {
|
||||
// provides interface backward compatibility
|
||||
if (state === undefined) {
|
||||
state = { nextPosition: null, curPosition: null };
|
||||
}
|
||||
if(frame.isNative()) {
|
||||
state.curPosition = null;
|
||||
return frame;
|
||||
}
|
||||
|
||||
// Most call sites will return the source file from getFileName(), but code
|
||||
// passed to eval() ending in "//# sourceURL=..." will return the source file
|
||||
// from getScriptNameOrSourceURL() instead
|
||||
var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
|
||||
if (source) {
|
||||
var line = frame.getLineNumber();
|
||||
var column = frame.getColumnNumber() - 1;
|
||||
|
||||
// Fix position in Node where some (internal) code is prepended.
|
||||
// See https://github.com/evanw/node-source-map-support/issues/36
|
||||
// Header removed in node at ^10.16 || >=11.11.0
|
||||
// v11 is not an LTS candidate, we can just test the one version with it.
|
||||
// Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11
|
||||
var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
|
||||
var headerLength = noHeader.test(globalProcessVersion()) ? 0 : 62;
|
||||
if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {
|
||||
column -= headerLength;
|
||||
}
|
||||
|
||||
var position = mapSourcePosition({
|
||||
source: source,
|
||||
line: line,
|
||||
column: column
|
||||
});
|
||||
state.curPosition = position;
|
||||
frame = cloneCallSite(frame);
|
||||
var originalFunctionName = frame.getFunctionName;
|
||||
frame.getFunctionName = function() {
|
||||
if (state.nextPosition == null) {
|
||||
return originalFunctionName();
|
||||
}
|
||||
return state.nextPosition.name || originalFunctionName();
|
||||
};
|
||||
frame.getFileName = function() { return position.source; };
|
||||
frame.getLineNumber = function() { return position.line; };
|
||||
frame.getColumnNumber = function() { return position.column + 1; };
|
||||
frame.getScriptNameOrSourceURL = function() { return position.source; };
|
||||
return frame;
|
||||
}
|
||||
|
||||
// Code called using eval() needs special handling
|
||||
var origin = frame.isEval() && frame.getEvalOrigin();
|
||||
if (origin) {
|
||||
origin = mapEvalOrigin(origin);
|
||||
frame = cloneCallSite(frame);
|
||||
frame.getEvalOrigin = function() { return origin; };
|
||||
return frame;
|
||||
}
|
||||
|
||||
// If we get here then we were unable to change the source position
|
||||
return frame;
|
||||
}
|
||||
|
||||
// This function is part of the V8 stack trace API, for more info see:
|
||||
// https://v8.dev/docs/stack-trace-api
|
||||
function prepareStackTrace(error, stack) {
|
||||
if (emptyCacheBetweenOperations) {
|
||||
fileContentsCache = {};
|
||||
sourceMapCache = {};
|
||||
}
|
||||
|
||||
var name = error.name || 'Error';
|
||||
var message = error.message || '';
|
||||
var errorString = name + ": " + message;
|
||||
|
||||
var state = { nextPosition: null, curPosition: null };
|
||||
var processedStack = [];
|
||||
for (var i = stack.length - 1; i >= 0; i--) {
|
||||
processedStack.push('\n at ' + wrapCallSite(stack[i], state));
|
||||
state.nextPosition = state.curPosition;
|
||||
}
|
||||
state.curPosition = state.nextPosition = null;
|
||||
return errorString + processedStack.reverse().join('');
|
||||
}
|
||||
|
||||
// Generate position and snippet of original source with pointer
|
||||
function getErrorSource(error) {
|
||||
var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
|
||||
if (match) {
|
||||
var source = match[1];
|
||||
var line = +match[2];
|
||||
var column = +match[3];
|
||||
|
||||
// Support the inline sourceContents inside the source map
|
||||
var contents = fileContentsCache[source];
|
||||
|
||||
// Support files on disk
|
||||
if (!contents && fs && fs.existsSync(source)) {
|
||||
try {
|
||||
contents = fs.readFileSync(source, 'utf8');
|
||||
} catch (er) {
|
||||
contents = '';
|
||||
}
|
||||
}
|
||||
|
||||
// Format the line from the original source code like node does
|
||||
if (contents) {
|
||||
var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
|
||||
if (code) {
|
||||
return source + ':' + line + '\n' + code + '\n' +
|
||||
new Array(column).join(' ') + '^';
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function printErrorAndExit (error) {
|
||||
var source = getErrorSource(error);
|
||||
|
||||
// Ensure error is printed synchronously and not truncated
|
||||
var stderr = globalProcessStderr();
|
||||
if (stderr && stderr._handle && stderr._handle.setBlocking) {
|
||||
stderr._handle.setBlocking(true);
|
||||
}
|
||||
|
||||
if (source) {
|
||||
console.error();
|
||||
console.error(source);
|
||||
}
|
||||
|
||||
console.error(error.stack);
|
||||
globalProcessExit(1);
|
||||
}
|
||||
|
||||
function shimEmitUncaughtException () {
|
||||
var origEmit = process.emit;
|
||||
|
||||
process.emit = function (type) {
|
||||
if (type === 'uncaughtException') {
|
||||
var hasStack = (arguments[1] && arguments[1].stack);
|
||||
var hasListeners = (this.listeners(type).length > 0);
|
||||
|
||||
if (hasStack && !hasListeners) {
|
||||
return printErrorAndExit(arguments[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return origEmit.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
|
||||
var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0);
|
||||
var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0);
|
||||
|
||||
exports.wrapCallSite = wrapCallSite;
|
||||
exports.getErrorSource = getErrorSource;
|
||||
exports.mapSourcePosition = mapSourcePosition;
|
||||
exports.retrieveSourceMap = retrieveSourceMap;
|
||||
|
||||
exports.install = function(options) {
|
||||
options = options || {};
|
||||
|
||||
if (options.environment) {
|
||||
environment = options.environment;
|
||||
if (["node", "browser", "auto"].indexOf(environment) === -1) {
|
||||
throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}")
|
||||
}
|
||||
}
|
||||
|
||||
// Allow sources to be found by methods other than reading the files
|
||||
// directly from disk.
|
||||
if (options.retrieveFile) {
|
||||
if (options.overrideRetrieveFile) {
|
||||
retrieveFileHandlers.length = 0;
|
||||
}
|
||||
|
||||
retrieveFileHandlers.unshift(options.retrieveFile);
|
||||
}
|
||||
|
||||
// Allow source maps to be found by methods other than reading the files
|
||||
// directly from disk.
|
||||
if (options.retrieveSourceMap) {
|
||||
if (options.overrideRetrieveSourceMap) {
|
||||
retrieveMapHandlers.length = 0;
|
||||
}
|
||||
|
||||
retrieveMapHandlers.unshift(options.retrieveSourceMap);
|
||||
}
|
||||
|
||||
// Support runtime transpilers that include inline source maps
|
||||
if (options.hookRequire && !isInBrowser()) {
|
||||
// Use dynamicRequire to avoid including in browser bundles
|
||||
var Module = dynamicRequire(module, 'module');
|
||||
var $compile = Module.prototype._compile;
|
||||
|
||||
if (!$compile.__sourceMapSupport) {
|
||||
Module.prototype._compile = function(content, filename) {
|
||||
fileContentsCache[filename] = content;
|
||||
sourceMapCache[filename] = undefined;
|
||||
return $compile.call(this, content, filename);
|
||||
};
|
||||
|
||||
Module.prototype._compile.__sourceMapSupport = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Configure options
|
||||
if (!emptyCacheBetweenOperations) {
|
||||
emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
|
||||
options.emptyCacheBetweenOperations : false;
|
||||
}
|
||||
|
||||
// Install the error reformatter
|
||||
if (!errorFormatterInstalled) {
|
||||
errorFormatterInstalled = true;
|
||||
Error.prepareStackTrace = prepareStackTrace;
|
||||
}
|
||||
|
||||
if (!uncaughtShimInstalled) {
|
||||
var installHandler = 'handleUncaughtExceptions' in options ?
|
||||
options.handleUncaughtExceptions : true;
|
||||
|
||||
// Do not override 'uncaughtException' with our own handler in Node.js
|
||||
// Worker threads. Workers pass the error to the main thread as an event,
|
||||
// rather than printing something to stderr and exiting.
|
||||
try {
|
||||
// We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify.
|
||||
var worker_threads = dynamicRequire(module, 'worker_threads');
|
||||
if (worker_threads.isMainThread === false) {
|
||||
installHandler = false;
|
||||
}
|
||||
} catch(e) {}
|
||||
|
||||
// Provide the option to not install the uncaught exception handler. This is
|
||||
// to support other uncaught exception handlers (in test frameworks, for
|
||||
// example). If this handler is not installed and there are no other uncaught
|
||||
// exception handlers, uncaught exceptions will be caught by node's built-in
|
||||
// exception handler and the process will still be terminated. However, the
|
||||
// generated JavaScript code will be shown above the stack trace instead of
|
||||
// the original source code.
|
||||
if (installHandler && hasGlobalProcessEventEmitter()) {
|
||||
uncaughtShimInstalled = true;
|
||||
shimEmitUncaughtException();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.resetRetrieveHandlers = function() {
|
||||
retrieveFileHandlers.length = 0;
|
||||
retrieveMapHandlers.length = 0;
|
||||
|
||||
retrieveFileHandlers = originalRetrieveFileHandlers.slice(0);
|
||||
retrieveMapHandlers = originalRetrieveMapHandlers.slice(0);
|
||||
|
||||
retrieveSourceMap = handlerExec(retrieveMapHandlers);
|
||||
retrieveFile = handlerExec(retrieveFileHandlers);
|
||||
};
|
||||
} (sourceMapSupport, sourceMapSupport.exports));
|
||||
|
||||
export { sourceMapSupport as s };
|
||||
101
node_modules/vitest/dist/worker.js
generated
vendored
Normal file
101
node_modules/vitest/dist/worker.js
generated
vendored
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { b as resolve, e as distDir } from './chunk-utils-env.03f840f2.js';
|
||||
import { c as createBirpc, M as ModuleCacheMap } from './chunk-vite-node-source-map.b4ea5792.js';
|
||||
import { workerId } from 'tinypool';
|
||||
import { g as getWorkerState } from './chunk-typecheck-constants.ed987901.js';
|
||||
import { e as executeInViteNode } from './chunk-runtime-mocker.99b910d0.js';
|
||||
import { r as rpc } from './chunk-runtime-rpc.42aebbb9.js';
|
||||
import { p as processError } from './chunk-runtime-error.616e92ca.js';
|
||||
import 'tty';
|
||||
import 'url';
|
||||
import 'path';
|
||||
import 'module';
|
||||
import 'vm';
|
||||
import './chunk-vite-node-utils.0e4a6a88.js';
|
||||
import 'fs';
|
||||
import 'acorn';
|
||||
import 'assert';
|
||||
import 'util';
|
||||
import 'debug';
|
||||
import './vendor-source-map-support.1ce17397.js';
|
||||
import 'source-map';
|
||||
import 'local-pkg';
|
||||
import 'vite';
|
||||
import './chunk-utils-timers.793fd179.js';
|
||||
import 'chai';
|
||||
|
||||
let _viteNode;
|
||||
const moduleCache = new ModuleCacheMap();
|
||||
const mockMap = /* @__PURE__ */ new Map();
|
||||
async function startViteNode(ctx) {
|
||||
if (_viteNode)
|
||||
return _viteNode;
|
||||
const processExit = process.exit;
|
||||
process.on("beforeExit", (code) => {
|
||||
rpc().onWorkerExit(code);
|
||||
});
|
||||
process.exit = (code = process.exitCode || 0) => {
|
||||
rpc().onWorkerExit(code);
|
||||
return processExit(code);
|
||||
};
|
||||
process.on("unhandledRejection", (err) => {
|
||||
rpc().onUnhandledRejection(processError(err));
|
||||
});
|
||||
const { config } = ctx;
|
||||
const { run: run2 } = (await executeInViteNode({
|
||||
files: [
|
||||
resolve(distDir, "entry.js")
|
||||
],
|
||||
fetchModule(id) {
|
||||
return rpc().fetch(id);
|
||||
},
|
||||
resolveId(id, importer) {
|
||||
return rpc().resolveId(id, importer);
|
||||
},
|
||||
moduleCache,
|
||||
mockMap,
|
||||
interopDefault: config.deps.interopDefault ?? true,
|
||||
root: config.root,
|
||||
base: config.base
|
||||
}))[0];
|
||||
_viteNode = { run: run2 };
|
||||
return _viteNode;
|
||||
}
|
||||
function init(ctx) {
|
||||
if (typeof __vitest_worker__ !== "undefined" && ctx.config.threads && ctx.config.isolate)
|
||||
throw new Error(`worker for ${ctx.files.join(",")} already initialized by ${getWorkerState().ctx.files.join(",")}. This is probably an internal bug of Vitest.`);
|
||||
const { config, port, workerId: workerId$1 } = ctx;
|
||||
process.env.VITEST_WORKER_ID = String(workerId$1);
|
||||
process.env.VITEST_POOL_ID = String(workerId);
|
||||
globalThis.__vitest_worker__ = {
|
||||
ctx,
|
||||
moduleCache,
|
||||
config,
|
||||
mockMap,
|
||||
rpc: createBirpc(
|
||||
{},
|
||||
{
|
||||
eventNames: ["onUserConsoleLog", "onFinished", "onCollected", "onWorkerExit"],
|
||||
post(v) {
|
||||
port.postMessage(v);
|
||||
},
|
||||
on(fn) {
|
||||
port.addListener("message", fn);
|
||||
}
|
||||
}
|
||||
)
|
||||
};
|
||||
if (ctx.invalidates) {
|
||||
ctx.invalidates.forEach((fsPath) => {
|
||||
moduleCache.delete(fsPath);
|
||||
moduleCache.delete(`mock:${fsPath}`);
|
||||
});
|
||||
}
|
||||
ctx.files.forEach((i) => moduleCache.delete(i));
|
||||
}
|
||||
async function run(ctx) {
|
||||
init(ctx);
|
||||
const { run: run2 } = await startViteNode(ctx);
|
||||
return run2(ctx.files, ctx.config);
|
||||
}
|
||||
|
||||
export { run };
|
||||
Loading…
Add table
Add a link
Reference in a new issue