@shopify/create-app
Version:
A CLI tool to create a new Shopify app.
11,301 lines • 522 kB
JavaScript
import {
__commonJS,
__export,
__toESM,
init_cjs_shims
} from "./chunk-3XNI6LP4.js";
// ../../node_modules/.pnpm/expect-type@1.4.0/node_modules/expect-type/dist/branding.js
var require_branding = __commonJS({
"../../node_modules/.pnpm/expect-type@1.4.0/node_modules/expect-type/dist/branding.js"(exports) {
"use strict";
init_cjs_shims();
Object.defineProperty(exports, "__esModule", { value: !0 });
}
});
// ../../node_modules/.pnpm/expect-type@1.4.0/node_modules/expect-type/dist/messages.js
var require_messages = __commonJS({
"../../node_modules/.pnpm/expect-type@1.4.0/node_modules/expect-type/dist/messages.js"(exports) {
"use strict";
init_cjs_shims();
Object.defineProperty(exports, "__esModule", { value: !0 });
}
});
// ../../node_modules/.pnpm/expect-type@1.4.0/node_modules/expect-type/dist/overloads.js
var require_overloads = __commonJS({
"../../node_modules/.pnpm/expect-type@1.4.0/node_modules/expect-type/dist/overloads.js"(exports) {
"use strict";
init_cjs_shims();
Object.defineProperty(exports, "__esModule", { value: !0 });
}
});
// ../../node_modules/.pnpm/expect-type@1.4.0/node_modules/expect-type/dist/utils.js
var require_utils = __commonJS({
"../../node_modules/.pnpm/expect-type@1.4.0/node_modules/expect-type/dist/utils.js"(exports) {
"use strict";
init_cjs_shims();
Object.defineProperty(exports, "__esModule", { value: !0 });
}
});
// ../../node_modules/.pnpm/expect-type@1.4.0/node_modules/expect-type/dist/index.js
var require_dist = __commonJS({
"../../node_modules/.pnpm/expect-type@1.4.0/node_modules/expect-type/dist/index.js"(exports) {
"use strict";
init_cjs_shims();
var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
k2 === void 0 && (k2 = k);
var desc = Object.getOwnPropertyDescriptor(m, k);
(!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) && (desc = { enumerable: !0, get: function() {
return m[k];
} }), Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
k2 === void 0 && (k2 = k), o[k2] = m[k];
})), __exportStar = exports && exports.__exportStar || function(m, exports2) {
for (var p in m) p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p) && __createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", { value: !0 });
exports.expectTypeOf = void 0;
__exportStar(require_branding(), exports);
__exportStar(require_messages(), exports);
__exportStar(require_overloads(), exports);
__exportStar(require_utils(), exports);
var fn2 = () => !0, expectTypeOf2 = (_actual) => {
let nonFunctionProperties = [
"parameters",
"returns",
"resolves",
"not",
"items",
"constructorParameters",
"thisParameter",
"instance",
"guards",
"asserts"
];
function createBranded() {
return {
inspect: () => !0,
configure: () => createBranded(),
toEqualTypeOf: fn2
};
}
let obj = {
toBeAny: fn2,
toBeUnknown: fn2,
toBeNever: fn2,
toBeFunction: fn2,
toBeObject: fn2,
toBeArray: fn2,
toBeString: fn2,
toBeNumber: fn2,
toBeBoolean: fn2,
toBeVoid: fn2,
toBeSymbol: fn2,
toBeNull: fn2,
toBeUndefined: fn2,
toBeNullable: fn2,
toBeBigInt: fn2,
toMatchTypeOf: fn2,
toEqualTypeOf: fn2,
toBeConstructibleWith: fn2,
toMatchObjectType: fn2,
toExtend: fn2,
map: exports.expectTypeOf,
toBeCallableWith: exports.expectTypeOf,
extract: exports.expectTypeOf,
exclude: exports.expectTypeOf,
pick: exports.expectTypeOf,
omit: exports.expectTypeOf,
toHaveProperty: exports.expectTypeOf,
parameter: exports.expectTypeOf,
get branded() {
return createBranded();
}
};
return nonFunctionProperties.forEach((prop) => Object.defineProperty(obj, prop, { get: () => (0, exports.expectTypeOf)({}) })), obj;
};
exports.expectTypeOf = expectTypeOf2;
}
});
// src/index.test.ts
init_cjs_shims();
// ../../node_modules/.pnpm/vitest@4.1.10_@opentelemetry+api@1.9.1_@types+node@22.20.1_@vitest+coverage-istanbul@3._f51dec9f55339d6c09addddd62782db2/node_modules/vitest/dist/index.js
init_cjs_shims();
// ../../node_modules/.pnpm/vitest@4.1.10_@opentelemetry+api@1.9.1_@types+node@22.20.1_@vitest+coverage-istanbul@3._f51dec9f55339d6c09addddd62782db2/node_modules/vitest/dist/chunks/test.DNmyFkvJ.js
init_cjs_shims();
// ../../node_modules/.pnpm/@vitest+runner@4.1.10/node_modules/@vitest/runner/dist/index.js
init_cjs_shims();
// ../../node_modules/.pnpm/@vitest+runner@4.1.10/node_modules/@vitest/runner/dist/chunk-artifact.js
init_cjs_shims();
// ../../node_modules/.pnpm/@vitest+utils@4.1.10/node_modules/@vitest/utils/dist/error.js
init_cjs_shims();
// ../../node_modules/.pnpm/@vitest+pretty-format@4.1.10/node_modules/@vitest/pretty-format/dist/index.js
init_cjs_shims();
// ../../node_modules/.pnpm/tinyrainbow@3.1.0/node_modules/tinyrainbow/dist/index.js
init_cjs_shims();
var b = {
reset: [0, 0],
bold: [1, 22, "\x1B[22m\x1B[1m"],
dim: [2, 22, "\x1B[22m\x1B[2m"],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
blackBright: [90, 39],
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39],
bgBlackBright: [100, 49],
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
};
function i(e) {
return String(e);
}
i.open = "";
i.close = "";
function B() {
let e = typeof process < "u" ? process : void 0, r = e?.env || {}, a = r.FORCE_TTY !== "false", l = e?.argv || [];
return !("NO_COLOR" in r || l.includes("--no-color")) && ("FORCE_COLOR" in r || l.includes("--color") || e?.platform === "win32" || a && r.TERM !== "dumb" || "CI" in r) || typeof window < "u" && !!window.chrome;
}
function C({ force: e } = {}) {
let r = e || B(), a = (t, o, u, n) => {
let g = "", s = 0;
do
g += t.substring(s, n) + u, s = n + o.length, n = t.indexOf(o, s);
while (~n);
return g + t.substring(s);
}, l = (t, o, u = t) => {
let n = (g) => {
let s = String(g), h = s.indexOf(o, t.length);
return ~h ? t + a(s, o, u, h) + o : t + s + o;
};
return n.open = t, n.close = o, n;
}, c = {
isColorSupported: r
}, f = (t) => `\x1B[${t}m`;
for (let t in b) {
let o = b[t];
c[t] = r ? l(
f(o[0]),
f(o[1]),
o[2]
) : i;
}
return c;
}
var d = C();
var y = d;
// ../../node_modules/.pnpm/@vitest+pretty-format@4.1.10/node_modules/@vitest/pretty-format/dist/index.js
function _mergeNamespaces(n, m) {
return m.forEach(function(e) {
e && typeof e != "string" && !Array.isArray(e) && Object.keys(e).forEach(function(k) {
if (k !== "default" && !(k in n)) {
var d2 = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d2.get ? d2 : {
enumerable: !0,
get: function() {
return e[k];
}
});
}
});
}), Object.freeze(n);
}
function getKeysOfEnumerableProperties(object2, compareKeys) {
let rawKeys = Object.keys(object2), keys2 = compareKeys === null ? rawKeys : rawKeys.sort(compareKeys);
if (Object.getOwnPropertySymbols)
for (let symbol of Object.getOwnPropertySymbols(object2))
Object.getOwnPropertyDescriptor(object2, symbol).enumerable && keys2.push(symbol);
return keys2;
}
function printIteratorEntries(iterator, config2, indentation, depth, refs, printer2, separator = ": ") {
let result = "", width = 0, current = iterator.next();
if (!current.done) {
result += config2.spacingOuter;
let indentationNext = indentation + config2.indent;
for (; !current.done; ) {
if (result += indentationNext, width++ === config2.maxWidth) {
result += "\u2026";
break;
}
let name = printer2(current.value[0], config2, indentationNext, depth, refs), value = printer2(current.value[1], config2, indentationNext, depth, refs);
result += name + separator + value, current = iterator.next(), current.done ? config2.min || (result += ",") : result += `,${config2.spacingInner}`;
}
result += config2.spacingOuter + indentation;
}
return result;
}
function printIteratorValues(iterator, config2, indentation, depth, refs, printer2) {
let result = "", width = 0, current = iterator.next();
if (!current.done) {
result += config2.spacingOuter;
let indentationNext = indentation + config2.indent;
for (; !current.done; ) {
if (result += indentationNext, width++ === config2.maxWidth) {
result += "\u2026";
break;
}
result += printer2(current.value, config2, indentationNext, depth, refs), current = iterator.next(), current.done ? config2.min || (result += ",") : result += `,${config2.spacingInner}`;
}
result += config2.spacingOuter + indentation;
}
return result;
}
function printListItems(list, config2, indentation, depth, refs, printer2) {
let result = "";
list = list instanceof ArrayBuffer ? new DataView(list) : list;
let isDataView = (l) => l instanceof DataView, length = isDataView(list) ? list.byteLength : list.length;
if (length > 0) {
result += config2.spacingOuter;
let indentationNext = indentation + config2.indent;
for (let i2 = 0; i2 < length; i2++) {
if (result += indentationNext, i2 === config2.maxWidth) {
result += "\u2026";
break;
}
(isDataView(list) || i2 in list) && (result += printer2(isDataView(list) ? list.getInt8(i2) : list[i2], config2, indentationNext, depth, refs)), i2 < length - 1 ? result += `,${config2.spacingInner}` : config2.min || (result += ",");
}
result += config2.spacingOuter + indentation;
}
return result;
}
function printObjectProperties(val, config2, indentation, depth, refs, printer2) {
let result = "", keys2 = getKeysOfEnumerableProperties(val, config2.compareKeys);
if (keys2.length > 0) {
result += config2.spacingOuter;
let indentationNext = indentation + config2.indent;
for (let i2 = 0; i2 < keys2.length; i2++) {
let key = keys2[i2], name = printer2(key, config2, indentationNext, depth, refs), value = printer2(val[key], config2, indentationNext, depth, refs);
result += `${indentationNext + name}: ${value}`, i2 < keys2.length - 1 ? result += `,${config2.spacingInner}` : config2.min || (result += ",");
}
result += config2.spacingOuter + indentation;
}
return result;
}
var asymmetricMatcher = typeof Symbol == "function" && Symbol.for ? /* @__PURE__ */ Symbol.for("jest.asymmetricMatcher") : 1267621, SPACE$2 = " ", serialize$5 = (val, config2, indentation, depth, refs, printer2) => {
let stringedValue = val.toString();
if (stringedValue === "ArrayContaining" || stringedValue === "ArrayNotContaining")
return ++depth > config2.maxDepth ? `[${stringedValue}]` : `${stringedValue + SPACE$2}[${printListItems(val.sample, config2, indentation, depth, refs, printer2)}]`;
if (stringedValue === "ObjectContaining" || stringedValue === "ObjectNotContaining")
return ++depth > config2.maxDepth ? `[${stringedValue}]` : `${stringedValue + SPACE$2}{${printObjectProperties(val.sample, config2, indentation, depth, refs, printer2)}}`;
if (stringedValue === "StringMatching" || stringedValue === "StringNotMatching" || stringedValue === "StringContaining" || stringedValue === "StringNotContaining")
return stringedValue + SPACE$2 + printer2(val.sample, config2, indentation, depth, refs);
if (typeof val.toAsymmetricMatcher != "function")
throw new TypeError(`Asymmetric matcher ${val.constructor.name} does not implement toAsymmetricMatcher()`);
return val.toAsymmetricMatcher();
}, test$5 = (val) => val && val.$$typeof === asymmetricMatcher, plugin$5 = {
serialize: serialize$5,
test: test$5
}, SPACE$1 = " ", OBJECT_NAMES = /* @__PURE__ */ new Set(["DOMStringMap", "NamedNodeMap"]), ARRAY_REGEXP = /^(?:HTML\w*Collection|NodeList)$/;
function testName(name) {
return OBJECT_NAMES.has(name) || ARRAY_REGEXP.test(name);
}
var test$4 = (val) => val && val.constructor && !!val.constructor.name && testName(val.constructor.name);
function isNamedNodeMap(collection) {
return collection.constructor.name === "NamedNodeMap";
}
var serialize$4 = (collection, config2, indentation, depth, refs, printer2) => {
let name = collection.constructor.name;
return ++depth > config2.maxDepth ? `[${name}]` : (config2.min ? "" : name + SPACE$1) + (OBJECT_NAMES.has(name) ? `{${printObjectProperties(isNamedNodeMap(collection) ? [...collection].reduce((props, attribute) => (props[attribute.name] = attribute.value, props), {}) : { ...collection }, config2, indentation, depth, refs, printer2)}}` : `[${printListItems([...collection], config2, indentation, depth, refs, printer2)}]`);
}, plugin$4 = {
serialize: serialize$4,
test: test$4
};
function escapeHTML(str) {
return str.replaceAll("<", "<").replaceAll(">", ">");
}
function printProps(keys2, props, config2, indentation, depth, refs, printer2) {
let indentationNext = indentation + config2.indent, colors = config2.colors;
return keys2.map((key) => {
let value = props[key];
if (typeof value == "string" && value[0] === "_" && value.startsWith("__vitest_") && value.match(/__vitest_\d+__/))
return "";
let printed = printer2(value, config2, indentationNext, depth, refs);
return typeof value != "string" && (printed.includes(`
`) && (printed = config2.spacingOuter + indentationNext + printed + config2.spacingOuter + indentation), printed = `{${printed}}`), `${config2.spacingInner + indentation + colors.prop.open + key + colors.prop.close}=${colors.value.open}${printed}${colors.value.close}`;
}).join("");
}
function printChildren(children, config2, indentation, depth, refs, printer2) {
return children.map((child) => config2.spacingOuter + indentation + (typeof child == "string" ? printText(child, config2) : printer2(child, config2, indentation, depth, refs))).join("");
}
function printShadowRoot(children, config2, indentation, depth, refs, printer2) {
return config2.printShadowRoot === !1 ? "" : [`${config2.spacingOuter + indentation}#shadow-root`, printChildren(children, config2, indentation + config2.indent, depth, refs, printer2)].join("");
}
function printText(text, config2) {
let contentColor = config2.colors.content;
return contentColor.open + escapeHTML(text) + contentColor.close;
}
function printComment(comment, config2) {
let commentColor = config2.colors.comment;
return `${commentColor.open}<!--${escapeHTML(comment)}-->${commentColor.close}`;
}
function printElement(type3, printedProps, printedChildren, config2, indentation) {
let tagColor = config2.colors.tag;
return `${tagColor.open}<${type3}${printedProps && tagColor.close + printedProps + config2.spacingOuter + indentation + tagColor.open}${printedChildren ? `>${tagColor.close}${printedChildren}${config2.spacingOuter}${indentation}${tagColor.open}</${type3}` : `${printedProps && !config2.min ? "" : " "}/`}>${tagColor.close}`;
}
function printElementAsLeaf(type3, config2) {
let tagColor = config2.colors.tag;
return `${tagColor.open}<${type3}${tagColor.close} \u2026${tagColor.open} />${tagColor.close}`;
}
var ELEMENT_NODE = 1, TEXT_NODE = 3, COMMENT_NODE = 8, FRAGMENT_NODE = 11, ELEMENT_REGEXP = /^(?:(?:HTML|SVG)\w*)?Element$/;
function testHasAttribute(val) {
try {
return typeof val.hasAttribute == "function" && val.hasAttribute("is");
} catch {
return !1;
}
}
function testNode(val) {
let constructorName = val.constructor.name, { nodeType, tagName } = val, isCustomElement = typeof tagName == "string" && tagName.includes("-") || testHasAttribute(val);
return nodeType === ELEMENT_NODE && (ELEMENT_REGEXP.test(constructorName) || isCustomElement) || nodeType === TEXT_NODE && constructorName === "Text" || nodeType === COMMENT_NODE && constructorName === "Comment" || nodeType === FRAGMENT_NODE && constructorName === "DocumentFragment";
}
var test$3 = (val) => val?.constructor?.name && testNode(val);
function nodeIsText(node) {
return node.nodeType === TEXT_NODE;
}
function nodeIsComment(node) {
return node.nodeType === COMMENT_NODE;
}
function nodeIsFragment(node) {
return node.nodeType === FRAGMENT_NODE;
}
function filterChildren(children, filterNode) {
let filtered = children.filter((node) => node.nodeType === TEXT_NODE ? (node.data || "").trim().length > 0 : !0);
return filterNode && (filtered = filtered.filter(filterNode)), filtered;
}
function serializeDOM(node, config2, indentation, depth, refs, printer2, filterNode) {
if (nodeIsText(node))
return printText(node.data, config2);
if (nodeIsComment(node))
return printComment(node.data, config2);
let type3 = nodeIsFragment(node) ? "DocumentFragment" : node.tagName.toLowerCase();
if (++depth > config2.maxDepth)
return printElementAsLeaf(type3, config2);
let children = Array.prototype.slice.call(node.childNodes || node.children), shadowChildren = nodeIsFragment(node) || !node.shadowRoot ? [] : Array.prototype.slice.call(node.shadowRoot.children), resolvedChildren = filterNode ? filterChildren(children, filterNode) : children, resolvedShadowChildren = filterNode ? filterChildren(shadowChildren, filterNode) : shadowChildren;
return printElement(type3, printProps(nodeIsFragment(node) ? [] : Array.from(node.attributes, (attr) => attr.name).sort(), nodeIsFragment(node) ? {} : [...node.attributes].reduce((props, attribute) => (props[attribute.name] = attribute.value, props), {}), config2, indentation + config2.indent, depth, refs, printer2), (resolvedShadowChildren.length > 0 ? printShadowRoot(resolvedShadowChildren, config2, indentation + config2.indent, depth, refs, printer2) : "") + printChildren(resolvedChildren, config2, indentation + config2.indent, depth, refs, printer2), config2, indentation);
}
var serialize$3 = (node, config2, indentation, depth, refs, printer2) => serializeDOM(node, config2, indentation, depth, refs, printer2);
function createDOMElementFilter(filterNode) {
return {
test: test$3,
serialize: (node, config2, indentation, depth, refs, printer2) => serializeDOM(node, config2, indentation, depth, refs, printer2, filterNode)
};
}
var plugin$3 = {
serialize: serialize$3,
test: test$3
}, IS_ITERABLE_SENTINEL = "@@__IMMUTABLE_ITERABLE__@@", IS_LIST_SENTINEL = "@@__IMMUTABLE_LIST__@@", IS_KEYED_SENTINEL = "@@__IMMUTABLE_KEYED__@@", IS_MAP_SENTINEL = "@@__IMMUTABLE_MAP__@@", IS_ORDERED_SENTINEL = "@@__IMMUTABLE_ORDERED__@@", IS_RECORD_SENTINEL = "@@__IMMUTABLE_RECORD__@@", IS_SEQ_SENTINEL = "@@__IMMUTABLE_SEQ__@@", IS_SET_SENTINEL = "@@__IMMUTABLE_SET__@@", IS_STACK_SENTINEL = "@@__IMMUTABLE_STACK__@@", getImmutableName = (name) => `Immutable.${name}`, printAsLeaf = (name) => `[${name}]`, SPACE = " ", LAZY = "\u2026";
function printImmutableEntries(val, config2, indentation, depth, refs, printer2, type3) {
return ++depth > config2.maxDepth ? printAsLeaf(getImmutableName(type3)) : `${getImmutableName(type3) + SPACE}{${printIteratorEntries(val.entries(), config2, indentation, depth, refs, printer2)}}`;
}
function getRecordEntries(val) {
let i2 = 0;
return { next() {
if (i2 < val._keys.length) {
let key = val._keys[i2++];
return {
done: !1,
value: [key, val.get(key)]
};
}
return {
done: !0,
value: void 0
};
} };
}
function printImmutableRecord(val, config2, indentation, depth, refs, printer2) {
let name = getImmutableName(val._name || "Record");
return ++depth > config2.maxDepth ? printAsLeaf(name) : `${name + SPACE}{${printIteratorEntries(getRecordEntries(val), config2, indentation, depth, refs, printer2)}}`;
}
function printImmutableSeq(val, config2, indentation, depth, refs, printer2) {
let name = getImmutableName("Seq");
return ++depth > config2.maxDepth ? printAsLeaf(name) : val[IS_KEYED_SENTINEL] ? `${name + SPACE}{${val._iter || val._object ? printIteratorEntries(val.entries(), config2, indentation, depth, refs, printer2) : LAZY}}` : `${name + SPACE}[${val._iter || val._array || val._collection || val._iterable ? printIteratorValues(val.values(), config2, indentation, depth, refs, printer2) : LAZY}]`;
}
function printImmutableValues(val, config2, indentation, depth, refs, printer2, type3) {
return ++depth > config2.maxDepth ? printAsLeaf(getImmutableName(type3)) : `${getImmutableName(type3) + SPACE}[${printIteratorValues(val.values(), config2, indentation, depth, refs, printer2)}]`;
}
var serialize$2 = (val, config2, indentation, depth, refs, printer2) => val[IS_MAP_SENTINEL] ? printImmutableEntries(val, config2, indentation, depth, refs, printer2, val[IS_ORDERED_SENTINEL] ? "OrderedMap" : "Map") : val[IS_LIST_SENTINEL] ? printImmutableValues(val, config2, indentation, depth, refs, printer2, "List") : val[IS_SET_SENTINEL] ? printImmutableValues(val, config2, indentation, depth, refs, printer2, val[IS_ORDERED_SENTINEL] ? "OrderedSet" : "Set") : val[IS_STACK_SENTINEL] ? printImmutableValues(val, config2, indentation, depth, refs, printer2, "Stack") : val[IS_SEQ_SENTINEL] ? printImmutableSeq(val, config2, indentation, depth, refs, printer2) : printImmutableRecord(val, config2, indentation, depth, refs, printer2), test$2 = (val) => val && (val[IS_ITERABLE_SENTINEL] === !0 || val[IS_RECORD_SENTINEL] === !0), plugin$2 = {
serialize: serialize$2,
test: test$2
};
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x.default : x;
}
var reactIs$1 = { exports: {} }, reactIs_production = {};
var hasRequiredReactIs_production;
function requireReactIs_production() {
if (hasRequiredReactIs_production) return reactIs_production;
hasRequiredReactIs_production = 1;
var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_VIEW_TRANSITION_TYPE = /* @__PURE__ */ Symbol.for("react.view_transition"), REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference");
function typeOf2(object2) {
if (typeof object2 == "object" && object2 !== null) {
var $$typeof = object2.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
switch (object2 = object2.type, object2) {
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
case REACT_SUSPENSE_LIST_TYPE:
case REACT_VIEW_TRANSITION_TYPE:
return object2;
default:
switch (object2 = object2 && object2.$$typeof, object2) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
return object2;
case REACT_CONSUMER_TYPE:
return object2;
default:
return $$typeof;
}
}
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
}
return reactIs_production.ContextConsumer = REACT_CONSUMER_TYPE, reactIs_production.ContextProvider = REACT_CONTEXT_TYPE, reactIs_production.Element = REACT_ELEMENT_TYPE, reactIs_production.ForwardRef = REACT_FORWARD_REF_TYPE, reactIs_production.Fragment = REACT_FRAGMENT_TYPE, reactIs_production.Lazy = REACT_LAZY_TYPE, reactIs_production.Memo = REACT_MEMO_TYPE, reactIs_production.Portal = REACT_PORTAL_TYPE, reactIs_production.Profiler = REACT_PROFILER_TYPE, reactIs_production.StrictMode = REACT_STRICT_MODE_TYPE, reactIs_production.Suspense = REACT_SUSPENSE_TYPE, reactIs_production.SuspenseList = REACT_SUSPENSE_LIST_TYPE, reactIs_production.isContextConsumer = function(object2) {
return typeOf2(object2) === REACT_CONSUMER_TYPE;
}, reactIs_production.isContextProvider = function(object2) {
return typeOf2(object2) === REACT_CONTEXT_TYPE;
}, reactIs_production.isElement = function(object2) {
return typeof object2 == "object" && object2 !== null && object2.$$typeof === REACT_ELEMENT_TYPE;
}, reactIs_production.isForwardRef = function(object2) {
return typeOf2(object2) === REACT_FORWARD_REF_TYPE;
}, reactIs_production.isFragment = function(object2) {
return typeOf2(object2) === REACT_FRAGMENT_TYPE;
}, reactIs_production.isLazy = function(object2) {
return typeOf2(object2) === REACT_LAZY_TYPE;
}, reactIs_production.isMemo = function(object2) {
return typeOf2(object2) === REACT_MEMO_TYPE;
}, reactIs_production.isPortal = function(object2) {
return typeOf2(object2) === REACT_PORTAL_TYPE;
}, reactIs_production.isProfiler = function(object2) {
return typeOf2(object2) === REACT_PROFILER_TYPE;
}, reactIs_production.isStrictMode = function(object2) {
return typeOf2(object2) === REACT_STRICT_MODE_TYPE;
}, reactIs_production.isSuspense = function(object2) {
return typeOf2(object2) === REACT_SUSPENSE_TYPE;
}, reactIs_production.isSuspenseList = function(object2) {
return typeOf2(object2) === REACT_SUSPENSE_LIST_TYPE;
}, reactIs_production.isValidElementType = function(type3) {
return typeof type3 == "string" || typeof type3 == "function" || type3 === REACT_FRAGMENT_TYPE || type3 === REACT_PROFILER_TYPE || type3 === REACT_STRICT_MODE_TYPE || type3 === REACT_SUSPENSE_TYPE || type3 === REACT_SUSPENSE_LIST_TYPE || typeof type3 == "object" && type3 !== null && (type3.$$typeof === REACT_LAZY_TYPE || type3.$$typeof === REACT_MEMO_TYPE || type3.$$typeof === REACT_CONTEXT_TYPE || type3.$$typeof === REACT_CONSUMER_TYPE || type3.$$typeof === REACT_FORWARD_REF_TYPE || type3.$$typeof === REACT_CLIENT_REFERENCE || type3.getModuleId !== void 0);
}, reactIs_production.typeOf = typeOf2, reactIs_production;
}
var hasRequiredReactIs$1;
function requireReactIs$1() {
return hasRequiredReactIs$1 || (hasRequiredReactIs$1 = 1, reactIs$1.exports = requireReactIs_production()), reactIs$1.exports;
}
var reactIsExports$1 = requireReactIs$1(), index$1 = /* @__PURE__ */ getDefaultExportFromCjs(reactIsExports$1), ReactIs19 = /* @__PURE__ */ _mergeNamespaces({
__proto__: null,
default: index$1
}, [reactIsExports$1]), reactIs = { exports: {} }, reactIs_production_min = {};
var hasRequiredReactIs_production_min;
function requireReactIs_production_min() {
if (hasRequiredReactIs_production_min) return reactIs_production_min;
hasRequiredReactIs_production_min = 1;
var b2 = /* @__PURE__ */ Symbol.for("react.element"), c = /* @__PURE__ */ Symbol.for("react.portal"), d2 = /* @__PURE__ */ Symbol.for("react.fragment"), e = /* @__PURE__ */ Symbol.for("react.strict_mode"), f = /* @__PURE__ */ Symbol.for("react.profiler"), g = /* @__PURE__ */ Symbol.for("react.provider"), h = /* @__PURE__ */ Symbol.for("react.context"), k = /* @__PURE__ */ Symbol.for("react.server_context"), l = /* @__PURE__ */ Symbol.for("react.forward_ref"), m = /* @__PURE__ */ Symbol.for("react.suspense"), n = /* @__PURE__ */ Symbol.for("react.suspense_list"), p = /* @__PURE__ */ Symbol.for("react.memo"), q = /* @__PURE__ */ Symbol.for("react.lazy"), t = /* @__PURE__ */ Symbol.for("react.offscreen"), u;
u = /* @__PURE__ */ Symbol.for("react.module.reference");
function v(a) {
if (typeof a == "object" && a !== null) {
var r = a.$$typeof;
switch (r) {
case b2:
switch (a = a.type, a) {
case d2:
case f:
case e:
case m:
case n:
return a;
default:
switch (a = a && a.$$typeof, a) {
case k:
case h:
case l:
case q:
case p:
case g:
return a;
default:
return r;
}
}
case c:
return r;
}
}
}
return reactIs_production_min.ContextConsumer = h, reactIs_production_min.ContextProvider = g, reactIs_production_min.Element = b2, reactIs_production_min.ForwardRef = l, reactIs_production_min.Fragment = d2, reactIs_production_min.Lazy = q, reactIs_production_min.Memo = p, reactIs_production_min.Portal = c, reactIs_production_min.Profiler = f, reactIs_production_min.StrictMode = e, reactIs_production_min.Suspense = m, reactIs_production_min.SuspenseList = n, reactIs_production_min.isAsyncMode = function() {
return !1;
}, reactIs_production_min.isConcurrentMode = function() {
return !1;
}, reactIs_production_min.isContextConsumer = function(a) {
return v(a) === h;
}, reactIs_production_min.isContextProvider = function(a) {
return v(a) === g;
}, reactIs_production_min.isElement = function(a) {
return typeof a == "object" && a !== null && a.$$typeof === b2;
}, reactIs_production_min.isForwardRef = function(a) {
return v(a) === l;
}, reactIs_production_min.isFragment = function(a) {
return v(a) === d2;
}, reactIs_production_min.isLazy = function(a) {
return v(a) === q;
}, reactIs_production_min.isMemo = function(a) {
return v(a) === p;
}, reactIs_production_min.isPortal = function(a) {
return v(a) === c;
}, reactIs_production_min.isProfiler = function(a) {
return v(a) === f;
}, reactIs_production_min.isStrictMode = function(a) {
return v(a) === e;
}, reactIs_production_min.isSuspense = function(a) {
return v(a) === m;
}, reactIs_production_min.isSuspenseList = function(a) {
return v(a) === n;
}, reactIs_production_min.isValidElementType = function(a) {
return typeof a == "string" || typeof a == "function" || a === d2 || a === f || a === e || a === m || a === n || a === t || typeof a == "object" && a !== null && (a.$$typeof === q || a.$$typeof === p || a.$$typeof === g || a.$$typeof === h || a.$$typeof === l || a.$$typeof === u || a.getModuleId !== void 0);
}, reactIs_production_min.typeOf = v, reactIs_production_min;
}
var hasRequiredReactIs;
function requireReactIs() {
return hasRequiredReactIs || (hasRequiredReactIs = 1, reactIs.exports = requireReactIs_production_min()), reactIs.exports;
}
var reactIsExports = requireReactIs(), index = /* @__PURE__ */ getDefaultExportFromCjs(reactIsExports), ReactIs18 = /* @__PURE__ */ _mergeNamespaces({
__proto__: null,
default: index
}, [reactIsExports]), reactIsMethods = [
"isAsyncMode",
"isConcurrentMode",
"isContextConsumer",
"isContextProvider",
"isElement",
"isForwardRef",
"isFragment",
"isLazy",
"isMemo",
"isPortal",
"isProfiler",
"isStrictMode",
"isSuspense",
"isSuspenseList",
"isValidElementType"
], ReactIs = Object.fromEntries(reactIsMethods.map((m) => [m, (v) => ReactIs18[m](v) || ReactIs19[m](v)]));
function getChildren(arg, children = []) {
if (Array.isArray(arg))
for (let item of arg)
getChildren(item, children);
else arg != null && arg !== !1 && arg !== "" && children.push(arg);
return children;
}
function getType(element) {
let type3 = element.type;
if (typeof type3 == "string")
return type3;
if (typeof type3 == "function")
return type3.displayName || type3.name || "Unknown";
if (ReactIs.isFragment(element))
return "React.Fragment";
if (ReactIs.isSuspense(element))
return "React.Suspense";
if (typeof type3 == "object" && type3 !== null) {
if (ReactIs.isContextProvider(element))
return "Context.Provider";
if (ReactIs.isContextConsumer(element))
return "Context.Consumer";
if (ReactIs.isForwardRef(element)) {
if (type3.displayName)
return type3.displayName;
let functionName2 = type3.render.displayName || type3.render.name || "";
return functionName2 === "" ? "ForwardRef" : `ForwardRef(${functionName2})`;
}
if (ReactIs.isMemo(element)) {
let functionName2 = type3.displayName || type3.type.displayName || type3.type.name || "";
return functionName2 === "" ? "Memo" : `Memo(${functionName2})`;
}
}
return "UNDEFINED";
}
function getPropKeys$1(element) {
let { props } = element;
return Object.keys(props).filter((key) => key !== "children" && props[key] !== void 0).sort();
}
var serialize$1 = (element, config2, indentation, depth, refs, printer2) => ++depth > config2.maxDepth ? printElementAsLeaf(getType(element), config2) : printElement(getType(element), printProps(getPropKeys$1(element), element.props, config2, indentation + config2.indent, depth, refs, printer2), printChildren(getChildren(element.props.children), config2, indentation + config2.indent, depth, refs, printer2), config2, indentation), test$1 = (val) => val != null && ReactIs.isElement(val), plugin$1 = {
serialize: serialize$1,
test: test$1
}, testSymbol = typeof Symbol == "function" && Symbol.for ? /* @__PURE__ */ Symbol.for("react.test.json") : 245830487;
function getPropKeys(object2) {
let { props } = object2;
return props ? Object.keys(props).filter((key) => props[key] !== void 0).sort() : [];
}
var serialize = (object2, config2, indentation, depth, refs, printer2) => ++depth > config2.maxDepth ? printElementAsLeaf(object2.type, config2) : printElement(object2.type, object2.props ? printProps(getPropKeys(object2), object2.props, config2, indentation + config2.indent, depth, refs, printer2) : "", object2.children ? printChildren(object2.children, config2, indentation + config2.indent, depth, refs, printer2) : "", config2, indentation), test = (val) => val && val.$$typeof === testSymbol, plugin = {
serialize,
test
}, toString = Object.prototype.toString, toISOString = Date.prototype.toISOString, errorToString = Error.prototype.toString, regExpToString = RegExp.prototype.toString;
function getConstructorName(val) {
return typeof val.constructor == "function" && val.constructor.name || "Object";
}
function isWindow(val) {
return typeof window < "u" && val === window;
}
var SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/, NEWLINE_REGEXP = /\n/g, PrettyFormatPluginError = class extends Error {
constructor(message, stack) {
super(message), this.stack = stack, this.name = this.constructor.name;
}
};
function isToStringedArrayType(toStringed) {
return toStringed === "[object Array]" || toStringed === "[object ArrayBuffer]" || toStringed === "[object DataView]" || toStringed === "[object Float32Array]" || toStringed === "[object Float64Array]" || toStringed === "[object Int8Array]" || toStringed === "[object Int16Array]" || toStringed === "[object Int32Array]" || toStringed === "[object Uint8Array]" || toStringed === "[object Uint8ClampedArray]" || toStringed === "[object Uint16Array]" || toStringed === "[object Uint32Array]";
}
function printNumber(val) {
return Object.is(val, -0) ? "-0" : String(val);
}
function printBigInt(val) {
return `${val}n`;
}
function printFunction(val, printFunctionName2) {
return printFunctionName2 ? `[Function ${val.name || "anonymous"}]` : "[Function]";
}
function printSymbol(val) {
return String(val).replace(SYMBOL_REGEXP, "Symbol($1)");
}
function printError(val) {
return `[${errorToString.call(val)}]`;
}
function printBasicValue(val, printFunctionName2, escapeRegex2, escapeString) {
if (val === !0 || val === !1)
return `${val}`;
if (val === void 0)
return "undefined";
if (val === null)
return "null";
let typeOf2 = typeof val;
if (typeOf2 === "number")
return printNumber(val);
if (typeOf2 === "bigint")
return printBigInt(val);
if (typeOf2 === "string")
return escapeString ? `"${val.replaceAll(/"|\\/g, "\\$&")}"` : `"${val}"`;
if (typeOf2 === "function")
return printFunction(val, printFunctionName2);
if (typeOf2 === "symbol")
return printSymbol(val);
let toStringed = toString.call(val);
return toStringed === "[object WeakMap]" ? "WeakMap {}" : toStringed === "[object WeakSet]" ? "WeakSet {}" : toStringed === "[object Function]" || toStringed === "[object GeneratorFunction]" ? printFunction(val, printFunctionName2) : toStringed === "[object Symbol]" ? printSymbol(val) : toStringed === "[object Date]" ? Number.isNaN(+val) ? "Date { NaN }" : toISOString.call(val) : toStringed === "[object Error]" ? printError(val) : toStringed === "[object RegExp]" ? escapeRegex2 ? regExpToString.call(val).replaceAll(/[$()*+.?[\\\]^{|}]/g, "\\$&") : regExpToString.call(val) : val instanceof Error ? printError(val) : null;
}
function printComplexValue(val, config2, indentation, depth, refs, hasCalledToJSON) {
if (refs.includes(val))
return "[Circular]";
refs = [...refs], refs.push(val);
let hitMaxDepth = ++depth > config2.maxDepth, min = config2.min;
if (config2.callToJSON && !hitMaxDepth && val.toJSON && typeof val.toJSON == "function" && !hasCalledToJSON)
return printer(val.toJSON(), config2, indentation, depth, refs, !0);
let toStringed = toString.call(val);
return toStringed === "[object Arguments]" ? hitMaxDepth ? "[Arguments]" : `${min ? "" : "Arguments "}[${printListItems(val, config2, indentation, depth, refs, printer)}]` : isToStringedArrayType(toStringed) ? hitMaxDepth ? `[${val.constructor.name}]` : `${min || !config2.printBasicPrototype && val.constructor.name === "Array" ? "" : `${val.constructor.name} `}[${printListItems(val, config2, indentation, depth, refs, printer)}]` : toStringed === "[object Map]" ? hitMaxDepth ? "[Map]" : `Map {${printIteratorEntries(val.entries(), config2, indentation, depth, refs, printer, " => ")}}` : toStringed === "[object Set]" ? hitMaxDepth ? "[Set]" : `Set {${printIteratorValues(val.values(), config2, indentation, depth, refs, printer)}}` : hitMaxDepth || isWindow(val) ? `[${getConstructorName(val)}]` : `${min || !config2.printBasicPrototype && getConstructorName(val) === "Object" ? "" : `${getConstructorName(val)} `}{${printObjectProperties(val, config2, indentation, depth, refs, printer)}}`;
}
var ErrorPlugin = {
test: (val) => val && val instanceof Error,
serialize(val, config2, indentation, depth, refs, printer2) {
if (refs.includes(val))
return "[Circular]";
refs = [...refs, val];
let hitMaxDepth = ++depth > config2.maxDepth, { message, cause, ...rest } = val, entries = {
message,
...typeof cause < "u" ? { cause } : {},
...val instanceof AggregateError ? { errors: val.errors } : {},
...rest
}, name = val.name !== "Error" ? val.name : getConstructorName(val);
return hitMaxDepth ? `[${name}]` : `${name} {${printIteratorEntries(Object.entries(entries).values(), config2, indentation, depth, refs, printer2)}}`;
}
};
function isNewPlugin(plugin3) {
return plugin3.serialize != null;
}
function printPlugin(plugin3, val, config2, indentation, depth, refs) {
let printed;
try {
printed = isNewPlugin(plugin3) ? plugin3.serialize(val, config2, indentation, depth, refs, printer) : plugin3.print(val, (valChild) => printer(valChild, config2, indentation, depth, refs), (str) => {
let indentationNext = indentation + config2.indent;
return indentationNext + str.replaceAll(NEWLINE_REGEXP, `
${indentationNext}`);
}, {
edgeSpacing: config2.spacingOuter,
min: config2.min,
spacing: config2.spacingInner
}, config2.colors);
} catch (error) {
throw new PrettyFormatPluginError(error.message, error.stack);
}
if (typeof printed != "string")
throw new TypeError(`pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".`);
return printed;
}
function findPlugin(plugins2, val) {
for (let plugin3 of plugins2)
try {
if (plugin3.test(val))
return plugin3;
} catch (error) {
throw new PrettyFormatPluginError(error.message, error.stack);
}
return null;
}
function printer(val, config2, indentation, depth, refs, hasCalledToJSON) {
let result, plugin3 = findPlugin(config2.plugins, val);
if (plugin3 !== null)
result = printPlugin(plugin3, val, config2, indentation, depth, refs);
else {
let basicResult = printBasicValue(val, config2.printFunctionName, config2.escapeRegex, config2.escapeString);
basicResult !== null ? result = basicResult : result = printComplexValue(val, config2, indentation, depth, refs, hasCalledToJSON);
}
return config2._outputLengthPerDepth[depth] ??= 0, config2._outputLengthPerDepth[depth] += result.length, config2._outputLengthPerDepth[depth] > config2.maxOutputLength && (config2.maxDepth = 0), result;
}
var DEFAULT_THEME = {
comment: "gray",
content: "reset",
prop: "yellow",
tag: "cyan",
value: "green"
}, DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME), DEFAULT_OPTIONS = {
callToJSON: !0,
compareKeys: void 0,
escapeRegex: !1,
escapeString: !0,
highlight: !1,
indent: 2,
maxDepth: Number.POSITIVE_INFINITY,
maxOutputLength: 1e6,
maxWidth: Number.POSITIVE_INFINITY,
min: !1,
plugins: [],
printBasicPrototype: !0,
printFunctionName: !0,
printShadowRoot: !0,
theme: DEFAULT_THEME
};
function validateOptions(options) {
for (let key of Object.keys(options))
if (!Object.hasOwn(DEFAULT_OPTIONS, key))
throw new Error(`pretty-format: Unknown option "${key}".`);
if (options.min && options.indent !== void 0 && options.indent !== 0)
throw new Error('pretty-format: Options "min" and "indent" cannot be used together.');
}
function getColorsHighlight() {
return DEFAULT_THEME_KEYS.reduce((colors, key) => {
let value = DEFAULT_THEME[key], color = value && y[value];
if (color && typeof color.close == "string" && typeof color.open == "string")
colors[key] = color;
else
throw new Error(`pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.`);
return colors;
}, /* @__PURE__ */ Object.create(null));
}
function getColorsEmpty() {
return DEFAULT_THEME_KEYS.reduce((colors, key) => (colors[key] = {
close: "",
open: ""
}, colors), /* @__PURE__ */ Object.create(null));
}
function getPrintFunctionName(options) {
return options?.printFunctionName ?? DEFAULT_OPTIONS.printFunctionName;
}
function getEscapeRegex(options) {
return options?.escapeRegex ?? DEFAULT_OPTIONS.escapeRegex;
}
function getEscapeString(options) {
return options?.escapeString ?? DEFAULT_OPTIONS.escapeString;
}
function getConfig(options) {
return {
callToJSON: options?.callToJSON ?? DEFAULT_OPTIONS.callToJSON,
colors: options?.highlight ? getColorsHighlight() : getColorsEmpty(),
compareKeys: typeof options?.compareKeys == "function" || options?.compareKeys === null ? options.compareKeys : DEFAULT_OPTIONS.compareKeys,
escapeRegex: getEscapeRegex(options),
escapeString: getEscapeString(options),
indent: options?.min ? "" : createIndent(options?.indent ?? DEFAULT_OPTIONS.indent),
maxDepth: options?.maxDepth ?? DEFAULT_OPTIONS.maxDepth,
maxWidth: options?.maxWidth ?? DEFAULT_OPTIONS.maxWidth,
min: options?.min ?? DEFAULT_OPTIONS.min,
plugins: options?.plugins ?? DEFAULT_OPTIONS.plugins,
printBasicPrototype: options?.printBasicPrototype ?? !0,
printFunctionName: getPrintFunctionName(options),
printShadowRoot: options?.printShadowRoot ?? !0,
spacingInner: options?.min ? " " : `
`,
spacingOuter: options?.min ? "" : `
`,
maxOutputLength: options?.maxOutputLength ?? DEFAULT_OPTIONS.maxOutputLength,
_outputLengthPerDepth: []
};
}
function createIndent(indent) {
return Array.from({ length: indent + 1 }).join(" ");
}
function format(val, options) {
if (options && (validateOptions(options), options.plugins)) {
let plugin3 = findPlugin(options.plugins, val);
if (plugin3 !== null)
return printPlugin(plugin3, val, getConfig(options), "", 0, []);
}
let basicResult = printBasicValue(val, getPrintFunctionName(options), getEscapeRegex(options), getEscapeString(options));
return basicResult !== null ? basicResult : printComplexValue(val, getConfig(options), "", 0, []);
}
var plugins = {
AsymmetricMatcher: plugin$5,
DOMCollection: plugin$4,
DOMElement: plugin$3,
Immutable: plugin$2,
ReactElement: plugin$1,
ReactTestComponent: plugin,
Error: ErrorPlugin
};
// ../../node_modules/.pnpm/@vitest+utils@4.1.10/node_modules/@vitest/utils/dist/diff.js
init_cjs_shims();
// ../../node_modules/.pnpm/@vitest+utils@4.1.10/node_modules/@vitest/utils/dist/display.js
init_cjs_shims();
var ansiColors = {
bold: ["1", "22"],
dim: ["2", "22"],
italic: ["3", "23"],
underline: ["4", "24"],
// 5 & 6 are blinking
inverse: ["7", "27"],
hidden: ["8", "28"],
strike: ["9", "29"],
// 10-20 are fonts
// 21-29 are resets for 1-9
black: ["30", "39"],
red: ["31", "39"],
green: ["32", "39"],
yellow: ["33", "39"],
blue: ["34", "39"],
magenta: ["35", "39"],
cyan: ["36", "39"],
white: ["37", "39"],
brightblack: ["30;1", "39"],
brightred: ["31;1", "39"],
brightgreen: ["32;1", "39"],
brightyellow: ["33;1", "39"],
brightblue: ["34;1", "39"],
brightmagenta: ["35;1", "39"],
brightcyan: ["36;1", "39"],
brightwhite: ["37;1", "39"],
grey: ["90", "39"]
}, styles = {
special: "cyan",
number: "yellow",
bigint: "yellow",
boolean: "yellow",
undefined: "grey",
null: "bold",
string: "green",
symbol: "green",
date: "magenta",
regexp: "red"
}, truncator = "\u2026";
function colorise(value, styleType) {
let color = ansiColors[styles[styleType]] || ansiColors[styleType] || "";
return color ? `\x1B[${color[0]}m${String(value)}\x1B[${color[1]}m` : String(value);
}
function normaliseOptions({
showHidden = !1,
depth = 2,
colors = !1,
customInspect = !0,
showProxy = !1,
maxArrayLength = 1 / 0,
breakLength = 1 / 0,
seen = [],
// eslint-disable-next-line no-shadow
truncate: truncate3 = 1 / 0,
stylize = String
} = {}, inspect3) {
let options = {
showHidden: !!showHidden,
depth: Number(depth),
colors: !!colors,
customInspect: !!customInspect,
showProxy: !!showProxy,
maxArrayLength: Number(maxArrayLength),
breakLength: Number(breakLength),
truncate: Number(truncate3),
seen,
inspect: inspect3,
stylize
};
return options.colors && (options.stylize = colorise), options;
}
function isHighSurrogate(char) {
return char >= "\uD800" && char <= "\uDBFF";
}
function truncate(string2, length, tail = truncator) {
string2 = String(string2);
let tailLength = tail.length, stringLength = string2.length;
if (tailLength > length && stringLength > tailLength)
return tail;
if (stringLength > length && stringLength > tailLength) {
let end = length - tailLength;
return end > 0 && isHighSurrogate(string2[end - 1]) && (end = end - 1), `${string2.slice(0, end)}${tail}`;
}
return string2;
}
function inspectList(list, options, inspectItem, separator = ", ") {
inspectItem = inspectItem || options.inspect;
let size = list.length;
if (size === 0)
return "";
let originalLength = options.truncate, output = "", peek = "", truncated = "";
for (let i2 = 0; i2 < size; i2 += 1) {
let last = i2 + 1 === list.length, secondToLast = i2 + 2 === list.length;
truncated = `${truncator}(${list.length - i2})`;
let value = list[i2];
options.truncate = originalLength - output.length - (last ? 0 : separator.length);
let string2 = peek || inspectItem(value, options) + (last ? "" : separator), nextLength = output.length + string2.length, truncatedLength = nextLength + truncated.length;
if (last && nextLength > originalLength && output.length + truncated.length <= originalLength || !last && !secondToLast && truncatedLength > originalLength || (peek = last ? "" : inspectItem(list[i2 + 1], options) + (secondToLast ? "" : separator), !last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength))
break;
if (output += string2, !last && !secondToLast && nextLength + peek.length >= originalLength) {
truncated = `${truncator}(${list.length - i2 - 1})`;
break;
}
truncated = "";
}
return `${output}${truncated}`;
}
function quoteComplexKey(key) {
return key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/) ? key : JSON.stringify(key).replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
}
function inspectProperty([key, value], options) {
return options.truncate -= 2, typeof key == "string" ? key = quoteComplexKey(key) : typeof key != "number" && (key = `[${options.inspect(key, options)}]`), options.truncate -= key.length, value = options.inspect(value, options), `${key}: ${value}`;
}
function inspectArray(array2, options) {
let nonIndexProperties = Object.keys(array2).slice(array2.length);
if (!array2.length && !nonIndexProperties.length)
return "[]";
options.truncate -= 4;
let listContents = inspectList(array2, options);
options.truncate -= listContents.length;
let propertyContents = "";
return nonIndexProperties.length && (propertyContents = inspectList(nonIndexProperties.map((key) => [key, array2[key]]), options, inspectProperty)), `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ""} ]`;
}
var getArrayName = (array2) => typeof Buffer == "function" && array2 instanceof Buffer ? "Buffer" : array2[Symbol.toStringTag] ? array2[Symbol.toStringTag] : array2.constructor.name;
function inspectTypedArray(array2, options) {
let name = getArrayName(array2);
options.truncate -= name.length + 4;
let nonIndexProperties = Object.keys(array2).slice(array2.length);
if (!array2.length && !nonIndexProperties.length)
return `${name}[]`;
let output = "";
for (let i2 = 0; i2 < array2.length; i2++) {
let string2 = `${options.stylize(truncate(array2[i2], options.truncate), "number")}${i2 === array2.length - 1 ? "" : ", "}`;
if (options.truncate -= string2.length, array2[i2] !== array2.length && options.truncate <= 3) {
output += `${truncator}(${array2.length - array2[i2] + 1})`;
break;
}
output += string2;
}
let propertyContents = "";
return nonIndexProperties.length && (propertyContents = inspectList(nonIndexProperties.map((key) => [key, array2[key]]), options, inspectProperty)), `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ""} ]`;
}
function inspectDate(dateObject, options) {
let stringRepresentation = dateObject.toJSON();
if (stringRepresentation === null)
return "Invalid Date";
let split = stringRepresentation.split("T"), date = split[0];
return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, "date");
}
function inspectFunction(func, options) {
let functionType = func[Symbol.toStringTag] || "Function", name = func.name;
return name ? options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, "special") : options.stylize(`[${functionType}]`, "special");
}
function inspectMapEntry([key, value], options) {
return options.truncate -= 4, key = options.inspect(key, options), options.truncate -= key.length, value = options.inspect(value, options), `${key} => ${value}`;
}
function mapToEntries(map2) {
let entries = [];
return map2.forEach((value, key) => {
entries.push([key, value]);
}), entries;
}
function inspectMap(map2, options) {
return map2.size === 0 ? "Map{}" : (options.truncate -= 7, `Map{ ${inspectList(mapToEntries(map2), options, inspectMapEntry)} }`);
}
var isNaN = Number.isNaN || ((i2) => i2 !== i2);
function inspectNumber(number, options) {
return isNaN(number) ? options.stylize("NaN", "number") : number === 1 / 0 ? options.stylize("Infinity", "number") : number === -1 / 0 ? options.stylize("-Infinity", "number") : number === 0 ? options.stylize(1 / number === 1 / 0 ? "+0" : "-0", "number") : options.stylize(truncate(String(number), options.truncate), "number");
}
function inspectBigInt(number, options) {
let nums = truncate(number.toString(), options.truncate - 1);
return nums !== truncator && (nums += "n"), options.stylize(nums, "bigint");
}
function inspectRegExp(value, options) {
let flags = value.toString().split("/")[2], sourceLength = options.truncate - (2 + flags.length), source = value.source;
return options.stylize(`/${truncate(source, sourceLength)}/${flags}`, "regexp");
}
function arrayFromSet(set3) {
let values = [];
return set3.forEach((value) => {
values.push(value);
}), values;
}
function inspectSet(set3, options) {
return set3.size === 0 ? "Set{}" : (options.truncate -= 7, `Set{ ${inspectList(arrayFromSet(set3), options)} }`);
}
var stringEscapeChars = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]", "g"), escapeCharacters = {
"\b": "\\b",
" ": "\\t",
"\n": "\\n",
"\f": "\\f",
"\r": "\\r",
"'": "\\'",
"\\": "\\\\"
}, hex = 16;
function escape(char) {
return escapeCharacters[char] || `\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-4)}`;
}
function inspectString(string2, options) {
return stringEscapeChars.test(string2) && (string2 = string2.replace(stringEscapeChars, escape)), options.stylize(`'${truncate(string2, options.truncate - 2)}'`, "string");
}
function inspectSymbol(value) {
return "description" in Symbol.prototype ? value.description ? `Symbol(${value.description})` : "Symbol()" : value.toString();
}
var getPromiseValue = () => "Promise{\u2026}";
function inspectObject$1(object2, options) {
let properties = Object.getOwnPropertyNames(object2), symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object2) : [];
if (properties.length === 0 && symbols.length === 0)
return "{}";
if (options.truncate -= 4, options.seen = options.seen || [], options.seen.includes(object2))
return "[Circular]";
options.seen.push(object2);
let propertyContents = inspectList(properties.map((key) => [key, object2[key]]), options, inspectProperty), symbolContents = inspectList(symbols.map((key) => [key, object2[key]]), options, inspectProperty);
options.seen.pop();
let sep = "";
return propertyContents && symbolContents && (sep = ", "), `{ ${propertyContents}${sep}${symbolContents} }`;
}
var toStringTag = typeof Symbol < "u" && Symbol.toStringTag ? Symbol.toStringTag : !1;
function inspectClass(value, options) {
let name = "";
return toStringTag && toStringTag in value && (name = value[toStringTag]), name = name || value.constructor.name, (!name || name === "_class") && (name = "<Anonymous Class>"), options.truncate -= name.length, `${name}${inspectObject$1(value, options)}`;
}
function inspectArguments(args, options) {
return args.length === 0 ? "Arguments[]" : (options.truncate -= 13, `Arguments[ ${inspectList(args, options)} ]`);
}
var errorKeys = [
"stack",
"line",
"column",
"name",
"message",
"fileName",
"lineNumber",
"columnNumber",
"number",
"description",
"cause"
];
function inspectObject(error, options) {
let properties = Object.getOwnPropertyNames(error).filter((key) => errorKeys.indexOf(key) === -1), name = error.name;
options.truncate -= name.length;
let message = "";
if (typeof error.message == "string" ? message = truncate(error.message, options.truncate) : properties.unshift("message"), message = message ? `: ${message}` : "", options.truncate -= message.length + 5, options.seen = options.seen || [], options.seen.includes(error))
return "[Circular]";
options.seen.push(error);
let propertyContents = inspectList(properties.map((key) => [key, error[key]]), options, inspectProperty);
return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ""}`;
}
function inspectAttribute([key, value], options) {
return options.truncate -= 3, value ? `${options.stylize(String(key), "yellow")}=${options.stylize(`"${value}"`, "string")}` : `${options.stylize(String(key), "yellow")}`;
}
function inspectNodeCollection(collection, options) {
return inspectList(collection, options, inspectNode, `
`);
}
function inspectNode(node, options) {
switch (node.nodeType) {
case 1:
return inspectHTML(node, options);
case 3:
return options.inspect(node.data, options);
default:
return options.inspect(node, options);
}
}
function inspectHTML(element, options) {
let properties = element.getAttributeNames(), name = element.tagName.toLowerCase(), head = options.stylize(`<${name}`, "special"), headClose = options.stylize(">", "special"), tail = options.stylize(`</${name}>`, "special");
options.truncate -= name.length * 2 + 5;
let propertyContents = "";
properties.length > 0 && (propertyContents += " ", propertyContents += inspectList(properties.map((key) => [key, element.getAttribute(key)]), options, inspectAttribute, " ")), options.truncate -= propertyContents.length;
let truncate3 = options.truncate, children = inspectNodeCollection(element.children, options);
return children && children.length > truncate3 && (children = `${truncator}(${element.children.length})`), `${head}${propertyContents}${headClose}${children}${tail}`;
}
var symbolsSupported = typeof Symbol == "function" && typeof Symbol.for == "function", chaiInspect = symbolsSupported ? /* @__PURE__ */ Symbol.for("chai/inspect") : "@@chai/inspect", nodeInspect = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), constructorMap = /* @__PURE__ */ new WeakMap(), stringTagMap = {}, baseTypesMap = {
undefined: (value, options) => options.stylize("undefined", "undefined"),
null: (value, options) => options.stylize("null", "null"),
boolean: (value, options) => options.stylize(String(value), "boolean"),
Boolean: (value, options) => options.stylize(String(value), "boolean"),
number: inspectNumber,
Number: inspectNumber,
bigint: inspectBigInt,
BigInt: inspectBigInt,
string: inspectString,
String: inspectString,
function: inspectFunction,
Function: inspectFunction,
symbol: inspectSymbol,
// A Symbol polyfill will return `Symbol` not `symbol` from typedetect
Symbol: inspectSymbol,
Array: inspectArray,
Date: inspectDate,
Map: inspectMap,
Set: inspectSet,
RegExp: inspectRegExp,
Promise: getPromiseValue,
// WeakSet, WeakMap are totally opaque to us
WeakSet: (value, options) => options.stylize("WeakSet{\u2026}", "special"),
WeakMap: (value, options) => options.stylize("WeakMap{\u2026}", "special"),
Arguments: inspectArguments,
Int8Array: inspectTypedArray,
Uint8Array: inspectTypedArray,
Uint8ClampedArray: inspectTypedArray,
Int16Array: inspectTypedArray,
Uint16Array: inspectTypedArray,
Int32Array: inspectTypedArray,
Uint32Array: inspectTypedArray,
Float32Array: inspectTypedArray,
Float64Array: inspectTypedArray,
Generator: () => "",
DataView: () => "",
ArrayBuffer: () => "",
Error: inspectObject,
HTMLCollection: inspectNodeCollection,
NodeList: inspectNodeCollection
}, inspectCustom = (value, options, type3, inspectFn) => chaiInspect in value && typeof value[chaiInspect] == "function" ? value[chaiInspect](options) : nodeInspect in value && typeof value[nodeInspect] == "function" ? value[nodeInspect](options.depth, options, inspectFn) : "inspect" in value && typeof value.inspect == "function" ? value.inspect(options.depth, options) : "constructor" in value && constructorMap.has(value.constructor) ? constructorMap.get(value.constructor)(value, options) : stringTagMap[type3] ? stringTagMap[type3](value, options) : "", toString2 = Object.prototype.toString;
function inspect$1(value, opts = {}) {
let options = normaliseOptions(opts, inspect$1), { customInspect } = options, type3 = value === null ? "null" : typeof value;
if (type3 === "object" && (type3 = toString2.call(value).slice(8, -1)), type3 in baseTypesMap)
return baseTypesMap[type3](value, options);
if (customInspect && value) {
let output = inspectCustom(value, options, type3, inspect$1);
if (output)
return typeof output == "string" ? output : inspect$1(output, options);
}
let proto = value ? Object.getPrototypeOf(value) : !1;
return proto === Object.prototype || proto === null ? inspectObject$1(value, options) : value && typeof HTMLElement == "function" && value instanceof HTMLElement ? inspectHTML(value, options) : "constructor" in value ? value.constructor !== Object ? inspectClass(value, options) : inspectObject$1(value, options) : value === Object(value) ? inspectObject$1(value, options) : options.stylize(String(value), type3);
}
var { AsymmetricMatcher, DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent } = plugins, PLUGINS = [
ReactTestComponent,
ReactElement,
DOMElement,
DOMCollection,
Immutable,
AsymmetricMatcher
];
function stringify(object2, maxDepth = 10, { maxLength, filterNode, ...options } = {}) {
let MAX_LENGTH = maxLength ?? 1e4, result, filterFn = typeof filterNode == "string" ? createNodeFilterFromSelector(filterNode) : filterNode, plugins2 = filterFn ? [
ReactTestComponent,
ReactElement,
createDOMElementFilter(filterFn),
DOMCollection,
Immutable,
AsymmetricMatcher
] : PLUGINS;
try {
result = format(object2, {
maxDepth,
escapeString: !1,
plugins: plugins2,
...options
});
} catch {
result = format(object2, {
callToJSON: !1,
maxDepth,
escapeString: !1,
plugins: plugins2,
...options
});
}
return result.length >= MAX_LENGTH && maxDepth > 1 ? stringify(object2, Math.floor(Math.min(maxDepth, Number.MAX_SAFE_INTEGER) / 2), {
maxLength,
filterNode,
...options
}) : result;
}
function createNodeFilterFromSelector(selector) {
return (node) => {
if (node.nodeType === 8)
return !1;
if (node.nodeType === 1 && node.matches)
try {
return !node.matches(selector);
} catch {
return !0;
}
return !0;
};
}
var formatRegExp = /%[sdjifoOc%]/g;
function baseFormat(args, options = {}) {
let formatArg = (item, inspecOptions) => options.prettifyObject ? stringify(item, void 0, {
printBasicPrototype: !1,
escapeString: !1
}) : inspect(item, inspecOptions);
if (typeof args[0] != "string") {
let objects = [];
for (let i3 = 0; i3 < args.length; i3++)
objects.push(formatArg(args[i3], {
depth: 0,
colors: !1
}));
return objects.join(" ");
}
let len = args.length, i2 = 1, template = args[0], str = String(template).replace(formatRegExp, (x) => {
if (x === "%%")
return "%";
if (i2 >= len)
return x;
switch (x) {
case "%s": {
let value = args[i2++];
return typeof value == "bigint" ? `${value.toString()}n` : typeof value == "number" && value === 0 && 1 / value < 0 ? "-0" : typeof value == "object" && value !== null ? typeof value.toString == "function" && value.toString !== Object.prototype.toString ? value.toString() : formatArg(value, {
depth: 0,
colors: !1
}) : String(value);
}
case "%d": {
let value = args[i2++];
return typeof value == "bigint" ? `${value.toString()}n` : typeof value == "symbol" ? "NaN" : Number(value).toString();
}
case "%i": {
let value = args[i2++];
return typeof value == "bigint" ? `${value.toString()}n` : Number.parseInt(String(value)).toString();
}
case "%f":
return Number.parseFloat(String(args[i2++])).toString();
case "%o":
return formatArg(args[i2++], {
showHidden: !0,
showProxy: !0
});
case "%O":
return formatArg(args[i2++]);
case "%c":
return i2++, "";
case "%j":
try {
return JSON.stringify(args[i2++]);
} catch (err) {
let m = err.message;
if (m.includes("circular structure") || m.includes("cyclic structures") || m.includes("cyclic object"))
return "[Circular]";
throw err;
}
default:
return x;
}
});
for (let x = args[i2]; i2 < len; x = args[++i2])
x === null || typeof x != "object" ? str += ` ${typeof x == "symbol" ? x.toString() : x}` : str += ` ${formatArg(x)}`;
return str;
}
function format2(...args) {
return baseFormat(args);
}
function inspect(obj, options = {}) {
return options.truncate === 0 && (options.truncate = Number.POSITIVE_INFINITY), inspect$1(obj, options);
}
function objDisplay(obj, options = {}) {
typeof options.truncate > "u" && (options.truncate = 40);
let str = inspect(obj, options), type3 = Object.prototype.toString.call(obj);
if (options.truncate && str.length >= options.truncate)
if (type3 === "[object Function]") {
let fn2 = obj;
return fn2.name ? `[Function: ${fn2.name}]` : "[Function]";
} else {
if (type3 === "[object Array]")
return `[ Array(${obj.length}) ]`;
if (type3 === "[object Object]") {
let keys2 = Object.keys(obj);
return `{ Object (${keys2.length > 2 ? `${keys2.splice(0, 2).join(", ")}, ...` : keys2.join(", ")}) }`;
} else
return str;
}
return str;
}
// ../../node_modules/.pnpm/@vitest+utils@4.1.10/node_modules/@vitest/utils/dist/helpers.js
init_cjs_shims();
function createSimpleStackTrace(options) {
let { message = "$$stack trace error", stackTraceLimit = 1 } = options || {}, limit = Error.stackTraceLimit, prepareStackTrace = Error.prepareStackTrace;
Error.stackTraceLimit = stackTraceLimit, Error.prepareStackTrace = (e) => e.stack;
let stackTrace = new Error(message).stack || "";
return Error.prepareStackTrace = prepareStackTrace, Error.stackTraceLimit = limit, stackTrace;
}
function notNullish(v) {
return v != null;
}
function assertTypes(value, name, types) {
let receivedType = typeof value;
if (!types.includes(receivedType))
throw new TypeError(`${name} value must be ${types.join(" or ")}, received "${receivedType}"`);
}
function isPrimitive(value) {
return value === null || typeof value != "function" && typeof value != "object";
}
function filterOutComments(s) {
let result = [], commentState = "none";
for (let i2 = 0; i2 < s.length; ++i2)
commentState === "singleline" ? s[i2] === `
` && (commentState = "none") : commentState === "multiline" ? s[i2 - 1] === "*" && s[i2] === "/" && (commentState = "none") : commentState === "none" && (s[i2] === "/" && s[i2 + 1] === "/" ? commentState = "singleline" : s[i2] === "/" && s[i2 + 1] === "*" ? (commentState = "multiline", i2 += 2) : result.push(s[i2]));
return result.join("");
}
function toArray(array2) {
return array2 == null && (array2 = []), Array.isArray(array2) ? array2 : [array2];
}
function isObject(item) {
return item != null && typeof item == "object" && !Array.isArray(item);
}
function isFinalObj(obj) {
return obj === Object.prototype || obj === Function.prototype || obj === RegExp.prototype;
}
function getType2(value) {
return Object.prototype.toString.apply(value).slice(8, -1);
}
function collectOwnProperties(obj, collector) {
let collect = typeof collector == "function" ? collector : (key) => collector.add(key);
Object.getOwnPropertyNames(obj).forEach(collect), Object.getOwnPropertySymbols(obj).forEach(collect);
}
function getOwnProperties(obj) {
let ownProps = /* @__PURE__ */ new Set();
return isFinalObj(obj) ? [] : (collectOwnProperties(obj, ownProps), Array.from(ownProps));
}
var defaultCloneOptions = { forceWritable: !1 };
function deepClone(val, options = defaultCloneOptions) {
return clone(val, /* @__PURE__ */ new WeakMap(), options);
}
function clone(val, seen, options = defaultCloneOptions) {
let k, out;
if (seen.has(val))
return seen.get(val);
if (Array.isArray(val)) {
for (out = Array.from({ length: k = val.length }), seen.set(val, out); k--; )
out[k] = clone(val[k], seen, options);
return out;
}
if (Object.prototype.toString.call(val) === "[object Object]") {
out = Object.create(Object.getPrototypeOf(val)), seen.set(val, out);
let props = getOwnProperties(val);
for (let k2 of props) {
let descriptor = Object.getOwnPropertyDescriptor(val, k2);
if (!descriptor)
continue;
let cloned = clone(val[k2], seen, options);
options.forceWritable ? Object.defineProperty(out, k2, {
enumerable: descriptor.enumerable,
configurable: !0,
writable: !0,
value: cloned
}) : "get" in descriptor ? Object.defineProperty(out, k2, {
...descriptor,
get() {
return cloned;
}
}) : Object.defineProperty(out, k2, {
...descriptor,
value: cloned
});
}
return out;
}
return val;
}
function noop() {
}
function objectAttr(source, path, defaultValue = void 0) {
let paths = path.replace(/\[(\d+)\]/g, ".$1").split("."), result = source;
for (let p of paths)
if (result = new Object(result)[p], result === void 0)
return defaultValue;
return result;
}
function createDefer() {
let resolve2 = null, reject = null, p = new Promise((_resolve, _reject) => {
resolve2 = _resolve, reject = _reject;
});
return p.resolve = resolve2, p.reject = reject, p;
}
function getCallLastIndex(code) {
let charIndex = -1, inString = null, startedBracers = 0, endedBracers = 0, beforeChar = null;
for (; charIndex <= code.length; ) {
beforeChar = code[charIndex], charIndex++;
let char = code[charIndex];
if ((char === '"' || char === "'" || char === "`") && beforeChar !== "\\" && (inString === char ? inString = null : inString || (inString = char)), inString || (char === "(" && startedBracers++, char === ")" && endedBracers++), startedBracers && endedBracers && startedBracers === endedBracers)
return charIndex;
}
return null;
}
function isNegativeNaN(val) {
if (!Number.isNaN(val))
return !1;
let f64 = new Float64Array(1);
return f64[0] = val, new Uint32Array(f64.buffer)[1] >>> 31 === 1;
}
function ordinal(i2) {
let j = i2 % 10, k = i2 % 100;
return j === 1 && k !== 11 ? `${i2}st` : j === 2 && k !== 12 ? `${i2}nd` : j === 3 && k !== 13 ? `${i2}rd` : `${i2}th`;
}
function unique(array2) {
return Array.from(new Set(array2));
}
// ../../node_modules/.pnpm/@vitest+utils@4.1.10/node_modules/@vitest/utils/dist/diff.js
var DIFF_DELETE = -1, DIFF_INSERT = 1, DIFF_EQUAL = 0, Diff = class {
0;
1;
constructor(op, text) {
this[0] = op, this[1] = text;
}
};
function diff_commonPrefix(text1, text2) {
if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0))
return 0;
let pointermin = 0, pointermax = Math.min(text1.length, text2.length), pointermid = pointermax, pointerstart = 0;
for (; pointermin < pointermid; )
text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid) ? (pointermin = pointermid, pointerstart = pointermin) : pointermax = pointermid, pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
return pointermid;
}
function diff_commonSuffix(text1, text2) {
if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1))
return 0;
let pointermin = 0, pointermax = Math.min(text1.length, text2.length), pointermid = pointermax, pointerend = 0;
for (; pointermin < pointermid; )
text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend) ? (pointermin = pointermid, pointerend = pointermin) : pointermax = pointermid, pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
return pointermid;
}
function diff_commonOverlap_(text1, text2) {
let text1_length = text1.length, text2_length = text2.length;
if (text1_length === 0 || text2_length === 0)
return 0;
text1_length > text2_length ? text1 = text1.substring(text1_length - text2_length) : text1_length < text2_length && (text2 = text2.substring(0, text1_length));
let text_length = Math.min(text1_length, text2_length);
if (text1 === text2)
return text_length;
let best = 0, length = 1;
for (; ; ) {
let pattern = text1.substring(text_length - length), found2 = text2.indexOf(pattern);
if (found2 === -1)
return best;
length += found2, (found2 === 0 || text1.substring(text_length - length) === text2.substring(0, length)) && (best = length, length++);
}
}
function diff_cleanupSemantic(diffs) {
let changes = !1, equalities = [], equalitiesLength = 0, lastEquality = null, pointer = 0, length_insertions1 = 0, length_deletions1 = 0, length_insertions2 = 0, length_deletions2 = 0;
for (; pointer < diffs.length; )
diffs[pointer][0] === DIFF_EQUAL ? (equalities[equalitiesLength++] = pointer, length_insertions1 = length_insertions2, length_deletions1 = length_deletions2, length_insertions2 = 0, length_deletions2 = 0, lastEquality = diffs[pointer][1]) : (diffs[pointer][0] === DIFF_INSERT ? length_insertions2 += diffs[pointer][1].length : length_deletions2 += diffs[pointer][1].length, lastEquality && lastEquality.length <= Math.max(length_insertions1, length_deletions1) && lastEquality.length <= Math.max(length_insertions2, length_deletions2) && (diffs.splice(equalities[equalitiesLength - 1], 0, new Diff(DIFF_DELETE, lastEquality)), diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT, equalitiesLength--, equalitiesLength--, pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1, length_insertions1 = 0, length_deletions1 = 0, length_insertions2 = 0, length_deletions2 = 0, lastEquality = null, changes = !0)), pointer++;
for (changes && diff_cleanupMerge(diffs), diff_cleanupSemanticLossless(diffs), pointer = 1; pointer < diffs.length; ) {
if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
let deletion = diffs[pointer - 1][1], insertion = diffs[pointer][1], overlap_length1 = diff_commonOverlap_(deletion, insertion), overlap_length2 = diff_commonOverlap_(insertion, deletion);
overlap_length1 >= overlap_length2 ? (overlap_length1 >= deletion.length / 2 || overlap_length1 >= insertion.length / 2) && (diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, insertion.substring(0, overlap_length1))), diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlap_length1), diffs[pointer + 1][1] = insertion.substring(overlap_length1), pointer++) : (overlap_length2 >= deletion.length / 2 || overlap_length2 >= insertion.length / 2) && (diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, deletion.substring(0, overlap_length2))), diffs[pointer - 1][0] = DIFF_INSERT, diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlap_length2), diffs[pointer + 1][0] = DIFF_DELETE, diffs[pointer + 1][1] = deletion.substring(overlap_length2), pointer++), pointer++;
}
pointer++;
}
}
var nonAlphaNumericRegex_ = /[^a-z0-9]/i, whitespaceRegex_ = /\s/, linebreakRegex_ = /[\r\n]/, blanklineEndRegex_ = /\n\r?\n$/, blanklineStartRegex_ = /^\r?\n\r?\n/;
function diff_cleanupSemanticLossless(diffs) {
let pointer = 1;
for (; pointer < diffs.length - 1; ) {
if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
let equality1 = diffs[pointer - 1][1], edit = diffs[pointer][1], equality2 = diffs[pointer + 1][1], commonOffset = diff_commonSuffix(equality1, edit);
if (commonOffset) {
let commonString = edit.substring(edit.length - commonOffset);
equality1 = equality1.substring(0, equality1.length - commonOffset), edit = commonString + edit.substring(0, edit.length - commonOffset), equality2 = commonString + equality2;
}
let bestEquality1 = equality1, bestEdit = edit, bestEquality2 = equality2, bestScore = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2);
for (; edit.charAt(0) === equality2.charAt(0); ) {
equality1 += edit.charAt(0), edit = edit.substring(1) + equality2.charAt(0), equality2 = equality2.substring(1);
let score = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2);
score >= bestScore && (bestScore = score, bestEquality1 = equality1, bestEdit = edit, bestEquality2 = equality2);
}
diffs[pointer - 1][1] !== bestEquality1 && (bestEquality1 ? diffs[pointer - 1][1] = bestEquality1 : (diffs.splice(pointer - 1, 1), pointer--), diffs[pointer][1] = bestEdit, bestEquality2 ? diffs[pointer + 1][1] = bestEquality2 : (diffs.splice(pointer + 1, 1), pointer--));
}
pointer++;
}
}
function diff_cleanupMerge(diffs) {
diffs.push(new Diff(DIFF_EQUAL, ""));
let pointer = 0, count_delete = 0, count_insert = 0, text_delete = "", text_insert = "", commonlength;
for (; pointer < diffs.length; )
switch (diffs[pointer][0]) {
case DIFF_INSERT:
count_insert++, text_insert += diffs[pointer][1], pointer++;
break;
case DIFF_DELETE:
count_delete++, text_delete += diffs[pointer][1], pointer++;
break;
case DIFF_EQUAL:
count_delete + count_insert > 1 ? (count_delete !== 0 && count_insert !== 0 && (commonlength = diff_commonPrefix(text_insert, text_delete), commonlength !== 0 && (pointer - count_delete - count_insert > 0 && diffs[pointer - count_delete - count_insert - 1][0] === DIFF_EQUAL ? diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength) : (diffs.splice(0, 0, new Diff(DIFF_EQUAL, text_insert.substring(0, commonlength))), pointer++), text_insert = text_insert.substring(commonlength), text_delete = text_delete.substring(commonlength)), commonlength = diff_commonSuffix(text_insert, text_delete), commonlength !== 0 && (diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1], text_insert = text_insert.substring(0, text_insert.length - commonlength), text_delete = text_delete.substring(0, text_delete.length - commonlength))), pointer -= count_delete + count_insert, diffs.splice(pointer, count_delete + count_insert), text_delete.length && (diffs.splice(pointer, 0, new Diff(DIFF_DELETE, text_delete)), pointer++), text_insert.length && (diffs.splice(pointer, 0, new Diff(DIFF_INSERT, text_insert)), pointer++), pointer++) : pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL ? (diffs[pointer - 1][1] += diffs[pointer][1], diffs.splice(pointer, 1)) : pointer++, count_insert = 0, count_delete = 0, text_delete = "", text_insert = "";
break;
}
diffs.at(-1)?.[1] === "" && diffs.pop();
let changes = !1;
for (pointer = 1; pointer < diffs.length - 1; )
diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL && (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1] ? (diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length), diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1], diffs.splice(pointer - 1, 1), changes = !0) : diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1] && (diffs[pointer - 1][1] += diffs[pointer + 1][1], diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1], diffs.splice(pointer + 1, 1), changes = !0)), pointer++;
changes && diff_cleanupMerge(diffs);
}
function diff_cleanupSemanticScore_(one, two) {
if (!one || !two)
return 6;
let char1 = one.charAt(one.length - 1), char2 = two.charAt(0), nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex_), nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex_), whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex_), whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex_), lineBreak1 = whitespace1 && char1.match(linebreakRegex_), lineBreak2 = whitespace2 && char2.match(linebreakRegex_), blankLine1 = lineBreak1 && one.match(blanklineEndRegex_), blankLine2 = lineBreak2 && two.match(blanklineStartRegex_);
return blankLine1 || blankLine2 ? 5 : lineBreak1 || lineBreak2 ? 4 : nonAlphaNumeric1 && !whitespace1 && whitespace2 ? 3 : whitespace1 || whitespace2 ? 2 : nonAlphaNumeric1 || nonAlphaNumeric2 ? 1 : 0;
}
var NO_DIFF_MESSAGE = "Compared values have no visual difference.", SIMILAR_MESSAGE = "Compared values serialize to the same structure.\nPrinting internal object structure without calling `toJSON` instead.";
function getDefaultExportFromCjs2(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x.default : x;
}
var build = {}, hasRequiredBuild;
function requireBuild() {
if (hasRequiredBuild) return build;
hasRequiredBuild = 1, Object.defineProperty(build, "__esModule", {
value: !0
}), build.default = diffSequence;
let pkg = "diff-sequences", NOT_YET_SET = 0, countCommonItemsF = (aIndex, aEnd, bIndex, bEnd, isCommon) => {
let nCommon = 0;
for (; aIndex < aEnd && bIndex < bEnd && isCommon(aIndex, bIndex); )
aIndex += 1, bIndex += 1, nCommon += 1;
return nCommon;
}, countCommonItemsR = (aStart, aIndex, bStart, bIndex, isCommon) => {
let nCommon = 0;
for (; aStart <= aIndex && bStart <= bIndex && isCommon(aIndex, bIndex); )
aIndex -= 1, bIndex -= 1, nCommon += 1;
return nCommon;
}, extendPathsF = (d2, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF) => {
let iF = 0, kF = -d2, aFirst = aIndexesF[iF], aIndexPrev1 = aFirst;
aIndexesF[iF] += countCommonItemsF(
aFirst + 1,
aEnd,
bF + aFirst - kF + 1,
bEnd,
isCommon
);
let nF = d2 < iMaxF ? d2 : iMaxF;
for (iF += 1, kF += 2; iF <= nF; iF += 1, kF += 2) {
if (iF !== d2 && aIndexPrev1 < aIndexesF[iF])
aFirst = aIndexesF[iF];
else if (aFirst = aIndexPrev1 + 1, aEnd <= aFirst)
return iF - 1;
aIndexPrev1 = aIndexesF[iF], aIndexesF[iF] = aFirst + countCommonItemsF(aFirst + 1, aEnd, bF + aFirst - kF + 1, bEnd, isCommon);
}
return iMaxF;
}, extendPathsR = (d2, aStart, bStart, bR, isCommon, aIndexesR, iMaxR) => {
let iR = 0, kR = d2, aFirst = aIndexesR[iR], aIndexPrev1 = aFirst;
aIndexesR[iR] -= countCommonItemsR(
aStart,
aFirst - 1,
bStart,
bR + aFirst - kR - 1,
isCommon
);
let nR = d2 < iMaxR ? d2 : iMaxR;
for (iR += 1, kR -= 2; iR <= nR; iR += 1, kR -= 2) {
if (iR !== d2 && aIndexesR[iR] < aIndexPrev1)
aFirst = aIndexesR[iR];
else if (aFirst = aIndexPrev1 - 1, aFirst < aStart)
return iR - 1;
aIndexPrev1 = aIndexesR[iR], aIndexesR[iR] = aFirst - countCommonItemsR(
aStart,
aFirst - 1,
bStart,
bR + aFirst - kR - 1,
isCommon
);
}
return iMaxR;
}, extendOverlappablePathsF = (d2, aStart, aEnd, bStart, bEnd, isCommon, aIndexesF, iMaxF, aIndexesR, iMaxR, division) => {
let bF = bStart - aStart, aLength = aEnd - aStart, baDeltaLength = bEnd - bStart - aLength, kMinOverlapF = -baDeltaLength - (d2 - 1), kMaxOverlapF = -baDeltaLength + (d2 - 1), aIndexPrev1 = NOT_YET_SET, nF = d2 < iMaxF ? d2 : iMaxF;
for (let iF = 0, kF = -d2; iF <= nF; iF += 1, kF += 2) {
let insert = iF === 0 || iF !== d2 && aIndexPrev1 < aIndexesF[iF], aLastPrev = insert ? aIndexesF[iF] : aIndexPrev1, aFirst = insert ? aLastPrev : aLastPrev + 1, bFirst = bF + aFirst - kF, nCommonF = countCommonItemsF(
aFirst + 1,
aEnd,
bFirst + 1,
bEnd,
isCommon
), aLast = aFirst + nCommonF;
if (aIndexPrev1 = aIndexesF[iF], aIndexesF[iF] = aLast, kMinOverlapF <= kF && kF <= kMaxOverlapF) {
let iR = (d2 - 1 - (kF + baDeltaLength)) / 2;
if (iR <= iMaxR && aIndexesR[iR] - 1 <= aLast) {
let bLastPrev = bF + aLastPrev - (insert ? kF + 1 : kF - 1), nCommonR = countCommonItemsR(
aStart,
aLastPrev,
bStart,
bLastPrev,
isCommon
), aIndexPrevFirst = aLastPrev - nCommonR, bIndexPrevFirst = bLastPrev - nCommonR, aEndPreceding = aIndexPrevFirst + 1, bEndPreceding = bIndexPrevFirst + 1;
division.nChangePreceding = d2 - 1, d2 - 1 === aEndPreceding + bEndPreceding - aStart - bStart ? (division.aEndPreceding = aStart, division.bEndPreceding = bStart) : (division.aEndPreceding = aEndPreceding, division.bEndPreceding = bEndPreceding), division.nCommonPreceding = nCommonR, nCommonR !== 0 && (division.aCommonPreceding = aEndPreceding, division.bCommonPreceding = bEndPreceding), division.nCommonFollowing = nCommonF, nCommonF !== 0 && (division.aCommonFollowing = aFirst + 1, division.bCommonFollowing = bFirst + 1);
let aStartFollowing = aLast + 1, bStartFollowing = bFirst + nCommonF + 1;
return division.nChangeFollowing = d2 - 1, d2 - 1 === aEnd + bEnd - aStartFollowing - bStartFollowing ? (division.aStartFollowing = aEnd, division.bStartFollowing = bEnd) : (division.aStartFollowing = aStartFollowing, division.bStartFollowing = bStartFollowing), !0;
}
}
}
return !1;
}, extendOverlappablePathsR = (d2, aStart, aEnd, bStart, bEnd, isCommon, aIndexesF, iMaxF, aIndexesR, iMaxR, division) => {
let bR = bEnd - aEnd, aLength = aEnd - aStart, baDeltaLength = bEnd - bStart - aLength, kMinOverlapR = baDeltaLength - d2, kMaxOverlapR = baDeltaLength + d2, aIndexPrev1 = NOT_YET_SET, nR = d2 < iMaxR ? d2 : iMaxR;
for (let iR = 0, kR = d2; iR <= nR; iR += 1, kR -= 2) {
let insert = iR === 0 || iR !== d2 && aIndexesR[iR] < aIndexPrev1, aLastPrev = insert ? aIndexesR[iR] : aIndexPrev1, aFirst = insert ? aLastPrev : aLastPrev - 1, bFirst = bR + aFirst - kR, nCommonR = countCommonItemsR(
aStart,
aFirst - 1,
bStart,
bFirst - 1,
isCommon
), aLast = aFirst - nCommonR;
if (aIndexPrev1 = aIndexesR[iR], aIndexesR[iR] = aLast, kMinOverlapR <= kR && kR <= kMaxOverlapR) {
let iF = (d2 + (kR - baDeltaLength)) / 2;
if (iF <= iMaxF && aLast - 1 <= aIndexesF[iF]) {
let bLast = bFirst - nCommonR;
if (division.nChangePreceding = d2, d2 === aLast + bLast - aStart - bStart ? (division.aEndPreceding = aStart, division.bEndPreceding = bStart) : (division.aEndPreceding = aLast, division.bEndPreceding = bLast), division.nCommonPreceding = nCommonR, nCommonR !== 0 && (division.aCommonPreceding = aLast, division.bCommonPreceding = bLast), division.nChangeFollowing = d2 - 1, d2 === 1)
division.nCommonFollowing = 0, division.aStartFollowing = aEnd, division.bStartFollowing = bEnd;
else {
let bLastPrev = bR + aLastPrev - (insert ? kR - 1 : kR + 1), nCommonF = countCommonItemsF(
aLastPrev,
aEnd,
bLastPrev,
bEnd,
isCommon
);
division.nCommonFollowing = nCommonF, nCommonF !== 0 && (division.aCommonFollowing = aLastPrev, division.bCommonFollowing = bLastPrev);
let aStartFollowing = aLastPrev + nCommonF, bStartFollowing = bLastPrev + nCommonF;
d2 - 1 === aEnd + bEnd - aStartFollowing - bStartFollowing ? (division.aStartFollowing = aEnd, division.bStartFollowing = bEnd) : (division.aStartFollowing = aStartFollowing, division.bStartFollowing = bStartFollowing);
}
return !0;
}
}
}
return !1;
}, divide = (nChange, aStart, aEnd, bStart, bEnd, isCommon, aIndexesF, aIndexesR, division) => {
let bF = bStart - aStart, bR = bEnd - aEnd, aLength = aEnd - aStart, bLength = bEnd - bStart, baDeltaLength = bLength - aLength, iMaxF = aLength, iMaxR = aLength;
if (aIndexesF[0] = aStart - 1, aIndexesR[0] = aEnd, baDeltaLength % 2 === 0) {
let dMin = (nChange || baDeltaLength) / 2, dMax = (aLength + bLength) / 2;
for (let d2 = 1; d2 <= dMax; d2 += 1)
if (iMaxF = extendPathsF(d2, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF), d2 < dMin)
iMaxR = extendPathsR(d2, aStart, bStart, bR, isCommon, aIndexesR, iMaxR);
else if (
// If a reverse path overlaps a forward path in the same diagonal,
// return a division of the index intervals at the middle change.
extendOverlappablePathsR(
d2,
aStart,
aEnd,
bStart,
bEnd,
isCommon,
aIndexesF,
iMaxF,
aIndexesR,
iMaxR,
division
)
)
return;
} else {
let dMin = ((nChange || baDeltaLength) + 1) / 2, dMax = (aLength + bLength + 1) / 2, d2 = 1;
for (iMaxF = extendPathsF(d2, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF), d2 += 1; d2 <= dMax; d2 += 1)
if (iMaxR = extendPathsR(
d2 - 1,
aStart,
bStart,
bR,
isCommon,
aIndexesR,
iMaxR
), d2 < dMin)
iMaxF = extendPathsF(d2, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF);
else if (
// If a forward path overlaps a reverse path in the same diagonal,
// return a division of the index intervals at the middle change.
extendOverlappablePathsF(
d2,
aStart,
aEnd,
bStart,
bEnd,
isCommon,
aIndexesF,
iMaxF,
aIndexesR,
iMaxR,
division
)
)
return;
}
throw new Error(
`${pkg}: no overlap aStart=${aStart} aEnd=${aEnd} bStart=${bStart} bEnd=${bEnd}`
);
}, findSubsequences = (nChange, aStart, aEnd, bStart, bEnd, transposed, callbacks, aIndexesF, aIndexesR, division) => {
if (bEnd - bStart < aEnd - aStart) {
if (transposed = !transposed, transposed && callbacks.length === 1) {
let { foundSubsequence: foundSubsequence2, isCommon: isCommon2 } = callbacks[0];
callbacks[1] = {
foundSubsequence: (nCommon, bCommon, aCommon) => {
foundSubsequence2(nCommon, aCommon, bCommon);
},
isCommon: (bIndex, aIndex) => isCommon2(aIndex, bIndex)
};
}
let tStart = aStart, tEnd = aEnd;
aStart = bStart, aEnd = bEnd, bStart = tStart, bEnd = tEnd;
}
let { foundSubsequence, isCommon } = callbacks[transposed ? 1 : 0];
divide(
nChange,
aStart,
aEnd,
bStart,
bEnd,
isCommon,
aIndexesF,
aIndexesR,
division
);
let {
nChangePreceding,
aEndPreceding,
bEndPreceding,
nCommonPreceding,
aCommonPreceding,
bCommonPreceding,
nCommonFollowing,
aCommonFollowing,
bCommonFollowing,
nChangeFollowing,
aStartFollowing,
bStartFollowing
} = division;
aStart < aEndPreceding && bStart < bEndPreceding && findSubsequences(
nChangePreceding,
aStart,
aEndPreceding,
bStart,
bEndPreceding,
transposed,
callbacks,
aIndexesF,
aIndexesR,
division
), nCommonPreceding !== 0 && foundSubsequence(nCommonPreceding, aCommonPreceding, bCommonPreceding), nCommonFollowing !== 0 && foundSubsequence(nCommonFollowing, aCommonFollowing, bCommonFollowing), aStartFollowing < aEnd && bStartFollowing < bEnd && findSubsequences(
nChangeFollowing,
aStartFollowing,
aEnd,
bStartFollowing,
bEnd,
transposed,
callbacks,
aIndexesF,
aIndexesR,
division
);
}, validateLength = (name, arg) => {
if (typeof arg != "number")
throw new TypeError(`${pkg}: ${name} typeof ${typeof arg} is not a number`);
if (!Number.isSafeInteger(arg))
throw new RangeError(`${pkg}: ${name} value ${arg} is not a safe integer`);
if (arg < 0)
throw new RangeError(`${pkg}: ${name} value ${arg} is a negative integer`);
}, validateCallback = (name, arg) => {
let type3 = typeof arg;
if (type3 !== "function")
throw new TypeError(`${pkg}: ${name} typeof ${type3} is not a function`);
};
function diffSequence(aLength, bLength, isCommon, foundSubsequence) {
validateLength("aLength", aLength), validateLength("bLength", bLength), validateCallback("isCommon", isCommon), validateCallback("foundSubsequence", foundSubsequence);
let nCommonF = countCommonItemsF(0, aLength, 0, bLength, isCommon);
if (nCommonF !== 0 && foundSubsequence(nCommonF, 0, 0), aLength !== nCommonF || bLength !== nCommonF) {
let aStart = nCommonF, bStart = nCommonF, nCommonR = countCommonItemsR(
aStart,
aLength - 1,
bStart,
bLength - 1,
isCommon
), aEnd = aLength - nCommonR, bEnd = bLength - nCommonR, nCommonFR = nCommonF + nCommonR;
aLength !== nCommonFR && bLength !== nCommonFR && findSubsequences(
0,
aStart,
aEnd,
bStart,
bEnd,
!1,
[
{
foundSubsequence,
isCommon
}
],
[NOT_YET_SET],
[NOT_YET_SET],
{
aCommonFollowing: NOT_YET_SET,
aCommonPreceding: NOT_YET_SET,
aEndPreceding: NOT_YET_SET,
aStartFollowing: NOT_YET_SET,
bCommonFollowing: NOT_YET_SET,
bCommonPreceding: NOT_YET_SET,
bEndPreceding: NOT_YET_SET,
bStartFollowing: NOT_YET_SET,
nChangeFollowing: NOT_YET_SET,
nChangePreceding: NOT_YET_SET,
nCommonFollowing: NOT_YET_SET,
nCommonPreceding: NOT_YET_SET
}
), nCommonR !== 0 && foundSubsequence(nCommonR, aEnd, bEnd);
}
}
return build;
}
var buildExports = /* @__PURE__ */ requireBuild(), diffSequences = /* @__PURE__ */ getDefaultExportFromCjs2(buildExports);
function formatTrailingSpaces(line, trailingSpaceFormatter) {
return line.replace(/\s+$/, (match) => trailingSpaceFormatter(match));
}
function printDiffLine(line, isFirstOrLast, color, indicator, trailingSpaceFormatter, emptyFirstOrLastLinePlaceholder) {
return line.length !== 0 ? color(`${indicator} ${formatTrailingSpaces(line, trailingSpaceFormatter)}`) : indicator !== " " ? color(indicator) : isFirstOrLast && emptyFirstOrLastLinePlaceholder.length !== 0 ? color(`${indicator} ${emptyFirstOrLastLinePlaceholder}`) : "";
}
function printDeleteLine(line, isFirstOrLast, { aColor, aIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) {
return printDiffLine(line, isFirstOrLast, aColor, aIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder);
}
function printInsertLine(line, isFirstOrLast, { bColor, bIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) {
return printDiffLine(line, isFirstOrLast, bColor, bIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder);
}
function printCommonLine(line, isFirstOrLast, { commonColor, commonIndicator, commonLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) {
return printDiffLine(line, isFirstOrLast, commonColor, commonIndicator, commonLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder);
}
function createPatchMark(aStart, aEnd, bStart, bEnd, { patchColor }) {
return patchColor(`@@ -${aStart + 1},${aEnd - aStart} +${bStart + 1},${bEnd - bStart} @@`);
}
function joinAlignedDiffsNoExpand(diffs, options) {
let iLength = diffs.length, nContextLines = options.contextLines, nContextLines2 = nContextLines + nContextLines, jLength = iLength, hasExcessAtStartOrEnd = !1, nExcessesBetweenChanges = 0, i2 = 0;
for (; i2 !== iLength; ) {
let iStart = i2;
for (; i2 !== iLength && diffs[i2][0] === DIFF_EQUAL; )
i2 += 1;
if (iStart !== i2)
if (iStart === 0)
i2 > nContextLines && (jLength -= i2 - nContextLines, hasExcessAtStartOrEnd = !0);
else if (i2 === iLength) {
let n = i2 - iStart;
n > nContextLines && (jLength -= n - nContextLines, hasExcessAtStartOrEnd = !0);
} else {
let n = i2 - iStart;
n > nContextLines2 && (jLength -= n - nContextLines2, nExcessesBetweenChanges += 1);
}
for (; i2 !== iLength && diffs[i2][0] !== DIFF_EQUAL; )
i2 += 1;
}
let hasPatch = nExcessesBetweenChanges !== 0 || hasExcessAtStartOrEnd;
nExcessesBetweenChanges !== 0 ? jLength += nExcessesBetweenChanges + 1 : hasExcessAtStartOrEnd && (jLength += 1);
let jLast = jLength - 1, lines = [], jPatchMark = 0;
hasPatch && lines.push("");
let aStart = 0, bStart = 0, aEnd = 0, bEnd = 0, pushCommonLine = (line) => {
let j = lines.length;
lines.push(printCommonLine(line, j === 0 || j === jLast, options)), aEnd += 1, bEnd += 1;
}, pushDeleteLine = (line) => {
let j = lines.length;
lines.push(printDeleteLine(line, j === 0 || j === jLast, options)), aEnd += 1;
}, pushInsertLine = (line) => {
let j = lines.length;
lines.push(printInsertLine(line, j === 0 || j === jLast, options)), bEnd += 1;
};
for (i2 = 0; i2 !== iLength; ) {
let iStart = i2;
for (; i2 !== iLength && diffs[i2][0] === DIFF_EQUAL; )
i2 += 1;
if (iStart !== i2)
if (iStart === 0) {
i2 > nContextLines && (iStart = i2 - nContextLines, aStart = iStart, bStart = iStart, aEnd = aStart, bEnd = bStart);
for (let iCommon = iStart; iCommon !== i2; iCommon += 1)
pushCommonLine(diffs[iCommon][1]);
} else if (i2 === iLength) {
let iEnd = i2 - iStart > nContextLines ? iStart + nContextLines : i2;
for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1)
pushCommonLine(diffs[iCommon][1]);
} else {
let nCommon = i2 - iStart;
if (nCommon > nContextLines2) {
let iEnd = iStart + nContextLines;
for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1)
pushCommonLine(diffs[iCommon][1]);
lines[jPatchMark] = createPatchMark(aStart, aEnd, bStart, bEnd, options), jPatchMark = lines.length, lines.push("");
let nOmit = nCommon - nContextLines2;
aStart = aEnd + nOmit, bStart = bEnd + nOmit, aEnd = aStart, bEnd = bStart;
for (let iCommon = i2 - nContextLines; iCommon !== i2; iCommon += 1)
pushCommonLine(diffs[iCommon][1]);
} else
for (let iCommon = iStart; iCommon !== i2; iCommon += 1)
pushCommonLine(diffs[iCommon][1]);
}
for (; i2 !== iLength && diffs[i2][0] === DIFF_DELETE; )
pushDeleteLine(diffs[i2][1]), i2 += 1;
for (; i2 !== iLength && diffs[i2][0] === DIFF_INSERT; )
pushInsertLine(diffs[i2][1]), i2 += 1;
}
return hasPatch && (lines[jPatchMark] = createPatchMark(aStart, aEnd, bStart, bEnd, options)), lines.join(`
`);
}
function joinAlignedDiffsExpand(diffs, options) {
return diffs.map((diff2, i2, diffs2) => {
let line = diff2[1], isFirstOrLast = i2 === 0 || i2 === diffs2.length - 1;
switch (diff2[0]) {
case DIFF_DELETE:
return printDeleteLine(line, isFirstOrLast, options);
case DIFF_INSERT:
return printInsertLine(line, isFirstOrLast, options);
default:
return printCommonLine(line, isFirstOrLast, options);
}
}).join(`
`);
}
var noColor = (string2) => string2, DIFF_CONTEXT_DEFAULT = 5, DIFF_TRUNCATE_THRESHOLD_DEFAULT = 0;
function getDefaultOptions() {
return {
aAnnotation: "Expected",
aColor: y.green,
aIndicator: "-",
bAnnotation: "Received",
bColor: y.red,
bIndicator: "+",
changeColor: y.inverse,
changeLineTrailingSpaceColor: noColor,
commonColor: y.dim,
commonIndicator: " ",
commonLineTrailingSpaceColor: noColor,
compareKeys: void 0,
contextLines: DIFF_CONTEXT_DEFAULT,
emptyFirstOrLastLinePlaceholder: "",
expand: !1,
includeChangeCounts: !1,
omitAnnotationLines: !1,
patchColor: y.yellow,
printBasicPrototype: !1,
truncateThreshold: DIFF_TRUNCATE_THRESHOLD_DEFAULT,
truncateAnnotation: "... Diff result is truncated",
truncateAnnotationColor: noColor
};
}
function getCompareKeys(compareKeys) {
return compareKeys && typeof compareKeys == "function" ? compareKeys : void 0;
}
function getContextLines(contextLines) {
return typeof contextLines == "number" && Number.isSafeInteger(contextLines) && contextLines >= 0 ? contextLines : DIFF_CONTEXT_DEFAULT;
}
function normalizeDiffOptions(options = {}) {
return {
...getDefaultOptions(),
...options,
compareKeys: getCompareKeys(options.compareKeys),
contextLines: getContextLines(options.contextLines)
};
}
function isEmptyString(lines) {
return lines.length === 1 && lines[0].length === 0;
}
function countChanges(diffs) {
let a = 0, b2 = 0;
return diffs.forEach((diff2) => {
switch (diff2[0]) {
case DIFF_DELETE:
a += 1;
break;
case DIFF_INSERT:
b2 += 1;
break;
}
}), {
a,
b: b2
};
}
function printAnnotation({ aAnnotation, aColor, aIndicator, bAnnotation, bColor, bIndicator, includeChangeCounts, omitAnnotationLines }, changeCounts) {
if (omitAnnotationLines)
return "";
let aRest = "", bRest = "";
if (includeChangeCounts) {
let aCount = String(changeCounts.a), bCount = String(changeCounts.b), baAnnotationLengthDiff = bAnnotation.length - aAnnotation.length, aAnnotationPadding = " ".repeat(Math.max(0, baAnnotationLengthDiff)), bAnnotationPadding = " ".repeat(Math.max(0, -baAnnotationLengthDiff)), baCountLengthDiff = bCount.length - aCount.length, aCountPadding = " ".repeat(Math.max(0, baCountLengthDiff)), bCountPadding = " ".repeat(Math.max(0, -baCountLengthDiff));
aRest = `${aAnnotationPadding} ${aIndicator} ${aCountPadding}${aCount}`, bRest = `${bAnnotationPadding} ${bIndicator} ${bCountPadding}${bCount}`;
}
let a = `${aIndicator} ${aAnnotation}${aRest}`, b2 = `${bIndicator} ${bAnnotation}${bRest}`;
return `${aColor(a)}
${bColor(b2)}
`;
}
function printDiffLines(diffs, truncated, options) {
return printAnnotation(options, countChanges(diffs)) + (options.expand ? joinAlignedDiffsExpand(diffs, options) : joinAlignedDiffsNoExpand(diffs, options)) + (truncated ? options.truncateAnnotationColor(`
${options.truncateAnnotation}`) : "");
}
function diffLinesUnified(aLines, bLines, options) {
let normalizedOptions = normalizeDiffOptions(options), [diffs, truncated] = diffLinesRaw(isEmptyString(aLines) ? [] : aLines, isEmptyString(bLines) ? [] : bLines, normalizedOptions);
return printDiffLines(diffs, truncated, normalizedOptions);
}
function diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options) {
if (isEmptyString(aLinesDisplay) && isEmptyString(aLinesCompare) && (aLinesDisplay = [], aLinesCompare = []), isEmptyString(bLinesDisplay) && isEmptyString(bLinesCompare) && (bLinesDisplay = [], bLinesCompare = []), aLinesDisplay.length !== aLinesCompare.length || bLinesDisplay.length !== bLinesCompare.length)
return diffLinesUnified(aLinesDisplay, bLinesDisplay, options);
let [diffs, truncated] = diffLinesRaw(aLinesCompare, bLinesCompare, options), aIndex = 0, bIndex = 0;
return diffs.forEach((diff2) => {
switch (diff2[0]) {
case DIFF_DELETE:
diff2[1] = aLinesDisplay[aIndex], aIndex += 1;
break;
case DIFF_INSERT:
diff2[1] = bLinesDisplay[bIndex], bIndex += 1;
break;
default:
diff2[1] = bLinesDisplay[bIndex], aIndex += 1, bIndex += 1;
}
}), printDiffLines(diffs, truncated, normalizeDiffOptions(options));
}
function diffLinesRaw(aLines, bLines, options) {
let truncate3 = options?.truncateThreshold ?? !1, truncateThreshold = Math.max(Math.floor(options?.truncateThreshold ?? 0), 0), aLength = truncate3 ? Math.min(aLines.length, truncateThreshold) : aLines.length, bLength = truncate3 ? Math.min(bLines.length, truncateThreshold) : bLines.length, truncated = aLength !== aLines.length || bLength !== bLines.length, isCommon = (aIndex2, bIndex2) => aLines[aIndex2] === bLines[bIndex2], diffs = [], aIndex = 0, bIndex = 0;
for (diffSequences(aLength, bLength, isCommon, (nCommon, aCommon, bCommon) => {
for (; aIndex !== aCommon; aIndex += 1)
diffs.push(new Diff(DIFF_DELETE, aLines[aIndex]));
for (; bIndex !== bCommon; bIndex += 1)
diffs.push(new Diff(DIFF_INSERT, bLines[bIndex]));
for (; nCommon !== 0; nCommon -= 1, aIndex += 1, bIndex += 1)
diffs.push(new Diff(DIFF_EQUAL, bLines[bIndex]));
}); aIndex !== aLength; aIndex += 1)
diffs.push(new Diff(DIFF_DELETE, aLines[aIndex]));
for (; bIndex !== bLength; bIndex += 1)
diffs.push(new Diff(DIFF_INSERT, bLines[bIndex]));
return [diffs, truncated];
}
function getType3(value) {
if (value === void 0)
return "undefined";
if (value === null)
return "null";
if (Array.isArray(value))
return "array";
if (typeof value == "boolean")
return "boolean";
if (typeof value == "function")
return "function";
if (typeof value == "number")
return "number";
if (typeof value == "string")
return "string";
if (typeof value == "bigint")
return "bigint";
if (typeof value == "object") {
if (value != null) {
if (value.constructor === RegExp)
return "regexp";
if (value.constructor === Map)
return "map";
if (value.constructor === Set)
return "set";
if (value.constructor === Date)
return "date";
}
return "object";
} else if (typeof value == "symbol")
return "symbol";
throw new Error(`value of unknown type: ${value}`);
}
function getNewLineSymbol(string2) {
return string2.includes(`\r
`) ? `\r
` : `
`;
}
function diffStrings(a, b2, options) {
let truncate3 = options?.truncateThreshold ?? !1, truncateThreshold = Math.max(Math.floor(options?.truncateThreshold ?? 0), 0), aLength = a.length, bLength = b2.length;
if (truncate3) {
let aMultipleLines = a.includes(`
`), bMultipleLines = b2.includes(`
`), aNewLineSymbol = getNewLineSymbol(a), bNewLineSymbol = getNewLineSymbol(b2), _a = aMultipleLines ? `${a.split(aNewLineSymbol, truncateThreshold).join(aNewLineSymbol)}
` : a, _b = bMultipleLines ? `${b2.split(bNewLineSymbol, truncateThreshold).join(bNewLineSymbol)}
` : b2;
aLength = _a.length, bLength = _b.length;
}
let truncated = aLength !== a.length || bLength !== b2.length, isCommon = (aIndex2, bIndex2) => a[aIndex2] === b2[bIndex2], aIndex = 0, bIndex = 0, diffs = [];
return diffSequences(aLength, bLength, isCommon, (nCommon, aCommon, bCommon) => {
aIndex !== aCommon && diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex, aCommon))), bIndex !== bCommon && diffs.push(new Diff(DIFF_INSERT, b2.slice(bIndex, bCommon))), aIndex = aCommon + nCommon, bIndex = bCommon + nCommon, diffs.push(new Diff(DIFF_EQUAL, b2.slice(bCommon, bIndex)));
}), aIndex !== aLength && diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex))), bIndex !== bLength && diffs.push(new Diff(DIFF_INSERT, b2.slice(bIndex))), [diffs, truncated];
}
function concatenateRelevantDiffs(op, diffs, changeColor) {
return diffs.reduce((reduced, diff2) => reduced + (diff2[0] === DIFF_EQUAL ? diff2[1] : diff2[0] === op && diff2[1].length !== 0 ? changeColor(diff2[1]) : ""), "");
}
var ChangeBuffer = class {
op;
line;
lines;
changeColor;
constructor(op, changeColor) {
this.op = op, this.line = [], this.lines = [], this.changeColor = changeColor;
}
pushSubstring(substring) {
this.pushDiff(new Diff(this.op, substring));
}
pushLine() {
this.lines.push(this.line.length !== 1 ? new Diff(this.op, concatenateRelevantDiffs(this.op, this.line, this.changeColor)) : this.line[0][0] === this.op ? this.line[0] : new Diff(this.op, this.line[0][1])), this.line.length = 0;
}
isLineEmpty() {
return this.line.length === 0;
}
// Minor input to buffer.
pushDiff(diff2) {
this.line.push(diff2);
}
// Main input to buffer.
align(diff2) {
let string2 = diff2[1];
if (string2.includes(`
`)) {
let substrings = string2.split(`
`), iLast = substrings.length - 1;
substrings.forEach((substring, i2) => {
i2 < iLast ? (this.pushSubstring(substring), this.pushLine()) : substring.length !== 0 && this.pushSubstring(substring);
});
} else
this.pushDiff(diff2);
}
// Output from buffer.
moveLinesTo(lines) {
this.isLineEmpty() || this.pushLine(), lines.push(...this.lines), this.lines.length = 0;
}
}, CommonBuffer = class {
deleteBuffer;
insertBuffer;
lines;
constructor(deleteBuffer, insertBuffer) {
this.deleteBuffer = deleteBuffer, this.insertBuffer = insertBuffer, this.lines = [];
}
pushDiffCommonLine(diff2) {
this.lines.push(diff2);
}
pushDiffChangeLines(diff2) {
let isDiffEmpty = diff2[1].length === 0;
(!isDiffEmpty || this.deleteBuffer.isLineEmpty()) && this.deleteBuffer.pushDiff(diff2), (!isDiffEmpty || this.insertBuffer.isLineEmpty()) && this.insertBuffer.pushDiff(diff2);
}
flushChangeLines() {
this.deleteBuffer.moveLinesTo(this.lines), this.insertBuffer.moveLinesTo(this.lines);
}
// Input to buffer.
align(diff2) {
let op = diff2[0], string2 = diff2[1];
if (string2.includes(`
`)) {
let substrings = string2.split(`
`), iLast = substrings.length - 1;
substrings.forEach((substring, i2) => {
if (i2 === 0) {
let subdiff = new Diff(op, substring);
this.deleteBuffer.isLineEmpty() && this.insertBuffer.isLineEmpty() ? (this.flushChangeLines(), this.pushDiffCommonLine(subdiff)) : (this.pushDiffChangeLines(subdiff), this.flushChangeLines());
} else i2 < iLast ? this.pushDiffCommonLine(new Diff(op, substring)) : substring.length !== 0 && this.pushDiffChangeLines(new Diff(op, substring));
});
} else
this.pushDiffChangeLines(diff2);
}
// Output from buffer.
getLines() {
return this.flushChangeLines(), this.lines;
}
};
function getAlignedDiffs(diffs, changeColor) {
let deleteBuffer = new ChangeBuffer(DIFF_DELETE, changeColor), insertBuffer = new ChangeBuffer(DIFF_INSERT, changeColor), commonBuffer = new CommonBuffer(deleteBuffer, insertBuffer);
return diffs.forEach((diff2) => {
switch (diff2[0]) {
case DIFF_DELETE:
deleteBuffer.align(diff2);
break;
case DIFF_INSERT:
insertBuffer.align(diff2);
break;
default:
commonBuffer.align(diff2);
}
}), commonBuffer.getLines();
}
function hasCommonDiff(diffs, isMultiline) {
if (isMultiline) {
let iLast = diffs.length - 1;
return diffs.some((diff2, i2) => diff2[0] === DIFF_EQUAL && (i2 !== iLast || diff2[1] !== `
`));
}
return diffs.some((diff2) => diff2[0] === DIFF_EQUAL);
}
function diffStringsUnified(a, b2, options) {
if (a !== b2 && a.length !== 0 && b2.length !== 0) {
let isMultiline = a.includes(`
`) || b2.includes(`
`), [diffs, truncated] = diffStringsRaw(isMultiline ? `${a}
` : a, isMultiline ? `${b2}
` : b2, !0, options);
if (hasCommonDiff(diffs, isMultiline)) {
let optionsNormalized = normalizeDiffOptions(options), lines = getAlignedDiffs(diffs, optionsNormalized.changeColor);
return printDiffLines(lines, truncated, optionsNormalized);
}
}
return diffLinesUnified(a.split(`
`), b2.split(`
`), options);
}
function diffStringsRaw(a, b2, cleanup, options) {
let [diffs, truncated] = diffStrings(a, b2, options);
return cleanup && diff_cleanupSemantic(diffs), [diffs, truncated];
}
function getCommonMessage(message, options) {
let { commonColor } = normalizeDiffOptions(options);
return commonColor(message);
}
var { AsymmetricMatcher: AsymmetricMatcher2, DOMCollection: DOMCollection2, DOMElement: DOMElement2, Immutable: Immutable2, ReactElement: ReactElement2, ReactTestComponent: ReactTestComponent2 } = plugins, PLUGINS2 = [
ReactTestComponent2,
ReactElement2,
DOMElement2,
DOMCollection2,
Immutable2,
AsymmetricMatcher2,
plugins.Error
], FORMAT_OPTIONS = {
maxDepth: 20,
plugins: PLUGINS2
}, FALLBACK_FORMAT_OPTIONS = {
callToJSON: !1,
maxDepth: 8,
plugins: PLUGINS2
}, DEFAULT_MEMORIZE = (_, v) => v;
function diff(a, b2, options, memorize = DEFAULT_MEMORIZE) {
if (Object.is(a, b2))
return "";
let aType = getType3(a), expectedType = aType, omitDifference = !1;
if (aType === "object" && typeof a.asymmetricMatch == "function") {
if (a.$$typeof !== /* @__PURE__ */ Symbol.for("jest.asymmetricMatcher") || typeof a.getExpectedType != "function")
return;
expectedType = a.getExpectedType(), omitDifference = expectedType === "string";
}
if (expectedType !== getType3(b2)) {
let truncate3 = function(s) {
return s.length <= MAX_LENGTH ? s : `${s.slice(0, MAX_LENGTH)}...`;
}, { aAnnotation, aColor, aIndicator, bAnnotation, bColor, bIndicator } = normalizeDiffOptions(options), formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options), aDisplay = format(a, formatOptions), bDisplay = format(b2, formatOptions), MAX_LENGTH = 1e5;
aDisplay = memorize("expected", truncate3(aDisplay)), bDisplay = memorize("actual", truncate3(bDisplay));
let aDiff = `${aColor(`${aIndicator} ${aAnnotation}:`)}
${aDisplay}`, bDiff = `${bColor(`${bIndicator} ${bAnnotation}:`)}
${bDisplay}`;
return `${aDiff}
${bDiff}`;
}
if (!omitDifference)
switch (aType) {
case "string":
return diffLinesUnified(a.split(`
`), b2.split(`
`), options);
case "boolean":
case "number":
return comparePrimitive(a, b2, options, memorize);
case "map":
return compareObjects(sortMap(a), sortMap(b2), options, memorize);
case "set":
return compareObjects(sortSet(a), sortSet(b2), options, memorize);
default:
return compareObjects(a, b2, options, memorize);
}
}
function createMemorize(memory) {
return (pointer, stringifiedValue) => (memory[pointer] = stringifiedValue, stringifiedValue);
}
function comparePrimitive(a, b2, options, memorize = DEFAULT_MEMORIZE) {
let aFormat = memorize("expected", format(a, FORMAT_OPTIONS)), bFormat = memorize("actual", format(b2, FORMAT_OPTIONS));
return aFormat === bFormat ? "" : diffLinesUnified(aFormat.split(`
`), bFormat.split(`
`), options);
}
function sortMap(map2) {
return new Map(Array.from(map2.entries()).sort());
}
function sortSet(set3) {
return new Set(Array.from(set3.values()).sort());
}
function compareObjects(a, b2, options, memorize = DEFAULT_MEMORIZE) {
let difference, hasThrown = !1;
try {
let formatOptions = getFormatOptions(FORMAT_OPTIONS, options);
difference = getObjectsDifference(a, b2, formatOptions, options, memorize);
} catch {
hasThrown = !0;
}
let noDiffMessage = getCommonMessage(NO_DIFF_MESSAGE, options);
if (difference === void 0 || difference === noDiffMessage) {
let formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options);
difference = getObjectsDifference(a, b2, formatOptions, options, memorize), difference !== noDiffMessage && !hasThrown && (difference = `${getCommonMessage(SIMILAR_MESSAGE, options)}
${difference}`);
}
return difference;
}
function getDefaultFormatOptions(options) {
return getFormatOptions(FORMAT_OPTIONS, options);
}
function getFormatOptions(formatOptions, options) {
let { compareKeys, printBasicPrototype, maxDepth } = normalizeDiffOptions(options);
return {
...formatOptions,
compareKeys,
printBasicPrototype,
maxDepth: maxDepth ?? formatOptions.maxDepth
};
}
function getObjectsDifference(a, b2, formatOptions, options, memorize = DEFAULT_MEMORIZE) {
let formatOptionsZeroIndent = {
...formatOptions,
indent: 0
}, aCompare = format(a, formatOptionsZeroIndent), bCompare = format(b2, formatOptionsZeroIndent);
if (aCompare === bCompare)
return getCommonMessage(NO_DIFF_MESSAGE, options);
{
let aDisplay = memorize("expected", format(a, formatOptions)), bDisplay = memorize("actual", format(b2, formatOptions));
return diffLinesUnified2(aDisplay.split(`
`), bDisplay.split(`
`), aCompare.split(`
`), bCompare.split(`
`), options);
}
}
var MAX_DIFF_STRING_LENGTH = 2e4;
function isAsymmetricMatcher(data) {
return getType2(data) === "Object" && typeof data.asymmetricMatch == "function";
}
function isReplaceable(obj1, obj2) {
let obj1Type = getType2(obj1), obj2Type = getType2(obj2);
return obj1Type === obj2Type && (obj1Type === "Object" || obj1Type === "Array");
}
function printDiffOrStringify(received, expected, options, memory) {
let { aAnnotation, bAnnotation } = normalizeDiffOptions(options);
if (typeof expected == "string" && typeof received == "string" && expected.length > 0 && received.length > 0 && expected.length <= MAX_DIFF_STRING_LENGTH && received.length <= MAX_DIFF_STRING_LENGTH && expected !== received) {
if (expected.includes(`
`) || received.includes(`
`))
return diffStringsUnified(expected, received, options);
let [diffs] = diffStringsRaw(expected, received, !0), hasCommonDiff2 = diffs.some((diff2) => diff2[0] === DIFF_EQUAL), printLabel = getLabelPrinter(aAnnotation, bAnnotation), expectedLine = printLabel(aAnnotation) + printExpected(getCommonAndChangedSubstrings(diffs, DIFF_DELETE, hasCommonDiff2)), receivedLine = printLabel(bAnnotation) + printReceived(getCommonAndChangedSubstrings(diffs, DIFF_INSERT, hasCommonDiff2));
return `${expectedLine}
${receivedLine}`;
}
let clonedExpected = deepClone(expected, { forceWritable: !0 }), clonedReceived = deepClone(received, { forceWritable: !0 }), { replacedExpected, replacedActual } = replaceAsymmetricMatcher(clonedReceived, clonedExpected), memorize = memory ? createMemorize(memory) : DEFAULT_MEMORIZE;
return diff(replacedExpected, replacedActual, options, memorize);
}
function replaceAsymmetricMatcher(actual, expected, actualReplaced = /* @__PURE__ */ new WeakSet(), expectedReplaced = /* @__PURE__ */ new WeakSet()) {
return actual instanceof Error && expected instanceof Error && typeof actual.cause < "u" && typeof expected.cause > "u" ? (delete actual.cause, {
replacedActual: actual,
replacedExpected: expected
}) : isReplaceable(actual, expected) ? actualReplaced.has(actual) || expectedReplaced.has(expected) ? {
replacedActual: actual,
replacedExpected: expected
} : (actualReplaced.add(actual), expectedReplaced.add(expected), getOwnProperties(expected).forEach((key) => {
let expectedValue = expected[key], actualValue = actual[key];
if (isAsymmetricMatcher(expectedValue)) {
if (expectedValue.asymmetricMatch(actualValue))
expected[key] = actualValue;
else if ("sample" in expectedValue && expectedValue.sample !== void 0 && isReplaceable(actualValue, expectedValue.sample)) {
let replaced = replaceAsymmetricMatcher(actualValue, expectedValue.sample, actualReplaced, expectedReplaced);
actual[key] = replaced.replacedActual, expected[key] = replaced.replacedExpected;
}
} else if (isAsymmetricMatcher(actualValue)) {
if (actualValue.asymmetricMatch(expectedValue))
actual[key] = expectedValue;
else if ("sample" in actualValue && actualValue.sample !== void 0 && isReplaceable(actualValue.sample, expectedValue)) {
let replaced = replaceAsymmetricMatcher(actualValue.sample, expectedValue, actualReplaced, expectedReplaced);
actual[key] = replaced.replacedActual, expected[key] = replaced.replacedExpected;
}
} else if (isReplaceable(actualValue, expectedValue)) {
let replaced = replaceAsymmetricMatcher(actualValue, expectedValue, actualReplaced, expectedReplaced);
actual[key] = replaced.replacedActual, expected[key] = replaced.replacedExpected;
}
}), {
replacedActual: actual,
replacedExpected: expected
}) : {
replacedActual: actual,
replacedExpected: expected
};
}
function getLabelPrinter(...strings) {
let maxLength = strings.reduce((max, string2) => string2.length > max ? string2.length : max, 0);
return (string2) => `${string2}: ${" ".repeat(maxLength - string2.length)}`;
}
var SPACE_SYMBOL = "\xB7";
function replaceTrailingSpaces(text) {
return text.replace(/\s+$/gm, (spaces) => SPACE_SYMBOL.repeat(spaces.length));
}
function printReceived(object2) {
return y.red(replaceTrailingSpaces(stringify(object2)));
}
function printExpected(value) {
return y.green(replaceTrailingSpaces(stringify(value)));
}
function getCommonAndChangedSubstrings(diffs, op, hasCommonDiff2) {
return diffs.reduce((reduced, diff2) => reduced + (diff2[0] === DIFF_EQUAL ? diff2[1] : diff2[0] === op ? hasCommonDiff2 ? y.inverse(diff2[1]) : diff2[1] : ""), "");
}
// ../../node_modules/.pnpm/@vitest+utils@4.1.10/node_modules/@vitest/utils/dist/serialize.js
init_cjs_shims();
var IS_RECORD_SYMBOL = "@@__IMMUTABLE_RECORD__@@", IS_COLLECTION_SYMBOL = "@@__IMMUTABLE_ITERABLE__@@";
function isImmutable(v) {
return v && (v[IS_COLLECTION_SYMBOL] || v[IS_RECORD_SYMBOL]);
}
var OBJECT_PROTO = Object.getPrototypeOf({});
function getUnserializableMessage(err) {
return err instanceof Error ? `<unserializable>: ${err.message}` : typeof err == "string" ? `<unserializable>: ${err}` : "<unserializable>";
}
function serializeValue(val, seen = /* @__PURE__ */ new WeakMap()) {
if (!val || typeof val == "string")
return val;
if (val instanceof Error && "toJSON" in val && typeof val.toJSON == "function") {
let jsonValue = val.toJSON();
return jsonValue && jsonValue !== val && typeof jsonValue == "object" && (typeof val.message == "string" && safe(() => jsonValue.message ??= normalizeErrorMessage(val.message)), typeof val.stack == "string" && safe(() => jsonValue.stack ??= val.stack), typeof val.name == "string" && safe(() => jsonValue.name ??= val.name), val.cause != null && safe(() => jsonValue.cause ??= serializeValue(val.cause, seen))), serializeValue(jsonValue, seen);
}
if (typeof val == "function")
return `Function<${val.name || "anonymous"}>`;
if (typeof val == "symbol")
return val.toString();
if (typeof val != "object")
return val;
if (typeof Buffer < "u" && val instanceof Buffer)
return `<Buffer(${val.length}) ...>`;
if (typeof Uint8Array < "u" && val instanceof Uint8Array)
return `<Uint8Array(${val.length}) ...>`;
if (isImmutable(val))
return serializeValue(val.toJSON(), seen);
if (val instanceof Promise || val.constructor && val.constructor.prototype === "AsyncFunction")
return "Promise";
if (typeof Element < "u" && val instanceof Element)
return val.tagName;
if (typeof val.toJSON == "function")
return serializeValue(val.toJSON(), seen);
if (seen.has(val))
return seen.get(val);
if (Array.isArray(val)) {
let clone2 = new Array(val.length);
return seen.set(val, clone2), val.forEach((e, i2) => {
try {
clone2[i2] = serializeValue(e, seen);
} catch (err) {
clone2[i2] = getUnserializableMessage(err);
}
}), clone2;
} else {
let clone2 = /* @__PURE__ */ Object.create(null);
seen.set(val, clone2);
let obj = val;
for (; obj && obj !== OBJECT_PROTO; )
Object.getOwnPropertyNames(obj).forEach((key) => {
if (!(key in clone2))
try {
clone2[key] = serializeValue(val[key], seen);
} catch (err) {
delete clone2[key], clone2[key] = getUnserializableMessage(err);
}
}), obj = Object.getPrototypeOf(obj);
return val instanceof Error && safe(() => clone2.message = normalizeErrorMessage(val.message)), clone2;
}
}
function safe(fn2) {
try {
return fn2();
} catch {
}
}
function normalizeErrorMessage(message) {
return message.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/getByTestId('__vitest_\d+__')/g, "page");
}
// ../../node_modules/.pnpm/@vitest+utils@4.1.10/node_modules/@vitest/utils/dist/error.js
function processError(_err, diffOptions, seen = /* @__PURE__ */ new WeakSet()) {
if (!_err || typeof _err != "object")
return { message: String(_err) };
let err = _err;
if (err.showDiff || err.showDiff === void 0 && err.expected !== void 0 && err.actual !== void 0) {
let options = {
...diffOptions,
...err.diffOptions
};
err.diff = printDiffOrStringify(err.actual, err.expected, options, err), err.expected = prettifyValue(err.expected, options), err.actual = prettifyValue(err.actual, options);
}
try {
!seen.has(err) && typeof err.cause == "object" && (seen.add(err), err.cause = processError(err.cause, diffOptions, seen));
} catch {
}
try {
return serializeValue(err);
} catch (e) {
return serializeValue(new Error(`Failed to fully serialize error: ${e?.message}
Inner error message: ${err?.message}`));
}
}
function prettifyValue(value, options) {
return typeof value != "string" ? format(value, getDefaultFormatOptions(options)) : value;
}
// ../../node_modules/.pnpm/@vitest+utils@4.1.10/node_modules/@vitest/utils/dist/timers.js
init_cjs_shims();
var SAFE_TIMERS_SYMBOL = /* @__PURE__ */ Symbol("vitest:SAFE_TIMERS");
function getSafeTimers() {
let { setTimeout: safeSetTimeout, setInterval: safeSetInterval, clearInterval: safeClearInterval, clearTimeout: safeClearTimeout, setImmediate: safeSetImmediate, clearImmediate: safeClearImmediate, queueMicrotask: safeQueueMicrotask } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis, { nextTick: safeNextTick } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis.process || {};
return {
nextTick: safeNextTick,
setTimeout: safeSetTimeout,
setInterval: safeSetInterval,
clearInterval: safeClearInterval,
clearTimeout: safeClearTimeout,
setImmediate: safeSetImmediate,
clearImmediate: safeClearImmediate,
queueMicrotask: safeQueueMicrotask
};
}
function delay(timeout, scheduler = setTimeout) {
return new Promise((resolve2) => scheduler(resolve2, timeout));
}
// ../../node_modules/.pnpm/@vitest+utils@4.1.10/node_modules/@vitest/utils/dist/source-map.js
init_cjs_shims();
// ../../node_modules/.pnpm/@vitest+utils@4.1.10/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js
init_cjs_shims();
var _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
function normalizeWindowsPath(input = "") {
return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
}
var _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
function cwd() {
return typeof process < "u" && typeof process.cwd == "function" ? process.cwd().replace(/\\/g, "/") : "/";
}
var resolve = function(...arguments_) {
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
let resolvedPath = "", resolvedAbsolute = !1;
for (let index2 = arguments_.length - 1; index2 >= -1 && !resolvedAbsolute; index2--) {
let path = index2 >= 0 ? arguments_[index2] : cwd();
!path || path.length === 0 || (resolvedPath = `${path}/${resolvedPath}`, resolvedAbsolute = isAbsolute(path));
}
return resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
};
function normalizeString(path, allowAboveRoot) {
let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
for (let index2 = 0; index2 <= path.length; ++index2) {
if (index2 < path.length)
char = path[index2];
else {
if (char === "/")
break;
char = "/";
}
if (char === "/") {
if (!(lastSlash === index2 - 1 || dots === 1)) if (dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
if (res.length > 2) {
let lastSlashIndex = res.lastIndexOf("/");
lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index2, dots = 0;
continue;
} else if (res.length > 0) {
res = "", lastSegmentLength = 0, lastSlash = index2, dots = 0;
continue;
}
}
allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
} else
res.length > 0 ? res += `/${path.slice(lastSlash + 1, index2)}` : res = path.slice(lastSlash + 1, index2), lastSegmentLength = index2 - lastSlash - 1;
lastSlash = index2, dots = 0;
} else char === "." && dots !== -1 ? ++dots : dots = -1;
}
return res;
}
var isAbsolute = function(p) {
return _IS_ABSOLUTE_RE.test(p);
};
// ../../node_modules/.pnpm/@vitest+utils@4.1.10/node_modules/@vitest/utils/dist/source-map.js
var comma = 44, chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", intToChar = new Uint8Array(64), charToInt = new Uint8Array(128);
for (let i2 = 0; i2 < chars.length; i2++) {
let c = chars.charCodeAt(i2);
intToChar[i2] = c, charToInt[c] = i2;
}
function decodeInteger(reader, relative) {
let value = 0, shift = 0, integer = 0;
do {
let c = reader.next();
integer = charToInt[c], value |= (integer & 31) << shift, shift += 5;
} while (integer & 32);
let shouldNegate = value & 1;
return value >>>= 1, shouldNegate && (value = -2147483648 | -value), relative + value;
}
function hasMoreVlq(reader, max) {
return reader.pos >= max ? !1 : reader.peek() !== comma;
}
var StringReader = class {
constructor(buffer) {
this.pos = 0, this.buffer = buffer;
}
next() {
return this.buffer.charCodeAt(this.pos++);
}
peek() {
return this.buffer.charCodeAt(this.pos);
}
indexOf(char) {
let { buffer, pos } = this, idx = buffer.indexOf(char, pos);
return idx === -1 ? buffer.length : idx;
}
};
function decode(mappings) {
let { length } = mappings, reader = new StringReader(mappings), decoded = [], genColumn = 0, sourcesIndex = 0, sourceLine = 0, sourceColumn = 0, namesIndex = 0;
do {
let semi = reader.indexOf(";"), line = [], sorted = !0, lastCol = 0;
for (genColumn = 0; reader.pos < semi; ) {
let seg;
genColumn = decodeInteger(reader, genColumn), genColumn < lastCol && (sorted = !1), lastCol = genColumn, hasMoreVlq(reader, semi) ? (sourcesIndex = decodeInteger(reader, sourcesIndex), sourceLine = decodeInteger(reader, sourceLine), sourceColumn = decodeInteger(reader, sourceColumn), hasMoreVlq(reader, semi) ? (namesIndex = decodeInteger(reader, namesIndex), seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]) : seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]) : seg = [genColumn], line.push(seg), reader.pos++;
}
sorted || sort(line), decoded.push(line), reader.pos = semi + 1;
} while (reader.pos <= length);
return decoded;
}
function sort(line) {
line.sort(sortComparator);
}
function sortComparator(a, b2) {
return a[0] - b2[0];
}
var COLUMN = 0, SOURCES_INDEX = 1, SOURCE_LINE = 2, SOURCE_COLUMN = 3, NAMES_INDEX = 4, found = !1;
function binarySearch(haystack, needle, low, high) {
for (; low <= high; ) {
let mid = low + (high - low >> 1), cmp = haystack[mid][COLUMN] - needle;
if (cmp === 0)
return found = !0, mid;
cmp < 0 ? low = mid + 1 : high = mid - 1;
}
return found = !1, low - 1;
}
function upperBound(haystack, needle, index2) {
for (let i2 = index2 + 1; i2 < haystack.length && haystack[i2][COLUMN] === needle; index2 = i2++)
;
return index2;
}
function lowerBound(haystack, needle, index2) {
for (let i2 = index2 - 1; i2 >= 0 && haystack[i2][COLUMN] === needle; index2 = i2--)
;
return index2;
}
function memoizedBinarySearch(haystack, needle, state, key) {
let { lastKey, lastNeedle, lastIndex } = state, low = 0, high = haystack.length - 1;
if (key === lastKey) {
if (needle === lastNeedle)
return found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle, lastIndex;
needle >= lastNeedle ? low = lastIndex === -1 ? 0 : lastIndex : high = lastIndex;
}
return state.lastKey = key, state.lastNeedle = needle, state.lastIndex = binarySearch(haystack, needle, low, high);
}
var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)", COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)", LEAST_UPPER_BOUND = -1, GREATEST_LOWER_BOUND = 1;
function decodedMappings(map2) {
var _a;
return (_a = map2)._decoded || (_a._decoded = decode(map2._encoded));
}
function originalPositionFor(map2, needle) {
let { line, column, bias } = needle;
if (line--, line < 0) throw new Error(LINE_GTR_ZERO);
if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
let decoded = decodedMappings(map2);
if (line >= decoded.length) return OMapping(null, null, null, null);
let segments = decoded[line], index2 = traceSegmentInternal(
segments,
map2._decodedMemo,
line,
column,
bias || GREATEST_LOWER_BOUND
);
if (index2 === -1) return OMapping(null, null, null, null);
let segment = segments[index2];
if (segment.length === 1) return OMapping(null, null, null, null);
let { names, resolvedSources } = map2;
return OMapping(
resolvedSources[segment[SOURCES_INDEX]],
segment[SOURCE_LINE] + 1,
segment[SOURCE_COLUMN],
segment.length === 5 ? names[segment[NAMES_INDEX]] : null
);
}
function OMapping(source, line, column, name) {
return { source, line, column, name };
}
function traceSegmentInternal(segments, memo2, line, column, bias) {
let index2 = memoizedBinarySearch(segments, column, memo2, line);
return found ? index2 = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index2) : bias === LEAST_UPPER_BOUND && index2++, index2 === -1 || index2 === segments.length ? -1 : index2;
}
var CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m, SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/, stackIgnorePatterns = [
"node:internal",
/\/packages\/\w+\/dist\//,
/\/@vitest\/\w+\/dist\//,
"/vitest/dist/",
"/vitest/src/",
"/node_modules/chai/",
"/node_modules/tinyspy/",
"/vite/dist/node/module-runner",
"/rolldown-vite/dist/node/module-runner",
"/deps/chunk-",
"/deps/@vitest",
"/deps/loupe",
"/deps/chai",
"/browser-playwright/dist/locators.js",
"/browser-webdriverio/dist/locators.js",
"/browser-preview/dist/locators.js",
/node:\w+/,
/__vitest_test__/,
/__vitest_browser__/,
"/@id/__x00__vitest/browser",
/\/deps\/vitest_/
], NOW_LENGTH = Date.now().toString().length, REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`);
function extractLocation(urlLike) {
if (!urlLike.includes(":"))
return [urlLike];
let parts = /(.+?)(?::(\d+))?(?::(\d+))?$/.exec(urlLike.replace(/^\(|\)$/g, ""));
if (!parts)
return [urlLike];
let url = parts[1];
if (url.startsWith("async ") && (url = url.slice(6)), url.startsWith("http:") || url.startsWith("https:")) {
let urlObj = new URL(url);
urlObj.searchParams.delete("import"), urlObj.searchParams.delete("browserv"), url = urlObj.pathname + urlObj.hash + urlObj.search;
}
if (url.startsWith("/@fs/")) {
let isWindows2 = /^\/@fs\/[a-zA-Z]:\//.test(url);
url = url.slice(isWindows2 ? 5 : 4);
}
return url.includes("vitest=") && (url = url.replace(REGEXP_VITEST, "").replace(/[?&]$/, "")), [
url,
parts[2] || void 0,
parts[3] || void 0
];
}
function parseSingleFFOrSafariStack(raw) {
let line = raw.trim();
if (SAFARI_NATIVE_CODE_REGEXP.test(line) || (line.includes(" > eval") && (line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1")), !line.includes("@")))
return null;
let atIndex = -1, locationPart = "", functionName2;
for (let i2 = 0; i2 < line.length; i2++)
if (line[i2] === "@") {
let candidateLocation = line.slice(i2 + 1);
if (candidateLocation.includes(":") && candidateLocation.length >= 3) {
atIndex = i2, locationPart = candidateLocation, functionName2 = i2 > 0 ? line.slice(0, i2) : void 0;
break;
}
}
if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3)
return null;
let [url, lineNumber, columnNumber] = extractLocation(locationPart);
return !url || !lineNumber || !columnNumber ? null : {
file: url,
method: functionName2 || "",
line: Number.parseInt(lineNumber),
column: Number.parseInt(columnNumber)
};
}
function parseSingleStack(raw) {
let line = raw.trim();
return CHROME_IE_STACK_REGEXP.test(line) ? parseSingleV8Stack(line) : parseSingleFFOrSafariStack(line);
}
function parseSingleV8Stack(raw) {
let line = raw.trim();
if (!CHROME_IE_STACK_REGEXP.test(line))
return null;
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+/, ""), location = sanitizedLine.match(/ (\(.+\)$)/);
sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine;
let [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine), method = location && sanitizedLine || "", file = url && ["eval", "<anonymous>"].includes(url) ? void 0 : url;
return !file || !lineNumber || !columnNumber ? null : (method.startsWith("async ") && (method = method.slice(6)), file.startsWith("file://") && (file = file.slice(7)), file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file), method && (method = method.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "")), {
method,
file,
line: Number.parseInt(lineNumber),
column: Number.parseInt(columnNumber)
});
}
function parseStacktrace(stack, options = {}) {
let { ignoreStackEntries = stackIgnorePatterns } = options, stacks = CHROME_IE_STACK_REGEXP.test(stack) ? parseV8Stacktrace(stack) : parseFFOrSafariStackTrace(stack), helperIndex = stacks.findLastIndex((s) => s.method.includes("__VITEST_HELPER__"));
return helperIndex >= 0 && (stacks = stacks.slice(helperIndex + 1)), stacks.map((stack2) => {
options.getUrlId && (stack2.file = options.getUrlId(stack2.file));
let map2 = options.getSourceMap?.(stack2.file);
if (!map2 || typeof map2 != "object" || !map2.version)
return shouldFilter(ignoreStackEntries, stack2.file) ? null : stack2;
let traceMap = new DecodedMap(map2, stack2.file), position = getOriginalPosition(traceMap, stack2);
if (!position)
return stack2;
let { line, column, source, name } = position, file = source || stack2.file;
return file.match(/\/\w:\//) && (file = file.slice(1)), shouldFilter(ignoreStackEntries, file) ? null : line != null && column != null ? {
line,
column,
file,
method: name || stack2.method
} : stack2;
}).filter((s) => s != null);
}
function shouldFilter(ignoreStackEntries, file) {
return ignoreStackEntries.some((p) => file.match(p));
}
function parseFFOrSafariStackTrace(stack) {
return stack.split(`
`).map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish);
}
function parseV8Stacktrace(stack) {
return stack.split(`
`).map((line) => parseSingleV8Stack(line)).filter(notNullish);
}
function parseErrorStacktrace(e, options = {}) {
if (!e || isPrimitive(e))
return [];
if ("stacks" in e && e.stacks)
return e.stacks;
let stackStr = e.stack || "", stackFrames = typeof stackStr == "string" ? parseStacktrace(stackStr, options) : [];
if (!stackFrames.length) {
let e_ = e;
e_.fileName != null && e_.lineNumber != null && e_.columnNumber != null && (stackFrames = parseStacktrace(`${e_.fileName}:${e_.lineNumber}:${e_.columnNumber}`, options)), e_.sourceURL != null && e_.line != null && e_._column != null && (stackFrames = parseStacktrace(`${e_.sourceURL}:${e_.line}:${e_.column}`, options));
}
return options.frameFilter && (stackFrames = stackFrames.filter((f) => options.frameFilter(e, f) !== !1)), e.stacks = stackFrames, stackFrames;
}
var DecodedMap = class {
_encoded;
_decoded;
_decodedMemo;
url;
version;
names = [];
resolvedSources;
constructor(map2, from) {
this.map = map2;
let { mappings, names, sources } = map2;
this.version = map2.version, this.names = names || [], this._encoded = mappings || "", this._decodedMemo = memoizedState(), this.url = from, this.resolvedSources = (sources || []).map((s) => resolve(from, "..", s || ""));
}
};
function memoizedState() {
return {
lastKey: -1,
lastNeedle: -1,
lastIndex: -1
};
}
function getOriginalPosition(map2, needle) {
let result = originalPositionFor(map2, needle);
return result.column == null ? null : result;
}
// ../../node_modules/.pnpm/@vitest+runner@4.1.10/node_modules/@vitest/runner/dist/chunk-artifact.js
var PendingError = class extends Error {
code = "VITEST_PENDING";
taskId;
constructor(message, task, note) {
super(message), this.message = message, this.note = note, this.taskId = task.id;
}
};
var FixtureDependencyError = class extends Error {
name = "FixtureDependencyError";
}, FixtureAccessError = class extends Error {
name = "FixtureAccessError";
}, FixtureParseError = class extends Error {
name = "FixtureParseError";
};
var fnMap = /* @__PURE__ */ new WeakMap(), testFixtureMap = /* @__PURE__ */ new WeakMap(), hooksMap = /* @__PURE__ */ new WeakMap();
function setFn(key, fn2) {
fnMap.set(key, fn2);
}
function setTestFixture(key, fixture) {
testFixtureMap.set(key, fixture);
}
function getTestFixtures(key) {
return testFixtureMap.get(key);
}
function setHooks(key, hooks) {
hooksMap.set(key, hooks);
}
function getHooks(key) {
return hooksMap.get(key);
}
var FIXTURE_STACK_TRACE_KEY = /* @__PURE__ */ Symbol.for("VITEST_FIXTURE_STACK_TRACE"), TestFixtures = class _TestFixtures {
_suiteContexts;
_overrides = /* @__PURE__ */ new WeakMap();
_registrations;
static _definitions = [];
static _builtinFixtures = [
"task",
"signal",
"onTestFailed",
"onTestFinished",
"skip",
"annotate"
];
static _fixtureOptionKeys = [
"auto",
"injected",
"scope"
];
static _fixtureScopes = [
"test",
"file",
"worker"
];
static _workerContextSuite = { type: "worker" };
static clearDefinitions() {
_TestFixtures._definitions.length = 0;
}
static getWorkerContexts() {
return _TestFixtures._definitions.map((f) => f.getWorkerContext());
}
static getFileContexts(file) {
return _TestFixtures._definitions.map((f) => f.getFileContext(file));
}
static isFixtureOptions(obj) {
return isObject(obj) && Object.keys(obj).some((key) => _TestFixtures._fixtureOptionKeys.includes(key));
}
constructor(registrations) {
this._registrations = registrations ?? /* @__PURE__ */ new Map(), this._suiteContexts = /* @__PURE__ */ new WeakMap(), _TestFixtures._definitions.push(this);
}
extend(runner2, userFixtures) {
let { suite: suite2 } = getCurrentSuite(), isTopLevel = !suite2 || suite2.file === suite2, registrations = this.parseUserFixtures(runner2, userFixtures, isTopLevel);
return new _TestFixtures(registrations);
}
get(suite2) {
let currentSuite = suite2;
for (; currentSuite; ) {
let overrides = this._overrides.get(currentSuite);
if (overrides)
return overrides;
if (currentSuite === currentSuite.file)
break;
currentSuite = currentSuite.suite || currentSuite.file;
}
return this._registrations;
}
override(runner2, userFixtures) {
let { suite: currentSuite, file } = getCurrentSuite(), suite2 = currentSuite || file, isTopLevel = !currentSuite || currentSuite.file === currentSuite, suiteRegistrations = new Map(this.get(suite2)), registrations = this.parseUserFixtures(runner2, userFixtures, isTopLevel, suiteRegistrations);
isTopLevel ? this._registrations = registrations : this._overrides.set(suite2, registrations);
}
getFileContext(file) {
return this._suiteContexts.has(file) || this._suiteContexts.set(file, /* @__PURE__ */ Object.create(null)), this._suiteContexts.get(file);
}
getWorkerContext() {
return this._suiteContexts.has(_TestFixtures._workerContextSuite) || this._suiteContexts.set(_TestFixtures._workerContextSuite, /* @__PURE__ */ Object.create(null)), this._suiteContexts.get(_TestFixtures._workerContextSuite);
}
parseUserFixtures(runner2, userFixtures, supportNonTest, registrations = new Map(this._registrations)) {
let errors = [];
Object.entries(userFixtures).forEach(([name, fn2]) => {
let options, value, _options;
Array.isArray(fn2) && fn2.length >= 2 && _TestFixtures.isFixtureOptions(fn2[1]) ? (_options = fn2[1], options = {
auto: _options.auto ?? !1,
scope: _options.scope ?? "test",
injected: _options.injected ?? !1
}, value = options.injected ? runner2.injectValue?.(name) ?? fn2[0] : fn2[0]) : value = fn2;
let parent = registrations.get(name);
parent && options ? (parent.scope !== options.scope && errors.push(new FixtureDependencyError(`The "${name}" fixture was already registered with a "${options.scope}" scope.`)), parent.auto !== options.auto && errors.push(new FixtureDependencyError(`The "${name}" fixture was already registered as { auto: ${options.auto} }.`))) : parent ? options = {
auto: parent.auto,
scope: parent.scope,
injected: parent.injected
} : options || (options = {
auto: !1,
injected: !1,
scope: "test"
}), options.scope && !_TestFixtures._fixtureScopes.includes(options.scope) && errors.push(new FixtureDependencyError(`The "${name}" fixture has unknown scope "${options.scope}".`)), !supportNonTest && options.scope !== "test" && errors.push(new FixtureDependencyError(`The "${name}" fixture cannot be defined with a ${options.scope} scope${!_options?.scope && parent?.scope ? " (inherited from the base fixture)" : ""} inside the describe block. Define it at the top level of the file instead.`));
let deps = isFixtureFunction(value) ? getUsedProps(value) : /* @__PURE__ */ new Set(), item = {
name,
value,
auto: options.auto ?? !1,
injected: options.injected ?? !1,
scope: options.scope ?? "test",
deps,
parent
};
isFixtureFunction(value) && Object.assign(value, { [FIXTURE_STACK_TRACE_KEY]: new Error("STACK_TRACE_ERROR") }), registrations.set(name, item), item.scope === "worker" && (runner2.pool === "vmThreads" || runner2.pool === "vmForks") && (item.scope = "file");
});
for (let fixture of registrations.values())
for (let depName of fixture.deps) {
if (_TestFixtures._builtinFixtures.includes(depName))
continue;
let dep = registrations.get(depName);
if (!dep) {
errors.push(new FixtureDependencyError(`The "${fixture.name}" fixture depends on unknown fixture "${depName}".`));
continue;
}
if (depName === fixture.name && !fixture.parent) {
errors.push(new FixtureDependencyError(`The "${fixture.name}" fixture depends on itself, but does not have a base implementation.`));
continue;
}
if (_TestFixtures._fixtureScopes.indexOf(fixture.scope) > _TestFixtures._fixtureScopes.indexOf(dep.scope)) {
errors.push(new FixtureDependencyError(`The ${fixture.scope} "${fixture.name}" fixture cannot depend on a ${dep.scope} fixture "${dep.name}".`));
continue;
}
}
if (errors.length === 1)
throw errors[0];
if (errors.length > 1)
throw new AggregateError(errors, "Cannot resolve user fixtures. See errors for more information.");
return registrations;
}
}, cleanupFnArrayMap = /* @__PURE__ */ new WeakMap();
var contextHasFixturesCache = /* @__PURE__ */ new WeakMap();
function withFixtures(fn2, options) {
let collector = getCurrentSuite(), suite2 = options?.suite || collector.suite || collector.file;
return async (hookContext) => {
let context = hookContext || options?.context;
if (!context)
return options?.suiteHook && validateSuiteHook(fn2, options.suiteHook, options.stackTraceError), fn2({});
let fixtures = options?.fixtures || getTestFixtures(context);
if (!fixtures)
return fn2(context);
let registrations = fixtures.get(suite2);
if (!registrations.size)
return fn2(context);
let usedFixtures = [], usedProps = getUsedProps(fn2);
for (let fixture of registrations.values())
(isAutoFixture(fixture, options) || usedProps.has(fixture.name)) && usedFixtures.push(fixture);
if (!usedFixtures.length)
return fn2(context);
cleanupFnArrayMap.has(context) || cleanupFnArrayMap.set(context, []);
let cleanupFnArray = cleanupFnArrayMap.get(context), pendingFixtures = resolveDeps(usedFixtures, registrations);
if (!pendingFixtures.length)
return fn2(context);
if (options?.suiteHook) {
let testScopedFixtures = pendingFixtures.filter((f) => f.scope === "test");
if (testScopedFixtures.length > 0) {
let fixtureNames = testScopedFixtures.map((f) => `"${f.name}"`).join(", "), alternativeHook = {
aroundAll: "aroundEach",
beforeAll: "beforeEach",
afterAll: "afterEach"
}, error = new FixtureDependencyError(`Test-scoped fixtures cannot be used inside ${options.suiteHook} hook. The following fixtures are test-scoped: ${fixtureNames}. Use { scope: 'file' } or { scope: 'worker' } fixtures instead, or move the logic to ${alternativeHook[options.suiteHook]} hook.`);
throw options.stackTraceError?.stack && (error.stack = error.message + options.stackTraceError.stack.replace(options.stackTraceError.message, "")), error;
}
}
contextHasFixturesCache.has(context) || contextHasFixturesCache.set(context, /* @__PURE__ */ new WeakSet());
let cachedFixtures = contextHasFixturesCache.get(context);
for (let fixture of pendingFixtures)
if (fixture.scope === "test") {
if (cachedFixtures.has(fixture))
continue;
cachedFixtures.add(fixture);
let resolvedValue = await resolveTestFixtureValue(fixture, context, cleanupFnArray);
context[fixture.name] = resolvedValue, cleanupFnArray.push(() => {
cachedFixtures.delete(fixture);
});
} else {
let resolvedValue = await resolveScopeFixtureValue(fixtures, suite2, fixture);
context[fixture.name] = resolvedValue;
}
return fn2(context);
};
}
function isAutoFixture(fixture, options) {
return !(!fixture.auto || options?.suiteHook && fixture.scope === "test");
}
function isFixtureFunction(value) {
return typeof value == "function";
}
function resolveTestFixtureValue(fixture, context, cleanupFnArray) {
return isFixtureFunction(fixture.value) ? resolveFixtureFunction(fixture.value, fixture.name, context, cleanupFnArray) : fixture.value;
}
var scopedFixturePromiseCache = /* @__PURE__ */ new WeakMap();
async function resolveScopeFixtureValue(fixtures, suite2, fixture) {
let workerContext = fixtures.getWorkerContext(), fileContext = fixtures.getFileContext(suite2.file), fixtureContext = fixture.scope === "worker" ? workerContext : fileContext;
if (!isFixtureFunction(fixture.value))
return fixtureContext[fixture.name] = fixture.value, fixture.value;
if (fixture.name in fixtureContext)
return fixtureContext[fixture.name];
if (scopedFixturePromiseCache.has(fixture))
return scopedFixturePromiseCache.get(fixture);
cleanupFnArrayMap.has(fixtureContext) || cleanupFnArrayMap.set(fixtureContext, []);
let cleanupFnFileArray = cleanupFnArrayMap.get(fixtureContext), promise = resolveFixtureFunction(fixture.value, fixture.name, fixture.scope === "file" ? {
...workerContext,
...fileContext
} : fixtureContext, cleanupFnFileArray).then((value) => (fixtureContext[fixture.name] = value, scopedFixturePromiseCache.delete(fixture), value));
return scopedFixturePromiseCache.set(fixture, promise), promise;
}
async function resolveFixtureFunction(fixtureFn, fixtureName, context, cleanupFnArray) {
let useFnArgPromise = createDefer(), stackTraceError = FIXTURE_STACK_TRACE_KEY in fixtureFn && fixtureFn[FIXTURE_STACK_TRACE_KEY] instanceof Error ? fixtureFn[FIXTURE_STACK_TRACE_KEY] : void 0, isUseFnArgResolved = !1, fixtureReturn = fixtureFn(context, async (useFnArg) => {
isUseFnArgResolved = !0, useFnArgPromise.resolve(useFnArg);
let useReturnPromise = createDefer();
cleanupFnArray.push(async () => {
useReturnPromise.resolve(), await fixtureReturn;
}), await useReturnPromise;
}).then(() => {
if (!isUseFnArgResolved) {
let error = new Error(`Fixture "${fixtureName}" returned without calling "use". Make sure to call "use" in every code path of the fixture function.`);
stackTraceError?.stack && (error.stack = error.message + stackTraceError.stack.replace(stackTraceError.message, "")), useFnArgPromise.reject(error);
}
}).catch((e) => {
if (!isUseFnArgResolved) {
useFnArgPromise.reject(e);
return;
}
throw e;
});
return useFnArgPromise;
}
function resolveDeps(usedFixtures, registrations, depSet = /* @__PURE__ */ new Set(), pendingFixtures = []) {
return usedFixtures.forEach((fixture) => {
if (!pendingFixtures.includes(fixture)) {
if (!isFixtureFunction(fixture.value) || !fixture.deps) {
pendingFixtures.push(fixture);
return;
}
if (depSet.has(fixture))
if (fixture.parent)
fixture = fixture.parent;
else
throw new Error(`Circular fixture dependency detected: ${fixture.name} <- ${[...depSet].reverse().map((d2) => d2.name).join(" <- ")}`);
depSet.add(fixture), resolveDeps([...fixture.deps].map((n) => n === fixture.name ? fixture.parent : registrations.get(n)).filter((n) => !!n), registrations, depSet, pendingFixtures), pendingFixtures.push(fixture), depSet.clear();
}
}), pendingFixtures;
}
function validateSuiteHook(fn2, hook, suiteError) {
let usedProps = getUsedProps(fn2, {
sourceError: suiteError,
suiteHook: hook
});
if (usedProps.size) {
let error = new FixtureAccessError(`The ${hook} hook uses fixtures "${[...usedProps].join('", "')}", but has no access to context. Did you forget to call it as "test.${hook}()" instead of "${hook}()"?
If you used internal "suite" task as the first argument previously, access it in the second argument instead. See https://vitest.dev/guide/test-context#suite-level-hooks`);
throw suiteError && (error.stack = suiteError.stack?.replace(suiteError.message, error.message)), error;
}
}
var kPropsSymbol = /* @__PURE__ */ Symbol("$vitest:fixture-props"), kPropNamesSymbol = /* @__PURE__ */ Symbol("$vitest:fixture-prop-names");
function configureProps(fn2, options) {
Object.defineProperty(fn2, kPropsSymbol, {
value: options,
enumerable: !1
});
}
function memoProps(fn2, props) {
return fn2[kPropNamesSymbol] = props, props;
}
function getUsedProps(fn2, { sourceError, suiteHook } = {}) {
if (kPropNamesSymbol in fn2)
return fn2[kPropNamesSymbol];
let { index: fixturesIndex = 0, original: implementation = fn2 } = kPropsSymbol in fn2 ? fn2[kPropsSymbol] : {}, fnString = filterOutComments(implementation.toString());
/__async\((?:this|null), (?:null|arguments|\[[_0-9, ]*\]), function\*/.test(fnString) && (fnString = fnString.split(/__async\((?:this|null),/)[1]);
let match = fnString.match(/[^(]*\(([^)]*)/);
if (!match)
return memoProps(fn2, /* @__PURE__ */ new Set());
let args = splitByComma(match[1]);
if (!args.length)
return memoProps(fn2, /* @__PURE__ */ new Set());
let fixturesArgument = args[fixturesIndex];
if (!fixturesArgument)
return memoProps(fn2, /* @__PURE__ */ new Set());
if (!(fixturesArgument[0] === "{" && fixturesArgument.endsWith("}"))) {
let ordinalArgument = ordinal(fixturesIndex + 1), error = new FixtureParseError(`The ${ordinalArgument} argument inside a fixture must use object destructuring pattern, e.g. ({ task } => {}). Instead, received "${fixturesArgument}".${suiteHook ? ` If you used internal "suite" task as the ${ordinalArgument} argument previously, access it in the ${ordinal(fixturesIndex + 2)} argument instead.` : ""}`);
throw sourceError && (error.stack = sourceError.stack?.replace(sourceError.message, error.message)), error;
}
let _first = fixturesArgument.slice(1, -1).replace(/\s/g, ""), props = splitByComma(_first).map((prop) => prop.replace(/:.*|=.*/g, "")), last = props.at(-1);
if (last && last.startsWith("...")) {
let error = new FixtureParseError(`Rest parameters are not supported in fixtures, received "${last}".`);
throw sourceError && (error.stack = sourceError.stack?.replace(sourceError.message, error.message)), error;
}
return memoProps(fn2, new Set(props));
}
function splitByComma(s) {
let result = [], stack = [], start = 0;
for (let i2 = 0; i2 < s.length; i2++)
if (s[i2] === "{" || s[i2] === "[")
stack.push(s[i2] === "{" ? "}" : "]");
else if (s[i2] === stack.at(-1))
stack.pop();
else if (!stack.length && s[i2] === ",") {
let token = s.substring(start, i2).trim();
token && result.push(token), start = i2 + 1;
}
let lastToken = s.substring(start).trim();
return lastToken && result.push(lastToken), result;
}
var _test;
function getCurrentTest() {
return _test;
}
var kChainableContext = /* @__PURE__ */ Symbol("kChainableContext");
function getChainableContext(chainable) {
return chainable?.[kChainableContext];
}
function createChainable(keys2, fn2, context) {
function create(context2) {
let chain2 = function(...args) {
return fn2.apply(context2, args);
};
Object.assign(chain2, fn2), Object.defineProperty(chain2, kChainableContext, {
value: {
withContext: () => chain2.bind(context2),
getFixtures: () => context2.fixtures,
setContext: (key, value) => {
context2[key] = value;
},
mergeContext: (ctx) => {
Object.assign(context2, ctx);
}
},
enumerable: !1
});
for (let key of keys2)
Object.defineProperty(chain2, key, { get() {
return create({
...context2,
[key]: !0
});
} });
return chain2;
}
let chain = create(context ?? {});
return Object.defineProperty(chain, "fn", {
value: fn2,
enumerable: !1
}), chain;
}
function getDefaultHookTimeout() {
return getRunner().config.hookTimeout;
}
var CLEANUP_TIMEOUT_KEY = /* @__PURE__ */ Symbol.for("VITEST_CLEANUP_TIMEOUT"), CLEANUP_STACK_TRACE_KEY = /* @__PURE__ */ Symbol.for("VITEST_CLEANUP_STACK_TRACE"), AROUND_TIMEOUT_KEY = /* @__PURE__ */ Symbol.for("VITEST_AROUND_TIMEOUT"), AROUND_STACK_TRACE_KEY = /* @__PURE__ */ Symbol.for("VITEST_AROUND_STACK_TRACE");
function beforeAll(fn2, timeout = getDefaultHookTimeout()) {
assertTypes(fn2, '"beforeAll" callback', ["function"]);
let stackTraceError = new Error("STACK_TRACE_ERROR"), context = getChainableContext(this);
return getCurrentSuite().on("beforeAll", Object.assign(withTimeout(withSuiteFixtures("beforeAll", fn2, context, stackTraceError), timeout, !0, stackTraceError), {
[CLEANUP_TIMEOUT_KEY]: timeout,
[CLEANUP_STACK_TRACE_KEY]: stackTraceError
}));
}
function afterAll(fn2, timeout) {
assertTypes(fn2, '"afterAll" callback', ["function"]);
let context = getChainableContext(this), stackTraceError = new Error("STACK_TRACE_ERROR");
return getCurrentSuite().on("afterAll", withTimeout(withSuiteFixtures("afterAll", fn2, context, stackTraceError), timeout ?? getDefaultHookTimeout(), !0, stackTraceError));
}
function beforeEach(fn2, timeout = getDefaultHookTimeout()) {
assertTypes(fn2, '"beforeEach" callback', ["function"]);
let stackTraceError = new Error("STACK_TRACE_ERROR"), wrapper = (context, suite2) => withFixtures(fn2, { suite: suite2 })(context);
return getCurrentSuite().on("beforeEach", Object.assign(withTimeout(wrapper, timeout ?? getDefaultHookTimeout(), !0, stackTraceError, abortIfTimeout), {
[CLEANUP_TIMEOUT_KEY]: timeout,
[CLEANUP_STACK_TRACE_KEY]: stackTraceError
}));
}
function afterEach(fn2, timeout) {
assertTypes(fn2, '"afterEach" callback', ["function"]);
let wrapper = (context, suite2) => withFixtures(fn2, { suite: suite2 })(context);
return getCurrentSuite().on("afterEach", withTimeout(wrapper, timeout ?? getDefaultHookTimeout(), !0, new Error("STACK_TRACE_ERROR"), abortIfTimeout));
}
var onTestFailed = createTestHook("onTestFailed", (test5, handler, timeout) => {
test5.onFailed ||= [], test5.onFailed.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), !0, new Error("STACK_TRACE_ERROR"), abortIfTimeout));
}), onTestFinished = createTestHook("onTestFinished", (test5, handler, timeout) => {
test5.onFinished ||= [], test5.onFinished.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), !0, new Error("STACK_TRACE_ERROR"), abortIfTimeout));
});
function aroundAll(fn2, timeout) {
assertTypes(fn2, '"aroundAll" callback', ["function"]);
let stackTraceError = new Error("STACK_TRACE_ERROR"), resolvedTimeout = timeout ?? getDefaultHookTimeout(), context = getChainableContext(this);
return getCurrentSuite().on("aroundAll", Object.assign(withSuiteFixtures("aroundAll", fn2, context, stackTraceError, 1), {
[AROUND_TIMEOUT_KEY]: resolvedTimeout,
[AROUND_STACK_TRACE_KEY]: stackTraceError
}));
}
function aroundEach(fn2, timeout) {
assertTypes(fn2, '"aroundEach" callback', ["function"]);
let stackTraceError = new Error("STACK_TRACE_ERROR"), resolvedTimeout = timeout ?? getDefaultHookTimeout(), wrapper = (runTest, context, suite2) => {
let innerFn = (ctx) => fn2(runTest, ctx, suite2);
return configureProps(innerFn, {
index: 1,
original: fn2
}), withFixtures(innerFn, { suite: suite2 })(context);
};
return getCurrentSuite().on("aroundEach", Object.assign(wrapper, {
[AROUND_TIMEOUT_KEY]: resolvedTimeout,
[AROUND_STACK_TRACE_KEY]: stackTraceError
}));
}
function withSuiteFixtures(suiteHook, fn2, context, stackTraceError, contextIndex = 0) {
return (...args) => {
let suite2 = args.at(-1), prefix = args.slice(0, -1), wrapper = (ctx) => fn2(...prefix, ctx, suite2);
configureProps(wrapper, {
index: contextIndex,
original: fn2
});
let fixtures = context?.getFixtures(), fileContext = fixtures?.getFileContext(suite2.file);
return withFixtures(wrapper, {
suiteHook,
fixtures,
context: fileContext,
stackTraceError
})();
};
}
function createTestHook(name, handler) {
return (fn2, timeout) => {
assertTypes(fn2, `"${name}" callback`, ["function"]);
let current = getCurrentTest();
if (!current)
throw new Error(`Hook ${name}() can only be called inside a test`);
return handler(current, fn2, timeout);
};
}
function findTestFileStackTrace(testFilePath, error) {
let lines = error.split(`
`).slice(1);
for (let line of lines) {
let stack = parseSingleStack(line);
if (stack && stack.file === testFilePath)
return stack;
}
}
function validateTags(config2, tags) {
if (!config2.strictTags)
return;
let availableTags = new Set(config2.tags.map((tag) => tag.name));
for (let tag of tags)
if (!availableTags.has(tag))
throw createNoTagsError(config2.tags, tag);
}
function createNoTagsError(availableTags, tag, prefix = "tag") {
throw availableTags.length ? new Error(`The ${prefix} "${tag}" is not defined in the configuration. Available tags are:
${availableTags.map((t) => `- ${t.name}${t.description ? `: ${t.description}` : ""}`).join(`
`)}`) : new Error(`The Vitest config does't define any "tags", cannot apply "${tag}" ${prefix} for this test. See: https://vitest.dev/guide/test-tags`);
}
function getNames(task) {
let names = [task.name], current = task;
for (; current?.suite; )
current = current.suite, current?.name && names.unshift(current.name);
return current !== task.file && names.unshift(task.file.name), names;
}
function createTaskName(names, separator = " > ") {
return names.filter((name) => name !== void 0).join(separator);
}
var suite = createSuite(), test2 = createTest(function(name, optionsOrFn, optionsOrTest) {
if (getCurrentTest())
throw new Error('Calling the test function inside another test function is not allowed. Please put it inside "describe" or "suite" so it can be properly collected.');
getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest);
}), describe = suite;
var runner, defaultSuite, currentTestFilepath;
function assert(condition, message) {
if (!condition)
throw new Error(`Vitest failed to find ${message}. One of the following is possible:
- "vitest" is imported directly without running "vitest" command
- "vitest" is imported inside "globalSetup" (to fix this, use "setupFiles" instead, because "globalSetup" runs in a different context)
- "vitest" is imported inside Vite / Vitest config file
- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues
`);
}
function getRunner() {
return assert(runner, "the runner"), runner;
}
function getCurrentSuite() {
let currentSuite = collectorContext.currentSuite || defaultSuite;
return assert(currentSuite, "the current suite"), currentSuite;
}
function createSuiteHooks() {
return {
beforeAll: [],
afterAll: [],
beforeEach: [],
afterEach: [],
aroundEach: [],
aroundAll: []
};
}
var POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
function parseArguments(optionsOrFn, timeoutOrTest) {
if (timeoutOrTest != null && typeof timeoutOrTest == "object")
throw new TypeError('Signature "test(name, fn, { ... })" was deprecated in Vitest 3 and removed in Vitest 4. Please, provide options as a second argument instead.');
let options = {}, fn2;
if (typeof timeoutOrTest == "number" ? options = { timeout: timeoutOrTest } : typeof optionsOrFn == "object" && (options = optionsOrFn), typeof optionsOrFn == "function") {
if (typeof timeoutOrTest == "function")
throw new TypeError("Cannot use two functions as arguments. Please use the second argument for options.");
fn2 = optionsOrFn;
} else typeof timeoutOrTest == "function" && (fn2 = timeoutOrTest);
return {
options,
handler: fn2
};
}
function createSuiteCollector(name, factory = () => {
}, mode, each, suiteOptions) {
let tasks = [], suite2;
initSuite(!0);
let task = function(name2 = "", options = {}) {
let currentSuite = collectorContext.currentSuite?.suite, parentTags = (currentSuite ?? collectorContext.currentSuite?.file)?.tags || [], testTags = unique([...parentTags, ...toArray(options.tags)]), tagsOptions = testTags.map((tag) => {
let tagDefinition = runner.config.tags?.find((t) => t.name === tag);
if (!tagDefinition && runner.config.strictTags)
throw createNoTagsError(runner.config.tags, tag);
return tagDefinition;
}).filter((r) => r != null).sort((tag1, tag2) => (tag2.priority ?? POSITIVE_INFINITY) - (tag1.priority ?? POSITIVE_INFINITY)).reduce((acc, tag) => {
let { name: name3, description, priority, meta, ...options2 } = tag;
return Object.assign(acc, options2), meta && (acc.meta = Object.assign(acc.meta ?? /* @__PURE__ */ Object.create(null), meta)), acc;
}, {}), testOwnMeta = options.meta;
options = {
...tagsOptions,
...options
};
let timeout = options.timeout ?? runner.config.testTimeout, parentMeta = currentSuite?.meta, tagMeta = tagsOptions.meta, testMeta = /* @__PURE__ */ Object.create(null);
tagMeta && Object.assign(testMeta, tagMeta), parentMeta && Object.assign(testMeta, parentMeta), testOwnMeta && Object.assign(testMeta, testOwnMeta);
let task2 = {
id: "",
name: name2,
fullName: createTaskName([currentSuite?.fullName ?? collectorContext.currentSuite?.file?.fullName, name2]),
fullTestName: createTaskName([currentSuite?.fullTestName, name2]),
suite: currentSuite,
each: options.each,
fails: options.fails,
context: void 0,
type: "test",
file: currentSuite?.file ?? collectorContext.currentSuite?.file,
timeout,
retry: options.retry ?? runner.config.retry,
repeats: options.repeats,
mode: options.only ? "only" : options.skip ? "skip" : options.todo ? "todo" : "run",
meta: testMeta,
annotations: [],
artifacts: [],
tags: testTags
}, handler = options.handler;
task2.mode === "run" && !handler && (task2.mode = "todo"), (options.concurrent ?? (!options.sequential && runner.config.sequence.concurrent)) && (task2.concurrent = !0), task2.shuffle = suiteOptions?.shuffle;
let context = createTestContext(task2, runner);
Object.defineProperty(task2, "context", {
value: context,
enumerable: !1
}), setTestFixture(context, options.fixtures ?? new TestFixtures());
let limit = Error.stackTraceLimit;
Error.stackTraceLimit = 10;
let stackTraceError = new Error("STACK_TRACE_ERROR");
if (Error.stackTraceLimit = limit, handler && setFn(task2, withTimeout(withCancel(withAwaitAsyncAssertions(withFixtures(handler, { context }), task2), task2.context.signal), timeout, !1, stackTraceError, (_, error) => abortIfTimeout([context], error))), runner.config.includeTaskLocation) {
let error = stackTraceError.stack, stack = findTestFileStackTrace(currentTestFilepath, error);
stack && (task2.location = {
line: stack.line,
column: stack.column
});
}
return tasks.push(task2), task2;
}, test5 = createTest(function(name2, optionsOrFn, timeoutOrTest) {
let { options, handler } = parseArguments(optionsOrFn, timeoutOrTest);
typeof suiteOptions == "object" && (options = Object.assign({}, suiteOptions, options));
let concurrent = this.concurrent ?? (!this.sequential && options?.concurrent);
options.concurrent != null && concurrent != null && (options.concurrent = concurrent);
let sequential = this.sequential ?? (!this.concurrent && options?.sequential);
options.sequential != null && sequential != null && (options.sequential = sequential);
let test6 = task(formatName(name2), {
...this,
...options,
handler
});
test6.type = "test";
}), collector = {
type: "collector",
name,
mode,
suite: suite2,
options: suiteOptions,
test: test5,
file: suite2.file,
tasks,
collect,
task,
clear,
on: addHook
};
function addHook(name2, ...fn2) {
getHooks(suite2)[name2].push(...fn2);
}
function initSuite(includeLocation) {
typeof suiteOptions == "number" && (suiteOptions = { timeout: suiteOptions });
let currentSuite = collectorContext.currentSuite?.suite, parentTask = currentSuite ?? collectorContext.currentSuite?.file, suiteTags = toArray(suiteOptions?.tags);
if (validateTags(runner.config, suiteTags), suite2 = {
id: "",
type: "suite",
name,
fullName: createTaskName([currentSuite?.fullName ?? collectorContext.currentSuite?.file?.fullName, name]),
fullTestName: createTaskName([currentSuite?.fullTestName, name]),
suite: currentSuite,
mode,
each,
file: currentSuite?.file ?? collectorContext.currentSuite?.file,
shuffle: suiteOptions?.shuffle,
tasks: [],
meta: suiteOptions?.meta ?? /* @__PURE__ */ Object.create(null),
concurrent: suiteOptions?.concurrent,
tags: unique([...parentTask?.tags || [], ...suiteTags])
}, runner && includeLocation && runner.config.includeTaskLocation) {
let limit = Error.stackTraceLimit;
Error.stackTraceLimit = 15;
let error = new Error("stacktrace").stack;
Error.stackTraceLimit = limit;
let stack = findTestFileStackTrace(currentTestFilepath, error);
stack && (suite2.location = {
line: stack.line,
column: stack.column
});
}
setHooks(suite2, createSuiteHooks());
}
function clear() {
tasks.length = 0, initSuite(!1);
}
async function collect(file) {
if (!file)
throw new TypeError("File is required to collect tasks.");
factory && await runWithSuite(collector, () => factory(test5));
let allChildren = [];
for (let i2 of tasks)
allChildren.push(i2.type === "collector" ? await i2.collect(file) : i2);
return suite2.tasks = allChildren, suite2;
}
return collectTask(collector), collector;
}
function withAwaitAsyncAssertions(fn2, task) {
return (async (...args) => {
let fnResult = await fn2(...args);
if (task.promises) {
let errors = (await Promise.allSettled(task.promises)).map((r) => r.status === "rejected" ? r.reason : void 0).filter(Boolean);
if (errors.length)
throw errors;
}
return fnResult;
});
}
function createSuite() {
function suiteFn(name, factoryOrOptions, optionsOrFactory) {
if (getCurrentTest())
throw new Error("Calling the suite function inside test function is not allowed. It can be only called at the top level or inside another suite function.");
let currentSuite = collectorContext.currentSuite || defaultSuite, { options, handler: factory } = parseArguments(factoryOrOptions, optionsOrFactory), isConcurrentSpecified = options.concurrent || this.concurrent || options.sequential === !1, isSequentialSpecified = options.sequential || this.sequential || options.concurrent === !1, { meta: parentMeta, ...parentOptions } = currentSuite?.options || {};
options = {
...parentOptions,
...options
};
let shuffle2 = this.shuffle ?? options.shuffle ?? currentSuite?.options?.shuffle ?? runner?.config.sequence.shuffle;
shuffle2 != null && (options.shuffle = shuffle2);
let mode = this.only ?? options.only ? "only" : this.skip ?? options.skip ? "skip" : this.todo ?? options.todo ? "todo" : "run";
mode === "run" && !factory && (mode = "todo");
let isConcurrent = isConcurrentSpecified || options.concurrent && !isSequentialSpecified, isSequential = isSequentialSpecified || options.sequential && !isConcurrentSpecified;
return isConcurrent != null && (options.concurrent = isConcurrent && !isSequential), isSequential != null && (options.sequential = isSequential && !isConcurrent), parentMeta && (options.meta = Object.assign(/* @__PURE__ */ Object.create(null), parentMeta, options.meta)), createSuiteCollector(formatName(name), factory, mode, this.each, options);
}
return suiteFn.each = function(cases, ...args) {
let context = getChainableContext(this), suite2 = context.withContext();
return context.setContext("each", !0), Array.isArray(cases) && args.length && (cases = formatTemplateString(cases, args)), (name, optionsOrFn, fnOrOptions) => {
let _name = formatName(name), arrayOnlyCases = cases.every(Array.isArray), { options, handler } = parseArguments(optionsOrFn, fnOrOptions), fnFirst = typeof optionsOrFn == "function";
cases.forEach((i2, idx) => {
let items = Array.isArray(i2) ? i2 : [i2];
fnFirst ? arrayOnlyCases ? suite2(formatTitle(_name, items, idx), handler ? () => handler(...items) : void 0, options.timeout) : suite2(formatTitle(_name, items, idx), handler ? () => handler(i2) : void 0, options.timeout) : arrayOnlyCases ? suite2(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : void 0) : suite2(formatTitle(_name, items, idx), options, handler ? () => handler(i2) : void 0);
}), context.setContext("each", void 0);
};
}, suiteFn.for = function(cases, ...args) {
return Array.isArray(cases) && args.length && (cases = formatTemplateString(cases, args)), (name, optionsOrFn, fnOrOptions) => {
let name_ = formatName(name), { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
cases.forEach((item, idx) => {
suite(formatTitle(name_, toArray(item), idx), options, handler ? () => handler(item) : void 0);
});
};
}, suiteFn.skipIf = (condition) => condition ? suite.skip : suite, suiteFn.runIf = (condition) => condition ? suite : suite.skip, createChainable([
"concurrent",
"sequential",
"shuffle",
"skip",
"only",
"todo"
], suiteFn);
}
function createTaskCollector(fn2) {
let taskFn = fn2;
taskFn.each = function(cases, ...args) {
let context = getChainableContext(this), test5 = context.withContext();
return context.setContext("each", !0), Array.isArray(cases) && args.length && (cases = formatTemplateString(cases, args)), (name, optionsOrFn, fnOrOptions) => {
let _name = formatName(name), arrayOnlyCases = cases.every(Array.isArray), { options, handler } = parseArguments(optionsOrFn, fnOrOptions), fnFirst = typeof optionsOrFn == "function";
cases.forEach((i2, idx) => {
let items = Array.isArray(i2) ? i2 : [i2];
fnFirst ? arrayOnlyCases ? test5(formatTitle(_name, items, idx), handler ? () => handler(...items) : void 0, options.timeout) : test5(formatTitle(_name, items, idx), handler ? () => handler(i2) : void 0, options.timeout) : arrayOnlyCases ? test5(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : void 0) : test5(formatTitle(_name, items, idx), options, handler ? () => handler(i2) : void 0);
}), context.setContext("each", void 0);
};
}, taskFn.for = function(cases, ...args) {
let test5 = getChainableContext(this).withContext();
return Array.isArray(cases) && args.length && (cases = formatTemplateString(cases, args)), (name, optionsOrFn, fnOrOptions) => {
let _name = formatName(name), { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
cases.forEach((item, idx) => {
let handlerWrapper = handler ? (ctx) => handler(item, ctx) : void 0;
handlerWrapper && configureProps(handlerWrapper, {
index: 1,
original: handler
}), test5(formatTitle(_name, toArray(item), idx), options, handlerWrapper);
});
};
}, taskFn.skipIf = function(condition) {
return condition ? this.skip : this;
}, taskFn.runIf = function(condition) {
return condition ? this : this.skip;
};
function parseBuilderFixtures(fixturesOrName, optionsOrFn, maybeFn) {
if (typeof fixturesOrName != "string")
return fixturesOrName;
let fixtureName = fixturesOrName, fixtureOptions, fixtureValue;
if (maybeFn !== void 0 ? (fixtureOptions = optionsOrFn, fixtureValue = maybeFn) : optionsOrFn !== null && typeof optionsOrFn == "object" && !Array.isArray(optionsOrFn) && TestFixtures.isFixtureOptions(optionsOrFn) ? (fixtureOptions = optionsOrFn, fixtureValue = {}) : (fixtureOptions = void 0, fixtureValue = optionsOrFn), typeof fixtureValue == "function") {
let builderFn = fixtureValue, fixture = async (ctx, use2) => {
let cleanup, value = await builderFn(ctx, { onCleanup: (fn3) => {
if (cleanup !== void 0)
throw new Error("onCleanup can only be called once per fixture. Define separate fixtures if you need multiple cleanup functions.");
cleanup = fn3;
} });
await use2(value), cleanup && await cleanup();
};
return configureProps(fixture, { original: builderFn }), fixtureOptions ? { [fixtureName]: [fixture, fixtureOptions] } : { [fixtureName]: fixture };
}
return fixtureOptions ? { [fixtureName]: [fixtureValue, fixtureOptions] } : { [fixtureName]: fixtureValue };
}
return taskFn.override = function(fixturesOrName, optionsOrFn, maybeFn) {
let userFixtures = parseBuilderFixtures(fixturesOrName, optionsOrFn, maybeFn);
return getChainableContext(this).getFixtures().override(runner, userFixtures), this;
}, taskFn.scoped = function(fixtures) {
return console.warn("test.scoped() is deprecated and will be removed in future versions. Please use test.override() instead."), this.override(fixtures);
}, taskFn.extend = function(fixturesOrName, optionsOrFn, maybeFn) {
let userFixtures = parseBuilderFixtures(fixturesOrName, optionsOrFn, maybeFn), fixtures = getChainableContext(this).getFixtures().extend(runner, userFixtures), _test3 = createTest(function(name, optionsOrFn2, optionsOrTest) {
fn2.call(this, formatName(name), optionsOrFn2, optionsOrTest);
});
return getChainableContext(_test3).mergeContext({ fixtures }), _test3;
}, taskFn.describe = suite, taskFn.suite = suite, taskFn.beforeEach = beforeEach, taskFn.afterEach = afterEach, taskFn.beforeAll = beforeAll, taskFn.afterAll = afterAll, taskFn.aroundEach = aroundEach, taskFn.aroundAll = aroundAll, createChainable([
"concurrent",
"sequential",
"skip",
"only",
"todo",
"fails"
], taskFn, { fixtures: new TestFixtures() });
}
function createTest(fn2) {
return createTaskCollector(fn2);
}
function formatName(name) {
return typeof name == "string" ? name : typeof name == "function" ? name.name || "<anonymous>" : String(name);
}
function formatTitle(template, items, idx) {
(template.includes("%#") || template.includes("%$")) && (template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/%\$/g, `${idx + 1}`).replace(/__vitest_escaped_%__/g, "%%"));
let count = template.split("%").length - 1;
template.includes("%f") && (template.match(/%f/g) || []).forEach((_, i3) => {
if (isNegativeNaN(items[i3]) || Object.is(items[i3], -0)) {
let occurrence = 0;
template = template.replace(/%f/g, (match) => (occurrence++, occurrence === i3 + 1 ? "-%f" : match));
}
});
let isObjectItem = isObject(items[0]);
function formatAttribute(s) {
return s.replace(/\$([$\w.]+)/g, (_, key) => {
let isArrayKey = /^\d+$/.test(key);
if (!isObjectItem && !isArrayKey)
return `$${key}`;
let arrayElement = isArrayKey ? objectAttr(items, key) : void 0, value = isObjectItem ? objectAttr(items[0], key, arrayElement) : arrayElement;
return objDisplay(value, { truncate: runner?.config?.chaiConfig?.truncateThreshold });
});
}
let output = "", i2 = 0;
return handleRegexMatch(
template,
formatRegExp,
// format "%"
(match) => {
i2 < count ? output += format2(match[0], items[i2++]) : output += match[0];
},
// format "$"
(nonMatch) => {
output += formatAttribute(nonMatch);
}
), output;
}
function handleRegexMatch(input, regex, onMatch, onNonMatch) {
let lastIndex = 0;
for (let m of input.matchAll(regex))
lastIndex < m.index && onNonMatch(input.slice(lastIndex, m.index)), onMatch(m), lastIndex = m.index + m[0].length;
lastIndex < input.length && onNonMatch(input.slice(lastIndex));
}
function formatTemplateString(cases, args) {
let header = cases.join("").trim().replace(/ /g, "").split(`
`).map((i2) => i2.split("|"))[0], res = [];
for (let i2 = 0; i2 < Math.floor(args.length / header.length); i2++) {
let oneCase = {};
for (let j = 0; j < header.length; j++)
oneCase[header[j]] = args[i2 * header.length + j];
res.push(oneCase);
}
return res;
}
var now$2 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now, collectorContext = {
tasks: [],
currentSuite: null
};
function collectTask(task) {
collectorContext.currentSuite?.tasks.push(task);
}
async function runWithSuite(suite2, fn2) {
let prev = collectorContext.currentSuite;
collectorContext.currentSuite = suite2, await fn2(), collectorContext.currentSuite = prev;
}
function withTimeout(fn2, timeout, isHook = !1, stackTraceError, onTimeout) {
if (timeout <= 0 || timeout === Number.POSITIVE_INFINITY)
return fn2;
let { setTimeout: setTimeout3, clearTimeout: clearTimeout3 } = getSafeTimers();
return (function(...args) {
let startTime = now$2(), runner2 = getRunner();
return runner2._currentTaskStartTime = startTime, runner2._currentTaskTimeout = timeout, new Promise((resolve_, reject_) => {
let timer = setTimeout3(() => {
clearTimeout3(timer), rejectTimeoutError();
}, timeout);
timer.unref?.();
function rejectTimeoutError() {
let error = makeTimeoutError(isHook, timeout, stackTraceError);
onTimeout?.(args, error), reject_(error);
}
function resolve2(result) {
if (runner2._currentTaskStartTime = void 0, runner2._currentTaskTimeout = void 0, clearTimeout3(timer), now$2() - startTime >= timeout) {
rejectTimeoutError();
return;
}
resolve_(result);
}
function reject(error) {
runner2._currentTaskStartTime = void 0, runner2._currentTaskTimeout = void 0, clearTimeout3(timer), reject_(error);
}
try {
let result = fn2(...args);
typeof result == "object" && result != null && typeof result.then == "function" ? result.then(resolve2, reject) : resolve2(result);
} catch (error) {
reject(error);
}
});
});
}
function withCancel(fn2, signal) {
return (function(...args) {
return new Promise((resolve2, reject) => {
signal.addEventListener("abort", () => reject(signal.reason));
try {
let result = fn2(...args);
typeof result == "object" && result != null && typeof result.then == "function" ? result.then(resolve2, reject) : resolve2(result);
} catch (error) {
reject(error);
}
});
});
}
var abortControllers = /* @__PURE__ */ new WeakMap();
function abortIfTimeout([context], error) {
context && abortContextSignal(context, error);
}
function abortContextSignal(context, error) {
abortControllers.get(context)?.abort(error);
}
function createTestContext(test5, runner2) {
let context = function() {
throw new Error("done() callback is deprecated, use promise instead");
}, abortController = abortControllers.get(context);
return abortController || (abortController = new AbortController(), abortControllers.set(context, abortController)), context.signal = abortController.signal, context.task = test5, context.skip = (condition, note) => {
if (condition !== !1)
throw test5.result ??= { state: "skip" }, test5.result.pending = !0, new PendingError("test is skipped; abort execution", test5, typeof condition == "string" ? condition : note);
}, context.annotate = ((message, type3, attachment) => {
if (test5.result && test5.result.state !== "run")
throw new Error(`Cannot annotate tests outside of the test run. The test "${test5.name}" finished running with the "${test5.result.state}" state already.`);
let annotation = {
message,
type: typeof type3 == "object" || type3 === void 0 ? "notice" : type3
}, annotationAttachment = typeof type3 == "object" ? type3 : attachment;
return annotationAttachment && (annotation.attachment = annotationAttachment, manageArtifactAttachment(annotation.attachment)), recordAsyncOperation(test5, recordArtifact(test5, {
type: "internal:annotation",
annotation
}).then(async ({ annotation: annotation2 }) => {
if (!runner2.onTestAnnotate)
throw new Error("Test runner doesn't support test annotations.");
await finishSendTasksUpdate(runner2);
let resolvedAnnotation = await runner2.onTestAnnotate(test5, annotation2);
return test5.annotations.push(resolvedAnnotation), resolvedAnnotation;
}));
}), context.onTestFailed = (handler, timeout) => {
test5.onFailed ||= [], test5.onFailed.push(withTimeout(handler, timeout ?? runner2.config.hookTimeout, !0, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
}, context.onTestFinished = (handler, timeout) => {
test5.onFinished ||= [], test5.onFinished.push(withTimeout(handler, timeout ?? runner2.config.hookTimeout, !0, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
}, runner2.extendTaskContext?.(context) || context;
}
function makeTimeoutError(isHook, timeout, stackTraceError) {
let message = `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms.
If this is a long-running ${isHook ? "hook" : "test"}, pass a timeout value as the last argument or configure it globally with "${isHook ? "hookTimeout" : "testTimeout"}".`, error = new Error(message);
return stackTraceError?.stack && (error.stack = stackTraceError.stack.replace(error.message, stackTraceError.message)), error;
}
var now$1 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
var now = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now, unixNow = Date.now, { clearTimeout: clearTimeout2, setTimeout: setTimeout2 } = getSafeTimers();
var packs = /* @__PURE__ */ new Map(), eventsPacks = [], pendingTasksUpdates = [];
function sendTasksUpdate(runner2) {
if (packs.size) {
let taskPacks = Array.from(packs).map(([id, task]) => [
id,
task[0],
task[1]
]), p = runner2.onTaskUpdate?.(taskPacks, eventsPacks);
p && (pendingTasksUpdates.push(p), p.then(() => pendingTasksUpdates.splice(pendingTasksUpdates.indexOf(p), 1), () => {
})), eventsPacks.length = 0, packs.clear();
}
}
async function finishSendTasksUpdate(runner2) {
sendTasksUpdate(runner2), await Promise.all(pendingTasksUpdates);
}
function throttle(fn2, ms) {
let last = 0, pendingCall;
return function call2(...args) {
let now3 = unixNow();
if (now3 - last > ms)
return last = now3, clearTimeout2(pendingCall), pendingCall = void 0, fn2.apply(this, args);
pendingCall ??= setTimeout2(() => call2.bind(this)(...args), ms);
};
}
var sendTasksUpdateThrottled = throttle(sendTasksUpdate, 100);
async function recordArtifact(task, artifact) {
let runner2 = getRunner(), stack = findTestFileStackTrace(task.file.filepath, new Error("STACK_TRACE").stack);
if (stack && (artifact.location = {
file: stack.file,
line: stack.line,
column: stack.column
}, artifact.type === "internal:annotation" && (artifact.annotation.location = artifact.location)), Array.isArray(artifact.attachments))
for (let attachment of artifact.attachments)
manageArtifactAttachment(attachment);
if (artifact.type === "internal:annotation")
return artifact;
if (!runner2.onTestArtifactRecord)
throw new Error("Test runner doesn't support test artifacts.");
await finishSendTasksUpdate(runner2);
let resolvedArtifact = await runner2.onTestArtifactRecord(task, artifact);
return task.artifacts.push(resolvedArtifact), resolvedArtifact;
}
var table = [];
for (let i2 = 65; i2 < 91; i2++)
table.push(String.fromCharCode(i2));
for (let i2 = 97; i2 < 123; i2++)
table.push(String.fromCharCode(i2));
for (let i2 = 0; i2 < 10; i2++)
table.push(i2.toString(10));
table.push("+", "/");
function encodeUint8Array(bytes) {
let base64 = "", len = bytes.byteLength;
for (let i2 = 0; i2 < len; i2 += 3)
if (len === i2 + 1) {
let a = (bytes[i2] & 252) >> 2, b2 = (bytes[i2] & 3) << 4;
base64 += table[a], base64 += table[b2], base64 += "==";
} else if (len === i2 + 2) {
let a = (bytes[i2] & 252) >> 2, b2 = (bytes[i2] & 3) << 4 | (bytes[i2 + 1] & 240) >> 4, c = (bytes[i2 + 1] & 15) << 2;
base64 += table[a], base64 += table[b2], base64 += table[c], base64 += "=";
} else {
let a = (bytes[i2] & 252) >> 2, b2 = (bytes[i2] & 3) << 4 | (bytes[i2 + 1] & 240) >> 4, c = (bytes[i2 + 1] & 15) << 2 | (bytes[i2 + 2] & 192) >> 6, d2 = bytes[i2 + 2] & 63;
base64 += table[a], base64 += table[b2], base64 += table[c], base64 += table[d2];
}
return base64;
}
function recordAsyncOperation(test5, promise) {
return promise = promise.finally(() => {
if (!test5.promises)
return;
let index2 = test5.promises.indexOf(promise);
index2 !== -1 && test5.promises.splice(index2, 1);
}), test5.promises || (test5.promises = []), test5.promises.push(promise), promise;
}
function manageArtifactAttachment(attachment) {
if (attachment.body == null && !attachment.path)
throw new TypeError('Test attachment requires "body" or "path" to be set. Both are missing.');
if (attachment.body && attachment.path)
throw new TypeError('Test attachment requires only one of "body" or "path" to be set. Both are specified.');
if (attachment.path && attachment.bodyEncoding)
throw new TypeError('Test attachment with "path" should not have "bodyEncoding" specified.');
attachment.body instanceof Uint8Array && (attachment.body = encodeUint8Array(attachment.body)), attachment.body != null && (attachment.bodyEncoding ??= "base64");
}
// ../../node_modules/.pnpm/@vitest+runner@4.1.10/node_modules/@vitest/runner/dist/utils.js
init_cjs_shims();
// ../../node_modules/.pnpm/vitest@4.1.10_@opentelemetry+api@1.9.1_@types+node@22.20.1_@vitest+coverage-istanbul@3._f51dec9f55339d6c09addddd62782db2/node_modules/vitest/dist/chunks/utils.BX5Fg8C4.js
init_cjs_shims();
var NAME_WORKER_STATE = "__vitest_worker__";
function getWorkerState() {
let workerState = globalThis[NAME_WORKER_STATE];
if (!workerState) throw new Error(`Vitest failed to access its internal state.
One of the following is possible:
- "vitest" is imported directly without running "vitest" command
- "vitest" is imported inside "globalSetup" (to fix this, use "setupFiles" instead, because "globalSetup" runs in a different context)
- "vitest" is imported inside Vite / Vitest config file
- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues
`);
return workerState;
}
function isChildProcess() {
return typeof process < "u" && !!process.send;
}
function resetModules(modules, resetMocks = !1) {
let skipPaths = [
/\/vitest\/dist\//,
/vitest-virtual-\w+\/dist/,
/@vitest\/dist/,
...resetMocks ? [] : [/^mock:/]
];
modules.idToModuleMap.forEach((node, path) => {
skipPaths.some((re) => re.test(path)) || (node.promise = void 0, node.exports = void 0, node.evaluated = !1, node.importers.clear());
});
}
function waitNextTick() {
let { setTimeout: setTimeout3 } = getSafeTimers();
return new Promise((resolve2) => setTimeout3(resolve2, 0));
}
async function waitForImportsToResolve() {
await waitNextTick();
let state = getWorkerState(), promises = [], resolvingCount = state.resolvingModules.size;
for (let [_, mod] of state.evaluatedModules.idToModuleMap) mod.promise && !mod.evaluated && promises.push(mod.promise);
!promises.length && !resolvingCount || (await Promise.allSettled(promises), await waitForImportsToResolve());
}
// ../../node_modules/.pnpm/@vitest+expect@4.1.10/node_modules/@vitest/expect/dist/index.js
init_cjs_shims();
// ../../node_modules/.pnpm/@vitest+spy@4.1.10/node_modules/@vitest/spy/dist/index.js
init_cjs_shims();
function isMockFunction(fn2) {
return typeof fn2 == "function" && "_isMockFunction" in fn2 && fn2._isMockFunction === !0;
}
var MOCK_RESTORE = /* @__PURE__ */ new Set(), REGISTERED_MOCKS = /* @__PURE__ */ new Set(), MOCK_CONFIGS = /* @__PURE__ */ new WeakMap();
function createMockInstance(options = {}) {
let { originalImplementation, restore, mockImplementation, resetToMockImplementation, resetToMockName } = options;
restore && MOCK_RESTORE.add(restore);
let config2 = getDefaultConfig(originalImplementation), state = getDefaultState(), mock = createMock({
config: config2,
state,
...options
}), mockLength = (mockImplementation || originalImplementation)?.length ?? 0;
return Object.defineProperty(mock, "length", {
writable: !0,
enumerable: !1,
value: mockLength,
configurable: !0
}), resetToMockName && (config2.mockName = mock.name || "vi.fn()"), MOCK_CONFIGS.set(mock, config2), REGISTERED_MOCKS.add(mock), mock._isMockFunction = !0, mock.getMockImplementation = () => config2.onceMockImplementations[0] || config2.mockImplementation, Object.defineProperty(mock, "mock", {
configurable: !1,
enumerable: !0,
writable: !1,
value: state
}), mock.mockImplementation = function(implementation) {
return config2.mockImplementation = implementation, mock;
}, mock.mockImplementationOnce = function(implementation) {
return config2.onceMockImplementations.push(implementation), mock;
}, mock.withImplementation = function(implementation, callback) {
let previousImplementation = config2.mockImplementation, previousOnceImplementations = config2.onceMockImplementations, reset = () => {
config2.mockImplementation = previousImplementation, config2.onceMockImplementations = previousOnceImplementations;
};
config2.mockImplementation = implementation, config2.onceMockImplementations = [];
let returnValue = callback();
return typeof returnValue == "object" && typeof returnValue?.then == "function" ? returnValue.then(() => (reset(), mock)) : (reset(), mock);
}, mock.mockReturnThis = function() {
return mock.mockImplementation(function() {
return this;
});
}, mock.mockReturnValue = function(value) {
return mock.mockImplementation(function() {
return new.target && throwConstructorError("mockReturnValue"), value;
});
}, mock.mockReturnValueOnce = function(value) {
return mock.mockImplementationOnce(function() {
return new.target && throwConstructorError("mockReturnValueOnce"), value;
});
}, mock.mockThrow = function(value) {
return mock.mockImplementation(function() {
throw value;
});
}, mock.mockThrowOnce = function(value) {
return mock.mockImplementationOnce(function() {
throw value;
});
}, mock.mockResolvedValue = function(value) {
return mock.mockImplementation(function() {
return new.target && throwConstructorError("mockResolvedValue"), Promise.resolve(value);
});
}, mock.mockResolvedValueOnce = function(value) {
return mock.mockImplementationOnce(function() {
return new.target && throwConstructorError("mockResolvedValueOnce"), Promise.resolve(value);
});
}, mock.mockRejectedValue = function(value) {
return mock.mockImplementation(function() {
return new.target && throwConstructorError("mockRejectedValue"), Promise.reject(value);
});
}, mock.mockRejectedValueOnce = function(value) {
return mock.mockImplementationOnce(function() {
return new.target && throwConstructorError("mockRejectedValueOnce"), Promise.reject(value);
});
}, mock.mockClear = function() {
return state.calls = [], state.contexts = [], state.instances = [], state.invocationCallOrder = [], state.results = [], state.settledResults = [], mock;
}, mock.mockReset = function() {
return mock.mockClear(), config2.mockImplementation = resetToMockImplementation ? mockImplementation : void 0, config2.mockName = resetToMockName && mock.name || "vi.fn()", config2.onceMockImplementations = [], mock;
}, mock.mockRestore = function() {
return mock.mockReset(), restore?.();
}, mock.mockName = function(name) {
return typeof name == "string" && (config2.mockName = name), mock;
}, mock.getMockName = function() {
return config2.mockName || "vi.fn()";
}, Symbol.dispose && (mock[Symbol.dispose] = () => mock.mockRestore()), mockImplementation && mock.mockImplementation(mockImplementation), mock;
}
function fn(originalImplementation) {
return originalImplementation != null && isMockFunction(originalImplementation) ? originalImplementation : createMockInstance({
mockImplementation: originalImplementation,
resetToMockImplementation: !0
});
}
function spyOn(object2, key, accessor) {
assert2(object2 != null, "The vi.spyOn() function could not find an object to spy upon. The first argument must be defined."), assert2(typeof object2 == "object" || typeof object2 == "function", "Vitest cannot spy on a primitive value.");
let [originalDescriptorObject, originalDescriptor] = getDescriptor(object2, key) || [];
assert2(originalDescriptor || key in object2, `The property "${String(key)}" is not defined on the ${typeof object2}.`);
let accessType = accessor || "value", ssr = !1;
accessType === "value" && originalDescriptor && originalDescriptor.value == null && originalDescriptor.get && (accessType = "get", ssr = !0);
let original;
originalDescriptor ? (original = originalDescriptor[accessType], original == null && accessType === "value" && (original = object2[key])) : accessType !== "value" ? original = () => object2[key] : original = object2[key];
let originalImplementation = ssr && original ? original() : original, originalType = typeof originalImplementation;
if (assert2(
// allow only functions
originalType === "function" || accessType !== "value" && original == null,
`vi.spyOn() can only spy on a function. Received ${originalType}.`
), isMockFunction(originalImplementation))
return originalImplementation;
let reassign = (cb) => {
let { value, ...desc } = originalDescriptor || {
configurable: !0,
writable: !0
};
accessType !== "value" && delete desc.writable, desc[accessType] = cb, Object.defineProperty(object2, key, desc);
}, mock = createMockInstance({
restore: () => {
originalDescriptorObject !== object2 ? Reflect.deleteProperty(object2, key) : originalDescriptor && !original ? Object.defineProperty(object2, key, originalDescriptor) : reassign(original);
},
originalImplementation,
resetToMockName: !0
});
try {
reassign(ssr ? () => mock : mock);
} catch (error) {
throw error instanceof TypeError && Symbol.toStringTag && object2[Symbol.toStringTag] === "Module" && (error.message.includes("Cannot redefine property") || error.message.includes("Cannot replace module namespace") || error.message.includes("can't redefine non-configurable property")) ? new TypeError(`Cannot spy on export "${String(key)}". Module namespace is not configurable in ESM. See: https://vitest.dev/guide/browser/#limitations`, { cause: error }) : error;
}
return mock;
}
function getDescriptor(obj, method) {
let objDescriptor = Object.getOwnPropertyDescriptor(obj, method);
if (objDescriptor)
return [obj, objDescriptor];
let currentProto = Object.getPrototypeOf(obj);
for (; currentProto !== null; ) {
let descriptor = Object.getOwnPropertyDescriptor(currentProto, method);
if (descriptor)
return [currentProto, descriptor];
currentProto = Object.getPrototypeOf(currentProto);
}
}
function assert2(condition, message) {
if (!condition)
throw new Error(message);
}
var invocationCallCounter = 1;
function createMock({ state, config: config2, name: mockName, prototypeState, prototypeConfig, keepMembersImplementation, mockImplementation, prototypeMembers = [] }) {
let original = config2.mockOriginal, pseudoOriginal = mockImplementation, name = mockName || original?.name || "Mock", namedObject = { [name]: (function(...args) {
registerCalls(args, state, prototypeState), registerInvocationOrder(invocationCallCounter++, state, prototypeState);
let result = {
type: "incomplete",
value: void 0
}, settledResult = {
type: "incomplete",
value: void 0
};
registerResult(result, state, prototypeState), registerSettledResult(settledResult, state, prototypeState);
let context = new.target ? void 0 : this, [instanceIndex, instancePrototypeIndex] = registerInstance(context, state, prototypeState), [contextIndex, contextPrototypeIndex] = registerContext(context, state, prototypeState), implementation = config2.onceMockImplementations.shift() || config2.mockImplementation || prototypeConfig?.onceMockImplementations.shift() || prototypeConfig?.mockImplementation || original || function() {
}, returnValue, thrownValue, didThrow = !1;
try {
if (new.target) {
returnValue = Reflect.construct(implementation, args, new.target);
for (let prop of prototypeMembers) {
let prototypeMock = returnValue[prop];
if (prototypeMock !== mock.prototype[prop])
continue;
let isMock = isMockFunction(prototypeMock), prototypeState2 = isMock ? prototypeMock.mock : void 0, prototypeConfig2 = isMock ? MOCK_CONFIGS.get(prototypeMock) : void 0;
returnValue[prop] = createMockInstance({
originalImplementation: keepMembersImplementation ? prototypeConfig2?.mockOriginal : void 0,
prototypeState: prototypeState2,
prototypeConfig: prototypeConfig2,
keepMembersImplementation
});
}
} else
returnValue = implementation.apply(this, args);
} catch (error) {
throw thrownValue = error, didThrow = !0, error instanceof TypeError && error.message.includes("is not a constructor") && console.warn(`[vitest] The ${namedObject[name].getMockName()} mock did not use 'function' or 'class' in its implementation, see https://vitest.dev/api/vi#vi-spyon for examples.`), error;
} finally {
didThrow ? (result.type = "throw", result.value = thrownValue, settledResult.type = "rejected", settledResult.value = thrownValue) : (result.type = "return", result.value = returnValue, new.target && (state.contexts[contextIndex - 1] = returnValue, state.instances[instanceIndex - 1] = returnValue, contextPrototypeIndex != null && prototypeState && (prototypeState.contexts[contextPrototypeIndex - 1] = returnValue), instancePrototypeIndex != null && prototypeState && (prototypeState.instances[instancePrototypeIndex - 1] = returnValue)), returnValue instanceof Promise ? returnValue.then((settledValue) => {
settledResult.type = "fulfilled", settledResult.value = settledValue;
}, (rejectedValue) => {
settledResult.type = "rejected", settledResult.value = rejectedValue;
}) : (settledResult.type = "fulfilled", settledResult.value = returnValue));
}
return returnValue;
}) }, mock = namedObject[name], copyPropertiesFrom = original || pseudoOriginal;
return copyPropertiesFrom && copyOriginalStaticProperties(mock, copyPropertiesFrom), mock;
}
function registerCalls(args, state, prototypeState) {
state.calls.push(args), prototypeState?.calls.push(args);
}
function registerInvocationOrder(order, state, prototypeState) {
state.invocationCallOrder.push(order), prototypeState?.invocationCallOrder.push(order);
}
function registerResult(result, state, prototypeState) {
state.results.push(result), prototypeState?.results.push(result);
}
function registerSettledResult(result, state, prototypeState) {
state.settledResults.push(result), prototypeState?.settledResults.push(result);
}
function registerInstance(instance, state, prototypeState) {
let instanceIndex = state.instances.push(instance), instancePrototypeIndex = prototypeState?.instances.push(instance);
return [instanceIndex, instancePrototypeIndex];
}
function registerContext(context, state, prototypeState) {
let contextIndex = state.contexts.push(context), contextPrototypeIndex = prototypeState?.contexts.push(context);
return [contextIndex, contextPrototypeIndex];
}
function copyOriginalStaticProperties(mock, original) {
let { properties, descriptors } = getAllProperties(original);
for (let key of properties) {
let descriptor = descriptors[key];
getDescriptor(mock, key) || Object.defineProperty(mock, key, descriptor);
}
}
var ignoreProperties = /* @__PURE__ */ new Set([
"length",
"name",
"prototype",
/* @__PURE__ */ Symbol.for("nodejs.util.promisify.custom")
]);
function getAllProperties(original) {
let properties = /* @__PURE__ */ new Set(), descriptors = {};
for (; original && original !== Object.prototype && original !== Function.prototype; ) {
let ownProperties = [...Object.getOwnPropertyNames(original), ...Object.getOwnPropertySymbols(original)];
for (let prop of ownProperties)
descriptors[prop] || ignoreProperties.has(prop) || (properties.add(prop), descriptors[prop] = Object.getOwnPropertyDescriptor(original, prop));
original = Object.getPrototypeOf(original);
}
return {
properties,
descriptors
};
}
function getDefaultConfig(original) {
return {
mockImplementation: void 0,
mockOriginal: original,
mockName: "vi.fn()",
onceMockImplementations: []
};
}
function getDefaultState() {
let state = {
calls: [],
contexts: [],
instances: [],
invocationCallOrder: [],
settledResults: [],
results: [],
get lastCall() {
return state.calls.at(-1);
}
};
return state;
}
function restoreAllMocks() {
for (let restore of MOCK_RESTORE)
restore();
MOCK_RESTORE.clear();
}
function clearAllMocks() {
REGISTERED_MOCKS.forEach((mock) => mock.mockClear());
}
function resetAllMocks() {
REGISTERED_MOCKS.forEach((mock) => mock.mockReset());
}
function throwConstructorError(shorthand) {
throw new TypeError(`Cannot use \`${shorthand}\` when called with \`new\`. Use \`mockImplementation\` with a \`class\` keyword instead. See https://vitest.dev/api/mock#class-support for more information.`);
}
// ../../node_modules/.pnpm/chai@6.2.2/node_modules/chai/index.js
var chai_exports = {};
__export(chai_exports, {
Assertion: () => Assertion,
AssertionError: () => AssertionError,
Should: () => Should,
assert: () => assert3,
config: () => config,
expect: () => expect,
should: () => should,
use: () => use,
util: () => utils_exports
});
init_cjs_shims();
var __defProp = Object.defineProperty, __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __name = (target, value) => __defProp(target, "name", { value, configurable: !0 }), __export2 = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: !0 });
}, __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value), utils_exports = {};
__export2(utils_exports, {
addChainableMethod: () => addChainableMethod,
addLengthGuard: () => addLengthGuard,
addMethod: () => addMethod,
addProperty: () => addProperty,
checkError: () => check_error_exports,
compareByInspect: () => compareByInspect,
eql: () => deep_eql_default,
events: () => events,
expectTypes: () => expectTypes,
flag: () => flag,
getActual: () => getActual,
getMessage: () => getMessage2,
getName: () => getName,
getOperator: () => getOperator,
getOwnEnumerableProperties: () => getOwnEnumerableProperties,
getOwnEnumerablePropertySymbols: () => getOwnEnumerablePropertySymbols,
getPathInfo: () => getPathInfo,
hasProperty: () => hasProperty,
inspect: () => inspect22,
isNaN: () => isNaN22,
isNumeric: () => isNumeric,
isProxyEnabled: () => isProxyEnabled,
isRegExp: () => isRegExp2,
objDisplay: () => objDisplay2,
overwriteChainableMethod: () => overwriteChainableMethod,
overwriteMethod: () => overwriteMethod,
overwriteProperty: () => overwriteProperty,
proxify: () => proxify,
test: () => test3,
transferFlags: () => transferFlags,
type: () => type
});
var check_error_exports = {};
__export2(check_error_exports, {
compatibleConstructor: () => compatibleConstructor,
compatibleInstance: () => compatibleInstance,
compatibleMessage: () => compatibleMessage,
getConstructorName: () => getConstructorName2,
getMessage: () => getMessage
});
function isErrorInstance(obj) {
return obj instanceof Error || Object.prototype.toString.call(obj) === "[object Error]";
}
__name(isErrorInstance, "isErrorInstance");
function isRegExp(obj) {
return Object.prototype.toString.call(obj) === "[object RegExp]";
}
__name(isRegExp, "isRegExp");
function compatibleInstance(thrown, errorLike) {
return isErrorInstance(errorLike) && thrown === errorLike;
}
__name(compatibleInstance, "compatibleInstance");
function compatibleConstructor(thrown, errorLike) {
return isErrorInstance(errorLike) ? thrown.constructor === errorLike.constructor || thrown instanceof errorLike.constructor : (typeof errorLike == "object" || typeof errorLike == "function") && errorLike.prototype ? thrown.constructor === errorLike || thrown instanceof errorLike : !1;
}
__name(compatibleConstructor, "compatibleConstructor");
function compatibleMessage(thrown, errMatcher) {
let comparisonString = typeof thrown == "string" ? thrown : thrown.message;
return isRegExp(errMatcher) ? errMatcher.test(comparisonString) : typeof errMatcher == "string" ? comparisonString.indexOf(errMatcher) !== -1 : !1;
}
__name(compatibleMessage, "compatibleMessage");
function getConstructorName2(errorLike) {
let constructorName = errorLike;
return isErrorInstance(errorLike) ? constructorName = errorLike.constructor.name : typeof errorLike == "function" && (constructorName = errorLike.name, constructorName === "" && (constructorName = new errorLike().name || constructorName)), constructorName;
}
__name(getConstructorName2, "getConstructorName");
function getMessage(errorLike) {
let msg = "";
return errorLike && errorLike.message ? msg = errorLike.message : typeof errorLike == "string" && (msg = errorLike), msg;
}
__name(getMessage, "getMessage");
function flag(obj, key, value) {
let flags = obj.__flags || (obj.__flags = /* @__PURE__ */ Object.create(null));
if (arguments.length === 3)
flags[key] = value;
else
return flags[key];
}
__name(flag, "flag");
function test3(obj, args) {
let negate = flag(obj, "negate"), expr = args[0];
return negate ? !expr : expr;
}
__name(test3, "test");
function type(obj) {
if (typeof obj > "u")
return "undefined";
if (obj === null)
return "null";
let stringTag = obj[Symbol.toStringTag];
return typeof stringTag == "string" ? stringTag : Object.prototype.toString.call(obj).slice(8, -1);
}
__name(type, "type");
var canElideFrames = "captureStackTrace" in Error, _AssertionError = class _AssertionError2 extends Error {
constructor(message = "Unspecified AssertionError", props, ssf) {
super(message), __publicField(this, "message"), this.message = message, canElideFrames && Error.captureStackTrace(this, ssf || _AssertionError2);
for (let key in props)
key in this || (this[key] = props[key]);
}
get name() {
return "AssertionError";
}
get ok() {
return !1;
}
toJSON(stack) {
return {
...this,
name: this.name,
message: this.message,
ok: !1,
stack: stack !== !1 ? this.stack : void 0
};
}
};
__name(_AssertionError, "AssertionError");
var AssertionError = _AssertionError;
function expectTypes(obj, types) {
let flagMsg = flag(obj, "message"), ssfi = flag(obj, "ssfi");
flagMsg = flagMsg ? flagMsg + ": " : "", obj = flag(obj, "object"), types = types.map(function(t) {
return t.toLowerCase();
}), types.sort();
let str = types.map(function(t, index2) {
let art = ~["a", "e", "i", "o", "u"].indexOf(t.charAt(0)) ? "an" : "a";
return (types.length > 1 && index2 === types.length - 1 ? "or " : "") + art + " " + t;
}).join(", "), objType = type(obj).toLowerCase();
if (!types.some(function(expected) {
return objType === expected;
}))
throw new AssertionError(
flagMsg + "object tested must be " + str + ", but " + objType + " given",
void 0,
ssfi
);
}
__name(expectTypes, "expectTypes");
function getActual(obj, args) {
return args.length > 4 ? args[4] : obj._obj;
}
__name(getActual, "getActual");
var ansiColors2 = {
bold: ["1", "22"],
dim: ["2", "22"],
italic: ["3", "23"],
underline: ["4", "24"],
// 5 & 6 are blinking
inverse: ["7", "27"],
hidden: ["8", "28"],
strike: ["9", "29"],
// 10-20 are fonts
// 21-29 are resets for 1-9
black: ["30", "39"],
red: ["31", "39"],
green: ["32", "39"],
yellow: ["33", "39"],
blue: ["34", "39"],
magenta: ["35", "39"],
cyan: ["36", "39"],
white: ["37", "39"],
brightblack: ["30;1", "39"],
brightred: ["31;1", "39"],
brightgreen: ["32;1", "39"],
brightyellow: ["33;1", "39"],
brightblue: ["34;1", "39"],
brightmagenta: ["35;1", "39"],
brightcyan: ["36;1", "39"],
brightwhite: ["37;1", "39"],
grey: ["90", "39"]
}, styles2 = {
special: "cyan",
number: "yellow",
bigint: "yellow",
boolean: "yellow",
undefined: "grey",
null: "bold",
string: "green",
symbol: "green",
date: "magenta",
regexp: "red"
}, truncator2 = "\u2026";
function colorise2(value, styleType) {
let color = ansiColors2[styles2[styleType]] || ansiColors2[styleType] || "";
return color ? `\x1B[${color[0]}m${String(value)}\x1B[${color[1]}m` : String(value);
}
__name(colorise2, "colorise");
function normaliseOptions2({
showHidden = !1,
depth = 2,
colors = !1,
customInspect = !0,
showProxy = !1,
maxArrayLength = 1 / 0,
breakLength = 1 / 0,
seen = [],
// eslint-disable-next-line no-shadow
truncate: truncate22 = 1 / 0,
stylize = String
} = {}, inspect3) {
let options = {
showHidden: !!showHidden,
depth: Number(depth),
colors: !!colors,
customInspect: !!customInspect,
showProxy: !!showProxy,
maxArrayLength: Number(maxArrayLength),
breakLength: Number(breakLength),
truncate: Number(truncate22),
seen,
inspect: inspect3,
stylize
};
return options.colors && (options.stylize = colorise2), options;
}
__name(normaliseOptions2, "normaliseOptions");
function isHighSurrogate2(char) {
return char >= "\uD800" && char <= "\uDBFF";
}
__name(isHighSurrogate2, "isHighSurrogate");
function truncate2(string2, length, tail = truncator2) {
string2 = String(string2);
let tailLength = tail.length, stringLength = string2.length;
if (tailLength > length && stringLength > tailLength)
return tail;
if (stringLength > length && stringLength > tailLength) {
let end = length - tailLength;
return end > 0 && isHighSurrogate2(string2[end - 1]) && (end = end - 1), `${string2.slice(0, end)}${tail}`;
}
return string2;
}
__name(truncate2, "truncate");
function inspectList2(list, options, inspectItem, separator = ", ") {
inspectItem = inspectItem || options.inspect;
let size = list.length;
if (size === 0)
return "";
let originalLength = options.truncate, output = "", peek = "", truncated = "";
for (let i2 = 0; i2 < size; i2 += 1) {
let last = i2 + 1 === list.length, secondToLast = i2 + 2 === list.length;
truncated = `${truncator2}(${list.length - i2})`;
let value = list[i2];
options.truncate = originalLength - output.length - (last ? 0 : separator.length);
let string2 = peek || inspectItem(value, options) + (last ? "" : separator), nextLength = output.length + string2.length, truncatedLength = nextLength + truncated.length;
if (last && nextLength > originalLength && output.length + truncated.length <= originalLength || !last && !secondToLast && truncatedLength > originalLength || (peek = last ? "" : inspectItem(list[i2 + 1], options) + (secondToLast ? "" : separator), !last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength))
break;
if (output += string2, !last && !secondToLast && nextLength + peek.length >= originalLength) {
truncated = `${truncator2}(${list.length - i2 - 1})`;
break;
}
truncated = "";
}
return `${output}${truncated}`;
}
__name(inspectList2, "inspectList");
function quoteComplexKey2(key) {
return key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/) ? key : JSON.stringify(key).replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
}
__name(quoteComplexKey2, "quoteComplexKey");
function inspectProperty2([key, value], options) {
return options.truncate -= 2, typeof key == "string" ? key = quoteComplexKey2(key) : typeof key != "number" && (key = `[${options.inspect(key, options)}]`), options.truncate -= key.length, value = options.inspect(value, options), `${key}: ${value}`;
}
__name(inspectProperty2, "inspectProperty");
function inspectArray2(array2, options) {
let nonIndexProperties = Object.keys(array2).slice(array2.length);
if (!array2.length && !nonIndexProperties.length)
return "[]";
options.truncate -= 4;
let listContents = inspectList2(array2, options);
options.truncate -= listContents.length;
let propertyContents = "";
return nonIndexProperties.length && (propertyContents = inspectList2(nonIndexProperties.map((key) => [key, array2[key]]), options, inspectProperty2)), `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ""} ]`;
}
__name(inspectArray2, "inspectArray");
var getArrayName2 = /* @__PURE__ */ __name((array2) => typeof Buffer == "function" && array2 instanceof Buffer ? "Buffer" : array2[Symbol.toStringTag] ? array2[Symbol.toStringTag] : array2.constructor.name, "getArrayName");
function inspectTypedArray2(array2, options) {
let name = getArrayName2(array2);
options.truncate -= name.length + 4;
let nonIndexProperties = Object.keys(array2).slice(array2.length);
if (!array2.length && !nonIndexProperties.length)
return `${name}[]`;
let output = "";
for (let i2 = 0; i2 < array2.length; i2++) {
let string2 = `${options.stylize(truncate2(array2[i2], options.truncate), "number")}${i2 === array2.length - 1 ? "" : ", "}`;
if (options.truncate -= string2.length, array2[i2] !== array2.length && options.truncate <= 3) {
output += `${truncator2}(${array2.length - array2[i2] + 1})`;
break;
}
output += string2;
}
let propertyContents = "";
return nonIndexProperties.length && (propertyContents = inspectList2(nonIndexProperties.map((key) => [key, array2[key]]), options, inspectProperty2)), `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ""} ]`;
}
__name(inspectTypedArray2, "inspectTypedArray");
function inspectDate2(dateObject, options) {
let stringRepresentation = dateObject.toJSON();
if (stringRepresentation === null)
return "Invalid Date";
let split = stringRepresentation.split("T"), date = split[0];
return options.stylize(`${date}T${truncate2(split[1], options.truncate - date.length - 1)}`, "date");
}
__name(inspectDate2, "inspectDate");
function inspectFunction2(func, options) {
let functionType = func[Symbol.toStringTag] || "Function", name = func.name;
return name ? options.stylize(`[${functionType} ${truncate2(name, options.truncate - 11)}]`, "special") : options.stylize(`[${functionType}]`, "special");
}
__name(inspectFunction2, "inspectFunction");
function inspectMapEntry2([key, value], options) {
return options.truncate -= 4, key = options.inspect(key, options), options.truncate -= key.length, value = options.inspect(value, options), `${key} => ${value}`;
}
__name(inspectMapEntry2, "inspectMapEntry");
function mapToEntries2(map2) {
let entries = [];
return map2.forEach((value, key) => {
entries.push([key, value]);
}), entries;
}
__name(mapToEntries2, "mapToEntries");
function inspectMap2(map2, options) {
return map2.size === 0 ? "Map{}" : (options.truncate -= 7, `Map{ ${inspectList2(mapToEntries2(map2), options, inspectMapEntry2)} }`);
}
__name(inspectMap2, "inspectMap");
var isNaN2 = Number.isNaN || ((i2) => i2 !== i2);
function inspectNumber2(number, options) {
return isNaN2(number) ? options.stylize("NaN", "number") : number === 1 / 0 ? options.stylize("Infinity", "number") : number === -1 / 0 ? options.stylize("-Infinity", "number") : number === 0 ? options.stylize(1 / number === 1 / 0 ? "+0" : "-0", "number") : options.stylize(truncate2(String(number), options.truncate), "number");
}
__name(inspectNumber2, "inspectNumber");
function inspectBigInt2(number, options) {
let nums = truncate2(number.toString(), options.truncate - 1);
return nums !== truncator2 && (nums += "n"), options.stylize(nums, "bigint");
}
__name(inspectBigInt2, "inspectBigInt");
function inspectRegExp2(value, options) {
let flags = value.toString().split("/")[2], sourceLength = options.truncate - (2 + flags.length), source = value.source;
return options.stylize(`/${truncate2(source, sourceLength)}/${flags}`, "regexp");
}
__name(inspectRegExp2, "inspectRegExp");
function arrayFromSet2(set22) {
let values = [];
return set22.forEach((value) => {
values.push(value);
}), values;
}
__name(arrayFromSet2, "arrayFromSet");
function inspectSet2(set22, options) {
return set22.size === 0 ? "Set{}" : (options.truncate -= 7, `Set{ ${inspectList2(arrayFromSet2(set22), options)} }`);
}
__name(inspectSet2, "inspectSet");
var stringEscapeChars2 = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]", "g"), escapeCharacters2 = {
"\b": "\\b",
" ": "\\t",
"\n": "\\n",
"\f": "\\f",
"\r": "\\r",
"'": "\\'",
"\\": "\\\\"
}, hex2 = 16, unicodeLength = 4;
function escape2(char) {
return escapeCharacters2[char] || `\\u${`0000${char.charCodeAt(0).toString(hex2)}`.slice(-unicodeLength)}`;
}
__name(escape2, "escape");
function inspectString2(string2, options) {
return stringEscapeChars2.test(string2) && (string2 = string2.replace(stringEscapeChars2, escape2)), options.stylize(`'${truncate2(string2, options.truncate - 2)}'`, "string");
}
__name(inspectString2, "inspectString");
function inspectSymbol2(value) {
return "description" in Symbol.prototype ? value.description ? `Symbol(${value.description})` : "Symbol()" : value.toString();
}
__name(inspectSymbol2, "inspectSymbol");
var getPromiseValue2 = /* @__PURE__ */ __name(() => "Promise{\u2026}", "getPromiseValue"), promise_default = getPromiseValue2;
function inspectObject2(object2, options) {
let properties = Object.getOwnPropertyNames(object2), symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object2) : [];
if (properties.length === 0 && symbols.length === 0)
return "{}";
if (options.truncate -= 4, options.seen = options.seen || [], options.seen.includes(object2))
return "[Circular]";
options.seen.push(object2);
let propertyContents = inspectList2(properties.map((key) => [key, object2[key]]), options, inspectProperty2), symbolContents = inspectList2(symbols.map((key) => [key, object2[key]]), options, inspectProperty2);
options.seen.pop();
let sep = "";
return propertyContents && symbolContents && (sep = ", "), `{ ${propertyContents}${sep}${symbolContents} }`;
}
__name(inspectObject2, "inspectObject");
var toStringTag2 = typeof Symbol < "u" && Symbol.toStringTag ? Symbol.toStringTag : !1;
function inspectClass2(value, options) {
let name = "";
return toStringTag2 && toStringTag2 in value && (name = value[toStringTag2]), name = name || value.constructor.name, (!name || name === "_class") && (name = "<Anonymous Class>"), options.truncate -= name.length, `${name}${inspectObject2(value, options)}`;
}
__name(inspectClass2, "inspectClass");
function inspectArguments2(args, options) {
return args.length === 0 ? "Arguments[]" : (options.truncate -= 13, `Arguments[ ${inspectList2(args, options)} ]`);
}
__name(inspectArguments2, "inspectArguments");
var errorKeys2 = [
"stack",
"line",
"column",
"name",
"message",
"fileName",
"lineNumber",
"columnNumber",
"number",
"description",
"cause"
];
function inspectObject22(error, options) {
let properties = Object.getOwnPropertyNames(error).filter((key) => errorKeys2.indexOf(key) === -1), name = error.name;
options.truncate -= name.length;
let message = "";
if (typeof error.message == "string" ? message = truncate2(error.message, options.truncate) : properties.unshift("message"), message = message ? `: ${message}` : "", options.truncate -= message.length + 5, options.seen = options.seen || [], options.seen.includes(error))
return "[Circular]";
options.seen.push(error);
let propertyContents = inspectList2(properties.map((key) => [key, error[key]]), options, inspectProperty2);
return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ""}`;
}
__name(inspectObject22, "inspectObject");
function inspectAttribute2([key, value], options) {
return options.truncate -= 3, value ? `${options.stylize(String(key), "yellow")}=${options.stylize(`"${value}"`, "string")}` : `${options.stylize(String(key), "yellow")}`;
}
__name(inspectAttribute2, "inspectAttribute");
function inspectNodeCollection2(collection, options) {
return inspectList2(collection, options, inspectNode2, `
`);
}
__name(inspectNodeCollection2, "inspectNodeCollection");
function inspectNode2(node, options) {
switch (node.nodeType) {
case 1:
return inspectHTML2(node, options);
case 3:
return options.inspect(node.data, options);
default:
return options.inspect(node, options);
}
}
__name(inspectNode2, "inspectNode");
function inspectHTML2(element, options) {
let properties = element.getAttributeNames(), name = element.tagName.toLowerCase(), head = options.stylize(`<${name}`, "special"), headClose = options.stylize(">", "special"), tail = options.stylize(`</${name}>`, "special");
options.truncate -= name.length * 2 + 5;
let propertyContents = "";
properties.length > 0 && (propertyContents += " ", propertyContents += inspectList2(properties.map((key) => [key, element.getAttribute(key)]), options, inspectAttribute2, " ")), options.truncate -= propertyContents.length;
let truncate22 = options.truncate, children = inspectNodeCollection2(element.children, options);
return children && children.length > truncate22 && (children = `${truncator2}(${element.children.length})`), `${head}${propertyContents}${headClose}${children}${tail}`;
}
__name(inspectHTML2, "inspectHTML");
var symbolsSupported2 = typeof Symbol == "function" && typeof Symbol.for == "function", chaiInspect2 = symbolsSupported2 ? /* @__PURE__ */ Symbol.for("chai/inspect") : "@@chai/inspect", nodeInspect2 = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), constructorMap2 = /* @__PURE__ */ new WeakMap(), stringTagMap2 = {}, baseTypesMap2 = {
undefined: /* @__PURE__ */ __name((value, options) => options.stylize("undefined", "undefined"), "undefined"),
null: /* @__PURE__ */ __name((value, options) => options.stylize("null", "null"), "null"),
boolean: /* @__PURE__ */ __name((value, options) => options.stylize(String(value), "boolean"), "boolean"),
Boolean: /* @__PURE__ */ __name((value, options) => options.stylize(String(value), "boolean"), "Boolean"),
number: inspectNumber2,
Number: inspectNumber2,
bigint: inspectBigInt2,
BigInt: inspectBigInt2,
string: inspectString2,
String: inspectString2,
function: inspectFunction2,
Function: inspectFunction2,
symbol: inspectSymbol2,
// A Symbol polyfill will return `Symbol` not `symbol` from typedetect
Symbol: inspectSymbol2,
Array: inspectArray2,
Date: inspectDate2,
Map: inspectMap2,
Set: inspectSet2,
RegExp: inspectRegExp2,
Promise: promise_default,
// WeakSet, WeakMap are totally opaque to us
WeakSet: /* @__PURE__ */ __name((value, options) => options.stylize("WeakSet{\u2026}", "special"), "WeakSet"),
WeakMap: /* @__PURE__ */ __name((value, options) => options.stylize("WeakMap{\u2026}", "special"), "WeakMap"),
Arguments: inspectArguments2,
Int8Array: inspectTypedArray2,
Uint8Array: inspectTypedArray2,
Uint8ClampedArray: inspectTypedArray2,
Int16Array: inspectTypedArray2,
Uint16Array: inspectTypedArray2,
Int32Array: inspectTypedArray2,
Uint32Array: inspectTypedArray2,
Float32Array: inspectTypedArray2,
Float64Array: inspectTypedArray2,
Generator: /* @__PURE__ */ __name(() => "", "Generator"),
DataView: /* @__PURE__ */ __name(() => "", "DataView"),
ArrayBuffer: /* @__PURE__ */ __name(() => "", "ArrayBuffer"),
Error: inspectObject22,
HTMLCollection: inspectNodeCollection2,
NodeList: inspectNodeCollection2
}, inspectCustom2 = /* @__PURE__ */ __name((value, options, type3, inspectFn) => chaiInspect2 in value && typeof value[chaiInspect2] == "function" ? value[chaiInspect2](options) : nodeInspect2 in value && typeof value[nodeInspect2] == "function" ? value[nodeInspect2](options.depth, options, inspectFn) : "inspect" in value && typeof value.inspect == "function" ? value.inspect(options.depth, options) : "constructor" in value && constructorMap2.has(value.constructor) ? constructorMap2.get(value.constructor)(value, options) : stringTagMap2[type3] ? stringTagMap2[type3](value, options) : "", "inspectCustom"), toString3 = Object.prototype.toString;
function inspect2(value, opts = {}) {
let options = normaliseOptions2(opts, inspect2), { customInspect } = options, type3 = value === null ? "null" : typeof value;
if (type3 === "object" && (type3 = toString3.call(value).slice(8, -1)), type3 in baseTypesMap2)
return baseTypesMap2[type3](value, options);
if (customInspect && value) {
let output = inspectCustom2(value, options, type3, inspect2);
if (output)
return typeof output == "string" ? output : inspect2(output, options);
}
let proto = value ? Object.getPrototypeOf(value) : !1;
return proto === Object.prototype || proto === null ? inspectObject2(value, options) : value && typeof HTMLElement == "function" && value instanceof HTMLElement ? inspectHTML2(value, options) : "constructor" in value ? value.constructor !== Object ? inspectClass2(value, options) : inspectObject2(value, options) : value === Object(value) ? inspectObject2(value, options) : options.stylize(String(value), type3);
}
__name(inspect2, "inspect");
var config = {
/**
* ### config.includeStack
*
* User configurable property, influences whether stack trace
* is included in Assertion error message. Default of false
* suppresses stack trace in the error message.
*
* chai.config.includeStack = true; // enable stack on error
*
* @param {boolean}
* @public
*/
includeStack: !1,
/**
* ### config.showDiff
*
* User configurable property, influences whether or not
* the `showDiff` flag should be included in the thrown
* AssertionErrors. `false` will always be `false`; `true`
* will be true when the assertion has requested a diff
* be shown.
*
* @param {boolean}
* @public
*/
showDiff: !0,
/**
* ### config.truncateThreshold
*
* User configurable property, sets length threshold for actual and
* expected values in assertion errors. If this threshold is exceeded, for
* example for large data structures, the value is replaced with something
* like `[ Array(3) ]` or `{ Object (prop1, prop2) }`.
*
* Set it to zero if you want to disable truncating altogether.
*
* This is especially userful when doing assertions on arrays: having this
* set to a reasonable large value makes the failure messages readily
* inspectable.
*
* chai.config.truncateThreshold = 0; // disable truncating
*
* @param {number}
* @public
*/
truncateThreshold: 40,
/**
* ### config.useProxy
*
* User configurable property, defines if chai will use a Proxy to throw
* an error when a non-existent property is read, which protects users
* from typos when using property-based assertions.
*
* Set it to false if you want to disable this feature.
*
* chai.config.useProxy = false; // disable use of Proxy
*
* This feature is automatically disabled regardless of this config value
* in environments that don't support proxies.
*
* @param {boolean}
* @public
*/
useProxy: !0,
/**
* ### config.proxyExcludedKeys
*
* User configurable property, defines which properties should be ignored
* instead of throwing an error if they do not exist on the assertion.
* This is only applied if the environment Chai is running in supports proxies and
* if the `useProxy` configuration setting is enabled.
* By default, `then` and `inspect` will not throw an error if they do not exist on the
* assertion object because the `.inspect` property is read by `util.inspect` (for example, when
* using `console.log` on the assertion object) and `.then` is necessary for promise type-checking.
*
* // By default these keys will not throw an error if they do not exist on the assertion object
* chai.config.proxyExcludedKeys = ['then', 'inspect'];
*
* @param {Array}
* @public
*/
proxyExcludedKeys: ["then", "catch", "inspect", "toJSON"],
/**
* ### config.deepEqual
*
* User configurable property, defines which a custom function to use for deepEqual
* comparisons.
* By default, the function used is the one from the `deep-eql` package without custom comparator.
*
* // use a custom comparator
* chai.config.deepEqual = (expected, actual) => {
* return chai.util.eql(expected, actual, {
* comparator: (expected, actual) => {
* // for non number comparison, use the default behavior
* if(typeof expected !== 'number') return null;
* // allow a difference of 10 between compared numbers
* return typeof actual === 'number' && Math.abs(actual - expected) < 10
* }
* })
* };
*
* @param {Function}
* @public
*/
deepEqual: null
};
function inspect22(obj, showHidden, depth, colors) {
let options = {
colors,
depth: typeof depth > "u" ? 2 : depth,
showHidden,
truncate: config.truncateThreshold ? config.truncateThreshold : 1 / 0
};
return inspect2(obj, options);
}
__name(inspect22, "inspect");
function objDisplay2(obj) {
let str = inspect22(obj), type3 = Object.prototype.toString.call(obj);
if (config.truncateThreshold && str.length >= config.truncateThreshold) {
if (type3 === "[object Function]")
return !obj.name || obj.name === "" ? "[Function]" : "[Function: " + obj.name + "]";
if (type3 === "[object Array]")
return "[ Array(" + obj.length + ") ]";
if (type3 === "[object Object]") {
let keys2 = Object.keys(obj);
return "{ Object (" + (keys2.length > 2 ? keys2.splice(0, 2).join(", ") + ", ..." : keys2.join(", ")) + ") }";
} else
return str;
} else
return str;
}
__name(objDisplay2, "objDisplay");
function getMessage2(obj, args) {
let negate = flag(obj, "negate"), val = flag(obj, "object"), expected = args[3], actual = getActual(obj, args), msg = negate ? args[2] : args[1], flagMsg = flag(obj, "message");
return typeof msg == "function" && (msg = msg()), msg = msg || "", msg = msg.replace(/#\{this\}/g, function() {
return objDisplay2(val);
}).replace(/#\{act\}/g, function() {
return objDisplay2(actual);
}).replace(/#\{exp\}/g, function() {
return objDisplay2(expected);
}), flagMsg ? flagMsg + ": " + msg : msg;
}
__name(getMessage2, "getMessage");
function transferFlags(assertion, object2, includeAll) {
let flags = assertion.__flags || (assertion.__flags = /* @__PURE__ */ Object.create(null));
object2.__flags || (object2.__flags = /* @__PURE__ */ Object.create(null)), includeAll = arguments.length === 3 ? includeAll : !0;
for (let flag3 in flags)
(includeAll || flag3 !== "object" && flag3 !== "ssfi" && flag3 !== "lockSsfi" && flag3 != "message") && (object2.__flags[flag3] = flags[flag3]);
}
__name(transferFlags, "transferFlags");
function type2(obj) {
if (typeof obj > "u")
return "undefined";
if (obj === null)
return "null";
let stringTag = obj[Symbol.toStringTag];
return typeof stringTag == "string" ? stringTag : Object.prototype.toString.call(obj).slice(8, -1);
}
__name(type2, "type");
function FakeMap() {
this._key = "chai/deep-eql__" + Math.random() + Date.now();
}
__name(FakeMap, "FakeMap");
FakeMap.prototype = {
get: /* @__PURE__ */ __name(function(key) {
return key[this._key];
}, "get"),
set: /* @__PURE__ */ __name(function(key, value) {
Object.isExtensible(key) && Object.defineProperty(key, this._key, {
value,
configurable: !0
});
}, "set")
};
var MemoizeMap = typeof WeakMap == "function" ? WeakMap : FakeMap;
function memoizeCompare(leftHandOperand, rightHandOperand, memoizeMap) {
if (!memoizeMap || isPrimitive2(leftHandOperand) || isPrimitive2(rightHandOperand))
return null;
var leftHandMap = memoizeMap.get(leftHandOperand);
if (leftHandMap) {
var result = leftHandMap.get(rightHandOperand);
if (typeof result == "boolean")
return result;
}
return null;
}
__name(memoizeCompare, "memoizeCompare");
function memoizeSet(leftHandOperand, rightHandOperand, memoizeMap, result) {
if (!(!memoizeMap || isPrimitive2(leftHandOperand) || isPrimitive2(rightHandOperand))) {
var leftHandMap = memoizeMap.get(leftHandOperand);
leftHandMap ? leftHandMap.set(rightHandOperand, result) : (leftHandMap = new MemoizeMap(), leftHandMap.set(rightHandOperand, result), memoizeMap.set(leftHandOperand, leftHandMap));
}
}
__name(memoizeSet, "memoizeSet");
var deep_eql_default = deepEqual;
function deepEqual(leftHandOperand, rightHandOperand, options) {
if (options && options.comparator)
return extensiveDeepEqual(leftHandOperand, rightHandOperand, options);
var simpleResult = simpleEqual(leftHandOperand, rightHandOperand);
return simpleResult !== null ? simpleResult : extensiveDeepEqual(leftHandOperand, rightHandOperand, options);
}
__name(deepEqual, "deepEqual");
function simpleEqual(leftHandOperand, rightHandOperand) {
return leftHandOperand === rightHandOperand ? leftHandOperand !== 0 || 1 / leftHandOperand === 1 / rightHandOperand : leftHandOperand !== leftHandOperand && // eslint-disable-line no-self-compare
rightHandOperand !== rightHandOperand ? !0 : isPrimitive2(leftHandOperand) || isPrimitive2(rightHandOperand) ? !1 : null;
}
__name(simpleEqual, "simpleEqual");
function extensiveDeepEqual(leftHandOperand, rightHandOperand, options) {
options = options || {}, options.memoize = options.memoize === !1 ? !1 : options.memoize || new MemoizeMap();
var comparator = options && options.comparator, memoizeResultLeft = memoizeCompare(leftHandOperand, rightHandOperand, options.memoize);
if (memoizeResultLeft !== null)
return memoizeResultLeft;
var memoizeResultRight = memoizeCompare(rightHandOperand, leftHandOperand, options.memoize);
if (memoizeResultRight !== null)
return memoizeResultRight;
if (comparator) {
var comparatorResult = comparator(leftHandOperand, rightHandOperand);
if (comparatorResult === !1 || comparatorResult === !0)
return memoizeSet(leftHandOperand, rightHandOperand, options.memoize, comparatorResult), comparatorResult;
var simpleResult = simpleEqual(leftHandOperand, rightHandOperand);
if (simpleResult !== null)
return simpleResult;
}
var leftHandType = type2(leftHandOperand);
if (leftHandType !== type2(rightHandOperand))
return memoizeSet(leftHandOperand, rightHandOperand, options.memoize, !1), !1;
memoizeSet(leftHandOperand, rightHandOperand, options.memoize, !0);
var result = extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options);
return memoizeSet(leftHandOperand, rightHandOperand, options.memoize, result), result;
}
__name(extensiveDeepEqual, "extensiveDeepEqual");
function extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options) {
switch (leftHandType) {
case "String":
case "Number":
case "Boolean":
case "Date":
return deepEqual(leftHandOperand.valueOf(), rightHandOperand.valueOf());
case "Promise":
case "Symbol":
case "function":
case "WeakMap":
case "WeakSet":
return leftHandOperand === rightHandOperand;
case "Error":
return keysEqual(leftHandOperand, rightHandOperand, ["name", "message", "code"], options);
case "Arguments":
case "Int8Array":
case "Uint8Array":
case "Uint8ClampedArray":
case "Int16Array":
case "Uint16Array":
case "Int32Array":
case "Uint32Array":
case "Float32Array":
case "Float64Array":
case "Array":
return iterableEqual(leftHandOperand, rightHandOperand, options);
case "RegExp":
return regexpEqual(leftHandOperand, rightHandOperand);
case "Generator":
return generatorEqual(leftHandOperand, rightHandOperand, options);
case "DataView":
return iterableEqual(new Uint8Array(leftHandOperand.buffer), new Uint8Array(rightHandOperand.buffer), options);
case "ArrayBuffer":
return iterableEqual(new Uint8Array(leftHandOperand), new Uint8Array(rightHandOperand), options);
case "Set":
return entriesEqual(leftHandOperand, rightHandOperand, options);
case "Map":
return entriesEqual(leftHandOperand, rightHandOperand, options);
case "Temporal.PlainDate":
case "Temporal.PlainTime":
case "Temporal.PlainDateTime":
case "Temporal.Instant":
case "Temporal.ZonedDateTime":
case "Temporal.PlainYearMonth":
case "Temporal.PlainMonthDay":
return leftHandOperand.equals(rightHandOperand);
case "Temporal.Duration":
return leftHandOperand.total("nanoseconds") === rightHandOperand.total("nanoseconds");
case "Temporal.TimeZone":
case "Temporal.Calendar":
return leftHandOperand.toString() === rightHandOperand.toString();
default:
return objectEqual(leftHandOperand, rightHandOperand, options);
}
}
__name(extensiveDeepEqualByType, "extensiveDeepEqualByType");
function regexpEqual(leftHandOperand, rightHandOperand) {
return leftHandOperand.toString() === rightHandOperand.toString();
}
__name(regexpEqual, "regexpEqual");
function entriesEqual(leftHandOperand, rightHandOperand, options) {
try {
if (leftHandOperand.size !== rightHandOperand.size)
return !1;
if (leftHandOperand.size === 0)
return !0;
} catch {
return !1;
}
var leftHandItems = [], rightHandItems = [];
return leftHandOperand.forEach(/* @__PURE__ */ __name(function(key, value) {
leftHandItems.push([key, value]);
}, "gatherEntries")), rightHandOperand.forEach(/* @__PURE__ */ __name(function(key, value) {
rightHandItems.push([key, value]);
}, "gatherEntries")), iterableEqual(leftHandItems.sort(), rightHandItems.sort(), options);
}
__name(entriesEqual, "entriesEqual");
function iterableEqual(leftHandOperand, rightHandOperand, options) {
var length = leftHandOperand.length;
if (length !== rightHandOperand.length)
return !1;
if (length === 0)
return !0;
for (var index2 = -1; ++index2 < length; )
if (deepEqual(leftHandOperand[index2], rightHandOperand[index2], options) === !1)
return !1;
return !0;
}
__name(iterableEqual, "iterableEqual");
function generatorEqual(leftHandOperand, rightHandOperand, options) {
return iterableEqual(getGeneratorEntries(leftHandOperand), getGeneratorEntries(rightHandOperand), options);
}
__name(generatorEqual, "generatorEqual");
function hasIteratorFunction(target) {
return typeof Symbol < "u" && typeof target == "object" && typeof Symbol.iterator < "u" && typeof target[Symbol.iterator] == "function";
}
__name(hasIteratorFunction, "hasIteratorFunction");
function getIteratorEntries(target) {
if (hasIteratorFunction(target))
try {
return getGeneratorEntries(target[Symbol.iterator]());
} catch {
return [];
}
return [];
}
__name(getIteratorEntries, "getIteratorEntries");
function getGeneratorEntries(generator) {
for (var generatorResult = generator.next(), accumulator = [generatorResult.value]; generatorResult.done === !1; )
generatorResult = generator.next(), accumulator.push(generatorResult.value);
return accumulator;
}
__name(getGeneratorEntries, "getGeneratorEntries");
function getEnumerableKeys(target) {
var keys2 = [];
for (var key in target)
keys2.push(key);
return keys2;
}
__name(getEnumerableKeys, "getEnumerableKeys");
function getEnumerableSymbols(target) {
for (var keys2 = [], allKeys = Object.getOwnPropertySymbols(target), i2 = 0; i2 < allKeys.length; i2 += 1) {
var key = allKeys[i2];
Object.getOwnPropertyDescriptor(target, key).enumerable && keys2.push(key);
}
return keys2;
}
__name(getEnumerableSymbols, "getEnumerableSymbols");
function keysEqual(leftHandOperand, rightHandOperand, keys2, options) {
var length = keys2.length;
if (length === 0)
return !0;
for (var i2 = 0; i2 < length; i2 += 1)
if (deepEqual(leftHandOperand[keys2[i2]], rightHandOperand[keys2[i2]], options) === !1)
return !1;
return !0;
}
__name(keysEqual, "keysEqual");
function objectEqual(leftHandOperand, rightHandOperand, options) {
var leftHandKeys = getEnumerableKeys(leftHandOperand), rightHandKeys = getEnumerableKeys(rightHandOperand), leftHandSymbols = getEnumerableSymbols(leftHandOperand), rightHandSymbols = getEnumerableSymbols(rightHandOperand);
if (leftHandKeys = leftHandKeys.concat(leftHandSymbols), rightHandKeys = rightHandKeys.concat(rightHandSymbols), leftHandKeys.length && leftHandKeys.length === rightHandKeys.length)
return iterableEqual(mapSymbols(leftHandKeys).sort(), mapSymbols(rightHandKeys).sort()) === !1 ? !1 : keysEqual(leftHandOperand, rightHandOperand, leftHandKeys, options);
var leftHandEntries = getIteratorEntries(leftHandOperand), rightHandEntries = getIteratorEntries(rightHandOperand);
return leftHandEntries.length && leftHandEntries.length === rightHandEntries.length ? (leftHandEntries.sort(), rightHandEntries.sort(), iterableEqual(leftHandEntries, rightHandEntries, options)) : leftHandKeys.length === 0 && leftHandEntries.length === 0 && rightHandKeys.length === 0 && rightHandEntries.length === 0;
}
__name(objectEqual, "objectEqual");
function isPrimitive2(value) {
return value === null || typeof value != "object";
}
__name(isPrimitive2, "isPrimitive");
function mapSymbols(arr) {
return arr.map(/* @__PURE__ */ __name(function(entry) {
return typeof entry == "symbol" ? entry.toString() : entry;
}, "mapSymbol"));
}
__name(mapSymbols, "mapSymbols");
function hasProperty(obj, name) {
return typeof obj > "u" || obj === null ? !1 : name in Object(obj);
}
__name(hasProperty, "hasProperty");
function parsePath(path) {
return path.replace(/([^\\])\[/g, "$1.[").match(/(\\\.|[^.]+?)+/g).map((value) => {
if (value === "constructor" || value === "__proto__" || value === "prototype")
return {};
let mArr = /^\[(\d+)\]$/.exec(value), parsed = null;
return mArr ? parsed = { i: parseFloat(mArr[1]) } : parsed = { p: value.replace(/\\([.[\]])/g, "$1") }, parsed;
});
}
__name(parsePath, "parsePath");
function internalGetPathValue(obj, parsed, pathDepth) {
let temporaryValue = obj, res = null;
pathDepth = typeof pathDepth > "u" ? parsed.length : pathDepth;
for (let i2 = 0; i2 < pathDepth; i2++) {
let part = parsed[i2];
temporaryValue && (typeof part.p > "u" ? temporaryValue = temporaryValue[part.i] : temporaryValue = temporaryValue[part.p], i2 === pathDepth - 1 && (res = temporaryValue));
}
return res;
}
__name(internalGetPathValue, "internalGetPathValue");
function getPathInfo(obj, path) {
let parsed = parsePath(path), last = parsed[parsed.length - 1], info = {
parent: parsed.length > 1 ? internalGetPathValue(obj, parsed, parsed.length - 1) : obj,
name: last.p || last.i,
value: internalGetPathValue(obj, parsed)
};
return info.exists = hasProperty(info.parent, info.name), info;
}
__name(getPathInfo, "getPathInfo");
var _Assertion = class _Assertion2 {
/**
* Creates object for chaining.
* `Assertion` objects contain metadata in the form of flags. Three flags can
* be assigned during instantiation by passing arguments to this constructor:
*
* - `object`: This flag contains the target of the assertion. For example, in
* the assertion `expect(numKittens).to.equal(7);`, the `object` flag will
* contain `numKittens` so that the `equal` assertion can reference it when
* needed.
*
* - `message`: This flag contains an optional custom error message to be
* prepended to the error message that's generated by the assertion when it
* fails.
*
* - `ssfi`: This flag stands for "start stack function indicator". It
* contains a function reference that serves as the starting point for
* removing frames from the stack trace of the error that's created by the
* assertion when it fails. The goal is to provide a cleaner stack trace to
* end users by removing Chai's internal functions. Note that it only works
* in environments that support `Error.captureStackTrace`, and only when
* `Chai.config.includeStack` hasn't been set to `false`.
*
* - `lockSsfi`: This flag controls whether or not the given `ssfi` flag
* should retain its current value, even as assertions are chained off of
* this object. This is usually set to `true` when creating a new assertion
* from within another assertion. It's also temporarily set to `true` before
* an overwritten assertion gets called by the overwriting assertion.
*
* - `eql`: This flag contains the deepEqual function to be used by the assertion.
*
* @param {unknown} obj target of the assertion
* @param {string} [msg] (optional) custom error message
* @param {Function} [ssfi] (optional) starting point for removing stack frames
* @param {boolean} [lockSsfi] (optional) whether or not the ssfi flag is locked
*/
constructor(obj, msg, ssfi, lockSsfi) {
return __publicField(this, "__flags", {}), flag(this, "ssfi", ssfi || _Assertion2), flag(this, "lockSsfi", lockSsfi), flag(this, "object", obj), flag(this, "message", msg), flag(this, "eql", config.deepEqual || deep_eql_default), proxify(this);
}
/** @returns {boolean} */
static get includeStack() {
return console.warn(
"Assertion.includeStack is deprecated, use chai.config.includeStack instead."
), config.includeStack;
}
/** @param {boolean} value */
static set includeStack(value) {
console.warn(
"Assertion.includeStack is deprecated, use chai.config.includeStack instead."
), config.includeStack = value;
}
/** @returns {boolean} */
static get showDiff() {
return console.warn(
"Assertion.showDiff is deprecated, use chai.config.showDiff instead."
), config.showDiff;
}
/** @param {boolean} value */
static set showDiff(value) {
console.warn(
"Assertion.showDiff is deprecated, use chai.config.showDiff instead."
), config.showDiff = value;
}
/**
* @param {string} name
* @param {Function} fn
*/
static addProperty(name, fn2) {
addProperty(this.prototype, name, fn2);
}
/**
* @param {string} name
* @param {Function} fn
*/
static addMethod(name, fn2) {
addMethod(this.prototype, name, fn2);
}
/**
* @param {string} name
* @param {Function} fn
* @param {Function} chainingBehavior
*/
static addChainableMethod(name, fn2, chainingBehavior) {
addChainableMethod(this.prototype, name, fn2, chainingBehavior);
}
/**
* @param {string} name
* @param {Function} fn
*/
static overwriteProperty(name, fn2) {
overwriteProperty(this.prototype, name, fn2);
}
/**
* @param {string} name
* @param {Function} fn
*/
static overwriteMethod(name, fn2) {
overwriteMethod(this.prototype, name, fn2);
}
/**
* @param {string} name
* @param {Function} fn
* @param {Function} chainingBehavior
*/
static overwriteChainableMethod(name, fn2, chainingBehavior) {
overwriteChainableMethod(this.prototype, name, fn2, chainingBehavior);
}
/**
* ### .assert(expression, message, negateMessage, expected, actual, showDiff)
*
* Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass.
*
* @name assert
* @param {unknown} _expr to be tested
* @param {string | Function} msg or function that returns message to display if expression fails
* @param {string | Function} _negateMsg or function that returns negatedMessage to display if negated expression fails
* @param {unknown} expected value (remember to check for negation)
* @param {unknown} _actual (optional) will default to `this.obj`
* @param {boolean} showDiff (optional) when set to `true`, assert will display a diff in addition to the message if expression fails
* @returns {void}
*/
assert(_expr, msg, _negateMsg, expected, _actual, showDiff) {
let ok = test3(this, arguments);
if (showDiff !== !1 && (showDiff = !0), expected === void 0 && _actual === void 0 && (showDiff = !1), config.showDiff !== !0 && (showDiff = !1), !ok) {
msg = getMessage2(this, arguments);
let assertionErrorObjectProperties = {
actual: getActual(this, arguments),
expected,
showDiff
}, operator = getOperator(this, arguments);
throw operator && (assertionErrorObjectProperties.operator = operator), new AssertionError(
msg,
assertionErrorObjectProperties,
// @ts-expect-error Not sure what to do about these types yet
config.includeStack ? this.assert : flag(this, "ssfi")
);
}
}
/**
* Quick reference to stored `actual` value for plugin developers.
*
* @returns {unknown}
*/
get _obj() {
return flag(this, "object");
}
/**
* Quick reference to stored `actual` value for plugin developers.
*
* @param {unknown} val
*/
set _obj(val) {
flag(this, "object", val);
}
};
__name(_Assertion, "Assertion");
var Assertion = _Assertion, events = new EventTarget(), _PluginEvent = class extends Event {
constructor(type3, name, fn2) {
super(type3), this.name = String(name), this.fn = fn2;
}
};
__name(_PluginEvent, "PluginEvent");
var PluginEvent = _PluginEvent;
function isProxyEnabled() {
return config.useProxy && typeof Proxy < "u" && typeof Reflect < "u";
}
__name(isProxyEnabled, "isProxyEnabled");
function addProperty(ctx, name, getter) {
getter = getter === void 0 ? function() {
} : getter, Object.defineProperty(ctx, name, {
get: /* @__PURE__ */ __name(function propertyGetter() {
!isProxyEnabled() && !flag(this, "lockSsfi") && flag(this, "ssfi", propertyGetter);
let result = getter.call(this);
if (result !== void 0) return result;
let newAssertion = new Assertion();
return transferFlags(this, newAssertion), newAssertion;
}, "propertyGetter"),
configurable: !0
}), events.dispatchEvent(new PluginEvent("addProperty", name, getter));
}
__name(addProperty, "addProperty");
var fnLengthDesc = Object.getOwnPropertyDescriptor(function() {
}, "length");
function addLengthGuard(fn2, assertionName, isChainable) {
return fnLengthDesc.configurable && Object.defineProperty(fn2, "length", {
get: /* @__PURE__ */ __name(function() {
throw Error(
isChainable ? "Invalid Chai property: " + assertionName + '.length. Due to a compatibility issue, "length" cannot directly follow "' + assertionName + '". Use "' + assertionName + '.lengthOf" instead.' : "Invalid Chai property: " + assertionName + '.length. See docs for proper usage of "' + assertionName + '".'
);
}, "get")
}), fn2;
}
__name(addLengthGuard, "addLengthGuard");
function getProperties(object2) {
let result = Object.getOwnPropertyNames(object2);
function addProperty2(property) {
result.indexOf(property) === -1 && result.push(property);
}
__name(addProperty2, "addProperty");
let proto = Object.getPrototypeOf(object2);
for (; proto !== null; )
Object.getOwnPropertyNames(proto).forEach(addProperty2), proto = Object.getPrototypeOf(proto);
return result;
}
__name(getProperties, "getProperties");
var builtins = ["__flags", "__methods", "_obj", "assert"];
function proxify(obj, nonChainableMethodName) {
return isProxyEnabled() ? new Proxy(obj, {
get: /* @__PURE__ */ __name(function proxyGetter(target, property) {
if (typeof property == "string" && config.proxyExcludedKeys.indexOf(property) === -1 && !Reflect.has(target, property)) {
if (nonChainableMethodName)
throw Error(
"Invalid Chai property: " + nonChainableMethodName + "." + property + '. See docs for proper usage of "' + nonChainableMethodName + '".'
);
let suggestion = null, suggestionDistance = 4;
throw getProperties(target).forEach(function(prop) {
if (
// we actually mean to check `Object.prototype` here
// eslint-disable-next-line no-prototype-builtins
!Object.prototype.hasOwnProperty(prop) && builtins.indexOf(prop) === -1
) {
let dist = stringDistanceCapped(property, prop, suggestionDistance);
dist < suggestionDistance && (suggestion = prop, suggestionDistance = dist);
}
}), Error(
suggestion !== null ? "Invalid Chai property: " + property + '. Did you mean "' + suggestion + '"?' : "Invalid Chai property: " + property
);
}
return builtins.indexOf(property) === -1 && !flag(target, "lockSsfi") && flag(target, "ssfi", proxyGetter), Reflect.get(target, property);
}, "proxyGetter")
}) : obj;
}
__name(proxify, "proxify");
function stringDistanceCapped(strA, strB, cap) {
if (Math.abs(strA.length - strB.length) >= cap)
return cap;
let memo2 = [];
for (let i2 = 0; i2 <= strA.length; i2++)
memo2[i2] = Array(strB.length + 1).fill(0), memo2[i2][0] = i2;
for (let j = 0; j < strB.length; j++)
memo2[0][j] = j;
for (let i2 = 1; i2 <= strA.length; i2++) {
let ch = strA.charCodeAt(i2 - 1);
for (let j = 1; j <= strB.length; j++) {
if (Math.abs(i2 - j) >= cap) {
memo2[i2][j] = cap;
continue;
}
memo2[i2][j] = Math.min(
memo2[i2 - 1][j] + 1,
memo2[i2][j - 1] + 1,
memo2[i2 - 1][j - 1] + (ch === strB.charCodeAt(j - 1) ? 0 : 1)
);
}
}
return memo2[strA.length][strB.length];
}
__name(stringDistanceCapped, "stringDistanceCapped");
function addMethod(ctx, name, method) {
let methodWrapper = /* @__PURE__ */ __name(function() {
flag(this, "lockSsfi") || flag(this, "ssfi", methodWrapper);
let result = method.apply(this, arguments);
if (result !== void 0) return result;
let newAssertion = new Assertion();
return transferFlags(this, newAssertion), newAssertion;
}, "methodWrapper");
addLengthGuard(methodWrapper, name, !1), ctx[name] = proxify(methodWrapper, name), events.dispatchEvent(new PluginEvent("addMethod", name, method));
}
__name(addMethod, "addMethod");
function overwriteProperty(ctx, name, getter) {
let _get = Object.getOwnPropertyDescriptor(ctx, name), _super = /* @__PURE__ */ __name(function() {
}, "_super");
_get && typeof _get.get == "function" && (_super = _get.get), Object.defineProperty(ctx, name, {
get: /* @__PURE__ */ __name(function overwritingPropertyGetter() {
!isProxyEnabled() && !flag(this, "lockSsfi") && flag(this, "ssfi", overwritingPropertyGetter);
let origLockSsfi = flag(this, "lockSsfi");
flag(this, "lockSsfi", !0);
let result = getter(_super).call(this);
if (flag(this, "lockSsfi", origLockSsfi), result !== void 0)
return result;
let newAssertion = new Assertion();
return transferFlags(this, newAssertion), newAssertion;
}, "overwritingPropertyGetter"),
configurable: !0
});
}
__name(overwriteProperty, "overwriteProperty");
function overwriteMethod(ctx, name, method) {
let _method = ctx[name], _super = /* @__PURE__ */ __name(function() {
throw new Error(name + " is not a function");
}, "_super");
_method && typeof _method == "function" && (_super = _method);
let overwritingMethodWrapper = /* @__PURE__ */ __name(function() {
flag(this, "lockSsfi") || flag(this, "ssfi", overwritingMethodWrapper);
let origLockSsfi = flag(this, "lockSsfi");
flag(this, "lockSsfi", !0);
let result = method(_super).apply(this, arguments);
if (flag(this, "lockSsfi", origLockSsfi), result !== void 0)
return result;
let newAssertion = new Assertion();
return transferFlags(this, newAssertion), newAssertion;
}, "overwritingMethodWrapper");
addLengthGuard(overwritingMethodWrapper, name, !1), ctx[name] = proxify(overwritingMethodWrapper, name);
}
__name(overwriteMethod, "overwriteMethod");
var canSetPrototype = typeof Object.setPrototypeOf == "function", testFn = /* @__PURE__ */ __name(function() {
}, "testFn"), excludeNames = Object.getOwnPropertyNames(testFn).filter(function(name) {
let propDesc = Object.getOwnPropertyDescriptor(testFn, name);
return typeof propDesc != "object" ? !0 : !propDesc.configurable;
}), call = Function.prototype.call, apply = Function.prototype.apply, _PluginAddChainableMethodEvent = class extends PluginEvent {
constructor(type3, name, fn2, chainingBehavior) {
super(type3, name, fn2), this.chainingBehavior = chainingBehavior;
}
};
__name(_PluginAddChainableMethodEvent, "PluginAddChainableMethodEvent");
var PluginAddChainableMethodEvent = _PluginAddChainableMethodEvent;
function addChainableMethod(ctx, name, method, chainingBehavior) {
typeof chainingBehavior != "function" && (chainingBehavior = /* @__PURE__ */ __name(function() {
}, "chainingBehavior"));
let chainableBehavior = {
method,
chainingBehavior
};
ctx.__methods || (ctx.__methods = {}), ctx.__methods[name] = chainableBehavior, Object.defineProperty(ctx, name, {
get: /* @__PURE__ */ __name(function() {
chainableBehavior.chainingBehavior.call(this);
let chainableMethodWrapper = /* @__PURE__ */ __name(function() {
flag(this, "lockSsfi") || flag(this, "ssfi", chainableMethodWrapper);
let result = chainableBehavior.method.apply(this, arguments);
if (result !== void 0)
return result;
let newAssertion = new Assertion();
return transferFlags(this, newAssertion), newAssertion;
}, "chainableMethodWrapper");
if (addLengthGuard(chainableMethodWrapper, name, !0), canSetPrototype) {
let prototype = Object.create(this);
prototype.call = call, prototype.apply = apply, Object.setPrototypeOf(chainableMethodWrapper, prototype);
} else
Object.getOwnPropertyNames(ctx).forEach(function(asserterName) {
if (excludeNames.indexOf(asserterName) !== -1)
return;
let pd = Object.getOwnPropertyDescriptor(ctx, asserterName);
Object.defineProperty(chainableMethodWrapper, asserterName, pd);
});
return transferFlags(this, chainableMethodWrapper), proxify(chainableMethodWrapper);
}, "chainableMethodGetter"),
configurable: !0
}), events.dispatchEvent(
new PluginAddChainableMethodEvent(
"addChainableMethod",
name,
method,
chainingBehavior
)
);
}
__name(addChainableMethod, "addChainableMethod");
function overwriteChainableMethod(ctx, name, method, chainingBehavior) {
let chainableBehavior = ctx.__methods[name], _chainingBehavior = chainableBehavior.chainingBehavior;
chainableBehavior.chainingBehavior = /* @__PURE__ */ __name(function() {
let result = chainingBehavior(_chainingBehavior).call(this);
if (result !== void 0)
return result;
let newAssertion = new Assertion();
return transferFlags(this, newAssertion), newAssertion;
}, "overwritingChainableMethodGetter");
let _method = chainableBehavior.method;
chainableBehavior.method = /* @__PURE__ */ __name(function() {
let result = method(_method).apply(this, arguments);
if (result !== void 0)
return result;
let newAssertion = new Assertion();
return transferFlags(this, newAssertion), newAssertion;
}, "overwritingChainableMethodWrapper");
}
__name(overwriteChainableMethod, "overwriteChainableMethod");
function compareByInspect(a, b2) {
return inspect22(a) < inspect22(b2) ? -1 : 1;
}
__name(compareByInspect, "compareByInspect");
function getOwnEnumerablePropertySymbols(obj) {
return typeof Object.getOwnPropertySymbols != "function" ? [] : Object.getOwnPropertySymbols(obj).filter(function(sym) {
return Object.getOwnPropertyDescriptor(obj, sym).enumerable;
});
}
__name(getOwnEnumerablePropertySymbols, "getOwnEnumerablePropertySymbols");
function getOwnEnumerableProperties(obj) {
return Object.keys(obj).concat(getOwnEnumerablePropertySymbols(obj));
}
__name(getOwnEnumerableProperties, "getOwnEnumerableProperties");
var isNaN22 = Number.isNaN;
function isObjectType(obj) {
let objectType = type(obj);
return ["Array", "Object", "Function"].indexOf(objectType) !== -1;
}
__name(isObjectType, "isObjectType");
function getOperator(obj, args) {
let operator = flag(obj, "operator"), negate = flag(obj, "negate"), expected = args[3], msg = negate ? args[2] : args[1];
if (operator)
return operator;
if (typeof msg == "function" && (msg = msg()), msg = msg || "", !msg || /\shave\s/.test(msg))
return;
let isObject2 = isObjectType(expected);
return /\snot\s/.test(msg) ? isObject2 ? "notDeepStrictEqual" : "notStrictEqual" : isObject2 ? "deepStrictEqual" : "strictEqual";
}
__name(getOperator, "getOperator");
function getName(fn2) {
return fn2.name;
}
__name(getName, "getName");
function isRegExp2(obj) {
return Object.prototype.toString.call(obj) === "[object RegExp]";
}
__name(isRegExp2, "isRegExp");
function isNumeric(obj) {
return ["Number", "BigInt"].includes(type(obj));
}
__name(isNumeric, "isNumeric");
var { flag: flag2 } = utils_exports;
[
"to",
"be",
"been",
"is",
"and",
"has",
"have",
"with",
"that",
"which",
"at",
"of",
"same",
"but",
"does",
"still",
"also"
].forEach(function(chain) {
Assertion.addProperty(chain);
});
Assertion.addProperty("not", function() {
flag2(this, "negate", !0);
});
Assertion.addProperty("deep", function() {
flag2(this, "deep", !0);
});
Assertion.addProperty("nested", function() {
flag2(this, "nested", !0);
});
Assertion.addProperty("own", function() {
flag2(this, "own", !0);
});
Assertion.addProperty("ordered", function() {
flag2(this, "ordered", !0);
});
Assertion.addProperty("any", function() {
flag2(this, "any", !0), flag2(this, "all", !1);
});
Assertion.addProperty("all", function() {
flag2(this, "all", !0), flag2(this, "any", !1);
});
var functionTypes = {
function: [
"function",
"asyncfunction",
"generatorfunction",
"asyncgeneratorfunction"
],
asyncfunction: ["asyncfunction", "asyncgeneratorfunction"],
generatorfunction: ["generatorfunction", "asyncgeneratorfunction"],
asyncgeneratorfunction: ["asyncgeneratorfunction"]
};
function an(type3, msg) {
msg && flag2(this, "message", msg), type3 = type3.toLowerCase();
let obj = flag2(this, "object"), article = ~["a", "e", "i", "o", "u"].indexOf(type3.charAt(0)) ? "an " : "a ", detectedType = type(obj).toLowerCase();
functionTypes.function.includes(type3) ? this.assert(
functionTypes[type3].includes(detectedType),
"expected #{this} to be " + article + type3,
"expected #{this} not to be " + article + type3
) : this.assert(
type3 === detectedType,
"expected #{this} to be " + article + type3,
"expected #{this} not to be " + article + type3
);
}
__name(an, "an");
Assertion.addChainableMethod("an", an);
Assertion.addChainableMethod("a", an);
function SameValueZero(a, b2) {
return isNaN22(a) && isNaN22(b2) || a === b2;
}
__name(SameValueZero, "SameValueZero");
function includeChainingBehavior() {
flag2(this, "contains", !0);
}
__name(includeChainingBehavior, "includeChainingBehavior");
function include(val, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object"), objType = type(obj).toLowerCase(), flagMsg = flag2(this, "message"), negate = flag2(this, "negate"), ssfi = flag2(this, "ssfi"), isDeep = flag2(this, "deep"), descriptor = isDeep ? "deep " : "", isEql = isDeep ? flag2(this, "eql") : SameValueZero;
flagMsg = flagMsg ? flagMsg + ": " : "";
let included = !1;
switch (objType) {
case "string":
included = obj.indexOf(val) !== -1;
break;
case "weakset":
if (isDeep)
throw new AssertionError(
flagMsg + "unable to use .deep.include with WeakSet",
void 0,
ssfi
);
included = obj.has(val);
break;
case "map":
obj.forEach(function(item) {
included = included || isEql(item, val);
});
break;
case "set":
isDeep ? obj.forEach(function(item) {
included = included || isEql(item, val);
}) : included = obj.has(val);
break;
case "array":
isDeep ? included = obj.some(function(item) {
return isEql(item, val);
}) : included = obj.indexOf(val) !== -1;
break;
default: {
if (val !== Object(val))
throw new AssertionError(
flagMsg + "the given combination of arguments (" + objType + " and " + type(val).toLowerCase() + ") is invalid for this assertion. You can use an array, a map, an object, a set, a string, or a weakset instead of a " + type(val).toLowerCase(),
void 0,
ssfi
);
let props = Object.keys(val), firstErr = null, numErrs = 0;
if (props.forEach(function(prop) {
let propAssertion = new Assertion(obj);
if (transferFlags(this, propAssertion, !0), flag2(propAssertion, "lockSsfi", !0), !negate || props.length === 1) {
propAssertion.property(prop, val[prop]);
return;
}
try {
propAssertion.property(prop, val[prop]);
} catch (err) {
if (!check_error_exports.compatibleConstructor(err, AssertionError))
throw err;
firstErr === null && (firstErr = err), numErrs++;
}
}, this), negate && props.length > 1 && numErrs === props.length)
throw firstErr;
return;
}
}
this.assert(
included,
"expected #{this} to " + descriptor + "include " + inspect22(val),
"expected #{this} to not " + descriptor + "include " + inspect22(val)
);
}
__name(include, "include");
Assertion.addChainableMethod("include", include, includeChainingBehavior);
Assertion.addChainableMethod("contain", include, includeChainingBehavior);
Assertion.addChainableMethod("contains", include, includeChainingBehavior);
Assertion.addChainableMethod("includes", include, includeChainingBehavior);
Assertion.addProperty("ok", function() {
this.assert(
flag2(this, "object"),
"expected #{this} to be truthy",
"expected #{this} to be falsy"
);
});
Assertion.addProperty("true", function() {
this.assert(
flag2(this, "object") === !0,
"expected #{this} to be true",
"expected #{this} to be false",
!flag2(this, "negate")
);
});
Assertion.addProperty("numeric", function() {
let object2 = flag2(this, "object");
this.assert(
["Number", "BigInt"].includes(type(object2)),
"expected #{this} to be numeric",
"expected #{this} to not be numeric",
!flag2(this, "negate")
);
});
Assertion.addProperty("callable", function() {
let val = flag2(this, "object"), ssfi = flag2(this, "ssfi"), message = flag2(this, "message"), msg = message ? `${message}: ` : "", negate = flag2(this, "negate"), assertionMessage = negate ? `${msg}expected ${inspect22(val)} not to be a callable function` : `${msg}expected ${inspect22(val)} to be a callable function`, isCallable = [
"Function",
"AsyncFunction",
"GeneratorFunction",
"AsyncGeneratorFunction"
].includes(type(val));
if (isCallable && negate || !isCallable && !negate)
throw new AssertionError(assertionMessage, void 0, ssfi);
});
Assertion.addProperty("false", function() {
this.assert(
flag2(this, "object") === !1,
"expected #{this} to be false",
"expected #{this} to be true",
!!flag2(this, "negate")
);
});
Assertion.addProperty("null", function() {
this.assert(
flag2(this, "object") === null,
"expected #{this} to be null",
"expected #{this} not to be null"
);
});
Assertion.addProperty("undefined", function() {
this.assert(
flag2(this, "object") === void 0,
"expected #{this} to be undefined",
"expected #{this} not to be undefined"
);
});
Assertion.addProperty("NaN", function() {
this.assert(
isNaN22(flag2(this, "object")),
"expected #{this} to be NaN",
"expected #{this} not to be NaN"
);
});
function assertExist() {
let val = flag2(this, "object");
this.assert(
val != null,
"expected #{this} to exist",
"expected #{this} to not exist"
);
}
__name(assertExist, "assertExist");
Assertion.addProperty("exist", assertExist);
Assertion.addProperty("exists", assertExist);
Assertion.addProperty("empty", function() {
let val = flag2(this, "object"), ssfi = flag2(this, "ssfi"), flagMsg = flag2(this, "message"), itemsCount;
switch (flagMsg = flagMsg ? flagMsg + ": " : "", type(val).toLowerCase()) {
case "array":
case "string":
itemsCount = val.length;
break;
case "map":
case "set":
itemsCount = val.size;
break;
case "weakmap":
case "weakset":
throw new AssertionError(
flagMsg + ".empty was passed a weak collection",
void 0,
ssfi
);
case "function": {
let msg = flagMsg + ".empty was passed a function " + getName(val);
throw new AssertionError(msg.trim(), void 0, ssfi);
}
default:
if (val !== Object(val))
throw new AssertionError(
flagMsg + ".empty was passed non-string primitive " + inspect22(val),
void 0,
ssfi
);
itemsCount = Object.keys(val).length;
}
this.assert(
itemsCount === 0,
"expected #{this} to be empty",
"expected #{this} not to be empty"
);
});
function checkArguments() {
let obj = flag2(this, "object"), type3 = type(obj);
this.assert(
type3 === "Arguments",
"expected #{this} to be arguments but got " + type3,
"expected #{this} to not be arguments"
);
}
__name(checkArguments, "checkArguments");
Assertion.addProperty("arguments", checkArguments);
Assertion.addProperty("Arguments", checkArguments);
function assertEqual(val, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object");
if (flag2(this, "deep")) {
let prevLockSsfi = flag2(this, "lockSsfi");
flag2(this, "lockSsfi", !0), this.eql(val), flag2(this, "lockSsfi", prevLockSsfi);
} else
this.assert(
val === obj,
"expected #{this} to equal #{exp}",
"expected #{this} to not equal #{exp}",
val,
this._obj,
!0
);
}
__name(assertEqual, "assertEqual");
Assertion.addMethod("equal", assertEqual);
Assertion.addMethod("equals", assertEqual);
Assertion.addMethod("eq", assertEqual);
function assertEql(obj, msg) {
msg && flag2(this, "message", msg);
let eql = flag2(this, "eql");
this.assert(
eql(obj, flag2(this, "object")),
"expected #{this} to deeply equal #{exp}",
"expected #{this} to not deeply equal #{exp}",
obj,
this._obj,
!0
);
}
__name(assertEql, "assertEql");
Assertion.addMethod("eql", assertEql);
Assertion.addMethod("eqls", assertEql);
function assertAbove(n, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase();
if (doLength && objType !== "map" && objType !== "set" && new Assertion(obj, flagMsg, ssfi, !0).to.have.property("length"), !doLength && objType === "date" && nType !== "date")
throw new AssertionError(
msgPrefix + "the argument to above must be a date",
void 0,
ssfi
);
if (!isNumeric(n) && (doLength || isNumeric(obj)))
throw new AssertionError(
msgPrefix + "the argument to above must be a number",
void 0,
ssfi
);
if (!doLength && objType !== "date" && !isNumeric(obj)) {
let printObj = objType === "string" ? "'" + obj + "'" : obj;
throw new AssertionError(
msgPrefix + "expected " + printObj + " to be a number or a date",
void 0,
ssfi
);
}
if (doLength) {
let descriptor = "length", itemsCount;
objType === "map" || objType === "set" ? (descriptor = "size", itemsCount = obj.size) : itemsCount = obj.length, this.assert(
itemsCount > n,
"expected #{this} to have a " + descriptor + " above #{exp} but got #{act}",
"expected #{this} to not have a " + descriptor + " above #{exp}",
n,
itemsCount
);
} else
this.assert(
obj > n,
"expected #{this} to be above #{exp}",
"expected #{this} to be at most #{exp}",
n
);
}
__name(assertAbove, "assertAbove");
Assertion.addMethod("above", assertAbove);
Assertion.addMethod("gt", assertAbove);
Assertion.addMethod("greaterThan", assertAbove);
function assertLeast(n, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(), errorMessage, shouldThrow = !0;
if (doLength && objType !== "map" && objType !== "set" && new Assertion(obj, flagMsg, ssfi, !0).to.have.property("length"), !doLength && objType === "date" && nType !== "date")
errorMessage = msgPrefix + "the argument to least must be a date";
else if (!isNumeric(n) && (doLength || isNumeric(obj)))
errorMessage = msgPrefix + "the argument to least must be a number";
else if (!doLength && objType !== "date" && !isNumeric(obj)) {
let printObj = objType === "string" ? "'" + obj + "'" : obj;
errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date";
} else
shouldThrow = !1;
if (shouldThrow)
throw new AssertionError(errorMessage, void 0, ssfi);
if (doLength) {
let descriptor = "length", itemsCount;
objType === "map" || objType === "set" ? (descriptor = "size", itemsCount = obj.size) : itemsCount = obj.length, this.assert(
itemsCount >= n,
"expected #{this} to have a " + descriptor + " at least #{exp} but got #{act}",
"expected #{this} to have a " + descriptor + " below #{exp}",
n,
itemsCount
);
} else
this.assert(
obj >= n,
"expected #{this} to be at least #{exp}",
"expected #{this} to be below #{exp}",
n
);
}
__name(assertLeast, "assertLeast");
Assertion.addMethod("least", assertLeast);
Assertion.addMethod("gte", assertLeast);
Assertion.addMethod("greaterThanOrEqual", assertLeast);
function assertBelow(n, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(), errorMessage, shouldThrow = !0;
if (doLength && objType !== "map" && objType !== "set" && new Assertion(obj, flagMsg, ssfi, !0).to.have.property("length"), !doLength && objType === "date" && nType !== "date")
errorMessage = msgPrefix + "the argument to below must be a date";
else if (!isNumeric(n) && (doLength || isNumeric(obj)))
errorMessage = msgPrefix + "the argument to below must be a number";
else if (!doLength && objType !== "date" && !isNumeric(obj)) {
let printObj = objType === "string" ? "'" + obj + "'" : obj;
errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date";
} else
shouldThrow = !1;
if (shouldThrow)
throw new AssertionError(errorMessage, void 0, ssfi);
if (doLength) {
let descriptor = "length", itemsCount;
objType === "map" || objType === "set" ? (descriptor = "size", itemsCount = obj.size) : itemsCount = obj.length, this.assert(
itemsCount < n,
"expected #{this} to have a " + descriptor + " below #{exp} but got #{act}",
"expected #{this} to not have a " + descriptor + " below #{exp}",
n,
itemsCount
);
} else
this.assert(
obj < n,
"expected #{this} to be below #{exp}",
"expected #{this} to be at least #{exp}",
n
);
}
__name(assertBelow, "assertBelow");
Assertion.addMethod("below", assertBelow);
Assertion.addMethod("lt", assertBelow);
Assertion.addMethod("lessThan", assertBelow);
function assertMost(n, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(), errorMessage, shouldThrow = !0;
if (doLength && objType !== "map" && objType !== "set" && new Assertion(obj, flagMsg, ssfi, !0).to.have.property("length"), !doLength && objType === "date" && nType !== "date")
errorMessage = msgPrefix + "the argument to most must be a date";
else if (!isNumeric(n) && (doLength || isNumeric(obj)))
errorMessage = msgPrefix + "the argument to most must be a number";
else if (!doLength && objType !== "date" && !isNumeric(obj)) {
let printObj = objType === "string" ? "'" + obj + "'" : obj;
errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date";
} else
shouldThrow = !1;
if (shouldThrow)
throw new AssertionError(errorMessage, void 0, ssfi);
if (doLength) {
let descriptor = "length", itemsCount;
objType === "map" || objType === "set" ? (descriptor = "size", itemsCount = obj.size) : itemsCount = obj.length, this.assert(
itemsCount <= n,
"expected #{this} to have a " + descriptor + " at most #{exp} but got #{act}",
"expected #{this} to have a " + descriptor + " above #{exp}",
n,
itemsCount
);
} else
this.assert(
obj <= n,
"expected #{this} to be at most #{exp}",
"expected #{this} to be above #{exp}",
n
);
}
__name(assertMost, "assertMost");
Assertion.addMethod("most", assertMost);
Assertion.addMethod("lte", assertMost);
Assertion.addMethod("lessThanOrEqual", assertMost);
Assertion.addMethod("within", function(start, finish, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), startType = type(start).toLowerCase(), finishType = type(finish).toLowerCase(), errorMessage, shouldThrow = !0, range = startType === "date" && finishType === "date" ? start.toISOString() + ".." + finish.toISOString() : start + ".." + finish;
if (doLength && objType !== "map" && objType !== "set" && new Assertion(obj, flagMsg, ssfi, !0).to.have.property("length"), !doLength && objType === "date" && (startType !== "date" || finishType !== "date"))
errorMessage = msgPrefix + "the arguments to within must be dates";
else if ((!isNumeric(start) || !isNumeric(finish)) && (doLength || isNumeric(obj)))
errorMessage = msgPrefix + "the arguments to within must be numbers";
else if (!doLength && objType !== "date" && !isNumeric(obj)) {
let printObj = objType === "string" ? "'" + obj + "'" : obj;
errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date";
} else
shouldThrow = !1;
if (shouldThrow)
throw new AssertionError(errorMessage, void 0, ssfi);
if (doLength) {
let descriptor = "length", itemsCount;
objType === "map" || objType === "set" ? (descriptor = "size", itemsCount = obj.size) : itemsCount = obj.length, this.assert(
itemsCount >= start && itemsCount <= finish,
"expected #{this} to have a " + descriptor + " within " + range,
"expected #{this} to not have a " + descriptor + " within " + range
);
} else
this.assert(
obj >= start && obj <= finish,
"expected #{this} to be within " + range,
"expected #{this} to not be within " + range
);
});
function assertInstanceOf(constructor, msg) {
msg && flag2(this, "message", msg);
let target = flag2(this, "object"), ssfi = flag2(this, "ssfi"), flagMsg = flag2(this, "message"), isInstanceOf;
try {
isInstanceOf = target instanceof constructor;
} catch (err) {
throw err instanceof TypeError ? (flagMsg = flagMsg ? flagMsg + ": " : "", new AssertionError(
flagMsg + "The instanceof assertion needs a constructor but " + type(constructor) + " was given.",
void 0,
ssfi
)) : err;
}
let name = getName(constructor);
name == null && (name = "an unnamed constructor"), this.assert(
isInstanceOf,
"expected #{this} to be an instance of " + name,
"expected #{this} to not be an instance of " + name
);
}
__name(assertInstanceOf, "assertInstanceOf");
Assertion.addMethod("instanceof", assertInstanceOf);
Assertion.addMethod("instanceOf", assertInstanceOf);
function assertProperty(name, val, msg) {
msg && flag2(this, "message", msg);
let isNested = flag2(this, "nested"), isOwn = flag2(this, "own"), flagMsg = flag2(this, "message"), obj = flag2(this, "object"), ssfi = flag2(this, "ssfi"), nameType = typeof name;
if (flagMsg = flagMsg ? flagMsg + ": " : "", isNested) {
if (nameType !== "string")
throw new AssertionError(
flagMsg + "the argument to property must be a string when using nested syntax",
void 0,
ssfi
);
} else if (nameType !== "string" && nameType !== "number" && nameType !== "symbol")
throw new AssertionError(
flagMsg + "the argument to property must be a string, number, or symbol",
void 0,
ssfi
);
if (isNested && isOwn)
throw new AssertionError(
flagMsg + 'The "nested" and "own" flags cannot be combined.',
void 0,
ssfi
);
if (obj == null)
throw new AssertionError(
flagMsg + "Target cannot be null or undefined.",
void 0,
ssfi
);
let isDeep = flag2(this, "deep"), negate = flag2(this, "negate"), pathInfo = isNested ? getPathInfo(obj, name) : null, value = isNested ? pathInfo.value : obj[name], isEql = isDeep ? flag2(this, "eql") : (val1, val2) => val1 === val2, descriptor = "";
isDeep && (descriptor += "deep "), isOwn && (descriptor += "own "), isNested && (descriptor += "nested "), descriptor += "property ";
let hasProperty2;
isOwn ? hasProperty2 = Object.prototype.hasOwnProperty.call(obj, name) : isNested ? hasProperty2 = pathInfo.exists : hasProperty2 = hasProperty(obj, name), (!negate || arguments.length === 1) && this.assert(
hasProperty2,
"expected #{this} to have " + descriptor + inspect22(name),
"expected #{this} to not have " + descriptor + inspect22(name)
), arguments.length > 1 && this.assert(
hasProperty2 && isEql(val, value),
"expected #{this} to have " + descriptor + inspect22(name) + " of #{exp}, but got #{act}",
"expected #{this} to not have " + descriptor + inspect22(name) + " of #{act}",
val,
value
), flag2(this, "object", value);
}
__name(assertProperty, "assertProperty");
Assertion.addMethod("property", assertProperty);
function assertOwnProperty(_name, _value, _msg) {
flag2(this, "own", !0), assertProperty.apply(this, arguments);
}
__name(assertOwnProperty, "assertOwnProperty");
Assertion.addMethod("ownProperty", assertOwnProperty);
Assertion.addMethod("haveOwnProperty", assertOwnProperty);
function assertOwnPropertyDescriptor(name, descriptor, msg) {
typeof descriptor == "string" && (msg = descriptor, descriptor = null), msg && flag2(this, "message", msg);
let obj = flag2(this, "object"), actualDescriptor = Object.getOwnPropertyDescriptor(Object(obj), name), eql = flag2(this, "eql");
actualDescriptor && descriptor ? this.assert(
eql(descriptor, actualDescriptor),
"expected the own property descriptor for " + inspect22(name) + " on #{this} to match " + inspect22(descriptor) + ", got " + inspect22(actualDescriptor),
"expected the own property descriptor for " + inspect22(name) + " on #{this} to not match " + inspect22(descriptor),
descriptor,
actualDescriptor,
!0
) : this.assert(
actualDescriptor,
"expected #{this} to have an own property descriptor for " + inspect22(name),
"expected #{this} to not have an own property descriptor for " + inspect22(name)
), flag2(this, "object", actualDescriptor);
}
__name(assertOwnPropertyDescriptor, "assertOwnPropertyDescriptor");
Assertion.addMethod("ownPropertyDescriptor", assertOwnPropertyDescriptor);
Assertion.addMethod("haveOwnPropertyDescriptor", assertOwnPropertyDescriptor);
function assertLengthChain() {
flag2(this, "doLength", !0);
}
__name(assertLengthChain, "assertLengthChain");
function assertLength(n, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object"), objType = type(obj).toLowerCase(), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"), descriptor = "length", itemsCount;
switch (objType) {
case "map":
case "set":
descriptor = "size", itemsCount = obj.size;
break;
default:
new Assertion(obj, flagMsg, ssfi, !0).to.have.property("length"), itemsCount = obj.length;
}
this.assert(
itemsCount == n,
"expected #{this} to have a " + descriptor + " of #{exp} but got #{act}",
"expected #{this} to not have a " + descriptor + " of #{act}",
n,
itemsCount
);
}
__name(assertLength, "assertLength");
Assertion.addChainableMethod("length", assertLength, assertLengthChain);
Assertion.addChainableMethod("lengthOf", assertLength, assertLengthChain);
function assertMatch(re, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object");
this.assert(
re.exec(obj),
"expected #{this} to match " + re,
"expected #{this} not to match " + re
);
}
__name(assertMatch, "assertMatch");
Assertion.addMethod("match", assertMatch);
Assertion.addMethod("matches", assertMatch);
Assertion.addMethod("string", function(str, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi");
new Assertion(obj, flagMsg, ssfi, !0).is.a("string"), this.assert(
~obj.indexOf(str),
"expected #{this} to contain " + inspect22(str),
"expected #{this} to not contain " + inspect22(str)
);
});
function assertKeys(keys2) {
let obj = flag2(this, "object"), objType = type(obj), keysType = type(keys2), ssfi = flag2(this, "ssfi"), isDeep = flag2(this, "deep"), str, deepStr = "", actual, ok = !0, flagMsg = flag2(this, "message");
flagMsg = flagMsg ? flagMsg + ": " : "";
let mixedArgsMsg = flagMsg + "when testing keys against an object or an array you must give a single Array|Object|String argument or multiple String arguments";
if (objType === "Map" || objType === "Set")
deepStr = isDeep ? "deeply " : "", actual = [], obj.forEach(function(val, key) {
actual.push(key);
}), keysType !== "Array" && (keys2 = Array.prototype.slice.call(arguments));
else {
switch (actual = getOwnEnumerableProperties(obj), keysType) {
case "Array":
if (arguments.length > 1)
throw new AssertionError(mixedArgsMsg, void 0, ssfi);
break;
case "Object":
if (arguments.length > 1)
throw new AssertionError(mixedArgsMsg, void 0, ssfi);
keys2 = Object.keys(keys2);
break;
default:
keys2 = Array.prototype.slice.call(arguments);
}
keys2 = keys2.map(function(val) {
return typeof val == "symbol" ? val : String(val);
});
}
if (!keys2.length)
throw new AssertionError(flagMsg + "keys required", void 0, ssfi);
let len = keys2.length, any = flag2(this, "any"), all = flag2(this, "all"), expected = keys2, isEql = isDeep ? flag2(this, "eql") : (val1, val2) => val1 === val2;
if (!any && !all && (all = !0), any && (ok = expected.some(function(expectedKey) {
return actual.some(function(actualKey) {
return isEql(expectedKey, actualKey);
});
})), all && (ok = expected.every(function(expectedKey) {
return actual.some(function(actualKey) {
return isEql(expectedKey, actualKey);
});
}), flag2(this, "contains") || (ok = ok && keys2.length == actual.length)), len > 1) {
keys2 = keys2.map(function(key) {
return inspect22(key);
});
let last = keys2.pop();
all && (str = keys2.join(", ") + ", and " + last), any && (str = keys2.join(", ") + ", or " + last);
} else
str = inspect22(keys2[0]);
str = (len > 1 ? "keys " : "key ") + str, str = (flag2(this, "contains") ? "contain " : "have ") + str, this.assert(
ok,
"expected #{this} to " + deepStr + str,
"expected #{this} to not " + deepStr + str,
expected.slice(0).sort(compareByInspect),
actual.sort(compareByInspect),
!0
);
}
__name(assertKeys, "assertKeys");
Assertion.addMethod("keys", assertKeys);
Assertion.addMethod("key", assertKeys);
function assertThrows(errorLike, errMsgMatcher, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object"), ssfi = flag2(this, "ssfi"), flagMsg = flag2(this, "message"), negate = flag2(this, "negate") || !1;
new Assertion(obj, flagMsg, ssfi, !0).is.a("function"), (isRegExp2(errorLike) || typeof errorLike == "string") && (errMsgMatcher = errorLike, errorLike = null);
let caughtErr, errorWasThrown = !1;
try {
obj();
} catch (err) {
errorWasThrown = !0, caughtErr = err;
}
let everyArgIsUndefined = errorLike === void 0 && errMsgMatcher === void 0, everyArgIsDefined = !!(errorLike && errMsgMatcher), errorLikeFail = !1, errMsgMatcherFail = !1;
if (everyArgIsUndefined || !everyArgIsUndefined && !negate) {
let errorLikeString = "an error";
errorLike instanceof Error ? errorLikeString = "#{exp}" : errorLike && (errorLikeString = check_error_exports.getConstructorName(errorLike));
let actual = caughtErr;
if (caughtErr instanceof Error)
actual = caughtErr.toString();
else if (typeof caughtErr == "string")
actual = caughtErr;
else if (caughtErr && (typeof caughtErr == "object" || typeof caughtErr == "function"))
try {
actual = check_error_exports.getConstructorName(caughtErr);
} catch {
}
this.assert(
errorWasThrown,
"expected #{this} to throw " + errorLikeString,
"expected #{this} to not throw an error but #{act} was thrown",
errorLike && errorLike.toString(),
actual
);
}
if (errorLike && caughtErr && (errorLike instanceof Error && check_error_exports.compatibleInstance(
caughtErr,
errorLike
) === negate && (everyArgIsDefined && negate ? errorLikeFail = !0 : this.assert(
negate,
"expected #{this} to throw #{exp} but #{act} was thrown",
"expected #{this} to not throw #{exp}" + (caughtErr && !negate ? " but #{act} was thrown" : ""),
errorLike.toString(),
caughtErr.toString()
)), check_error_exports.compatibleConstructor(
caughtErr,
errorLike
) === negate && (everyArgIsDefined && negate ? errorLikeFail = !0 : this.assert(
negate,
"expected #{this} to throw #{exp} but #{act} was thrown",
"expected #{this} to not throw #{exp}" + (caughtErr ? " but #{act} was thrown" : ""),
errorLike instanceof Error ? errorLike.toString() : errorLike && check_error_exports.getConstructorName(errorLike),
caughtErr instanceof Error ? caughtErr.toString() : caughtErr && check_error_exports.getConstructorName(caughtErr)
))), caughtErr && errMsgMatcher !== void 0 && errMsgMatcher !== null) {
let placeholder = "including";
isRegExp2(errMsgMatcher) && (placeholder = "matching"), check_error_exports.compatibleMessage(
caughtErr,
errMsgMatcher
) === negate && (everyArgIsDefined && negate ? errMsgMatcherFail = !0 : this.assert(
negate,
"expected #{this} to throw error " + placeholder + " #{exp} but got #{act}",
"expected #{this} to throw error not " + placeholder + " #{exp}",
errMsgMatcher,
check_error_exports.getMessage(caughtErr)
));
}
errorLikeFail && errMsgMatcherFail && this.assert(
negate,
"expected #{this} to throw #{exp} but #{act} was thrown",
"expected #{this} to not throw #{exp}" + (caughtErr ? " but #{act} was thrown" : ""),
errorLike instanceof Error ? errorLike.toString() : errorLike && check_error_exports.getConstructorName(errorLike),
caughtErr instanceof Error ? caughtErr.toString() : caughtErr && check_error_exports.getConstructorName(caughtErr)
), flag2(this, "object", caughtErr);
}
__name(assertThrows, "assertThrows");
Assertion.addMethod("throw", assertThrows);
Assertion.addMethod("throws", assertThrows);
Assertion.addMethod("Throw", assertThrows);
function respondTo(method, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object"), itself = flag2(this, "itself"), context = typeof obj == "function" && !itself ? obj.prototype[method] : obj[method];
this.assert(
typeof context == "function",
"expected #{this} to respond to " + inspect22(method),
"expected #{this} to not respond to " + inspect22(method)
);
}
__name(respondTo, "respondTo");
Assertion.addMethod("respondTo", respondTo);
Assertion.addMethod("respondsTo", respondTo);
Assertion.addProperty("itself", function() {
flag2(this, "itself", !0);
});
function satisfy(matcher, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object"), result = matcher(obj);
this.assert(
result,
"expected #{this} to satisfy " + objDisplay2(matcher),
"expected #{this} to not satisfy" + objDisplay2(matcher),
!flag2(this, "negate"),
result
);
}
__name(satisfy, "satisfy");
Assertion.addMethod("satisfy", satisfy);
Assertion.addMethod("satisfies", satisfy);
function closeTo(expected, delta, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi");
new Assertion(obj, flagMsg, ssfi, !0).is.numeric;
let message = "A `delta` value is required for `closeTo`";
if (delta == null)
throw new AssertionError(
flagMsg ? `${flagMsg}: ${message}` : message,
void 0,
ssfi
);
if (new Assertion(delta, flagMsg, ssfi, !0).is.numeric, message = "A `expected` value is required for `closeTo`", expected == null)
throw new AssertionError(
flagMsg ? `${flagMsg}: ${message}` : message,
void 0,
ssfi
);
new Assertion(expected, flagMsg, ssfi, !0).is.numeric;
let abs = /* @__PURE__ */ __name((x) => x < 0 ? -x : x, "abs"), strip = /* @__PURE__ */ __name((number) => parseFloat(parseFloat(number).toPrecision(12)), "strip");
this.assert(
strip(abs(obj - expected)) <= delta,
"expected #{this} to be close to " + expected + " +/- " + delta,
"expected #{this} not to be close to " + expected + " +/- " + delta
);
}
__name(closeTo, "closeTo");
Assertion.addMethod("closeTo", closeTo);
Assertion.addMethod("approximately", closeTo);
function isSubsetOf(_subset, _superset, cmp, contains, ordered) {
let superset = Array.from(_superset), subset = Array.from(_subset);
if (!contains) {
if (subset.length !== superset.length) return !1;
superset = superset.slice();
}
return subset.every(function(elem, idx) {
if (ordered) return cmp ? cmp(elem, superset[idx]) : elem === superset[idx];
if (!cmp) {
let matchIdx = superset.indexOf(elem);
return matchIdx === -1 ? !1 : (contains || superset.splice(matchIdx, 1), !0);
}
return superset.some(function(elem2, matchIdx) {
return cmp(elem, elem2) ? (contains || superset.splice(matchIdx, 1), !0) : !1;
});
});
}
__name(isSubsetOf, "isSubsetOf");
Assertion.addMethod("members", function(subset, msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi");
new Assertion(obj, flagMsg, ssfi, !0).to.be.iterable, new Assertion(subset, flagMsg, ssfi, !0).to.be.iterable;
let contains = flag2(this, "contains"), ordered = flag2(this, "ordered"), subject, failMsg, failNegateMsg;
contains ? (subject = ordered ? "an ordered superset" : "a superset", failMsg = "expected #{this} to be " + subject + " of #{exp}", failNegateMsg = "expected #{this} to not be " + subject + " of #{exp}") : (subject = ordered ? "ordered members" : "members", failMsg = "expected #{this} to have the same " + subject + " as #{exp}", failNegateMsg = "expected #{this} to not have the same " + subject + " as #{exp}");
let cmp = flag2(this, "deep") ? flag2(this, "eql") : void 0;
this.assert(
isSubsetOf(subset, obj, cmp, contains, ordered),
failMsg,
failNegateMsg,
subset,
obj,
!0
);
});
Assertion.addProperty("iterable", function(msg) {
msg && flag2(this, "message", msg);
let obj = flag2(this, "object");
this.assert(
obj != null && obj[Symbol.iterator],
"expected #{this} to be an iterable",
"expected #{this} to not be an iterable",
obj
);
});
function oneOf(list, msg) {
msg && flag2(this, "message", msg);
let expected = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"), contains = flag2(this, "contains"), isDeep = flag2(this, "deep"), eql = flag2(this, "eql");
new Assertion(list, flagMsg, ssfi, !0).to.be.an("array"), contains ? this.assert(
list.some(function(possibility) {
return expected.indexOf(possibility) > -1;
}),
"expected #{this} to contain one of #{exp}",
"expected #{this} to not contain one of #{exp}",
list,
expected
) : isDeep ? this.assert(
list.some(function(possibility) {
return eql(expected, possibility);
}),
"expected #{this} to deeply equal one of #{exp}",
"expected #{this} to deeply equal one of #{exp}",
list,
expected
) : this.assert(
list.indexOf(expected) > -1,
"expected #{this} to be one of #{exp}",
"expected #{this} to not be one of #{exp}",
list,
expected
);
}
__name(oneOf, "oneOf");
Assertion.addMethod("oneOf", oneOf);
function assertChanges(subject, prop, msg) {
msg && flag2(this, "message", msg);
let fn2 = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi");
new Assertion(fn2, flagMsg, ssfi, !0).is.a("function");
let initial;
prop ? (new Assertion(subject, flagMsg, ssfi, !0).to.have.property(prop), initial = subject[prop]) : (new Assertion(subject, flagMsg, ssfi, !0).is.a("function"), initial = subject()), fn2();
let final = prop == null ? subject() : subject[prop], msgObj = prop == null ? initial : "." + prop;
flag2(this, "deltaMsgObj", msgObj), flag2(this, "initialDeltaValue", initial), flag2(this, "finalDeltaValue", final), flag2(this, "deltaBehavior", "change"), flag2(this, "realDelta", final !== initial), this.assert(
initial !== final,
"expected " + msgObj + " to change",
"expected " + msgObj + " to not change"
);
}
__name(assertChanges, "assertChanges");
Assertion.addMethod("change", assertChanges);
Assertion.addMethod("changes", assertChanges);
function assertIncreases(subject, prop, msg) {
msg && flag2(this, "message", msg);
let fn2 = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi");
new Assertion(fn2, flagMsg, ssfi, !0).is.a("function");
let initial;
prop ? (new Assertion(subject, flagMsg, ssfi, !0).to.have.property(prop), initial = subject[prop]) : (new Assertion(subject, flagMsg, ssfi, !0).is.a("function"), initial = subject()), new Assertion(initial, flagMsg, ssfi, !0).is.a("number"), fn2();
let final = prop == null ? subject() : subject[prop], msgObj = prop == null ? initial : "." + prop;
flag2(this, "deltaMsgObj", msgObj), flag2(this, "initialDeltaValue", initial), flag2(this, "finalDeltaValue", final), flag2(this, "deltaBehavior", "increase"), flag2(this, "realDelta", final - initial), this.assert(
final - initial > 0,
"expected " + msgObj + " to increase",
"expected " + msgObj + " to not increase"
);
}
__name(assertIncreases, "assertIncreases");
Assertion.addMethod("increase", assertIncreases);
Assertion.addMethod("increases", assertIncreases);
function assertDecreases(subject, prop, msg) {
msg && flag2(this, "message", msg);
let fn2 = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi");
new Assertion(fn2, flagMsg, ssfi, !0).is.a("function");
let initial;
prop ? (new Assertion(subject, flagMsg, ssfi, !0).to.have.property(prop), initial = subject[prop]) : (new Assertion(subject, flagMsg, ssfi, !0).is.a("function"), initial = subject()), new Assertion(initial, flagMsg, ssfi, !0).is.a("number"), fn2();
let final = prop == null ? subject() : subject[prop], msgObj = prop == null ? initial : "." + prop;
flag2(this, "deltaMsgObj", msgObj), flag2(this, "initialDeltaValue", initial), flag2(this, "finalDeltaValue", final), flag2(this, "deltaBehavior", "decrease"), flag2(this, "realDelta", initial - final), this.assert(
final - initial < 0,
"expected " + msgObj + " to decrease",
"expected " + msgObj + " to not decrease"
);
}
__name(assertDecreases, "assertDecreases");
Assertion.addMethod("decrease", assertDecreases);
Assertion.addMethod("decreases", assertDecreases);
function assertDelta(delta, msg) {
msg && flag2(this, "message", msg);
let msgObj = flag2(this, "deltaMsgObj"), initial = flag2(this, "initialDeltaValue"), final = flag2(this, "finalDeltaValue"), behavior = flag2(this, "deltaBehavior"), realDelta = flag2(this, "realDelta"), expression;
behavior === "change" ? expression = Math.abs(final - initial) === Math.abs(delta) : expression = realDelta === Math.abs(delta), this.assert(
expression,
"expected " + msgObj + " to " + behavior + " by " + delta,
"expected " + msgObj + " to not " + behavior + " by " + delta
);
}
__name(assertDelta, "assertDelta");
Assertion.addMethod("by", assertDelta);
Assertion.addProperty("extensible", function() {
let obj = flag2(this, "object"), isExtensible = obj === Object(obj) && Object.isExtensible(obj);
this.assert(
isExtensible,
"expected #{this} to be extensible",
"expected #{this} to not be extensible"
);
});
Assertion.addProperty("sealed", function() {
let obj = flag2(this, "object"), isSealed = obj === Object(obj) ? Object.isSealed(obj) : !0;
this.assert(
isSealed,
"expected #{this} to be sealed",
"expected #{this} to not be sealed"
);
});
Assertion.addProperty("frozen", function() {
let obj = flag2(this, "object"), isFrozen = obj === Object(obj) ? Object.isFrozen(obj) : !0;
this.assert(
isFrozen,
"expected #{this} to be frozen",
"expected #{this} to not be frozen"
);
});
Assertion.addProperty("finite", function(_msg) {
let obj = flag2(this, "object");
this.assert(
typeof obj == "number" && isFinite(obj),
"expected #{this} to be a finite number",
"expected #{this} to not be a finite number"
);
});
function compareSubset(expected, actual) {
return expected === actual ? !0 : typeof actual != typeof expected ? !1 : typeof expected != "object" || expected === null ? expected === actual : actual ? Array.isArray(expected) ? Array.isArray(actual) ? expected.every(function(exp) {
return actual.some(function(act) {
return compareSubset(exp, act);
});
}) : !1 : expected instanceof Date ? actual instanceof Date ? expected.getTime() === actual.getTime() : !1 : Object.keys(expected).every(function(key) {
let expectedValue = expected[key], actualValue = actual[key];
return typeof expectedValue == "object" && expectedValue !== null && actualValue !== null ? compareSubset(expectedValue, actualValue) : typeof expectedValue == "function" ? expectedValue(actualValue) : actualValue === expectedValue;
}) : !1;
}
__name(compareSubset, "compareSubset");
Assertion.addMethod("containSubset", function(expected) {
let actual = flag(this, "object"), showDiff = config.showDiff;
this.assert(
compareSubset(expected, actual),
"expected #{act} to contain subset #{exp}",
"expected #{act} to not contain subset #{exp}",
expected,
actual,
showDiff
);
});
function expect(val, message) {
return new Assertion(val, message);
}
__name(expect, "expect");
expect.fail = function(actual, expected, message, operator) {
throw arguments.length < 2 && (message = actual, actual = void 0), message = message || "expect.fail()", new AssertionError(
message,
{
actual,
expected,
operator
},
expect.fail
);
};
var should_exports = {};
__export2(should_exports, {
Should: () => Should,
should: () => should
});
function loadShould() {
function shouldGetter() {
return this instanceof String || this instanceof Number || this instanceof Boolean || typeof Symbol == "function" && this instanceof Symbol || typeof BigInt == "function" && this instanceof BigInt ? new Assertion(this.valueOf(), null, shouldGetter) : new Assertion(this, null, shouldGetter);
}
__name(shouldGetter, "shouldGetter");
function shouldSetter(value) {
Object.defineProperty(this, "should", {
value,
enumerable: !0,
configurable: !0,
writable: !0
});
}
__name(shouldSetter, "shouldSetter"), Object.defineProperty(Object.prototype, "should", {
set: shouldSetter,
get: shouldGetter,
configurable: !0
});
let should22 = {};
return should22.fail = function(actual, expected, message, operator) {
throw arguments.length < 2 && (message = actual, actual = void 0), message = message || "should.fail()", new AssertionError(
message,
{
actual,
expected,
operator
},
should22.fail
);
}, should22.equal = function(actual, expected, message) {
new Assertion(actual, message).to.equal(expected);
}, should22.Throw = function(fn2, errt, errs, msg) {
new Assertion(fn2, msg).to.Throw(errt, errs);
}, should22.exist = function(val, msg) {
new Assertion(val, msg).to.exist;
}, should22.not = {}, should22.not.equal = function(actual, expected, msg) {
new Assertion(actual, msg).to.not.equal(expected);
}, should22.not.Throw = function(fn2, errt, errs, msg) {
new Assertion(fn2, msg).to.not.Throw(errt, errs);
}, should22.not.exist = function(val, msg) {
new Assertion(val, msg).to.not.exist;
}, should22.throw = should22.Throw, should22.not.throw = should22.not.Throw, should22;
}
__name(loadShould, "loadShould");
var should = loadShould, Should = loadShould;
function assert3(express, errmsg) {
new Assertion(null, null, assert3, !0).assert(express, errmsg, "[ negation message unavailable ]");
}
__name(assert3, "assert");
assert3.fail = function(actual, expected, message, operator) {
throw arguments.length < 2 && (message = actual, actual = void 0), message = message || "assert.fail()", new AssertionError(
message,
{
actual,
expected,
operator
},
assert3.fail
);
};
assert3.isOk = function(val, msg) {
new Assertion(val, msg, assert3.isOk, !0).is.ok;
};
assert3.isNotOk = function(val, msg) {
new Assertion(val, msg, assert3.isNotOk, !0).is.not.ok;
};
assert3.equal = function(act, exp, msg) {
let test22 = new Assertion(act, msg, assert3.equal, !0);
test22.assert(
exp == flag(test22, "object"),
"expected #{this} to equal #{exp}",
"expected #{this} to not equal #{act}",
exp,
act,
!0
);
};
assert3.notEqual = function(act, exp, msg) {
let test22 = new Assertion(act, msg, assert3.notEqual, !0);
test22.assert(
exp != flag(test22, "object"),
"expected #{this} to not equal #{exp}",
"expected #{this} to equal #{act}",
exp,
act,
!0
);
};
assert3.strictEqual = function(act, exp, msg) {
new Assertion(act, msg, assert3.strictEqual, !0).to.equal(exp);
};
assert3.notStrictEqual = function(act, exp, msg) {
new Assertion(act, msg, assert3.notStrictEqual, !0).to.not.equal(exp);
};
assert3.deepEqual = assert3.deepStrictEqual = function(act, exp, msg) {
new Assertion(act, msg, assert3.deepEqual, !0).to.eql(exp);
};
assert3.notDeepEqual = function(act, exp, msg) {
new Assertion(act, msg, assert3.notDeepEqual, !0).to.not.eql(exp);
};
assert3.isAbove = function(val, abv, msg) {
new Assertion(val, msg, assert3.isAbove, !0).to.be.above(abv);
};
assert3.isAtLeast = function(val, atlst, msg) {
new Assertion(val, msg, assert3.isAtLeast, !0).to.be.least(atlst);
};
assert3.isBelow = function(val, blw, msg) {
new Assertion(val, msg, assert3.isBelow, !0).to.be.below(blw);
};
assert3.isAtMost = function(val, atmst, msg) {
new Assertion(val, msg, assert3.isAtMost, !0).to.be.most(atmst);
};
assert3.isTrue = function(val, msg) {
new Assertion(val, msg, assert3.isTrue, !0).is.true;
};
assert3.isNotTrue = function(val, msg) {
new Assertion(val, msg, assert3.isNotTrue, !0).to.not.equal(!0);
};
assert3.isFalse = function(val, msg) {
new Assertion(val, msg, assert3.isFalse, !0).is.false;
};
assert3.isNotFalse = function(val, msg) {
new Assertion(val, msg, assert3.isNotFalse, !0).to.not.equal(!1);
};
assert3.isNull = function(val, msg) {
new Assertion(val, msg, assert3.isNull, !0).to.equal(null);
};
assert3.isNotNull = function(val, msg) {
new Assertion(val, msg, assert3.isNotNull, !0).to.not.equal(null);
};
assert3.isNaN = function(val, msg) {
new Assertion(val, msg, assert3.isNaN, !0).to.be.NaN;
};
assert3.isNotNaN = function(value, message) {
new Assertion(value, message, assert3.isNotNaN, !0).not.to.be.NaN;
};
assert3.exists = function(val, msg) {
new Assertion(val, msg, assert3.exists, !0).to.exist;
};
assert3.notExists = function(val, msg) {
new Assertion(val, msg, assert3.notExists, !0).to.not.exist;
};
assert3.isUndefined = function(val, msg) {
new Assertion(val, msg, assert3.isUndefined, !0).to.equal(void 0);
};
assert3.isDefined = function(val, msg) {
new Assertion(val, msg, assert3.isDefined, !0).to.not.equal(void 0);
};
assert3.isCallable = function(value, message) {
new Assertion(value, message, assert3.isCallable, !0).is.callable;
};
assert3.isNotCallable = function(value, message) {
new Assertion(value, message, assert3.isNotCallable, !0).is.not.callable;
};
assert3.isObject = function(val, msg) {
new Assertion(val, msg, assert3.isObject, !0).to.be.a("object");
};
assert3.isNotObject = function(val, msg) {
new Assertion(val, msg, assert3.isNotObject, !0).to.not.be.a("object");
};
assert3.isArray = function(val, msg) {
new Assertion(val, msg, assert3.isArray, !0).to.be.an("array");
};
assert3.isNotArray = function(val, msg) {
new Assertion(val, msg, assert3.isNotArray, !0).to.not.be.an("array");
};
assert3.isString = function(val, msg) {
new Assertion(val, msg, assert3.isString, !0).to.be.a("string");
};
assert3.isNotString = function(val, msg) {
new Assertion(val, msg, assert3.isNotString, !0).to.not.be.a("string");
};
assert3.isNumber = function(val, msg) {
new Assertion(val, msg, assert3.isNumber, !0).to.be.a("number");
};
assert3.isNotNumber = function(val, msg) {
new Assertion(val, msg, assert3.isNotNumber, !0).to.not.be.a("number");
};
assert3.isNumeric = function(val, msg) {
new Assertion(val, msg, assert3.isNumeric, !0).is.numeric;
};
assert3.isNotNumeric = function(val, msg) {
new Assertion(val, msg, assert3.isNotNumeric, !0).is.not.numeric;
};
assert3.isFinite = function(val, msg) {
new Assertion(val, msg, assert3.isFinite, !0).to.be.finite;
};
assert3.isBoolean = function(val, msg) {
new Assertion(val, msg, assert3.isBoolean, !0).to.be.a("boolean");
};
assert3.isNotBoolean = function(val, msg) {
new Assertion(val, msg, assert3.isNotBoolean, !0).to.not.be.a("boolean");
};
assert3.typeOf = function(val, type3, msg) {
new Assertion(val, msg, assert3.typeOf, !0).to.be.a(type3);
};
assert3.notTypeOf = function(value, type3, message) {
new Assertion(value, message, assert3.notTypeOf, !0).to.not.be.a(type3);
};
assert3.instanceOf = function(val, type3, msg) {
new Assertion(val, msg, assert3.instanceOf, !0).to.be.instanceOf(type3);
};
assert3.notInstanceOf = function(val, type3, msg) {
new Assertion(val, msg, assert3.notInstanceOf, !0).to.not.be.instanceOf(
type3
);
};
assert3.include = function(exp, inc, msg) {
new Assertion(exp, msg, assert3.include, !0).include(inc);
};
assert3.notInclude = function(exp, inc, msg) {
new Assertion(exp, msg, assert3.notInclude, !0).not.include(inc);
};
assert3.deepInclude = function(exp, inc, msg) {
new Assertion(exp, msg, assert3.deepInclude, !0).deep.include(inc);
};
assert3.notDeepInclude = function(exp, inc, msg) {
new Assertion(exp, msg, assert3.notDeepInclude, !0).not.deep.include(inc);
};
assert3.nestedInclude = function(exp, inc, msg) {
new Assertion(exp, msg, assert3.nestedInclude, !0).nested.include(inc);
};
assert3.notNestedInclude = function(exp, inc, msg) {
new Assertion(exp, msg, assert3.notNestedInclude, !0).not.nested.include(
inc
);
};
assert3.deepNestedInclude = function(exp, inc, msg) {
new Assertion(exp, msg, assert3.deepNestedInclude, !0).deep.nested.include(
inc
);
};
assert3.notDeepNestedInclude = function(exp, inc, msg) {
new Assertion(
exp,
msg,
assert3.notDeepNestedInclude,
!0
).not.deep.nested.include(inc);
};
assert3.ownInclude = function(exp, inc, msg) {
new Assertion(exp, msg, assert3.ownInclude, !0).own.include(inc);
};
assert3.notOwnInclude = function(exp, inc, msg) {
new Assertion(exp, msg, assert3.notOwnInclude, !0).not.own.include(inc);
};
assert3.deepOwnInclude = function(exp, inc, msg) {
new Assertion(exp, msg, assert3.deepOwnInclude, !0).deep.own.include(inc);
};
assert3.notDeepOwnInclude = function(exp, inc, msg) {
new Assertion(exp, msg, assert3.notDeepOwnInclude, !0).not.deep.own.include(
inc
);
};
assert3.match = function(exp, re, msg) {
new Assertion(exp, msg, assert3.match, !0).to.match(re);
};
assert3.notMatch = function(exp, re, msg) {
new Assertion(exp, msg, assert3.notMatch, !0).to.not.match(re);
};
assert3.property = function(obj, prop, msg) {
new Assertion(obj, msg, assert3.property, !0).to.have.property(prop);
};
assert3.notProperty = function(obj, prop, msg) {
new Assertion(obj, msg, assert3.notProperty, !0).to.not.have.property(prop);
};
assert3.propertyVal = function(obj, prop, val, msg) {
new Assertion(obj, msg, assert3.propertyVal, !0).to.have.property(prop, val);
};
assert3.notPropertyVal = function(obj, prop, val, msg) {
new Assertion(obj, msg, assert3.notPropertyVal, !0).to.not.have.property(
prop,
val
);
};
assert3.deepPropertyVal = function(obj, prop, val, msg) {
new Assertion(obj, msg, assert3.deepPropertyVal, !0).to.have.deep.property(
prop,
val
);
};
assert3.notDeepPropertyVal = function(obj, prop, val, msg) {
new Assertion(
obj,
msg,
assert3.notDeepPropertyVal,
!0
).to.not.have.deep.property(prop, val);
};
assert3.ownProperty = function(obj, prop, msg) {
new Assertion(obj, msg, assert3.ownProperty, !0).to.have.own.property(prop);
};
assert3.notOwnProperty = function(obj, prop, msg) {
new Assertion(obj, msg, assert3.notOwnProperty, !0).to.not.have.own.property(
prop
);
};
assert3.ownPropertyVal = function(obj, prop, value, msg) {
new Assertion(obj, msg, assert3.ownPropertyVal, !0).to.have.own.property(
prop,
value
);
};
assert3.notOwnPropertyVal = function(obj, prop, value, msg) {
new Assertion(
obj,
msg,
assert3.notOwnPropertyVal,
!0
).to.not.have.own.property(prop, value);
};
assert3.deepOwnPropertyVal = function(obj, prop, value, msg) {
new Assertion(
obj,
msg,
assert3.deepOwnPropertyVal,
!0
).to.have.deep.own.property(prop, value);
};
assert3.notDeepOwnPropertyVal = function(obj, prop, value, msg) {
new Assertion(
obj,
msg,
assert3.notDeepOwnPropertyVal,
!0
).to.not.have.deep.own.property(prop, value);
};
assert3.nestedProperty = function(obj, prop, msg) {
new Assertion(obj, msg, assert3.nestedProperty, !0).to.have.nested.property(
prop
);
};
assert3.notNestedProperty = function(obj, prop, msg) {
new Assertion(
obj,
msg,
assert3.notNestedProperty,
!0
).to.not.have.nested.property(prop);
};
assert3.nestedPropertyVal = function(obj, prop, val, msg) {
new Assertion(
obj,
msg,
assert3.nestedPropertyVal,
!0
).to.have.nested.property(prop, val);
};
assert3.notNestedPropertyVal = function(obj, prop, val, msg) {
new Assertion(
obj,
msg,
assert3.notNestedPropertyVal,
!0
).to.not.have.nested.property(prop, val);
};
assert3.deepNestedPropertyVal = function(obj, prop, val, msg) {
new Assertion(
obj,
msg,
assert3.deepNestedPropertyVal,
!0
).to.have.deep.nested.property(prop, val);
};
assert3.notDeepNestedPropertyVal = function(obj, prop, val, msg) {
new Assertion(
obj,
msg,
assert3.notDeepNestedPropertyVal,
!0
).to.not.have.deep.nested.property(prop, val);
};
assert3.lengthOf = function(exp, len, msg) {
new Assertion(exp, msg, assert3.lengthOf, !0).to.have.lengthOf(len);
};
assert3.hasAnyKeys = function(obj, keys2, msg) {
new Assertion(obj, msg, assert3.hasAnyKeys, !0).to.have.any.keys(keys2);
};
assert3.hasAllKeys = function(obj, keys2, msg) {
new Assertion(obj, msg, assert3.hasAllKeys, !0).to.have.all.keys(keys2);
};
assert3.containsAllKeys = function(obj, keys2, msg) {
new Assertion(obj, msg, assert3.containsAllKeys, !0).to.contain.all.keys(
keys2
);
};
assert3.doesNotHaveAnyKeys = function(obj, keys2, msg) {
new Assertion(obj, msg, assert3.doesNotHaveAnyKeys, !0).to.not.have.any.keys(
keys2
);
};
assert3.doesNotHaveAllKeys = function(obj, keys2, msg) {
new Assertion(obj, msg, assert3.doesNotHaveAllKeys, !0).to.not.have.all.keys(
keys2
);
};
assert3.hasAnyDeepKeys = function(obj, keys2, msg) {
new Assertion(obj, msg, assert3.hasAnyDeepKeys, !0).to.have.any.deep.keys(
keys2
);
};
assert3.hasAllDeepKeys = function(obj, keys2, msg) {
new Assertion(obj, msg, assert3.hasAllDeepKeys, !0).to.have.all.deep.keys(
keys2
);
};
assert3.containsAllDeepKeys = function(obj, keys2, msg) {
new Assertion(
obj,
msg,
assert3.containsAllDeepKeys,
!0
).to.contain.all.deep.keys(keys2);
};
assert3.doesNotHaveAnyDeepKeys = function(obj, keys2, msg) {
new Assertion(
obj,
msg,
assert3.doesNotHaveAnyDeepKeys,
!0
).to.not.have.any.deep.keys(keys2);
};
assert3.doesNotHaveAllDeepKeys = function(obj, keys2, msg) {
new Assertion(
obj,
msg,
assert3.doesNotHaveAllDeepKeys,
!0
).to.not.have.all.deep.keys(keys2);
};
assert3.throws = function(fn2, errorLike, errMsgMatcher, msg) {
(typeof errorLike == "string" || errorLike instanceof RegExp) && (errMsgMatcher = errorLike, errorLike = null);
let assertErr = new Assertion(fn2, msg, assert3.throws, !0).to.throw(
errorLike,
errMsgMatcher
);
return flag(assertErr, "object");
};
assert3.doesNotThrow = function(fn2, errorLike, errMsgMatcher, message) {
(typeof errorLike == "string" || errorLike instanceof RegExp) && (errMsgMatcher = errorLike, errorLike = null), new Assertion(fn2, message, assert3.doesNotThrow, !0).to.not.throw(
errorLike,
errMsgMatcher
);
};
assert3.operator = function(val, operator, val2, msg) {
let ok;
switch (operator) {
case "==":
ok = val == val2;
break;
case "===":
ok = val === val2;
break;
case ">":
ok = val > val2;
break;
case ">=":
ok = val >= val2;
break;
case "<":
ok = val < val2;
break;
case "<=":
ok = val <= val2;
break;
case "!=":
ok = val != val2;
break;
case "!==":
ok = val !== val2;
break;
default:
throw msg = msg && msg + ": ", new AssertionError(
msg + 'Invalid operator "' + operator + '"',
void 0,
assert3.operator
);
}
let test22 = new Assertion(ok, msg, assert3.operator, !0);
test22.assert(
flag(test22, "object") === !0,
"expected " + inspect22(val) + " to be " + operator + " " + inspect22(val2),
"expected " + inspect22(val) + " to not be " + operator + " " + inspect22(val2)
);
};
assert3.closeTo = function(act, exp, delta, msg) {
new Assertion(act, msg, assert3.closeTo, !0).to.be.closeTo(exp, delta);
};
assert3.approximately = function(act, exp, delta, msg) {
new Assertion(act, msg, assert3.approximately, !0).to.be.approximately(
exp,
delta
);
};
assert3.sameMembers = function(set1, set22, msg) {
new Assertion(set1, msg, assert3.sameMembers, !0).to.have.same.members(set22);
};
assert3.notSameMembers = function(set1, set22, msg) {
new Assertion(
set1,
msg,
assert3.notSameMembers,
!0
).to.not.have.same.members(set22);
};
assert3.sameDeepMembers = function(set1, set22, msg) {
new Assertion(
set1,
msg,
assert3.sameDeepMembers,
!0
).to.have.same.deep.members(set22);
};
assert3.notSameDeepMembers = function(set1, set22, msg) {
new Assertion(
set1,
msg,
assert3.notSameDeepMembers,
!0
).to.not.have.same.deep.members(set22);
};
assert3.sameOrderedMembers = function(set1, set22, msg) {
new Assertion(
set1,
msg,
assert3.sameOrderedMembers,
!0
).to.have.same.ordered.members(set22);
};
assert3.notSameOrderedMembers = function(set1, set22, msg) {
new Assertion(
set1,
msg,
assert3.notSameOrderedMembers,
!0
).to.not.have.same.ordered.members(set22);
};
assert3.sameDeepOrderedMembers = function(set1, set22, msg) {
new Assertion(
set1,
msg,
assert3.sameDeepOrderedMembers,
!0
).to.have.same.deep.ordered.members(set22);
};
assert3.notSameDeepOrderedMembers = function(set1, set22, msg) {
new Assertion(
set1,
msg,
assert3.notSameDeepOrderedMembers,
!0
).to.not.have.same.deep.ordered.members(set22);
};
assert3.includeMembers = function(superset, subset, msg) {
new Assertion(superset, msg, assert3.includeMembers, !0).to.include.members(
subset
);
};
assert3.notIncludeMembers = function(superset, subset, msg) {
new Assertion(
superset,
msg,
assert3.notIncludeMembers,
!0
).to.not.include.members(subset);
};
assert3.includeDeepMembers = function(superset, subset, msg) {
new Assertion(
superset,
msg,
assert3.includeDeepMembers,
!0
).to.include.deep.members(subset);
};
assert3.notIncludeDeepMembers = function(superset, subset, msg) {
new Assertion(
superset,
msg,
assert3.notIncludeDeepMembers,
!0
).to.not.include.deep.members(subset);
};
assert3.includeOrderedMembers = function(superset, subset, msg) {
new Assertion(
superset,
msg,
assert3.includeOrderedMembers,
!0
).to.include.ordered.members(subset);
};
assert3.notIncludeOrderedMembers = function(superset, subset, msg) {
new Assertion(
superset,
msg,
assert3.notIncludeOrderedMembers,
!0
).to.not.include.ordered.members(subset);
};
assert3.includeDeepOrderedMembers = function(superset, subset, msg) {
new Assertion(
superset,
msg,
assert3.includeDeepOrderedMembers,
!0
).to.include.deep.ordered.members(subset);
};
assert3.notIncludeDeepOrderedMembers = function(superset, subset, msg) {
new Assertion(
superset,
msg,
assert3.notIncludeDeepOrderedMembers,
!0
).to.not.include.deep.ordered.members(subset);
};
assert3.oneOf = function(inList, list, msg) {
new Assertion(inList, msg, assert3.oneOf, !0).to.be.oneOf(list);
};
assert3.isIterable = function(obj, msg) {
if (obj == null || !obj[Symbol.iterator])
throw msg = msg ? `${msg} expected ${inspect22(obj)} to be an iterable` : `expected ${inspect22(obj)} to be an iterable`, new AssertionError(msg, void 0, assert3.isIterable);
};
assert3.changes = function(fn2, obj, prop, msg) {
arguments.length === 3 && typeof obj == "function" && (msg = prop, prop = null), new Assertion(fn2, msg, assert3.changes, !0).to.change(obj, prop);
};
assert3.changesBy = function(fn2, obj, prop, delta, msg) {
if (arguments.length === 4 && typeof obj == "function") {
let tmpMsg = delta;
delta = prop, msg = tmpMsg;
} else arguments.length === 3 && (delta = prop, prop = null);
new Assertion(fn2, msg, assert3.changesBy, !0).to.change(obj, prop).by(delta);
};
assert3.doesNotChange = function(fn2, obj, prop, msg) {
return arguments.length === 3 && typeof obj == "function" && (msg = prop, prop = null), new Assertion(fn2, msg, assert3.doesNotChange, !0).to.not.change(
obj,
prop
);
};
assert3.changesButNotBy = function(fn2, obj, prop, delta, msg) {
if (arguments.length === 4 && typeof obj == "function") {
let tmpMsg = delta;
delta = prop, msg = tmpMsg;
} else arguments.length === 3 && (delta = prop, prop = null);
new Assertion(fn2, msg, assert3.changesButNotBy, !0).to.change(obj, prop).but.not.by(delta);
};
assert3.increases = function(fn2, obj, prop, msg) {
return arguments.length === 3 && typeof obj == "function" && (msg = prop, prop = null), new Assertion(fn2, msg, assert3.increases, !0).to.increase(obj, prop);
};
assert3.increasesBy = function(fn2, obj, prop, delta, msg) {
if (arguments.length === 4 && typeof obj == "function") {
let tmpMsg = delta;
delta = prop, msg = tmpMsg;
} else arguments.length === 3 && (delta = prop, prop = null);
new Assertion(fn2, msg, assert3.increasesBy, !0).to.increase(obj, prop).by(delta);
};
assert3.doesNotIncrease = function(fn2, obj, prop, msg) {
return arguments.length === 3 && typeof obj == "function" && (msg = prop, prop = null), new Assertion(fn2, msg, assert3.doesNotIncrease, !0).to.not.increase(
obj,
prop
);
};
assert3.increasesButNotBy = function(fn2, obj, prop, delta, msg) {
if (arguments.length === 4 && typeof obj == "function") {
let tmpMsg = delta;
delta = prop, msg = tmpMsg;
} else arguments.length === 3 && (delta = prop, prop = null);
new Assertion(fn2, msg, assert3.increasesButNotBy, !0).to.increase(obj, prop).but.not.by(delta);
};
assert3.decreases = function(fn2, obj, prop, msg) {
return arguments.length === 3 && typeof obj == "function" && (msg = prop, prop = null), new Assertion(fn2, msg, assert3.decreases, !0).to.decrease(obj, prop);
};
assert3.decreasesBy = function(fn2, obj, prop, delta, msg) {
if (arguments.length === 4 && typeof obj == "function") {
let tmpMsg = delta;
delta = prop, msg = tmpMsg;
} else arguments.length === 3 && (delta = prop, prop = null);
new Assertion(fn2, msg, assert3.decreasesBy, !0).to.decrease(obj, prop).by(delta);
};
assert3.doesNotDecrease = function(fn2, obj, prop, msg) {
return arguments.length === 3 && typeof obj == "function" && (msg = prop, prop = null), new Assertion(fn2, msg, assert3.doesNotDecrease, !0).to.not.decrease(
obj,
prop
);
};
assert3.doesNotDecreaseBy = function(fn2, obj, prop, delta, msg) {
if (arguments.length === 4 && typeof obj == "function") {
let tmpMsg = delta;
delta = prop, msg = tmpMsg;
} else arguments.length === 3 && (delta = prop, prop = null);
return new Assertion(fn2, msg, assert3.doesNotDecreaseBy, !0).to.not.decrease(obj, prop).by(delta);
};
assert3.decreasesButNotBy = function(fn2, obj, prop, delta, msg) {
if (arguments.length === 4 && typeof obj == "function") {
let tmpMsg = delta;
delta = prop, msg = tmpMsg;
} else arguments.length === 3 && (delta = prop, prop = null);
new Assertion(fn2, msg, assert3.decreasesButNotBy, !0).to.decrease(obj, prop).but.not.by(delta);
};
assert3.ifError = function(val) {
if (val)
throw val;
};
assert3.isExtensible = function(obj, msg) {
new Assertion(obj, msg, assert3.isExtensible, !0).to.be.extensible;
};
assert3.isNotExtensible = function(obj, msg) {
new Assertion(obj, msg, assert3.isNotExtensible, !0).to.not.be.extensible;
};
assert3.isSealed = function(obj, msg) {
new Assertion(obj, msg, assert3.isSealed, !0).to.be.sealed;
};
assert3.isNotSealed = function(obj, msg) {
new Assertion(obj, msg, assert3.isNotSealed, !0).to.not.be.sealed;
};
assert3.isFrozen = function(obj, msg) {
new Assertion(obj, msg, assert3.isFrozen, !0).to.be.frozen;
};
assert3.isNotFrozen = function(obj, msg) {
new Assertion(obj, msg, assert3.isNotFrozen, !0).to.not.be.frozen;
};
assert3.isEmpty = function(val, msg) {
new Assertion(val, msg, assert3.isEmpty, !0).to.be.empty;
};
assert3.isNotEmpty = function(val, msg) {
new Assertion(val, msg, assert3.isNotEmpty, !0).to.not.be.empty;
};
assert3.containsSubset = function(val, exp, msg) {
new Assertion(val, msg).to.containSubset(exp);
};
assert3.doesNotContainSubset = function(val, exp, msg) {
new Assertion(val, msg).to.not.containSubset(exp);
};
var aliases = [
["isOk", "ok"],
["isNotOk", "notOk"],
["throws", "throw"],
["throws", "Throw"],
["isExtensible", "extensible"],
["isNotExtensible", "notExtensible"],
["isSealed", "sealed"],
["isNotSealed", "notSealed"],
["isFrozen", "frozen"],
["isNotFrozen", "notFrozen"],
["isEmpty", "empty"],
["isNotEmpty", "notEmpty"],
["isCallable", "isFunction"],
["isNotCallable", "isNotFunction"],
["containsSubset", "containSubset"]
];
for (let [name, as] of aliases)
assert3[as] = assert3[name];
var used = [];
function use(fn2) {
let exports = {
use,
AssertionError,
util: utils_exports,
config,
expect,
assert: assert3,
Assertion,
...should_exports
};
return ~used.indexOf(fn2) || (fn2(exports, utils_exports), used.push(fn2)), exports;
}
__name(use, "use");
// ../../node_modules/.pnpm/@vitest+expect@4.1.10/node_modules/@vitest/expect/dist/index.js
var ChaiStyleAssertions = (chai, utils) => {
function defProperty(name, delegateTo) {
utils.addProperty(chai.Assertion.prototype, name, function() {
let jestMethod = chai.Assertion.prototype[delegateTo];
if (!jestMethod)
throw new Error(`Cannot delegate to ${String(delegateTo)}: method not found. Ensure JestChaiExpect plugin is loaded first.`);
return jestMethod.call(this);
});
}
function defPropertyWithArgs(name, delegateTo, ...args) {
utils.addProperty(chai.Assertion.prototype, name, function() {
let jestMethod = chai.Assertion.prototype[delegateTo];
if (!jestMethod)
throw new Error(`Cannot delegate to ${String(delegateTo)}: method not found. Ensure JestChaiExpect plugin is loaded first.`);
return jestMethod.call(this, ...args);
});
}
function defMethod(name, delegateTo) {
utils.addMethod(chai.Assertion.prototype, name, function(...args) {
let jestMethod = chai.Assertion.prototype[delegateTo];
if (!jestMethod)
throw new Error(`Cannot delegate to ${String(delegateTo)}: method not found. Ensure JestChaiExpect plugin is loaded first.`);
return jestMethod.call(this, ...args);
});
}
defProperty("called", "toHaveBeenCalled"), defProperty("calledOnce", "toHaveBeenCalledOnce"), defPropertyWithArgs("calledTwice", "toHaveBeenCalledTimes", 2), defPropertyWithArgs("calledThrice", "toHaveBeenCalledTimes", 3), defMethod("callCount", "toHaveBeenCalledTimes"), defMethod("calledWith", "toHaveBeenCalledWith"), defMethod("calledOnceWith", "toHaveBeenCalledExactlyOnceWith"), defMethod("lastCalledWith", "toHaveBeenLastCalledWith"), defMethod("nthCalledWith", "toHaveBeenNthCalledWith"), defMethod("returned", "toHaveReturned"), defMethod("returnedWith", "toHaveReturnedWith"), defMethod("returnedTimes", "toHaveReturnedTimes"), defMethod("lastReturnedWith", "toHaveLastReturnedWith"), defMethod("nthReturnedWith", "toHaveNthReturnedWith"), defMethod("calledBefore", "toHaveBeenCalledBefore"), defMethod("calledAfter", "toHaveBeenCalledAfter");
}, MATCHERS_OBJECT = /* @__PURE__ */ Symbol.for("matchers-object"), JEST_MATCHERS_OBJECT = /* @__PURE__ */ Symbol.for("$$jest-matchers-object"), GLOBAL_EXPECT = /* @__PURE__ */ Symbol.for("expect-global"), ASYMMETRIC_MATCHERS_OBJECT = /* @__PURE__ */ Symbol.for("asymmetric-matchers-object"), customMatchers = {
toSatisfy(actual, expected, message) {
let { printReceived: printReceived3, printExpected: printExpected3, matcherHint: matcherHint2 } = this.utils, pass = expected(actual);
return {
pass,
message: () => pass ? `${matcherHint2(".not.toSatisfy", "received", "")}
Expected value to not satisfy:
${message || printExpected3(expected)}
Received:
${printReceived3(actual)}` : `${matcherHint2(".toSatisfy", "received", "")}
Expected value to satisfy:
${message || printExpected3(expected)}
Received:
${printReceived3(actual)}`
};
},
toBeOneOf(actual, expected) {
let { equals: equals2, customTesters } = this, { printReceived: printReceived3, printExpected: printExpected3, matcherHint: matcherHint2 } = this.utils, pass;
if (Array.isArray(expected))
pass = expected.length === 0 || expected.some((item) => equals2(item, actual, customTesters));
else if (expected instanceof Set)
pass = expected.size === 0 || expected.has(actual) || [...expected].some((item) => equals2(item, actual, customTesters));
else
throw new TypeError(`You must provide an array or set to ${matcherHint2(".toBeOneOf")}, not '${typeof expected}'.`);
return {
pass,
message: () => pass ? `${matcherHint2(".not.toBeOneOf", "received", "")}
Expected value to not be one of:
${printExpected3(expected)}
Received:
${printReceived3(actual)}` : `${matcherHint2(".toBeOneOf", "received", "")}
Expected value to be one of:
${printExpected3(expected)}
Received:
${printReceived3(actual)}`
};
}
}, EXPECTED_COLOR = y.green, RECEIVED_COLOR = y.red, INVERTED_COLOR = y.inverse, BOLD_WEIGHT = y.bold, DIM_COLOR = y.dim;
function matcherHint(matcherName, received = "received", expected = "expected", options = {}) {
let { comment = "", isDirectExpectCall = !1, isNot = !1, promise = "", secondArgument = "", expectedColor = EXPECTED_COLOR, receivedColor = RECEIVED_COLOR, secondArgumentColor = EXPECTED_COLOR } = options, hint = "", dimString = "expect";
return !isDirectExpectCall && received !== "" && (hint += DIM_COLOR(`${dimString}(`) + receivedColor(received), dimString = ")"), promise !== "" && (hint += DIM_COLOR(`${dimString}.`) + promise, dimString = ""), isNot && (hint += `${DIM_COLOR(`${dimString}.`)}not`, dimString = ""), matcherName.includes(".") ? dimString += matcherName : (hint += DIM_COLOR(`${dimString}.`) + matcherName, dimString = ""), expected === "" ? dimString += "()" : (hint += DIM_COLOR(`${dimString}(`) + expectedColor(expected), secondArgument && (hint += DIM_COLOR(", ") + secondArgumentColor(secondArgument)), dimString = ")"), comment !== "" && (dimString += ` // ${comment}`), dimString !== "" && (hint += DIM_COLOR(dimString)), hint;
}
var SPACE_SYMBOL2 = "\xB7";
function replaceTrailingSpaces2(text) {
return text.replace(/\s+$/gm, (spaces) => SPACE_SYMBOL2.repeat(spaces.length));
}
function printReceived2(object2) {
return RECEIVED_COLOR(replaceTrailingSpaces2(stringify(object2)));
}
function printExpected2(value) {
return EXPECTED_COLOR(replaceTrailingSpaces2(stringify(value)));
}
function getMatcherUtils() {
return {
EXPECTED_COLOR,
RECEIVED_COLOR,
INVERTED_COLOR,
BOLD_WEIGHT,
DIM_COLOR,
diff,
matcherHint,
printReceived: printReceived2,
printExpected: printExpected2,
printDiffOrStringify,
printWithType
};
}
function printWithType(name, value, print) {
let type3 = getType2(value), hasType = type3 !== "null" && type3 !== "undefined" ? `${name} has type: ${type3}
` : "", hasValue = `${name} has value: ${print(value)}`;
return hasType + hasValue;
}
function addCustomEqualityTesters(newTesters) {
if (!Array.isArray(newTesters))
throw new TypeError(`expect.customEqualityTesters: Must be set to an array of Testers. Was given "${getType2(newTesters)}"`);
globalThis[JEST_MATCHERS_OBJECT].customEqualityTesters.push(...newTesters);
}
function getCustomEqualityTesters() {
return globalThis[JEST_MATCHERS_OBJECT].customEqualityTesters;
}
function equals(a, b2, customTesters, strictCheck) {
return customTesters = customTesters || [], eq(a, b2, [], [], customTesters, strictCheck ? hasKey : hasDefinedKey);
}
var functionToString = Function.prototype.toString;
function isAsymmetric(obj) {
return !!obj && typeof obj == "object" && "asymmetricMatch" in obj && isA("Function", obj.asymmetricMatch);
}
function asymmetricMatch(a, b2, customTesters) {
let asymmetricA = isAsymmetric(a), asymmetricB = isAsymmetric(b2);
if (!(asymmetricA && asymmetricB)) {
if (asymmetricA)
return a.asymmetricMatch(b2, customTesters);
if (asymmetricB)
return b2.asymmetricMatch(a, customTesters);
}
}
function isError(value) {
if (typeof Error.isError == "function")
return Error.isError(value);
switch (Object.prototype.toString.call(value)) {
case "[object Error]":
case "[object Exception]":
case "[object DOMException]":
return !0;
default:
return value instanceof Error;
}
}
function eq(a, b2, aStack, bStack, customTesters, hasKey2) {
let result = !0, asymmetricResult = asymmetricMatch(a, b2, customTesters);
if (asymmetricResult !== void 0)
return asymmetricResult;
let testerContext = { equals };
for (let i2 = 0; i2 < customTesters.length; i2++) {
let customTesterResult = customTesters[i2].call(testerContext, a, b2, customTesters);
if (customTesterResult !== void 0)
return customTesterResult;
}
if (typeof URL == "function" && a instanceof URL && b2 instanceof URL)
return a.href === b2.href;
if (Object.is(a, b2))
return !0;
if (a === null || b2 === null)
return a === b2;
let className = Object.prototype.toString.call(a);
if (className !== Object.prototype.toString.call(b2))
return !1;
switch (className) {
case "[object Boolean]":
case "[object String]":
case "[object Number]":
return typeof a != typeof b2 ? !1 : typeof a != "object" && typeof b2 != "object" ? Object.is(a, b2) : Object.is(a.valueOf(), b2.valueOf());
case "[object Date]": {
let numA = +a, numB = +b2;
return numA === numB || Number.isNaN(numA) && Number.isNaN(numB);
}
case "[object RegExp]":
return a.source === b2.source && a.flags === b2.flags;
case "[object Temporal.Instant]":
case "[object Temporal.ZonedDateTime]":
case "[object Temporal.PlainDateTime]":
case "[object Temporal.PlainDate]":
case "[object Temporal.PlainTime]":
case "[object Temporal.PlainYearMonth]":
case "[object Temporal.PlainMonthDay]":
return a.equals(b2);
case "[object Temporal.Duration]":
return a.toString() === b2.toString();
}
if (typeof a != "object" || typeof b2 != "object")
return !1;
if (isDomNode(a) && isDomNode(b2))
return a.isEqualNode(b2);
let length = aStack.length;
for (; length--; ) {
if (aStack[length] === a)
return bStack[length] === b2;
if (bStack[length] === b2)
return !1;
}
if (aStack.push(a), bStack.push(b2), className === "[object Array]" && a.length !== b2.length)
return !1;
if (isError(a) && isError(b2))
try {
return isErrorEqual(a, b2, aStack, bStack, customTesters, hasKey2);
} finally {
aStack.pop(), bStack.pop();
}
let aKeys = keys(a, hasKey2), key, size = aKeys.length;
if (keys(b2, hasKey2).length !== size)
return !1;
for (; size--; )
if (key = aKeys[size], result = hasKey2(b2, key) && eq(a[key], b2[key], aStack, bStack, customTesters, hasKey2), !result)
return !1;
return aStack.pop(), bStack.pop(), result;
}
function isErrorEqual(a, b2, aStack, bStack, customTesters, hasKey2) {
let result = Object.prototype.toString.call(a) === Object.prototype.toString.call(b2) && a.name === b2.name && a.message === b2.message;
return typeof b2.cause < "u" && (result &&= eq(a.cause, b2.cause, aStack, bStack, customTesters, hasKey2)), a instanceof AggregateError && b2 instanceof AggregateError && (result &&= eq(a.errors, b2.errors, aStack, bStack, customTesters, hasKey2)), result &&= eq({ ...a }, { ...b2 }, aStack, bStack, customTesters, hasKey2), result;
}
function keys(obj, hasKey2) {
let keys2 = [];
for (let key in obj)
hasKey2(obj, key) && keys2.push(key);
return keys2.concat(Object.getOwnPropertySymbols(obj).filter((symbol) => Object.getOwnPropertyDescriptor(obj, symbol).enumerable));
}
function hasDefinedKey(obj, key) {
return hasKey(obj, key) && obj[key] !== void 0;
}
function hasKey(obj, key) {
return Object.hasOwn(obj, key);
}
function isA(typeName, value) {
return Object.prototype.toString.apply(value) === `[object ${typeName}]`;
}
function isDomNode(obj) {
return obj !== null && typeof obj == "object" && "nodeType" in obj && typeof obj.nodeType == "number" && "nodeName" in obj && typeof obj.nodeName == "string" && "isEqualNode" in obj && typeof obj.isEqualNode == "function";
}
var IS_KEYED_SENTINEL2 = "@@__IMMUTABLE_KEYED__@@", IS_SET_SENTINEL2 = "@@__IMMUTABLE_SET__@@", IS_LIST_SENTINEL2 = "@@__IMMUTABLE_LIST__@@", IS_ORDERED_SENTINEL2 = "@@__IMMUTABLE_ORDERED__@@", IS_RECORD_SYMBOL2 = "@@__IMMUTABLE_RECORD__@@";
function isImmutableUnorderedKeyed(maybeKeyed) {
return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL2] && !maybeKeyed[IS_ORDERED_SENTINEL2]);
}
function isImmutableUnorderedSet(maybeSet) {
return !!(maybeSet && maybeSet[IS_SET_SENTINEL2] && !maybeSet[IS_ORDERED_SENTINEL2]);
}
function isObjectLiteral(source) {
return source != null && typeof source == "object" && !Array.isArray(source);
}
function isImmutableList(source) {
return !!(source && isObjectLiteral(source) && source[IS_LIST_SENTINEL2]);
}
function isImmutableOrderedKeyed(source) {
return !!(source && isObjectLiteral(source) && source[IS_KEYED_SENTINEL2] && source[IS_ORDERED_SENTINEL2]);
}
function isImmutableOrderedSet(source) {
return !!(source && isObjectLiteral(source) && source[IS_SET_SENTINEL2] && source[IS_ORDERED_SENTINEL2]);
}
function isImmutableRecord(source) {
return !!(source && isObjectLiteral(source) && source[IS_RECORD_SYMBOL2]);
}
var IteratorSymbol = Symbol.iterator;
function hasIterator(object2) {
return !!(object2 != null && object2[IteratorSymbol]);
}
function iterableEquality(a, b2, customTesters = [], aStack = [], bStack = []) {
if (typeof a != "object" || typeof b2 != "object" || Array.isArray(a) || Array.isArray(b2) || !hasIterator(a) || !hasIterator(b2))
return;
if (a.constructor !== b2.constructor)
return !1;
let length = aStack.length;
for (; length--; )
if (aStack[length] === a)
return bStack[length] === b2;
aStack.push(a), bStack.push(b2);
let filteredCustomTesters = [...customTesters.filter((t) => t !== iterableEquality), iterableEqualityWithStack];
function iterableEqualityWithStack(a2, b3) {
return iterableEquality(a2, b3, [...customTesters], [...aStack], [...bStack]);
}
if (a.size !== void 0) {
if (a.size !== b2.size)
return !1;
if (isA("Set", a) || isImmutableUnorderedSet(a)) {
let allFound = !0;
for (let aValue of a)
if (!b2.has(aValue)) {
let has = !1;
for (let bValue of b2)
equals(aValue, bValue, filteredCustomTesters) === !0 && (has = !0);
if (has === !1) {
allFound = !1;
break;
}
}
return aStack.pop(), bStack.pop(), allFound;
} else if (isA("Map", a) || isImmutableUnorderedKeyed(a)) {
let allFound = !0;
for (let aEntry of a)
if (!b2.has(aEntry[0]) || !equals(aEntry[1], b2.get(aEntry[0]), filteredCustomTesters)) {
let has = !1;
for (let bEntry of b2) {
let matchedKey = equals(aEntry[0], bEntry[0], filteredCustomTesters), matchedValue = !1;
matchedKey === !0 && (matchedValue = equals(aEntry[1], bEntry[1], filteredCustomTesters)), matchedValue === !0 && (has = !0);
}
if (has === !1) {
allFound = !1;
break;
}
}
return aStack.pop(), bStack.pop(), allFound;
}
}
let bIterator = b2[IteratorSymbol]();
for (let aValue of a) {
let nextB = bIterator.next();
if (nextB.done || !equals(aValue, nextB.value, filteredCustomTesters))
return !1;
}
if (!bIterator.next().done)
return !1;
if (!isImmutableList(a) && !isImmutableOrderedKeyed(a) && !isImmutableOrderedSet(a) && !isImmutableRecord(a)) {
let aEntries = Object.entries(a), bEntries = Object.entries(b2);
if (!equals(aEntries, bEntries, filteredCustomTesters))
return !1;
}
return aStack.pop(), bStack.pop(), !0;
}
function hasPropertyInObject(object2, key) {
return !object2 || typeof object2 != "object" || object2 === Object.prototype ? !1 : Object.hasOwn(object2, key) || hasPropertyInObject(Object.getPrototypeOf(object2), key);
}
function isObjectWithKeys(a) {
return isObject(a) && !isError(a) && !Array.isArray(a) && !(a instanceof Date) && !(a instanceof Set) && !(a instanceof Map);
}
function subsetEquality(object2, subset, customTesters = []) {
let filteredCustomTesters = customTesters.filter((t) => t !== subsetEquality), subsetEqualityWithContext = (seenReferences = /* @__PURE__ */ new WeakMap()) => (object3, subset2) => {
if (isObjectWithKeys(subset2))
return Object.keys(subset2).every((key) => {
if (subset2[key] != null && typeof subset2[key] == "object") {
if (seenReferences.has(subset2[key]))
return equals(object3[key], subset2[key], filteredCustomTesters);
seenReferences.set(subset2[key], !0);
}
let result = object3 != null && hasPropertyInObject(object3, key) && equals(object3[key], subset2[key], [...filteredCustomTesters, subsetEqualityWithContext(seenReferences)]);
return seenReferences.delete(subset2[key]), result;
});
};
return subsetEqualityWithContext()(object2, subset);
}
function typeEquality(a, b2) {
if (!(a == null || b2 == null || a.constructor === b2.constructor))
return !1;
}
function arrayBufferEquality(a, b2) {
let dataViewA = a, dataViewB = b2;
if (!(a instanceof DataView && b2 instanceof DataView)) {
if (!(a instanceof ArrayBuffer) || !(b2 instanceof ArrayBuffer))
return;
try {
dataViewA = new DataView(a), dataViewB = new DataView(b2);
} catch {
return;
}
}
if (dataViewA.byteLength !== dataViewB.byteLength)
return !1;
for (let i2 = 0; i2 < dataViewA.byteLength; i2++)
if (dataViewA.getUint8(i2) !== dataViewB.getUint8(i2))
return !1;
return !0;
}
function sparseArrayEquality(a, b2, customTesters = []) {
if (!Array.isArray(a) || !Array.isArray(b2))
return;
let aKeys = Object.keys(a), bKeys = Object.keys(b2), filteredCustomTesters = customTesters.filter((t) => t !== sparseArrayEquality);
return equals(a, b2, filteredCustomTesters, !0) && equals(aKeys, bKeys);
}
function generateToBeMessage(deepEqualityName, expected = "#{this}", actual = "#{exp}") {
let toBeMessage = `expected ${expected} to be ${actual} // Object.is equality`;
return ["toStrictEqual", "toEqual"].includes(deepEqualityName) ? `${toBeMessage}
If it should pass with deep equality, replace "toBe" with "${deepEqualityName}"
Expected: ${expected}
Received: serializes to the same string
` : toBeMessage;
}
function pluralize(word, count) {
return `${count} ${word}${count === 1 ? "" : "s"}`;
}
function getObjectKeys(object2) {
return [...Object.keys(object2), ...Object.getOwnPropertySymbols(object2).filter((s) => Object.getOwnPropertyDescriptor(object2, s)?.enumerable)];
}
function getObjectSubset(object2, subset, customTesters) {
let stripped = 0, getObjectSubsetWithContext = (seenReferences = /* @__PURE__ */ new WeakMap()) => (object3, subset2) => {
if (Array.isArray(object3)) {
if (Array.isArray(subset2) && subset2.length === object3.length)
return subset2.map((sub, i2) => getObjectSubsetWithContext(seenReferences)(object3[i2], sub));
} else {
if (object3 instanceof Date)
return object3;
if (isObject(object3) && isObject(subset2)) {
if (equals(object3, subset2, [
...customTesters,
iterableEquality,
subsetEquality
]))
return subset2;
let trimmed = {};
seenReferences.set(object3, trimmed), typeof object3.constructor == "function" && typeof object3.constructor.name == "string" && Object.defineProperty(trimmed, "constructor", {
enumerable: !1,
value: object3.constructor
});
for (let key of getObjectKeys(object3))
hasPropertyInObject(subset2, key) ? trimmed[key] = seenReferences.has(object3[key]) ? seenReferences.get(object3[key]) : getObjectSubsetWithContext(seenReferences)(object3[key], subset2[key]) : seenReferences.has(object3[key]) || (stripped += 1, isObject(object3[key]) && (stripped += getObjectKeys(object3[key]).length), getObjectSubsetWithContext(seenReferences)(object3[key], subset2[key]));
if (getObjectKeys(trimmed).length > 0)
return trimmed;
}
}
return object3;
};
return {
subset: getObjectSubsetWithContext()(object2, subset),
stripped
};
}
function isStandardSchema(obj) {
return !!obj && (typeof obj == "object" || typeof obj == "function") && obj["~standard"] && typeof obj["~standard"].validate == "function";
}
if (!Object.hasOwn(globalThis, MATCHERS_OBJECT)) {
let globalState = /* @__PURE__ */ new WeakMap(), matchers = /* @__PURE__ */ Object.create(null), customEqualityTesters = [], asymmetricMatchers = /* @__PURE__ */ Object.create(null);
Object.defineProperty(globalThis, MATCHERS_OBJECT, { get: () => globalState }), Object.defineProperty(globalThis, JEST_MATCHERS_OBJECT, {
configurable: !0,
get: () => ({
state: globalState.get(globalThis[GLOBAL_EXPECT]),
matchers,
customEqualityTesters
})
}), Object.defineProperty(globalThis, ASYMMETRIC_MATCHERS_OBJECT, { get: () => asymmetricMatchers });
}
function getState(expect2) {
return globalThis[MATCHERS_OBJECT].get(expect2);
}
function setState(state, expect2) {
let map2 = globalThis[MATCHERS_OBJECT], current = map2.get(expect2) || {}, results = Object.defineProperties(current, {
...Object.getOwnPropertyDescriptors(current),
...Object.getOwnPropertyDescriptors(state)
});
map2.set(expect2, results);
}
var AsymmetricMatcher3 = class {
// should have "jest" to be compatible with its ecosystem
$$typeof = /* @__PURE__ */ Symbol.for("jest.asymmetricMatcher");
constructor(sample, inverse = !1) {
this.sample = sample, this.inverse = inverse;
}
getMatcherContext(expect2) {
return {
...getState(expect2 || globalThis[GLOBAL_EXPECT]),
equals,
isNot: this.inverse,
customTesters: getCustomEqualityTesters(),
utils: {
...getMatcherUtils(),
diff,
stringify,
iterableEquality,
subsetEquality
}
};
}
};
AsymmetricMatcher3.prototype[/* @__PURE__ */ Symbol.for("chai/inspect")] = function(options) {
let result = stringify(this, options.depth, { min: !0 });
return result.length <= options.truncate ? result : `${this.toString()}{\u2026}`;
};
var StringContaining = class extends AsymmetricMatcher3 {
constructor(sample, inverse = !1) {
if (!isA("String", sample))
throw new Error("Expected is not a string");
super(sample, inverse);
}
asymmetricMatch(other) {
let result = isA("String", other) && other.includes(this.sample);
return this.inverse ? !result : result;
}
toString() {
return `String${this.inverse ? "Not" : ""}Containing`;
}
getExpectedType() {
return "string";
}
}, Anything = class extends AsymmetricMatcher3 {
asymmetricMatch(other) {
return other != null;
}
toString() {
return "Anything";
}
toAsymmetricMatcher() {
return "Anything";
}
}, ObjectContaining = class extends AsymmetricMatcher3 {
constructor(sample, inverse = !1) {
super(sample, inverse);
}
getPrototype(obj) {
return Object.getPrototypeOf ? Object.getPrototypeOf(obj) : obj.constructor.prototype === obj ? null : obj.constructor.prototype;
}
hasProperty(obj, property) {
return obj ? Object.hasOwn(obj, property) ? !0 : this.hasProperty(this.getPrototype(obj), property) : !1;
}
getProperties(obj) {
return [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj).filter((s) => Object.getOwnPropertyDescriptor(obj, s)?.enumerable)];
}
asymmetricMatch(other, customTesters) {
if (typeof this.sample != "object")
throw new TypeError(`You must provide an object to ${this.toString()}, not '${typeof this.sample}'.`);
let result = !0, properties = this.getProperties(this.sample);
for (let property of properties) {
if (!this.hasProperty(other, property)) {
result = !1;
break;
}
let value = this.sample[property], otherValue = other[property];
if (!equals(value, otherValue, customTesters)) {
result = !1;
break;
}
}
return this.inverse ? !result : result;
}
toString() {
return `Object${this.inverse ? "Not" : ""}Containing`;
}
getExpectedType() {
return "object";
}
}, ArrayContaining = class extends AsymmetricMatcher3 {
constructor(sample, inverse = !1) {
super(sample, inverse);
}
asymmetricMatch(other, customTesters) {
if (!Array.isArray(this.sample))
throw new TypeError(`You must provide an array to ${this.toString()}, not '${typeof this.sample}'.`);
let result = this.sample.length === 0 || Array.isArray(other) && this.sample.every((item) => other.some((another) => equals(item, another, customTesters)));
return this.inverse ? !result : result;
}
toString() {
return `Array${this.inverse ? "Not" : ""}Containing`;
}
getExpectedType() {
return "array";
}
}, Any = class extends AsymmetricMatcher3 {
constructor(sample) {
if (typeof sample > "u")
throw new TypeError("any() expects to be passed a constructor function. Please pass one or use anything() to match any object.");
super(sample);
}
fnNameFor(func) {
if (func.name)
return func.name;
let matches = Function.prototype.toString.call(func).match(/^(?:async)?\s*function\s*(?:\*\s*)?([\w$]+)\s*\(/);
return matches ? matches[1] : "<anonymous>";
}
asymmetricMatch(other) {
return this.sample === String ? typeof other == "string" || other instanceof String : this.sample === Number ? typeof other == "number" || other instanceof Number : this.sample === Function ? typeof other == "function" || typeof other == "function" : this.sample === Boolean ? typeof other == "boolean" || other instanceof Boolean : this.sample === BigInt ? typeof other == "bigint" || other instanceof BigInt : this.sample === Symbol ? typeof other == "symbol" || other instanceof Symbol : this.sample === Object ? typeof other == "object" : other instanceof this.sample;
}
toString() {
return "Any";
}
getExpectedType() {
return this.sample === String ? "string" : this.sample === Number ? "number" : this.sample === Function ? "function" : this.sample === Object ? "object" : this.sample === Boolean ? "boolean" : this.fnNameFor(this.sample);
}
toAsymmetricMatcher() {
return `Any<${this.fnNameFor(this.sample)}>`;
}
}, StringMatching = class extends AsymmetricMatcher3 {
constructor(sample, inverse = !1) {
if (!isA("String", sample) && !isA("RegExp", sample))
throw new Error("Expected is not a String or a RegExp");
super(new RegExp(sample), inverse);
}
asymmetricMatch(other) {
let result = isA("String", other) && this.sample.test(other);
return this.inverse ? !result : result;
}
toString() {
return `String${this.inverse ? "Not" : ""}Matching`;
}
getExpectedType() {
return "string";
}
}, CloseTo = class extends AsymmetricMatcher3 {
precision;
constructor(sample, precision = 2, inverse = !1) {
if (!isA("Number", sample))
throw new Error("Expected is not a Number");
if (!isA("Number", precision))
throw new Error("Precision is not a Number");
super(sample), this.inverse = inverse, this.precision = precision;
}
asymmetricMatch(other) {
if (!isA("Number", other))
return !1;
let result = !1;
return other === Number.POSITIVE_INFINITY && this.sample === Number.POSITIVE_INFINITY || other === Number.NEGATIVE_INFINITY && this.sample === Number.NEGATIVE_INFINITY ? result = !0 : result = Math.abs(this.sample - other) < 10 ** -this.precision / 2, this.inverse ? !result : result;
}
toString() {
return `Number${this.inverse ? "Not" : ""}CloseTo`;
}
getExpectedType() {
return "number";
}
toAsymmetricMatcher() {
return [
this.toString(),
this.sample,
`(${pluralize("digit", this.precision)})`
].join(" ");
}
}, SchemaMatching = class extends AsymmetricMatcher3 {
result;
constructor(sample, inverse = !1) {
if (!isStandardSchema(sample))
throw new TypeError("SchemaMatching expected to receive a Standard Schema.");
super(sample, inverse);
}
asymmetricMatch(other) {
let result = this.sample["~standard"].validate(other);
if (result instanceof Promise)
throw new TypeError("Async schema validation is not supported in asymmetric matchers.");
this.result = result;
let pass = !this.result.issues || this.result.issues.length === 0;
return this.inverse ? !pass : pass;
}
toString() {
return `Schema${this.inverse ? "Not" : ""}Matching`;
}
getExpectedType() {
return "object";
}
toAsymmetricMatcher() {
let { utils } = this.getMatcherContext();
return (this.result?.issues || []).length > 0 ? `${this.toString()} ${utils.stringify(this.result, void 0, { printBasicPrototype: !1 })}` : this.toString();
}
}, JestAsymmetricMatchers = (chai, utils) => {
utils.addMethod(chai.expect, "anything", () => new Anything()), utils.addMethod(chai.expect, "any", (expected) => new Any(expected)), utils.addMethod(chai.expect, "stringContaining", (expected) => new StringContaining(expected)), utils.addMethod(chai.expect, "objectContaining", (expected) => new ObjectContaining(expected)), utils.addMethod(chai.expect, "arrayContaining", (expected) => new ArrayContaining(expected)), utils.addMethod(chai.expect, "stringMatching", (expected) => new StringMatching(expected)), utils.addMethod(chai.expect, "closeTo", (expected, precision) => new CloseTo(expected, precision)), utils.addMethod(chai.expect, "schemaMatching", (expected) => new SchemaMatching(expected)), chai.expect.not = {
stringContaining: (expected) => new StringContaining(expected, !0),
objectContaining: (expected) => new ObjectContaining(expected, !0),
arrayContaining: (expected) => new ArrayContaining(expected, !0),
stringMatching: (expected) => new StringMatching(expected, !0),
closeTo: (expected, precision) => new CloseTo(expected, precision, !0),
schemaMatching: (expected) => new SchemaMatching(expected, !0)
};
};
function createAssertionMessage(util, assertion, hasArgs) {
let soft = util.flag(assertion, "soft") ? ".soft" : "", not = util.flag(assertion, "negate") ? "not." : "", name = `${util.flag(assertion, "_name")}(${hasArgs ? "expected" : ""})`, promiseName = util.flag(assertion, "promise"), promise = promiseName ? `.${promiseName}` : "";
return `expect${soft}(actual)${promise}.${not}${name}`;
}
function recordAsyncExpect(_test2, promise, assertion, error, isSoft) {
let test5 = _test2;
if (test5 && promise instanceof Promise) {
promise = promise.finally(() => {
if (!test5.promises)
return;
let index2 = test5.promises.indexOf(promise);
index2 !== -1 && test5.promises.splice(index2, 1);
}), test5.promises || (test5.promises = []), isSoft && (promise = promise.then(noop, (err) => {
handleTestError(test5, err);
})), test5.promises.push(promise);
let resolved = !1;
return test5.onFinished ??= [], test5.onFinished.push(() => {
if (!resolved) {
let stack = (globalThis.__vitest_worker__?.onFilterStackTrace || ((s) => s || ""))(error.stack);
console.warn([
`Promise returned by \`${assertion}\` was not awaited. `,
"Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in the next Vitest major. ",
`Please remember to await the assertion.
`,
stack
].join(""));
}
}), {
then(onFulfilled, onRejected) {
return resolved = !0, promise.then(onFulfilled, onRejected);
},
catch(onRejected) {
return resolved = !0, promise.catch(onRejected);
},
finally(onFinally) {
return resolved = !0, promise.finally(onFinally);
},
[Symbol.toStringTag]: "Promise"
};
}
return promise;
}
function handleTestError(test5, err) {
test5.result ||= { state: "fail" }, test5.result.state = "fail", test5.result.errors ||= [], test5.result.errors.push(processError(err));
}
function wrapAssertion(utils, name, fn2) {
return function(...args) {
if (name !== "withTest" && utils.flag(this, "_name", name), !utils.flag(this, "soft"))
return fn2.apply(this, args);
let test5 = utils.flag(this, "vitest-test");
if (!test5)
throw new Error("expect.soft() can only be used inside a test");
try {
let result = fn2.apply(this, args);
return result && typeof result == "object" && typeof result.then == "function" ? result.then(noop, (err) => {
handleTestError(test5, err);
}) : result;
} catch (err) {
handleTestError(test5, err);
}
};
}
var JestChaiExpect = (chai, utils) => {
let { AssertionError: AssertionError2 } = chai, customTesters = getCustomEqualityTesters();
function def(name, fn2) {
let addMethod2 = (n) => {
let softWrapper = wrapAssertion(utils, n, fn2);
utils.addMethod(chai.Assertion.prototype, n, softWrapper), utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, n, softWrapper);
};
Array.isArray(name) ? name.forEach((n) => addMethod2(n)) : addMethod2(name);
}
[
"throw",
"throws",
"Throw"
].forEach((m) => {
utils.overwriteMethod(chai.Assertion.prototype, m, (_super) => function(...args) {
let promise = utils.flag(this, "promise"), object2 = utils.flag(this, "object"), isNot = utils.flag(this, "negate");
if (promise === "rejects")
utils.flag(this, "object", () => {
throw object2;
});
else if (promise === "resolves" && typeof object2 != "function") {
if (isNot)
return;
{
let message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't", error = { showDiff: !1 };
throw new AssertionError2(message, error, utils.flag(this, "ssfi"));
}
}
_super.apply(this, args);
});
}), def("withTest", function(test5) {
return utils.flag(this, "vitest-test", test5), this;
}), def("toEqual", function(expected) {
let actual = utils.flag(this, "object"), equal = equals(actual, expected, [...customTesters, iterableEquality]);
return this.assert(equal, "expected #{this} to deeply equal #{exp}", "expected #{this} to not deeply equal #{exp}", expected, actual);
}), def("toStrictEqual", function(expected) {
let obj = utils.flag(this, "object"), equal = equals(obj, expected, [
...customTesters,
iterableEquality,
typeEquality,
sparseArrayEquality,
arrayBufferEquality
], !0);
return this.assert(equal, "expected #{this} to strictly equal #{exp}", "expected #{this} to not strictly equal #{exp}", expected, obj);
}), def("toBe", function(expected) {
let actual = this._obj, pass = Object.is(actual, expected), deepEqualityName = "";
return pass || (equals(actual, expected, [
...customTesters,
iterableEquality,
typeEquality,
sparseArrayEquality,
arrayBufferEquality
], !0) ? deepEqualityName = "toStrictEqual" : equals(actual, expected, [...customTesters, iterableEquality]) && (deepEqualityName = "toEqual")), this.assert(pass, generateToBeMessage(deepEqualityName), "expected #{this} not to be #{exp} // Object.is equality", expected, actual);
}), def("toMatchObject", function(expected) {
let actual = this._obj, pass = equals(actual, expected, [
...customTesters,
iterableEquality,
subsetEquality
]), isNot = utils.flag(this, "negate"), { subset: actualSubset, stripped } = getObjectSubset(actual, expected, customTesters);
if (pass && isNot || !pass && !isNot) {
let msg = utils.getMessage(this, [
pass,
"expected #{this} to match object #{exp}",
"expected #{this} to not match object #{exp}",
expected,
actualSubset,
!1
]), message = stripped === 0 ? msg : `${msg}
(${stripped} matching ${stripped === 1 ? "property" : "properties"} omitted from actual)`;
throw new AssertionError2(message, {
showDiff: !0,
expected,
actual: actualSubset
});
}
}), def("toMatch", function(expected) {
let actual = this._obj;
if (typeof actual != "string")
throw new TypeError(`.toMatch() expects to receive a string, but got ${typeof actual}`);
return this.assert(typeof expected == "string" ? actual.includes(expected) : actual.match(expected), "expected #{this} to match #{exp}", "expected #{this} not to match #{exp}", expected, actual);
}), def("toContain", function(item) {
let actual = this._obj;
if (typeof Node < "u" && actual instanceof Node) {
if (!(item instanceof Node))
throw new TypeError(`toContain() expected a DOM node as the argument, but got ${typeof item}`);
return this.assert(actual.contains(item), "expected #{this} to contain element #{exp}", "expected #{this} not to contain element #{exp}", item, actual);
}
if (typeof DOMTokenList < "u" && actual instanceof DOMTokenList) {
assertTypes(item, "class name", ["string"]);
let expectedClassList = utils.flag(this, "negate") ? actual.value.replace(item, "").trim() : `${actual.value} ${item}`;
return this.assert(actual.contains(item), `expected "${actual.value}" to contain "${item}"`, `expected "${actual.value}" not to contain "${item}"`, expectedClassList, actual.value);
}
return typeof actual == "string" && typeof item == "string" ? this.assert(actual.includes(item), "expected #{this} to contain #{exp}", "expected #{this} not to contain #{exp}", item, actual) : (actual != null && typeof actual != "string" && utils.flag(this, "object", Array.from(actual)), this.contain(item));
}), def("toContainEqual", function(expected) {
let obj = utils.flag(this, "object"), index2 = Array.from(obj).findIndex((item) => equals(item, expected, customTesters));
this.assert(index2 !== -1, "expected #{this} to deep equally contain #{exp}", "expected #{this} to not deep equally contain #{exp}", expected);
}), def("toBeTruthy", function() {
let obj = utils.flag(this, "object");
this.assert(!!obj, "expected #{this} to be truthy", "expected #{this} to not be truthy", !0, obj);
}), def("toBeFalsy", function() {
let obj = utils.flag(this, "object");
this.assert(!obj, "expected #{this} to be falsy", "expected #{this} to not be falsy", !1, obj);
}), def("toBeGreaterThan", function(expected) {
let actual = this._obj;
return assertTypes(actual, "actual", ["number", "bigint"]), assertTypes(expected, "expected", ["number", "bigint"]), this.assert(actual > expected, `expected ${actual} to be greater than ${expected}`, `expected ${actual} to be not greater than ${expected}`, expected, actual, !1);
}), def("toBeGreaterThanOrEqual", function(expected) {
let actual = this._obj;
return assertTypes(actual, "actual", ["number", "bigint"]), assertTypes(expected, "expected", ["number", "bigint"]), this.assert(actual >= expected, `expected ${actual} to be greater than or equal to ${expected}`, `expected ${actual} to be not greater than or equal to ${expected}`, expected, actual, !1);
}), def("toBeLessThan", function(expected) {
let actual = this._obj;
return assertTypes(actual, "actual", ["number", "bigint"]), assertTypes(expected, "expected", ["number", "bigint"]), this.assert(actual < expected, `expected ${actual} to be less than ${expected}`, `expected ${actual} to be not less than ${expected}`, expected, actual, !1);
}), def("toBeLessThanOrEqual", function(expected) {
let actual = this._obj;
return assertTypes(actual, "actual", ["number", "bigint"]), assertTypes(expected, "expected", ["number", "bigint"]), this.assert(actual <= expected, `expected ${actual} to be less than or equal to ${expected}`, `expected ${actual} to be not less than or equal to ${expected}`, expected, actual, !1);
}), def("toBeNaN", function() {
let obj = utils.flag(this, "object");
this.assert(Number.isNaN(obj), "expected #{this} to be NaN", "expected #{this} not to be NaN", Number.NaN, obj);
}), def("toBeUndefined", function() {
let obj = utils.flag(this, "object");
this.assert(obj === void 0, "expected #{this} to be undefined", "expected #{this} not to be undefined", void 0, obj);
}), def("toBeNull", function() {
let obj = utils.flag(this, "object");
this.assert(obj === null, "expected #{this} to be null", "expected #{this} not to be null", null, obj);
}), def("toBeNullable", function() {
let obj = utils.flag(this, "object");
this.assert(obj == null, "expected #{this} to be nullish", "expected #{this} not to be nullish", null, obj);
}), def("toBeDefined", function() {
let obj = utils.flag(this, "object");
this.assert(typeof obj < "u", "expected #{this} to be defined", "expected #{this} to be undefined", obj);
}), def("toBeTypeOf", function(expected) {
let actual = typeof this._obj, equal = expected === actual;
return this.assert(equal, "expected #{this} to be type of #{exp}", "expected #{this} not to be type of #{exp}", expected, actual);
}), def("toBeInstanceOf", function(obj) {
return this.instanceOf(obj);
}), def("toHaveLength", function(length) {
return this.have.length(length);
}), def("toHaveProperty", function(...args) {
Array.isArray(args[0]) && (args[0] = args[0].map((key) => String(key).replace(/([.[\]])/g, "\\$1")).join("."));
let actual = this._obj, [propertyName, expected] = args, getValue = () => Object.hasOwn(actual, propertyName) ? {
value: actual[propertyName],
exists: !0
} : utils.getPathInfo(actual, propertyName), { value, exists } = getValue(), pass = exists && (args.length === 1 || equals(expected, value, customTesters)), valueString = args.length === 1 ? "" : ` with value ${utils.objDisplay(expected)}`;
return this.assert(pass, `expected #{this} to have property "${propertyName}"${valueString}`, `expected #{this} to not have property "${propertyName}"${valueString}`, expected, exists ? value : void 0);
}), def("toBeCloseTo", function(received, precision = 2) {
let expected = this._obj, pass = !1, expectedDiff = 0, receivedDiff = 0;
return received === Number.POSITIVE_INFINITY && expected === Number.POSITIVE_INFINITY || received === Number.NEGATIVE_INFINITY && expected === Number.NEGATIVE_INFINITY ? pass = !0 : (expectedDiff = 10 ** -precision / 2, receivedDiff = Math.abs(expected - received), pass = receivedDiff < expectedDiff), this.assert(pass, `expected #{this} to be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`, `expected #{this} to not be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`, received, expected, !1);
});
function assertIsMock(assertion) {
if (!isMockFunction(assertion._obj))
throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`);
}
function getSpy(assertion) {
return assertIsMock(assertion), assertion._obj;
}
def(["toHaveBeenCalledTimes", "toBeCalledTimes"], function(number) {
let spy = getSpy(this), spyName = spy.getMockName(), callCount = spy.mock.calls.length;
return this.assert(callCount === number, `expected "${spyName}" to be called #{exp} times, but got ${callCount} times`, `expected "${spyName}" to not be called #{exp} times`, number, callCount, !1);
}), def("toHaveBeenCalledOnce", function() {
let spy = getSpy(this), spyName = spy.getMockName(), callCount = spy.mock.calls.length;
return this.assert(callCount === 1, `expected "${spyName}" to be called once, but got ${callCount} times`, `expected "${spyName}" to not be called once`, 1, callCount, !1);
}), def(["toHaveBeenCalled", "toBeCalled"], function() {
let spy = getSpy(this), spyName = spy.getMockName(), callCount = spy.mock.calls.length, called = callCount > 0, isNot = utils.flag(this, "negate"), msg = utils.getMessage(this, [
called,
`expected "${spyName}" to be called at least once`,
`expected "${spyName}" to not be called at all, but actually been called ${callCount} times`,
!0,
called
]);
if (called && isNot && (msg = formatCalls(spy, msg)), called && isNot || !called && !isNot)
throw new AssertionError2(msg);
});
function equalsArgumentArray(a, b2) {
return a.length === b2.length && a.every((aItem, i2) => equals(aItem, b2[i2], [...customTesters, iterableEquality]));
}
def(["toHaveBeenCalledWith", "toBeCalledWith"], function(...args) {
let spy = getSpy(this), spyName = spy.getMockName(), pass = spy.mock.calls.some((callArg) => equalsArgumentArray(callArg, args)), isNot = utils.flag(this, "negate"), msg = utils.getMessage(this, [
pass,
`expected "${spyName}" to be called with arguments: #{exp}`,
`expected "${spyName}" to not be called with arguments: #{exp}`,
args
]);
if (pass && isNot || !pass && !isNot)
throw new AssertionError2(formatCalls(spy, msg, args));
}), def("toHaveBeenCalledExactlyOnceWith", function(...args) {
let spy = getSpy(this), spyName = spy.getMockName(), callCount = spy.mock.calls.length, pass = spy.mock.calls.some((callArg) => equalsArgumentArray(callArg, args)) && callCount === 1, isNot = utils.flag(this, "negate"), msg = utils.getMessage(this, [
pass,
`expected "${spyName}" to be called once with arguments: #{exp}`,
`expected "${spyName}" to not be called once with arguments: #{exp}`,
args
]);
if (pass && isNot || !pass && !isNot)
throw new AssertionError2(formatCalls(spy, msg, args));
}), def("toHaveBeenNthCalledWith", function(times, ...args) {
let spy = getSpy(this), spyName = spy.getMockName(), nthCall = spy.mock.calls[times - 1], callCount = spy.mock.calls.length, isCalled = times <= callCount;
this.assert(nthCall && equalsArgumentArray(nthCall, args), `expected ${ordinal(times)} "${spyName}" call to have been called with #{exp}${isCalled ? "" : `, but called only ${callCount} times`}`, `expected ${ordinal(times)} "${spyName}" call to not have been called with #{exp}`, args, nthCall, isCalled);
}), def("toHaveBeenLastCalledWith", function(...args) {
let spy = getSpy(this), spyName = spy.getMockName(), lastCall = spy.mock.calls.at(-1);
this.assert(lastCall && equalsArgumentArray(lastCall, args), `expected last "${spyName}" call to have been called with #{exp}`, `expected last "${spyName}" call to not have been called with #{exp}`, args, lastCall);
});
function isSpyCalledBeforeAnotherSpy(beforeSpy, afterSpy, failIfNoFirstInvocation) {
let beforeInvocationCallOrder = beforeSpy.mock.invocationCallOrder, afterInvocationCallOrder = afterSpy.mock.invocationCallOrder;
return beforeInvocationCallOrder.length === 0 ? !failIfNoFirstInvocation : afterInvocationCallOrder.length === 0 ? !1 : beforeInvocationCallOrder[0] < afterInvocationCallOrder[0];
}
def(["toHaveBeenCalledBefore"], function(resultSpy, failIfNoFirstInvocation = !0) {
let expectSpy = getSpy(this);
if (!isMockFunction(resultSpy))
throw new TypeError(`${utils.inspect(resultSpy)} is not a spy or a call to a spy`);
this.assert(isSpyCalledBeforeAnotherSpy(expectSpy, resultSpy, failIfNoFirstInvocation), `expected "${expectSpy.getMockName()}" to have been called before "${resultSpy.getMockName()}"`, `expected "${expectSpy.getMockName()}" to not have been called before "${resultSpy.getMockName()}"`, resultSpy, expectSpy);
}), def(["toHaveBeenCalledAfter"], function(resultSpy, failIfNoFirstInvocation = !0) {
let expectSpy = getSpy(this);
if (!isMockFunction(resultSpy))
throw new TypeError(`${utils.inspect(resultSpy)} is not a spy or a call to a spy`);
this.assert(isSpyCalledBeforeAnotherSpy(resultSpy, expectSpy, failIfNoFirstInvocation), `expected "${expectSpy.getMockName()}" to have been called after "${resultSpy.getMockName()}"`, `expected "${expectSpy.getMockName()}" to not have been called after "${resultSpy.getMockName()}"`, resultSpy, expectSpy);
}), def(["toThrow", "toThrowError"], function(expected) {
if (typeof expected == "string" || typeof expected > "u" || expected instanceof RegExp)
return this.throws(expected === "" ? /^$/ : expected);
let obj = this._obj, promise = utils.flag(this, "promise"), isNot = utils.flag(this, "negate"), thrown = null;
if (promise === "rejects")
thrown = obj;
else if (promise === "resolves" && typeof obj != "function") {
if (isNot)
return;
{
let message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't", error = { showDiff: !1 };
throw new AssertionError2(message, error, utils.flag(this, "ssfi"));
}
} else {
let isThrow = !1;
try {
obj();
} catch (err) {
isThrow = !0, thrown = err;
}
if (!isThrow && !isNot) {
let message = utils.flag(this, "message") || "expected function to throw an error, but it didn't", error = { showDiff: !1 };
throw new AssertionError2(message, error, utils.flag(this, "ssfi"));
}
}
if (typeof expected == "function") {
let name = expected.name || expected.prototype.constructor.name;
return this.assert(thrown && thrown instanceof expected, `expected error to be instance of ${name}`, `expected error not to be instance of ${name}`, expected, thrown);
}
if (isError(expected)) {
let equal2 = equals(thrown, expected, [...customTesters, iterableEquality]);
return this.assert(equal2, "expected a thrown error to be #{exp}", "expected a thrown error not to be #{exp}", expected, thrown);
}
if (typeof expected == "object" && "asymmetricMatch" in expected && typeof expected.asymmetricMatch == "function") {
let matcher = expected;
return this.assert(thrown && matcher.asymmetricMatch(thrown), "expected error to match asymmetric matcher", "expected error not to match asymmetric matcher", matcher, thrown);
}
let equal = equals(thrown, expected, [...customTesters, iterableEquality]);
return this.assert(equal, "expected a thrown value to equal #{exp}", "expected a thrown value not to equal #{exp}", expected, thrown);
}), [{
name: "toHaveResolved",
condition: (spy) => spy.mock.settledResults.length > 0 && spy.mock.settledResults.some(({ type: type3 }) => type3 === "fulfilled"),
action: "resolved"
}, {
name: ["toHaveReturned", "toReturn"],
condition: (spy) => spy.mock.calls.length > 0 && spy.mock.results.some(({ type: type3 }) => type3 !== "throw"),
action: "called"
}].forEach(({ name, condition, action }) => {
def(name, function() {
let spy = getSpy(this), spyName = spy.getMockName(), pass = condition(spy);
this.assert(pass, `expected "${spyName}" to be successfully ${action} at least once`, `expected "${spyName}" to not be successfully ${action}`, pass, !pass, !1);
});
}), [{
name: "toHaveResolvedTimes",
condition: (spy, times) => spy.mock.settledResults.reduce((s, { type: type3 }) => type3 === "fulfilled" ? ++s : s, 0) === times,
action: "resolved"
}, {
name: ["toHaveReturnedTimes", "toReturnTimes"],
condition: (spy, times) => spy.mock.results.reduce((s, { type: type3 }) => type3 === "throw" ? s : ++s, 0) === times,
action: "called"
}].forEach(({ name, condition, action }) => {
def(name, function(times) {
let spy = getSpy(this), spyName = spy.getMockName(), pass = condition(spy, times);
this.assert(pass, `expected "${spyName}" to be successfully ${action} ${times} times`, `expected "${spyName}" to not be successfully ${action} ${times} times`, `expected resolved times: ${times}`, `received resolved times: ${pass}`, !1);
});
}), [{
name: "toHaveResolvedWith",
condition: (spy, value) => spy.mock.settledResults.some(({ type: type3, value: result }) => type3 === "fulfilled" && equals(value, result)),
action: "resolve"
}, {
name: ["toHaveReturnedWith", "toReturnWith"],
condition: (spy, value) => spy.mock.results.some(({ type: type3, value: result }) => type3 === "return" && equals(value, result)),
action: "return"
}].forEach(({ name, condition, action }) => {
def(name, function(value) {
let spy = getSpy(this), pass = condition(spy, value), isNot = utils.flag(this, "negate");
if (pass && isNot || !pass && !isNot) {
let spyName = spy.getMockName(), msg = utils.getMessage(this, [
pass,
`expected "${spyName}" to ${action} with: #{exp} at least once`,
`expected "${spyName}" to not ${action} with: #{exp}`,
value
]), results = action === "return" ? spy.mock.results : spy.mock.settledResults;
throw new AssertionError2(formatReturns(spy, results, msg, value));
}
});
}), [{
name: "toHaveLastResolvedWith",
condition: (spy, value) => {
let result = spy.mock.settledResults.at(-1);
return !!(result && result.type === "fulfilled" && equals(result.value, value));
},
action: "resolve"
}, {
name: "toHaveLastReturnedWith",
condition: (spy, value) => {
let result = spy.mock.results.at(-1);
return !!(result && result.type === "return" && equals(result.value, value));
},
action: "return"
}].forEach(({ name, condition, action }) => {
def(name, function(value) {
let spy = getSpy(this), result = (action === "return" ? spy.mock.results : spy.mock.settledResults).at(-1), spyName = spy.getMockName();
this.assert(condition(spy, value), `expected last "${spyName}" call to ${action} #{exp}`, `expected last "${spyName}" call to not ${action} #{exp}`, value, result?.value);
});
}), [{
name: "toHaveNthResolvedWith",
condition: (spy, index2, value) => {
let result = spy.mock.settledResults[index2 - 1];
return result && result.type === "fulfilled" && equals(result.value, value);
},
action: "resolve"
}, {
name: "toHaveNthReturnedWith",
condition: (spy, index2, value) => {
let result = spy.mock.results[index2 - 1];
return result && result.type === "return" && equals(result.value, value);
},
action: "return"
}].forEach(({ name, condition, action }) => {
def(name, function(nthCall, value) {
let spy = getSpy(this), spyName = spy.getMockName(), result = (action === "return" ? spy.mock.results : spy.mock.settledResults)[nthCall - 1], ordinalCall = `${ordinal(nthCall)} call`;
this.assert(condition(spy, nthCall, value), `expected ${ordinalCall} "${spyName}" call to ${action} #{exp}`, `expected ${ordinalCall} "${spyName}" call to not ${action} #{exp}`, value, result?.value);
});
}), def("withContext", function(context) {
for (let key in context)
utils.flag(this, key, context[key]);
return this;
}), utils.addProperty(chai.Assertion.prototype, "resolves", function() {
let error = new Error("resolves");
utils.flag(this, "promise", "resolves"), utils.flag(this, "error", error);
let test5 = utils.flag(this, "vitest-test"), obj = utils.flag(this, "object");
if (utils.flag(this, "poll"))
throw new SyntaxError("expect.poll() is not supported in combination with .resolves");
if (typeof obj?.then != "function")
throw new TypeError(`You must provide a Promise to expect() when using .resolves, not '${typeof obj}'.`);
let proxy = new Proxy(this, { get: (target, key, receiver) => {
let result = Reflect.get(target, key, receiver);
return typeof result != "function" ? result instanceof chai.Assertion ? proxy : result : (...args) => {
utils.flag(this, "_name", key);
let promise = Promise.resolve(obj).then((value) => (utils.flag(this, "object", value), result.call(this, ...args)), (err) => {
let _error = new AssertionError2(`promise rejected "${utils.inspect(err)}" instead of resolving`, { showDiff: !1 });
throw _error.cause = err, _error;
}).catch((err) => {
throw isError(err) && error.stack && (err.stack = error.stack.replace(error.message, err.message)), err;
});
return recordAsyncExpect(test5, promise, createAssertionMessage(utils, this, !!args.length), error, utils.flag(this, "soft"));
};
} });
return proxy;
}), utils.addProperty(chai.Assertion.prototype, "rejects", function() {
let error = new Error("rejects");
utils.flag(this, "promise", "rejects"), utils.flag(this, "error", error);
let test5 = utils.flag(this, "vitest-test"), obj = utils.flag(this, "object"), wrapper = typeof obj == "function" ? obj() : obj;
if (utils.flag(this, "poll"))
throw new SyntaxError("expect.poll() is not supported in combination with .rejects");
if (typeof wrapper?.then != "function")
throw new TypeError(`You must provide a Promise to expect() when using .rejects, not '${typeof wrapper}'.`);
let proxy = new Proxy(this, { get: (target, key, receiver) => {
let result = Reflect.get(target, key, receiver);
return typeof result != "function" ? result instanceof chai.Assertion ? proxy : result : (...args) => {
utils.flag(this, "_name", key);
let promise = Promise.resolve(wrapper).then((value) => {
throw new AssertionError2(`promise resolved "${utils.inspect(value)}" instead of rejecting`, {
showDiff: !0,
expected: new Error("rejected promise"),
actual: value
});
}, (err) => (utils.flag(this, "object", err), result.call(this, ...args))).catch((err) => {
throw isError(err) && error.stack && (err.stack = error.stack.replace(error.message, err.message)), err;
});
return recordAsyncExpect(test5, promise, createAssertionMessage(utils, this, !!args.length), error, utils.flag(this, "soft"));
};
} });
return proxy;
});
};
function formatCalls(spy, msg, showActualCall) {
return spy.mock.calls.length && (msg += y.gray(`
Received:
${spy.mock.calls.map((callArg, i2) => {
let methodCall = y.bold(` ${ordinal(i2 + 1)} ${spy.getMockName()} call:
`);
return showActualCall ? methodCall += diff(showActualCall, callArg, { omitAnnotationLines: !0 }) : methodCall += stringify(callArg).split(`
`).map((line) => ` ${line}`).join(`
`), methodCall += `
`, methodCall;
}).join(`
`)}`)), msg += y.gray(`
Number of calls: ${y.bold(spy.mock.calls.length)}
`), msg;
}
function formatReturns(spy, results, msg, showActualReturn) {
return results.length && (msg += y.gray(`
Received:
${results.map((callReturn, i2) => {
let methodCall = y.bold(` ${ordinal(i2 + 1)} ${spy.getMockName()} call return:
`);
return showActualReturn ? methodCall += diff(showActualReturn, callReturn.value, { omitAnnotationLines: !0 }) : methodCall += stringify(callReturn).split(`
`).map((line) => ` ${line}`).join(`
`), methodCall += `
`, methodCall;
}).join(`
`)}`)), msg += y.gray(`
Number of calls: ${y.bold(spy.mock.calls.length)}
`), msg;
}
function getMatcherState(assertion, expect2) {
let obj = assertion._obj, isNot = utils_exports.flag(assertion, "negate"), promise = utils_exports.flag(assertion, "promise") || "", customMessage = utils_exports.flag(assertion, "message"), jestUtils = {
...getMatcherUtils(),
diff,
stringify,
iterableEquality,
subsetEquality
}, task = utils_exports.flag(assertion, "vitest-test"), currentTestName = task?.fullTestName ?? "";
task?.type !== "test" && (task = void 0);
let matcherState = {
...getState(expect2),
currentTestName,
customTesters: getCustomEqualityTesters(),
isNot,
utils: jestUtils,
promise,
equals,
suppressedErrors: [],
soft: utils_exports.flag(assertion, "soft"),
poll: utils_exports.flag(assertion, "poll"),
assertion
};
return Object.assign(matcherState, { task }), {
state: matcherState,
isNot,
obj,
customMessage
};
}
var JestExtendError = class extends Error {
constructor(message, actual, expected, __vitest_error_context__) {
super(message), this.actual = actual, this.expected = expected, this.__vitest_error_context__ = __vitest_error_context__;
}
};
function JestExtendPlugin(c, expect2, matchers) {
return (_, utils) => {
Object.entries(matchers).forEach(([expectAssertionName, expectAssertion]) => {
function __VITEST_EXTEND_ASSERTION__(...args) {
let { state, isNot, obj, customMessage } = getMatcherState(this, expect2), result = expectAssertion.call(state, obj, ...args);
if (result && typeof result == "object" && typeof result.then == "function")
return result.then(({ pass: pass2, message: message2, actual: actual2, expected: expected2, meta: meta2 }) => {
if (pass2 && isNot || !pass2 && !isNot) {
let errorMessage = (customMessage ? `${customMessage}: ` : "") + message2();
throw new JestExtendError(errorMessage, actual2, expected2, {
assertionName: expectAssertionName,
meta: meta2
});
}
});
let { pass, message, actual, expected, meta } = result;
if (pass && isNot || !pass && !isNot) {
let errorMessage = (customMessage ? `${customMessage}: ` : "") + message();
throw new JestExtendError(errorMessage, actual, expected, {
assertionName: expectAssertionName,
meta
});
}
}
let softWrapper = wrapAssertion(utils, expectAssertionName, __VITEST_EXTEND_ASSERTION__);
if (utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, expectAssertionName, softWrapper), utils.addMethod(c.Assertion.prototype, expectAssertionName, softWrapper), expectAssertion.__vitest_poll_takeover__) {
let addedMethod = c.Assertion.prototype[expectAssertionName];
Object.defineProperty(addedMethod, "__vitest_poll_takeover__", { value: !0 });
}
class CustomMatcher extends AsymmetricMatcher3 {
constructor(inverse = !1, ...sample) {
super(sample, inverse);
}
asymmetricMatch(other) {
let { pass } = expectAssertion.call(this.getMatcherContext(expect2), other, ...this.sample);
return this.inverse ? !pass : pass;
}
toString() {
return `${this.inverse ? "not." : ""}${expectAssertionName}`;
}
getExpectedType() {
return "any";
}
toAsymmetricMatcher() {
return `${this.toString()}<${this.sample.map((item) => stringify(item)).join(", ")}>`;
}
}
let customMatcher = (...sample) => new CustomMatcher(!1, ...sample);
Object.defineProperty(expect2, expectAssertionName, {
configurable: !0,
enumerable: !0,
value: customMatcher,
writable: !0
}), Object.defineProperty(expect2.not, expectAssertionName, {
configurable: !0,
enumerable: !0,
value: (...sample) => new CustomMatcher(!0, ...sample),
writable: !0
}), Object.defineProperty(globalThis[ASYMMETRIC_MATCHERS_OBJECT], expectAssertionName, {
configurable: !0,
enumerable: !0,
value: customMatcher,
writable: !0
});
});
};
}
var JestExtend = (chai, utils) => {
utils.addMethod(chai.expect, "extend", (expect2, expects) => {
use(JestExtendPlugin(chai, expect2, expects));
});
};
// ../../node_modules/.pnpm/@vitest+utils@4.1.10/node_modules/@vitest/utils/dist/offset.js
init_cjs_shims();
var lineSplitRE = /\r?\n/;
function positionToOffset(source, lineNumber, columnNumber) {
let lines = source.split(lineSplitRE), nl = /\r\n/.test(source) ? 2 : 1, start = 0;
if (lineNumber > lines.length)
return source.length;
for (let i2 = 0; i2 < lineNumber - 1; i2++)
start += lines[i2].length + nl;
return start + columnNumber;
}
function offsetToLineNumber(source, offset) {
if (offset > source.length)
throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`);
let lines = source.split(lineSplitRE), nl = /\r\n/.test(source) ? 2 : 1, counted = 0, line = 0;
for (; line < lines.length; line++) {
let lineLength = lines[line].length + nl;
if (counted + lineLength >= offset)
break;
counted += lineLength;
}
return line + 1;
}
// ../../node_modules/.pnpm/vitest@4.1.10_@opentelemetry+api@1.9.1_@types+node@22.20.1_@vitest+coverage-istanbul@3._f51dec9f55339d6c09addddd62782db2/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.js
init_cjs_shims();
var commonjsGlobal = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
// ../../node_modules/.pnpm/vitest@4.1.10_@opentelemetry+api@1.9.1_@types+node@22.20.1_@vitest+coverage-istanbul@3._f51dec9f55339d6c09addddd62782db2/node_modules/vitest/dist/chunks/rpc.MzXet3jl.js
init_cjs_shims();
var RealDate = Date, now2 = null, MockDate = class _MockDate extends RealDate {
constructor(y2, m, d2, h, M, s, ms) {
super();
let date;
switch (arguments.length) {
case 0:
now2 !== null ? date = new RealDate(now2.valueOf()) : date = new RealDate();
break;
case 1:
date = new RealDate(y2);
break;
default:
d2 = typeof d2 > "u" ? 1 : d2, h = h || 0, M = M || 0, s = s || 0, ms = ms || 0, date = new RealDate(y2, m, d2, h, M, s, ms);
break;
}
return Object.setPrototypeOf(date, _MockDate.prototype), 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) {
let dateObj = new RealDate(date.valueOf());
if (Number.isNaN(dateObj.getTime())) throw new TypeError(`mockdate: The time set is an invalid date: ${date}`);
globalThis.Date = MockDate, now2 = dateObj.valueOf();
}
function resetDate() {
globalThis.Date = RealDate;
}
var { get: get2 } = Reflect;
// ../../node_modules/.pnpm/@vitest+snapshot@4.1.10/node_modules/@vitest/snapshot/dist/index.js
init_cjs_shims();
function getDefaultExportFromCjs3(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x.default : x;
}
var naturalCompare$1 = { exports: {} }, hasRequiredNaturalCompare;
function requireNaturalCompare() {
if (hasRequiredNaturalCompare) return naturalCompare$1.exports;
hasRequiredNaturalCompare = 1;
var naturalCompare2 = function(a, b2) {
var i2, codeA, codeB = 1, posA = 0, posB = 0, alphabet = String.alphabet;
function getCode(str, pos, code) {
if (code) {
for (i2 = pos; code = getCode(str, i2), code < 76 && code > 65; ) ++i2;
return +str.slice(pos - 1, i2);
}
return code = alphabet && alphabet.indexOf(str.charAt(pos)), code > -1 ? code + 76 : (code = str.charCodeAt(pos) || 0, code < 45 || code > 127 ? code : code < 46 ? 65 : code < 48 ? code - 1 : code < 58 ? code + 18 : code < 65 ? code - 11 : code < 91 ? code + 11 : code < 97 ? code - 37 : code < 123 ? code + 5 : code - 63);
}
if ((a += "") != (b2 += "")) {
for (; codeB; )
if (codeA = getCode(a, posA++), codeB = getCode(b2, posB++), codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66 && (codeA = getCode(a, posA, posA), codeB = getCode(b2, posB, posA = i2), posB = i2), codeA != codeB) return codeA < codeB ? -1 : 1;
}
return 0;
};
try {
naturalCompare$1.exports = naturalCompare2;
} catch {
String.naturalCompare = naturalCompare2;
}
return naturalCompare$1.exports;
}
var naturalCompareExports = requireNaturalCompare(), naturalCompare = /* @__PURE__ */ getDefaultExportFromCjs3(naturalCompareExports), serialize$12 = (val, config2, indentation, depth, refs, printer2) => {
let name = val.getMockName(), nameString = name === "vi.fn()" ? "" : ` ${name}`, callsString = "";
if (val.mock.calls.length !== 0) {
let indentationNext = indentation + config2.indent;
callsString = ` {${config2.spacingOuter}${indentationNext}"calls": ${printer2(val.mock.calls, config2, indentationNext, depth, refs)}${config2.min ? ", " : ","}${config2.spacingOuter}${indentationNext}"results": ${printer2(val.mock.results, config2, indentationNext, depth, refs)}${config2.min ? "" : ","}${config2.spacingOuter}${indentation}}`;
}
return `[MockFunction${nameString}]${callsString}`;
}, test4 = (val) => val && !!val._isMockFunction, plugin2 = {
serialize: serialize$12,
test: test4
}, { DOMCollection: DOMCollection3, DOMElement: DOMElement3, Immutable: Immutable3, ReactElement: ReactElement3, ReactTestComponent: ReactTestComponent3, AsymmetricMatcher: AsymmetricMatcher4 } = plugins, PLUGINS3 = [
ReactTestComponent3,
ReactElement3,
DOMElement3,
DOMCollection3,
Immutable3,
AsymmetricMatcher4,
plugin2
];
function addSerializer(plugin3) {
PLUGINS3 = [plugin3].concat(PLUGINS3);
}
function getSerializers() {
return PLUGINS3;
}
function testNameToKey(testName2, count) {
return `${testName2} ${count}`;
}
function keyToTestName(key) {
if (!/ \d+$/.test(key))
throw new Error("Snapshot keys must end with a number.");
return key.replace(/ \d+$/, "");
}
function getSnapshotData(content, options) {
let update = options.updateSnapshot, data = /* @__PURE__ */ Object.create(null), snapshotContents = "", dirty = !1;
if (content != null)
try {
snapshotContents = content, new Function("exports", snapshotContents)(data);
} catch {
}
return (update === "all" || update === "new") && snapshotContents && (dirty = !0), {
data,
dirty
};
}
function addExtraLineBreaks(string2) {
return string2.includes(`
`) ? `
${string2}
` : string2;
}
function removeExtraLineBreaks(string2) {
return string2.length > 2 && string2[0] === `
` && string2.endsWith(`
`) ? string2.slice(1, -1) : string2;
}
var escapeRegex = !0, printFunctionName = !1;
function serialize2(val, indent = 2, formatOverrides = {}) {
return normalizeNewlines(format(val, {
escapeRegex,
indent,
plugins: getSerializers(),
printFunctionName,
...formatOverrides
}));
}
function escapeBacktickString(str) {
return str.replace(/`|\\|\$\{/g, "\\$&");
}
function printBacktickString(str) {
return `\`${escapeBacktickString(str)}\``;
}
function normalizeNewlines(string2) {
return string2.replace(/\r\n|\r/g, `
`);
}
async function saveSnapshotFile(environment, snapshotData, snapshotPath) {
let snapshots = Object.keys(snapshotData).sort(naturalCompare).map((key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`), content = `${environment.getHeader()}
${snapshots.join(`
`)}
`, oldContent = await environment.readSnapshotFile(snapshotPath);
oldContent != null && oldContent === content || await environment.saveSnapshotFile(snapshotPath, content);
}
function deepMergeArray(target = [], source = []) {
let mergedOutput = Array.from(target);
return source.forEach((sourceElement, index2) => {
let targetElement = mergedOutput[index2];
Array.isArray(target[index2]) ? mergedOutput[index2] = deepMergeArray(target[index2], sourceElement) : isObject(targetElement) ? mergedOutput[index2] = deepMergeSnapshot(target[index2], sourceElement) : mergedOutput[index2] = sourceElement;
}), mergedOutput;
}
function deepMergeSnapshot(target, source) {
if (isObject(target) && isObject(source)) {
let mergedOutput = { ...target };
return Object.keys(source).forEach((key) => {
isObject(source[key]) && !source[key].$$typeof ? key in target ? mergedOutput[key] = deepMergeSnapshot(target[key], source[key]) : Object.assign(mergedOutput, { [key]: source[key] }) : Array.isArray(source[key]) ? mergedOutput[key] = deepMergeArray(target[key], source[key]) : Object.assign(mergedOutput, { [key]: source[key] });
}), mergedOutput;
} else if (Array.isArray(target) && Array.isArray(source))
return deepMergeArray(target, source);
return target;
}
var DefaultMap = class extends Map {
constructor(defaultFn, entries) {
super(entries), this.defaultFn = defaultFn;
}
get(key) {
return this.has(key) || this.set(key, this.defaultFn(key)), super.get(key);
}
}, CounterMap = class extends DefaultMap {
constructor() {
super(() => 0);
}
// compat for jest-image-snapshot https://github.com/vitest-dev/vitest/issues/7322
// `valueOf` and `Snapshot.added` setter allows
// snapshotState.added = snapshotState.added + 1
// to function as
// snapshotState.added.total_ = snapshotState.added.total() + 1
_total;
valueOf() {
return this._total = this.total();
}
increment(key) {
typeof this._total < "u" && this._total++, this.set(key, this.get(key) + 1);
}
total() {
if (typeof this._total < "u")
return this._total;
let total = 0;
for (let x of this.values())
total += x;
return total;
}
};
// @__NO_SIDE_EFFECTS__
function memo(fn2) {
let cache = /* @__PURE__ */ new Map();
return (arg) => (cache.has(arg) || cache.set(arg, fn2(arg)), cache.get(arg));
}
async function saveInlineSnapshots(environment, snapshots) {
let MagicString = (await import("./magic-string.es-PUBJJZST.js")).default, files = new Set(snapshots.map((i2) => i2.file));
await Promise.all(Array.from(files).map(async (file) => {
let snaps = snapshots.filter((i2) => i2.file === file), code = await environment.readSnapshotFile(file);
if (code == null)
throw new Error(`cannot read ${file} when saving inline snapshot`);
let s = new MagicString(code);
for (let snap of snaps) {
let index2 = positionToOffset(code, snap.line, snap.column);
replaceInlineSnap(code, s, index2, snap.snapshot, snap.assertionName);
}
let transformed = s.toString();
transformed !== code && await environment.saveSnapshotFile(file, transformed);
}));
}
var defaultStartObjectRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*\{/;
function escapeRegExp(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
var buildStartObjectRegex = /* @__PURE__ */ memo((assertionName) => {
let replaced = defaultStartObjectRegex.source.replace("toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot", escapeRegExp(assertionName));
return new RegExp(replaced);
});
function replaceObjectSnap(code, s, index2, newSnap, assertionName) {
let _code = code.slice(index2), startMatch = (assertionName ? buildStartObjectRegex(assertionName) : defaultStartObjectRegex).exec(_code);
if (!startMatch)
return !1;
_code = _code.slice(startMatch.index);
let callEnd = getCallLastIndex(_code);
if (callEnd === null)
return !1;
callEnd += index2 + startMatch.index;
let shapeStart = index2 + startMatch.index + startMatch[0].length, shapeEnd = getObjectShapeEndIndex(code, shapeStart), snap = `, ${prepareSnapString(newSnap, code, index2)}`;
return shapeEnd === callEnd ? s.appendLeft(callEnd, snap) : s.overwrite(shapeEnd, callEnd, snap), !0;
}
function getObjectShapeEndIndex(code, index2) {
let startBraces = 1, endBraces = 0;
for (; startBraces !== endBraces && index2 < code.length; ) {
let s = code[index2++];
s === "{" ? startBraces++ : s === "}" && endBraces++;
}
return index2;
}
function prepareSnapString(snap, source, index2) {
let lineNumber = offsetToLineNumber(source, index2), indent = source.split(lineSplitRE)[lineNumber - 1].match(/^\s*/)[0] || "", indentNext = indent.includes(" ") ? `${indent} ` : `${indent} `, lines = snap.trim().replace(/\\/g, "\\\\").split(/\n/g), isOneline = lines.length <= 1, quote = "`";
return isOneline ? `${quote}${lines.join(`
`).replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}${quote}` : `${quote}
${lines.map((i2) => i2 ? indentNext + i2 : "").join(`
`).replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}
${indent}${quote}`;
}
var defaultMethodNames = ["toMatchInlineSnapshot", "toThrowErrorMatchingInlineSnapshot"];
function getCodeStartingAtIndex(code, index2, methodNames) {
for (let name of methodNames) {
let adjusted = index2 - name.length;
if (adjusted >= 0 && code.slice(adjusted, index2) === name)
return {
code: code.slice(adjusted),
index: adjusted
};
}
return {
code: code.slice(index2),
index: index2
};
}
var defaultStartRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*[\w$]*(['"`)])/, buildStartRegex = /* @__PURE__ */ memo((assertionName) => {
let replaced = defaultStartRegex.source.replace("toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot", escapeRegExp(assertionName));
return new RegExp(replaced);
});
function replaceInlineSnap(code, s, currentIndex, newSnap, assertionName) {
let methodNames = assertionName ? [assertionName] : defaultMethodNames, { code: codeStartingAtIndex, index: index2 } = getCodeStartingAtIndex(code, currentIndex, methodNames), startMatch = (assertionName ? buildStartRegex(assertionName) : defaultStartRegex).exec(codeStartingAtIndex), firstKeywordMatch = (assertionName ? new RegExp(escapeRegExp(assertionName)) : /toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot/).exec(codeStartingAtIndex);
if (!startMatch || startMatch.index !== firstKeywordMatch?.index)
return replaceObjectSnap(code, s, index2, newSnap, assertionName);
let quote = startMatch[1], startIndex = index2 + startMatch.index + startMatch[0].length, snapString = prepareSnapString(newSnap, code, index2);
if (quote === ")")
return s.appendRight(startIndex - 1, snapString), !0;
let endMatch = new RegExp(`(?:^|[^\\\\])${quote}`).exec(code.slice(startIndex));
if (!endMatch)
return !1;
let endIndex = startIndex + endMatch.index + endMatch[0].length;
return s.overwrite(startIndex - 1, endIndex, snapString), !0;
}
var INDENTATION_REGEX = /^([^\S\n]*)\S/m;
function stripSnapshotIndentation(inlineSnapshot) {
let match = inlineSnapshot.match(INDENTATION_REGEX);
if (!match || !match[1])
return inlineSnapshot;
let indentation = match[1], lines = inlineSnapshot.split(/\n/g);
if (lines.length <= 2 || lines[0].trim() !== "" || lines.at(-1)?.trim() !== "")
return inlineSnapshot;
for (let i2 = 1; i2 < lines.length - 1; i2++)
if (lines[i2] !== "") {
if (lines[i2].indexOf(indentation) !== 0)
return inlineSnapshot;
lines[i2] = lines[i2].substring(indentation.length);
}
return lines[lines.length - 1] = "", inlineSnapshot = lines.join(`
`), inlineSnapshot;
}
async function saveRawSnapshots(environment, snapshots) {
await Promise.all(snapshots.map(async (snap) => {
snap.readonly || await environment.saveSnapshotFile(snap.file, snap.snapshot);
}));
}
function isSameStackPosition(x, y2) {
return x.file === y2.file && x.column === y2.column && x.line === y2.line;
}
var SnapshotState = class _SnapshotState {
_counters = new CounterMap();
_dirty;
_updateSnapshot;
_snapshotData;
_initialData;
_inlineSnapshots;
_inlineSnapshotStacks;
_testIdToKeys = new DefaultMap(() => []);
_rawSnapshots;
_uncheckedKeys;
_snapshotFormat;
_environment;
_fileExists;
expand;
// getter/setter for jest-image-snapshot compat
// https://github.com/vitest-dev/vitest/issues/7322
_added = new CounterMap();
_matched = new CounterMap();
_unmatched = new CounterMap();
_updated = new CounterMap();
get added() {
return this._added;
}
set added(value) {
this._added._total = value;
}
get matched() {
return this._matched;
}
set matched(value) {
this._matched._total = value;
}
get unmatched() {
return this._unmatched;
}
set unmatched(value) {
this._unmatched._total = value;
}
get updated() {
return this._updated;
}
set updated(value) {
this._updated._total = value;
}
constructor(testFilePath, snapshotPath, snapshotContent, options) {
this.testFilePath = testFilePath, this.snapshotPath = snapshotPath;
let { data, dirty } = getSnapshotData(snapshotContent, options);
this._fileExists = snapshotContent != null, this._initialData = { ...data }, this._snapshotData = { ...data }, this._dirty = dirty, this._inlineSnapshots = [], this._inlineSnapshotStacks = [], this._rawSnapshots = [], this._uncheckedKeys = new Set(Object.keys(this._snapshotData)), this.expand = options.expand || !1, this._updateSnapshot = options.updateSnapshot, this._snapshotFormat = {
printBasicPrototype: !1,
escapeString: !1,
maxOutputLength: 2 ** 27,
...options.snapshotFormat
}, this._environment = options.snapshotEnvironment;
}
static async create(testFilePath, options) {
let snapshotPath = await options.snapshotEnvironment.resolvePath(testFilePath), content = await options.snapshotEnvironment.readSnapshotFile(snapshotPath);
return new _SnapshotState(testFilePath, snapshotPath, content, options);
}
get snapshotUpdateState() {
return this._updateSnapshot;
}
get environment() {
return this._environment;
}
markSnapshotsAsCheckedForTest(testName2) {
this._uncheckedKeys.forEach((uncheckedKey) => {
/ \d+$| > /.test(uncheckedKey.slice(testName2.length)) && this._uncheckedKeys.delete(uncheckedKey);
});
}
clearTest(testId) {
this._inlineSnapshots = this._inlineSnapshots.filter((s) => s.testId !== testId), this._inlineSnapshotStacks = this._inlineSnapshotStacks.filter((s) => s.testId !== testId);
for (let key of this._testIdToKeys.get(testId)) {
let name = keyToTestName(key), count = this._counters.get(name);
count > 0 && ((key in this._snapshotData || key in this._initialData) && (this._snapshotData[key] = this._initialData[key]), this._counters.set(name, count - 1));
}
this._testIdToKeys.delete(testId), this.added.delete(testId), this.updated.delete(testId), this.matched.delete(testId), this.unmatched.delete(testId);
}
_inferInlineSnapshotStack(stacks) {
let promiseIndex = stacks.findIndex((i2) => i2.method.match(/__VITEST_(RESOLVES|REJECTS)__/));
if (promiseIndex !== -1)
return stacks[promiseIndex + 3];
let pollChainIndex = stacks.findIndex((i2) => i2.method.match(/__VITEST_POLL_CHAIN__/));
if (pollChainIndex !== -1)
return stacks[pollChainIndex + 1];
for (let i2 = 0; i2 < stacks.length; i2++) {
let match = stacks[i2].method.match(/__INLINE_SNAPSHOT_OFFSET_(\d+)__/);
if (match)
return stacks[i2 + Number(match[1])] ?? null;
}
let customMatcherIndex = stacks.findIndex((i2) => i2.method.includes("__VITEST_EXTEND_ASSERTION__"));
if (customMatcherIndex !== -1)
return stacks[customMatcherIndex + 3] ?? null;
let stackIndex = stacks.findIndex((i2) => i2.method.includes("__INLINE_SNAPSHOT__"));
return stackIndex !== -1 ? stacks[stackIndex + 2] : null;
}
_addSnapshot(key, receivedSerialized, options) {
this._dirty = !0, options.stack ? this._inlineSnapshots.push({
...options.stack,
snapshot: receivedSerialized,
testId: options.testId,
assertionName: options.assertionName
}) : options.rawSnapshot ? this._rawSnapshots.push({
...options.rawSnapshot,
snapshot: receivedSerialized
}) : this._snapshotData[key] = receivedSerialized;
}
_resolveKey(testId, testName2, key) {
this._counters.increment(testName2);
let count = this._counters.get(testName2);
return key || (key = testNameToKey(testName2, count)), this._testIdToKeys.get(testId).push(key), {
key,
count
};
}
_resolveInlineStack(options) {
let { testId, snapshot, assertionName, error } = options, stacks = parseErrorStacktrace(error, { ignoreStackEntries: [] }), _stack = this._inferInlineSnapshotStack(stacks);
if (!_stack) {
let message = stacks.map((s) => ` ${s.file}:${s.line}:${s.column}${s.method ? ` (${s.method})` : ""}`).join(`
`);
throw new Error(`@vitest/snapshot: Couldn't infer stack frame for inline snapshot.
${message}`);
}
let stack = this.environment.processStackTrace?.(_stack) || _stack;
stack.column--;
let snapshotsWithSameStack = this._inlineSnapshotStacks.filter((s) => isSameStackPosition(s, stack));
if (snapshotsWithSameStack.length > 0) {
this._inlineSnapshots = this._inlineSnapshots.filter((s) => !isSameStackPosition(s, stack));
let differentSnapshot = snapshotsWithSameStack.find((s) => s.snapshot !== snapshot);
if (differentSnapshot)
throw Object.assign(new Error(`${assertionName} with different snapshots cannot be called at the same location`), {
actual: snapshot,
expected: differentSnapshot.snapshot
});
}
return this._inlineSnapshotStacks.push({
...stack,
testId,
snapshot
}), stack;
}
_reconcile(opts) {
return opts.hasSnapshot && this._updateSnapshot === "all" || (!opts.hasSnapshot || !opts.snapshotIsPersisted) && (this._updateSnapshot === "new" || this._updateSnapshot === "all") ? (this._updateSnapshot === "all" ? opts.pass ? this.matched.increment(opts.testId) : (opts.hasSnapshot ? this.updated.increment(opts.testId) : this.added.increment(opts.testId), this._addSnapshot(opts.key, opts.addValue, {
stack: opts.stack,
testId: opts.testId,
rawSnapshot: opts.rawSnapshot,
assertionName: opts.assertionName
})) : (this._addSnapshot(opts.key, opts.addValue, {
stack: opts.stack,
testId: opts.testId,
rawSnapshot: opts.rawSnapshot,
assertionName: opts.assertionName
}), this.added.increment(opts.testId)), {
actual: "",
count: opts.count,
expected: "",
key: opts.key,
pass: !0
}) : opts.pass ? (this.matched.increment(opts.testId), {
actual: "",
count: opts.count,
expected: "",
key: opts.key,
pass: !0
}) : (this.unmatched.increment(opts.testId), {
actual: opts.actualDisplay,
count: opts.count,
expected: opts.expectedDisplay,
key: opts.key,
pass: !1
});
}
async save() {
let hasExternalSnapshots = Object.keys(this._snapshotData).length, hasInlineSnapshots = this._inlineSnapshots.length, hasRawSnapshots = this._rawSnapshots.length, isEmpty = !hasExternalSnapshots && !hasInlineSnapshots && !hasRawSnapshots, status = {
deleted: !1,
saved: !1
};
return (this._dirty || this._uncheckedKeys.size) && !isEmpty ? (hasExternalSnapshots && (await saveSnapshotFile(this._environment, this._snapshotData, this.snapshotPath), this._fileExists = !0), hasInlineSnapshots && await saveInlineSnapshots(this._environment, this._inlineSnapshots), hasRawSnapshots && await saveRawSnapshots(this._environment, this._rawSnapshots), status.saved = !0) : !hasExternalSnapshots && this._fileExists && (this._updateSnapshot === "all" && (await this._environment.removeSnapshotFile(this.snapshotPath), this._fileExists = !1), status.deleted = !0), status;
}
getUncheckedCount() {
return this._uncheckedKeys.size || 0;
}
getUncheckedKeys() {
return Array.from(this._uncheckedKeys);
}
removeUncheckedKeys() {
this._updateSnapshot === "all" && this._uncheckedKeys.size && (this._dirty = !0, this._uncheckedKeys.forEach((key) => delete this._snapshotData[key]), this._uncheckedKeys.clear());
}
probeExpectedSnapshot(options) {
let count = this._counters.get(options.testName) + 1, key = testNameToKey(options.testName, count);
return {
key,
count,
data: options?.isInline ? options.inlineSnapshot : this._snapshotData[key],
markAsChecked: () => {
this._counters.increment(options.testName), this._testIdToKeys.get(options.testId).push(key), this._uncheckedKeys.delete(key);
}
};
}
match({ testId, testName: testName2, received, key, inlineSnapshot, isInline, error, rawSnapshot, assertionName }) {
let resolved = this._resolveKey(testId, testName2, key);
key = resolved.key;
let count = resolved.count;
isInline && this._snapshotData[key] !== void 0 || this._uncheckedKeys.delete(key);
let receivedSerialized = rawSnapshot && typeof received == "string" ? received : serialize2(received, void 0, this._snapshotFormat);
rawSnapshot || (receivedSerialized = addExtraLineBreaks(receivedSerialized)), rawSnapshot && rawSnapshot.content && rawSnapshot.content.match(/\r\n/) && !receivedSerialized.match(/\r\n/) && (rawSnapshot.content = normalizeNewlines(rawSnapshot.content));
let expected = isInline ? inlineSnapshot : rawSnapshot ? rawSnapshot.content : this._snapshotData[key], expectedTrimmed = rawSnapshot ? expected : expected?.trim(), pass = expectedTrimmed === (rawSnapshot ? receivedSerialized : receivedSerialized.trim()), hasSnapshot = expected !== void 0, snapshotIsPersisted = isInline || this._fileExists || rawSnapshot && rawSnapshot.content != null;
pass && !isInline && !rawSnapshot && (this._snapshotData[key] = receivedSerialized);
let stack = isInline ? this._resolveInlineStack({
testId,
snapshot: receivedSerialized,
assertionName: assertionName || "toMatchInlineSnapshot",
error: error || new Error("snapshot")
}) : void 0;
return this._reconcile({
testId,
key,
count,
pass,
hasSnapshot,
snapshotIsPersisted: !!snapshotIsPersisted,
addValue: receivedSerialized,
actualDisplay: rawSnapshot ? receivedSerialized : removeExtraLineBreaks(receivedSerialized),
expectedDisplay: expectedTrimmed !== void 0 ? rawSnapshot ? expectedTrimmed : removeExtraLineBreaks(expectedTrimmed) : void 0,
stack,
rawSnapshot,
assertionName
});
}
processDomainSnapshot({ testId, received, expectedSnapshot, matchResult, isInline, error, assertionName }) {
let stack = isInline ? this._resolveInlineStack({
testId,
snapshot: received,
assertionName,
error: error || new Error("STACK_TRACE_ERROR")
}) : void 0, actualResolved = matchResult?.resolved ?? received, expectedResolved = matchResult?.expected ?? expectedSnapshot.data;
return this._reconcile({
testId,
key: expectedSnapshot.key,
count: expectedSnapshot.count,
pass: matchResult?.pass ?? !1,
hasSnapshot: !!expectedSnapshot.data,
snapshotIsPersisted: isInline ? !0 : this._fileExists,
addValue: actualResolved,
actualDisplay: removeExtraLineBreaks(actualResolved),
expectedDisplay: expectedResolved !== void 0 ? removeExtraLineBreaks(expectedResolved) : void 0,
stack,
assertionName
});
}
async pack() {
let snapshot = {
filepath: this.testFilePath,
added: 0,
fileDeleted: !1,
matched: 0,
unchecked: 0,
uncheckedKeys: [],
unmatched: 0,
updated: 0
}, uncheckedCount = this.getUncheckedCount(), uncheckedKeys = this.getUncheckedKeys();
uncheckedCount && this.removeUncheckedKeys();
let status = await this.save();
return snapshot.fileDeleted = status.deleted, snapshot.added = this.added.total(), snapshot.matched = this.matched.total(), snapshot.unmatched = this.unmatched.total(), snapshot.updated = this.updated.total(), snapshot.unchecked = status.deleted ? 0 : uncheckedCount, snapshot.uncheckedKeys = Array.from(uncheckedKeys), snapshot;
}
};
function createMismatchError(message, expand, actual, expected) {
let error = new Error(message);
return Object.defineProperty(error, "actual", {
value: actual,
enumerable: !0,
configurable: !0,
writable: !0
}), Object.defineProperty(error, "expected", {
value: expected,
enumerable: !0,
configurable: !0,
writable: !0
}), Object.defineProperty(error, "diffOptions", { value: { expand } }), error;
}
var SnapshotClient = class {
snapshotStateMap = /* @__PURE__ */ new Map();
constructor(options = {}) {
this.options = options;
}
async setup(filepath, options) {
this.snapshotStateMap.has(filepath) || this.snapshotStateMap.set(filepath, await SnapshotState.create(filepath, options));
}
async finish(filepath) {
let result = await this.getSnapshotState(filepath).pack();
return this.snapshotStateMap.delete(filepath), result;
}
skipTest(filepath, testName2) {
this.getSnapshotState(filepath).markSnapshotsAsCheckedForTest(testName2);
}
clearTest(filepath, testId) {
this.getSnapshotState(filepath).clearTest(testId);
}
getSnapshotState(filepath) {
let state = this.snapshotStateMap.get(filepath);
if (!state)
throw new Error(`The snapshot state for '${filepath}' is not found. Did you call 'SnapshotClient.setup()'?`);
return state;
}
match(options) {
let { filepath, name, testId = name, message, isInline = !1, properties, inlineSnapshot, error, errorMessage, rawSnapshot, assertionName } = options, { received } = options;
if (!filepath)
throw new Error("Snapshot cannot be used outside of test");
let snapshotState = this.getSnapshotState(filepath), testName2 = [name, ...message ? [message] : []].join(" > "), expectedSnapshot = snapshotState.probeExpectedSnapshot({
testName: testName2,
testId,
isInline,
inlineSnapshot
});
if (typeof properties == "object") {
if (typeof received != "object" || !received)
throw expectedSnapshot.markAsChecked(), new Error("Received value must be an object when the matcher has properties");
let propertiesPass;
try {
propertiesPass = this.options.isEqual?.(received, properties) ?? !1;
} catch (err) {
throw expectedSnapshot.markAsChecked(), err;
}
if (!propertiesPass)
return expectedSnapshot.markAsChecked(), {
pass: !1,
message: () => errorMessage || "Snapshot properties mismatched",
actual: received,
expected: properties
};
received = deepMergeSnapshot(received, properties);
}
let { actual, expected, key, pass } = snapshotState.match({
testId,
testName: testName2,
received,
isInline,
error,
inlineSnapshot,
rawSnapshot,
assertionName
});
return {
pass,
message: () => `Snapshot \`${key || "unknown"}\` mismatched`,
actual: rawSnapshot ? actual : actual?.trim(),
expected: rawSnapshot ? expected : expected?.trim()
};
}
assert(options) {
let result = this.match(options);
if (!result.pass) {
let snapshotState = this.getSnapshotState(options.filepath);
throw createMismatchError(result.message(), snapshotState.expand, result.actual, result.expected);
}
}
matchDomain(options) {
let { received, filepath, name, testId = name, message, adapter, isInline = !1, inlineSnapshot, error } = options;
if (!filepath)
throw new Error("Snapshot cannot be used outside of test");
let captured = adapter.capture(received), rendered = adapter.render(captured), snapshotState = this.getSnapshotState(filepath), testName2 = [name, ...message ? [message] : []].join(" > "), expectedSnapshot = snapshotState.probeExpectedSnapshot({
testName: testName2,
testId,
isInline,
inlineSnapshot
});
expectedSnapshot.markAsChecked();
let matchResult = expectedSnapshot.data ? adapter.match(captured, adapter.parseExpected(expectedSnapshot.data)) : void 0, { actual, expected, key, pass } = snapshotState.processDomainSnapshot({
testId,
received: rendered,
expectedSnapshot,
matchResult,
isInline,
error,
assertionName: options.assertionName
});
return {
pass,
message: () => `Snapshot \`${key}\` mismatched`,
actual: actual?.trim(),
expected: expected?.trim()
};
}
async pollMatchDomain(options) {
let { poll, filepath, name, testId = name, message, adapter, isInline = !1, inlineSnapshot, error, timeout = 1e3, interval = 50 } = options;
if (!filepath)
throw new Error("Snapshot cannot be used outside of test");
let snapshotState = this.getSnapshotState(filepath), testName2 = [name, ...message ? [message] : []].join(" > "), expectedSnapshot = snapshotState.probeExpectedSnapshot({
testName: testName2,
testId,
isInline,
inlineSnapshot
}), reference = expectedSnapshot.data && snapshotState.snapshotUpdateState !== "all" ? adapter.parseExpected(expectedSnapshot.data) : void 0, timedOut = timeout > 0 ? new Promise((r) => setTimeout(r, timeout)) : void 0, stableResult = await getStableSnapshot({
adapter,
poll,
interval,
timedOut,
match: reference ? (captured) => adapter.match(captured, reference).pass : void 0
});
if (expectedSnapshot.markAsChecked(), !stableResult?.rendered) {
if (stableResult?.lastPollError)
throw stableResult.lastPollError;
return {
pass: !1,
message: () => "poll() did not produce a stable snapshot within the timeout"
};
}
let matchResult = expectedSnapshot.data ? adapter.match(stableResult.captured, adapter.parseExpected(expectedSnapshot.data)) : void 0, { actual, expected, key, pass } = snapshotState.processDomainSnapshot({
testId,
received: stableResult.rendered,
expectedSnapshot,
matchResult,
isInline,
error,
assertionName: options.assertionName
});
return {
pass,
message: () => `Snapshot \`${key}\` mismatched`,
actual: actual?.trim(),
expected: expected?.trim()
};
}
async assertRaw(options) {
if (!options.rawSnapshot)
throw new Error("Raw snapshot is required");
let { filepath, rawSnapshot } = options;
if (rawSnapshot.content == null) {
if (!filepath)
throw new Error("Snapshot cannot be used outside of test");
let snapshotState = this.getSnapshotState(filepath);
options.filepath ||= filepath, rawSnapshot.file = await snapshotState.environment.resolveRawPath(filepath, rawSnapshot.file), rawSnapshot.content = await snapshotState.environment.readSnapshotFile(rawSnapshot.file) ?? void 0;
}
return this.assert(options);
}
clear() {
this.snapshotStateMap.clear();
}
};
async function getStableSnapshot({ adapter, poll, interval, timedOut, match }) {
let lastRendered, lastPollError, lastStable;
for (; ; ) {
try {
let pollResult = await raceWith(Promise.resolve(poll()), timedOut);
if (!pollResult.ok)
break;
let captured = adapter.capture(pollResult.value), rendered = adapter.render(captured);
if (lastRendered !== void 0 && rendered === lastRendered) {
if (lastStable = {
captured,
rendered
}, !match || match(captured))
break;
} else
lastRendered = rendered, lastStable = void 0;
} catch (pollError) {
lastRendered = void 0, lastStable = void 0, lastPollError = pollError;
}
if (!(await raceWith(new Promise((r) => setTimeout(r, interval)), timedOut)).ok)
break;
}
return {
...lastStable,
lastPollError
};
}
function raceWith(promise, other) {
let left = promise.then((value) => ({
ok: !0,
value
}));
return other ? Promise.race([left, other.then((value) => ({
ok: !1,
value
}))]) : left;
}
// ../../node_modules/.pnpm/vitest@4.1.10_@opentelemetry+api@1.9.1_@types+node@22.20.1_@vitest+coverage-istanbul@3._f51dec9f55339d6c09addddd62782db2/node_modules/vitest/dist/chunks/test.DNmyFkvJ.js
var fakeTimersSrc = {}, global2, hasRequiredGlobal;
function requireGlobal() {
if (hasRequiredGlobal) return global2;
hasRequiredGlobal = 1;
var globalObject;
return typeof commonjsGlobal < "u" ? globalObject = commonjsGlobal : typeof window < "u" ? globalObject = window : globalObject = self, global2 = globalObject, global2;
}
var throwsOnProto_1, hasRequiredThrowsOnProto;
function requireThrowsOnProto() {
if (hasRequiredThrowsOnProto) return throwsOnProto_1;
hasRequiredThrowsOnProto = 1;
let throwsOnProto;
try {
({}).__proto__, throwsOnProto = !1;
} catch {
throwsOnProto = !0;
}
return throwsOnProto_1 = throwsOnProto, throwsOnProto_1;
}
var copyPrototypeMethods, hasRequiredCopyPrototypeMethods;
function requireCopyPrototypeMethods() {
if (hasRequiredCopyPrototypeMethods) return copyPrototypeMethods;
hasRequiredCopyPrototypeMethods = 1;
var call2 = Function.call, throwsOnProto = requireThrowsOnProto(), disallowedProperties = [
// ignore size because it throws from Map
"size",
"caller",
"callee",
"arguments"
];
return throwsOnProto && disallowedProperties.push("__proto__"), copyPrototypeMethods = function(prototype) {
return Object.getOwnPropertyNames(prototype).reduce(
function(result, name) {
return disallowedProperties.includes(name) || typeof prototype[name] != "function" || (result[name] = call2.bind(prototype[name])), result;
},
/* @__PURE__ */ Object.create(null)
);
}, copyPrototypeMethods;
}
var array, hasRequiredArray;
function requireArray() {
if (hasRequiredArray) return array;
hasRequiredArray = 1;
var copyPrototype = requireCopyPrototypeMethods();
return array = copyPrototype(Array.prototype), array;
}
var calledInOrder_1, hasRequiredCalledInOrder;
function requireCalledInOrder() {
if (hasRequiredCalledInOrder) return calledInOrder_1;
hasRequiredCalledInOrder = 1;
var every2 = requireArray().every;
function hasCallsLeft(callMap, spy) {
return callMap[spy.id] === void 0 && (callMap[spy.id] = 0), callMap[spy.id] < spy.callCount;
}
function checkAdjacentCalls(callMap, spy, index2, spies) {
var calledBeforeNext = !0;
return index2 !== spies.length - 1 && (calledBeforeNext = spy.calledBefore(spies[index2 + 1])), hasCallsLeft(callMap, spy) && calledBeforeNext ? (callMap[spy.id] += 1, !0) : !1;
}
function calledInOrder(spies) {
var callMap = {}, _spies = arguments.length > 1 ? arguments : spies;
return every2(_spies, checkAdjacentCalls.bind(null, callMap));
}
return calledInOrder_1 = calledInOrder, calledInOrder_1;
}
var className_1, hasRequiredClassName;
function requireClassName() {
if (hasRequiredClassName) return className_1;
hasRequiredClassName = 1;
function className(value) {
return value.constructor && value.constructor.name || null;
}
return className_1 = className, className_1;
}
var deprecated = {}, hasRequiredDeprecated;
function requireDeprecated() {
return hasRequiredDeprecated || (hasRequiredDeprecated = 1, (function(exports$1) {
exports$1.wrap = function(func, msg) {
var wrapped = function() {
return exports$1.printWarning(msg), func.apply(this, arguments);
};
return func.prototype && (wrapped.prototype = func.prototype), wrapped;
}, exports$1.defaultMsg = function(packageName, funcName) {
return `${packageName}.${funcName} is deprecated and will be removed from the public API in a future version of ${packageName}.`;
}, exports$1.printWarning = function(msg) {
typeof process == "object" && process.emitWarning ? process.emitWarning(msg) : console.info ? console.info(msg) : console.log(msg);
};
})(deprecated)), deprecated;
}
var every, hasRequiredEvery;
function requireEvery() {
return hasRequiredEvery || (hasRequiredEvery = 1, every = function(obj, fn2) {
var pass = !0;
try {
obj.forEach(function() {
if (!fn2.apply(this, arguments))
throw new Error();
});
} catch {
pass = !1;
}
return pass;
}), every;
}
var functionName, hasRequiredFunctionName;
function requireFunctionName() {
return hasRequiredFunctionName || (hasRequiredFunctionName = 1, functionName = function(func) {
if (!func)
return "";
try {
return func.displayName || func.name || // Use function decomposition as a last resort to get function
// name. Does not rely on function decomposition to work - if it
// doesn't debugging will be slightly less informative
// (i.e. toString will say 'spy' rather than 'myFunc').
(String(func).match(/function ([^\s(]+)/) || [])[1];
} catch {
return "";
}
}), functionName;
}
var orderByFirstCall_1, hasRequiredOrderByFirstCall;
function requireOrderByFirstCall() {
if (hasRequiredOrderByFirstCall) return orderByFirstCall_1;
hasRequiredOrderByFirstCall = 1;
var sort2 = requireArray().sort, slice = requireArray().slice;
function comparator(a, b2) {
var aCall = a.getCall(0), bCall = b2.getCall(0), aId = aCall && aCall.callId || -1, bId = bCall && bCall.callId || -1;
return aId < bId ? -1 : 1;
}
function orderByFirstCall(spies) {
return sort2(slice(spies), comparator);
}
return orderByFirstCall_1 = orderByFirstCall, orderByFirstCall_1;
}
var _function, hasRequired_function;
function require_function() {
if (hasRequired_function) return _function;
hasRequired_function = 1;
var copyPrototype = requireCopyPrototypeMethods();
return _function = copyPrototype(Function.prototype), _function;
}
var map, hasRequiredMap;
function requireMap() {
if (hasRequiredMap) return map;
hasRequiredMap = 1;
var copyPrototype = requireCopyPrototypeMethods();
return map = copyPrototype(Map.prototype), map;
}
var object, hasRequiredObject;
function requireObject() {
if (hasRequiredObject) return object;
hasRequiredObject = 1;
var copyPrototype = requireCopyPrototypeMethods();
return object = copyPrototype(Object.prototype), object;
}
var set2, hasRequiredSet;
function requireSet() {
if (hasRequiredSet) return set2;
hasRequiredSet = 1;
var copyPrototype = requireCopyPrototypeMethods();
return set2 = copyPrototype(Set.prototype), set2;
}
var string, hasRequiredString;
function requireString() {
if (hasRequiredString) return string;
hasRequiredString = 1;
var copyPrototype = requireCopyPrototypeMethods();
return string = copyPrototype(String.prototype), string;
}
var prototypes, hasRequiredPrototypes;
function requirePrototypes() {
return hasRequiredPrototypes || (hasRequiredPrototypes = 1, prototypes = {
array: requireArray(),
function: require_function(),
map: requireMap(),
object: requireObject(),
set: requireSet(),
string: requireString()
}), prototypes;
}
var typeDetect$1 = { exports: {} }, typeDetect = typeDetect$1.exports, hasRequiredTypeDetect;
function requireTypeDetect() {
return hasRequiredTypeDetect || (hasRequiredTypeDetect = 1, (function(module, exports$1) {
(function(global3, factory) {
module.exports = factory();
})(typeDetect, (function() {
var promiseExists = typeof Promise == "function", globalObject = typeof self == "object" ? self : commonjsGlobal, symbolExists = typeof Symbol < "u", mapExists = typeof Map < "u", setExists = typeof Set < "u", weakMapExists = typeof WeakMap < "u", weakSetExists = typeof WeakSet < "u", dataViewExists = typeof DataView < "u", symbolIteratorExists = symbolExists && typeof Symbol.iterator < "u", symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag < "u", setEntriesExists = setExists && typeof Set.prototype.entries == "function", mapEntriesExists = mapExists && typeof Map.prototype.entries == "function", setIteratorPrototype = setEntriesExists && Object.getPrototypeOf((/* @__PURE__ */ new Set()).entries()), mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf((/* @__PURE__ */ new Map()).entries()), arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] == "function", arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]()), stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] == "function", stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(""[Symbol.iterator]()), toStringLeftSliceLength = 8, toStringRightSliceLength = -1;
function typeDetect2(obj) {
var typeofObj = typeof obj;
if (typeofObj !== "object")
return typeofObj;
if (obj === null)
return "null";
if (obj === globalObject)
return "global";
if (Array.isArray(obj) && (symbolToStringTagExists === !1 || !(Symbol.toStringTag in obj)))
return "Array";
if (typeof window == "object" && window !== null) {
if (typeof window.location == "object" && obj === window.location)
return "Location";
if (typeof window.document == "object" && obj === window.document)
return "Document";
if (typeof window.navigator == "object") {
if (typeof window.navigator.mimeTypes == "object" && obj === window.navigator.mimeTypes)
return "MimeTypeArray";
if (typeof window.navigator.plugins == "object" && obj === window.navigator.plugins)
return "PluginArray";
}
if ((typeof window.HTMLElement == "function" || typeof window.HTMLElement == "object") && obj instanceof window.HTMLElement) {
if (obj.tagName === "BLOCKQUOTE")
return "HTMLQuoteElement";
if (obj.tagName === "TD")
return "HTMLTableDataCellElement";
if (obj.tagName === "TH")
return "HTMLTableHeaderCellElement";
}
}
var stringTag = symbolToStringTagExists && obj[Symbol.toStringTag];
if (typeof stringTag == "string")
return stringTag;
var objPrototype = Object.getPrototypeOf(obj);
return objPrototype === RegExp.prototype ? "RegExp" : objPrototype === Date.prototype ? "Date" : promiseExists && objPrototype === Promise.prototype ? "Promise" : setExists && objPrototype === Set.prototype ? "Set" : mapExists && objPrototype === Map.prototype ? "Map" : weakSetExists && objPrototype === WeakSet.prototype ? "WeakSet" : weakMapExists && objPrototype === WeakMap.prototype ? "WeakMap" : dataViewExists && objPrototype === DataView.prototype ? "DataView" : mapExists && objPrototype === mapIteratorPrototype ? "Map Iterator" : setExists && objPrototype === setIteratorPrototype ? "Set Iterator" : arrayIteratorExists && objPrototype === arrayIteratorPrototype ? "Array Iterator" : stringIteratorExists && objPrototype === stringIteratorPrototype ? "String Iterator" : objPrototype === null ? "Object" : Object.prototype.toString.call(obj).slice(toStringLeftSliceLength, toStringRightSliceLength);
}
return typeDetect2;
}));
})(typeDetect$1)), typeDetect$1.exports;
}
var typeOf, hasRequiredTypeOf;
function requireTypeOf() {
if (hasRequiredTypeOf) return typeOf;
hasRequiredTypeOf = 1;
var type3 = requireTypeDetect();
return typeOf = function(value) {
return type3(value).toLowerCase();
}, typeOf;
}
var valueToString_1, hasRequiredValueToString;
function requireValueToString() {
if (hasRequiredValueToString) return valueToString_1;
hasRequiredValueToString = 1;
function valueToString(value) {
return value && value.toString ? value.toString() : String(value);
}
return valueToString_1 = valueToString, valueToString_1;
}
var lib, hasRequiredLib;
function requireLib() {
return hasRequiredLib || (hasRequiredLib = 1, lib = {
global: requireGlobal(),
calledInOrder: requireCalledInOrder(),
className: requireClassName(),
deprecated: requireDeprecated(),
every: requireEvery(),
functionName: requireFunctionName(),
orderByFirstCall: requireOrderByFirstCall(),
prototypes: requirePrototypes(),
typeOf: requireTypeOf(),
valueToString: requireValueToString()
}), lib;
}
var hasRequiredFakeTimersSrc;
function requireFakeTimersSrc() {
if (hasRequiredFakeTimersSrc) return fakeTimersSrc;
hasRequiredFakeTimersSrc = 1;
let globalObject = requireLib().global, timersModule, timersPromisesModule;
if (typeof __vitest_required__ < "u") {
try {
timersModule = __vitest_required__.timers;
} catch {
}
try {
timersPromisesModule = __vitest_required__.timersPromises;
} catch {
}
}
function withGlobal(_global) {
let maxTimeout = Math.pow(2, 31) - 1, idCounterStart = 1e12, NOOP = function() {
}, NOOP_ARRAY = function() {
return [];
}, isPresent = {}, timeoutResult, addTimerReturnsObject = !1;
_global.setTimeout && (isPresent.setTimeout = !0, timeoutResult = _global.setTimeout(NOOP, 0), addTimerReturnsObject = typeof timeoutResult == "object"), isPresent.clearTimeout = !!_global.clearTimeout, isPresent.setInterval = !!_global.setInterval, isPresent.clearInterval = !!_global.clearInterval, isPresent.hrtime = _global.process && typeof _global.process.hrtime == "function", isPresent.hrtimeBigint = isPresent.hrtime && typeof _global.process.hrtime.bigint == "function", isPresent.nextTick = _global.process && typeof _global.process.nextTick == "function";
let utilPromisify = _global.process && _global.__vitest_required__ && _global.__vitest_required__.util.promisify;
isPresent.performance = _global.performance && typeof _global.performance.now == "function";
let hasPerformancePrototype = _global.Performance && (typeof _global.Performance).match(/^(function|object)$/), hasPerformanceConstructorPrototype = _global.performance && _global.performance.constructor && _global.performance.constructor.prototype;
isPresent.queueMicrotask = _global.hasOwnProperty("queueMicrotask"), isPresent.requestAnimationFrame = _global.requestAnimationFrame && typeof _global.requestAnimationFrame == "function", isPresent.cancelAnimationFrame = _global.cancelAnimationFrame && typeof _global.cancelAnimationFrame == "function", isPresent.requestIdleCallback = _global.requestIdleCallback && typeof _global.requestIdleCallback == "function", isPresent.cancelIdleCallbackPresent = _global.cancelIdleCallback && typeof _global.cancelIdleCallback == "function", isPresent.setImmediate = _global.setImmediate && typeof _global.setImmediate == "function", isPresent.clearImmediate = _global.clearImmediate && typeof _global.clearImmediate == "function", isPresent.Intl = _global.Intl && typeof _global.Intl == "object", _global.clearTimeout && _global.clearTimeout(timeoutResult);
let NativeDate = _global.Date, NativeIntl = isPresent.Intl ? Object.defineProperties(
/* @__PURE__ */ Object.create(null),
Object.getOwnPropertyDescriptors(_global.Intl)
) : void 0, uniqueTimerId = idCounterStart;
if (NativeDate === void 0)
throw new Error(
"The global scope doesn't have a `Date` object (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)"
);
isPresent.Date = !0;
class FakePerformanceEntry {
constructor(name, entryType, startTime, duration) {
this.name = name, this.entryType = entryType, this.startTime = startTime, this.duration = duration;
}
toJSON() {
return JSON.stringify({ ...this });
}
}
function isNumberFinite(num) {
return Number.isFinite ? Number.isFinite(num) : isFinite(num);
}
let isNearInfiniteLimit = !1;
function checkIsNearInfiniteLimit(clock, i2) {
clock.loopLimit && i2 === clock.loopLimit - 1 && (isNearInfiniteLimit = !0);
}
function resetIsNearInfiniteLimit() {
isNearInfiniteLimit = !1;
}
function parseTime(str) {
if (!str)
return 0;
let strings = str.split(":"), l = strings.length, i2 = l, ms = 0, parsed;
if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str))
throw new Error(
"tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits"
);
for (; i2--; ) {
if (parsed = parseInt(strings[i2], 10), parsed >= 60)
throw new Error(`Invalid time ${str}`);
ms += parsed * Math.pow(60, l - i2 - 1);
}
return ms * 1e3;
}
function nanoRemainder(msFloat) {
let remainder = msFloat * 1e6 % 1e6, positiveRemainder = remainder < 0 ? remainder + 1e6 : remainder;
return Math.floor(positiveRemainder);
}
function getEpoch(epoch) {
if (!epoch)
return 0;
if (typeof epoch.getTime == "function")
return epoch.getTime();
if (typeof epoch == "number")
return epoch;
throw new TypeError("now should be milliseconds since UNIX epoch");
}
function inRange(from, to, timer) {
return timer && timer.callAt >= from && timer.callAt <= to;
}
function getInfiniteLoopError(clock, job) {
let infiniteLoopError = new Error(
`Aborting after running ${clock.loopLimit} timers, assuming an infinite loop!`
);
if (!job.error)
return infiniteLoopError;
let computedTargetPattern = /target\.*[<|(|[].*?[>|\]|)]\s*/, clockMethodPattern = new RegExp(
String(Object.keys(clock).join("|"))
);
addTimerReturnsObject && (clockMethodPattern = new RegExp(
`\\s+at (Object\\.)?(?:${Object.keys(clock).join("|")})\\s+`
));
let matchedLineIndex = -1;
job.error.stack.split(`
`).some(function(line, i2) {
return line.match(computedTargetPattern) ? (matchedLineIndex = i2, !0) : line.match(clockMethodPattern) ? (matchedLineIndex = i2, !1) : matchedLineIndex >= 0;
});
let stack = `${infiniteLoopError}
${job.type || "Microtask"} - ${job.func.name || "anonymous"}
${job.error.stack.split(`
`).slice(matchedLineIndex + 1).join(`
`)}`;
try {
Object.defineProperty(infiniteLoopError, "stack", {
value: stack
});
} catch {
}
return infiniteLoopError;
}
function createDate() {
class ClockDate extends NativeDate {
/**
* @param {number} year
* @param {number} month
* @param {number} date
* @param {number} hour
* @param {number} minute
* @param {number} second
* @param {number} ms
* @returns void
*/
// eslint-disable-next-line no-unused-vars
constructor(year, month, date, hour, minute, second, ms) {
arguments.length === 0 ? super(ClockDate.clock.now) : super(...arguments), Object.defineProperty(this, "constructor", {
value: NativeDate,
enumerable: !1
});
}
static [Symbol.hasInstance](instance) {
return instance instanceof NativeDate;
}
}
return ClockDate.isFake = !0, NativeDate.now && (ClockDate.now = function() {
return ClockDate.clock.now;
}), NativeDate.toSource && (ClockDate.toSource = function() {
return NativeDate.toSource();
}), ClockDate.toString = function() {
return NativeDate.toString();
}, new Proxy(ClockDate, {
// handler for [[Call]] invocations (i.e. not using `new`)
apply() {
if (this instanceof ClockDate)
throw new TypeError(
"A Proxy should only capture `new` calls with the `construct` handler. This is not supposed to be possible, so check the logic."
);
return new NativeDate(ClockDate.clock.now).toString();
}
});
}
function createIntl() {
let ClockIntl = {};
return Object.getOwnPropertyNames(NativeIntl).forEach(
(property) => ClockIntl[property] = NativeIntl[property]
), ClockIntl.DateTimeFormat = function(...args) {
let realFormatter = new NativeIntl.DateTimeFormat(...args), formatter = {};
return ["formatRange", "formatRangeToParts", "resolvedOptions"].forEach(
(method) => {
formatter[method] = realFormatter[method].bind(realFormatter);
}
), ["format", "formatToParts"].forEach((method) => {
formatter[method] = function(date) {
return realFormatter[method](date || ClockIntl.clock.now);
};
}), formatter;
}, ClockIntl.DateTimeFormat.prototype = Object.create(
NativeIntl.DateTimeFormat.prototype
), ClockIntl.DateTimeFormat.supportedLocalesOf = NativeIntl.DateTimeFormat.supportedLocalesOf, ClockIntl;
}
function enqueueJob(clock, job) {
clock.jobs || (clock.jobs = []), clock.jobs.push(job);
}
function runJobs(clock) {
if (clock.jobs) {
for (let i2 = 0; i2 < clock.jobs.length; i2++) {
let job = clock.jobs[i2];
if (job.func.apply(null, job.args), checkIsNearInfiniteLimit(clock, i2), clock.loopLimit && i2 > clock.loopLimit)
throw getInfiniteLoopError(clock, job);
}
resetIsNearInfiniteLimit(), clock.jobs = [];
}
}
function addTimer(clock, timer) {
if (timer.func === void 0)
throw new Error("Callback must be provided to timer calls");
if (addTimerReturnsObject && typeof timer.func != "function")
throw new TypeError(
`[ERR_INVALID_CALLBACK]: Callback must be a function. Received ${timer.func} of type ${typeof timer.func}`
);
if (isNearInfiniteLimit && (timer.error = new Error()), timer.type = timer.immediate ? "Immediate" : "Timeout", timer.hasOwnProperty("delay") && (typeof timer.delay != "number" && (timer.delay = parseInt(timer.delay, 10)), isNumberFinite(timer.delay) || (timer.delay = 0), timer.delay = timer.delay > maxTimeout ? 1 : timer.delay, timer.delay = Math.max(0, timer.delay)), timer.hasOwnProperty("interval") && (timer.type = "Interval", timer.interval = timer.interval > maxTimeout ? 1 : timer.interval), timer.hasOwnProperty("animation") && (timer.type = "AnimationFrame", timer.animation = !0), timer.hasOwnProperty("idleCallback") && (timer.type = "IdleCallback", timer.idleCallback = !0), clock.timers || (clock.timers = {}), timer.id = uniqueTimerId++, timer.createdAt = clock.now, timer.callAt = clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0)), clock.timers[timer.id] = timer, addTimerReturnsObject) {
let res = {
refed: !0,
ref: function() {
return this.refed = !0, res;
},
unref: function() {
return this.refed = !1, res;
},
hasRef: function() {
return this.refed;
},
refresh: function() {
return timer.callAt = clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0)), clock.timers[timer.id] = timer, res;
},
[Symbol.toPrimitive]: function() {
return timer.id;
}
};
return res;
}
return timer.id;
}
function compareTimers(a, b2) {
if (a.callAt < b2.callAt)
return -1;
if (a.callAt > b2.callAt)
return 1;
if (a.immediate && !b2.immediate)
return -1;
if (!a.immediate && b2.immediate)
return 1;
if (a.createdAt < b2.createdAt)
return -1;
if (a.createdAt > b2.createdAt)
return 1;
if (a.id < b2.id)
return -1;
if (a.id > b2.id)
return 1;
}
function firstTimerInRange(clock, from, to) {
let timers2 = clock.timers, timer = null, id, isInRange;
for (id in timers2)
timers2.hasOwnProperty(id) && (isInRange = inRange(from, to, timers2[id]), isInRange && (!timer || compareTimers(timer, timers2[id]) === 1) && (timer = timers2[id]));
return timer;
}
function firstTimer(clock) {
let timers2 = clock.timers, timer = null, id;
for (id in timers2)
timers2.hasOwnProperty(id) && (!timer || compareTimers(timer, timers2[id]) === 1) && (timer = timers2[id]);
return timer;
}
function lastTimer(clock) {
let timers2 = clock.timers, timer = null, id;
for (id in timers2)
timers2.hasOwnProperty(id) && (!timer || compareTimers(timer, timers2[id]) === -1) && (timer = timers2[id]);
return timer;
}
function callTimer(clock, timer) {
if (typeof timer.interval == "number" ? clock.timers[timer.id].callAt += timer.interval : delete clock.timers[timer.id], typeof timer.func == "function")
timer.func.apply(null, timer.args);
else {
let eval2 = eval;
(function() {
eval2(timer.func);
})();
}
}
function getClearHandler(ttype) {
return ttype === "IdleCallback" || ttype === "AnimationFrame" ? `cancel${ttype}` : `clear${ttype}`;
}
function getScheduleHandler(ttype) {
return ttype === "IdleCallback" || ttype === "AnimationFrame" ? `request${ttype}` : `set${ttype}`;
}
function createWarnOnce() {
let calls = 0;
return function(msg) {
!calls++ && console.warn(msg);
};
}
let warnOnce = createWarnOnce();
function clearTimer(clock, timerId, ttype) {
if (!timerId)
return;
clock.timers || (clock.timers = {});
let id = Number(timerId);
if (Number.isNaN(id) || id < idCounterStart) {
let handlerName = getClearHandler(ttype);
if (clock.shouldClearNativeTimers === !0) {
let nativeHandler = clock[`_${handlerName}`];
return typeof nativeHandler == "function" ? nativeHandler(timerId) : void 0;
}
warnOnce(
`FakeTimers: ${handlerName} was invoked to clear a native timer instead of one created by this library.
To automatically clean-up native timers, use \`shouldClearNativeTimers\`.`
);
}
if (clock.timers.hasOwnProperty(id)) {
let timer = clock.timers[id];
if (timer.type === ttype || timer.type === "Timeout" && ttype === "Interval" || timer.type === "Interval" && ttype === "Timeout")
delete clock.timers[id];
else {
let clear = getClearHandler(ttype), schedule = getScheduleHandler(timer.type);
throw new Error(
`Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()`
);
}
}
}
function uninstall(clock) {
let method, i2, l, installedHrTime = "_hrtime", installedNextTick = "_nextTick";
for (i2 = 0, l = clock.methods.length; i2 < l; i2++) {
if (method = clock.methods[i2], method === "hrtime" && _global.process)
_global.process.hrtime = clock[installedHrTime];
else if (method === "nextTick" && _global.process)
_global.process.nextTick = clock[installedNextTick];
else if (method === "performance") {
let originalPerfDescriptor = Object.getOwnPropertyDescriptor(
clock,
`_${method}`
);
originalPerfDescriptor && originalPerfDescriptor.get && !originalPerfDescriptor.set ? Object.defineProperty(
_global,
method,
originalPerfDescriptor
) : originalPerfDescriptor.configurable && (_global[method] = clock[`_${method}`]);
} else if (_global[method] && _global[method].hadOwnProperty)
_global[method] = clock[`_${method}`];
else
try {
delete _global[method];
} catch {
}
if (clock.timersModuleMethods !== void 0)
for (let j = 0; j < clock.timersModuleMethods.length; j++) {
let entry = clock.timersModuleMethods[j];
timersModule[entry.methodName] = entry.original;
}
if (clock.timersPromisesModuleMethods !== void 0)
for (let j = 0; j < clock.timersPromisesModuleMethods.length; j++) {
let entry = clock.timersPromisesModuleMethods[j];
timersPromisesModule[entry.methodName] = entry.original;
}
}
clock.setTickMode("manual"), clock.methods = [];
for (let [listener, signal] of clock.abortListenerMap.entries())
signal.removeEventListener("abort", listener), clock.abortListenerMap.delete(listener);
return clock.timers ? Object.keys(clock.timers).map(function(key) {
return clock.timers[key];
}) : [];
}
function hijackMethod(target, method, clock) {
if (clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(
target,
method
), clock[`_${method}`] = target[method], method === "Date")
target[method] = clock[method];
else if (method === "Intl")
target[method] = clock[method];
else if (method === "performance") {
let originalPerfDescriptor = Object.getOwnPropertyDescriptor(
target,
method
);
if (originalPerfDescriptor && originalPerfDescriptor.get && !originalPerfDescriptor.set) {
Object.defineProperty(
clock,
`_${method}`,
originalPerfDescriptor
);
let perfDescriptor = Object.getOwnPropertyDescriptor(
clock,
method
);
Object.defineProperty(target, method, perfDescriptor);
} else
target[method] = clock[method];
} else
target[method] = function() {
return clock[method].apply(clock, arguments);
}, Object.defineProperties(
target[method],
Object.getOwnPropertyDescriptors(clock[method])
);
target[method].clock = clock;
}
function doIntervalTick(clock, advanceTimeDelta) {
clock.tick(advanceTimeDelta);
}
let timers = {
setTimeout: _global.setTimeout,
clearTimeout: _global.clearTimeout,
setInterval: _global.setInterval,
clearInterval: _global.clearInterval,
Date: _global.Date
};
isPresent.setImmediate && (timers.setImmediate = _global.setImmediate), isPresent.clearImmediate && (timers.clearImmediate = _global.clearImmediate), isPresent.hrtime && (timers.hrtime = _global.process.hrtime), isPresent.nextTick && (timers.nextTick = _global.process.nextTick), isPresent.performance && (timers.performance = _global.performance), isPresent.requestAnimationFrame && (timers.requestAnimationFrame = _global.requestAnimationFrame), isPresent.queueMicrotask && (timers.queueMicrotask = _global.queueMicrotask), isPresent.cancelAnimationFrame && (timers.cancelAnimationFrame = _global.cancelAnimationFrame), isPresent.requestIdleCallback && (timers.requestIdleCallback = _global.requestIdleCallback), isPresent.cancelIdleCallback && (timers.cancelIdleCallback = _global.cancelIdleCallback), isPresent.Intl && (timers.Intl = NativeIntl);
let originalSetTimeout = _global.setImmediate || _global.setTimeout, originalClearInterval = _global.clearInterval, originalSetInterval = _global.setInterval;
function createClock(start, loopLimit) {
start = Math.floor(getEpoch(start)), loopLimit = loopLimit || 1e3;
let nanos = 0, adjustedSystemTime = [0, 0], clock = {
now: start,
Date: createDate(),
loopLimit,
tickMode: { mode: "manual", counter: 0, delta: void 0 }
};
clock.Date.clock = clock;
function getTimeToNextFrame() {
return 16 - (clock.now - start) % 16;
}
function hrtime(prev) {
let millisSinceStart = clock.now - adjustedSystemTime[0] - start, secsSinceStart = Math.floor(millisSinceStart / 1e3), remainderInNanos = (millisSinceStart - secsSinceStart * 1e3) * 1e6 + nanos - adjustedSystemTime[1];
if (Array.isArray(prev)) {
if (prev[1] > 1e9)
throw new TypeError(
"Number of nanoseconds can't exceed a billion"
);
let oldSecs = prev[0], nanoDiff = remainderInNanos - prev[1], secDiff = secsSinceStart - oldSecs;
return nanoDiff < 0 && (nanoDiff += 1e9, secDiff -= 1), [secDiff, nanoDiff];
}
return [secsSinceStart, remainderInNanos];
}
function fakePerformanceNow() {
let hrt = hrtime();
return hrt[0] * 1e3 + hrt[1] / 1e6;
}
isPresent.hrtimeBigint && (hrtime.bigint = function() {
let parts = hrtime();
return BigInt(parts[0]) * BigInt(1e9) + BigInt(parts[1]);
}), isPresent.Intl && (clock.Intl = createIntl(), clock.Intl.clock = clock), clock.setTickMode = function(tickModeConfig) {
let { mode: newMode, delta: newDelta } = tickModeConfig, { mode: oldMode, delta: oldDelta } = clock.tickMode;
newMode === oldMode && newDelta === oldDelta || (oldMode === "interval" && originalClearInterval(clock.attachedInterval), clock.tickMode = {
counter: clock.tickMode.counter + 1,
mode: newMode,
delta: newDelta
}, newMode === "nextAsync" ? advanceUntilModeChanges() : newMode === "interval" && createIntervalTick(clock, newDelta || 20));
};
async function advanceUntilModeChanges() {
async function newMacrotask() {
let channel = new MessageChannel();
await new Promise((resolve2) => {
channel.port1.onmessage = () => {
resolve2(), channel.port1.close();
}, channel.port2.postMessage(void 0);
}), channel.port1.close(), channel.port2.close(), await new Promise((resolve2) => {
originalSetTimeout(resolve2);
});
}
let { counter } = clock.tickMode;
for (; clock.tickMode.counter === counter; ) {
if (await newMacrotask(), clock.tickMode.counter !== counter)
return;
clock.next();
}
}
function pauseAutoTickUntilFinished(promise) {
return clock.tickMode.mode !== "nextAsync" ? promise : (clock.setTickMode({ mode: "manual" }), promise.finally(() => {
clock.setTickMode({ mode: "nextAsync" });
}));
}
clock.requestIdleCallback = function(func, timeout) {
let timeToNextIdlePeriod = 0;
clock.countTimers() > 0 && (timeToNextIdlePeriod = 50);
let result = addTimer(clock, {
func,
args: Array.prototype.slice.call(arguments, 2),
delay: typeof timeout > "u" ? timeToNextIdlePeriod : Math.min(timeout, timeToNextIdlePeriod),
idleCallback: !0
});
return Number(result);
}, clock.cancelIdleCallback = function(timerId) {
return clearTimer(clock, timerId, "IdleCallback");
}, clock.setTimeout = function(func, timeout) {
return addTimer(clock, {
func,
args: Array.prototype.slice.call(arguments, 2),
delay: timeout
});
}, typeof _global.Promise < "u" && utilPromisify && (clock.setTimeout[utilPromisify.custom] = function(timeout, arg) {
return new _global.Promise(function(resolve2) {
addTimer(clock, {
func: resolve2,
args: [arg],
delay: timeout
});
});
}), clock.clearTimeout = function(timerId) {
return clearTimer(clock, timerId, "Timeout");
}, clock.nextTick = function(func) {
return enqueueJob(clock, {
func,
args: Array.prototype.slice.call(arguments, 1),
error: isNearInfiniteLimit ? new Error() : null
});
}, clock.queueMicrotask = function(func) {
return clock.nextTick(func);
}, clock.setInterval = function(func, timeout) {
return timeout = parseInt(timeout, 10), addTimer(clock, {
func,
args: Array.prototype.slice.call(arguments, 2),
delay: timeout,
interval: timeout
});
}, clock.clearInterval = function(timerId) {
return clearTimer(clock, timerId, "Interval");
}, isPresent.setImmediate && (clock.setImmediate = function(func) {
return addTimer(clock, {
func,
args: Array.prototype.slice.call(arguments, 1),
immediate: !0
});
}, typeof _global.Promise < "u" && utilPromisify && (clock.setImmediate[utilPromisify.custom] = function(arg) {
return new _global.Promise(
function(resolve2) {
addTimer(clock, {
func: resolve2,
args: [arg],
immediate: !0
});
}
);
}), clock.clearImmediate = function(timerId) {
return clearTimer(clock, timerId, "Immediate");
}), clock.countTimers = function() {
return Object.keys(clock.timers || {}).length + (clock.jobs || []).length;
}, clock.requestAnimationFrame = function(func) {
let result = addTimer(clock, {
func,
delay: getTimeToNextFrame(),
get args() {
return [fakePerformanceNow()];
},
animation: !0
});
return Number(result);
}, clock.cancelAnimationFrame = function(timerId) {
return clearTimer(clock, timerId, "AnimationFrame");
}, clock.runMicrotasks = function() {
runJobs(clock);
};
function doTick(tickValue, isAsync, resolve2, reject) {
let msFloat = typeof tickValue == "number" ? tickValue : parseTime(tickValue), ms = Math.floor(msFloat), remainder = nanoRemainder(msFloat), nanosTotal = nanos + remainder, tickTo = clock.now + ms;
if (msFloat < 0)
throw new TypeError("Negative ticks are not supported");
nanosTotal >= 1e6 && (tickTo += 1, nanosTotal -= 1e6), nanos = nanosTotal;
let tickFrom = clock.now, previous = clock.now, timer, firstException, oldNow, nextPromiseTick, compensationCheck, postTimerCall;
clock.duringTick = !0, oldNow = clock.now, runJobs(clock), oldNow !== clock.now && (tickFrom += clock.now - oldNow, tickTo += clock.now - oldNow);
function doTickInner() {
for (timer = firstTimerInRange(clock, tickFrom, tickTo); timer && tickFrom <= tickTo; ) {
if (clock.timers[timer.id]) {
tickFrom = timer.callAt, clock.now = timer.callAt, oldNow = clock.now;
try {
runJobs(clock), callTimer(clock, timer);
} catch (e) {
firstException = firstException || e;
}
if (isAsync) {
originalSetTimeout(nextPromiseTick);
return;
}
compensationCheck();
}
postTimerCall();
}
if (oldNow = clock.now, runJobs(clock), oldNow !== clock.now && (tickFrom += clock.now - oldNow, tickTo += clock.now - oldNow), clock.duringTick = !1, timer = firstTimerInRange(clock, tickFrom, tickTo), timer)
try {
clock.tick(tickTo - clock.now);
} catch (e) {
firstException = firstException || e;
}
else
clock.now = tickTo, nanos = nanosTotal;
if (firstException)
throw firstException;
if (isAsync)
resolve2(clock.now);
else
return clock.now;
}
return nextPromiseTick = isAsync && function() {
try {
compensationCheck(), postTimerCall(), doTickInner();
} catch (e) {
reject(e);
}
}, compensationCheck = function() {
oldNow !== clock.now && (tickFrom += clock.now - oldNow, tickTo += clock.now - oldNow, previous += clock.now - oldNow);
}, postTimerCall = function() {
timer = firstTimerInRange(clock, previous, tickTo), previous = tickFrom;
}, doTickInner();
}
return clock.tick = function(tickValue) {
return doTick(tickValue, !1);
}, typeof _global.Promise < "u" && (clock.tickAsync = function(tickValue) {
return pauseAutoTickUntilFinished(
new _global.Promise(function(resolve2, reject) {
originalSetTimeout(function() {
try {
doTick(tickValue, !0, resolve2, reject);
} catch (e) {
reject(e);
}
});
})
);
}), clock.next = function() {
runJobs(clock);
let timer = firstTimer(clock);
if (!timer)
return clock.now;
clock.duringTick = !0;
try {
return clock.now = timer.callAt, callTimer(clock, timer), runJobs(clock), clock.now;
} finally {
clock.duringTick = !1;
}
}, typeof _global.Promise < "u" && (clock.nextAsync = function() {
return pauseAutoTickUntilFinished(
new _global.Promise(function(resolve2, reject) {
originalSetTimeout(function() {
try {
let timer = firstTimer(clock);
if (!timer) {
resolve2(clock.now);
return;
}
let err;
clock.duringTick = !0, clock.now = timer.callAt;
try {
callTimer(clock, timer);
} catch (e) {
err = e;
}
clock.duringTick = !1, originalSetTimeout(function() {
err ? reject(err) : resolve2(clock.now);
});
} catch (e) {
reject(e);
}
});
})
);
}), clock.runAll = function() {
let numTimers, i2;
for (runJobs(clock), i2 = 0; i2 < clock.loopLimit; i2++) {
if (!clock.timers || (numTimers = Object.keys(clock.timers).length, numTimers === 0))
return resetIsNearInfiniteLimit(), clock.now;
clock.next(), checkIsNearInfiniteLimit(clock, i2);
}
let excessJob = firstTimer(clock);
throw getInfiniteLoopError(clock, excessJob);
}, clock.runToFrame = function() {
return clock.tick(getTimeToNextFrame());
}, typeof _global.Promise < "u" && (clock.runAllAsync = function() {
return pauseAutoTickUntilFinished(
new _global.Promise(function(resolve2, reject) {
let i2 = 0;
function doRun() {
originalSetTimeout(function() {
try {
runJobs(clock);
let numTimers;
if (i2 < clock.loopLimit) {
if (!clock.timers) {
resetIsNearInfiniteLimit(), resolve2(clock.now);
return;
}
if (numTimers = Object.keys(
clock.timers
).length, numTimers === 0) {
resetIsNearInfiniteLimit(), resolve2(clock.now);
return;
}
clock.next(), i2++, doRun(), checkIsNearInfiniteLimit(clock, i2);
return;
}
let excessJob = firstTimer(clock);
reject(
getInfiniteLoopError(clock, excessJob)
);
} catch (e) {
reject(e);
}
});
}
doRun();
})
);
}), clock.runToLast = function() {
let timer = lastTimer(clock);
return timer ? clock.tick(timer.callAt - clock.now) : (runJobs(clock), clock.now);
}, typeof _global.Promise < "u" && (clock.runToLastAsync = function() {
return pauseAutoTickUntilFinished(
new _global.Promise(function(resolve2, reject) {
originalSetTimeout(function() {
try {
let timer = lastTimer(clock);
timer || (runJobs(clock), resolve2(clock.now)), resolve2(
clock.tickAsync(timer.callAt - clock.now)
);
} catch (e) {
reject(e);
}
});
})
);
}), clock.reset = function() {
nanos = 0, clock.timers = {}, clock.jobs = [], clock.now = start;
}, clock.setSystemTime = function(systemTime) {
let newNow = getEpoch(systemTime), difference = newNow - clock.now, id, timer;
adjustedSystemTime[0] = adjustedSystemTime[0] + difference, adjustedSystemTime[1] = adjustedSystemTime[1] + nanos, clock.now = newNow, nanos = 0;
for (id in clock.timers)
clock.timers.hasOwnProperty(id) && (timer = clock.timers[id], timer.createdAt += difference, timer.callAt += difference);
}, clock.jump = function(tickValue) {
let msFloat = typeof tickValue == "number" ? tickValue : parseTime(tickValue), ms = Math.floor(msFloat);
for (let timer of Object.values(clock.timers))
clock.now + ms > timer.callAt && (timer.callAt = clock.now + ms);
clock.tick(ms);
}, isPresent.performance && (clock.performance = /* @__PURE__ */ Object.create(null), clock.performance.now = fakePerformanceNow), isPresent.hrtime && (clock.hrtime = hrtime), clock;
}
function createIntervalTick(clock, delta) {
let intervalTick = doIntervalTick.bind(null, clock, delta), intervalId = originalSetInterval(intervalTick, delta);
clock.attachedInterval = intervalId;
}
function install(config2) {
if (arguments.length > 1 || config2 instanceof Date || Array.isArray(config2) || typeof config2 == "number")
throw new TypeError(
`FakeTimers.install called with ${String(
config2
)} install requires an object parameter`
);
if (_global.Date.isFake === !0)
throw new TypeError(
"Can't install fake timers twice on the same global object."
);
if (config2 = typeof config2 < "u" ? config2 : {}, config2.shouldAdvanceTime = config2.shouldAdvanceTime || !1, config2.advanceTimeDelta = config2.advanceTimeDelta || 20, config2.shouldClearNativeTimers = config2.shouldClearNativeTimers || !1, config2.target)
throw new TypeError(
"config.target is no longer supported. Use `withGlobal(target)` instead."
);
function handleMissingTimer(timer) {
if (!config2.ignoreMissingTimers)
throw new ReferenceError(
`non-existent timers and/or objects cannot be faked: '${timer}'`
);
}
let i2, l, clock = createClock(config2.now, config2.loopLimit);
if (clock.shouldClearNativeTimers = config2.shouldClearNativeTimers, clock.uninstall = function() {
return uninstall(clock);
}, clock.abortListenerMap = /* @__PURE__ */ new Map(), clock.methods = config2.toFake || [], clock.methods.length === 0 && (clock.methods = Object.keys(timers)), config2.shouldAdvanceTime === !0 && clock.setTickMode({
mode: "interval",
delta: config2.advanceTimeDelta
}), clock.methods.includes("performance")) {
let proto = (() => {
if (hasPerformanceConstructorPrototype)
return _global.performance.constructor.prototype;
if (hasPerformancePrototype)
return _global.Performance.prototype;
})();
if (proto)
Object.getOwnPropertyNames(proto).forEach(function(name) {
name !== "now" && (clock.performance[name] = name.indexOf("getEntries") === 0 ? NOOP_ARRAY : NOOP);
}), clock.performance.mark = (name) => new FakePerformanceEntry(name, "mark", 0, 0), clock.performance.measure = (name) => new FakePerformanceEntry(name, "measure", 0, 100), clock.performance.timeOrigin = getEpoch(config2.now);
else if ((config2.toFake || []).includes("performance"))
return handleMissingTimer("performance");
}
for (_global === globalObject && timersModule && (clock.timersModuleMethods = []), _global === globalObject && timersPromisesModule && (clock.timersPromisesModuleMethods = []), i2 = 0, l = clock.methods.length; i2 < l; i2++) {
let nameOfMethodToReplace = clock.methods[i2];
if (!isPresent[nameOfMethodToReplace]) {
handleMissingTimer(nameOfMethodToReplace);
continue;
}
if (nameOfMethodToReplace === "hrtime" ? _global.process && typeof _global.process.hrtime == "function" && hijackMethod(_global.process, nameOfMethodToReplace, clock) : nameOfMethodToReplace === "nextTick" ? _global.process && typeof _global.process.nextTick == "function" && hijackMethod(_global.process, nameOfMethodToReplace, clock) : hijackMethod(_global, nameOfMethodToReplace, clock), clock.timersModuleMethods !== void 0 && timersModule[nameOfMethodToReplace]) {
let original = timersModule[nameOfMethodToReplace];
clock.timersModuleMethods.push({
methodName: nameOfMethodToReplace,
original
}), timersModule[nameOfMethodToReplace] = _global[nameOfMethodToReplace];
}
clock.timersPromisesModuleMethods !== void 0 && (nameOfMethodToReplace === "setTimeout" ? (clock.timersPromisesModuleMethods.push({
methodName: "setTimeout",
original: timersPromisesModule.setTimeout
}), timersPromisesModule.setTimeout = (delay2, value, options = {}) => new Promise((resolve2, reject) => {
let abort = () => {
options.signal.removeEventListener(
"abort",
abort
), clock.abortListenerMap.delete(abort), clock.clearTimeout(handle), reject(options.signal.reason);
}, handle = clock.setTimeout(() => {
options.signal && (options.signal.removeEventListener(
"abort",
abort
), clock.abortListenerMap.delete(abort)), resolve2(value);
}, delay2);
options.signal && (options.signal.aborted ? abort() : (options.signal.addEventListener(
"abort",
abort
), clock.abortListenerMap.set(
abort,
options.signal
)));
})) : nameOfMethodToReplace === "setImmediate" ? (clock.timersPromisesModuleMethods.push({
methodName: "setImmediate",
original: timersPromisesModule.setImmediate
}), timersPromisesModule.setImmediate = (value, options = {}) => new Promise((resolve2, reject) => {
let abort = () => {
options.signal.removeEventListener(
"abort",
abort
), clock.abortListenerMap.delete(abort), clock.clearImmediate(handle), reject(options.signal.reason);
}, handle = clock.setImmediate(() => {
options.signal && (options.signal.removeEventListener(
"abort",
abort
), clock.abortListenerMap.delete(abort)), resolve2(value);
});
options.signal && (options.signal.aborted ? abort() : (options.signal.addEventListener(
"abort",
abort
), clock.abortListenerMap.set(
abort,
options.signal
)));
})) : nameOfMethodToReplace === "setInterval" && (clock.timersPromisesModuleMethods.push({
methodName: "setInterval",
original: timersPromisesModule.setInterval
}), timersPromisesModule.setInterval = (delay2, value, options = {}) => ({
[Symbol.asyncIterator]: () => {
let createResolvable = () => {
let resolve2, reject, promise = new Promise((res, rej) => {
resolve2 = res, reject = rej;
});
return promise.resolve = resolve2, promise.reject = reject, promise;
}, done = !1, hasThrown = !1, returnCall, nextAvailable = 0, nextQueue = [], handle = clock.setInterval(() => {
nextQueue.length > 0 ? nextQueue.shift().resolve() : nextAvailable++;
}, delay2), abort = () => {
options.signal.removeEventListener(
"abort",
abort
), clock.abortListenerMap.delete(abort), clock.clearInterval(handle), done = !0;
for (let resolvable of nextQueue)
resolvable.resolve();
};
return options.signal && (options.signal.aborted ? done = !0 : (options.signal.addEventListener(
"abort",
abort
), clock.abortListenerMap.set(
abort,
options.signal
))), {
next: async () => {
if (options.signal?.aborted && !hasThrown)
throw hasThrown = !0, options.signal.reason;
if (done)
return { done: !0, value: void 0 };
if (nextAvailable > 0)
return nextAvailable--, { done: !1, value };
let resolvable = createResolvable();
if (nextQueue.push(resolvable), await resolvable, returnCall && nextQueue.length === 0 && returnCall.resolve(), options.signal?.aborted && !hasThrown)
throw hasThrown = !0, options.signal.reason;
return done ? { done: !0, value: void 0 } : { done: !1, value };
},
return: async () => done ? { done: !0, value: void 0 } : (nextQueue.length > 0 && (returnCall = createResolvable(), await returnCall), clock.clearInterval(handle), done = !0, options.signal && (options.signal.removeEventListener(
"abort",
abort
), clock.abortListenerMap.delete(abort)), { done: !0, value: void 0 })
};
}
})));
}
return clock;
}
return {
timers,
createClock,
install,
withGlobal
};
}
let defaultImplementation = withGlobal(globalObject);
return fakeTimersSrc.timers = defaultImplementation.timers, fakeTimersSrc.createClock = defaultImplementation.createClock, fakeTimersSrc.install = defaultImplementation.install, fakeTimersSrc.withGlobal = withGlobal, fakeTimersSrc;
}
var fakeTimersSrcExports = requireFakeTimersSrc(), FakeTimers = class {
_global;
_clock;
// | _fakingTime | _fakingDate |
// +-------------+-------------+
// | false | falsy | initial
// | false | truthy | vi.setSystemTime called first (for mocking only Date without fake timers)
// | true | falsy | vi.useFakeTimers called first
// | true | truthy | unreachable
_fakingTime;
_fakingDate;
_fakeTimers;
_userConfig;
_now = RealDate.now;
constructor({ global: global3, config: config2 }) {
this._userConfig = config2, this._fakingDate = null, this._fakingTime = !1, this._fakeTimers = fakeTimersSrcExports.withGlobal(global3), this._global = global3;
}
clearAllTimers() {
this._fakingTime && this._clock.reset();
}
dispose() {
this.useRealTimers();
}
runAllTimers() {
this._checkFakeTimers() && this._clock.runAll();
}
async runAllTimersAsync() {
this._checkFakeTimers() && await this._clock.runAllAsync();
}
runOnlyPendingTimers() {
this._checkFakeTimers() && this._clock.runToLast();
}
async runOnlyPendingTimersAsync() {
this._checkFakeTimers() && await this._clock.runToLastAsync();
}
advanceTimersToNextTimer(steps = 1) {
if (this._checkFakeTimers()) for (let i2 = steps; i2 > 0 && (this._clock.next(), this._clock.tick(0), this._clock.countTimers() !== 0); i2--)
;
}
async advanceTimersToNextTimerAsync(steps = 1) {
if (this._checkFakeTimers()) for (let i2 = steps; i2 > 0 && (await this._clock.nextAsync(), this._clock.tick(0), this._clock.countTimers() !== 0); i2--)
;
}
advanceTimersByTime(msToRun) {
this._checkFakeTimers() && this._clock.tick(msToRun);
}
async advanceTimersByTimeAsync(msToRun) {
this._checkFakeTimers() && await this._clock.tickAsync(msToRun);
}
advanceTimersToNextFrame() {
this._checkFakeTimers() && this._clock.runToFrame();
}
runAllTicks() {
this._checkFakeTimers() && this._clock.runMicrotasks();
}
useRealTimers() {
this._fakingDate && (resetDate(), this._fakingDate = null), this._fakingTime && (this._clock.uninstall(), this._fakingTime = !1);
}
useFakeTimers() {
let fakeDate = this._fakingDate || Date.now();
this._fakingDate && (resetDate(), this._fakingDate = null), this._fakingTime && this._clock.uninstall();
let toFake = Object.keys(this._fakeTimers.timers).filter((timer) => timer !== "nextTick" && timer !== "queueMicrotask");
if (this._userConfig?.toFake?.includes("nextTick") && isChildProcess()) throw new Error("process.nextTick cannot be mocked inside child_process");
this._clock = this._fakeTimers.install({
now: fakeDate,
...this._userConfig,
toFake: this._userConfig?.toFake || toFake,
ignoreMissingTimers: !0
}), this._fakingTime = !0;
}
reset() {
if (this._checkFakeTimers()) {
let { now: now3 } = this._clock;
this._clock.reset(), this._clock.setSystemTime(now3);
}
}
setSystemTime(now3) {
let date = typeof now3 > "u" || now3 instanceof Date ? now3 : new Date(now3);
this._fakingTime ? this._clock.setSystemTime(date) : (this._fakingDate = date ?? new Date(this.getRealSystemTime()), mockDate(this._fakingDate));
}
getMockedSystemTime() {
return this._fakingTime ? new Date(this._clock.now) : this._fakingDate;
}
getRealSystemTime() {
return this._now();
}
getTimerCount() {
return this._checkFakeTimers() ? this._clock.countTimers() : 0;
}
setTimerTickMode(mode, interval) {
if (this._checkFakeTimers()) if (mode === "manual") this._clock.setTickMode({ mode: "manual" });
else if (mode === "nextTimerAsync") this._clock.setTickMode({ mode: "nextAsync" });
else if (mode === "interval") this._clock.setTickMode({
mode: "interval",
delta: interval
});
else throw new Error(`Invalid tick mode: ${mode}`);
}
configure(config2) {
this._userConfig = config2;
}
isFakeTimers() {
return this._fakingTime;
}
_checkFakeTimers() {
if (!this._fakingTime) throw new Error("A function to advance timers was called but the timers APIs are not mocked. Call `vi.useFakeTimers()` in the test file first.");
return this._fakingTime;
}
};
function copyStackTrace$1(target, source) {
return source.stack !== void 0 && (target.stack = source.stack.replace(source.message, target.message)), target;
}
function waitFor(callback, options = {}) {
let { setTimeout: setTimeout3, setInterval: setInterval2, clearTimeout: clearTimeout3, clearInterval: clearInterval2 } = getSafeTimers(), { interval = 50, timeout = 1e3 } = typeof options == "number" ? { timeout: options } : options, STACK_TRACE_ERROR = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
return new Promise((resolve2, reject) => {
let lastError, promiseStatus = "idle", timeoutId, intervalId, onResolve = (result) => {
timeoutId && clearTimeout3(timeoutId), intervalId && clearInterval2(intervalId), resolve2(result);
}, handleTimeout = () => {
intervalId && clearInterval2(intervalId);
let error = lastError;
error || (error = copyStackTrace$1(/* @__PURE__ */ new Error("Timed out in waitFor!"), STACK_TRACE_ERROR)), reject(error);
}, checkCallback = () => {
if (vi.isFakeTimers() && vi.advanceTimersByTime(interval), promiseStatus !== "pending")
try {
let result = callback();
if (result !== null && typeof result == "object" && typeof result.then == "function") {
let thenable = result;
promiseStatus = "pending", thenable.then((resolvedValue) => {
promiseStatus = "resolved", onResolve(resolvedValue);
}, (rejectedValue) => {
promiseStatus = "rejected", lastError = rejectedValue;
});
} else
return onResolve(result), !0;
} catch (error) {
lastError = error;
}
};
checkCallback() !== !0 && (timeoutId = setTimeout3(handleTimeout, timeout), intervalId = setInterval2(checkCallback, interval));
});
}
function waitUntil(callback, options = {}) {
let { setTimeout: setTimeout3, setInterval: setInterval2, clearTimeout: clearTimeout3, clearInterval: clearInterval2 } = getSafeTimers(), { interval = 50, timeout = 1e3 } = typeof options == "number" ? { timeout: options } : options, STACK_TRACE_ERROR = /* @__PURE__ */ new Error("STACK_TRACE_ERROR");
return new Promise((resolve2, reject) => {
let promiseStatus = "idle", timeoutId, intervalId, onReject = (error) => {
intervalId && clearInterval2(intervalId), error || (error = copyStackTrace$1(/* @__PURE__ */ new Error("Timed out in waitUntil!"), STACK_TRACE_ERROR)), reject(error);
}, onResolve = (result) => {
if (result)
return timeoutId && clearTimeout3(timeoutId), intervalId && clearInterval2(intervalId), resolve2(result), !0;
}, checkCallback = () => {
if (vi.isFakeTimers() && vi.advanceTimersByTime(interval), promiseStatus !== "pending")
try {
let result = callback();
if (result !== null && typeof result == "object" && typeof result.then == "function") {
let thenable = result;
promiseStatus = "pending", thenable.then((resolvedValue) => {
promiseStatus = "resolved", onResolve(resolvedValue);
}, (rejectedValue) => {
promiseStatus = "rejected", onReject(rejectedValue);
});
} else return onResolve(result);
} catch (error) {
onReject(error);
}
};
checkCallback() !== !0 && (timeoutId = setTimeout3(onReject, timeout), intervalId = setInterval2(checkCallback, interval));
});
}
function createVitest() {
let _config = null, state = () => getWorkerState(), _timers, timers = () => _timers ||= new FakeTimers({
global: globalThis,
config: state().config.fakeTimers
}), _stubsGlobal = /* @__PURE__ */ new Map(), _stubsEnv = /* @__PURE__ */ new Map(), _envBooleans = [
"PROD",
"DEV",
"SSR"
], utils = {
useFakeTimers(config2) {
if (isChildProcess() && (config2?.toFake?.includes("nextTick") || state().config?.fakeTimers?.toFake?.includes("nextTick")))
throw new Error('vi.useFakeTimers({ toFake: ["nextTick"] }) is not supported in node:child_process. Use --pool=threads if mocking nextTick is required.');
return config2 ? timers().configure({
...state().config.fakeTimers,
...config2
}) : timers().configure(state().config.fakeTimers), timers().useFakeTimers(), utils;
},
isFakeTimers() {
return timers().isFakeTimers();
},
useRealTimers() {
return timers().useRealTimers(), utils;
},
runOnlyPendingTimers() {
return timers().runOnlyPendingTimers(), utils;
},
async runOnlyPendingTimersAsync() {
return await timers().runOnlyPendingTimersAsync(), utils;
},
runAllTimers() {
return timers().runAllTimers(), utils;
},
async runAllTimersAsync() {
return await timers().runAllTimersAsync(), utils;
},
runAllTicks() {
return timers().runAllTicks(), utils;
},
advanceTimersByTime(ms) {
return timers().advanceTimersByTime(ms), utils;
},
async advanceTimersByTimeAsync(ms) {
return await timers().advanceTimersByTimeAsync(ms), utils;
},
advanceTimersToNextTimer() {
return timers().advanceTimersToNextTimer(), utils;
},
async advanceTimersToNextTimerAsync() {
return await timers().advanceTimersToNextTimerAsync(), utils;
},
advanceTimersToNextFrame() {
return timers().advanceTimersToNextFrame(), utils;
},
getTimerCount() {
return timers().getTimerCount();
},
setSystemTime(time) {
return timers().setSystemTime(time), utils;
},
getMockedSystemTime() {
return timers().getMockedSystemTime();
},
getRealSystemTime() {
return timers().getRealSystemTime();
},
clearAllTimers() {
return timers().clearAllTimers(), utils;
},
setTimerTickMode(mode, interval) {
return timers().setTimerTickMode(mode, interval), utils;
},
spyOn,
fn,
waitFor,
waitUntil,
defineHelper: (fn2) => function(...args) {
let result = fn2.apply(this, args);
return result && typeof result == "object" && typeof result.then == "function" ? (async function() {
return await result;
})() : result;
},
hoisted(factory) {
return assertTypes(factory, '"vi.hoisted" factory', ["function"]), factory();
},
mock(path, factory) {
if (typeof path != "string") throw new TypeError(`vi.mock() expects a string path, but received a ${typeof path}`);
let importer = getImporter("mock");
_mocker().queueMock(path, importer, typeof factory == "function" ? () => factory(() => _mocker().importActual(path, importer, _mocker().getMockContext().callstack)) : factory);
},
unmock(path) {
if (typeof path != "string") throw new TypeError(`vi.unmock() expects a string path, but received a ${typeof path}`);
_mocker().queueUnmock(path, getImporter("unmock"));
},
doMock(path, factory) {
if (typeof path != "string") throw new TypeError(`vi.doMock() expects a string path, but received a ${typeof path}`);
let importer = getImporter("doMock");
_mocker().queueMock(path, importer, typeof factory == "function" ? () => factory(() => _mocker().importActual(path, importer, _mocker().getMockContext().callstack)) : factory);
let rv = {};
return Symbol.dispose && (rv[Symbol.dispose] = () => {
_mocker().queueUnmock(path, importer);
}), rv;
},
doUnmock(path) {
if (typeof path != "string") throw new TypeError(`vi.doUnmock() expects a string path, but received a ${typeof path}`);
let importer = getImporter("doUnmock");
_mocker().queueUnmock(path, importer);
},
async importActual(path) {
let importer = getImporter("importActual");
return _mocker().importActual(path, importer, _mocker().getMockContext().callstack);
},
async importMock(path) {
let importer = getImporter("importMock");
return _mocker().importMock(path, importer);
},
mockObject(value, options) {
return _mocker().mockObject({ value }, void 0, options?.spy ? "autospy" : "automock").value;
},
mocked(item, _options = {}) {
return item;
},
isMockFunction(fn2) {
return isMockFunction(fn2);
},
clearAllMocks() {
return clearAllMocks(), utils;
},
resetAllMocks() {
return resetAllMocks(), utils;
},
restoreAllMocks() {
return restoreAllMocks(), utils;
},
stubGlobal(name, value) {
return _stubsGlobal.has(name) || _stubsGlobal.set(name, Object.getOwnPropertyDescriptor(globalThis, name)), Object.defineProperty(globalThis, name, {
value,
writable: !0,
configurable: !0,
enumerable: !0
}), utils;
},
stubEnv(name, value) {
let env = state().metaEnv;
return _stubsEnv.has(name) || _stubsEnv.set(name, env[name]), _envBooleans.includes(name) ? env[name] = value ? "1" : "" : value === void 0 ? delete env[name] : env[name] = String(value), utils;
},
unstubAllGlobals() {
return _stubsGlobal.forEach((original, name) => {
original ? Object.defineProperty(globalThis, name, original) : Reflect.deleteProperty(globalThis, name);
}), _stubsGlobal.clear(), utils;
},
unstubAllEnvs() {
let env = state().metaEnv;
return _stubsEnv.forEach((original, name) => {
original === void 0 ? delete env[name] : env[name] = original;
}), _stubsEnv.clear(), utils;
},
resetModules() {
return resetModules(state().evaluatedModules), utils;
},
async dynamicImportSettled() {
return waitForImportsToResolve();
},
setConfig(config2) {
_config || (_config = { ...state().config }), Object.assign(state().config, config2);
},
resetConfig() {
_config && Object.assign(state().config, _config);
}
};
return utils;
}
var vitest = createVitest(), vi = vitest;
function _mocker() {
return typeof __vitest_mocker__ < "u" ? __vitest_mocker__ : new Proxy({}, { get(_, name) {
throw new Error(`Vitest mocker was not initialized in this environment. vi.${String(name)}() is forbidden.`);
} });
}
function getImporter(name) {
let stackArray = createSimpleStackTrace({ stackTraceLimit: 5 }).split(`
`);
return parseSingleStack(stackArray[stackArray.findLastIndex((stack) => stack.includes(` at Object.${name}`) || stack.includes(`${name}@`) || stack.includes(` at ${name} (`)) + 1])?.file || "";
}
var unsupported = [
"matchSnapshot",
"toMatchSnapshot",
"toMatchInlineSnapshot",
"toThrowErrorMatchingSnapshot",
"toThrowErrorMatchingInlineSnapshot",
"throws",
"Throw",
"throw",
"toThrow",
"toThrowError"
];
function throwWithCause(error, source) {
throw error.cause == null && (error.cause = /* @__PURE__ */ new Error("Matcher did not succeed in time.")), copyStackTrace(error, source);
}
function createExpectPoll(expect2) {
return function(fn2, options = {}) {
let defaults = getWorkerState().config.expect?.poll ?? {}, { interval = defaults.interval ?? 50, timeout = defaults.timeout ?? 1e3, message } = options, assertion = expect2(null, message).withContext({ poll: !0 });
fn2 = fn2.bind(assertion), chai_exports.util.flag(assertion, "_poll.fn", fn2), chai_exports.util.flag(assertion, "_poll.timeout", timeout), chai_exports.util.flag(assertion, "_poll.interval", interval);
let test5 = chai_exports.util.flag(assertion, "vitest-test");
if (!test5) throw new Error("expect.poll() must be called inside a test");
let proxy = new Proxy(assertion, { get(target, key, receiver) {
let assertionFunction = Reflect.get(target, key, receiver);
if (typeof assertionFunction != "function") return assertionFunction instanceof chai_exports.Assertion ? proxy : assertionFunction;
if (key === "assert") return assertionFunction;
if (typeof key == "string" && unsupported.includes(key)) throw new SyntaxError(`expect.poll() is not supported in combination with .${key}(). Use vi.waitFor() if your assertion condition is unstable.`);
return function(...args) {
let STACK_TRACE_ERROR = /* @__PURE__ */ new Error("STACK_TRACE_ERROR"), promise = async () => {
chai_exports.util.flag(assertion, "_name", key), chai_exports.util.flag(assertion, "error", STACK_TRACE_ERROR);
let onSettled = chai_exports.util.flag(assertion, "_poll.onSettled");
if (Object.getOwnPropertyDescriptor(assertionFunction, "__vitest_poll_takeover__")?.value) try {
let output = await assertionFunction.call(assertion, ...args);
return await onSettled?.({
assertion,
status: "pass"
}), output;
} catch (err) {
await onSettled?.({
assertion,
status: "fail"
}), throwWithCause(err, STACK_TRACE_ERROR);
}
let { setTimeout: setTimeout3, clearTimeout: clearTimeout3 } = getSafeTimers(), executionPhase = "fn", hasTimedOut = !1, timerId = setTimeout3(() => {
hasTimedOut = !0;
}, timeout);
try {
for (; ; ) {
let isLastAttempt = hasTimedOut;
isLastAttempt && chai_exports.util.flag(assertion, "_isLastPollAttempt", !0);
try {
executionPhase = "fn";
let obj = await fn2();
chai_exports.util.flag(assertion, "object", obj), executionPhase = "assertion";
let output = await assertionFunction.call(assertion, ...args);
return await onSettled?.({
assertion,
status: "pass"
}), output;
} catch (err) {
(isLastAttempt || executionPhase === "assertion" && chai_exports.util.flag(assertion, "_poll.assert_once")) && (await onSettled?.({
assertion,
status: "fail"
}), throwWithCause(err, STACK_TRACE_ERROR)), await delay(interval, setTimeout3), vi.isFakeTimers() && vi.advanceTimersByTime(interval);
}
}
} finally {
clearTimeout3(timerId);
}
}, awaited = !1;
test5.onFinished ??= [], test5.onFinished.push(() => {
if (!awaited) {
let negated = chai_exports.util.flag(assertion, "negate") ? "not." : "", assertionString = `expect.${chai_exports.util.flag(assertion, "_poll.element") ? "element(locator)" : "poll(assertion)"}.${negated}${String(key)}()`;
throw copyStackTrace(/* @__PURE__ */ new Error(`${assertionString} was not awaited. This assertion is asynchronous and must be awaited; otherwise, it is not executed to avoid unhandled rejections:
await ${assertionString}
`), STACK_TRACE_ERROR);
}
});
let resultPromise;
return {
then(onFulfilled, onRejected) {
return awaited = !0, (resultPromise ||= promise()).then(onFulfilled, onRejected);
},
catch(onRejected) {
return awaited = !0, (resultPromise ||= promise()).catch(onRejected);
},
finally(onFinally) {
return awaited = !0, (resultPromise ||= promise()).finally(onFinally);
},
[Symbol.toStringTag]: "Promise"
};
};
} });
return proxy;
};
}
function copyStackTrace(target, source) {
return source.stack !== void 0 && (target.stack = source.stack.replace(source.message, target.message)), target;
}
var _client;
function getSnapshotClient() {
return _client || (_client = new SnapshotClient({ isEqual: (received, expected) => equals(received, expected, [iterableEquality, subsetEquality]) })), _client;
}
function getError(expected, promise) {
if (typeof expected != "function") {
if (!promise) throw new Error(`expected must be a function, received ${typeof expected}`);
return expected;
}
try {
expected();
} catch (e) {
return e;
}
throw new Error("snapshot function didn't throw");
}
function getTestNames(test5) {
return {
filepath: test5.file.filepath,
name: getNames(test5).slice(1).join(" > "),
testId: test5.id
};
}
function getAssertionName(assertion) {
let name = chai_exports.util.flag(assertion, "_name");
if (!name) throw new Error("Assertion name is not set. This is a bug in Vitest. Please, open a new issue with reproduction.");
return name;
}
function getTest(obj) {
let test5 = chai_exports.util.flag(obj, "vitest-test");
if (!test5) throw new Error(`'${getAssertionName(obj)}' cannot be used without test context`);
return test5;
}
function validateAssertion(assertion) {
if (chai_exports.util.flag(assertion, "negate")) throw new Error(`${getAssertionName(assertion)} cannot be used with "not"`);
}
var SnapshotPlugin = (chai, utils) => {
for (let key of ["matchSnapshot", "toMatchSnapshot"]) utils.addMethod(chai.Assertion.prototype, key, wrapAssertion(utils, key, function(propertiesOrHint, hint) {
return assertMatchResult(toMatchSnapshotImpl({
assertion: this,
received: utils.flag(this, "object"),
...normalizeArguments(propertiesOrHint, hint)
}), chai.util.flag(this, "message"));
}));
utils.addMethod(chai.Assertion.prototype, "toMatchFileSnapshot", function(filepath, hint) {
utils.flag(this, "_name", "toMatchFileSnapshot"), validateAssertion(this);
let assertPromise = toMatchFileSnapshotImpl({
assertion: this,
received: utils.flag(this, "object"),
filepath,
hint
}).then((result) => assertMatchResult(result, chai.util.flag(this, "message")));
return recordAsyncExpect(getTest(this), assertPromise, createAssertionMessage(utils, this, !0), /* @__PURE__ */ new Error("resolves"), utils.flag(this, "soft"));
}), utils.addMethod(chai.Assertion.prototype, "toMatchInlineSnapshot", wrapAssertion(utils, "toMatchInlineSnapshot", function(propertiesOrInlineSnapshot, inlineSnapshotOrHint, hint) {
return assertMatchResult(toMatchSnapshotImpl({
assertion: this,
received: utils.flag(this, "object"),
isInline: !0,
...normalizeInlineArguments(propertiesOrInlineSnapshot, inlineSnapshotOrHint, hint)
}), chai.util.flag(this, "message"));
})), utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingSnapshot", wrapAssertion(utils, "toThrowErrorMatchingSnapshot", function(propertiesOrHint, hint) {
validateAssertion(this);
let received = utils.flag(this, "object"), promise = utils.flag(this, "promise");
return assertMatchResult(toMatchSnapshotImpl({
assertion: this,
received: getError(received, promise),
...normalizeArguments(propertiesOrHint, hint)
}), chai.util.flag(this, "message"));
})), utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingInlineSnapshot", wrapAssertion(utils, "toThrowErrorMatchingInlineSnapshot", function(inlineSnapshotOrHint, hint) {
validateAssertion(this);
let received = utils.flag(this, "object"), promise = utils.flag(this, "promise");
return assertMatchResult(toMatchSnapshotImpl({
assertion: this,
received: getError(received, promise),
isInline: !0,
...normalizeInlineArguments(void 0, inlineSnapshotOrHint, hint)
}), chai.util.flag(this, "message"));
})), utils.addMethod(chai.expect, "addSnapshotSerializer", addSerializer);
};
function normalizeArguments(propertiesOrHint, hint) {
return typeof propertiesOrHint == "string" ? { hint: propertiesOrHint } : {
properties: propertiesOrHint,
hint
};
}
function normalizeInlineArguments(propertiesOrInlineSnapshot, inlineSnapshotOrHint, hint) {
let inlineSnapshot;
return typeof propertiesOrInlineSnapshot == "string" ? (inlineSnapshot = stripSnapshotIndentation(propertiesOrInlineSnapshot), {
inlineSnapshot,
hint: inlineSnapshotOrHint
}) : (inlineSnapshotOrHint && (inlineSnapshot = stripSnapshotIndentation(inlineSnapshotOrHint)), {
properties: propertiesOrInlineSnapshot,
inlineSnapshot,
hint
});
}
function toMatchSnapshotImpl(options) {
let { assertion } = options;
validateAssertion(assertion);
let assertionName = getAssertionName(assertion), test5 = getTest(assertion);
return getSnapshotClient().match({
received: options.received,
properties: options.properties,
message: options.hint,
isInline: options.isInline,
inlineSnapshot: options.inlineSnapshot,
assertionName,
error: chai_exports.util.flag(assertion, "error"),
...getTestNames(test5)
});
}
async function toMatchFileSnapshotImpl(options) {
let { assertion } = options;
validateAssertion(assertion);
let testNames = getTestNames(getTest(assertion)), snapshotState = getSnapshotClient().getSnapshotState(testNames.filepath), rawSnapshotFile = await snapshotState.environment.resolveRawPath(testNames.filepath, options.filepath), rawSnapshotContent = await snapshotState.environment.readSnapshotFile(rawSnapshotFile);
return getSnapshotClient().match({
received: options.received,
message: options.hint,
rawSnapshot: {
file: rawSnapshotFile,
content: rawSnapshotContent ?? void 0
},
...testNames
});
}
function assertMatchResult(result, customMessage) {
if (!result.pass) {
let errorMessage = (customMessage ? `${customMessage}: ` : "") + result.message();
throw Object.assign(new Error(errorMessage), {
actual: result.actual,
expected: result.expected,
diffOptions: { expand: getWorkerState().config.snapshotOptions.expand }
});
}
}
chai_exports.use(JestExtend);
chai_exports.use(JestChaiExpect);
chai_exports.use(ChaiStyleAssertions);
chai_exports.use(SnapshotPlugin);
chai_exports.use(JestAsymmetricMatchers);
function createExpect(test5) {
let expect2 = ((value, message) => {
let { assertionCalls } = getState(expect2);
setState({ assertionCalls: assertionCalls + 1 }, expect2);
let assert5 = chai_exports.expect(value, message), _test2 = test5 || getCurrentTest();
return _test2 ? assert5.withTest(_test2) : assert5;
});
Object.assign(expect2, chai_exports.expect), Object.assign(expect2, globalThis[ASYMMETRIC_MATCHERS_OBJECT]), expect2.getState = () => getState(expect2), expect2.setState = (state) => setState(state, expect2);
let globalState = getState(globalThis[GLOBAL_EXPECT]) || {};
setState({
...globalState,
assertionCalls: 0,
isExpectingAssertions: !1,
isExpectingAssertionsError: null,
expectedAssertionsNumber: null,
expectedAssertionsNumberErrorGen: null,
get testPath() {
return getWorkerState().filepath;
},
currentTestName: test5 ? test5.fullTestName ?? "" : globalState.currentTestName
}, expect2), expect2.assert = chai_exports.assert, expect2.extend = (matchers) => chai_exports.expect.extend(expect2, matchers), expect2.addEqualityTesters = (customTesters) => addCustomEqualityTesters(customTesters), expect2.soft = (...args) => expect2(...args).withContext({ soft: !0 }), expect2.poll = createExpectPoll(expect2), expect2.unreachable = (message) => {
chai_exports.assert.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
};
function assertions(expected) {
let errorGen = () => /* @__PURE__ */ new Error(`expected number of assertions to be ${expected}, but got ${expect2.getState().assertionCalls}`);
Error.captureStackTrace && Error.captureStackTrace(errorGen(), assertions), expect2.setState({
expectedAssertionsNumber: expected,
expectedAssertionsNumberErrorGen: errorGen
});
}
function hasAssertions() {
let error = /* @__PURE__ */ new Error("expected any number of assertion, but got none");
Error.captureStackTrace && Error.captureStackTrace(error, hasAssertions), expect2.setState({
isExpectingAssertions: !0,
isExpectingAssertionsError: error
});
}
return chai_exports.util.addMethod(expect2, "assertions", assertions), chai_exports.util.addMethod(expect2, "hasAssertions", hasAssertions), expect2.extend(customMatchers), expect2;
}
var globalExpect = createExpect();
Object.defineProperty(globalThis, GLOBAL_EXPECT, {
value: globalExpect,
writable: !0,
configurable: !0
});
var assert4 = chai_exports.assert, should2 = chai_exports.should;
// ../../node_modules/.pnpm/vite@6.4.3_@types+node@22.20.1_jiti@2.6.1_sass@1.100.0_tsx@4.23.1_yaml@2.9.0/node_modules/vite/dist/node/module-runner.js
init_cjs_shims();
var SOURCEMAPPING_URL = "sourceMa";
SOURCEMAPPING_URL += "ppingURL";
var isWindows = typeof process < "u" && process.platform === "win32";
var AsyncFunction = async function() {
}.constructor;
var chars2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", intToChar2 = new Uint8Array(64), charToInt2 = new Uint8Array(128);
for (let i2 = 0; i2 < chars2.length; i2++) {
let c = chars2.charCodeAt(i2);
intToChar2[i2] = c, charToInt2[c] = i2;
}
var MODULE_RUNNER_SOURCEMAPPING_REGEXP = new RegExp(
`//# ${SOURCEMAPPING_URL}=data:application/json;base64,(.+)`
);
var retrieveFileHandlers = /* @__PURE__ */ new Set(), retrieveSourceMapHandlers = /* @__PURE__ */ new Set(), createExecHandlers = (handlers) => (...args) => {
for (let handler of handlers) {
let result = handler(...args);
if (result) return result;
}
return null;
}, retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers), retrieveSourceMapFromHandlers = createExecHandlers(
retrieveSourceMapHandlers
);
var originalPrepare = Error.prepareStackTrace;
// ../../node_modules/.pnpm/vitest@4.1.10_@opentelemetry+api@1.9.1_@types+node@22.20.1_@vitest+coverage-istanbul@3._f51dec9f55339d6c09addddd62782db2/node_modules/vitest/dist/index.js
var import_expect_type = __toESM(require_dist(), 1);
// src/index.test.ts
describe("init", () => {
test2("successfully initializes the app", () => {
globalExpect(!0).toBe(!0);
});
});
/*! Bundled license information:
@vitest/pretty-format/dist/index.js:
(**
* @license React
* react-is.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(**
* @license React
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
@vitest/snapshot/dist/index.js:
(*
* @version 1.4.0
* @date 2015-10-26
* @stability 3 - Stable
* @author Lauri Rooden (https://github.com/litejs/natural-compare-lite)
* @license MIT License
*)
*/
//# sourceMappingURL=index.test.js.map