@vitest/browser 4.1.5 → 5.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/context.d.ts +50 -1
  2. package/dist/client/.vite/manifest.json +15 -6
  3. package/dist/client/__vitest__/assets/index-Cd6On2Pm.js +136 -0
  4. package/dist/client/__vitest__/assets/index-Dw9P28Qt.css +1 -0
  5. package/dist/client/__vitest__/index.html +2 -2
  6. package/dist/client/__vitest_browser__/{orchestrator-DM4mHHP0.js → orchestrator-BfoS0x4w.js} +55 -31
  7. package/dist/client/__vitest_browser__/rrweb-snapshot-xhvrgOHx.js +5476 -0
  8. package/dist/client/__vitest_browser__/{utils-DmkAiRYk.js → tester-BJtW9QqZ.js} +2674 -930
  9. package/dist/client/__vitest_browser__/utils-Nd8hqrhP.js +189 -0
  10. package/dist/client/orchestrator.html +2 -2
  11. package/dist/client/tester/locators.d.ts +69 -0
  12. package/dist/client/tester/tester.html +2 -2
  13. package/dist/client/tester/trace.d.ts +54 -0
  14. package/dist/client.js +1 -0
  15. package/dist/context.js +155 -15
  16. package/dist/expect-element.js +30 -30
  17. package/dist/index.d.ts +6 -22
  18. package/dist/index.js +29 -4551
  19. package/dist/locators-CesZ2RSY.js +5 -0
  20. package/dist/locators.d.ts +9 -1
  21. package/dist/locators.js +1 -1
  22. package/dist/shared/screenshotMatcher/types.d.ts +3 -3
  23. package/dist/state.js +1 -0
  24. package/dist/vendor-types.d.ts +131 -0
  25. package/dist/vendor-types.ts +1 -0
  26. package/package.json +15 -7
  27. package/dist/client/__vitest__/assets/index-BPQdrqGZ.js +0 -94
  28. package/dist/client/__vitest__/assets/index-Da0hb3oU.css +0 -1
  29. package/dist/client/__vitest__/bg.png +0 -0
  30. package/dist/client/__vitest_browser__/tester-Bf18VQr2.js +0 -2288
  31. package/dist/index-D8jtZoIM.js +0 -5
@@ -1,32 +1,166 @@
1
- (function polyfill() {
2
- const relList = document.createElement("link").relList;
3
- if (relList && relList.supports && relList.supports("modulepreload")) return;
4
- for (const link of document.querySelectorAll('link[rel="modulepreload"]')) processPreload(link);
5
- new MutationObserver((mutations) => {
6
- for (const mutation of mutations) {
7
- if (mutation.type !== "childList") continue;
8
- for (const node of mutation.addedNodes) if (node.tagName === "LINK" && node.rel === "modulepreload") processPreload(node);
9
- }
10
- }).observe(document, {
11
- childList: true,
12
- subtree: true
1
+ import { b as resolve$1, g as getBrowserState, n as now$1, m as moduleRunner, c as getWorkerState, a as getConfig$1 } from "./utils-Nd8hqrhP.js";
2
+ import { onCancel, globalChannel, channel, client } from "@vitest/browser/client";
3
+ import { userEvent, page, server } from "vitest/browser";
4
+ import { getSafeTimers as getSafeTimers$1, DecodedMap as DecodedMap$1, getOriginalPosition as getOriginalPosition$1, loadDiffConfig, loadSnapshotSerializers, takeCoverageInsideWorker, format as format$2, setupCommonEnv, startCoverageInsideWorker, stopCoverageInsideWorker, startTests, collectTests, SpyModule } from "vitest/internal/browser";
5
+ import { Traces } from "vitest/internal/traces";
6
+ import { TestRunner, BenchmarkRunner, recordArtifact as recordArtifact$1 } from "vitest";
7
+ const scriptRel = "modulepreload";
8
+ const assetsURL = function(dep) {
9
+ return "/" + dep;
10
+ };
11
+ const seen = {};
12
+ const __vitePreload = function preload(baseModule, deps, importerUrl) {
13
+ let promise = Promise.resolve();
14
+ if (deps && deps.length > 0) {
15
+ let allSettled = function(promises$2) {
16
+ return Promise.all(promises$2.map((p) => Promise.resolve(p).then((value$1) => ({
17
+ status: "fulfilled",
18
+ value: value$1
19
+ }), (reason) => ({
20
+ status: "rejected",
21
+ reason
22
+ }))));
23
+ };
24
+ document.getElementsByTagName("link");
25
+ const cspNonceMeta = document.querySelector("meta[property=csp-nonce]");
26
+ const cspNonce = (cspNonceMeta == null ? void 0 : cspNonceMeta.nonce) || (cspNonceMeta == null ? void 0 : cspNonceMeta.getAttribute("nonce"));
27
+ promise = allSettled(deps.map((dep) => {
28
+ dep = assetsURL(dep);
29
+ if (dep in seen) return;
30
+ seen[dep] = true;
31
+ const isCss = dep.endsWith(".css");
32
+ const cssSelector = isCss ? '[rel="stylesheet"]' : "";
33
+ if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) return;
34
+ const link = document.createElement("link");
35
+ link.rel = isCss ? "stylesheet" : scriptRel;
36
+ if (!isCss) link.as = "script";
37
+ link.crossOrigin = "";
38
+ link.href = dep;
39
+ if (cspNonce) link.setAttribute("nonce", cspNonce);
40
+ document.head.appendChild(link);
41
+ if (isCss) return new Promise((res, rej) => {
42
+ link.addEventListener("load", res);
43
+ link.addEventListener("error", () => rej(/* @__PURE__ */ new Error(`Unable to preload CSS for ${dep}`)));
44
+ });
45
+ }));
46
+ }
47
+ function handlePreloadError(err$2) {
48
+ const e$1 = new Event("vite:preloadError", { cancelable: true });
49
+ e$1.payload = err$2;
50
+ window.dispatchEvent(e$1);
51
+ if (!e$1.defaultPrevented) throw err$2;
52
+ }
53
+ return promise.then((res) => {
54
+ for (const item of res || []) {
55
+ if (item.status !== "rejected") continue;
56
+ handlePreloadError(item.reason);
57
+ }
58
+ return baseModule().catch(handlePreloadError);
59
+ });
60
+ };
61
+ const { parse: $parse } = JSON;
62
+ const { keys } = Object;
63
+ const Primitive = String;
64
+ const primitive = "string";
65
+ const ignore = {};
66
+ const object = "object";
67
+ const noop = (_, value) => value;
68
+ const primitives = (value) => value instanceof Primitive ? Primitive(value) : value;
69
+ const Primitives = (_, value) => typeof value === primitive ? new Primitive(value) : value;
70
+ const resolver = (input, lazy, parsed, $) => (output) => {
71
+ for (let ke = keys(output), { length } = ke, y2 = 0; y2 < length; y2++) {
72
+ const k = ke[y2];
73
+ const value = output[k];
74
+ if (value instanceof Primitive) {
75
+ const tmp = input[+value];
76
+ if (typeof tmp === object && !parsed.has(tmp)) {
77
+ parsed.add(tmp);
78
+ output[k] = ignore;
79
+ lazy.push({ o: output, k, r: tmp });
80
+ } else
81
+ output[k] = $.call(output, k, tmp);
82
+ } else if (output[k] !== ignore)
83
+ output[k] = $.call(output, k, value);
84
+ }
85
+ return output;
86
+ };
87
+ const parse = (text, reviver) => {
88
+ const input = $parse(text, Primitives).map(primitives);
89
+ const $ = noop;
90
+ let value = input[0];
91
+ if (typeof value === object && value) {
92
+ const lazy = [];
93
+ const revive = resolver(input, lazy, /* @__PURE__ */ new Set(), $);
94
+ value = revive(value);
95
+ let i2 = 0;
96
+ while (i2 < lazy.length) {
97
+ const { o, k, r } = lazy[i2++];
98
+ o[k] = $.call(o, k, revive(r));
99
+ }
100
+ }
101
+ return $.call({ "": value }, "", value);
102
+ };
103
+ function showPopupWarning(name, value, defaultValue) {
104
+ return (...params) => {
105
+ const formattedParams = params.map((p) => JSON.stringify(p)).join(", ");
106
+ console.warn(`Vitest encountered a \`${name}(${formattedParams})\` call that it cannot handle by default, so it returned \`${value}\`. Read more in https://vitest.dev/guide/browser/#thread-blocking-dialogs.
107
+ If needed, mock the \`${name}\` call manually like:
108
+
109
+ \`\`\`
110
+ import { expect, vi } from "vitest"
111
+
112
+ vi.spyOn(window, "${name}")${defaultValue ? `.mockReturnValue(${JSON.stringify(defaultValue)})` : ""}
113
+ ${name}(${formattedParams})
114
+ expect(${name}).toHaveBeenCalledWith(${formattedParams})
115
+ \`\`\``);
116
+ return value;
117
+ };
118
+ }
119
+ function setupDialogsSpy() {
120
+ globalThis.alert = showPopupWarning("alert", void 0);
121
+ globalThis.confirm = showPopupWarning("confirm", false, true);
122
+ globalThis.prompt = showPopupWarning("prompt", null, "your value");
123
+ }
124
+ const { get } = Reflect;
125
+ function withSafeTimers(getTimers, fn) {
126
+ const { setTimeout, clearTimeout } = getTimers();
127
+ const currentSetTimeout = globalThis.setTimeout;
128
+ const currentClearTimeout = globalThis.clearTimeout;
129
+ try {
130
+ globalThis.setTimeout = setTimeout;
131
+ globalThis.clearTimeout = clearTimeout;
132
+ const result = fn();
133
+ return result;
134
+ } finally {
135
+ globalThis.setTimeout = currentSetTimeout;
136
+ globalThis.clearTimeout = currentClearTimeout;
137
+ }
138
+ }
139
+ const promises = /* @__PURE__ */ new Set();
140
+ function createSafeRpc(client2) {
141
+ return new Proxy(client2.rpc, {
142
+ get(target, p, handler) {
143
+ if (p === "then") {
144
+ return;
145
+ }
146
+ const sendCall = get(target, p, handler);
147
+ const safeSendCall = (...args) => withSafeTimers(getSafeTimers$1, async () => {
148
+ const result = sendCall(...args);
149
+ promises.add(result);
150
+ try {
151
+ return await result;
152
+ } finally {
153
+ promises.delete(result);
154
+ }
155
+ });
156
+ safeSendCall.asEvent = sendCall.asEvent;
157
+ return safeSendCall;
158
+ }
13
159
  });
14
- function getFetchOpts(link) {
15
- const fetchOpts = {};
16
- if (link.integrity) fetchOpts.integrity = link.integrity;
17
- if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy;
18
- if (link.crossOrigin === "use-credentials") fetchOpts.credentials = "include";
19
- else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit";
20
- else fetchOpts.credentials = "same-origin";
21
- return fetchOpts;
22
- }
23
- function processPreload(link) {
24
- if (link.ep) return;
25
- link.ep = true;
26
- const fetchOpts = getFetchOpts(link);
27
- fetch(link.href, fetchOpts);
28
- }
29
- })();
160
+ }
161
+ function rpc$2() {
162
+ return globalThis.__vitest_worker__.rpc;
163
+ }
30
164
  var b = {
31
165
  reset: [0, 0],
32
166
  bold: [1, 22, "\x1B[22m\x1B[1m"],
@@ -123,19 +257,19 @@ function _mergeNamespaces$1(n, m) {
123
257
  });
124
258
  return Object.freeze(n);
125
259
  }
126
- function getKeysOfEnumerableProperties(object, compareKeys) {
127
- const rawKeys = Object.keys(object);
128
- const keys = compareKeys === null ? rawKeys : rawKeys.sort(compareKeys);
260
+ function getKeysOfEnumerableProperties(object2, compareKeys) {
261
+ const rawKeys = Object.keys(object2);
262
+ const keys2 = compareKeys === null ? rawKeys : rawKeys.sort(compareKeys);
129
263
  if (Object.getOwnPropertySymbols) {
130
- for (const symbol of Object.getOwnPropertySymbols(object)) {
131
- if (Object.getOwnPropertyDescriptor(object, symbol).enumerable) {
132
- keys.push(symbol);
264
+ for (const symbol of Object.getOwnPropertySymbols(object2)) {
265
+ if (Object.getOwnPropertyDescriptor(object2, symbol).enumerable) {
266
+ keys2.push(symbol);
133
267
  }
134
268
  }
135
269
  }
136
- return keys;
270
+ return keys2;
137
271
  }
138
- function printIteratorEntries(iterator, config, indentation, depth, refs, printer2, separator = ": ") {
272
+ function printIteratorEntries(iterator, config, indentation, depth, refs, printer2, separator = ": ", length) {
139
273
  let result = "";
140
274
  let width = 0;
141
275
  let current = iterator.next();
@@ -145,7 +279,7 @@ function printIteratorEntries(iterator, config, indentation, depth, refs, printe
145
279
  while (!current.done) {
146
280
  result += indentationNext;
147
281
  if (width++ === config.maxWidth) {
148
- result += "…";
282
+ result += typeof length === "number" ? `…(${length - width + 1})` : "…";
149
283
  break;
150
284
  }
151
285
  const name = printer2(current.value[0], config, indentationNext, depth, refs);
@@ -162,7 +296,7 @@ function printIteratorEntries(iterator, config, indentation, depth, refs, printe
162
296
  }
163
297
  return result;
164
298
  }
165
- function printIteratorValues(iterator, config, indentation, depth, refs, printer2) {
299
+ function printIteratorValues(iterator, config, indentation, depth, refs, printer2, length) {
166
300
  let result = "";
167
301
  let width = 0;
168
302
  let current = iterator.next();
@@ -172,7 +306,7 @@ function printIteratorValues(iterator, config, indentation, depth, refs, printer
172
306
  while (!current.done) {
173
307
  result += indentationNext;
174
308
  if (width++ === config.maxWidth) {
175
- result += "…";
309
+ result += typeof length === "number" ? `…(${length - width + 1})` : "…";
176
310
  break;
177
311
  }
178
312
  result += printer2(current.value, config, indentationNext, depth, refs);
@@ -198,7 +332,7 @@ function printListItems(list, config, indentation, depth, refs, printer2) {
198
332
  for (let i2 = 0; i2 < length; i2++) {
199
333
  result += indentationNext;
200
334
  if (i2 === config.maxWidth) {
201
- result += "…";
335
+ result += `…(${length - i2})`;
202
336
  break;
203
337
  }
204
338
  if (isDataView(list) || i2 in list) {
@@ -214,18 +348,23 @@ function printListItems(list, config, indentation, depth, refs, printer2) {
214
348
  }
215
349
  return result;
216
350
  }
217
- function printObjectProperties(val, config, indentation, depth, refs, printer2) {
351
+ function printObjectProperties(val, config, indentation, depth, refs, printer2, compareKeysOverride = config.compareKeys) {
218
352
  let result = "";
219
- const keys = getKeysOfEnumerableProperties(val, config.compareKeys);
220
- if (keys.length > 0) {
353
+ const keys2 = getKeysOfEnumerableProperties(val, compareKeysOverride);
354
+ if (keys2.length > 0) {
221
355
  result += config.spacingOuter;
222
356
  const indentationNext = indentation + config.indent;
223
- for (let i2 = 0; i2 < keys.length; i2++) {
224
- const key = keys[i2];
225
- const name = printer2(key, config, indentationNext, depth, refs);
357
+ for (let i2 = 0; i2 < keys2.length; i2++) {
358
+ result += indentationNext;
359
+ if (i2 === config.maxWidth) {
360
+ result += `…(${keys2.length - i2})`;
361
+ break;
362
+ }
363
+ const key = keys2[i2];
364
+ const name = !config.quoteKeys && isUnquotableKey(key) ? key : printer2(key, config, indentationNext, depth, refs);
226
365
  const value = printer2(val[key], config, indentationNext, depth, refs);
227
- result += `${indentationNext + name}: ${value}`;
228
- if (i2 < keys.length - 1) {
366
+ result += `${name}: ${value}`;
367
+ if (i2 < keys2.length - 1) {
229
368
  result += `,${config.spacingInner}`;
230
369
  } else if (!config.min) {
231
370
  result += ",";
@@ -235,6 +374,10 @@ function printObjectProperties(val, config, indentation, depth, refs, printer2)
235
374
  }
236
375
  return result;
237
376
  }
377
+ const keyStrRegExp = /^[a-z_]\w*$/i;
378
+ function isUnquotableKey(key) {
379
+ return typeof key === "string" && key !== "__proto__" && keyStrRegExp.test(key);
380
+ }
238
381
  const asymmetricMatcher = typeof Symbol === "function" && Symbol.for ? Symbol.for("jest.asymmetricMatcher") : 1267621;
239
382
  const SPACE$2 = " ";
240
383
  const serialize$5 = (val, config, indentation, depth, refs, printer2) => {
@@ -294,10 +437,10 @@ const plugin$4 = {
294
437
  function escapeHTML(str) {
295
438
  return str.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
296
439
  }
297
- function printProps(keys, props, config, indentation, depth, refs, printer2) {
440
+ function printProps(keys2, props, config, indentation, depth, refs, printer2) {
298
441
  const indentationNext = indentation + config.indent;
299
442
  const colors = config.colors;
300
- return keys.map((key) => {
443
+ return keys2.map((key) => {
301
444
  const value = props[key];
302
445
  if (typeof value === "string" && value[0] === "_" && value.startsWith("__vitest_") && value.match(/__vitest_\d+__/)) {
303
446
  return "";
@@ -503,28 +646,28 @@ function requireReactIs_production() {
503
646
  if (hasRequiredReactIs_production) return reactIs_production;
504
647
  hasRequiredReactIs_production = 1;
505
648
  var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"), REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference");
506
- function typeOf(object) {
507
- if ("object" === typeof object && null !== object) {
508
- var $$typeof = object.$$typeof;
649
+ function typeOf(object2) {
650
+ if ("object" === typeof object2 && null !== object2) {
651
+ var $$typeof = object2.$$typeof;
509
652
  switch ($$typeof) {
510
653
  case REACT_ELEMENT_TYPE:
511
- switch (object = object.type, object) {
654
+ switch (object2 = object2.type, object2) {
512
655
  case REACT_FRAGMENT_TYPE:
513
656
  case REACT_PROFILER_TYPE:
514
657
  case REACT_STRICT_MODE_TYPE:
515
658
  case REACT_SUSPENSE_TYPE:
516
659
  case REACT_SUSPENSE_LIST_TYPE:
517
660
  case REACT_VIEW_TRANSITION_TYPE:
518
- return object;
661
+ return object2;
519
662
  default:
520
- switch (object = object && object.$$typeof, object) {
663
+ switch (object2 = object2 && object2.$$typeof, object2) {
521
664
  case REACT_CONTEXT_TYPE:
522
665
  case REACT_FORWARD_REF_TYPE:
523
666
  case REACT_LAZY_TYPE:
524
667
  case REACT_MEMO_TYPE:
525
- return object;
668
+ return object2;
526
669
  case REACT_CONSUMER_TYPE:
527
- return object;
670
+ return object2;
528
671
  default:
529
672
  return $$typeof;
530
673
  }
@@ -546,41 +689,41 @@ function requireReactIs_production() {
546
689
  reactIs_production.StrictMode = REACT_STRICT_MODE_TYPE;
547
690
  reactIs_production.Suspense = REACT_SUSPENSE_TYPE;
548
691
  reactIs_production.SuspenseList = REACT_SUSPENSE_LIST_TYPE;
549
- reactIs_production.isContextConsumer = function(object) {
550
- return typeOf(object) === REACT_CONSUMER_TYPE;
692
+ reactIs_production.isContextConsumer = function(object2) {
693
+ return typeOf(object2) === REACT_CONSUMER_TYPE;
551
694
  };
552
- reactIs_production.isContextProvider = function(object) {
553
- return typeOf(object) === REACT_CONTEXT_TYPE;
695
+ reactIs_production.isContextProvider = function(object2) {
696
+ return typeOf(object2) === REACT_CONTEXT_TYPE;
554
697
  };
555
- reactIs_production.isElement = function(object) {
556
- return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
698
+ reactIs_production.isElement = function(object2) {
699
+ return "object" === typeof object2 && null !== object2 && object2.$$typeof === REACT_ELEMENT_TYPE;
557
700
  };
558
- reactIs_production.isForwardRef = function(object) {
559
- return typeOf(object) === REACT_FORWARD_REF_TYPE;
701
+ reactIs_production.isForwardRef = function(object2) {
702
+ return typeOf(object2) === REACT_FORWARD_REF_TYPE;
560
703
  };
561
- reactIs_production.isFragment = function(object) {
562
- return typeOf(object) === REACT_FRAGMENT_TYPE;
704
+ reactIs_production.isFragment = function(object2) {
705
+ return typeOf(object2) === REACT_FRAGMENT_TYPE;
563
706
  };
564
- reactIs_production.isLazy = function(object) {
565
- return typeOf(object) === REACT_LAZY_TYPE;
707
+ reactIs_production.isLazy = function(object2) {
708
+ return typeOf(object2) === REACT_LAZY_TYPE;
566
709
  };
567
- reactIs_production.isMemo = function(object) {
568
- return typeOf(object) === REACT_MEMO_TYPE;
710
+ reactIs_production.isMemo = function(object2) {
711
+ return typeOf(object2) === REACT_MEMO_TYPE;
569
712
  };
570
- reactIs_production.isPortal = function(object) {
571
- return typeOf(object) === REACT_PORTAL_TYPE;
713
+ reactIs_production.isPortal = function(object2) {
714
+ return typeOf(object2) === REACT_PORTAL_TYPE;
572
715
  };
573
- reactIs_production.isProfiler = function(object) {
574
- return typeOf(object) === REACT_PROFILER_TYPE;
716
+ reactIs_production.isProfiler = function(object2) {
717
+ return typeOf(object2) === REACT_PROFILER_TYPE;
575
718
  };
576
- reactIs_production.isStrictMode = function(object) {
577
- return typeOf(object) === REACT_STRICT_MODE_TYPE;
719
+ reactIs_production.isStrictMode = function(object2) {
720
+ return typeOf(object2) === REACT_STRICT_MODE_TYPE;
578
721
  };
579
- reactIs_production.isSuspense = function(object) {
580
- return typeOf(object) === REACT_SUSPENSE_TYPE;
722
+ reactIs_production.isSuspense = function(object2) {
723
+ return typeOf(object2) === REACT_SUSPENSE_TYPE;
581
724
  };
582
- reactIs_production.isSuspenseList = function(object) {
583
- return typeOf(object) === REACT_SUSPENSE_LIST_TYPE;
725
+ reactIs_production.isSuspenseList = function(object2) {
726
+ return typeOf(object2) === REACT_SUSPENSE_LIST_TYPE;
584
727
  };
585
728
  reactIs_production.isValidElementType = function(type) {
586
729
  return "string" === typeof type || "function" === typeof type || type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || "object" === typeof type && null !== type && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_CONSUMER_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_CLIENT_REFERENCE || void 0 !== type.getModuleId) ? true : false;
@@ -753,7 +896,7 @@ function getChildren(arg, children = []) {
753
896
  }
754
897
  return children;
755
898
  }
756
- function getType(element) {
899
+ function getType$1(element) {
757
900
  const type = element.type;
758
901
  if (typeof type === "string") {
759
902
  return type;
@@ -792,24 +935,24 @@ function getPropKeys$1(element) {
792
935
  const { props } = element;
793
936
  return Object.keys(props).filter((key) => key !== "children" && props[key] !== void 0).sort();
794
937
  }
795
- const serialize$1 = (element, config, indentation, depth, refs, printer2) => ++depth > config.maxDepth ? printElementAsLeaf(getType(element), config) : printElement(getType(element), printProps(getPropKeys$1(element), element.props, config, indentation + config.indent, depth, refs, printer2), printChildren(getChildren(element.props.children), config, indentation + config.indent, depth, refs, printer2), config, indentation);
938
+ const serialize$1 = (element, config, indentation, depth, refs, printer2) => ++depth > config.maxDepth ? printElementAsLeaf(getType$1(element), config) : printElement(getType$1(element), printProps(getPropKeys$1(element), element.props, config, indentation + config.indent, depth, refs, printer2), printChildren(getChildren(element.props.children), config, indentation + config.indent, depth, refs, printer2), config, indentation);
796
939
  const test$1 = (val) => val != null && ReactIs.isElement(val);
797
940
  const plugin$1 = {
798
941
  serialize: serialize$1,
799
942
  test: test$1
800
943
  };
801
944
  const testSymbol = typeof Symbol === "function" && Symbol.for ? Symbol.for("react.test.json") : 245830487;
802
- function getPropKeys(object) {
803
- const { props } = object;
945
+ function getPropKeys(object2) {
946
+ const { props } = object2;
804
947
  return props ? Object.keys(props).filter((key) => props[key] !== void 0).sort() : [];
805
948
  }
806
- const serialize = (object, config, indentation, depth, refs, printer2) => ++depth > config.maxDepth ? printElementAsLeaf(object.type, config) : printElement(object.type, object.props ? printProps(getPropKeys(object), object.props, config, indentation + config.indent, depth, refs, printer2) : "", object.children ? printChildren(object.children, config, indentation + config.indent, depth, refs, printer2) : "", config, indentation);
949
+ const serialize = (object2, config, indentation, depth, refs, printer2) => ++depth > config.maxDepth ? printElementAsLeaf(object2.type, config) : printElement(object2.type, object2.props ? printProps(getPropKeys(object2), object2.props, config, indentation + config.indent, depth, refs, printer2) : "", object2.children ? printChildren(object2.children, config, indentation + config.indent, depth, refs, printer2) : "", config, indentation);
807
950
  const test = (val) => val && val.$$typeof === testSymbol;
808
951
  const plugin = {
809
952
  serialize,
810
953
  test
811
954
  };
812
- const toString$1 = Object.prototype.toString;
955
+ const toString = Object.prototype.toString;
813
956
  const toISOString = Date.prototype.toISOString;
814
957
  const errorToString = Error.prototype.toString;
815
958
  const regExpToString = RegExp.prototype.toString;
@@ -849,7 +992,7 @@ function printSymbol(val) {
849
992
  function printError(val) {
850
993
  return `[${errorToString.call(val)}]`;
851
994
  }
852
- function printBasicValue(val, printFunctionName, escapeRegex, escapeString) {
995
+ function printBasicValue(val, printFunctionName, escapeRegex, escapeString, singleQuote) {
853
996
  if (val === true || val === false) {
854
997
  return `${val}`;
855
998
  }
@@ -867,10 +1010,12 @@ function printBasicValue(val, printFunctionName, escapeRegex, escapeString) {
867
1010
  return printBigInt(val);
868
1011
  }
869
1012
  if (typeOf === "string") {
1013
+ const q = singleQuote ? "'" : '"';
870
1014
  if (escapeString) {
871
- return `"${val.replaceAll(/"|\\/g, "\\$&")}"`;
1015
+ const escapePattern = singleQuote ? /['\\]/g : /["\\]/g;
1016
+ return `${q}${val.replaceAll(escapePattern, "\\$&")}${q}`;
872
1017
  }
873
- return `"${val}"`;
1018
+ return `${q}${val}${q}`;
874
1019
  }
875
1020
  if (typeOf === "function") {
876
1021
  return printFunction(val, printFunctionName);
@@ -878,7 +1023,7 @@ function printBasicValue(val, printFunctionName, escapeRegex, escapeString) {
878
1023
  if (typeOf === "symbol") {
879
1024
  return printSymbol(val);
880
1025
  }
881
- const toStringed = toString$1.call(val);
1026
+ const toStringed = toString.call(val);
882
1027
  if (toStringed === "[object WeakMap]") {
883
1028
  return "WeakMap {}";
884
1029
  }
@@ -919,20 +1064,20 @@ function printComplexValue(val, config, indentation, depth, refs, hasCalledToJSO
919
1064
  if (config.callToJSON && !hitMaxDepth && val.toJSON && typeof val.toJSON === "function" && !hasCalledToJSON) {
920
1065
  return printer(val.toJSON(), config, indentation, depth, refs, true);
921
1066
  }
922
- const toStringed = toString$1.call(val);
1067
+ const toStringed = toString.call(val);
923
1068
  if (toStringed === "[object Arguments]") {
924
1069
  return hitMaxDepth ? "[Arguments]" : `${min ? "" : "Arguments "}[${printListItems(val, config, indentation, depth, refs, printer)}]`;
925
1070
  }
926
1071
  if (isToStringedArrayType(toStringed)) {
927
- return hitMaxDepth ? `[${val.constructor.name}]` : `${min ? "" : !config.printBasicPrototype && val.constructor.name === "Array" ? "" : `${val.constructor.name} `}[${printListItems(val, config, indentation, depth, refs, printer)}]`;
1072
+ return hitMaxDepth ? `[${val.constructor.name}]` : `${!config.printBasicPrototype && val.constructor.name === "Array" ? "" : `${val.constructor.name} `}[${printListItems(val, config, indentation, depth, refs, printer)}]`;
928
1073
  }
929
1074
  if (toStringed === "[object Map]") {
930
- return hitMaxDepth ? "[Map]" : `Map {${printIteratorEntries(val.entries(), config, indentation, depth, refs, printer, " => ")}}`;
1075
+ return hitMaxDepth ? "[Map]" : `Map {${printIteratorEntries(val.entries(), config, indentation, depth, refs, printer, " => ", val.size)}}`;
931
1076
  }
932
1077
  if (toStringed === "[object Set]") {
933
- return hitMaxDepth ? "[Set]" : `Set {${printIteratorValues(val.values(), config, indentation, depth, refs, printer)}}`;
1078
+ return hitMaxDepth ? "[Set]" : `Set {${printIteratorValues(val.values(), config, indentation, depth, refs, printer, val.size)}}`;
934
1079
  }
935
- return hitMaxDepth || isWindow(val) ? `[${getConstructorName(val)}]` : `${min ? "" : !config.printBasicPrototype && getConstructorName(val) === "Object" ? "" : `${getConstructorName(val)} `}{${printObjectProperties(val, config, indentation, depth, refs, printer)}}`;
1080
+ return hitMaxDepth || isWindow(val) ? `[${getConstructorName(val)}]` : `${!config.printBasicPrototype && getConstructorName(val) === "Object" ? "" : `${getConstructorName(val)} `}{${printObjectProperties(val, config, indentation, depth, refs, printer)}}`;
936
1081
  }
937
1082
  function isNewPlugin(plugin2) {
938
1083
  return plugin2.serialize != null;
@@ -976,7 +1121,7 @@ function printer(val, config, indentation, depth, refs, hasCalledToJSON) {
976
1121
  if (plugin2 !== null) {
977
1122
  result = printPlugin(plugin2, val, config, indentation, depth, refs);
978
1123
  } else {
979
- const basicResult = printBasicValue(val, config.printFunctionName, config.escapeRegex, config.escapeString);
1124
+ const basicResult = printBasicValue(val, config.printFunctionName, config.escapeRegex, config.escapeString, config.singleQuote);
980
1125
  if (basicResult !== null) {
981
1126
  result = basicResult;
982
1127
  } else {
@@ -1013,7 +1158,11 @@ const DEFAULT_OPTIONS = {
1013
1158
  printBasicPrototype: true,
1014
1159
  printFunctionName: true,
1015
1160
  printShadowRoot: true,
1016
- theme: DEFAULT_THEME
1161
+ theme: DEFAULT_THEME,
1162
+ singleQuote: false,
1163
+ quoteKeys: true,
1164
+ spacingInner: "\n",
1165
+ spacingOuter: "\n"
1017
1166
  };
1018
1167
  function validateOptions(options) {
1019
1168
  for (const key of Object.keys(options)) {
@@ -1055,7 +1204,7 @@ function getEscapeRegex(options) {
1055
1204
  function getEscapeString(options) {
1056
1205
  return (options == null ? void 0 : options.escapeString) ?? DEFAULT_OPTIONS.escapeString;
1057
1206
  }
1058
- function getConfig$1(options) {
1207
+ function getConfig(options) {
1059
1208
  return {
1060
1209
  callToJSON: (options == null ? void 0 : options.callToJSON) ?? DEFAULT_OPTIONS.callToJSON,
1061
1210
  colors: (options == null ? void 0 : options.highlight) ? getColorsHighlight() : getColorsEmpty(),
@@ -1067,11 +1216,13 @@ function getConfig$1(options) {
1067
1216
  maxWidth: (options == null ? void 0 : options.maxWidth) ?? DEFAULT_OPTIONS.maxWidth,
1068
1217
  min: (options == null ? void 0 : options.min) ?? DEFAULT_OPTIONS.min,
1069
1218
  plugins: (options == null ? void 0 : options.plugins) ?? DEFAULT_OPTIONS.plugins,
1070
- printBasicPrototype: (options == null ? void 0 : options.printBasicPrototype) ?? true,
1219
+ printBasicPrototype: (options == null ? void 0 : options.printBasicPrototype) ?? !(options == null ? void 0 : options.min),
1071
1220
  printFunctionName: getPrintFunctionName(options),
1072
1221
  printShadowRoot: (options == null ? void 0 : options.printShadowRoot) ?? true,
1073
- spacingInner: (options == null ? void 0 : options.min) ? " " : "\n",
1074
- spacingOuter: (options == null ? void 0 : options.min) ? "" : "\n",
1222
+ spacingInner: (options == null ? void 0 : options.spacingInner) ?? ((options == null ? void 0 : options.min) ? " " : "\n"),
1223
+ spacingOuter: (options == null ? void 0 : options.spacingOuter) ?? ((options == null ? void 0 : options.min) ? "" : "\n"),
1224
+ singleQuote: (options == null ? void 0 : options.singleQuote) ?? DEFAULT_OPTIONS.singleQuote,
1225
+ quoteKeys: (options == null ? void 0 : options.quoteKeys) ?? DEFAULT_OPTIONS.quoteKeys,
1075
1226
  maxOutputLength: (options == null ? void 0 : options.maxOutputLength) ?? DEFAULT_OPTIONS.maxOutputLength,
1076
1227
  _outputLengthPerDepth: []
1077
1228
  };
@@ -1082,18 +1233,17 @@ function createIndent(indent) {
1082
1233
  function format$1(val, options) {
1083
1234
  if (options) {
1084
1235
  validateOptions(options);
1085
- if (options.plugins) {
1086
- const plugin2 = findPlugin(options.plugins, val);
1087
- if (plugin2 !== null) {
1088
- return printPlugin(plugin2, val, getConfig$1(options), "", 0, []);
1089
- }
1090
- }
1091
1236
  }
1092
- const basicResult = printBasicValue(val, getPrintFunctionName(options), getEscapeRegex(options), getEscapeString(options));
1237
+ const config = getConfig(options);
1238
+ const plugin2 = findPlugin(config.plugins, val);
1239
+ if (plugin2 !== null) {
1240
+ return printPlugin(plugin2, val, config, "", 0, []);
1241
+ }
1242
+ const basicResult = printBasicValue(val, config.printFunctionName, config.escapeRegex, config.escapeString, config.singleQuote);
1093
1243
  if (basicResult !== null) {
1094
1244
  return basicResult;
1095
1245
  }
1096
- return printComplexValue(val, getConfig$1(options), "", 0, []);
1246
+ return printComplexValue(val, config, "", 0, []);
1097
1247
  }
1098
1248
  const plugins = {
1099
1249
  AsymmetricMatcher: plugin$5,
@@ -1103,523 +1253,6 @@ const plugins = {
1103
1253
  ReactElement: plugin$1,
1104
1254
  ReactTestComponent: plugin
1105
1255
  };
1106
- const ansiColors = {
1107
- bold: ["1", "22"],
1108
- dim: ["2", "22"],
1109
- italic: ["3", "23"],
1110
- underline: ["4", "24"],
1111
- // 5 & 6 are blinking
1112
- inverse: ["7", "27"],
1113
- hidden: ["8", "28"],
1114
- strike: ["9", "29"],
1115
- // 10-20 are fonts
1116
- // 21-29 are resets for 1-9
1117
- black: ["30", "39"],
1118
- red: ["31", "39"],
1119
- green: ["32", "39"],
1120
- yellow: ["33", "39"],
1121
- blue: ["34", "39"],
1122
- magenta: ["35", "39"],
1123
- cyan: ["36", "39"],
1124
- white: ["37", "39"],
1125
- brightblack: ["30;1", "39"],
1126
- brightred: ["31;1", "39"],
1127
- brightgreen: ["32;1", "39"],
1128
- brightyellow: ["33;1", "39"],
1129
- brightblue: ["34;1", "39"],
1130
- brightmagenta: ["35;1", "39"],
1131
- brightcyan: ["36;1", "39"],
1132
- brightwhite: ["37;1", "39"],
1133
- grey: ["90", "39"]
1134
- };
1135
- const styles = {
1136
- special: "cyan",
1137
- number: "yellow",
1138
- bigint: "yellow",
1139
- boolean: "yellow",
1140
- undefined: "grey",
1141
- null: "bold",
1142
- string: "green",
1143
- symbol: "green",
1144
- date: "magenta",
1145
- regexp: "red"
1146
- };
1147
- const truncator = "…";
1148
- function colorise(value, styleType) {
1149
- const color = ansiColors[styles[styleType]] || ansiColors[styleType] || "";
1150
- if (!color) {
1151
- return String(value);
1152
- }
1153
- return `\x1B[${color[0]}m${String(value)}\x1B[${color[1]}m`;
1154
- }
1155
- function normaliseOptions({
1156
- showHidden = false,
1157
- depth = 2,
1158
- colors = false,
1159
- customInspect = true,
1160
- showProxy = false,
1161
- maxArrayLength = Infinity,
1162
- breakLength = Infinity,
1163
- seen = [],
1164
- // eslint-disable-next-line no-shadow
1165
- truncate: truncate2 = Infinity,
1166
- stylize = String
1167
- } = {}, inspect2) {
1168
- const options = {
1169
- showHidden: Boolean(showHidden),
1170
- depth: Number(depth),
1171
- colors: Boolean(colors),
1172
- customInspect: Boolean(customInspect),
1173
- showProxy: Boolean(showProxy),
1174
- maxArrayLength: Number(maxArrayLength),
1175
- breakLength: Number(breakLength),
1176
- truncate: Number(truncate2),
1177
- seen,
1178
- inspect: inspect2,
1179
- stylize
1180
- };
1181
- if (options.colors) {
1182
- options.stylize = colorise;
1183
- }
1184
- return options;
1185
- }
1186
- function isHighSurrogate(char) {
1187
- return char >= "\uD800" && char <= "\uDBFF";
1188
- }
1189
- function truncate(string, length, tail = truncator) {
1190
- string = String(string);
1191
- const tailLength = tail.length;
1192
- const stringLength = string.length;
1193
- if (tailLength > length && stringLength > tailLength) {
1194
- return tail;
1195
- }
1196
- if (stringLength > length && stringLength > tailLength) {
1197
- let end = length - tailLength;
1198
- if (end > 0 && isHighSurrogate(string[end - 1])) {
1199
- end = end - 1;
1200
- }
1201
- return `${string.slice(0, end)}${tail}`;
1202
- }
1203
- return string;
1204
- }
1205
- function inspectList(list, options, inspectItem, separator = ", ") {
1206
- inspectItem = inspectItem || options.inspect;
1207
- const size = list.length;
1208
- if (size === 0)
1209
- return "";
1210
- const originalLength = options.truncate;
1211
- let output = "";
1212
- let peek = "";
1213
- let truncated = "";
1214
- for (let i2 = 0; i2 < size; i2 += 1) {
1215
- const last = i2 + 1 === list.length;
1216
- const secondToLast = i2 + 2 === list.length;
1217
- truncated = `${truncator}(${list.length - i2})`;
1218
- const value = list[i2];
1219
- options.truncate = originalLength - output.length - (last ? 0 : separator.length);
1220
- const string = peek || inspectItem(value, options) + (last ? "" : separator);
1221
- const nextLength = output.length + string.length;
1222
- const truncatedLength = nextLength + truncated.length;
1223
- if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) {
1224
- break;
1225
- }
1226
- if (!last && !secondToLast && truncatedLength > originalLength) {
1227
- break;
1228
- }
1229
- peek = last ? "" : inspectItem(list[i2 + 1], options) + (secondToLast ? "" : separator);
1230
- if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) {
1231
- break;
1232
- }
1233
- output += string;
1234
- if (!last && !secondToLast && nextLength + peek.length >= originalLength) {
1235
- truncated = `${truncator}(${list.length - i2 - 1})`;
1236
- break;
1237
- }
1238
- truncated = "";
1239
- }
1240
- return `${output}${truncated}`;
1241
- }
1242
- function quoteComplexKey(key) {
1243
- if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) {
1244
- return key;
1245
- }
1246
- return JSON.stringify(key).replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
1247
- }
1248
- function inspectProperty([key, value], options) {
1249
- options.truncate -= 2;
1250
- if (typeof key === "string") {
1251
- key = quoteComplexKey(key);
1252
- } else if (typeof key !== "number") {
1253
- key = `[${options.inspect(key, options)}]`;
1254
- }
1255
- options.truncate -= key.length;
1256
- value = options.inspect(value, options);
1257
- return `${key}: ${value}`;
1258
- }
1259
- function inspectArray(array, options) {
1260
- const nonIndexProperties = Object.keys(array).slice(array.length);
1261
- if (!array.length && !nonIndexProperties.length)
1262
- return "[]";
1263
- options.truncate -= 4;
1264
- const listContents = inspectList(array, options);
1265
- options.truncate -= listContents.length;
1266
- let propertyContents = "";
1267
- if (nonIndexProperties.length) {
1268
- propertyContents = inspectList(nonIndexProperties.map((key) => [key, array[key]]), options, inspectProperty);
1269
- }
1270
- return `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ""} ]`;
1271
- }
1272
- const getArrayName = (array) => {
1273
- if (typeof Buffer === "function" && array instanceof Buffer) {
1274
- return "Buffer";
1275
- }
1276
- if (array[Symbol.toStringTag]) {
1277
- return array[Symbol.toStringTag];
1278
- }
1279
- return array.constructor.name;
1280
- };
1281
- function inspectTypedArray(array, options) {
1282
- const name = getArrayName(array);
1283
- options.truncate -= name.length + 4;
1284
- const nonIndexProperties = Object.keys(array).slice(array.length);
1285
- if (!array.length && !nonIndexProperties.length)
1286
- return `${name}[]`;
1287
- let output = "";
1288
- for (let i2 = 0; i2 < array.length; i2++) {
1289
- const string = `${options.stylize(truncate(array[i2], options.truncate), "number")}${i2 === array.length - 1 ? "" : ", "}`;
1290
- options.truncate -= string.length;
1291
- if (array[i2] !== array.length && options.truncate <= 3) {
1292
- output += `${truncator}(${array.length - array[i2] + 1})`;
1293
- break;
1294
- }
1295
- output += string;
1296
- }
1297
- let propertyContents = "";
1298
- if (nonIndexProperties.length) {
1299
- propertyContents = inspectList(nonIndexProperties.map((key) => [key, array[key]]), options, inspectProperty);
1300
- }
1301
- return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ""} ]`;
1302
- }
1303
- function inspectDate(dateObject, options) {
1304
- const stringRepresentation = dateObject.toJSON();
1305
- if (stringRepresentation === null) {
1306
- return "Invalid Date";
1307
- }
1308
- const split = stringRepresentation.split("T");
1309
- const date = split[0];
1310
- return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, "date");
1311
- }
1312
- function inspectFunction(func, options) {
1313
- const functionType = func[Symbol.toStringTag] || "Function";
1314
- const name = func.name;
1315
- if (!name) {
1316
- return options.stylize(`[${functionType}]`, "special");
1317
- }
1318
- return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, "special");
1319
- }
1320
- function inspectMapEntry([key, value], options) {
1321
- options.truncate -= 4;
1322
- key = options.inspect(key, options);
1323
- options.truncate -= key.length;
1324
- value = options.inspect(value, options);
1325
- return `${key} => ${value}`;
1326
- }
1327
- function mapToEntries(map) {
1328
- const entries = [];
1329
- map.forEach((value, key) => {
1330
- entries.push([key, value]);
1331
- });
1332
- return entries;
1333
- }
1334
- function inspectMap(map, options) {
1335
- if (map.size === 0)
1336
- return "Map{}";
1337
- options.truncate -= 7;
1338
- return `Map{ ${inspectList(mapToEntries(map), options, inspectMapEntry)} }`;
1339
- }
1340
- const isNaN = Number.isNaN || ((i2) => i2 !== i2);
1341
- function inspectNumber(number, options) {
1342
- if (isNaN(number)) {
1343
- return options.stylize("NaN", "number");
1344
- }
1345
- if (number === Infinity) {
1346
- return options.stylize("Infinity", "number");
1347
- }
1348
- if (number === -Infinity) {
1349
- return options.stylize("-Infinity", "number");
1350
- }
1351
- if (number === 0) {
1352
- return options.stylize(1 / number === Infinity ? "+0" : "-0", "number");
1353
- }
1354
- return options.stylize(truncate(String(number), options.truncate), "number");
1355
- }
1356
- function inspectBigInt(number, options) {
1357
- let nums = truncate(number.toString(), options.truncate - 1);
1358
- if (nums !== truncator)
1359
- nums += "n";
1360
- return options.stylize(nums, "bigint");
1361
- }
1362
- function inspectRegExp(value, options) {
1363
- const flags = value.toString().split("/")[2];
1364
- const sourceLength = options.truncate - (2 + flags.length);
1365
- const source = value.source;
1366
- return options.stylize(`/${truncate(source, sourceLength)}/${flags}`, "regexp");
1367
- }
1368
- function arrayFromSet(set) {
1369
- const values = [];
1370
- set.forEach((value) => {
1371
- values.push(value);
1372
- });
1373
- return values;
1374
- }
1375
- function inspectSet(set, options) {
1376
- if (set.size === 0)
1377
- return "Set{}";
1378
- options.truncate -= 7;
1379
- return `Set{ ${inspectList(arrayFromSet(set), options)} }`;
1380
- }
1381
- const stringEscapeChars = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]", "g");
1382
- const escapeCharacters = {
1383
- "\b": "\\b",
1384
- " ": "\\t",
1385
- "\n": "\\n",
1386
- "\f": "\\f",
1387
- "\r": "\\r",
1388
- "'": "\\'",
1389
- "\\": "\\\\"
1390
- };
1391
- const hex = 16;
1392
- function escape(char) {
1393
- return escapeCharacters[char] || `\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-4)}`;
1394
- }
1395
- function inspectString(string, options) {
1396
- if (stringEscapeChars.test(string)) {
1397
- string = string.replace(stringEscapeChars, escape);
1398
- }
1399
- return options.stylize(`'${truncate(string, options.truncate - 2)}'`, "string");
1400
- }
1401
- function inspectSymbol(value) {
1402
- if ("description" in Symbol.prototype) {
1403
- return value.description ? `Symbol(${value.description})` : "Symbol()";
1404
- }
1405
- return value.toString();
1406
- }
1407
- const getPromiseValue = () => "Promise{…}";
1408
- function inspectObject$1(object, options) {
1409
- const properties = Object.getOwnPropertyNames(object);
1410
- const symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : [];
1411
- if (properties.length === 0 && symbols.length === 0) {
1412
- return "{}";
1413
- }
1414
- options.truncate -= 4;
1415
- options.seen = options.seen || [];
1416
- if (options.seen.includes(object)) {
1417
- return "[Circular]";
1418
- }
1419
- options.seen.push(object);
1420
- const propertyContents = inspectList(properties.map((key) => [key, object[key]]), options, inspectProperty);
1421
- const symbolContents = inspectList(symbols.map((key) => [key, object[key]]), options, inspectProperty);
1422
- options.seen.pop();
1423
- let sep = "";
1424
- if (propertyContents && symbolContents) {
1425
- sep = ", ";
1426
- }
1427
- return `{ ${propertyContents}${sep}${symbolContents} }`;
1428
- }
1429
- const toStringTag = typeof Symbol !== "undefined" && Symbol.toStringTag ? Symbol.toStringTag : false;
1430
- function inspectClass(value, options) {
1431
- let name = "";
1432
- if (toStringTag && toStringTag in value) {
1433
- name = value[toStringTag];
1434
- }
1435
- name = name || value.constructor.name;
1436
- if (!name || name === "_class") {
1437
- name = "<Anonymous Class>";
1438
- }
1439
- options.truncate -= name.length;
1440
- return `${name}${inspectObject$1(value, options)}`;
1441
- }
1442
- function inspectArguments(args, options) {
1443
- if (args.length === 0)
1444
- return "Arguments[]";
1445
- options.truncate -= 13;
1446
- return `Arguments[ ${inspectList(args, options)} ]`;
1447
- }
1448
- const errorKeys = [
1449
- "stack",
1450
- "line",
1451
- "column",
1452
- "name",
1453
- "message",
1454
- "fileName",
1455
- "lineNumber",
1456
- "columnNumber",
1457
- "number",
1458
- "description",
1459
- "cause"
1460
- ];
1461
- function inspectObject(error, options) {
1462
- const properties = Object.getOwnPropertyNames(error).filter((key) => errorKeys.indexOf(key) === -1);
1463
- const name = error.name;
1464
- options.truncate -= name.length;
1465
- let message = "";
1466
- if (typeof error.message === "string") {
1467
- message = truncate(error.message, options.truncate);
1468
- } else {
1469
- properties.unshift("message");
1470
- }
1471
- message = message ? `: ${message}` : "";
1472
- options.truncate -= message.length + 5;
1473
- options.seen = options.seen || [];
1474
- if (options.seen.includes(error)) {
1475
- return "[Circular]";
1476
- }
1477
- options.seen.push(error);
1478
- const propertyContents = inspectList(properties.map((key) => [key, error[key]]), options, inspectProperty);
1479
- return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ""}`;
1480
- }
1481
- function inspectAttribute([key, value], options) {
1482
- options.truncate -= 3;
1483
- if (!value) {
1484
- return `${options.stylize(String(key), "yellow")}`;
1485
- }
1486
- return `${options.stylize(String(key), "yellow")}=${options.stylize(`"${value}"`, "string")}`;
1487
- }
1488
- function inspectNodeCollection(collection, options) {
1489
- return inspectList(collection, options, inspectNode, "\n");
1490
- }
1491
- function inspectNode(node, options) {
1492
- switch (node.nodeType) {
1493
- case 1:
1494
- return inspectHTML(node, options);
1495
- case 3:
1496
- return options.inspect(node.data, options);
1497
- default:
1498
- return options.inspect(node, options);
1499
- }
1500
- }
1501
- function inspectHTML(element, options) {
1502
- const properties = element.getAttributeNames();
1503
- const name = element.tagName.toLowerCase();
1504
- const head = options.stylize(`<${name}`, "special");
1505
- const headClose = options.stylize(`>`, "special");
1506
- const tail = options.stylize(`</${name}>`, "special");
1507
- options.truncate -= name.length * 2 + 5;
1508
- let propertyContents = "";
1509
- if (properties.length > 0) {
1510
- propertyContents += " ";
1511
- propertyContents += inspectList(properties.map((key) => [key, element.getAttribute(key)]), options, inspectAttribute, " ");
1512
- }
1513
- options.truncate -= propertyContents.length;
1514
- const truncate2 = options.truncate;
1515
- let children = inspectNodeCollection(element.children, options);
1516
- if (children && children.length > truncate2) {
1517
- children = `${truncator}(${element.children.length})`;
1518
- }
1519
- return `${head}${propertyContents}${headClose}${children}${tail}`;
1520
- }
1521
- const symbolsSupported = typeof Symbol === "function" && typeof Symbol.for === "function";
1522
- const chaiInspect = symbolsSupported ? Symbol.for("chai/inspect") : "@@chai/inspect";
1523
- const nodeInspect = Symbol.for("nodejs.util.inspect.custom");
1524
- const constructorMap = /* @__PURE__ */ new WeakMap();
1525
- const stringTagMap = {};
1526
- const baseTypesMap = {
1527
- undefined: (value, options) => options.stylize("undefined", "undefined"),
1528
- null: (value, options) => options.stylize("null", "null"),
1529
- boolean: (value, options) => options.stylize(String(value), "boolean"),
1530
- Boolean: (value, options) => options.stylize(String(value), "boolean"),
1531
- number: inspectNumber,
1532
- Number: inspectNumber,
1533
- bigint: inspectBigInt,
1534
- BigInt: inspectBigInt,
1535
- string: inspectString,
1536
- String: inspectString,
1537
- function: inspectFunction,
1538
- Function: inspectFunction,
1539
- symbol: inspectSymbol,
1540
- // A Symbol polyfill will return `Symbol` not `symbol` from typedetect
1541
- Symbol: inspectSymbol,
1542
- Array: inspectArray,
1543
- Date: inspectDate,
1544
- Map: inspectMap,
1545
- Set: inspectSet,
1546
- RegExp: inspectRegExp,
1547
- Promise: getPromiseValue,
1548
- // WeakSet, WeakMap are totally opaque to us
1549
- WeakSet: (value, options) => options.stylize("WeakSet{…}", "special"),
1550
- WeakMap: (value, options) => options.stylize("WeakMap{…}", "special"),
1551
- Arguments: inspectArguments,
1552
- Int8Array: inspectTypedArray,
1553
- Uint8Array: inspectTypedArray,
1554
- Uint8ClampedArray: inspectTypedArray,
1555
- Int16Array: inspectTypedArray,
1556
- Uint16Array: inspectTypedArray,
1557
- Int32Array: inspectTypedArray,
1558
- Uint32Array: inspectTypedArray,
1559
- Float32Array: inspectTypedArray,
1560
- Float64Array: inspectTypedArray,
1561
- Generator: () => "",
1562
- DataView: () => "",
1563
- ArrayBuffer: () => "",
1564
- Error: inspectObject,
1565
- HTMLCollection: inspectNodeCollection,
1566
- NodeList: inspectNodeCollection
1567
- };
1568
- const inspectCustom = (value, options, type, inspectFn) => {
1569
- if (chaiInspect in value && typeof value[chaiInspect] === "function") {
1570
- return value[chaiInspect](options);
1571
- }
1572
- if (nodeInspect in value && typeof value[nodeInspect] === "function") {
1573
- return value[nodeInspect](options.depth, options, inspectFn);
1574
- }
1575
- if ("inspect" in value && typeof value.inspect === "function") {
1576
- return value.inspect(options.depth, options);
1577
- }
1578
- if ("constructor" in value && constructorMap.has(value.constructor)) {
1579
- return constructorMap.get(value.constructor)(value, options);
1580
- }
1581
- if (stringTagMap[type]) {
1582
- return stringTagMap[type](value, options);
1583
- }
1584
- return "";
1585
- };
1586
- const toString = Object.prototype.toString;
1587
- function inspect$1(value, opts = {}) {
1588
- const options = normaliseOptions(opts, inspect$1);
1589
- const { customInspect } = options;
1590
- let type = value === null ? "null" : typeof value;
1591
- if (type === "object") {
1592
- type = toString.call(value).slice(8, -1);
1593
- }
1594
- if (type in baseTypesMap) {
1595
- return baseTypesMap[type](value, options);
1596
- }
1597
- if (customInspect && value) {
1598
- const output = inspectCustom(value, options, type, inspect$1);
1599
- if (output) {
1600
- if (typeof output === "string")
1601
- return output;
1602
- return inspect$1(output, options);
1603
- }
1604
- }
1605
- const proto = value ? Object.getPrototypeOf(value) : false;
1606
- if (proto === Object.prototype || proto === null) {
1607
- return inspectObject$1(value, options);
1608
- }
1609
- if (value && typeof HTMLElement === "function" && value instanceof HTMLElement) {
1610
- return inspectHTML(value, options);
1611
- }
1612
- if ("constructor" in value) {
1613
- if (value.constructor !== Object) {
1614
- return inspectClass(value, options);
1615
- }
1616
- return inspectObject$1(value, options);
1617
- }
1618
- if (value === Object(value)) {
1619
- return inspectObject$1(value, options);
1620
- }
1621
- return options.stylize(String(value), type);
1622
- }
1623
1256
  const { AsymmetricMatcher, DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent } = plugins;
1624
1257
  const PLUGINS = [
1625
1258
  ReactTestComponent,
@@ -1629,7 +1262,7 @@ const PLUGINS = [
1629
1262
  Immutable,
1630
1263
  AsymmetricMatcher
1631
1264
  ];
1632
- function stringify(object, maxDepth = 10, { maxLength, filterNode, ...options } = {}) {
1265
+ function stringify(object2, maxDepth = 10, { maxLength, filterNode, ...options } = {}) {
1633
1266
  const MAX_LENGTH = maxLength ?? 1e4;
1634
1267
  let result;
1635
1268
  const filterFn = typeof filterNode === "string" ? createNodeFilterFromSelector(filterNode) : filterNode;
@@ -1642,14 +1275,14 @@ function stringify(object, maxDepth = 10, { maxLength, filterNode, ...options }
1642
1275
  AsymmetricMatcher
1643
1276
  ] : PLUGINS;
1644
1277
  try {
1645
- result = format$1(object, {
1278
+ result = format$1(object2, {
1646
1279
  maxDepth,
1647
1280
  escapeString: false,
1648
1281
  plugins: plugins2,
1649
1282
  ...options
1650
1283
  });
1651
1284
  } catch {
1652
- result = format$1(object, {
1285
+ result = format$1(object2, {
1653
1286
  callToJSON: false,
1654
1287
  maxDepth,
1655
1288
  escapeString: false,
@@ -1657,7 +1290,7 @@ function stringify(object, maxDepth = 10, { maxLength, filterNode, ...options }
1657
1290
  ...options
1658
1291
  });
1659
1292
  }
1660
- return result.length >= MAX_LENGTH && maxDepth > 1 ? stringify(object, Math.floor(Math.min(maxDepth, Number.MAX_SAFE_INTEGER) / 2), {
1293
+ return result.length >= MAX_LENGTH && maxDepth > 1 ? stringify(object2, Math.floor(Math.min(maxDepth, Number.MAX_SAFE_INTEGER) / 2), {
1661
1294
  maxLength,
1662
1295
  filterNode,
1663
1296
  ...options
@@ -1681,23 +1314,12 @@ function createNodeFilterFromSelector(selector) {
1681
1314
  };
1682
1315
  }
1683
1316
  const formatRegExp = /%[sdjifoOc%]/g;
1684
- function baseFormat(args, options = {}) {
1685
- const formatArg = (item, inspecOptions) => {
1686
- if (options.prettifyObject) {
1687
- return stringify(item, void 0, {
1688
- printBasicPrototype: false,
1689
- escapeString: false
1690
- });
1691
- }
1692
- return inspect(item, inspecOptions);
1693
- };
1317
+ function format(args, options = {}) {
1318
+ const formatArg = (item) => inspect(item, options);
1694
1319
  if (typeof args[0] !== "string") {
1695
1320
  const objects = [];
1696
1321
  for (let i3 = 0; i3 < args.length; i3++) {
1697
- objects.push(formatArg(args[i3], {
1698
- depth: 0,
1699
- colors: false
1700
- }));
1322
+ objects.push(formatArg(args[i3]));
1701
1323
  }
1702
1324
  return objects.join(" ");
1703
1325
  }
@@ -1724,10 +1346,7 @@ function baseFormat(args, options = {}) {
1724
1346
  if (typeof value.toString === "function" && value.toString !== Object.prototype.toString) {
1725
1347
  return value.toString();
1726
1348
  }
1727
- return formatArg(value, {
1728
- depth: 0,
1729
- colors: false
1730
- });
1349
+ return formatArg(value);
1731
1350
  }
1732
1351
  return String(value);
1733
1352
  }
@@ -1751,10 +1370,6 @@ function baseFormat(args, options = {}) {
1751
1370
  case "%f":
1752
1371
  return Number.parseFloat(String(args[i2++])).toString();
1753
1372
  case "%o":
1754
- return formatArg(args[i2++], {
1755
- showHidden: true,
1756
- showProxy: true
1757
- });
1758
1373
  case "%O":
1759
1374
  return formatArg(args[i2++]);
1760
1375
  case "%c": {
@@ -1784,36 +1399,85 @@ function baseFormat(args, options = {}) {
1784
1399
  }
1785
1400
  return str;
1786
1401
  }
1787
- function format(...args) {
1788
- return baseFormat(args);
1402
+ function inspect(obj, options) {
1403
+ const { truncate, multiline, ...stringifyOptions } = options ?? {};
1404
+ const prettyFormatOptions = {
1405
+ singleQuote: true,
1406
+ quoteKeys: false,
1407
+ min: true,
1408
+ spacingInner: " ",
1409
+ spacingOuter: " ",
1410
+ printBasicPrototype: false,
1411
+ compareKeys: null,
1412
+ ...multiline ? {
1413
+ min: false,
1414
+ spacingInner: void 0,
1415
+ spacingOuter: void 0
1416
+ } : {}
1417
+ };
1418
+ const threshold = truncate ?? 0;
1419
+ const formatted = stringify(obj, void 0, {
1420
+ ...prettyFormatOptions,
1421
+ ...stringifyOptions,
1422
+ maxLength: threshold || void 0
1423
+ });
1424
+ if (threshold === 0 || formatted.length <= threshold) {
1425
+ return formatted;
1426
+ }
1427
+ const type = Object.prototype.toString.call(obj);
1428
+ if (typeof obj === "string") {
1429
+ let end = threshold - 1;
1430
+ if (end > 0 && isHighSurrogate(formatted[end - 1])) {
1431
+ end = end - 1;
1432
+ }
1433
+ return `'${formatted.slice(1, end)}…'`;
1434
+ }
1435
+ if (type === "[object Array]" || type === "[object Object]" || type === "[object Set]" || type === "[object Map]") {
1436
+ return stringifyByMaxWidth(obj, threshold, {
1437
+ ...prettyFormatOptions,
1438
+ ...stringifyOptions,
1439
+ maxDepth: 1
1440
+ });
1441
+ }
1442
+ return stringify(obj, void 0, {
1443
+ ...prettyFormatOptions,
1444
+ ...stringifyOptions,
1445
+ maxDepth: 0
1446
+ });
1789
1447
  }
1790
- function inspect(obj, options = {}) {
1791
- if (options.truncate === 0) {
1792
- options.truncate = Number.POSITIVE_INFINITY;
1448
+ function truncateString(string, maxLength) {
1449
+ if (string.length <= maxLength) {
1450
+ return string;
1793
1451
  }
1794
- return inspect$1(obj, options);
1452
+ let end = maxLength - 1;
1453
+ if (isHighSurrogate(string[end - 1])) {
1454
+ end = end - 1;
1455
+ }
1456
+ return `${string.slice(0, end)}…`;
1795
1457
  }
1796
- function objDisplay(obj, options = {}) {
1797
- if (typeof options.truncate === "undefined") {
1798
- options.truncate = 40;
1458
+ function stringifyByMaxWidth(object2, threshold, options) {
1459
+ function evaluate(x) {
1460
+ return stringify(object2, void 0, {
1461
+ ...options,
1462
+ maxWidth: x
1463
+ });
1799
1464
  }
1800
- const str = inspect(obj, options);
1801
- const type = Object.prototype.toString.call(obj);
1802
- if (options.truncate && str.length >= options.truncate) {
1803
- if (type === "[object Function]") {
1804
- const fn = obj;
1805
- return !fn.name ? "[Function]" : `[Function: ${fn.name}]`;
1806
- } else if (type === "[object Array]") {
1807
- return `[ Array(${obj.length}) ]`;
1808
- } else if (type === "[object Object]") {
1809
- const keys = Object.keys(obj);
1810
- const kstr = keys.length > 2 ? `${keys.splice(0, 2).join(", ")}, ...` : keys.join(", ");
1811
- return `{ Object (${kstr}) }`;
1465
+ const opt = binarySearch$1(0, threshold, (x) => evaluate(x).length <= threshold);
1466
+ return evaluate(opt);
1467
+ }
1468
+ function binarySearch$1(x0, x1, f) {
1469
+ while (x0 + 1 < x1) {
1470
+ const x = Math.floor((x0 + x1) / 2);
1471
+ if (f(x)) {
1472
+ x0 = x;
1812
1473
  } else {
1813
- return str;
1474
+ x1 = x;
1814
1475
  }
1815
1476
  }
1816
- return str;
1477
+ return x0;
1478
+ }
1479
+ function isHighSurrogate(char) {
1480
+ return char >= "\uD800" && char <= "\uDBFF";
1817
1481
  }
1818
1482
  function assertTypes(value, name, types) {
1819
1483
  const receivedType = typeof value;
@@ -1931,18 +1595,18 @@ function normalizeWindowsPath$1(input = "") {
1931
1595
  return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE$1, (r) => r.toUpperCase());
1932
1596
  }
1933
1597
  const _IS_ABSOLUTE_RE$1 = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
1934
- function cwd$1() {
1598
+ function cwd() {
1935
1599
  if (typeof process !== "undefined" && typeof process.cwd === "function") {
1936
1600
  return process.cwd().replace(/\\/g, "/");
1937
1601
  }
1938
1602
  return "/";
1939
1603
  }
1940
- const resolve$1 = function(...arguments_) {
1604
+ const resolve = function(...arguments_) {
1941
1605
  arguments_ = arguments_.map((argument) => normalizeWindowsPath$1(argument));
1942
1606
  let resolvedPath = "";
1943
1607
  let resolvedAbsolute = false;
1944
1608
  for (let index2 = arguments_.length - 1; index2 >= -1 && !resolvedAbsolute; index2--) {
1945
- const path = index2 >= 0 ? arguments_[index2] : cwd$1();
1609
+ const path = index2 >= 0 ? arguments_[index2] : cwd();
1946
1610
  if (!path || path.length === 0) {
1947
1611
  continue;
1948
1612
  }
@@ -2018,19 +1682,19 @@ function normalizeString$1(path, allowAboveRoot) {
2018
1682
  const isAbsolute$1 = function(p) {
2019
1683
  return _IS_ABSOLUTE_RE$1.test(p);
2020
1684
  };
2021
- var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2022
- var intToChar = new Uint8Array(64);
2023
- var charToInt = new Uint8Array(128);
2024
- for (let i2 = 0; i2 < chars.length; i2++) {
2025
- const c = chars.charCodeAt(i2);
2026
- intToChar[i2] = c;
2027
- charToInt[c] = i2;
2028
- }
2029
- const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
2030
- const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
2031
- const NOW_LENGTH = Date.now().toString().length;
2032
- const REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`);
2033
- function extractLocation(urlLike) {
1685
+ var chars$2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1686
+ var intToChar$2 = new Uint8Array(64);
1687
+ var charToInt$2 = new Uint8Array(128);
1688
+ for (let i2 = 0; i2 < chars$2.length; i2++) {
1689
+ const c = chars$2.charCodeAt(i2);
1690
+ intToChar$2[i2] = c;
1691
+ charToInt$2[c] = i2;
1692
+ }
1693
+ const CHROME_IE_STACK_REGEXP$1 = /^\s*at .*(?:\S:\d+|\(native\))/m;
1694
+ const SAFARI_NATIVE_CODE_REGEXP$1 = /^(?:eval@)?(?:\[native code\])?$/;
1695
+ const NOW_LENGTH$1 = Date.now().toString().length;
1696
+ const REGEXP_VITEST$1 = new RegExp(`vitest=\\d{${NOW_LENGTH$1}}`);
1697
+ function extractLocation$1(urlLike) {
2034
1698
  if (!urlLike.includes(":")) {
2035
1699
  return [urlLike];
2036
1700
  }
@@ -2039,32 +1703,32 @@ function extractLocation(urlLike) {
2039
1703
  if (!parts) {
2040
1704
  return [urlLike];
2041
1705
  }
2042
- let url = parts[1];
2043
- if (url.startsWith("async ")) {
2044
- url = url.slice(6);
1706
+ let url2 = parts[1];
1707
+ if (url2.startsWith("async ")) {
1708
+ url2 = url2.slice(6);
2045
1709
  }
2046
- if (url.startsWith("http:") || url.startsWith("https:")) {
2047
- const urlObj = new URL(url);
1710
+ if (url2.startsWith("http:") || url2.startsWith("https:")) {
1711
+ const urlObj = new URL(url2);
2048
1712
  urlObj.searchParams.delete("import");
2049
1713
  urlObj.searchParams.delete("browserv");
2050
- url = urlObj.pathname + urlObj.hash + urlObj.search;
1714
+ url2 = urlObj.pathname + urlObj.hash + urlObj.search;
2051
1715
  }
2052
- if (url.startsWith("/@fs/")) {
2053
- const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url);
2054
- url = url.slice(isWindows ? 5 : 4);
1716
+ if (url2.startsWith("/@fs/")) {
1717
+ const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url2);
1718
+ url2 = url2.slice(isWindows ? 5 : 4);
2055
1719
  }
2056
- if (url.includes("vitest=")) {
2057
- url = url.replace(REGEXP_VITEST, "").replace(/[?&]$/, "");
1720
+ if (url2.includes("vitest=")) {
1721
+ url2 = url2.replace(REGEXP_VITEST$1, "").replace(/[?&]$/, "");
2058
1722
  }
2059
1723
  return [
2060
- url,
1724
+ url2,
2061
1725
  parts[2] || void 0,
2062
1726
  parts[3] || void 0
2063
1727
  ];
2064
1728
  }
2065
- function parseSingleFFOrSafariStack(raw) {
1729
+ function parseSingleFFOrSafariStack$1(raw) {
2066
1730
  let line = raw.trim();
2067
- if (SAFARI_NATIVE_CODE_REGEXP.test(line)) {
1731
+ if (SAFARI_NATIVE_CODE_REGEXP$1.test(line)) {
2068
1732
  return null;
2069
1733
  }
2070
1734
  if (line.includes(" > eval")) {
@@ -2090,12 +1754,12 @@ function parseSingleFFOrSafariStack(raw) {
2090
1754
  if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) {
2091
1755
  return null;
2092
1756
  }
2093
- const [url, lineNumber, columnNumber] = extractLocation(locationPart);
2094
- if (!url || !lineNumber || !columnNumber) {
1757
+ const [url2, lineNumber, columnNumber] = extractLocation$1(locationPart);
1758
+ if (!url2 || !lineNumber || !columnNumber) {
2095
1759
  return null;
2096
1760
  }
2097
1761
  return {
2098
- file: url,
1762
+ file: url2,
2099
1763
  method: functionName || "",
2100
1764
  line: Number.parseInt(lineNumber),
2101
1765
  column: Number.parseInt(columnNumber)
@@ -2103,25 +1767,25 @@ function parseSingleFFOrSafariStack(raw) {
2103
1767
  }
2104
1768
  function parseSingleStack(raw) {
2105
1769
  const line = raw.trim();
2106
- if (!CHROME_IE_STACK_REGEXP.test(line)) {
2107
- return parseSingleFFOrSafariStack(line);
1770
+ if (!CHROME_IE_STACK_REGEXP$1.test(line)) {
1771
+ return parseSingleFFOrSafariStack$1(line);
2108
1772
  }
2109
- return parseSingleV8Stack(line);
1773
+ return parseSingleV8Stack$1(line);
2110
1774
  }
2111
- function parseSingleV8Stack(raw) {
1775
+ function parseSingleV8Stack$1(raw) {
2112
1776
  let line = raw.trim();
2113
- if (!CHROME_IE_STACK_REGEXP.test(line)) {
1777
+ if (!CHROME_IE_STACK_REGEXP$1.test(line)) {
2114
1778
  return null;
2115
1779
  }
2116
1780
  if (line.includes("(eval ")) {
2117
1781
  line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, "");
2118
1782
  }
2119
1783
  let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, "");
2120
- const location = sanitizedLine.match(/ (\(.+\)$)/);
2121
- sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine;
2122
- const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine);
2123
- let method = location && sanitizedLine || "";
2124
- let file = url && ["eval", "<anonymous>"].includes(url) ? void 0 : url;
1784
+ const location2 = sanitizedLine.match(/ (\(.+\)$)/);
1785
+ sanitizedLine = location2 ? sanitizedLine.replace(location2[0], "") : sanitizedLine;
1786
+ const [url2, lineNumber, columnNumber] = extractLocation$1(location2 ? location2[1] : sanitizedLine);
1787
+ let method = location2 && sanitizedLine || "";
1788
+ let file = url2 && ["eval", "<anonymous>"].includes(url2) ? void 0 : url2;
2125
1789
  if (!file || !lineNumber || !columnNumber) {
2126
1790
  return null;
2127
1791
  }
@@ -2131,7 +1795,7 @@ function parseSingleV8Stack(raw) {
2131
1795
  if (file.startsWith("file://")) {
2132
1796
  file = file.slice(7);
2133
1797
  }
2134
- file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve$1(file);
1798
+ file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file);
2135
1799
  if (method) {
2136
1800
  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, "");
2137
1801
  }
@@ -2142,118 +1806,6 @@ function parseSingleV8Stack(raw) {
2142
1806
  column: Number.parseInt(columnNumber)
2143
1807
  };
2144
1808
  }
2145
- const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
2146
- function normalizeWindowsPath(input = "") {
2147
- if (!input) {
2148
- return input;
2149
- }
2150
- return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
2151
- }
2152
- const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
2153
- const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
2154
- function cwd() {
2155
- if (typeof process !== "undefined" && typeof process.cwd === "function") {
2156
- return process.cwd().replace(/\\/g, "/");
2157
- }
2158
- return "/";
2159
- }
2160
- const resolve = function(...arguments_) {
2161
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
2162
- let resolvedPath = "";
2163
- let resolvedAbsolute = false;
2164
- for (let index2 = arguments_.length - 1; index2 >= -1 && !resolvedAbsolute; index2--) {
2165
- const path = index2 >= 0 ? arguments_[index2] : cwd();
2166
- if (!path || path.length === 0) {
2167
- continue;
2168
- }
2169
- resolvedPath = `${path}/${resolvedPath}`;
2170
- resolvedAbsolute = isAbsolute(path);
2171
- }
2172
- resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
2173
- if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
2174
- return `/${resolvedPath}`;
2175
- }
2176
- return resolvedPath.length > 0 ? resolvedPath : ".";
2177
- };
2178
- function normalizeString(path, allowAboveRoot) {
2179
- let res = "";
2180
- let lastSegmentLength = 0;
2181
- let lastSlash = -1;
2182
- let dots = 0;
2183
- let char = null;
2184
- for (let index2 = 0; index2 <= path.length; ++index2) {
2185
- if (index2 < path.length) {
2186
- char = path[index2];
2187
- } else if (char === "/") {
2188
- break;
2189
- } else {
2190
- char = "/";
2191
- }
2192
- if (char === "/") {
2193
- if (lastSlash === index2 - 1 || dots === 1) ;
2194
- else if (dots === 2) {
2195
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
2196
- if (res.length > 2) {
2197
- const lastSlashIndex = res.lastIndexOf("/");
2198
- if (lastSlashIndex === -1) {
2199
- res = "";
2200
- lastSegmentLength = 0;
2201
- } else {
2202
- res = res.slice(0, lastSlashIndex);
2203
- lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
2204
- }
2205
- lastSlash = index2;
2206
- dots = 0;
2207
- continue;
2208
- } else if (res.length > 0) {
2209
- res = "";
2210
- lastSegmentLength = 0;
2211
- lastSlash = index2;
2212
- dots = 0;
2213
- continue;
2214
- }
2215
- }
2216
- if (allowAboveRoot) {
2217
- res += res.length > 0 ? "/.." : "..";
2218
- lastSegmentLength = 2;
2219
- }
2220
- } else {
2221
- if (res.length > 0) {
2222
- res += `/${path.slice(lastSlash + 1, index2)}`;
2223
- } else {
2224
- res = path.slice(lastSlash + 1, index2);
2225
- }
2226
- lastSegmentLength = index2 - lastSlash - 1;
2227
- }
2228
- lastSlash = index2;
2229
- dots = 0;
2230
- } else if (char === "." && dots !== -1) {
2231
- ++dots;
2232
- } else {
2233
- dots = -1;
2234
- }
2235
- }
2236
- return res;
2237
- }
2238
- const isAbsolute = function(p) {
2239
- return _IS_ABSOLUTE_RE.test(p);
2240
- };
2241
- const relative = function(from, to) {
2242
- const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
2243
- const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
2244
- if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) {
2245
- return _to.join("/");
2246
- }
2247
- const _fromCopy = [..._from];
2248
- for (const segment of _fromCopy) {
2249
- if (_to[0] !== segment) {
2250
- break;
2251
- }
2252
- _from.shift();
2253
- _to.shift();
2254
- }
2255
- return [..._from.map(() => ".."), ..._to].join("/");
2256
- };
2257
1809
  class PendingError extends Error {
2258
1810
  code = "VITEST_PENDING";
2259
1811
  taskId;
@@ -2746,7 +2298,7 @@ const kChainableContext = Symbol("kChainableContext");
2746
2298
  function getChainableContext(chainable) {
2747
2299
  return chainable == null ? void 0 : chainable[kChainableContext];
2748
2300
  }
2749
- function createChainable(keys, fn, context) {
2301
+ function createChainable(keys2, fn, context) {
2750
2302
  function create(context2) {
2751
2303
  const chain2 = function(...args) {
2752
2304
  return fn.apply(context2, args);
@@ -2765,7 +2317,7 @@ function createChainable(keys, fn, context) {
2765
2317
  },
2766
2318
  enumerable: false
2767
2319
  });
2768
- for (const key of keys) {
2320
+ for (const key of keys2) {
2769
2321
  Object.defineProperty(chain2, key, { get() {
2770
2322
  return create({
2771
2323
  ...context2,
@@ -2872,23 +2424,6 @@ function withSuiteFixtures(suiteHook, fn, context, stackTraceError, contextIndex
2872
2424
  return fixtured();
2873
2425
  };
2874
2426
  }
2875
- // @__NO_SIDE_EFFECTS__
2876
- function generateHash(str) {
2877
- let hash = 0;
2878
- if (str.length === 0) {
2879
- return `${hash}`;
2880
- }
2881
- for (let i2 = 0; i2 < str.length; i2++) {
2882
- const char = str.charCodeAt(i2);
2883
- hash = (hash << 5) - hash + char;
2884
- hash = hash & hash;
2885
- }
2886
- return `${hash}`;
2887
- }
2888
- // @__NO_SIDE_EFFECTS__
2889
- function generateFileHash(file, projectName) {
2890
- return /* @__PURE__ */ generateHash(`${file}${projectName || ""}`);
2891
- }
2892
2427
  function findTestFileStackTrace(testFilePath, error) {
2893
2428
  const lines = error.split("\n").slice(1);
2894
2429
  for (const line of lines) {
@@ -3003,7 +2538,7 @@ function createSuiteCollector(name, factory = () => {
3003
2538
  let suite2;
3004
2539
  initSuite();
3005
2540
  const task = function(name2 = "", options = {}) {
3006
- var _a, _b, _c, _d, _e;
2541
+ var _a, _b, _c, _d, _e, _f;
3007
2542
  const currentSuite = (_a = collectorContext.currentSuite) == null ? void 0 : _a.suite;
3008
2543
  const parentTask = currentSuite ?? ((_b = collectorContext.currentSuite) == null ? void 0 : _b.file);
3009
2544
  const parentTags = (parentTask == null ? void 0 : parentTask.tags) || [];
@@ -3024,7 +2559,9 @@ function createSuiteCollector(name, factory = () => {
3024
2559
  return acc;
3025
2560
  }, {});
3026
2561
  const testOwnMeta = options.meta;
2562
+ const parentOptions = (_c = collectorContext.currentSuite) == null ? void 0 : _c.options;
3027
2563
  options = {
2564
+ ...parentOptions,
3028
2565
  ...tagsOptions,
3029
2566
  ...options
3030
2567
  };
@@ -3044,14 +2581,14 @@ function createSuiteCollector(name, factory = () => {
3044
2581
  const task2 = {
3045
2582
  id: "",
3046
2583
  name: name2,
3047
- fullName: createTaskName([(currentSuite == null ? void 0 : currentSuite.fullName) ?? ((_d = (_c = collectorContext.currentSuite) == null ? void 0 : _c.file) == null ? void 0 : _d.fullName), name2]),
2584
+ fullName: createTaskName([(currentSuite == null ? void 0 : currentSuite.fullName) ?? ((_e = (_d = collectorContext.currentSuite) == null ? void 0 : _d.file) == null ? void 0 : _e.fullName), name2]),
3048
2585
  fullTestName: createTaskName([currentSuite == null ? void 0 : currentSuite.fullTestName, name2]),
3049
2586
  suite: currentSuite,
3050
2587
  each: options.each,
3051
2588
  fails: options.fails,
3052
2589
  context: void 0,
3053
2590
  type: "test",
3054
- file: (currentSuite == null ? void 0 : currentSuite.file) ?? ((_e = collectorContext.currentSuite) == null ? void 0 : _e.file),
2591
+ file: (currentSuite == null ? void 0 : currentSuite.file) ?? ((_f = collectorContext.currentSuite) == null ? void 0 : _f.file),
3055
2592
  timeout,
3056
2593
  retry: options.retry ?? runner.config.retry,
3057
2594
  repeats: options.repeats,
@@ -3065,7 +2602,7 @@ function createSuiteCollector(name, factory = () => {
3065
2602
  if (task2.mode === "run" && !handler) {
3066
2603
  task2.mode = "todo";
3067
2604
  }
3068
- if (options.concurrent || !options.sequential && runner.config.sequence.concurrent) {
2605
+ if (options.concurrent ?? runner.config.sequence.concurrent) {
3069
2606
  task2.concurrent = true;
3070
2607
  }
3071
2608
  task2.shuffle = suiteOptions == null ? void 0 : suiteOptions.shuffle;
@@ -3096,18 +2633,11 @@ function createSuiteCollector(name, factory = () => {
3096
2633
  return task2;
3097
2634
  };
3098
2635
  const test2 = createTest(function(name2, optionsOrFn, timeoutOrTest) {
3099
- let { options, handler } = parseArguments(optionsOrFn, timeoutOrTest);
3100
- if (typeof suiteOptions === "object") {
3101
- options = Object.assign({}, suiteOptions, options);
3102
- }
3103
- const concurrent = this.concurrent ?? (!this.sequential && (options == null ? void 0 : options.concurrent));
3104
- if (options.concurrent != null && concurrent != null) {
2636
+ const { options, handler } = parseArguments(optionsOrFn, timeoutOrTest);
2637
+ const concurrent = this.concurrent ?? (options == null ? void 0 : options.concurrent);
2638
+ if (concurrent != null) {
3105
2639
  options.concurrent = concurrent;
3106
2640
  }
3107
- const sequential = this.sequential ?? (!this.concurrent && (options == null ? void 0 : options.sequential));
3108
- if (options.sequential != null && sequential != null) {
3109
- options.sequential = sequential;
3110
- }
3111
2641
  const test3 = task(formatName(name2), {
3112
2642
  ...this,
3113
2643
  ...options,
@@ -3198,8 +2728,6 @@ function createSuite() {
3198
2728
  var _a;
3199
2729
  const currentSuite = collectorContext.currentSuite || defaultSuite;
3200
2730
  let { options, handler: factory } = parseArguments(factoryOrOptions, optionsOrFactory);
3201
- const isConcurrentSpecified = options.concurrent || this.concurrent || options.sequential === false;
3202
- const isSequentialSpecified = options.sequential || this.sequential || options.concurrent === false;
3203
2731
  const { meta: parentMeta, ...parentOptions } = (currentSuite == null ? void 0 : currentSuite.options) || {};
3204
2732
  options = {
3205
2733
  ...parentOptions,
@@ -3213,13 +2741,9 @@ function createSuite() {
3213
2741
  if (mode === "run" && !factory) {
3214
2742
  mode = "todo";
3215
2743
  }
3216
- const isConcurrent = isConcurrentSpecified || options.concurrent && !isSequentialSpecified;
3217
- const isSequential = isSequentialSpecified || options.sequential && !isConcurrentSpecified;
3218
- if (isConcurrent != null) {
3219
- options.concurrent = isConcurrent && !isSequential;
3220
- }
3221
- if (isSequential != null) {
3222
- options.sequential = isSequential && !isConcurrent;
2744
+ const concurrent = this.concurrent ?? options.concurrent;
2745
+ if (concurrent != null) {
2746
+ options.concurrent = concurrent;
3223
2747
  }
3224
2748
  if (parentMeta) {
3225
2749
  options.meta = Object.assign(/* @__PURE__ */ Object.create(null), parentMeta, options.meta);
@@ -3258,6 +2782,8 @@ function createSuite() {
3258
2782
  };
3259
2783
  };
3260
2784
  suiteFn.for = function(cases, ...args) {
2785
+ const context = getChainableContext(this);
2786
+ const suite2 = context.withContext();
3261
2787
  if (Array.isArray(cases) && args.length) {
3262
2788
  cases = formatTemplateString(cases, args);
3263
2789
  }
@@ -3265,7 +2791,7 @@ function createSuite() {
3265
2791
  const name_ = formatName(name);
3266
2792
  const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
3267
2793
  cases.forEach((item, idx) => {
3268
- suite(formatTitle(name_, toArray(item), idx), options, handler ? () => handler(item) : void 0);
2794
+ suite2(formatTitle(name_, toArray(item), idx), options, handler ? () => handler(item) : void 0);
3269
2795
  });
3270
2796
  };
3271
2797
  };
@@ -3273,7 +2799,6 @@ function createSuite() {
3273
2799
  suiteFn.runIf = (condition) => condition ? suite : suite.skip;
3274
2800
  return createChainable([
3275
2801
  "concurrent",
3276
- "sequential",
3277
2802
  "shuffle",
3278
2803
  "skip",
3279
2804
  "only",
@@ -3362,17 +2887,17 @@ function createTaskCollector(fn) {
3362
2887
  if (typeof fixtureValue === "function") {
3363
2888
  const builderFn = fixtureValue;
3364
2889
  const fixture = async (ctx, use) => {
3365
- let cleanup;
2890
+ let cleanup2;
3366
2891
  const onCleanup = (fn2) => {
3367
- if (cleanup !== void 0) {
2892
+ if (cleanup2 !== void 0) {
3368
2893
  throw new Error(`onCleanup can only be called once per fixture. Define separate fixtures if you need multiple cleanup functions.`);
3369
2894
  }
3370
- cleanup = fn2;
2895
+ cleanup2 = fn2;
3371
2896
  };
3372
2897
  const value = await builderFn(ctx, { onCleanup });
3373
2898
  await use(value);
3374
- if (cleanup) {
3375
- await cleanup();
2899
+ if (cleanup2) {
2900
+ await cleanup2();
3376
2901
  }
3377
2902
  };
3378
2903
  configureProps(fixture, { original: builderFn });
@@ -3414,7 +2939,6 @@ function createTaskCollector(fn) {
3414
2939
  taskFn.aroundAll = aroundAll;
3415
2940
  const _test = createChainable([
3416
2941
  "concurrent",
3417
- "sequential",
3418
2942
  "skip",
3419
2943
  "only",
3420
2944
  "todo",
@@ -3445,17 +2969,20 @@ function formatTitle(template, items, idx) {
3445
2969
  }
3446
2970
  });
3447
2971
  }
2972
+ const inspectOptions = { truncate: runner.config.taskTitleValueFormatTruncate };
3448
2973
  const isObjectItem = isObject(items[0]);
3449
2974
  function formatAttribute(s) {
3450
2975
  return s.replace(/\$([$\w.]+)/g, (_, key) => {
3451
- var _a, _b;
3452
2976
  const isArrayKey = /^\d+$/.test(key);
3453
2977
  if (!isObjectItem && !isArrayKey) {
3454
2978
  return `$${key}`;
3455
2979
  }
3456
2980
  const arrayElement = isArrayKey ? objectAttr(items, key) : void 0;
3457
2981
  const value = isObjectItem ? objectAttr(items[0], key, arrayElement) : arrayElement;
3458
- return objDisplay(value, { truncate: (_b = (_a = runner == null ? void 0 : runner.config) == null ? void 0 : _a.chaiConfig) == null ? void 0 : _b.truncateThreshold });
2982
+ if (typeof value === "string") {
2983
+ return truncateString(value, inspectOptions.truncate);
2984
+ }
2985
+ return inspect(value, inspectOptions);
3459
2986
  });
3460
2987
  }
3461
2988
  let output = "";
@@ -3466,7 +2993,7 @@ function formatTitle(template, items, idx) {
3466
2993
  // format "%"
3467
2994
  (match) => {
3468
2995
  if (i2 < count) {
3469
- output += format(match[0], items[i2++]);
2996
+ output += format([match[0], items[i2++]], inspectOptions);
3470
2997
  } else {
3471
2998
  output += match[0];
3472
2999
  }
@@ -3794,51 +3321,2268 @@ function manageArtifactAttachment(attachment) {
3794
3321
  attachment.bodyEncoding ?? (attachment.bodyEncoding = "base64");
3795
3322
  }
3796
3323
  }
3797
- async function importId(id) {
3798
- const name = `/@id/${id}`.replace(/\\/g, "/");
3799
- return (/* @__PURE__ */ getBrowserState()).wrapModule(() => import(
3800
- /* @vite-ignore */
3801
- name
3802
- ));
3324
+ var comma = ",".charCodeAt(0);
3325
+ var chars$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3326
+ var intToChar$1 = new Uint8Array(64);
3327
+ var charToInt$1 = new Uint8Array(128);
3328
+ for (let i2 = 0; i2 < chars$1.length; i2++) {
3329
+ const c = chars$1.charCodeAt(i2);
3330
+ intToChar$1[i2] = c;
3331
+ charToInt$1[c] = i2;
3332
+ }
3333
+ function decodeInteger(reader, relative) {
3334
+ let value = 0;
3335
+ let shift = 0;
3336
+ let integer = 0;
3337
+ do {
3338
+ const c = reader.next();
3339
+ integer = charToInt$1[c];
3340
+ value |= (integer & 31) << shift;
3341
+ shift += 5;
3342
+ } while (integer & 32);
3343
+ const shouldNegate = value & 1;
3344
+ value >>>= 1;
3345
+ if (shouldNegate) {
3346
+ value = -2147483648 | -value;
3347
+ }
3348
+ return relative + value;
3349
+ }
3350
+ function hasMoreVlq(reader, max) {
3351
+ if (reader.pos >= max) return false;
3352
+ return reader.peek() !== comma;
3353
+ }
3354
+ var StringReader = class {
3355
+ constructor(buffer) {
3356
+ this.pos = 0;
3357
+ this.buffer = buffer;
3358
+ }
3359
+ next() {
3360
+ return this.buffer.charCodeAt(this.pos++);
3361
+ }
3362
+ peek() {
3363
+ return this.buffer.charCodeAt(this.pos);
3364
+ }
3365
+ indexOf(char) {
3366
+ const { buffer, pos } = this;
3367
+ const idx = buffer.indexOf(char, pos);
3368
+ return idx === -1 ? buffer.length : idx;
3369
+ }
3370
+ };
3371
+ function decode(mappings) {
3372
+ const { length } = mappings;
3373
+ const reader = new StringReader(mappings);
3374
+ const decoded = [];
3375
+ let genColumn = 0;
3376
+ let sourcesIndex = 0;
3377
+ let sourceLine = 0;
3378
+ let sourceColumn = 0;
3379
+ let namesIndex = 0;
3380
+ do {
3381
+ const semi = reader.indexOf(";");
3382
+ const line = [];
3383
+ let sorted = true;
3384
+ let lastCol = 0;
3385
+ genColumn = 0;
3386
+ while (reader.pos < semi) {
3387
+ let seg;
3388
+ genColumn = decodeInteger(reader, genColumn);
3389
+ if (genColumn < lastCol) sorted = false;
3390
+ lastCol = genColumn;
3391
+ if (hasMoreVlq(reader, semi)) {
3392
+ sourcesIndex = decodeInteger(reader, sourcesIndex);
3393
+ sourceLine = decodeInteger(reader, sourceLine);
3394
+ sourceColumn = decodeInteger(reader, sourceColumn);
3395
+ if (hasMoreVlq(reader, semi)) {
3396
+ namesIndex = decodeInteger(reader, namesIndex);
3397
+ seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
3398
+ } else {
3399
+ seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
3400
+ }
3401
+ } else {
3402
+ seg = [genColumn];
3403
+ }
3404
+ line.push(seg);
3405
+ reader.pos++;
3406
+ }
3407
+ if (!sorted) sort(line);
3408
+ decoded.push(line);
3409
+ reader.pos = semi + 1;
3410
+ } while (reader.pos <= length);
3411
+ return decoded;
3412
+ }
3413
+ function sort(line) {
3414
+ line.sort(sortComparator);
3415
+ }
3416
+ function sortComparator(a, b2) {
3417
+ return a[0] - b2[0];
3418
+ }
3419
+ var resolveUri_umd$1 = { exports: {} };
3420
+ var resolveUri_umd = resolveUri_umd$1.exports;
3421
+ var hasRequiredResolveUri_umd;
3422
+ function requireResolveUri_umd() {
3423
+ if (hasRequiredResolveUri_umd) return resolveUri_umd$1.exports;
3424
+ hasRequiredResolveUri_umd = 1;
3425
+ (function(module, exports$1) {
3426
+ (function(global, factory) {
3427
+ module.exports = factory();
3428
+ })(resolveUri_umd, (function() {
3429
+ const schemeRegex = /^[\w+.-]+:\/\//;
3430
+ const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
3431
+ const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
3432
+ function isAbsoluteUrl(input) {
3433
+ return schemeRegex.test(input);
3434
+ }
3435
+ function isSchemeRelativeUrl(input) {
3436
+ return input.startsWith("//");
3437
+ }
3438
+ function isAbsolutePath(input) {
3439
+ return input.startsWith("/");
3440
+ }
3441
+ function isFileUrl(input) {
3442
+ return input.startsWith("file:");
3443
+ }
3444
+ function isRelative(input) {
3445
+ return /^[.?#]/.test(input);
3446
+ }
3447
+ function parseAbsoluteUrl(input) {
3448
+ const match = urlRegex.exec(input);
3449
+ return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
3450
+ }
3451
+ function parseFileUrl(input) {
3452
+ const match = fileRegex.exec(input);
3453
+ const path = match[2];
3454
+ return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || "");
3455
+ }
3456
+ function makeUrl(scheme, user, host, port, path, query, hash) {
3457
+ return {
3458
+ scheme,
3459
+ user,
3460
+ host,
3461
+ port,
3462
+ path,
3463
+ query,
3464
+ hash,
3465
+ type: 7
3466
+ };
3467
+ }
3468
+ function parseUrl(input) {
3469
+ if (isSchemeRelativeUrl(input)) {
3470
+ const url3 = parseAbsoluteUrl("http:" + input);
3471
+ url3.scheme = "";
3472
+ url3.type = 6;
3473
+ return url3;
3474
+ }
3475
+ if (isAbsolutePath(input)) {
3476
+ const url3 = parseAbsoluteUrl("http://foo.com" + input);
3477
+ url3.scheme = "";
3478
+ url3.host = "";
3479
+ url3.type = 5;
3480
+ return url3;
3481
+ }
3482
+ if (isFileUrl(input))
3483
+ return parseFileUrl(input);
3484
+ if (isAbsoluteUrl(input))
3485
+ return parseAbsoluteUrl(input);
3486
+ const url2 = parseAbsoluteUrl("http://foo.com/" + input);
3487
+ url2.scheme = "";
3488
+ url2.host = "";
3489
+ url2.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
3490
+ return url2;
3491
+ }
3492
+ function stripPathFilename(path) {
3493
+ if (path.endsWith("/.."))
3494
+ return path;
3495
+ const index2 = path.lastIndexOf("/");
3496
+ return path.slice(0, index2 + 1);
3497
+ }
3498
+ function mergePaths(url2, base) {
3499
+ normalizePath(base, base.type);
3500
+ if (url2.path === "/") {
3501
+ url2.path = base.path;
3502
+ } else {
3503
+ url2.path = stripPathFilename(base.path) + url2.path;
3504
+ }
3505
+ }
3506
+ function normalizePath(url2, type) {
3507
+ const rel = type <= 4;
3508
+ const pieces = url2.path.split("/");
3509
+ let pointer = 1;
3510
+ let positive = 0;
3511
+ let addTrailingSlash = false;
3512
+ for (let i2 = 1; i2 < pieces.length; i2++) {
3513
+ const piece = pieces[i2];
3514
+ if (!piece) {
3515
+ addTrailingSlash = true;
3516
+ continue;
3517
+ }
3518
+ addTrailingSlash = false;
3519
+ if (piece === ".")
3520
+ continue;
3521
+ if (piece === "..") {
3522
+ if (positive) {
3523
+ addTrailingSlash = true;
3524
+ positive--;
3525
+ pointer--;
3526
+ } else if (rel) {
3527
+ pieces[pointer++] = piece;
3528
+ }
3529
+ continue;
3530
+ }
3531
+ pieces[pointer++] = piece;
3532
+ positive++;
3533
+ }
3534
+ let path = "";
3535
+ for (let i2 = 1; i2 < pointer; i2++) {
3536
+ path += "/" + pieces[i2];
3537
+ }
3538
+ if (!path || addTrailingSlash && !path.endsWith("/..")) {
3539
+ path += "/";
3540
+ }
3541
+ url2.path = path;
3542
+ }
3543
+ function resolve2(input, base) {
3544
+ if (!input && !base)
3545
+ return "";
3546
+ const url2 = parseUrl(input);
3547
+ let inputType = url2.type;
3548
+ if (base && inputType !== 7) {
3549
+ const baseUrl = parseUrl(base);
3550
+ const baseType = baseUrl.type;
3551
+ switch (inputType) {
3552
+ case 1:
3553
+ url2.hash = baseUrl.hash;
3554
+ // fall through
3555
+ case 2:
3556
+ url2.query = baseUrl.query;
3557
+ // fall through
3558
+ case 3:
3559
+ case 4:
3560
+ mergePaths(url2, baseUrl);
3561
+ // fall through
3562
+ case 5:
3563
+ url2.user = baseUrl.user;
3564
+ url2.host = baseUrl.host;
3565
+ url2.port = baseUrl.port;
3566
+ // fall through
3567
+ case 6:
3568
+ url2.scheme = baseUrl.scheme;
3569
+ }
3570
+ if (baseType > inputType)
3571
+ inputType = baseType;
3572
+ }
3573
+ normalizePath(url2, inputType);
3574
+ const queryHash = url2.query + url2.hash;
3575
+ switch (inputType) {
3576
+ // This is impossible, because of the empty checks at the start of the function.
3577
+ // case UrlType.Empty:
3578
+ case 2:
3579
+ case 3:
3580
+ return queryHash;
3581
+ case 4: {
3582
+ const path = url2.path.slice(1);
3583
+ if (!path)
3584
+ return queryHash || ".";
3585
+ if (isRelative(base || input) && !isRelative(path)) {
3586
+ return "./" + path + queryHash;
3587
+ }
3588
+ return path + queryHash;
3589
+ }
3590
+ case 5:
3591
+ return url2.path + queryHash;
3592
+ default:
3593
+ return url2.scheme + "//" + url2.user + url2.host + url2.port + url2.path + queryHash;
3594
+ }
3595
+ }
3596
+ return resolve2;
3597
+ }));
3598
+ })(resolveUri_umd$1);
3599
+ return resolveUri_umd$1.exports;
3600
+ }
3601
+ requireResolveUri_umd();
3602
+ var COLUMN = 0;
3603
+ var SOURCES_INDEX = 1;
3604
+ var SOURCE_LINE = 2;
3605
+ var SOURCE_COLUMN = 3;
3606
+ var NAMES_INDEX = 4;
3607
+ var found = false;
3608
+ function binarySearch(haystack, needle, low, high) {
3609
+ while (low <= high) {
3610
+ const mid = low + (high - low >> 1);
3611
+ const cmp = haystack[mid][COLUMN] - needle;
3612
+ if (cmp === 0) {
3613
+ found = true;
3614
+ return mid;
3615
+ }
3616
+ if (cmp < 0) {
3617
+ low = mid + 1;
3618
+ } else {
3619
+ high = mid - 1;
3620
+ }
3621
+ }
3622
+ found = false;
3623
+ return low - 1;
3624
+ }
3625
+ function upperBound(haystack, needle, index2) {
3626
+ for (let i2 = index2 + 1; i2 < haystack.length; index2 = i2++) {
3627
+ if (haystack[i2][COLUMN] !== needle) break;
3628
+ }
3629
+ return index2;
3630
+ }
3631
+ function lowerBound(haystack, needle, index2) {
3632
+ for (let i2 = index2 - 1; i2 >= 0; index2 = i2--) {
3633
+ if (haystack[i2][COLUMN] !== needle) break;
3634
+ }
3635
+ return index2;
3636
+ }
3637
+ function memoizedBinarySearch(haystack, needle, state, key) {
3638
+ const { lastKey, lastNeedle, lastIndex } = state;
3639
+ let low = 0;
3640
+ let high = haystack.length - 1;
3641
+ if (key === lastKey) {
3642
+ if (needle === lastNeedle) {
3643
+ found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
3644
+ return lastIndex;
3645
+ }
3646
+ if (needle >= lastNeedle) {
3647
+ low = lastIndex === -1 ? 0 : lastIndex;
3648
+ } else {
3649
+ high = lastIndex;
3650
+ }
3651
+ }
3652
+ state.lastKey = key;
3653
+ state.lastNeedle = needle;
3654
+ return state.lastIndex = binarySearch(haystack, needle, low, high);
3655
+ }
3656
+ var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
3657
+ var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
3658
+ var LEAST_UPPER_BOUND = -1;
3659
+ var GREATEST_LOWER_BOUND = 1;
3660
+ function cast(map) {
3661
+ return map;
3662
+ }
3663
+ function decodedMappings(map) {
3664
+ var _a;
3665
+ return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
3666
+ }
3667
+ function originalPositionFor(map, needle) {
3668
+ let { line, column, bias } = needle;
3669
+ line--;
3670
+ if (line < 0) throw new Error(LINE_GTR_ZERO);
3671
+ if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
3672
+ const decoded = decodedMappings(map);
3673
+ if (line >= decoded.length) return OMapping(null, null, null, null);
3674
+ const segments = decoded[line];
3675
+ const index2 = traceSegmentInternal(
3676
+ segments,
3677
+ cast(map)._decodedMemo,
3678
+ line,
3679
+ column,
3680
+ bias || GREATEST_LOWER_BOUND
3681
+ );
3682
+ if (index2 === -1) return OMapping(null, null, null, null);
3683
+ const segment = segments[index2];
3684
+ if (segment.length === 1) return OMapping(null, null, null, null);
3685
+ const { names, resolvedSources } = map;
3686
+ return OMapping(
3687
+ resolvedSources[segment[SOURCES_INDEX]],
3688
+ segment[SOURCE_LINE] + 1,
3689
+ segment[SOURCE_COLUMN],
3690
+ segment.length === 5 ? names[segment[NAMES_INDEX]] : null
3691
+ );
3692
+ }
3693
+ function OMapping(source, line, column, name) {
3694
+ return { source, line, column, name };
3695
+ }
3696
+ function traceSegmentInternal(segments, memo, line, column, bias) {
3697
+ let index2 = memoizedBinarySearch(segments, column, memo, line);
3698
+ if (found) {
3699
+ index2 = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index2);
3700
+ } else if (bias === LEAST_UPPER_BOUND) index2++;
3701
+ if (index2 === -1 || index2 === segments.length) return -1;
3702
+ return index2;
3703
+ }
3704
+ function notNullish(v) {
3705
+ return v != null;
3803
3706
  }
3804
- async function importFs(id) {
3805
- const name = `/@fs/${id}`.replace(/\\/g, "/");
3806
- return (/* @__PURE__ */ getBrowserState()).wrapModule(() => import(
3807
- /* @vite-ignore */
3808
- name
3809
- ));
3707
+ const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
3708
+ const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
3709
+ const stackIgnorePatterns = [
3710
+ "node:internal",
3711
+ /\/packages\/\w+\/dist\//,
3712
+ /\/@vitest\/\w+\/dist\//,
3713
+ "/vitest/dist/",
3714
+ "/vitest/src/",
3715
+ "/node_modules/chai/",
3716
+ "/node_modules/tinyspy/",
3717
+ "/vite/dist/node/module-runner",
3718
+ "/rolldown-vite/dist/node/module-runner",
3719
+ // browser related deps
3720
+ "/deps/chunk-",
3721
+ "/deps/@vitest",
3722
+ "/deps/loupe",
3723
+ "/deps/chai",
3724
+ "/browser-playwright/dist/locators.js",
3725
+ "/browser-webdriverio/dist/locators.js",
3726
+ "/browser-preview/dist/locators.js",
3727
+ /node:\w+/,
3728
+ /__vitest_test__/,
3729
+ /__vitest_browser__/,
3730
+ "/@id/__x00__vitest/browser",
3731
+ /\/deps\/vitest_/
3732
+ ];
3733
+ const NOW_LENGTH = Date.now().toString().length;
3734
+ const REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`);
3735
+ function extractLocation(urlLike) {
3736
+ if (!urlLike.includes(":")) {
3737
+ return [urlLike];
3738
+ }
3739
+ const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/;
3740
+ const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, ""));
3741
+ if (!parts) {
3742
+ return [urlLike];
3743
+ }
3744
+ let url2 = parts[1];
3745
+ if (url2.startsWith("async ")) {
3746
+ url2 = url2.slice(6);
3747
+ }
3748
+ if (url2.startsWith("http:") || url2.startsWith("https:")) {
3749
+ const urlObj = new URL(url2);
3750
+ urlObj.searchParams.delete("import");
3751
+ urlObj.searchParams.delete("browserv");
3752
+ url2 = urlObj.pathname + urlObj.hash + urlObj.search;
3753
+ }
3754
+ if (url2.startsWith("/@fs/")) {
3755
+ const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url2);
3756
+ url2 = url2.slice(isWindows ? 5 : 4);
3757
+ }
3758
+ if (url2.includes("vitest=")) {
3759
+ url2 = url2.replace(REGEXP_VITEST, "").replace(/[?&]$/, "");
3760
+ }
3761
+ return [url2, parts[2] || void 0, parts[3] || void 0];
3810
3762
  }
3811
- const moduleRunner = {
3812
- isBrowser: true,
3813
- import: (id) => {
3814
- if (id[0] === "/" || id[1] === ":") {
3815
- return importFs(id);
3763
+ function parseSingleFFOrSafariStack(raw) {
3764
+ let line = raw.trim();
3765
+ if (SAFARI_NATIVE_CODE_REGEXP.test(line)) {
3766
+ return null;
3767
+ }
3768
+ if (line.includes(" > eval")) {
3769
+ line = line.replace(
3770
+ / line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,
3771
+ ":$1"
3772
+ );
3773
+ }
3774
+ if (!line.includes("@")) {
3775
+ return null;
3776
+ }
3777
+ let atIndex = -1;
3778
+ let locationPart = "";
3779
+ let functionName;
3780
+ for (let i2 = 0; i2 < line.length; i2++) {
3781
+ if (line[i2] === "@") {
3782
+ const candidateLocation = line.slice(i2 + 1);
3783
+ if (candidateLocation.includes(":") && candidateLocation.length >= 3) {
3784
+ atIndex = i2;
3785
+ locationPart = candidateLocation;
3786
+ functionName = i2 > 0 ? line.slice(0, i2) : void 0;
3787
+ break;
3788
+ }
3816
3789
  }
3817
- return importId(id);
3818
3790
  }
3819
- };
3820
- function getConfig() {
3821
- return (/* @__PURE__ */ getBrowserState()).config;
3822
- }
3823
- // @__NO_SIDE_EFFECTS__
3824
- function getBrowserState() {
3825
- return window.__vitest_browser_runner__;
3826
- }
3827
- // @__NO_SIDE_EFFECTS__
3828
- function getWorkerState() {
3829
- const state = window.__vitest_worker__;
3830
- if (!state) {
3831
- throw new Error("Worker state is not found. This is an issue with Vitest. Please, open an issue.");
3832
- }
3833
- return state;
3834
- }
3835
- export {
3836
- getConfig as a,
3837
- generateFileHash as b,
3838
- resolve as c,
3839
- getWorkerState as d,
3840
- getTestName as e,
3841
- getBrowserState as g,
3842
- moduleRunner as m,
3843
- relative as r
3844
- };
3791
+ if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) {
3792
+ return null;
3793
+ }
3794
+ const [url2, lineNumber, columnNumber] = extractLocation(locationPart);
3795
+ if (!url2 || !lineNumber || !columnNumber) {
3796
+ return null;
3797
+ }
3798
+ return {
3799
+ file: url2,
3800
+ method: functionName || "",
3801
+ line: Number.parseInt(lineNumber),
3802
+ column: Number.parseInt(columnNumber)
3803
+ };
3804
+ }
3805
+ function parseSingleV8Stack(raw) {
3806
+ let line = raw.trim();
3807
+ if (!CHROME_IE_STACK_REGEXP.test(line)) {
3808
+ return null;
3809
+ }
3810
+ if (line.includes("(eval ")) {
3811
+ line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, "");
3812
+ }
3813
+ let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, "");
3814
+ const location2 = sanitizedLine.match(/ (\(.+\)$)/);
3815
+ sanitizedLine = location2 ? sanitizedLine.replace(location2[0], "") : sanitizedLine;
3816
+ const [url2, lineNumber, columnNumber] = extractLocation(
3817
+ location2 ? location2[1] : sanitizedLine
3818
+ );
3819
+ let method = location2 && sanitizedLine || "";
3820
+ let file = url2 && ["eval", "<anonymous>"].includes(url2) ? void 0 : url2;
3821
+ if (!file || !lineNumber || !columnNumber) {
3822
+ return null;
3823
+ }
3824
+ if (method.startsWith("async ")) {
3825
+ method = method.slice(6);
3826
+ }
3827
+ if (file.startsWith("file://")) {
3828
+ file = file.slice(7);
3829
+ }
3830
+ file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve$1(file);
3831
+ if (method) {
3832
+ 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, "");
3833
+ }
3834
+ return {
3835
+ method,
3836
+ file,
3837
+ line: Number.parseInt(lineNumber),
3838
+ column: Number.parseInt(columnNumber)
3839
+ };
3840
+ }
3841
+ function createStackString(stacks) {
3842
+ return stacks.map((stack) => {
3843
+ const line = `${stack.file}:${stack.line}:${stack.column}`;
3844
+ if (stack.method) {
3845
+ return ` at ${stack.method}(${line})`;
3846
+ }
3847
+ return ` at ${line}`;
3848
+ }).join("\n");
3849
+ }
3850
+ function parseStacktrace(stack, options = {}) {
3851
+ const { ignoreStackEntries = stackIgnorePatterns } = options;
3852
+ let stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack);
3853
+ const helperIndex = stacks.findLastIndex(
3854
+ (s) => (
3855
+ // this covers cases such as
3856
+ // "__VITEST_HELPER__"
3857
+ // "__VITEST_HELPER__ [as <object method name>]"
3858
+ // "async*__VITEST_HELPER__" (firefox)
3859
+ // "async __VITEST_HELPER__" (webkit)
3860
+ s.method.includes("__VITEST_HELPER__")
3861
+ )
3862
+ );
3863
+ if (helperIndex >= 0) {
3864
+ stacks = stacks.slice(helperIndex + 1);
3865
+ }
3866
+ return stacks.map((stack2) => {
3867
+ var _a;
3868
+ if (options.getUrlId) {
3869
+ stack2.file = options.getUrlId(stack2.file);
3870
+ }
3871
+ const map = (_a = options.getSourceMap) == null ? void 0 : _a.call(options, stack2.file);
3872
+ if (!map || typeof map !== "object" || !map.version) {
3873
+ return shouldFilter(ignoreStackEntries, stack2.file) ? null : stack2;
3874
+ }
3875
+ const traceMap = new DecodedMap(map, stack2.file);
3876
+ const position = getOriginalPosition(traceMap, stack2);
3877
+ if (!position) {
3878
+ return stack2;
3879
+ }
3880
+ const { line, column, source, name } = position;
3881
+ let file = source || stack2.file;
3882
+ if (file.match(/\/\w:\//)) {
3883
+ file = file.slice(1);
3884
+ }
3885
+ if (shouldFilter(ignoreStackEntries, file)) {
3886
+ return null;
3887
+ }
3888
+ if (line != null && column != null) {
3889
+ return {
3890
+ line,
3891
+ column,
3892
+ file,
3893
+ method: name || stack2.method
3894
+ };
3895
+ }
3896
+ return stack2;
3897
+ }).filter((s) => s != null);
3898
+ }
3899
+ function shouldFilter(ignoreStackEntries, file) {
3900
+ return ignoreStackEntries.some((p) => file.match(p));
3901
+ }
3902
+ function parseFFOrSafariStackTrace(stack) {
3903
+ return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish);
3904
+ }
3905
+ function parseV8Stacktrace(stack) {
3906
+ return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish);
3907
+ }
3908
+ class DecodedMap {
3909
+ constructor(map, from) {
3910
+ this.map = map;
3911
+ const { mappings, names, sources } = map;
3912
+ this.version = map.version;
3913
+ this.names = names || [];
3914
+ this._encoded = mappings || "";
3915
+ this._decodedMemo = memoizedState();
3916
+ this.url = from;
3917
+ this.resolvedSources = (sources || []).map(
3918
+ (s) => resolve$1(from, "..", s || "")
3919
+ );
3920
+ }
3921
+ _encoded;
3922
+ _decoded;
3923
+ _decodedMemo;
3924
+ url;
3925
+ version;
3926
+ names = [];
3927
+ resolvedSources;
3928
+ }
3929
+ function memoizedState() {
3930
+ return {
3931
+ lastKey: -1,
3932
+ lastNeedle: -1,
3933
+ lastIndex: -1
3934
+ };
3935
+ }
3936
+ function getOriginalPosition(map, needle) {
3937
+ const result = originalPositionFor(map, needle);
3938
+ if (result.column == null) {
3939
+ return null;
3940
+ }
3941
+ return result;
3942
+ }
3943
+ class VitestBrowserSnapshotEnvironment {
3944
+ sourceMaps = /* @__PURE__ */ new Map();
3945
+ traceMaps = /* @__PURE__ */ new Map();
3946
+ addSourceMap(filepath, map) {
3947
+ this.sourceMaps.set(filepath, map);
3948
+ }
3949
+ getVersion() {
3950
+ return "1";
3951
+ }
3952
+ getHeader() {
3953
+ return `// Vitest Snapshot v${this.getVersion()}, https://vitest.dev/guide/snapshot.html`;
3954
+ }
3955
+ readSnapshotFile(filepath) {
3956
+ return rpc$1().readSnapshotFile(filepath);
3957
+ }
3958
+ saveSnapshotFile(filepath, snapshot) {
3959
+ return rpc$1().saveSnapshotFile(filepath, snapshot);
3960
+ }
3961
+ resolvePath(filepath) {
3962
+ return rpc$1().resolveSnapshotPath(filepath);
3963
+ }
3964
+ resolveRawPath(testPath, rawPath) {
3965
+ return rpc$1().resolveSnapshotRawPath(testPath, rawPath);
3966
+ }
3967
+ removeSnapshotFile(filepath) {
3968
+ return rpc$1().removeSnapshotFile(filepath);
3969
+ }
3970
+ processStackTrace(stack) {
3971
+ const map = this.sourceMaps.get(stack.file);
3972
+ if (!map) {
3973
+ return stack;
3974
+ }
3975
+ let traceMap = this.traceMaps.get(stack.file);
3976
+ if (!traceMap) {
3977
+ traceMap = new DecodedMap$1(map, stack.file);
3978
+ this.traceMaps.set(stack.file, traceMap);
3979
+ }
3980
+ const position = getOriginalPosition$1(traceMap, stack);
3981
+ if (position) {
3982
+ return { ...stack, line: position.line, column: position.column };
3983
+ }
3984
+ return stack;
3985
+ }
3986
+ }
3987
+ function rpc$1() {
3988
+ return globalThis.__vitest_worker__.rpc;
3989
+ }
3990
+ const PSEUDO_CLASS_NAMES = [
3991
+ ":hover",
3992
+ ":active",
3993
+ ":focus",
3994
+ ":focus-visible",
3995
+ ":focus-within"
3996
+ ];
3997
+ function getBrowserTraceState() {
3998
+ var _a;
3999
+ return (_a = getBrowserState()).browserTraceState ?? (_a.browserTraceState = {});
4000
+ }
4001
+ function getTraceStateKey(testId, repeats, retry) {
4002
+ return `${testId}:${repeats}:${retry}`;
4003
+ }
4004
+ function recordBrowserTraceEntry(task, options) {
4005
+ const attemptInfo = getBrowserState().browserTraceAttempts.get(task.id);
4006
+ const relativeStartTime = (options.startTime ?? now$1()) - attemptInfo.startTime;
4007
+ const snapshot = takeSnapshot(options.element);
4008
+ const entry = {
4009
+ ...options,
4010
+ startTime: relativeStartTime,
4011
+ snapshot
4012
+ };
4013
+ const { retry, repeats } = attemptInfo;
4014
+ const { recordCanvas } = getBrowserState().config.browser.traceView;
4015
+ const state = getBrowserTraceState();
4016
+ const traceKey = getTraceStateKey(task.id, repeats, retry);
4017
+ state[traceKey] ?? (state[traceKey] = { retry, repeats, recordCanvas, entries: [] });
4018
+ state[traceKey].entries.push(entry);
4019
+ }
4020
+ function takeSnapshot(serializedLocator) {
4021
+ const { snapshot, createMirror } = getBrowserState().browserTraceDomSnapshot;
4022
+ const traceView = getBrowserState().config.browser.traceView;
4023
+ const engine = getBrowserState().selectorEngine;
4024
+ const mirror = createMirror();
4025
+ const serialized = snapshot(document, {
4026
+ mirror,
4027
+ inlineImages: traceView.inlineImages,
4028
+ recordCanvas: traceView.recordCanvas
4029
+ });
4030
+ const result = {
4031
+ serialized,
4032
+ viewport: {
4033
+ width: window.innerWidth,
4034
+ height: window.innerHeight
4035
+ },
4036
+ scroll: {
4037
+ x: window.scrollX,
4038
+ y: window.scrollY
4039
+ },
4040
+ pseudoClassIds: {}
4041
+ };
4042
+ for (const className of PSEUDO_CLASS_NAMES) {
4043
+ const elements = document.querySelectorAll(className);
4044
+ const ids = Array.from(elements, (el) => mirror.getId(el)).filter((id) => id !== -1);
4045
+ result.pseudoClassIds[className] = ids;
4046
+ }
4047
+ if (serializedLocator) {
4048
+ try {
4049
+ const el = engine.querySelector(
4050
+ engine.parseSelector(serializedLocator._pwSelector ?? serializedLocator.selector),
4051
+ document.documentElement,
4052
+ false
4053
+ );
4054
+ if (!el) {
4055
+ result.selectorResolution = "missing";
4056
+ } else {
4057
+ const id = mirror.getId(el);
4058
+ if (id !== -1) {
4059
+ result.selectorId = id;
4060
+ result.selectorResolution = "matched";
4061
+ } else {
4062
+ result.selectorResolution = "missing";
4063
+ }
4064
+ }
4065
+ } catch (error) {
4066
+ result.selectorResolution = "error";
4067
+ result.selectorError = error instanceof Error ? error.message : String(error);
4068
+ }
4069
+ }
4070
+ return result;
4071
+ }
4072
+ function getBrowserTrace(testId, repeats, retry) {
4073
+ const state = getBrowserTraceState();
4074
+ const traceKey = getTraceStateKey(testId, repeats, retry);
4075
+ const result = state[traceKey];
4076
+ if (result) {
4077
+ delete state[traceKey];
4078
+ return result;
4079
+ }
4080
+ }
4081
+ const browserHashMap = /* @__PURE__ */ new Map();
4082
+ function createBrowserRunner(runnerClass, mocker, state, coverageModule) {
4083
+ return class BrowserTestRunner extends runnerClass {
4084
+ config;
4085
+ hashMap = browserHashMap;
4086
+ sourceMapCache = /* @__PURE__ */ new Map();
4087
+ method = "run";
4088
+ commands;
4089
+ _otel;
4090
+ constructor(options) {
4091
+ super(options.config);
4092
+ this.config = options.config;
4093
+ this.commands = getBrowserState().commands;
4094
+ this.viteEnvironment = "__browser__";
4095
+ this._otel = getBrowserState().traces;
4096
+ }
4097
+ setMethod(method) {
4098
+ this.method = method;
4099
+ }
4100
+ traces = /* @__PURE__ */ new Map();
4101
+ onBeforeTryTask = async (...args) => {
4102
+ var _a;
4103
+ await userEvent.cleanup();
4104
+ await ((_a = super.onBeforeTryTask) == null ? void 0 : _a.call(this, ...args));
4105
+ const trace = this.config.browser.trace;
4106
+ const test2 = args[0];
4107
+ const { retry, repeats } = args[1];
4108
+ const shouldTrace = trace !== "off" && !(trace === "on-all-retries" && retry === 0) && !(trace === "on-first-retry" && retry !== 1);
4109
+ const shouldTraceView = this.config.browser.traceView.enabled;
4110
+ if (!shouldTraceView && !shouldTrace) {
4111
+ getBrowserState().activeTraceTaskIds.delete(test2.id);
4112
+ getBrowserState().browserTraceAttempts.delete(test2.id);
4113
+ return;
4114
+ }
4115
+ if (shouldTraceView) {
4116
+ getBrowserState().browserTraceDomSnapshot = await __vitePreload(() => import("./rrweb-snapshot-xhvrgOHx.js"), true ? [] : void 0);
4117
+ getBrowserState().browserTraceAttempts.set(test2.id, { retry, repeats, startTime: now$1() });
4118
+ } else {
4119
+ getBrowserState().browserTraceAttempts.delete(test2.id);
4120
+ }
4121
+ if (!shouldTrace) {
4122
+ getBrowserState().activeTraceTaskIds.delete(test2.id);
4123
+ return;
4124
+ }
4125
+ getBrowserState().activeTraceTaskIds.add(test2.id);
4126
+ let title = getTestName(test2);
4127
+ if (retry) {
4128
+ title += ` (retry x${retry})`;
4129
+ }
4130
+ if (repeats) {
4131
+ title += ` (repeat x${repeats})`;
4132
+ }
4133
+ const name = getTraceName(test2, retry, repeats);
4134
+ await this.commands.triggerCommand(
4135
+ "__vitest_startChunkTrace",
4136
+ [{ name, title }]
4137
+ );
4138
+ };
4139
+ onAfterRetryTask = async (test2, { retry, repeats }) => {
4140
+ var _a, _b, _c, _d, _e, _f;
4141
+ const hasActiveTraceView = getBrowserState().browserTraceAttempts.has(test2.id);
4142
+ if (hasActiveTraceView) {
4143
+ const status = (_a = test2.result) == null ? void 0 : _a.state;
4144
+ const stack = status === "fail" ? (_c = (_b = test2.result) == null ? void 0 : _b.errors) == null ? void 0 : _c[0].stack : void 0;
4145
+ const location2 = test2.location ? { ...test2.location, file: test2.file.filepath } : void 0;
4146
+ recordBrowserTraceEntry(test2, {
4147
+ name: `vitest:onAfterRetryTask`,
4148
+ kind: "lifecycle",
4149
+ ...status === "pass" || status === "fail" ? { status } : {},
4150
+ ...stack ? { stack } : location2 ? { location: location2 } : {}
4151
+ });
4152
+ const traceData = getBrowserTrace(test2.id, repeats, retry);
4153
+ if (traceData) {
4154
+ await this.commands.triggerCommand(
4155
+ "__vitest_recordBrowserTrace",
4156
+ [{ testId: test2.id, data: traceData }]
4157
+ );
4158
+ }
4159
+ getBrowserState().browserTraceAttempts.delete(test2.id);
4160
+ }
4161
+ const hasActiveTrace = getBrowserState().activeTraceTaskIds.has(test2.id);
4162
+ if (!hasActiveTrace) {
4163
+ return;
4164
+ }
4165
+ await this.commands.triggerCommand("__vitest_markTrace", [{
4166
+ name: `onAfterRetryTask [${(_d = test2.result) == null ? void 0 : _d.state}]`,
4167
+ stack: (_f = (_e = test2.result) == null ? void 0 : _e.errors) == null ? void 0 : _f[0].stack
4168
+ }]);
4169
+ const name = getTraceName(test2, retry, repeats);
4170
+ if (!this.traces.has(test2.id)) {
4171
+ this.traces.set(test2.id, []);
4172
+ }
4173
+ const traces2 = this.traces.get(test2.id);
4174
+ const { tracePath } = await this.commands.triggerCommand(
4175
+ "__vitest_stopChunkTrace",
4176
+ [{ name }]
4177
+ );
4178
+ traces2.push(tracePath);
4179
+ };
4180
+ onAfterRunTask = async (task) => {
4181
+ var _a, _b, _c;
4182
+ await ((_a = super.onAfterRunTask) == null ? void 0 : _a.call(this, task));
4183
+ const trace = this.config.browser.trace;
4184
+ const traces2 = this.traces.get(task.id) || [];
4185
+ if (traces2.length) {
4186
+ if (trace === "retain-on-failure" && ((_b = task.result) == null ? void 0 : _b.state) === "pass") {
4187
+ await this.commands.triggerCommand(
4188
+ "__vitest_deleteTracing",
4189
+ [{ traces: traces2 }]
4190
+ );
4191
+ } else {
4192
+ await this.commands.triggerCommand(
4193
+ "__vitest_annotateTraces",
4194
+ [{ testId: task.id, traces: traces2 }]
4195
+ );
4196
+ }
4197
+ }
4198
+ if (this.config.bail && ((_c = task.result) == null ? void 0 : _c.state) === "fail") {
4199
+ const previousFailures = await rpc$2().getCountOfFailedTests();
4200
+ const currentFailures = 1 + previousFailures;
4201
+ if (currentFailures >= this.config.bail) {
4202
+ rpc$2().cancelCurrentRun("test-failure");
4203
+ this.cancel("test-failure");
4204
+ }
4205
+ }
4206
+ };
4207
+ onTaskFinished = async (task) => {
4208
+ var _a, _b, _c, _d, _e, _f;
4209
+ const lastErrorContext = (_c = (_b = (_a = task.result) == null ? void 0 : _a.errors) == null ? void 0 : _b.at(-1)) == null ? void 0 : _c.__vitest_error_context__;
4210
+ if (this.config.browser.screenshotFailures && document.body.clientHeight > 0 && ((_d = task.result) == null ? void 0 : _d.state) === "fail" && task.type === "test" && !(lastErrorContext && Reflect.get(lastErrorContext, "assertionName") === "toMatchScreenshot" && ((_e = Reflect.get(lastErrorContext, "meta")) == null ? void 0 : _e.outcome) !== "unstable-screenshot")) {
4211
+ const screenshot = await page.screenshot(
4212
+ {
4213
+ timeout: ((_f = this.config.browser.providerOptions) == null ? void 0 : _f.actionTimeout) ?? 5e3
4214
+ }
4215
+ /** TODO */
4216
+ ).catch((err) => {
4217
+ console.error("[vitest] Failed to take a screenshot", err);
4218
+ });
4219
+ if (screenshot) {
4220
+ await recordArtifact$1(task, {
4221
+ type: "internal:failureScreenshot",
4222
+ attachments: [{ contentType: "image/png", path: screenshot, originalPath: screenshot }]
4223
+ });
4224
+ }
4225
+ }
4226
+ };
4227
+ cancel = (reason) => {
4228
+ var _a;
4229
+ (_a = super.cancel) == null ? void 0 : _a.call(this, reason);
4230
+ globalChannel.postMessage({ type: "cancel", reason });
4231
+ };
4232
+ onBeforeRunSuite = async (suite2) => {
4233
+ var _a;
4234
+ await Promise.all([
4235
+ (_a = super.onBeforeRunSuite) == null ? void 0 : _a.call(this, suite2),
4236
+ (async () => {
4237
+ if (!("filepath" in suite2)) {
4238
+ return;
4239
+ }
4240
+ const map = await rpc$2().getBrowserFileSourceMap(suite2.filepath);
4241
+ this.sourceMapCache.set(suite2.filepath, map);
4242
+ const snapshotEnvironment = this.config.snapshotOptions.snapshotEnvironment;
4243
+ if (snapshotEnvironment instanceof VitestBrowserSnapshotEnvironment) {
4244
+ snapshotEnvironment.addSourceMap(suite2.filepath, map);
4245
+ }
4246
+ })()
4247
+ ]);
4248
+ };
4249
+ onAfterRunFiles = async (files) => {
4250
+ var _a, _b;
4251
+ const [coverage] = await Promise.all([
4252
+ (_a = coverageModule == null ? void 0 : coverageModule.takeCoverage) == null ? void 0 : _a.call(coverageModule),
4253
+ mocker.invalidate(),
4254
+ (_b = super.onAfterRunFiles) == null ? void 0 : _b.call(this, files)
4255
+ ]);
4256
+ if (coverage) {
4257
+ await rpc$2().onAfterSuiteRun({
4258
+ coverage,
4259
+ testFiles: files.map((file) => file.name),
4260
+ environment: "__browser__",
4261
+ projectName: this.config.name
4262
+ });
4263
+ }
4264
+ };
4265
+ onCollectStart = (file) => {
4266
+ return rpc$2().onQueued(this.method, file);
4267
+ };
4268
+ onCollected = async (files) => {
4269
+ files.forEach((file) => {
4270
+ file.prepareDuration = state.durations.prepare;
4271
+ file.environmentLoad = state.durations.environment;
4272
+ state.durations.prepare = 0;
4273
+ state.durations.environment = 0;
4274
+ });
4275
+ if (this.config.includeTaskLocation) {
4276
+ try {
4277
+ await updateTestFilesLocations(files, this.sourceMapCache);
4278
+ } catch {
4279
+ }
4280
+ }
4281
+ return rpc$2().onCollected(this.method, files);
4282
+ };
4283
+ onTestAnnotate = (test2, annotation) => {
4284
+ const artifact = { type: "internal:annotation", annotation, location: annotation.location };
4285
+ return this.onTestArtifactRecord(test2, artifact).then(({ annotation: annotation2 }) => annotation2);
4286
+ };
4287
+ onTestArtifactRecord = (test2, artifact) => {
4288
+ if (artifact.location) {
4289
+ const map = this.sourceMapCache.get(artifact.location.file);
4290
+ if (!map) {
4291
+ return rpc$2().onTaskArtifactRecord(test2.id, artifact);
4292
+ }
4293
+ const traceMap = new DecodedMap$1(map, artifact.location.file);
4294
+ const position = getOriginalPosition$1(traceMap, artifact.location);
4295
+ if (position) {
4296
+ const { source, column, line } = position;
4297
+ const file = source || artifact.location.file;
4298
+ artifact.location = {
4299
+ line,
4300
+ column: column + 1,
4301
+ // if the file path is on windows, we need to remove the starting slash
4302
+ file: file.match(/\/\w:\//) ? file.slice(1) : file
4303
+ };
4304
+ if (artifact.type === "internal:annotation") {
4305
+ artifact.annotation.location = artifact.location;
4306
+ }
4307
+ }
4308
+ }
4309
+ return rpc$2().onTaskArtifactRecord(test2.id, artifact);
4310
+ };
4311
+ onTaskUpdate = (task, events) => {
4312
+ return rpc$2().onTaskUpdate(this.method, task, events);
4313
+ };
4314
+ importFile = async (filepath, mode) => {
4315
+ let hash = this.hashMap.get(filepath);
4316
+ if (mode === "setup" || !hash) {
4317
+ hash = Date.now().toString();
4318
+ this.hashMap.set(filepath, hash);
4319
+ }
4320
+ const prefix = `/${/^\w:/.test(filepath) ? "@fs/" : ""}`;
4321
+ const query = `browserv=${hash}`;
4322
+ const importpath = `${prefix}${filepath}?${query}`.replace(/\/+/g, "/");
4323
+ const trace = this.config.browser.trace;
4324
+ if (mode === "collect" && trace !== "off") {
4325
+ await this.commands.triggerCommand("__vitest_startTracing", []);
4326
+ }
4327
+ try {
4328
+ await import(
4329
+ /* @vite-ignore */
4330
+ importpath
4331
+ );
4332
+ } catch (err) {
4333
+ throw new Error(`Failed to import test file ${filepath}`, { cause: err });
4334
+ }
4335
+ };
4336
+ trace = (name, attributes, cb) => {
4337
+ const options = typeof attributes === "object" ? { attributes } : {};
4338
+ return this._otel.$(`vitest.test.runner.${name}`, options, cb || attributes);
4339
+ };
4340
+ };
4341
+ }
4342
+ let cachedRunner = null;
4343
+ function getBrowserRunner() {
4344
+ return cachedRunner;
4345
+ }
4346
+ async function initiateRunner(state, mocker, config) {
4347
+ if (cachedRunner) {
4348
+ return cachedRunner;
4349
+ }
4350
+ const runnerClass = config.mode === "test" ? TestRunner : BenchmarkRunner;
4351
+ const BrowserRunner = createBrowserRunner(runnerClass, mocker, state, {
4352
+ takeCoverage: () => takeCoverageInsideWorker(config.coverage, moduleRunner)
4353
+ });
4354
+ if (!config.snapshotOptions.snapshotEnvironment) {
4355
+ config.snapshotOptions.snapshotEnvironment = new VitestBrowserSnapshotEnvironment();
4356
+ }
4357
+ const runner2 = new BrowserRunner({
4358
+ config
4359
+ });
4360
+ cachedRunner = runner2;
4361
+ onCancel((reason) => {
4362
+ var _a;
4363
+ (_a = runner2.cancel) == null ? void 0 : _a.call(runner2, reason);
4364
+ });
4365
+ const [diffOptions] = await Promise.all([
4366
+ loadDiffConfig(config, moduleRunner),
4367
+ loadSnapshotSerializers(config, moduleRunner)
4368
+ ]);
4369
+ runner2.config.diffOptions = diffOptions;
4370
+ getWorkerState().onFilterStackTrace = (stack) => {
4371
+ const stacks = parseStacktrace(stack, {
4372
+ getSourceMap(file) {
4373
+ return runner2.sourceMapCache.get(file);
4374
+ }
4375
+ });
4376
+ return createStackString(stacks);
4377
+ };
4378
+ return runner2;
4379
+ }
4380
+ async function getTraceMap(file, sourceMaps) {
4381
+ const result = sourceMaps.get(file) || await rpc$2().getBrowserFileSourceMap(file).then((map) => {
4382
+ sourceMaps.set(file, map);
4383
+ return map;
4384
+ });
4385
+ if (!result) {
4386
+ return null;
4387
+ }
4388
+ return new DecodedMap$1(result, file);
4389
+ }
4390
+ async function updateTestFilesLocations(files, sourceMaps) {
4391
+ const promises2 = files.map(async (file) => {
4392
+ const traceMap = await getTraceMap(file.filepath, sourceMaps);
4393
+ if (!traceMap) {
4394
+ return null;
4395
+ }
4396
+ const updateLocation = (task) => {
4397
+ if (task.location) {
4398
+ const position = getOriginalPosition$1(traceMap, task.location);
4399
+ if (position) {
4400
+ const { line, column } = position;
4401
+ task.location = { line, column: task.each ? column : column + 1 };
4402
+ }
4403
+ }
4404
+ if ("tasks" in task) {
4405
+ task.tasks.forEach(updateLocation);
4406
+ }
4407
+ };
4408
+ file.tasks.forEach(updateLocation);
4409
+ return null;
4410
+ });
4411
+ await Promise.all(promises2);
4412
+ }
4413
+ function getTraceName(task, retryCount, repeatsCount) {
4414
+ const name = getTestName(task, "-").replace(/[^a-z0-9]/gi, "-");
4415
+ return `${name}-${repeatsCount}-${retryCount}`;
4416
+ }
4417
+ const { Date: Date$1, console: console$1, performance: performance$1 } = globalThis;
4418
+ function setupConsoleLogSpy() {
4419
+ const {
4420
+ log,
4421
+ info,
4422
+ error,
4423
+ dir,
4424
+ dirxml,
4425
+ trace,
4426
+ time,
4427
+ timeEnd,
4428
+ timeLog,
4429
+ warn,
4430
+ debug: debug2,
4431
+ count,
4432
+ countReset
4433
+ } = console$1;
4434
+ console$1.log = stdout(log);
4435
+ console$1.debug = stdout(debug2);
4436
+ console$1.info = stdout(info);
4437
+ console$1.error = stderr(error);
4438
+ console$1.warn = stderr(warn);
4439
+ console$1.dir = (item, options) => {
4440
+ dir(item, options);
4441
+ sendLog("stdout", processLog([item]));
4442
+ };
4443
+ console$1.dirxml = (...args) => {
4444
+ dirxml(...args);
4445
+ sendLog("stdout", processLog(args));
4446
+ };
4447
+ console$1.trace = (...args) => {
4448
+ var _a;
4449
+ trace(...args);
4450
+ const content = processLog(args);
4451
+ const error2 = new Error("$$Trace");
4452
+ const processor = ((_a = globalThis.__vitest_worker__) == null ? void 0 : _a.onFilterStackTrace) || ((s) => s || "");
4453
+ const stack = processor(error2.stack || "");
4454
+ sendLog("stderr", `${content}
4455
+ ${stack}`, true);
4456
+ };
4457
+ const timeLabels = {};
4458
+ console$1.time = (label = "default") => {
4459
+ time(label);
4460
+ const now2 = performance$1.now();
4461
+ timeLabels[label] = now2;
4462
+ };
4463
+ console$1.timeLog = (label = "default") => {
4464
+ timeLog(label);
4465
+ if (!(label in timeLabels)) {
4466
+ sendLog("stderr", `Timer "${label}" does not exist`);
4467
+ } else {
4468
+ sendLog("stdout", `${label}: ${timeLabels[label]} ms`);
4469
+ }
4470
+ };
4471
+ console$1.timeEnd = (label = "default") => {
4472
+ timeEnd(label);
4473
+ const end = performance$1.now();
4474
+ const start = timeLabels[label];
4475
+ if (!(label in timeLabels)) {
4476
+ sendLog("stderr", `Timer "${label}" does not exist`);
4477
+ } else if (typeof start !== "undefined") {
4478
+ const duration = end - start;
4479
+ sendLog("stdout", `${label}: ${duration} ms`);
4480
+ }
4481
+ };
4482
+ const countLabels = {};
4483
+ console$1.count = (label = "default") => {
4484
+ count(label);
4485
+ const counter = (countLabels[label] ?? 0) + 1;
4486
+ countLabels[label] = counter;
4487
+ sendLog("stdout", `${label}: ${counter}`);
4488
+ };
4489
+ console$1.countReset = (label = "default") => {
4490
+ countReset(label);
4491
+ countLabels[label] = 0;
4492
+ };
4493
+ }
4494
+ function stdout(base) {
4495
+ return (...args) => {
4496
+ base(...args);
4497
+ if (args[0] === "[WDIO]") {
4498
+ if (args[1] === "newShadowRoot" || args[1] === "removeShadowRoot") {
4499
+ return;
4500
+ }
4501
+ }
4502
+ sendLog("stdout", processLog(args));
4503
+ };
4504
+ }
4505
+ function stderr(base) {
4506
+ return (...args) => {
4507
+ base(...args);
4508
+ sendLog("stderr", processLog(args));
4509
+ };
4510
+ }
4511
+ function processLog(args) {
4512
+ return format$2(args, { multiline: true });
4513
+ }
4514
+ function sendLog(type, content, disableStack) {
4515
+ var _a, _b, _c;
4516
+ if (content.startsWith("[vite]")) {
4517
+ return;
4518
+ }
4519
+ const unknownTestId = "__vitest__unknown_test__";
4520
+ const taskId = ((_b = (_a = globalThis.__vitest_worker__) == null ? void 0 : _a.current) == null ? void 0 : _b.id) ?? unknownTestId;
4521
+ const origin = getConfig$1().printConsoleTrace && !disableStack ? (_c = new Error("STACK_TRACE").stack) == null ? void 0 : _c.split("\n").slice(1).join("\n") : void 0;
4522
+ const runner2 = getBrowserRunner();
4523
+ rpc$2().sendLog((runner2 == null ? void 0 : runner2.method) || "run", {
4524
+ origin,
4525
+ content,
4526
+ browser: true,
4527
+ time: Date$1.now(),
4528
+ taskId,
4529
+ type,
4530
+ size: content.length
4531
+ });
4532
+ }
4533
+ class MockerRegistry {
4534
+ registryByUrl = /* @__PURE__ */ new Map();
4535
+ registryById = /* @__PURE__ */ new Map();
4536
+ clear() {
4537
+ this.registryByUrl.clear();
4538
+ this.registryById.clear();
4539
+ }
4540
+ keys() {
4541
+ return this.registryByUrl.keys();
4542
+ }
4543
+ add(mock) {
4544
+ this.registryByUrl.set(mock.url, mock);
4545
+ this.registryById.set(mock.id, mock);
4546
+ }
4547
+ register(typeOrEvent, raw, id, url2, factoryOrRedirect) {
4548
+ const type = typeof typeOrEvent === "object" ? typeOrEvent.type : typeOrEvent;
4549
+ if (typeof typeOrEvent === "object") {
4550
+ const event = typeOrEvent;
4551
+ if (event instanceof AutomockedModule || event instanceof AutospiedModule || event instanceof ManualMockedModule || event instanceof RedirectedModule) {
4552
+ throw new TypeError(`[vitest] Cannot register a mock that is already defined. Expected a JSON representation from \`MockedModule.toJSON\`, instead got "${event.type}". Use "registry.add()" to update a mock instead.`);
4553
+ }
4554
+ if (event.type === "automock") {
4555
+ const module = AutomockedModule.fromJSON(event);
4556
+ this.add(module);
4557
+ return module;
4558
+ } else if (event.type === "autospy") {
4559
+ const module = AutospiedModule.fromJSON(event);
4560
+ this.add(module);
4561
+ return module;
4562
+ } else if (event.type === "redirect") {
4563
+ const module = RedirectedModule.fromJSON(event);
4564
+ this.add(module);
4565
+ return module;
4566
+ } else if (event.type === "manual") {
4567
+ throw new Error(`Cannot set serialized manual mock. Define a factory function manually with \`ManualMockedModule.fromJSON()\`.`);
4568
+ } else {
4569
+ throw new Error(`Unknown mock type: ${event.type}`);
4570
+ }
4571
+ }
4572
+ if (typeof raw !== "string") {
4573
+ throw new TypeError("[vitest] Mocks require a raw string.");
4574
+ }
4575
+ if (typeof url2 !== "string") {
4576
+ throw new TypeError("[vitest] Mocks require a url string.");
4577
+ }
4578
+ if (typeof id !== "string") {
4579
+ throw new TypeError("[vitest] Mocks require an id string.");
4580
+ }
4581
+ if (type === "manual") {
4582
+ if (typeof factoryOrRedirect !== "function") {
4583
+ throw new TypeError("[vitest] Manual mocks require a factory function.");
4584
+ }
4585
+ const mock = new ManualMockedModule(raw, id, url2, factoryOrRedirect);
4586
+ this.add(mock);
4587
+ return mock;
4588
+ } else if (type === "automock" || type === "autospy") {
4589
+ const mock = type === "automock" ? new AutomockedModule(raw, id, url2) : new AutospiedModule(raw, id, url2);
4590
+ this.add(mock);
4591
+ return mock;
4592
+ } else if (type === "redirect") {
4593
+ if (typeof factoryOrRedirect !== "string") {
4594
+ throw new TypeError("[vitest] Redirect mocks require a redirect string.");
4595
+ }
4596
+ const mock = new RedirectedModule(raw, id, url2, factoryOrRedirect);
4597
+ this.add(mock);
4598
+ return mock;
4599
+ } else {
4600
+ throw new Error(`[vitest] Unknown mock type: ${type}`);
4601
+ }
4602
+ }
4603
+ delete(id) {
4604
+ this.registryByUrl.delete(id);
4605
+ }
4606
+ deleteById(id) {
4607
+ this.registryById.delete(id);
4608
+ }
4609
+ get(id) {
4610
+ return this.registryByUrl.get(id);
4611
+ }
4612
+ getById(id) {
4613
+ return this.registryById.get(id);
4614
+ }
4615
+ has(id) {
4616
+ return this.registryByUrl.has(id);
4617
+ }
4618
+ }
4619
+ class AutomockedModule {
4620
+ type = "automock";
4621
+ constructor(raw, id, url2) {
4622
+ this.raw = raw;
4623
+ this.id = id;
4624
+ this.url = url2;
4625
+ }
4626
+ static fromJSON(data) {
4627
+ return new AutomockedModule(data.raw, data.id, data.url);
4628
+ }
4629
+ toJSON() {
4630
+ return {
4631
+ type: this.type,
4632
+ url: this.url,
4633
+ raw: this.raw,
4634
+ id: this.id
4635
+ };
4636
+ }
4637
+ }
4638
+ class AutospiedModule {
4639
+ type = "autospy";
4640
+ constructor(raw, id, url2) {
4641
+ this.raw = raw;
4642
+ this.id = id;
4643
+ this.url = url2;
4644
+ }
4645
+ static fromJSON(data) {
4646
+ return new AutospiedModule(data.raw, data.id, data.url);
4647
+ }
4648
+ toJSON() {
4649
+ return {
4650
+ type: this.type,
4651
+ url: this.url,
4652
+ id: this.id,
4653
+ raw: this.raw
4654
+ };
4655
+ }
4656
+ }
4657
+ class RedirectedModule {
4658
+ type = "redirect";
4659
+ constructor(raw, id, url2, redirect) {
4660
+ this.raw = raw;
4661
+ this.id = id;
4662
+ this.url = url2;
4663
+ this.redirect = redirect;
4664
+ }
4665
+ static fromJSON(data) {
4666
+ return new RedirectedModule(data.raw, data.id, data.url, data.redirect);
4667
+ }
4668
+ toJSON() {
4669
+ return {
4670
+ type: this.type,
4671
+ url: this.url,
4672
+ raw: this.raw,
4673
+ id: this.id,
4674
+ redirect: this.redirect
4675
+ };
4676
+ }
4677
+ }
4678
+ class ManualMockedModule {
4679
+ cache;
4680
+ type = "manual";
4681
+ constructor(raw, id, url2, factory) {
4682
+ this.raw = raw;
4683
+ this.id = id;
4684
+ this.url = url2;
4685
+ this.factory = factory;
4686
+ }
4687
+ resolve() {
4688
+ if (this.cache) {
4689
+ return this.cache;
4690
+ }
4691
+ let exports$1;
4692
+ try {
4693
+ exports$1 = this.factory();
4694
+ } catch (err) {
4695
+ throw createHelpfulError(err);
4696
+ }
4697
+ if (typeof exports$1 === "object" && typeof (exports$1 == null ? void 0 : exports$1.then) === "function") {
4698
+ return exports$1.then((result) => {
4699
+ assertValidExports(this.raw, result);
4700
+ return this.cache = result;
4701
+ }, (error) => {
4702
+ throw createHelpfulError(error);
4703
+ });
4704
+ }
4705
+ assertValidExports(this.raw, exports$1);
4706
+ return this.cache = exports$1;
4707
+ }
4708
+ static fromJSON(data, factory) {
4709
+ return new ManualMockedModule(data.raw, data.id, data.url, factory);
4710
+ }
4711
+ toJSON() {
4712
+ return {
4713
+ type: this.type,
4714
+ url: this.url,
4715
+ id: this.id,
4716
+ raw: this.raw
4717
+ };
4718
+ }
4719
+ }
4720
+ function createHelpfulError(cause) {
4721
+ const error = new Error('[vitest] There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/vi.html#vi-mock');
4722
+ error.cause = cause;
4723
+ return error;
4724
+ }
4725
+ function assertValidExports(raw, exports$1) {
4726
+ if (exports$1 === null || typeof exports$1 !== "object" || Array.isArray(exports$1)) {
4727
+ throw new TypeError(`[vitest] vi.mock("${raw}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`);
4728
+ }
4729
+ }
4730
+ function mockObject(options, object2, mockExports = {}) {
4731
+ const finalizers = new Array();
4732
+ const refs = new RefTracker();
4733
+ const define = (container, key, value) => {
4734
+ try {
4735
+ container[key] = value;
4736
+ return true;
4737
+ } catch {
4738
+ return false;
4739
+ }
4740
+ };
4741
+ const createMock = (currentValue) => {
4742
+ if (!options.createMockInstance) {
4743
+ throw new Error("[@vitest/mocker] `createMockInstance` is not defined. This is a Vitest error. Please open a new issue with reproduction.");
4744
+ }
4745
+ const createMockInstance = options.createMockInstance;
4746
+ const prototypeMembers = currentValue.prototype ? collectFunctionProperties(currentValue.prototype) : [];
4747
+ return createMockInstance({
4748
+ name: currentValue.name,
4749
+ prototypeMembers,
4750
+ originalImplementation: options.type === "autospy" ? currentValue : void 0,
4751
+ keepMembersImplementation: options.type === "autospy"
4752
+ });
4753
+ };
4754
+ const mockPropertiesOf = (container, newContainer) => {
4755
+ const containerType = getType(container);
4756
+ const isModule = containerType === "Module" || !!container.__esModule;
4757
+ for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, options.globalConstructors)) {
4758
+ if (!isModule && descriptor.get) {
4759
+ try {
4760
+ if (options.type === "autospy") {
4761
+ Object.defineProperty(newContainer, property, descriptor);
4762
+ } else {
4763
+ Object.defineProperty(newContainer, property, {
4764
+ configurable: descriptor.configurable,
4765
+ enumerable: descriptor.enumerable,
4766
+ get: () => {
4767
+ },
4768
+ set: descriptor.set ? () => {
4769
+ } : void 0
4770
+ });
4771
+ }
4772
+ } catch {
4773
+ }
4774
+ continue;
4775
+ }
4776
+ if (isReadonlyProp(container[property], property)) {
4777
+ continue;
4778
+ }
4779
+ const value = container[property];
4780
+ const refId = refs.getId(value);
4781
+ if (refId !== void 0) {
4782
+ finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId)));
4783
+ continue;
4784
+ }
4785
+ const type = getType(value);
4786
+ if (Array.isArray(value)) {
4787
+ if (options.type === "automock") {
4788
+ define(newContainer, property, []);
4789
+ } else {
4790
+ const array = value.map((value2) => {
4791
+ if (value2 && typeof value2 === "object") {
4792
+ const newObject = {};
4793
+ mockPropertiesOf(value2, newObject);
4794
+ return newObject;
4795
+ }
4796
+ if (typeof value2 === "function") {
4797
+ return createMock(value2);
4798
+ }
4799
+ return value2;
4800
+ });
4801
+ define(newContainer, property, array);
4802
+ }
4803
+ continue;
4804
+ }
4805
+ const isFunction = type.includes("Function") && typeof value === "function";
4806
+ if ((!isFunction || value._isMockFunction) && type !== "Object" && type !== "Module") {
4807
+ define(newContainer, property, value);
4808
+ continue;
4809
+ }
4810
+ if (options.type === "autospy" && type === "Module") {
4811
+ const exports$1 = /* @__PURE__ */ Object.create(null);
4812
+ Object.defineProperty(exports$1, Symbol.toStringTag, {
4813
+ value: "Module",
4814
+ configurable: true,
4815
+ writable: true
4816
+ });
4817
+ try {
4818
+ newContainer[property] = exports$1;
4819
+ } catch {
4820
+ continue;
4821
+ }
4822
+ } else if (!define(newContainer, property, isFunction || options.type === "autospy" ? value : {})) {
4823
+ continue;
4824
+ }
4825
+ if (isFunction) {
4826
+ const mock = createMock(newContainer[property]);
4827
+ newContainer[property] = mock;
4828
+ }
4829
+ refs.track(value, newContainer[property]);
4830
+ mockPropertiesOf(value, newContainer[property]);
4831
+ }
4832
+ };
4833
+ const mockedObject = mockExports;
4834
+ mockPropertiesOf(object2, mockedObject);
4835
+ for (const finalizer of finalizers) {
4836
+ finalizer();
4837
+ }
4838
+ return mockedObject;
4839
+ }
4840
+ class RefTracker {
4841
+ idMap = /* @__PURE__ */ new Map();
4842
+ mockedValueMap = /* @__PURE__ */ new Map();
4843
+ getId(value) {
4844
+ return this.idMap.get(value);
4845
+ }
4846
+ getMockedValue(id) {
4847
+ return this.mockedValueMap.get(id);
4848
+ }
4849
+ track(originalValue, mockedValue) {
4850
+ const newId = this.idMap.size;
4851
+ this.idMap.set(originalValue, newId);
4852
+ this.mockedValueMap.set(newId, mockedValue);
4853
+ return newId;
4854
+ }
4855
+ }
4856
+ function getType(value) {
4857
+ return Object.prototype.toString.apply(value).slice(8, -1);
4858
+ }
4859
+ function isReadonlyProp(object2, prop) {
4860
+ if (prop === "arguments" || prop === "caller" || prop === "callee" || prop === "name" || prop === "length") {
4861
+ const typeName = getType(object2);
4862
+ return typeName === "Function" || typeName === "AsyncFunction" || typeName === "GeneratorFunction" || typeName === "AsyncGeneratorFunction";
4863
+ }
4864
+ if (prop === "source" || prop === "global" || prop === "ignoreCase" || prop === "multiline") {
4865
+ return getType(object2) === "RegExp";
4866
+ }
4867
+ return false;
4868
+ }
4869
+ function getAllMockableProperties(obj, isModule, constructors) {
4870
+ const { Map: Map2, Object: Object2, Function: Function2, RegExp: RegExp2, Array: Array2 } = constructors;
4871
+ const allProps = new Map2();
4872
+ let curr = obj;
4873
+ do {
4874
+ if (curr === Object2.prototype || curr === Function2.prototype || curr === RegExp2.prototype) {
4875
+ break;
4876
+ }
4877
+ collectOwnProperties(curr, (key) => {
4878
+ const descriptor = Object2.getOwnPropertyDescriptor(curr, key);
4879
+ if (descriptor) {
4880
+ allProps.set(key, {
4881
+ key,
4882
+ descriptor
4883
+ });
4884
+ }
4885
+ });
4886
+ } while (curr = Object2.getPrototypeOf(curr));
4887
+ if (isModule && !allProps.has("default") && "default" in obj) {
4888
+ const descriptor = Object2.getOwnPropertyDescriptor(obj, "default");
4889
+ if (descriptor) {
4890
+ allProps.set("default", {
4891
+ key: "default",
4892
+ descriptor
4893
+ });
4894
+ }
4895
+ }
4896
+ return Array2.from(allProps.values());
4897
+ }
4898
+ function collectOwnProperties(obj, collector) {
4899
+ const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
4900
+ Object.getOwnPropertyNames(obj).forEach(collect);
4901
+ Object.getOwnPropertySymbols(obj).forEach(collect);
4902
+ }
4903
+ function collectFunctionProperties(prototype) {
4904
+ const properties = /* @__PURE__ */ new Set();
4905
+ collectOwnProperties(prototype, (prop) => {
4906
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, prop);
4907
+ if (!descriptor || descriptor.get) {
4908
+ return;
4909
+ }
4910
+ const type = getType(descriptor.value);
4911
+ if (type.includes("Function") && !isReadonlyProp(descriptor.value, prop)) {
4912
+ properties.add(prop);
4913
+ }
4914
+ });
4915
+ return Array.from(properties);
4916
+ }
4917
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
4918
+ function normalizeWindowsPath(input = "") {
4919
+ if (!input) {
4920
+ return input;
4921
+ }
4922
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
4923
+ }
4924
+ const _UNC_REGEX = /^[/\\]{2}/;
4925
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
4926
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
4927
+ const _EXTNAME_RE = /.(\.[^./]+|\.)$/;
4928
+ const normalize = function(path) {
4929
+ if (path.length === 0) {
4930
+ return ".";
4931
+ }
4932
+ path = normalizeWindowsPath(path);
4933
+ const isUNCPath = path.match(_UNC_REGEX);
4934
+ const isPathAbsolute = isAbsolute(path);
4935
+ const trailingSeparator = path[path.length - 1] === "/";
4936
+ path = normalizeString(path, !isPathAbsolute);
4937
+ if (path.length === 0) {
4938
+ if (isPathAbsolute) {
4939
+ return "/";
4940
+ }
4941
+ return trailingSeparator ? "./" : ".";
4942
+ }
4943
+ if (trailingSeparator) {
4944
+ path += "/";
4945
+ }
4946
+ if (_DRIVE_LETTER_RE.test(path)) {
4947
+ path += "/";
4948
+ }
4949
+ if (isUNCPath) {
4950
+ if (!isPathAbsolute) {
4951
+ return `//./${path}`;
4952
+ }
4953
+ return `//${path}`;
4954
+ }
4955
+ return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
4956
+ };
4957
+ const join = function(...segments) {
4958
+ let path = "";
4959
+ for (const seg of segments) {
4960
+ if (!seg) {
4961
+ continue;
4962
+ }
4963
+ if (path.length > 0) {
4964
+ const pathTrailing = path[path.length - 1] === "/";
4965
+ const segLeading = seg[0] === "/";
4966
+ const both = pathTrailing && segLeading;
4967
+ if (both) {
4968
+ path += seg.slice(1);
4969
+ } else {
4970
+ path += pathTrailing || segLeading ? seg : `/${seg}`;
4971
+ }
4972
+ } else {
4973
+ path += seg;
4974
+ }
4975
+ }
4976
+ return normalize(path);
4977
+ };
4978
+ function normalizeString(path, allowAboveRoot) {
4979
+ let res = "";
4980
+ let lastSegmentLength = 0;
4981
+ let lastSlash = -1;
4982
+ let dots = 0;
4983
+ let char = null;
4984
+ for (let index2 = 0; index2 <= path.length; ++index2) {
4985
+ if (index2 < path.length) {
4986
+ char = path[index2];
4987
+ } else if (char === "/") {
4988
+ break;
4989
+ } else {
4990
+ char = "/";
4991
+ }
4992
+ if (char === "/") {
4993
+ if (lastSlash === index2 - 1 || dots === 1) ;
4994
+ else if (dots === 2) {
4995
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
4996
+ if (res.length > 2) {
4997
+ const lastSlashIndex = res.lastIndexOf("/");
4998
+ if (lastSlashIndex === -1) {
4999
+ res = "";
5000
+ lastSegmentLength = 0;
5001
+ } else {
5002
+ res = res.slice(0, lastSlashIndex);
5003
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
5004
+ }
5005
+ lastSlash = index2;
5006
+ dots = 0;
5007
+ continue;
5008
+ } else if (res.length > 0) {
5009
+ res = "";
5010
+ lastSegmentLength = 0;
5011
+ lastSlash = index2;
5012
+ dots = 0;
5013
+ continue;
5014
+ }
5015
+ }
5016
+ if (allowAboveRoot) {
5017
+ res += res.length > 0 ? "/.." : "..";
5018
+ lastSegmentLength = 2;
5019
+ }
5020
+ } else {
5021
+ if (res.length > 0) {
5022
+ res += `/${path.slice(lastSlash + 1, index2)}`;
5023
+ } else {
5024
+ res = path.slice(lastSlash + 1, index2);
5025
+ }
5026
+ lastSegmentLength = index2 - lastSlash - 1;
5027
+ }
5028
+ lastSlash = index2;
5029
+ dots = 0;
5030
+ } else if (char === "." && dots !== -1) {
5031
+ ++dots;
5032
+ } else {
5033
+ dots = -1;
5034
+ }
5035
+ }
5036
+ return res;
5037
+ }
5038
+ const isAbsolute = function(p) {
5039
+ return _IS_ABSOLUTE_RE.test(p);
5040
+ };
5041
+ const extname = function(p) {
5042
+ if (p === "..") return "";
5043
+ const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
5044
+ return match && match[1] || "";
5045
+ };
5046
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
5047
+ var intToChar = new Uint8Array(64);
5048
+ var charToInt = new Uint8Array(128);
5049
+ for (let i2 = 0; i2 < chars.length; i2++) {
5050
+ const c = chars.charCodeAt(i2);
5051
+ intToChar[i2] = c;
5052
+ charToInt[c] = i2;
5053
+ }
5054
+ Date.now().toString().length;
5055
+ const { now } = Date;
5056
+ class ModuleMocker {
5057
+ registry = new MockerRegistry();
5058
+ queue = /* @__PURE__ */ new Set();
5059
+ mockedIds = /* @__PURE__ */ new Set();
5060
+ constructor(interceptor, rpc2, createMockInstance, config) {
5061
+ this.interceptor = interceptor;
5062
+ this.rpc = rpc2;
5063
+ this.createMockInstance = createMockInstance;
5064
+ this.config = config;
5065
+ }
5066
+ async prepare() {
5067
+ if (!this.queue.size) {
5068
+ return;
5069
+ }
5070
+ await Promise.all([...this.queue.values()]);
5071
+ }
5072
+ async resolveFactoryModule(id) {
5073
+ const mock = this.registry.get(id);
5074
+ if (!mock || mock.type !== "manual") {
5075
+ throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`);
5076
+ }
5077
+ const result = await mock.resolve();
5078
+ return result;
5079
+ }
5080
+ getFactoryModule(id) {
5081
+ const mock = this.registry.get(id);
5082
+ if (!mock || mock.type !== "manual") {
5083
+ throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`);
5084
+ }
5085
+ if (!mock.cache) {
5086
+ throw new Error(`Mock ${id} wasn't resolved. This is probably a Vitest error. Please, open a new issue with reproduction.`);
5087
+ }
5088
+ return mock.cache;
5089
+ }
5090
+ async invalidate() {
5091
+ const ids = Array.from(this.mockedIds);
5092
+ if (!ids.length) {
5093
+ return;
5094
+ }
5095
+ await this.rpc.invalidate(ids);
5096
+ await this.interceptor.invalidate();
5097
+ this.registry.clear();
5098
+ }
5099
+ async importActual(id, importer) {
5100
+ const resolved = await this.rpc.resolveId(id, importer);
5101
+ if (resolved == null) {
5102
+ throw new Error(`[vitest] Cannot resolve "${id}" imported from "${importer}"`);
5103
+ }
5104
+ const ext = extname(resolved.id);
5105
+ const url2 = new URL(resolved.url, this.getBaseUrl());
5106
+ const query = `_vitest_original&ext${ext}`;
5107
+ const actualUrl = `${url2.pathname}${url2.search ? `${url2.search}&${query}` : `?${query}`}${url2.hash}`;
5108
+ return this.wrapDynamicImport(() => import(
5109
+ /* @vite-ignore */
5110
+ actualUrl
5111
+ )).then((mod) => {
5112
+ if (!resolved.optimized || typeof mod.default === "undefined") {
5113
+ return mod;
5114
+ }
5115
+ const m = mod.default;
5116
+ return (m == null ? void 0 : m.__esModule) ? m : {
5117
+ ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {},
5118
+ default: m
5119
+ };
5120
+ });
5121
+ }
5122
+ getBaseUrl() {
5123
+ return location.href;
5124
+ }
5125
+ async importMock(rawId, importer) {
5126
+ await this.prepare();
5127
+ const { resolvedId, resolvedUrl, redirectUrl } = await this.rpc.resolveMock(rawId, importer, { mock: "auto" });
5128
+ const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl));
5129
+ let mock = this.registry.get(mockUrl);
5130
+ if (!mock) {
5131
+ if (redirectUrl) {
5132
+ const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), this.getBaseUrl()).toString();
5133
+ mock = new RedirectedModule(rawId, resolvedId, mockUrl, resolvedRedirect);
5134
+ } else {
5135
+ mock = new AutomockedModule(rawId, resolvedId, mockUrl);
5136
+ }
5137
+ }
5138
+ if (mock.type === "manual") {
5139
+ return await mock.resolve();
5140
+ }
5141
+ if (mock.type === "automock" || mock.type === "autospy") {
5142
+ const url2 = new URL(`/@id/${resolvedId}`, this.getBaseUrl());
5143
+ const query = url2.search ? `${url2.search}&t=${now()}` : `?t=${now()}`;
5144
+ const moduleObject = await __vitePreload(() => import(
5145
+ /* @vite-ignore */
5146
+ `${url2.pathname}${query}&mock=${mock.type}${url2.hash}`
5147
+ ), true ? [] : void 0);
5148
+ return this.mockObject(moduleObject, mock.type);
5149
+ }
5150
+ return import(
5151
+ /* @vite-ignore */
5152
+ mock.redirect
5153
+ );
5154
+ }
5155
+ mockObject(object2, mockExportsOrModuleType, moduleType) {
5156
+ let mockExports;
5157
+ if (mockExportsOrModuleType === "automock" || mockExportsOrModuleType === "autospy") {
5158
+ moduleType = mockExportsOrModuleType;
5159
+ mockExports = void 0;
5160
+ } else {
5161
+ mockExports = mockExportsOrModuleType;
5162
+ }
5163
+ moduleType ?? (moduleType = "automock");
5164
+ const result = mockObject({
5165
+ globalConstructors: {
5166
+ Object,
5167
+ Function,
5168
+ Array,
5169
+ Map,
5170
+ RegExp
5171
+ },
5172
+ createMockInstance: this.createMockInstance,
5173
+ type: moduleType
5174
+ }, object2, mockExports);
5175
+ return result;
5176
+ }
5177
+ getMockContext() {
5178
+ return { callstack: null };
5179
+ }
5180
+ queueMock(rawId, importer, factoryOrOptions) {
5181
+ const promise = this.rpc.resolveMock(rawId, importer, { mock: typeof factoryOrOptions === "function" ? "factory" : (factoryOrOptions == null ? void 0 : factoryOrOptions.spy) ? "spy" : "auto" }).then(async ({ redirectUrl, resolvedId, resolvedUrl, needsInterop, mockType }) => {
5182
+ const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl));
5183
+ this.mockedIds.add(resolvedId);
5184
+ const factory = typeof factoryOrOptions === "function" ? async () => {
5185
+ const data = await factoryOrOptions();
5186
+ return needsInterop ? { default: data } : data;
5187
+ } : void 0;
5188
+ const mockRedirect = typeof redirectUrl === "string" ? new URL(this.resolveMockPath(cleanVersion(redirectUrl)), this.getBaseUrl()).toString() : null;
5189
+ let module;
5190
+ if (mockType === "manual") {
5191
+ module = this.registry.register("manual", rawId, resolvedId, mockUrl, factory);
5192
+ } else if (mockType === "autospy") {
5193
+ module = this.registry.register("autospy", rawId, resolvedId, mockUrl);
5194
+ } else if (mockType === "redirect") {
5195
+ module = this.registry.register("redirect", rawId, resolvedId, mockUrl, mockRedirect);
5196
+ } else {
5197
+ module = this.registry.register("automock", rawId, resolvedId, mockUrl);
5198
+ }
5199
+ await this.interceptor.register(module);
5200
+ }).finally(() => {
5201
+ this.queue.delete(promise);
5202
+ });
5203
+ this.queue.add(promise);
5204
+ }
5205
+ queueUnmock(id, importer) {
5206
+ const promise = this.rpc.resolveId(id, importer).then(async (resolved) => {
5207
+ if (!resolved) {
5208
+ return;
5209
+ }
5210
+ const mockUrl = this.resolveMockPath(cleanVersion(resolved.url));
5211
+ this.mockedIds.add(resolved.id);
5212
+ this.registry.delete(mockUrl);
5213
+ await this.interceptor.delete(mockUrl);
5214
+ }).finally(() => {
5215
+ this.queue.delete(promise);
5216
+ });
5217
+ this.queue.add(promise);
5218
+ }
5219
+ // We need to await mock registration before importing the actual module
5220
+ // In case there is a mocked module in the import chain
5221
+ wrapDynamicImport(moduleFactory) {
5222
+ if (typeof moduleFactory === "function") {
5223
+ const promise = new Promise((resolve2, reject) => {
5224
+ this.prepare().finally(() => {
5225
+ moduleFactory().then(resolve2, reject);
5226
+ });
5227
+ });
5228
+ return promise;
5229
+ }
5230
+ return moduleFactory;
5231
+ }
5232
+ getMockedModuleById(id) {
5233
+ return this.registry.getById(id);
5234
+ }
5235
+ reset() {
5236
+ this.registry.clear();
5237
+ this.mockedIds.clear();
5238
+ this.queue.clear();
5239
+ }
5240
+ resolveMockPath(path) {
5241
+ const config = this.config;
5242
+ const fsRoot = join("/@fs/", config.root);
5243
+ if (path.startsWith(config.root)) {
5244
+ return path.slice(config.root.length);
5245
+ }
5246
+ if (path.startsWith(fsRoot)) {
5247
+ return path.slice(fsRoot.length);
5248
+ }
5249
+ return path;
5250
+ }
5251
+ }
5252
+ const versionRegexp = /(\?|&)v=\w{8}/;
5253
+ function cleanVersion(url2) {
5254
+ return url2.replace(versionRegexp, "");
5255
+ }
5256
+ class VitestBrowserClientMocker extends ModuleMocker {
5257
+ // default "vi" utility tries to access mock context to avoid circular dependencies
5258
+ getMockContext() {
5259
+ return { callstack: null };
5260
+ }
5261
+ wrapDynamicImport(moduleFactory) {
5262
+ return getBrowserState().wrapModule(moduleFactory);
5263
+ }
5264
+ }
5265
+ function createModuleMockerInterceptor() {
5266
+ return {
5267
+ async register(module) {
5268
+ const state = getBrowserState();
5269
+ await rpc().registerMock(state.sessionId, module.toJSON());
5270
+ },
5271
+ async delete(id) {
5272
+ const state = getBrowserState();
5273
+ await rpc().unregisterMock(state.sessionId, id);
5274
+ },
5275
+ async invalidate() {
5276
+ const state = getBrowserState();
5277
+ await rpc().clearMocks(state.sessionId);
5278
+ }
5279
+ };
5280
+ }
5281
+ function rpc() {
5282
+ return getWorkerState().rpc;
5283
+ }
5284
+ const ACTION_TRACE_COMMANDS = /* @__PURE__ */ new Set([
5285
+ "__vitest_click",
5286
+ "__vitest_dblClick",
5287
+ "__vitest_tripleClick",
5288
+ "__vitest_wheel",
5289
+ "__vitest_type",
5290
+ "__vitest_clear",
5291
+ "__vitest_fill",
5292
+ "__vitest_selectOptions",
5293
+ "__vitest_dragAndDrop",
5294
+ "__vitest_hover",
5295
+ "__vitest_upload",
5296
+ "__vitest_tab",
5297
+ "__vitest_keyboard",
5298
+ "__vitest_takeScreenshot"
5299
+ ]);
5300
+ class CommandsManager {
5301
+ _listeners = [];
5302
+ onCommand(listener) {
5303
+ this._listeners.push(listener);
5304
+ }
5305
+ async triggerCommand(command, args, clientError = new Error("empty")) {
5306
+ var _a, _b;
5307
+ const state = getWorkerState();
5308
+ const rpc2 = state.rpc;
5309
+ const { sessionId, traces: traces2 } = getBrowserState();
5310
+ const filepath = state.filepath || ((_b = (_a = state.current) == null ? void 0 : _a.file) == null ? void 0 : _b.filepath);
5311
+ args = args.filter((arg) => arg !== void 0);
5312
+ const actionTraceGroupName = ACTION_TRACE_COMMANDS.has(command) ? `vitest:${command.slice("__vitest_".length)}` : void 0;
5313
+ const currentTest = getWorkerState().current;
5314
+ const hasActiveTrace = !!actionTraceGroupName && !!currentTest && getBrowserState().activeTraceTaskIds.has(currentTest.id);
5315
+ const hasActiveTraceView = !!actionTraceGroupName && !!currentTest && getBrowserState().browserTraceAttempts.has(currentTest.id);
5316
+ if (this._listeners.length) {
5317
+ await Promise.all(this._listeners.map((listener) => listener(command, args)));
5318
+ }
5319
+ return traces2.$(
5320
+ "vitest.browser.tester.command",
5321
+ {
5322
+ attributes: {
5323
+ "vitest.browser.command": command,
5324
+ "code.file.path": filepath
5325
+ }
5326
+ },
5327
+ async () => {
5328
+ var _a2;
5329
+ if (hasActiveTrace) {
5330
+ await rpc2.triggerCommand(
5331
+ sessionId,
5332
+ "__vitest_groupTraceStart",
5333
+ filepath,
5334
+ [{
5335
+ name: actionTraceGroupName,
5336
+ stack: clientError.stack
5337
+ }]
5338
+ );
5339
+ }
5340
+ let status = "pass";
5341
+ const startTime = now$1();
5342
+ try {
5343
+ return await rpc2.triggerCommand(sessionId, command, filepath, args);
5344
+ } catch (err) {
5345
+ status = "fail";
5346
+ clientError.message = err.message;
5347
+ clientError.name = err.name;
5348
+ clientError.stack = (_a2 = clientError.stack) == null ? void 0 : _a2.replace(clientError.message, err.message);
5349
+ throw clientError;
5350
+ } finally {
5351
+ if (hasActiveTraceView) {
5352
+ recordBrowserTraceEntry(currentTest, {
5353
+ name: actionTraceGroupName,
5354
+ kind: "action",
5355
+ status,
5356
+ startTime,
5357
+ duration: now$1() - startTime,
5358
+ element: typeof args[0] === "object" && "selector" in args[0] && "locator" in args[0] ? args[0] : void 0,
5359
+ stack: clientError.stack
5360
+ });
5361
+ }
5362
+ if (hasActiveTrace) {
5363
+ await rpc2.triggerCommand(
5364
+ sessionId,
5365
+ "__vitest_groupTraceEnd",
5366
+ filepath,
5367
+ []
5368
+ );
5369
+ }
5370
+ }
5371
+ }
5372
+ );
5373
+ }
5374
+ }
5375
+ getBrowserState().provider;
5376
+ const debugVar = getConfig$1().env.VITEST_BROWSER_DEBUG;
5377
+ const debug = debugVar && debugVar !== "false" ? (...args) => {
5378
+ var _a, _b;
5379
+ return (_b = (_a = client.rpc).debug) == null ? void 0 : _b.call(_a, ...args.map(String));
5380
+ } : void 0;
5381
+ const otelConfig = getConfig$1().experimental.openTelemetry;
5382
+ const traces = new Traces({
5383
+ enabled: !!((otelConfig == null ? void 0 : otelConfig.enabled) && (otelConfig == null ? void 0 : otelConfig.browserSdkPath)),
5384
+ sdkPath: `/@fs/${otelConfig == null ? void 0 : otelConfig.browserSdkPath}`
5385
+ });
5386
+ let rootTesterSpan;
5387
+ getBrowserState().traces = traces;
5388
+ channel.addEventListener("message", async (e) => {
5389
+ await client.waitForConnection();
5390
+ const data = e.data;
5391
+ debug == null ? void 0 : debug("event from orchestrator", JSON.stringify(e.data));
5392
+ if (!isEvent(data)) {
5393
+ const error = new Error(`Unknown message: ${JSON.stringify(e.data)}`);
5394
+ unhandledError(error, "Unknown Iframe Message");
5395
+ return;
5396
+ }
5397
+ if (!("iframeId" in data) || data.iframeId !== getBrowserState().iframeId) {
5398
+ return;
5399
+ }
5400
+ switch (data.event) {
5401
+ case "execute": {
5402
+ const { method, files, context } = data;
5403
+ const state = getWorkerState();
5404
+ const parsedContext = parse(context);
5405
+ state.ctx.providedContext = parsedContext;
5406
+ state.providedContext = parsedContext;
5407
+ if (method === "collect") {
5408
+ await executeTests("collect", files).catch((err) => unhandledError(err, "Collect Error"));
5409
+ } else {
5410
+ await executeTests("run", files).catch((err) => unhandledError(err, "Run Error"));
5411
+ }
5412
+ break;
5413
+ }
5414
+ case "cleanup": {
5415
+ await cleanup().catch((err) => unhandledError(err, "Cleanup Error"));
5416
+ rootTesterSpan == null ? void 0 : rootTesterSpan.span.end();
5417
+ await traces.finish();
5418
+ break;
5419
+ }
5420
+ case "prepare": {
5421
+ await traces.waitInit();
5422
+ const tracesContext = traces.getContextFromCarrier(data.otelCarrier);
5423
+ traces.recordInitSpan(tracesContext);
5424
+ rootTesterSpan = traces.startContextSpan(
5425
+ `vitest.browser.tester.run`,
5426
+ tracesContext
5427
+ );
5428
+ traces.bind(rootTesterSpan.context);
5429
+ await prepare(data).catch((err) => unhandledError(err, "Prepare Error"));
5430
+ break;
5431
+ }
5432
+ case "viewport:done":
5433
+ case "viewport:fail":
5434
+ case "viewport": {
5435
+ break;
5436
+ }
5437
+ default: {
5438
+ const error = new Error(`Unknown event: ${data.event}`);
5439
+ unhandledError(error, "Unknown Event");
5440
+ }
5441
+ }
5442
+ channel.postMessage({
5443
+ event: `response:${data.event}`,
5444
+ iframeId: getBrowserState().iframeId
5445
+ });
5446
+ });
5447
+ const url = new URL(location.href);
5448
+ const iframeId = url.searchParams.get("iframeId");
5449
+ const commands = new CommandsManager();
5450
+ getBrowserState().commands = commands;
5451
+ getBrowserState().activeTraceTaskIds = /* @__PURE__ */ new Set();
5452
+ getBrowserState().browserTraceAttempts = /* @__PURE__ */ new Map();
5453
+ getBrowserState().iframeId = iframeId;
5454
+ let contextSwitched = false;
5455
+ async function prepareTestEnvironment(options) {
5456
+ debug == null ? void 0 : debug("trying to resolve the runner");
5457
+ const config = getConfig$1();
5458
+ const rpc2 = createSafeRpc(client);
5459
+ const state = getWorkerState();
5460
+ state.metaEnv = __vitest_browser_import_meta_env_init__;
5461
+ state.onCancel = onCancel;
5462
+ state.ctx.rpc = rpc2;
5463
+ state.rpc = rpc2;
5464
+ const interceptor = createModuleMockerInterceptor();
5465
+ const mocker = new VitestBrowserClientMocker(
5466
+ interceptor,
5467
+ rpc2,
5468
+ SpyModule.createMockInstance,
5469
+ {
5470
+ root: getBrowserState().viteConfig.root
5471
+ }
5472
+ );
5473
+ globalThis.__vitest_mocker__ = mocker;
5474
+ setupConsoleLogSpy();
5475
+ setupDialogsSpy();
5476
+ const runner2 = await initiateRunner(state, mocker, config);
5477
+ getBrowserState().runner = runner2;
5478
+ if (server.provider === "webdriverio") {
5479
+ let switchPromise = null;
5480
+ commands.onCommand(async () => {
5481
+ if (switchPromise) {
5482
+ await switchPromise;
5483
+ }
5484
+ if (!contextSwitched) {
5485
+ switchPromise = rpc2.wdioSwitchContext("iframe").finally(() => {
5486
+ switchPromise = null;
5487
+ contextSwitched = true;
5488
+ });
5489
+ await switchPromise;
5490
+ }
5491
+ });
5492
+ }
5493
+ state.durations.prepare = performance.now() - options.startTime;
5494
+ return {
5495
+ runner: runner2,
5496
+ config,
5497
+ state
5498
+ };
5499
+ }
5500
+ let preparedData;
5501
+ async function executeTests(method, specifications) {
5502
+ if (!preparedData) {
5503
+ throw new Error(`Data was not properly initialized. This is a bug in Vitest. Please, open a new issue with reproduction.`);
5504
+ }
5505
+ debug == null ? void 0 : debug("runner resolved successfully");
5506
+ const { runner: runner2, state } = preparedData;
5507
+ state.ctx.files = specifications;
5508
+ runner2.setMethod(method);
5509
+ const version = url.searchParams.get("browserv") || "";
5510
+ specifications.forEach(({ filepath }) => {
5511
+ const currentVersion = browserHashMap.get(filepath);
5512
+ if (!currentVersion || currentVersion[1] !== version) {
5513
+ browserHashMap.set(filepath, version);
5514
+ }
5515
+ });
5516
+ for (const file of specifications) {
5517
+ state.filepath = file.filepath;
5518
+ debug == null ? void 0 : debug("running test file", file.filepath);
5519
+ await traces.$(
5520
+ `vitest.test.runner.${method}.module`,
5521
+ {
5522
+ attributes: { "code.file.path": file.filepath }
5523
+ },
5524
+ async () => {
5525
+ if (method === "run") {
5526
+ await startTests([file], runner2);
5527
+ } else {
5528
+ await collectTests([file], runner2);
5529
+ }
5530
+ }
5531
+ );
5532
+ }
5533
+ }
5534
+ async function prepare(options) {
5535
+ preparedData = await prepareTestEnvironment(options);
5536
+ debug == null ? void 0 : debug("runner resolved successfully");
5537
+ const { config, state } = preparedData;
5538
+ state.durations.prepare = performance.now() - state.durations.prepare;
5539
+ debug == null ? void 0 : debug("prepare time", state.durations.prepare, "ms");
5540
+ await Promise.all([
5541
+ setupCommonEnv(config),
5542
+ startCoverageInsideWorker(config.coverage, moduleRunner, { isolate: config.browser.isolate }),
5543
+ (async () => {
5544
+ const VitestIndex = await __vitePreload(() => import("vitest"), true ? [] : void 0);
5545
+ Object.defineProperty(window, "__vitest_index__", {
5546
+ value: VitestIndex,
5547
+ enumerable: false
5548
+ });
5549
+ })()
5550
+ ]);
5551
+ if (!config.browser.trackUnhandledErrors) {
5552
+ getBrowserState().disposeExceptionTracker();
5553
+ }
5554
+ }
5555
+ async function cleanup() {
5556
+ const state = getWorkerState();
5557
+ const config = getConfig$1();
5558
+ const rpc2 = state.rpc;
5559
+ const cleanupSymbol = Symbol.for("vitest:component-cleanup");
5560
+ if (cleanupSymbol in page) {
5561
+ try {
5562
+ await page[cleanupSymbol]();
5563
+ } catch (error) {
5564
+ await unhandledError(error, "Cleanup Error");
5565
+ }
5566
+ }
5567
+ await userEvent.cleanup().catch((error) => unhandledError(error, "Cleanup Error"));
5568
+ await Promise.all(
5569
+ getBrowserState().cleanups.map((fn) => fn())
5570
+ ).catch((error) => unhandledError(error, "Cleanup Error"));
5571
+ if (contextSwitched) {
5572
+ await rpc2.wdioSwitchContext("parent").catch((error) => unhandledError(error, "Cleanup Error"));
5573
+ }
5574
+ await stopCoverageInsideWorker(config.coverage, moduleRunner, { isolate: config.browser.isolate }).catch((error) => {
5575
+ return unhandledError(error, "Coverage Error");
5576
+ });
5577
+ }
5578
+ function unhandledError(e, type) {
5579
+ return client.rpc.onUnhandledError({
5580
+ name: e.name,
5581
+ message: e.message,
5582
+ stack: e.stack
5583
+ }, type).catch(() => {
5584
+ });
5585
+ }
5586
+ function isEvent(data) {
5587
+ return typeof data === "object" && !!data && "event" in data;
5588
+ }