@vitest/browser 4.0.0-beta.1 → 4.0.0-beta.11

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 (44) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +3 -15
  3. package/context.d.ts +153 -3
  4. package/dist/client/.vite/manifest.json +6 -6
  5. package/dist/client/__vitest__/assets/{index-KbpJLW--.css → index-CCvbyxW7.css} +1 -1
  6. package/dist/client/__vitest__/assets/index-CYIziQD6.js +53 -0
  7. package/dist/client/__vitest__/index.html +2 -2
  8. package/dist/client/__vitest_browser__/orchestrator-DOxlOAkk.js +293 -0
  9. package/dist/client/__vitest_browser__/tester-B7fynsGK.js +2090 -0
  10. package/dist/client/__vitest_browser__/{utils-Owv5OOOf.js → utils-CPmDBIKG.js} +3 -3
  11. package/dist/client/error-catcher.js +7 -3
  12. package/dist/client/esm-client-injector.js +1 -0
  13. package/dist/client/orchestrator.html +2 -2
  14. package/dist/client/tester/tester.html +2 -2
  15. package/dist/client.js +24 -8
  16. package/dist/context.js +29 -22
  17. package/dist/expect-element.js +10 -8
  18. package/dist/index-CwoiDq7G.js +6 -0
  19. package/dist/index-DDlvjJVO.js +1 -0
  20. package/dist/index.d.ts +16 -10
  21. package/dist/index.js +555 -104
  22. package/dist/locators/index.d.ts +8 -7
  23. package/dist/locators/index.js +1 -1
  24. package/dist/locators/playwright.js +1 -1
  25. package/dist/locators/preview.js +1 -1
  26. package/dist/locators/webdriverio.js +1 -1
  27. package/dist/providers/playwright.d.ts +103 -0
  28. package/dist/{webdriver-KA1WiV0q.js → providers/playwright.js} +37 -180
  29. package/dist/providers/preview.d.ts +16 -0
  30. package/dist/{providers.js → providers/preview.js} +17 -21
  31. package/dist/providers/webdriverio.d.ts +50 -0
  32. package/dist/providers/webdriverio.js +171 -0
  33. package/dist/shared/screenshotMatcher/types.d.ts +16 -0
  34. package/dist/state.js +4 -3
  35. package/dist/types.d.ts +5 -7
  36. package/jest-dom.d.ts +95 -1
  37. package/package.json +22 -32
  38. package/utils.d.ts +1 -1
  39. package/dist/client/__vitest__/assets/index-BjtzXzAw.js +0 -58
  40. package/dist/client/__vitest_browser__/orchestrator-CQgVbcQq.js +0 -3213
  41. package/dist/client/__vitest_browser__/tester-BScMoGFI.js +0 -3560
  42. package/dist/index-W1MM53zC.js +0 -1
  43. package/providers/playwright.d.ts +0 -81
  44. package/providers/webdriverio.d.ts +0 -22
@@ -1,3560 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
- import { b as resolve, e as executor, c as getWorkerState, a as getConfig, g as getBrowserState } from "./utils-Owv5OOOf.js";
5
- import { onCancel, globalChannel, channel, client } from "@vitest/browser/client";
6
- import { userEvent, page, server } from "@vitest/browser/context";
7
- import { getSafeTimers, TraceMap, originalPositionFor, loadDiffConfig, loadSnapshotSerializers, takeCoverageInsideWorker, stringify, format, setupCommonEnv, startCoverageInsideWorker, stopCoverageInsideWorker, startTests, collectTests, SpyModule } from "vitest/internal/browser";
8
- import { VitestTestRunner, NodeBenchmarkRunner } from "vitest/runners";
9
- const scriptRel = "modulepreload";
10
- const assetsURL = function(dep) {
11
- return "/" + dep;
12
- };
13
- const seen = {};
14
- const __vitePreload = function preload(baseModule, deps, importerUrl) {
15
- let promise = Promise.resolve();
16
- if (deps && deps.length > 0) {
17
- let allSettled2 = function(promises2) {
18
- return Promise.all(
19
- promises2.map(
20
- (p2) => Promise.resolve(p2).then(
21
- (value) => ({ status: "fulfilled", value }),
22
- (reason) => ({ status: "rejected", reason })
23
- )
24
- )
25
- );
26
- };
27
- document.getElementsByTagName("link");
28
- const cspNonceMeta = document.querySelector(
29
- "meta[property=csp-nonce]"
30
- );
31
- const cspNonce = (cspNonceMeta == null ? void 0 : cspNonceMeta.nonce) || (cspNonceMeta == null ? void 0 : cspNonceMeta.getAttribute("nonce"));
32
- promise = allSettled2(
33
- deps.map((dep) => {
34
- dep = assetsURL(dep);
35
- if (dep in seen) return;
36
- seen[dep] = true;
37
- const isCss = dep.endsWith(".css");
38
- const cssSelector = isCss ? '[rel="stylesheet"]' : "";
39
- if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
40
- return;
41
- }
42
- const link = document.createElement("link");
43
- link.rel = isCss ? "stylesheet" : scriptRel;
44
- if (!isCss) {
45
- link.as = "script";
46
- }
47
- link.crossOrigin = "";
48
- link.href = dep;
49
- if (cspNonce) {
50
- link.setAttribute("nonce", cspNonce);
51
- }
52
- document.head.appendChild(link);
53
- if (isCss) {
54
- return new Promise((res, rej) => {
55
- link.addEventListener("load", res);
56
- link.addEventListener(
57
- "error",
58
- () => rej(new Error(`Unable to preload CSS for ${dep}`))
59
- );
60
- });
61
- }
62
- })
63
- );
64
- }
65
- function handlePreloadError(err) {
66
- const e = new Event("vite:preloadError", {
67
- cancelable: true
68
- });
69
- e.payload = err;
70
- window.dispatchEvent(e);
71
- if (!e.defaultPrevented) {
72
- throw err;
73
- }
74
- }
75
- return promise.then((res) => {
76
- for (const item of res || []) {
77
- if (item.status !== "rejected") continue;
78
- handlePreloadError(item.reason);
79
- }
80
- return baseModule().catch(handlePreloadError);
81
- });
82
- };
83
- const { parse: $parse } = JSON;
84
- const { keys } = Object;
85
- const Primitive = String;
86
- const primitive = "string";
87
- const ignore = {};
88
- const object = "object";
89
- const noop = (_, value) => value;
90
- const primitives = (value) => value instanceof Primitive ? Primitive(value) : value;
91
- const Primitives = (_, value) => typeof value === primitive ? new Primitive(value) : value;
92
- const revive = (input, parsed, output, $) => {
93
- const lazy = [];
94
- for (let ke = keys(output), { length } = ke, y = 0; y < length; y++) {
95
- const k = ke[y];
96
- const value = output[k];
97
- if (value instanceof Primitive) {
98
- const tmp = input[value];
99
- if (typeof tmp === object && !parsed.has(tmp)) {
100
- parsed.add(tmp);
101
- output[k] = ignore;
102
- lazy.push({ k, a: [input, parsed, tmp, $] });
103
- } else
104
- output[k] = $.call(output, k, tmp);
105
- } else if (output[k] !== ignore)
106
- output[k] = $.call(output, k, value);
107
- }
108
- for (let { length } = lazy, i = 0; i < length; i++) {
109
- const { k, a: a2 } = lazy[i];
110
- output[k] = $.call(output, k, revive.apply(null, a2));
111
- }
112
- return output;
113
- };
114
- const parse = (text, reviver) => {
115
- const input = $parse(text, Primitives).map(primitives);
116
- const value = input[0];
117
- const $ = noop;
118
- const tmp = typeof value === object && value ? revive(input, /* @__PURE__ */ new Set(), value, $) : value;
119
- return $.call({ "": tmp }, "", tmp);
120
- };
121
- function showPopupWarning(name, value, defaultValue) {
122
- return (...params) => {
123
- const formattedParams = params.map((p2) => JSON.stringify(p2)).join(", ");
124
- 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.
125
- If needed, mock the \`${name}\` call manually like:
126
-
127
- \`\`\`
128
- import { expect, vi } from "vitest"
129
-
130
- vi.spyOn(window, "${name}")${defaultValue ? `.mockReturnValue(${JSON.stringify(defaultValue)})` : ""}
131
- ${name}(${formattedParams})
132
- expect(${name}).toHaveBeenCalledWith(${formattedParams})
133
- \`\`\``);
134
- return value;
135
- };
136
- }
137
- function setupDialogsSpy() {
138
- globalThis.alert = showPopupWarning("alert", void 0);
139
- globalThis.confirm = showPopupWarning("confirm", false, true);
140
- globalThis.prompt = showPopupWarning("prompt", null, "your value");
141
- }
142
- const { get } = Reflect;
143
- function withSafeTimers(getTimers, fn) {
144
- const { setTimeout, clearTimeout } = getTimers();
145
- const currentSetTimeout = globalThis.setTimeout;
146
- const currentClearTimeout = globalThis.clearTimeout;
147
- try {
148
- globalThis.setTimeout = setTimeout;
149
- globalThis.clearTimeout = clearTimeout;
150
- const result = fn();
151
- return result;
152
- } finally {
153
- globalThis.setTimeout = currentSetTimeout;
154
- globalThis.clearTimeout = currentClearTimeout;
155
- }
156
- }
157
- const promises = /* @__PURE__ */ new Set();
158
- function createSafeRpc(client2) {
159
- return new Proxy(client2.rpc, {
160
- get(target, p2, handler) {
161
- if (p2 === "then") {
162
- return;
163
- }
164
- const sendCall = get(target, p2, handler);
165
- const safeSendCall = (...args) => withSafeTimers(getSafeTimers, async () => {
166
- const result = sendCall(...args);
167
- promises.add(result);
168
- try {
169
- return await result;
170
- } finally {
171
- promises.delete(result);
172
- }
173
- });
174
- safeSendCall.asEvent = sendCall.asEvent;
175
- return safeSendCall;
176
- }
177
- });
178
- }
179
- function rpc$2() {
180
- return globalThis.__vitest_worker__.rpc;
181
- }
182
- var traceMapping_umd$1 = { exports: {} };
183
- var sourcemapCodec_umd$1 = { exports: {} };
184
- var sourcemapCodec_umd = sourcemapCodec_umd$1.exports;
185
- var hasRequiredSourcemapCodec_umd;
186
- function requireSourcemapCodec_umd() {
187
- if (hasRequiredSourcemapCodec_umd) return sourcemapCodec_umd$1.exports;
188
- hasRequiredSourcemapCodec_umd = 1;
189
- (function(module, exports) {
190
- (function(global, factory) {
191
- factory(exports);
192
- })(sourcemapCodec_umd, function(exports2) {
193
- const comma = ",".charCodeAt(0);
194
- const semicolon = ";".charCodeAt(0);
195
- const chars2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
196
- const intToChar2 = new Uint8Array(64);
197
- const charToInt2 = new Uint8Array(128);
198
- for (let i = 0; i < chars2.length; i++) {
199
- const c = chars2.charCodeAt(i);
200
- intToChar2[i] = c;
201
- charToInt2[c] = i;
202
- }
203
- function decodeInteger(reader, relative) {
204
- let value = 0;
205
- let shift = 0;
206
- let integer = 0;
207
- do {
208
- const c = reader.next();
209
- integer = charToInt2[c];
210
- value |= (integer & 31) << shift;
211
- shift += 5;
212
- } while (integer & 32);
213
- const shouldNegate = value & 1;
214
- value >>>= 1;
215
- if (shouldNegate) {
216
- value = -2147483648 | -value;
217
- }
218
- return relative + value;
219
- }
220
- function encodeInteger(builder, num, relative) {
221
- let delta = num - relative;
222
- delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
223
- do {
224
- let clamped = delta & 31;
225
- delta >>>= 5;
226
- if (delta > 0)
227
- clamped |= 32;
228
- builder.write(intToChar2[clamped]);
229
- } while (delta > 0);
230
- return num;
231
- }
232
- function hasMoreVlq(reader, max) {
233
- if (reader.pos >= max)
234
- return false;
235
- return reader.peek() !== comma;
236
- }
237
- const bufLength = 1024 * 16;
238
- const td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
239
- decode(buf) {
240
- const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
241
- return out.toString();
242
- }
243
- } : {
244
- decode(buf) {
245
- let out = "";
246
- for (let i = 0; i < buf.length; i++) {
247
- out += String.fromCharCode(buf[i]);
248
- }
249
- return out;
250
- }
251
- };
252
- class StringWriter {
253
- constructor() {
254
- this.pos = 0;
255
- this.out = "";
256
- this.buffer = new Uint8Array(bufLength);
257
- }
258
- write(v) {
259
- const { buffer } = this;
260
- buffer[this.pos++] = v;
261
- if (this.pos === bufLength) {
262
- this.out += td.decode(buffer);
263
- this.pos = 0;
264
- }
265
- }
266
- flush() {
267
- const { buffer, out, pos } = this;
268
- return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
269
- }
270
- }
271
- class StringReader {
272
- constructor(buffer) {
273
- this.pos = 0;
274
- this.buffer = buffer;
275
- }
276
- next() {
277
- return this.buffer.charCodeAt(this.pos++);
278
- }
279
- peek() {
280
- return this.buffer.charCodeAt(this.pos);
281
- }
282
- indexOf(char) {
283
- const { buffer, pos } = this;
284
- const idx = buffer.indexOf(char, pos);
285
- return idx === -1 ? buffer.length : idx;
286
- }
287
- }
288
- const EMPTY = [];
289
- function decodeOriginalScopes(input) {
290
- const { length } = input;
291
- const reader = new StringReader(input);
292
- const scopes = [];
293
- const stack = [];
294
- let line = 0;
295
- for (; reader.pos < length; reader.pos++) {
296
- line = decodeInteger(reader, line);
297
- const column = decodeInteger(reader, 0);
298
- if (!hasMoreVlq(reader, length)) {
299
- const last = stack.pop();
300
- last[2] = line;
301
- last[3] = column;
302
- continue;
303
- }
304
- const kind = decodeInteger(reader, 0);
305
- const fields = decodeInteger(reader, 0);
306
- const hasName = fields & 1;
307
- const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind];
308
- let vars = EMPTY;
309
- if (hasMoreVlq(reader, length)) {
310
- vars = [];
311
- do {
312
- const varsIndex = decodeInteger(reader, 0);
313
- vars.push(varsIndex);
314
- } while (hasMoreVlq(reader, length));
315
- }
316
- scope.vars = vars;
317
- scopes.push(scope);
318
- stack.push(scope);
319
- }
320
- return scopes;
321
- }
322
- function encodeOriginalScopes(scopes) {
323
- const writer = new StringWriter();
324
- for (let i = 0; i < scopes.length; ) {
325
- i = _encodeOriginalScopes(scopes, i, writer, [0]);
326
- }
327
- return writer.flush();
328
- }
329
- function _encodeOriginalScopes(scopes, index2, writer, state) {
330
- const scope = scopes[index2];
331
- const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
332
- if (index2 > 0)
333
- writer.write(comma);
334
- state[0] = encodeInteger(writer, startLine, state[0]);
335
- encodeInteger(writer, startColumn, 0);
336
- encodeInteger(writer, kind, 0);
337
- const fields = scope.length === 6 ? 1 : 0;
338
- encodeInteger(writer, fields, 0);
339
- if (scope.length === 6)
340
- encodeInteger(writer, scope[5], 0);
341
- for (const v of vars) {
342
- encodeInteger(writer, v, 0);
343
- }
344
- for (index2++; index2 < scopes.length; ) {
345
- const next = scopes[index2];
346
- const { 0: l, 1: c } = next;
347
- if (l > endLine || l === endLine && c >= endColumn) {
348
- break;
349
- }
350
- index2 = _encodeOriginalScopes(scopes, index2, writer, state);
351
- }
352
- writer.write(comma);
353
- state[0] = encodeInteger(writer, endLine, state[0]);
354
- encodeInteger(writer, endColumn, 0);
355
- return index2;
356
- }
357
- function decodeGeneratedRanges(input) {
358
- const { length } = input;
359
- const reader = new StringReader(input);
360
- const ranges = [];
361
- const stack = [];
362
- let genLine = 0;
363
- let definitionSourcesIndex = 0;
364
- let definitionScopeIndex = 0;
365
- let callsiteSourcesIndex = 0;
366
- let callsiteLine = 0;
367
- let callsiteColumn = 0;
368
- let bindingLine = 0;
369
- let bindingColumn = 0;
370
- do {
371
- const semi = reader.indexOf(";");
372
- let genColumn = 0;
373
- for (; reader.pos < semi; reader.pos++) {
374
- genColumn = decodeInteger(reader, genColumn);
375
- if (!hasMoreVlq(reader, semi)) {
376
- const last = stack.pop();
377
- last[2] = genLine;
378
- last[3] = genColumn;
379
- continue;
380
- }
381
- const fields = decodeInteger(reader, 0);
382
- const hasDefinition = fields & 1;
383
- const hasCallsite = fields & 2;
384
- const hasScope = fields & 4;
385
- let callsite = null;
386
- let bindings = EMPTY;
387
- let range;
388
- if (hasDefinition) {
389
- const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
390
- definitionScopeIndex = decodeInteger(reader, definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0);
391
- definitionSourcesIndex = defSourcesIndex;
392
- range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex];
393
- } else {
394
- range = [genLine, genColumn, 0, 0];
395
- }
396
- range.isScope = !!hasScope;
397
- if (hasCallsite) {
398
- const prevCsi = callsiteSourcesIndex;
399
- const prevLine = callsiteLine;
400
- callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);
401
- const sameSource = prevCsi === callsiteSourcesIndex;
402
- callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);
403
- callsiteColumn = decodeInteger(reader, sameSource && prevLine === callsiteLine ? callsiteColumn : 0);
404
- callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
405
- }
406
- range.callsite = callsite;
407
- if (hasMoreVlq(reader, semi)) {
408
- bindings = [];
409
- do {
410
- bindingLine = genLine;
411
- bindingColumn = genColumn;
412
- const expressionsCount = decodeInteger(reader, 0);
413
- let expressionRanges;
414
- if (expressionsCount < -1) {
415
- expressionRanges = [[decodeInteger(reader, 0)]];
416
- for (let i = -1; i > expressionsCount; i--) {
417
- const prevBl = bindingLine;
418
- bindingLine = decodeInteger(reader, bindingLine);
419
- bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);
420
- const expression = decodeInteger(reader, 0);
421
- expressionRanges.push([expression, bindingLine, bindingColumn]);
422
- }
423
- } else {
424
- expressionRanges = [[expressionsCount]];
425
- }
426
- bindings.push(expressionRanges);
427
- } while (hasMoreVlq(reader, semi));
428
- }
429
- range.bindings = bindings;
430
- ranges.push(range);
431
- stack.push(range);
432
- }
433
- genLine++;
434
- reader.pos = semi + 1;
435
- } while (reader.pos < length);
436
- return ranges;
437
- }
438
- function encodeGeneratedRanges(ranges) {
439
- if (ranges.length === 0)
440
- return "";
441
- const writer = new StringWriter();
442
- for (let i = 0; i < ranges.length; ) {
443
- i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
444
- }
445
- return writer.flush();
446
- }
447
- function _encodeGeneratedRanges(ranges, index2, writer, state) {
448
- const range = ranges[index2];
449
- const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, isScope, callsite, bindings } = range;
450
- if (state[0] < startLine) {
451
- catchupLine(writer, state[0], startLine);
452
- state[0] = startLine;
453
- state[1] = 0;
454
- } else if (index2 > 0) {
455
- writer.write(comma);
456
- }
457
- state[1] = encodeInteger(writer, range[1], state[1]);
458
- const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0);
459
- encodeInteger(writer, fields, 0);
460
- if (range.length === 6) {
461
- const { 4: sourcesIndex, 5: scopesIndex } = range;
462
- if (sourcesIndex !== state[2]) {
463
- state[3] = 0;
464
- }
465
- state[2] = encodeInteger(writer, sourcesIndex, state[2]);
466
- state[3] = encodeInteger(writer, scopesIndex, state[3]);
467
- }
468
- if (callsite) {
469
- const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite;
470
- if (sourcesIndex !== state[4]) {
471
- state[5] = 0;
472
- state[6] = 0;
473
- } else if (callLine !== state[5]) {
474
- state[6] = 0;
475
- }
476
- state[4] = encodeInteger(writer, sourcesIndex, state[4]);
477
- state[5] = encodeInteger(writer, callLine, state[5]);
478
- state[6] = encodeInteger(writer, callColumn, state[6]);
479
- }
480
- if (bindings) {
481
- for (const binding of bindings) {
482
- if (binding.length > 1)
483
- encodeInteger(writer, -binding.length, 0);
484
- const expression = binding[0][0];
485
- encodeInteger(writer, expression, 0);
486
- let bindingStartLine = startLine;
487
- let bindingStartColumn = startColumn;
488
- for (let i = 1; i < binding.length; i++) {
489
- const expRange = binding[i];
490
- bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine);
491
- bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn);
492
- encodeInteger(writer, expRange[0], 0);
493
- }
494
- }
495
- }
496
- for (index2++; index2 < ranges.length; ) {
497
- const next = ranges[index2];
498
- const { 0: l, 1: c } = next;
499
- if (l > endLine || l === endLine && c >= endColumn) {
500
- break;
501
- }
502
- index2 = _encodeGeneratedRanges(ranges, index2, writer, state);
503
- }
504
- if (state[0] < endLine) {
505
- catchupLine(writer, state[0], endLine);
506
- state[0] = endLine;
507
- state[1] = 0;
508
- } else {
509
- writer.write(comma);
510
- }
511
- state[1] = encodeInteger(writer, endColumn, state[1]);
512
- return index2;
513
- }
514
- function catchupLine(writer, lastLine, line) {
515
- do {
516
- writer.write(semicolon);
517
- } while (++lastLine < line);
518
- }
519
- function decode(mappings) {
520
- const { length } = mappings;
521
- const reader = new StringReader(mappings);
522
- const decoded = [];
523
- let genColumn = 0;
524
- let sourcesIndex = 0;
525
- let sourceLine = 0;
526
- let sourceColumn = 0;
527
- let namesIndex = 0;
528
- do {
529
- const semi = reader.indexOf(";");
530
- const line = [];
531
- let sorted = true;
532
- let lastCol = 0;
533
- genColumn = 0;
534
- while (reader.pos < semi) {
535
- let seg;
536
- genColumn = decodeInteger(reader, genColumn);
537
- if (genColumn < lastCol)
538
- sorted = false;
539
- lastCol = genColumn;
540
- if (hasMoreVlq(reader, semi)) {
541
- sourcesIndex = decodeInteger(reader, sourcesIndex);
542
- sourceLine = decodeInteger(reader, sourceLine);
543
- sourceColumn = decodeInteger(reader, sourceColumn);
544
- if (hasMoreVlq(reader, semi)) {
545
- namesIndex = decodeInteger(reader, namesIndex);
546
- seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
547
- } else {
548
- seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
549
- }
550
- } else {
551
- seg = [genColumn];
552
- }
553
- line.push(seg);
554
- reader.pos++;
555
- }
556
- if (!sorted)
557
- sort(line);
558
- decoded.push(line);
559
- reader.pos = semi + 1;
560
- } while (reader.pos <= length);
561
- return decoded;
562
- }
563
- function sort(line) {
564
- line.sort(sortComparator);
565
- }
566
- function sortComparator(a2, b) {
567
- return a2[0] - b[0];
568
- }
569
- function encode(decoded) {
570
- const writer = new StringWriter();
571
- let sourcesIndex = 0;
572
- let sourceLine = 0;
573
- let sourceColumn = 0;
574
- let namesIndex = 0;
575
- for (let i = 0; i < decoded.length; i++) {
576
- const line = decoded[i];
577
- if (i > 0)
578
- writer.write(semicolon);
579
- if (line.length === 0)
580
- continue;
581
- let genColumn = 0;
582
- for (let j = 0; j < line.length; j++) {
583
- const segment = line[j];
584
- if (j > 0)
585
- writer.write(comma);
586
- genColumn = encodeInteger(writer, segment[0], genColumn);
587
- if (segment.length === 1)
588
- continue;
589
- sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
590
- sourceLine = encodeInteger(writer, segment[2], sourceLine);
591
- sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
592
- if (segment.length === 4)
593
- continue;
594
- namesIndex = encodeInteger(writer, segment[4], namesIndex);
595
- }
596
- }
597
- return writer.flush();
598
- }
599
- exports2.decode = decode;
600
- exports2.decodeGeneratedRanges = decodeGeneratedRanges;
601
- exports2.decodeOriginalScopes = decodeOriginalScopes;
602
- exports2.encode = encode;
603
- exports2.encodeGeneratedRanges = encodeGeneratedRanges;
604
- exports2.encodeOriginalScopes = encodeOriginalScopes;
605
- Object.defineProperty(exports2, "__esModule", { value: true });
606
- });
607
- })(sourcemapCodec_umd$1, sourcemapCodec_umd$1.exports);
608
- return sourcemapCodec_umd$1.exports;
609
- }
610
- var resolveUri_umd$1 = { exports: {} };
611
- var resolveUri_umd = resolveUri_umd$1.exports;
612
- var hasRequiredResolveUri_umd;
613
- function requireResolveUri_umd() {
614
- if (hasRequiredResolveUri_umd) return resolveUri_umd$1.exports;
615
- hasRequiredResolveUri_umd = 1;
616
- (function(module, exports) {
617
- (function(global, factory) {
618
- module.exports = factory();
619
- })(resolveUri_umd, function() {
620
- const schemeRegex = /^[\w+.-]+:\/\//;
621
- const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
622
- const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
623
- var UrlType2;
624
- (function(UrlType3) {
625
- UrlType3[UrlType3["Empty"] = 1] = "Empty";
626
- UrlType3[UrlType3["Hash"] = 2] = "Hash";
627
- UrlType3[UrlType3["Query"] = 3] = "Query";
628
- UrlType3[UrlType3["RelativePath"] = 4] = "RelativePath";
629
- UrlType3[UrlType3["AbsolutePath"] = 5] = "AbsolutePath";
630
- UrlType3[UrlType3["SchemeRelative"] = 6] = "SchemeRelative";
631
- UrlType3[UrlType3["Absolute"] = 7] = "Absolute";
632
- })(UrlType2 || (UrlType2 = {}));
633
- function isAbsoluteUrl(input) {
634
- return schemeRegex.test(input);
635
- }
636
- function isSchemeRelativeUrl(input) {
637
- return input.startsWith("//");
638
- }
639
- function isAbsolutePath(input) {
640
- return input.startsWith("/");
641
- }
642
- function isFileUrl(input) {
643
- return input.startsWith("file:");
644
- }
645
- function isRelative(input) {
646
- return /^[.?#]/.test(input);
647
- }
648
- function parseAbsoluteUrl(input) {
649
- const match = urlRegex.exec(input);
650
- return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
651
- }
652
- function parseFileUrl(input) {
653
- const match = fileRegex.exec(input);
654
- const path = match[2];
655
- return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || "");
656
- }
657
- function makeUrl(scheme, user, host, port, path, query, hash) {
658
- return {
659
- scheme,
660
- user,
661
- host,
662
- port,
663
- path,
664
- query,
665
- hash,
666
- type: UrlType2.Absolute
667
- };
668
- }
669
- function parseUrl(input) {
670
- if (isSchemeRelativeUrl(input)) {
671
- const url3 = parseAbsoluteUrl("http:" + input);
672
- url3.scheme = "";
673
- url3.type = UrlType2.SchemeRelative;
674
- return url3;
675
- }
676
- if (isAbsolutePath(input)) {
677
- const url3 = parseAbsoluteUrl("http://foo.com" + input);
678
- url3.scheme = "";
679
- url3.host = "";
680
- url3.type = UrlType2.AbsolutePath;
681
- return url3;
682
- }
683
- if (isFileUrl(input))
684
- return parseFileUrl(input);
685
- if (isAbsoluteUrl(input))
686
- return parseAbsoluteUrl(input);
687
- const url2 = parseAbsoluteUrl("http://foo.com/" + input);
688
- url2.scheme = "";
689
- url2.host = "";
690
- url2.type = input ? input.startsWith("?") ? UrlType2.Query : input.startsWith("#") ? UrlType2.Hash : UrlType2.RelativePath : UrlType2.Empty;
691
- return url2;
692
- }
693
- function stripPathFilename(path) {
694
- if (path.endsWith("/.."))
695
- return path;
696
- const index2 = path.lastIndexOf("/");
697
- return path.slice(0, index2 + 1);
698
- }
699
- function mergePaths(url2, base) {
700
- normalizePath(base, base.type);
701
- if (url2.path === "/") {
702
- url2.path = base.path;
703
- } else {
704
- url2.path = stripPathFilename(base.path) + url2.path;
705
- }
706
- }
707
- function normalizePath(url2, type) {
708
- const rel = type <= UrlType2.RelativePath;
709
- const pieces = url2.path.split("/");
710
- let pointer = 1;
711
- let positive = 0;
712
- let addTrailingSlash = false;
713
- for (let i = 1; i < pieces.length; i++) {
714
- const piece = pieces[i];
715
- if (!piece) {
716
- addTrailingSlash = true;
717
- continue;
718
- }
719
- addTrailingSlash = false;
720
- if (piece === ".")
721
- continue;
722
- if (piece === "..") {
723
- if (positive) {
724
- addTrailingSlash = true;
725
- positive--;
726
- pointer--;
727
- } else if (rel) {
728
- pieces[pointer++] = piece;
729
- }
730
- continue;
731
- }
732
- pieces[pointer++] = piece;
733
- positive++;
734
- }
735
- let path = "";
736
- for (let i = 1; i < pointer; i++) {
737
- path += "/" + pieces[i];
738
- }
739
- if (!path || addTrailingSlash && !path.endsWith("/..")) {
740
- path += "/";
741
- }
742
- url2.path = path;
743
- }
744
- function resolve2(input, base) {
745
- if (!input && !base)
746
- return "";
747
- const url2 = parseUrl(input);
748
- let inputType = url2.type;
749
- if (base && inputType !== UrlType2.Absolute) {
750
- const baseUrl = parseUrl(base);
751
- const baseType = baseUrl.type;
752
- switch (inputType) {
753
- case UrlType2.Empty:
754
- url2.hash = baseUrl.hash;
755
- // fall through
756
- case UrlType2.Hash:
757
- url2.query = baseUrl.query;
758
- // fall through
759
- case UrlType2.Query:
760
- case UrlType2.RelativePath:
761
- mergePaths(url2, baseUrl);
762
- // fall through
763
- case UrlType2.AbsolutePath:
764
- url2.user = baseUrl.user;
765
- url2.host = baseUrl.host;
766
- url2.port = baseUrl.port;
767
- // fall through
768
- case UrlType2.SchemeRelative:
769
- url2.scheme = baseUrl.scheme;
770
- }
771
- if (baseType > inputType)
772
- inputType = baseType;
773
- }
774
- normalizePath(url2, inputType);
775
- const queryHash = url2.query + url2.hash;
776
- switch (inputType) {
777
- // This is impossible, because of the empty checks at the start of the function.
778
- // case UrlType.Empty:
779
- case UrlType2.Hash:
780
- case UrlType2.Query:
781
- return queryHash;
782
- case UrlType2.RelativePath: {
783
- const path = url2.path.slice(1);
784
- if (!path)
785
- return queryHash || ".";
786
- if (isRelative(base || input) && !isRelative(path)) {
787
- return "./" + path + queryHash;
788
- }
789
- return path + queryHash;
790
- }
791
- case UrlType2.AbsolutePath:
792
- return url2.path + queryHash;
793
- default:
794
- return url2.scheme + "//" + url2.user + url2.host + url2.port + url2.path + queryHash;
795
- }
796
- }
797
- return resolve2;
798
- });
799
- })(resolveUri_umd$1);
800
- return resolveUri_umd$1.exports;
801
- }
802
- var traceMapping_umd = traceMapping_umd$1.exports;
803
- var hasRequiredTraceMapping_umd;
804
- function requireTraceMapping_umd() {
805
- if (hasRequiredTraceMapping_umd) return traceMapping_umd$1.exports;
806
- hasRequiredTraceMapping_umd = 1;
807
- (function(module, exports) {
808
- (function(global, factory) {
809
- factory(exports, requireSourcemapCodec_umd(), requireResolveUri_umd());
810
- })(traceMapping_umd, function(exports2, sourcemapCodec, resolveUri) {
811
- function resolve2(input, base) {
812
- if (base && !base.endsWith("/"))
813
- base += "/";
814
- return resolveUri(input, base);
815
- }
816
- function stripFilename(path) {
817
- if (!path)
818
- return "";
819
- const index2 = path.lastIndexOf("/");
820
- return path.slice(0, index2 + 1);
821
- }
822
- const COLUMN = 0;
823
- const SOURCES_INDEX = 1;
824
- const SOURCE_LINE = 2;
825
- const SOURCE_COLUMN = 3;
826
- const NAMES_INDEX = 4;
827
- const REV_GENERATED_LINE = 1;
828
- const REV_GENERATED_COLUMN = 2;
829
- function maybeSort(mappings, owned) {
830
- const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
831
- if (unsortedIndex === mappings.length)
832
- return mappings;
833
- if (!owned)
834
- mappings = mappings.slice();
835
- for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
836
- mappings[i] = sortSegments(mappings[i], owned);
837
- }
838
- return mappings;
839
- }
840
- function nextUnsortedSegmentLine(mappings, start) {
841
- for (let i = start; i < mappings.length; i++) {
842
- if (!isSorted(mappings[i]))
843
- return i;
844
- }
845
- return mappings.length;
846
- }
847
- function isSorted(line) {
848
- for (let j = 1; j < line.length; j++) {
849
- if (line[j][COLUMN] < line[j - 1][COLUMN]) {
850
- return false;
851
- }
852
- }
853
- return true;
854
- }
855
- function sortSegments(line, owned) {
856
- if (!owned)
857
- line = line.slice();
858
- return line.sort(sortComparator);
859
- }
860
- function sortComparator(a2, b) {
861
- return a2[COLUMN] - b[COLUMN];
862
- }
863
- let found = false;
864
- function binarySearch(haystack, needle, low, high) {
865
- while (low <= high) {
866
- const mid = low + (high - low >> 1);
867
- const cmp = haystack[mid][COLUMN] - needle;
868
- if (cmp === 0) {
869
- found = true;
870
- return mid;
871
- }
872
- if (cmp < 0) {
873
- low = mid + 1;
874
- } else {
875
- high = mid - 1;
876
- }
877
- }
878
- found = false;
879
- return low - 1;
880
- }
881
- function upperBound(haystack, needle, index2) {
882
- for (let i = index2 + 1; i < haystack.length; index2 = i++) {
883
- if (haystack[i][COLUMN] !== needle)
884
- break;
885
- }
886
- return index2;
887
- }
888
- function lowerBound(haystack, needle, index2) {
889
- for (let i = index2 - 1; i >= 0; index2 = i--) {
890
- if (haystack[i][COLUMN] !== needle)
891
- break;
892
- }
893
- return index2;
894
- }
895
- function memoizedState() {
896
- return {
897
- lastKey: -1,
898
- lastNeedle: -1,
899
- lastIndex: -1
900
- };
901
- }
902
- function memoizedBinarySearch(haystack, needle, state, key) {
903
- const { lastKey, lastNeedle, lastIndex } = state;
904
- let low = 0;
905
- let high = haystack.length - 1;
906
- if (key === lastKey) {
907
- if (needle === lastNeedle) {
908
- found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
909
- return lastIndex;
910
- }
911
- if (needle >= lastNeedle) {
912
- low = lastIndex === -1 ? 0 : lastIndex;
913
- } else {
914
- high = lastIndex;
915
- }
916
- }
917
- state.lastKey = key;
918
- state.lastNeedle = needle;
919
- return state.lastIndex = binarySearch(haystack, needle, low, high);
920
- }
921
- function buildBySources(decoded, memos) {
922
- const sources = memos.map(buildNullArray);
923
- for (let i = 0; i < decoded.length; i++) {
924
- const line = decoded[i];
925
- for (let j = 0; j < line.length; j++) {
926
- const seg = line[j];
927
- if (seg.length === 1)
928
- continue;
929
- const sourceIndex2 = seg[SOURCES_INDEX];
930
- const sourceLine = seg[SOURCE_LINE];
931
- const sourceColumn = seg[SOURCE_COLUMN];
932
- const originalSource = sources[sourceIndex2];
933
- const originalLine = originalSource[sourceLine] || (originalSource[sourceLine] = []);
934
- const memo = memos[sourceIndex2];
935
- let index2 = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine));
936
- memo.lastIndex = ++index2;
937
- insert(originalLine, index2, [sourceColumn, i, seg[COLUMN]]);
938
- }
939
- }
940
- return sources;
941
- }
942
- function insert(array, index2, value) {
943
- for (let i = array.length; i > index2; i--) {
944
- array[i] = array[i - 1];
945
- }
946
- array[index2] = value;
947
- }
948
- function buildNullArray() {
949
- return { __proto__: null };
950
- }
951
- const AnyMap = function(map, mapUrl) {
952
- const parsed = parse2(map);
953
- if (!("sections" in parsed)) {
954
- return new TraceMap2(parsed, mapUrl);
955
- }
956
- const mappings = [];
957
- const sources = [];
958
- const sourcesContent = [];
959
- const names = [];
960
- const ignoreList = [];
961
- recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, ignoreList, 0, 0, Infinity, Infinity);
962
- const joined = {
963
- version: 3,
964
- file: parsed.file,
965
- names,
966
- sources,
967
- sourcesContent,
968
- mappings,
969
- ignoreList
970
- };
971
- return presortedDecodedMap(joined);
972
- };
973
- function parse2(map) {
974
- return typeof map === "string" ? JSON.parse(map) : map;
975
- }
976
- function recurse(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
977
- const { sections } = input;
978
- for (let i = 0; i < sections.length; i++) {
979
- const { map, offset } = sections[i];
980
- let sl = stopLine;
981
- let sc = stopColumn;
982
- if (i + 1 < sections.length) {
983
- const nextOffset = sections[i + 1].offset;
984
- sl = Math.min(stopLine, lineOffset + nextOffset.line);
985
- if (sl === stopLine) {
986
- sc = Math.min(stopColumn, columnOffset + nextOffset.column);
987
- } else if (sl < stopLine) {
988
- sc = columnOffset + nextOffset.column;
989
- }
990
- }
991
- addSection(map, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset + offset.line, columnOffset + offset.column, sl, sc);
992
- }
993
- }
994
- function addSection(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) {
995
- const parsed = parse2(input);
996
- if ("sections" in parsed)
997
- return recurse(...arguments);
998
- const map = new TraceMap2(parsed, mapUrl);
999
- const sourcesOffset = sources.length;
1000
- const namesOffset = names.length;
1001
- const decoded = decodedMappings(map);
1002
- const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map;
1003
- append(sources, resolvedSources);
1004
- append(names, map.names);
1005
- if (contents)
1006
- append(sourcesContent, contents);
1007
- else
1008
- for (let i = 0; i < resolvedSources.length; i++)
1009
- sourcesContent.push(null);
1010
- if (ignores)
1011
- for (let i = 0; i < ignores.length; i++)
1012
- ignoreList.push(ignores[i] + sourcesOffset);
1013
- for (let i = 0; i < decoded.length; i++) {
1014
- const lineI = lineOffset + i;
1015
- if (lineI > stopLine)
1016
- return;
1017
- const out = getLine(mappings, lineI);
1018
- const cOffset = i === 0 ? columnOffset : 0;
1019
- const line = decoded[i];
1020
- for (let j = 0; j < line.length; j++) {
1021
- const seg = line[j];
1022
- const column = cOffset + seg[COLUMN];
1023
- if (lineI === stopLine && column >= stopColumn)
1024
- return;
1025
- if (seg.length === 1) {
1026
- out.push([column]);
1027
- continue;
1028
- }
1029
- const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];
1030
- const sourceLine = seg[SOURCE_LINE];
1031
- const sourceColumn = seg[SOURCE_COLUMN];
1032
- out.push(seg.length === 4 ? [column, sourcesIndex, sourceLine, sourceColumn] : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]);
1033
- }
1034
- }
1035
- }
1036
- function append(arr, other) {
1037
- for (let i = 0; i < other.length; i++)
1038
- arr.push(other[i]);
1039
- }
1040
- function getLine(arr, index2) {
1041
- for (let i = arr.length; i <= index2; i++)
1042
- arr[i] = [];
1043
- return arr[index2];
1044
- }
1045
- const LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
1046
- const COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
1047
- const LEAST_UPPER_BOUND = -1;
1048
- const GREATEST_LOWER_BOUND = 1;
1049
- class TraceMap2 {
1050
- constructor(map, mapUrl) {
1051
- const isString = typeof map === "string";
1052
- if (!isString && map._decodedMemo)
1053
- return map;
1054
- const parsed = isString ? JSON.parse(map) : map;
1055
- const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
1056
- this.version = version;
1057
- this.file = file;
1058
- this.names = names || [];
1059
- this.sourceRoot = sourceRoot;
1060
- this.sources = sources;
1061
- this.sourcesContent = sourcesContent;
1062
- this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
1063
- const from = resolve2(sourceRoot || "", stripFilename(mapUrl));
1064
- this.resolvedSources = sources.map((s) => resolve2(s || "", from));
1065
- const { mappings } = parsed;
1066
- if (typeof mappings === "string") {
1067
- this._encoded = mappings;
1068
- this._decoded = void 0;
1069
- } else {
1070
- this._encoded = void 0;
1071
- this._decoded = maybeSort(mappings, isString);
1072
- }
1073
- this._decodedMemo = memoizedState();
1074
- this._bySources = void 0;
1075
- this._bySourceMemos = void 0;
1076
- }
1077
- }
1078
- function cast(map) {
1079
- return map;
1080
- }
1081
- function encodedMappings(map) {
1082
- var _a;
1083
- var _b;
1084
- return (_a = (_b = cast(map))._encoded) !== null && _a !== void 0 ? _a : _b._encoded = sourcemapCodec.encode(cast(map)._decoded);
1085
- }
1086
- function decodedMappings(map) {
1087
- var _a;
1088
- return (_a = cast(map))._decoded || (_a._decoded = sourcemapCodec.decode(cast(map)._encoded));
1089
- }
1090
- function traceSegment(map, line, column) {
1091
- const decoded = decodedMappings(map);
1092
- if (line >= decoded.length)
1093
- return null;
1094
- const segments = decoded[line];
1095
- const index2 = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, GREATEST_LOWER_BOUND);
1096
- return index2 === -1 ? null : segments[index2];
1097
- }
1098
- function originalPositionFor2(map, needle) {
1099
- let { line, column, bias } = needle;
1100
- line--;
1101
- if (line < 0)
1102
- throw new Error(LINE_GTR_ZERO);
1103
- if (column < 0)
1104
- throw new Error(COL_GTR_EQ_ZERO);
1105
- const decoded = decodedMappings(map);
1106
- if (line >= decoded.length)
1107
- return OMapping(null, null, null, null);
1108
- const segments = decoded[line];
1109
- const index2 = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
1110
- if (index2 === -1)
1111
- return OMapping(null, null, null, null);
1112
- const segment = segments[index2];
1113
- if (segment.length === 1)
1114
- return OMapping(null, null, null, null);
1115
- const { names, resolvedSources } = map;
1116
- return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
1117
- }
1118
- function generatedPositionFor(map, needle) {
1119
- const { source, line, column, bias } = needle;
1120
- return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);
1121
- }
1122
- function allGeneratedPositionsFor(map, needle) {
1123
- const { source, line, column, bias } = needle;
1124
- return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);
1125
- }
1126
- function eachMapping(map, cb) {
1127
- const decoded = decodedMappings(map);
1128
- const { names, resolvedSources } = map;
1129
- for (let i = 0; i < decoded.length; i++) {
1130
- const line = decoded[i];
1131
- for (let j = 0; j < line.length; j++) {
1132
- const seg = line[j];
1133
- const generatedLine = i + 1;
1134
- const generatedColumn = seg[0];
1135
- let source = null;
1136
- let originalLine = null;
1137
- let originalColumn = null;
1138
- let name = null;
1139
- if (seg.length !== 1) {
1140
- source = resolvedSources[seg[1]];
1141
- originalLine = seg[2] + 1;
1142
- originalColumn = seg[3];
1143
- }
1144
- if (seg.length === 5)
1145
- name = names[seg[4]];
1146
- cb({
1147
- generatedLine,
1148
- generatedColumn,
1149
- source,
1150
- originalLine,
1151
- originalColumn,
1152
- name
1153
- });
1154
- }
1155
- }
1156
- }
1157
- function sourceIndex(map, source) {
1158
- const { sources, resolvedSources } = map;
1159
- let index2 = sources.indexOf(source);
1160
- if (index2 === -1)
1161
- index2 = resolvedSources.indexOf(source);
1162
- return index2;
1163
- }
1164
- function sourceContentFor(map, source) {
1165
- const { sourcesContent } = map;
1166
- if (sourcesContent == null)
1167
- return null;
1168
- const index2 = sourceIndex(map, source);
1169
- return index2 === -1 ? null : sourcesContent[index2];
1170
- }
1171
- function isIgnored(map, source) {
1172
- const { ignoreList } = map;
1173
- if (ignoreList == null)
1174
- return false;
1175
- const index2 = sourceIndex(map, source);
1176
- return index2 === -1 ? false : ignoreList.includes(index2);
1177
- }
1178
- function presortedDecodedMap(map, mapUrl) {
1179
- const tracer = new TraceMap2(clone(map, []), mapUrl);
1180
- cast(tracer)._decoded = map.mappings;
1181
- return tracer;
1182
- }
1183
- function decodedMap(map) {
1184
- return clone(map, decodedMappings(map));
1185
- }
1186
- function encodedMap(map) {
1187
- return clone(map, encodedMappings(map));
1188
- }
1189
- function clone(map, mappings) {
1190
- return {
1191
- version: map.version,
1192
- file: map.file,
1193
- names: map.names,
1194
- sourceRoot: map.sourceRoot,
1195
- sources: map.sources,
1196
- sourcesContent: map.sourcesContent,
1197
- mappings,
1198
- ignoreList: map.ignoreList || map.x_google_ignoreList
1199
- };
1200
- }
1201
- function OMapping(source, line, column, name) {
1202
- return { source, line, column, name };
1203
- }
1204
- function GMapping(line, column) {
1205
- return { line, column };
1206
- }
1207
- function traceSegmentInternal(segments, memo, line, column, bias) {
1208
- let index2 = memoizedBinarySearch(segments, column, memo, line);
1209
- if (found) {
1210
- index2 = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index2);
1211
- } else if (bias === LEAST_UPPER_BOUND)
1212
- index2++;
1213
- if (index2 === -1 || index2 === segments.length)
1214
- return -1;
1215
- return index2;
1216
- }
1217
- function sliceGeneratedPositions(segments, memo, line, column, bias) {
1218
- let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);
1219
- if (!found && bias === LEAST_UPPER_BOUND)
1220
- min++;
1221
- if (min === -1 || min === segments.length)
1222
- return [];
1223
- const matchedColumn = found ? column : segments[min][COLUMN];
1224
- if (!found)
1225
- min = lowerBound(segments, matchedColumn, min);
1226
- const max = upperBound(segments, matchedColumn, min);
1227
- const result = [];
1228
- for (; min <= max; min++) {
1229
- const segment = segments[min];
1230
- result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));
1231
- }
1232
- return result;
1233
- }
1234
- function generatedPosition(map, source, line, column, bias, all) {
1235
- var _a;
1236
- line--;
1237
- if (line < 0)
1238
- throw new Error(LINE_GTR_ZERO);
1239
- if (column < 0)
1240
- throw new Error(COL_GTR_EQ_ZERO);
1241
- const { sources, resolvedSources } = map;
1242
- let sourceIndex2 = sources.indexOf(source);
1243
- if (sourceIndex2 === -1)
1244
- sourceIndex2 = resolvedSources.indexOf(source);
1245
- if (sourceIndex2 === -1)
1246
- return all ? [] : GMapping(null, null);
1247
- const generated = (_a = cast(map))._bySources || (_a._bySources = buildBySources(decodedMappings(map), cast(map)._bySourceMemos = sources.map(memoizedState)));
1248
- const segments = generated[sourceIndex2][line];
1249
- if (segments == null)
1250
- return all ? [] : GMapping(null, null);
1251
- const memo = cast(map)._bySourceMemos[sourceIndex2];
1252
- if (all)
1253
- return sliceGeneratedPositions(segments, memo, line, column, bias);
1254
- const index2 = traceSegmentInternal(segments, memo, line, column, bias);
1255
- if (index2 === -1)
1256
- return GMapping(null, null);
1257
- const segment = segments[index2];
1258
- return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);
1259
- }
1260
- exports2.AnyMap = AnyMap;
1261
- exports2.GREATEST_LOWER_BOUND = GREATEST_LOWER_BOUND;
1262
- exports2.LEAST_UPPER_BOUND = LEAST_UPPER_BOUND;
1263
- exports2.TraceMap = TraceMap2;
1264
- exports2.allGeneratedPositionsFor = allGeneratedPositionsFor;
1265
- exports2.decodedMap = decodedMap;
1266
- exports2.decodedMappings = decodedMappings;
1267
- exports2.eachMapping = eachMapping;
1268
- exports2.encodedMap = encodedMap;
1269
- exports2.encodedMappings = encodedMappings;
1270
- exports2.generatedPositionFor = generatedPositionFor;
1271
- exports2.isIgnored = isIgnored;
1272
- exports2.originalPositionFor = originalPositionFor2;
1273
- exports2.presortedDecodedMap = presortedDecodedMap;
1274
- exports2.sourceContentFor = sourceContentFor;
1275
- exports2.traceSegment = traceSegment;
1276
- });
1277
- })(traceMapping_umd$1, traceMapping_umd$1.exports);
1278
- return traceMapping_umd$1.exports;
1279
- }
1280
- var traceMapping_umdExports = requireTraceMapping_umd();
1281
- function notNullish(v) {
1282
- return v != null;
1283
- }
1284
- const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
1285
- const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
1286
- const stackIgnorePatterns = [
1287
- "node:internal",
1288
- /\/packages\/\w+\/dist\//,
1289
- /\/@vitest\/\w+\/dist\//,
1290
- "/vitest/dist/",
1291
- "/vitest/src/",
1292
- "/vite-node/dist/",
1293
- "/vite-node/src/",
1294
- "/node_modules/chai/",
1295
- "/node_modules/tinypool/",
1296
- "/node_modules/tinyspy/",
1297
- // browser related deps
1298
- "/deps/chunk-",
1299
- "/deps/@vitest",
1300
- "/deps/loupe",
1301
- "/deps/chai",
1302
- /node:\w+/,
1303
- /__vitest_test__/,
1304
- /__vitest_browser__/,
1305
- /\/deps\/vitest_/
1306
- ];
1307
- function extractLocation(urlLike) {
1308
- if (!urlLike.includes(":")) {
1309
- return [urlLike];
1310
- }
1311
- const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/;
1312
- const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, ""));
1313
- if (!parts) {
1314
- return [urlLike];
1315
- }
1316
- let url2 = parts[1];
1317
- if (url2.startsWith("async ")) {
1318
- url2 = url2.slice(6);
1319
- }
1320
- if (url2.startsWith("http:") || url2.startsWith("https:")) {
1321
- const urlObj = new URL(url2);
1322
- urlObj.searchParams.delete("import");
1323
- urlObj.searchParams.delete("browserv");
1324
- url2 = urlObj.pathname + urlObj.hash + urlObj.search;
1325
- }
1326
- if (url2.startsWith("/@fs/")) {
1327
- const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url2);
1328
- url2 = url2.slice(isWindows ? 5 : 4);
1329
- }
1330
- return [url2, parts[2] || void 0, parts[3] || void 0];
1331
- }
1332
- function parseSingleFFOrSafariStack(raw) {
1333
- let line = raw.trim();
1334
- if (SAFARI_NATIVE_CODE_REGEXP.test(line)) {
1335
- return null;
1336
- }
1337
- if (line.includes(" > eval")) {
1338
- line = line.replace(
1339
- / line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,
1340
- ":$1"
1341
- );
1342
- }
1343
- if (!line.includes("@") && !line.includes(":")) {
1344
- return null;
1345
- }
1346
- const functionNameRegex = /((.*".+"[^@]*)?[^@]*)(@)/;
1347
- const matches = line.match(functionNameRegex);
1348
- const functionName = matches && matches[1] ? matches[1] : void 0;
1349
- const [url2, lineNumber, columnNumber] = extractLocation(
1350
- line.replace(functionNameRegex, "")
1351
- );
1352
- if (!url2 || !lineNumber || !columnNumber) {
1353
- return null;
1354
- }
1355
- return {
1356
- file: url2,
1357
- method: functionName || "",
1358
- line: Number.parseInt(lineNumber),
1359
- column: Number.parseInt(columnNumber)
1360
- };
1361
- }
1362
- function parseSingleV8Stack(raw) {
1363
- let line = raw.trim();
1364
- if (!CHROME_IE_STACK_REGEXP.test(line)) {
1365
- return null;
1366
- }
1367
- if (line.includes("(eval ")) {
1368
- line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, "");
1369
- }
1370
- let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, "");
1371
- const location2 = sanitizedLine.match(/ (\(.+\)$)/);
1372
- sanitizedLine = location2 ? sanitizedLine.replace(location2[0], "") : sanitizedLine;
1373
- const [url2, lineNumber, columnNumber] = extractLocation(
1374
- location2 ? location2[1] : sanitizedLine
1375
- );
1376
- let method = location2 && sanitizedLine || "";
1377
- let file = url2 && ["eval", "<anonymous>"].includes(url2) ? void 0 : url2;
1378
- if (!file || !lineNumber || !columnNumber) {
1379
- return null;
1380
- }
1381
- if (method.startsWith("async ")) {
1382
- method = method.slice(6);
1383
- }
1384
- if (file.startsWith("file://")) {
1385
- file = file.slice(7);
1386
- }
1387
- file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file);
1388
- if (method) {
1389
- method = method.replace(/__vite_ssr_import_\d+__\./g, "");
1390
- }
1391
- return {
1392
- method,
1393
- file,
1394
- line: Number.parseInt(lineNumber),
1395
- column: Number.parseInt(columnNumber)
1396
- };
1397
- }
1398
- function createStackString(stacks) {
1399
- return stacks.map((stack) => {
1400
- const line = `${stack.file}:${stack.line}:${stack.column}`;
1401
- if (stack.method) {
1402
- return ` at ${stack.method}(${line})`;
1403
- }
1404
- return ` at ${line}`;
1405
- }).join("\n");
1406
- }
1407
- function parseStacktrace(stack, options = {}) {
1408
- const { ignoreStackEntries = stackIgnorePatterns } = options;
1409
- const stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack);
1410
- return stacks.map((stack2) => {
1411
- var _a;
1412
- if (options.getUrlId) {
1413
- stack2.file = options.getUrlId(stack2.file);
1414
- }
1415
- const map = (_a = options.getSourceMap) == null ? void 0 : _a.call(options, stack2.file);
1416
- if (!map || typeof map !== "object" || !map.version) {
1417
- return shouldFilter(ignoreStackEntries, stack2.file) ? null : stack2;
1418
- }
1419
- const traceMap = new traceMapping_umdExports.TraceMap(map);
1420
- const { line, column, source, name } = traceMapping_umdExports.originalPositionFor(traceMap, stack2);
1421
- let file = stack2.file;
1422
- if (source) {
1423
- const fileUrl = stack2.file.startsWith("file://") ? stack2.file : `file://${stack2.file}`;
1424
- const sourceRootUrl = map.sourceRoot ? new URL(map.sourceRoot, fileUrl) : fileUrl;
1425
- file = new URL(source, sourceRootUrl).pathname;
1426
- if (file.match(/\/\w:\//)) {
1427
- file = file.slice(1);
1428
- }
1429
- }
1430
- if (shouldFilter(ignoreStackEntries, file)) {
1431
- return null;
1432
- }
1433
- if (line != null && column != null) {
1434
- return {
1435
- line,
1436
- column,
1437
- file,
1438
- method: name || stack2.method
1439
- };
1440
- }
1441
- return stack2;
1442
- }).filter((s) => s != null);
1443
- }
1444
- function shouldFilter(ignoreStackEntries, file) {
1445
- return ignoreStackEntries.some((p2) => file.match(p2));
1446
- }
1447
- function parseFFOrSafariStackTrace(stack) {
1448
- return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish);
1449
- }
1450
- function parseV8Stacktrace(stack) {
1451
- return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish);
1452
- }
1453
- class VitestBrowserSnapshotEnvironment {
1454
- constructor() {
1455
- __publicField(this, "sourceMaps", /* @__PURE__ */ new Map());
1456
- __publicField(this, "traceMaps", /* @__PURE__ */ new Map());
1457
- }
1458
- addSourceMap(filepath, map) {
1459
- this.sourceMaps.set(filepath, map);
1460
- }
1461
- getVersion() {
1462
- return "1";
1463
- }
1464
- getHeader() {
1465
- return `// Vitest Snapshot v${this.getVersion()}, https://vitest.dev/guide/snapshot.html`;
1466
- }
1467
- readSnapshotFile(filepath) {
1468
- return rpc$1().readSnapshotFile(filepath);
1469
- }
1470
- saveSnapshotFile(filepath, snapshot) {
1471
- return rpc$1().saveSnapshotFile(filepath, snapshot);
1472
- }
1473
- resolvePath(filepath) {
1474
- return rpc$1().resolveSnapshotPath(filepath);
1475
- }
1476
- resolveRawPath(testPath, rawPath) {
1477
- return rpc$1().resolveSnapshotRawPath(testPath, rawPath);
1478
- }
1479
- removeSnapshotFile(filepath) {
1480
- return rpc$1().removeSnapshotFile(filepath);
1481
- }
1482
- processStackTrace(stack) {
1483
- const map = this.sourceMaps.get(stack.file);
1484
- if (!map) {
1485
- return stack;
1486
- }
1487
- let traceMap = this.traceMaps.get(stack.file);
1488
- if (!traceMap) {
1489
- traceMap = new TraceMap(map);
1490
- this.traceMaps.set(stack.file, traceMap);
1491
- }
1492
- const { line, column } = originalPositionFor(traceMap, stack);
1493
- if (line != null && column != null) {
1494
- return { ...stack, line, column };
1495
- }
1496
- return stack;
1497
- }
1498
- }
1499
- function rpc$1() {
1500
- return globalThis.__vitest_worker__.rpc;
1501
- }
1502
- const browserHashMap = /* @__PURE__ */ new Map();
1503
- function createBrowserRunner(runnerClass, mocker, state, coverageModule) {
1504
- return class BrowserTestRunner extends runnerClass {
1505
- constructor(options) {
1506
- super(options.config);
1507
- __publicField(this, "config");
1508
- __publicField(this, "hashMap", browserHashMap);
1509
- __publicField(this, "sourceMapCache", /* @__PURE__ */ new Map());
1510
- __publicField(this, "method", "run");
1511
- __publicField(this, "onBeforeTryTask", async (...args) => {
1512
- var _a;
1513
- await userEvent.cleanup();
1514
- await ((_a = super.onBeforeTryTask) == null ? void 0 : _a.call(this, ...args));
1515
- });
1516
- __publicField(this, "onAfterRunTask", async (task) => {
1517
- var _a, _b;
1518
- await ((_a = super.onAfterRunTask) == null ? void 0 : _a.call(this, task));
1519
- if (this.config.bail && ((_b = task.result) == null ? void 0 : _b.state) === "fail") {
1520
- const previousFailures = await rpc$2().getCountOfFailedTests();
1521
- const currentFailures = 1 + previousFailures;
1522
- if (currentFailures >= this.config.bail) {
1523
- rpc$2().cancelCurrentRun("test-failure");
1524
- this.cancel("test-failure");
1525
- }
1526
- }
1527
- });
1528
- __publicField(this, "onTaskFinished", async (task) => {
1529
- var _a, _b;
1530
- if (this.config.browser.screenshotFailures && document.body.clientHeight > 0 && ((_a = task.result) == null ? void 0 : _a.state) === "fail") {
1531
- const screenshot = await page.screenshot(
1532
- {
1533
- timeout: ((_b = this.config.browser.providerOptions) == null ? void 0 : _b.actionTimeout) ?? 5e3
1534
- }
1535
- /** TODO */
1536
- ).catch((err) => {
1537
- console.error("[vitest] Failed to take a screenshot", err);
1538
- });
1539
- if (screenshot) {
1540
- task.meta.failScreenshotPath = screenshot;
1541
- }
1542
- }
1543
- });
1544
- __publicField(this, "cancel", (reason) => {
1545
- var _a;
1546
- (_a = super.cancel) == null ? void 0 : _a.call(this, reason);
1547
- globalChannel.postMessage({ type: "cancel", reason });
1548
- });
1549
- __publicField(this, "onBeforeRunSuite", async (suite) => {
1550
- var _a;
1551
- await Promise.all([
1552
- (_a = super.onBeforeRunSuite) == null ? void 0 : _a.call(this, suite),
1553
- (async () => {
1554
- if ("filepath" in suite) {
1555
- const map = await rpc$2().getBrowserFileSourceMap(suite.filepath);
1556
- this.sourceMapCache.set(suite.filepath, map);
1557
- const snapshotEnvironment = this.config.snapshotOptions.snapshotEnvironment;
1558
- if (snapshotEnvironment instanceof VitestBrowserSnapshotEnvironment) {
1559
- snapshotEnvironment.addSourceMap(suite.filepath, map);
1560
- }
1561
- }
1562
- })()
1563
- ]);
1564
- });
1565
- __publicField(this, "onAfterRunFiles", async (files) => {
1566
- var _a, _b;
1567
- const [coverage] = await Promise.all([
1568
- (_a = coverageModule == null ? void 0 : coverageModule.takeCoverage) == null ? void 0 : _a.call(coverageModule),
1569
- mocker.invalidate(),
1570
- (_b = super.onAfterRunFiles) == null ? void 0 : _b.call(this, files)
1571
- ]);
1572
- if (coverage) {
1573
- await rpc$2().onAfterSuiteRun({
1574
- coverage,
1575
- testFiles: files.map((file) => file.name),
1576
- transformMode: "browser",
1577
- projectName: this.config.name
1578
- });
1579
- }
1580
- });
1581
- __publicField(this, "onCollectStart", (file) => {
1582
- return rpc$2().onQueued(this.method, file);
1583
- });
1584
- __publicField(this, "onCollected", async (files) => {
1585
- files.forEach((file) => {
1586
- file.prepareDuration = state.durations.prepare;
1587
- file.environmentLoad = state.durations.environment;
1588
- state.durations.prepare = 0;
1589
- state.durations.environment = 0;
1590
- });
1591
- if (this.config.includeTaskLocation) {
1592
- try {
1593
- await updateTestFilesLocations(files, this.sourceMapCache);
1594
- } catch {
1595
- }
1596
- }
1597
- return rpc$2().onCollected(this.method, files);
1598
- });
1599
- __publicField(this, "onTestAnnotate", (test, annotation) => {
1600
- if (annotation.location) {
1601
- const map = this.sourceMapCache.get(annotation.location.file);
1602
- if (!map) {
1603
- return rpc$2().onTaskAnnotate(test.id, annotation);
1604
- }
1605
- const traceMap = new TraceMap(map);
1606
- const { line, column, source } = originalPositionFor(traceMap, annotation.location);
1607
- if (line != null && column != null && source != null) {
1608
- let file = annotation.location.file;
1609
- if (source) {
1610
- const fileUrl = annotation.location.file.startsWith("file://") ? annotation.location.file : `file://${annotation.location.file}`;
1611
- const sourceRootUrl = map.sourceRoot ? new URL(map.sourceRoot, fileUrl) : fileUrl;
1612
- file = new URL(source, sourceRootUrl).pathname;
1613
- }
1614
- annotation.location = {
1615
- line,
1616
- column: column + 1,
1617
- // if the file path is on windows, we need to remove the starting slash
1618
- file: file.match(/\/\w:\//) ? file.slice(1) : file
1619
- };
1620
- }
1621
- }
1622
- return rpc$2().onTaskAnnotate(test.id, annotation);
1623
- });
1624
- __publicField(this, "onTaskUpdate", (task, events) => {
1625
- return rpc$2().onTaskUpdate(this.method, task, events);
1626
- });
1627
- __publicField(this, "importFile", async (filepath) => {
1628
- let hash = this.hashMap.get(filepath);
1629
- if (!hash) {
1630
- hash = Date.now().toString();
1631
- this.hashMap.set(filepath, hash);
1632
- }
1633
- const prefix = `/${/^\w:/.test(filepath) ? "@fs/" : ""}`;
1634
- const query = `browserv=${hash}`;
1635
- const importpath = `${prefix}${filepath}?${query}`.replace(/\/+/g, "/");
1636
- try {
1637
- await import(
1638
- /* @vite-ignore */
1639
- importpath
1640
- );
1641
- } catch (err) {
1642
- throw new Error(`Failed to import test file ${filepath}`, { cause: err });
1643
- }
1644
- });
1645
- this.config = options.config;
1646
- }
1647
- setMethod(method) {
1648
- this.method = method;
1649
- }
1650
- };
1651
- }
1652
- let cachedRunner = null;
1653
- function getBrowserRunner() {
1654
- return cachedRunner;
1655
- }
1656
- async function initiateRunner(state, mocker, config) {
1657
- if (cachedRunner) {
1658
- return cachedRunner;
1659
- }
1660
- const runnerClass = config.mode === "test" ? VitestTestRunner : NodeBenchmarkRunner;
1661
- const BrowserRunner = createBrowserRunner(runnerClass, mocker, state, {
1662
- takeCoverage: () => takeCoverageInsideWorker(config.coverage, executor)
1663
- });
1664
- if (!config.snapshotOptions.snapshotEnvironment) {
1665
- config.snapshotOptions.snapshotEnvironment = new VitestBrowserSnapshotEnvironment();
1666
- }
1667
- const runner = new BrowserRunner({
1668
- config
1669
- });
1670
- cachedRunner = runner;
1671
- onCancel.then((reason) => {
1672
- var _a;
1673
- (_a = runner.cancel) == null ? void 0 : _a.call(runner, reason);
1674
- });
1675
- const [diffOptions] = await Promise.all([
1676
- loadDiffConfig(config, executor),
1677
- loadSnapshotSerializers(config, executor)
1678
- ]);
1679
- runner.config.diffOptions = diffOptions;
1680
- getWorkerState().onFilterStackTrace = (stack) => {
1681
- const stacks = parseStacktrace(stack, {
1682
- getSourceMap(file) {
1683
- return runner.sourceMapCache.get(file);
1684
- }
1685
- });
1686
- return createStackString(stacks);
1687
- };
1688
- return runner;
1689
- }
1690
- async function getTraceMap(file, sourceMaps) {
1691
- const result = sourceMaps.get(file) || await rpc$2().getBrowserFileSourceMap(file).then((map) => {
1692
- sourceMaps.set(file, map);
1693
- return map;
1694
- });
1695
- if (!result) {
1696
- return null;
1697
- }
1698
- return new TraceMap(result);
1699
- }
1700
- async function updateTestFilesLocations(files, sourceMaps) {
1701
- const promises2 = files.map(async (file) => {
1702
- const traceMap = await getTraceMap(file.filepath, sourceMaps);
1703
- if (!traceMap) {
1704
- return null;
1705
- }
1706
- const updateLocation = (task) => {
1707
- if (task.location) {
1708
- const { line, column } = originalPositionFor(traceMap, task.location);
1709
- if (line != null && column != null) {
1710
- task.location = { line, column: task.each ? column : column + 1 };
1711
- }
1712
- }
1713
- if ("tasks" in task) {
1714
- task.tasks.forEach(updateLocation);
1715
- }
1716
- };
1717
- file.tasks.forEach(updateLocation);
1718
- return null;
1719
- });
1720
- await Promise.all(promises2);
1721
- }
1722
- const { Date: Date$1, console: console$1, performance: performance$1 } = globalThis;
1723
- function setupConsoleLogSpy() {
1724
- const {
1725
- log,
1726
- info,
1727
- error,
1728
- dir,
1729
- dirxml,
1730
- trace,
1731
- time,
1732
- timeEnd,
1733
- timeLog,
1734
- warn,
1735
- debug: debug2,
1736
- count,
1737
- countReset
1738
- } = console$1;
1739
- console$1.log = stdout(log);
1740
- console$1.debug = stdout(debug2);
1741
- console$1.info = stdout(info);
1742
- console$1.error = stderr(error);
1743
- console$1.warn = stderr(warn);
1744
- console$1.dir = (item, options) => {
1745
- dir(item, options);
1746
- sendLog("stdout", formatInput(item));
1747
- };
1748
- console$1.dirxml = (...args) => {
1749
- dirxml(...args);
1750
- sendLog("stdout", processLog(args));
1751
- };
1752
- console$1.trace = (...args) => {
1753
- var _a;
1754
- trace(...args);
1755
- const content = processLog(args);
1756
- const error2 = new Error("$$Trace");
1757
- const processor = ((_a = globalThis.__vitest_worker__) == null ? void 0 : _a.onFilterStackTrace) || ((s) => s || "");
1758
- const stack = processor(error2.stack || "");
1759
- sendLog("stderr", `${content}
1760
- ${stack}`, true);
1761
- };
1762
- const timeLabels = {};
1763
- console$1.time = (label = "default") => {
1764
- time(label);
1765
- const now2 = performance$1.now();
1766
- timeLabels[label] = now2;
1767
- };
1768
- console$1.timeLog = (label = "default") => {
1769
- timeLog(label);
1770
- if (!(label in timeLabels)) {
1771
- sendLog("stderr", `Timer "${label}" does not exist`);
1772
- } else {
1773
- sendLog("stdout", `${label}: ${timeLabels[label]} ms`);
1774
- }
1775
- };
1776
- console$1.timeEnd = (label = "default") => {
1777
- timeEnd(label);
1778
- const end = performance$1.now();
1779
- const start = timeLabels[label];
1780
- if (!(label in timeLabels)) {
1781
- sendLog("stderr", `Timer "${label}" does not exist`);
1782
- } else if (typeof start !== "undefined") {
1783
- const duration = end - start;
1784
- sendLog("stdout", `${label}: ${duration} ms`);
1785
- }
1786
- };
1787
- const countLabels = {};
1788
- console$1.count = (label = "default") => {
1789
- count(label);
1790
- const counter = (countLabels[label] ?? 0) + 1;
1791
- countLabels[label] = counter;
1792
- sendLog("stdout", `${label}: ${counter}`);
1793
- };
1794
- console$1.countReset = (label = "default") => {
1795
- countReset(label);
1796
- countLabels[label] = 0;
1797
- };
1798
- }
1799
- function stdout(base) {
1800
- return (...args) => {
1801
- base(...args);
1802
- if (args[0] === "[WDIO]") {
1803
- if (args[1] === "newShadowRoot" || args[1] === "removeShadowRoot") {
1804
- return;
1805
- }
1806
- }
1807
- sendLog("stdout", processLog(args));
1808
- };
1809
- }
1810
- function stderr(base) {
1811
- return (...args) => {
1812
- base(...args);
1813
- sendLog("stderr", processLog(args));
1814
- };
1815
- }
1816
- function formatInput(input) {
1817
- if (typeof input === "object") {
1818
- return stringify(input, void 0, {
1819
- printBasicPrototype: false,
1820
- escapeString: false
1821
- });
1822
- }
1823
- return format(input);
1824
- }
1825
- function processLog(args) {
1826
- return args.map(formatInput).join(" ");
1827
- }
1828
- function sendLog(type, content, disableStack) {
1829
- var _a, _b, _c;
1830
- if (content.startsWith("[vite]")) {
1831
- return;
1832
- }
1833
- const unknownTestId = "__vitest__unknown_test__";
1834
- const taskId = ((_b = (_a = globalThis.__vitest_worker__) == null ? void 0 : _a.current) == null ? void 0 : _b.id) ?? unknownTestId;
1835
- const origin = getConfig().printConsoleTrace && !disableStack ? (_c = new Error("STACK_TRACE").stack) == null ? void 0 : _c.split("\n").slice(1).join("\n") : void 0;
1836
- const runner = getBrowserRunner();
1837
- rpc$2().sendLog((runner == null ? void 0 : runner.method) || "run", {
1838
- origin,
1839
- content,
1840
- browser: true,
1841
- time: Date$1.now(),
1842
- taskId,
1843
- type,
1844
- size: content.length
1845
- });
1846
- }
1847
- class MockerRegistry {
1848
- constructor() {
1849
- __publicField(this, "registryByUrl", /* @__PURE__ */ new Map());
1850
- __publicField(this, "registryById", /* @__PURE__ */ new Map());
1851
- }
1852
- clear() {
1853
- this.registryByUrl.clear();
1854
- this.registryById.clear();
1855
- }
1856
- keys() {
1857
- return this.registryByUrl.keys();
1858
- }
1859
- add(mock) {
1860
- this.registryByUrl.set(mock.url, mock);
1861
- this.registryById.set(mock.id, mock);
1862
- }
1863
- register(typeOrEvent, raw, id, url2, factoryOrRedirect) {
1864
- const type = typeof typeOrEvent === "object" ? typeOrEvent.type : typeOrEvent;
1865
- if (typeof typeOrEvent === "object") {
1866
- const event = typeOrEvent;
1867
- if (event instanceof AutomockedModule || event instanceof AutospiedModule || event instanceof ManualMockedModule || event instanceof RedirectedModule) {
1868
- 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.`);
1869
- }
1870
- if (event.type === "automock") {
1871
- const module = AutomockedModule.fromJSON(event);
1872
- this.add(module);
1873
- return module;
1874
- } else if (event.type === "autospy") {
1875
- const module = AutospiedModule.fromJSON(event);
1876
- this.add(module);
1877
- return module;
1878
- } else if (event.type === "redirect") {
1879
- const module = RedirectedModule.fromJSON(event);
1880
- this.add(module);
1881
- return module;
1882
- } else if (event.type === "manual") {
1883
- throw new Error(`Cannot set serialized manual mock. Define a factory function manually with \`ManualMockedModule.fromJSON()\`.`);
1884
- } else {
1885
- throw new Error(`Unknown mock type: ${event.type}`);
1886
- }
1887
- }
1888
- if (typeof raw !== "string") {
1889
- throw new TypeError("[vitest] Mocks require a raw string.");
1890
- }
1891
- if (typeof url2 !== "string") {
1892
- throw new TypeError("[vitest] Mocks require a url string.");
1893
- }
1894
- if (typeof id !== "string") {
1895
- throw new TypeError("[vitest] Mocks require an id string.");
1896
- }
1897
- if (type === "manual") {
1898
- if (typeof factoryOrRedirect !== "function") {
1899
- throw new TypeError("[vitest] Manual mocks require a factory function.");
1900
- }
1901
- const mock = new ManualMockedModule(raw, id, url2, factoryOrRedirect);
1902
- this.add(mock);
1903
- return mock;
1904
- } else if (type === "automock" || type === "autospy") {
1905
- const mock = type === "automock" ? new AutomockedModule(raw, id, url2) : new AutospiedModule(raw, id, url2);
1906
- this.add(mock);
1907
- return mock;
1908
- } else if (type === "redirect") {
1909
- if (typeof factoryOrRedirect !== "string") {
1910
- throw new TypeError("[vitest] Redirect mocks require a redirect string.");
1911
- }
1912
- const mock = new RedirectedModule(raw, id, url2, factoryOrRedirect);
1913
- this.add(mock);
1914
- return mock;
1915
- } else {
1916
- throw new Error(`[vitest] Unknown mock type: ${type}`);
1917
- }
1918
- }
1919
- delete(id) {
1920
- this.registryByUrl.delete(id);
1921
- }
1922
- get(id) {
1923
- return this.registryByUrl.get(id);
1924
- }
1925
- getById(id) {
1926
- return this.registryById.get(id);
1927
- }
1928
- has(id) {
1929
- return this.registryByUrl.has(id);
1930
- }
1931
- }
1932
- class AutomockedModule {
1933
- constructor(raw, id, url2) {
1934
- __publicField(this, "type", "automock");
1935
- this.raw = raw;
1936
- this.id = id;
1937
- this.url = url2;
1938
- }
1939
- static fromJSON(data) {
1940
- return new AutospiedModule(data.raw, data.id, data.url);
1941
- }
1942
- toJSON() {
1943
- return {
1944
- type: this.type,
1945
- url: this.url,
1946
- raw: this.raw,
1947
- id: this.id
1948
- };
1949
- }
1950
- }
1951
- class AutospiedModule {
1952
- constructor(raw, id, url2) {
1953
- __publicField(this, "type", "autospy");
1954
- this.raw = raw;
1955
- this.id = id;
1956
- this.url = url2;
1957
- }
1958
- static fromJSON(data) {
1959
- return new AutospiedModule(data.raw, data.id, data.url);
1960
- }
1961
- toJSON() {
1962
- return {
1963
- type: this.type,
1964
- url: this.url,
1965
- id: this.id,
1966
- raw: this.raw
1967
- };
1968
- }
1969
- }
1970
- class RedirectedModule {
1971
- constructor(raw, id, url2, redirect) {
1972
- __publicField(this, "type", "redirect");
1973
- this.raw = raw;
1974
- this.id = id;
1975
- this.url = url2;
1976
- this.redirect = redirect;
1977
- }
1978
- static fromJSON(data) {
1979
- return new RedirectedModule(data.raw, data.id, data.url, data.redirect);
1980
- }
1981
- toJSON() {
1982
- return {
1983
- type: this.type,
1984
- url: this.url,
1985
- raw: this.raw,
1986
- id: this.id,
1987
- redirect: this.redirect
1988
- };
1989
- }
1990
- }
1991
- class ManualMockedModule {
1992
- constructor(raw, id, url2, factory) {
1993
- __publicField(this, "cache");
1994
- __publicField(this, "type", "manual");
1995
- this.raw = raw;
1996
- this.id = id;
1997
- this.url = url2;
1998
- this.factory = factory;
1999
- }
2000
- async resolve() {
2001
- if (this.cache) {
2002
- return this.cache;
2003
- }
2004
- let exports;
2005
- try {
2006
- exports = await this.factory();
2007
- } catch (err) {
2008
- const vitestError = 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');
2009
- vitestError.cause = err;
2010
- throw vitestError;
2011
- }
2012
- if (exports === null || typeof exports !== "object" || Array.isArray(exports)) {
2013
- throw new TypeError(`[vitest] vi.mock("${this.raw}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`);
2014
- }
2015
- return this.cache = exports;
2016
- }
2017
- static fromJSON(data, factory) {
2018
- return new ManualMockedModule(data.raw, data.id, data.url, factory);
2019
- }
2020
- toJSON() {
2021
- return {
2022
- type: this.type,
2023
- url: this.url,
2024
- id: this.id,
2025
- raw: this.raw
2026
- };
2027
- }
2028
- }
2029
- function mockObject(options, object2, mockExports = {}) {
2030
- const finalizers = new Array();
2031
- const refs = new RefTracker();
2032
- const define = (container, key, value) => {
2033
- try {
2034
- container[key] = value;
2035
- return true;
2036
- } catch {
2037
- return false;
2038
- }
2039
- };
2040
- const mockPropertiesOf = (container, newContainer) => {
2041
- const containerType = getType(container);
2042
- const isModule = containerType === "Module" || !!container.__esModule;
2043
- for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, options.globalConstructors)) {
2044
- if (!isModule && descriptor.get) {
2045
- try {
2046
- Object.defineProperty(newContainer, property, descriptor);
2047
- } catch {
2048
- }
2049
- continue;
2050
- }
2051
- if (isSpecialProp(property, containerType)) {
2052
- continue;
2053
- }
2054
- const value = container[property];
2055
- const refId = refs.getId(value);
2056
- if (refId !== void 0) {
2057
- finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId)));
2058
- continue;
2059
- }
2060
- const type = getType(value);
2061
- if (Array.isArray(value)) {
2062
- define(newContainer, property, []);
2063
- continue;
2064
- }
2065
- const isFunction = type.includes("Function") && typeof value === "function";
2066
- if ((!isFunction || value._isMockFunction) && type !== "Object" && type !== "Module") {
2067
- define(newContainer, property, value);
2068
- continue;
2069
- }
2070
- if (!define(newContainer, property, isFunction ? value : {})) {
2071
- continue;
2072
- }
2073
- if (isFunction) {
2074
- let mockFunction = function() {
2075
- if (this instanceof newContainer[property]) {
2076
- for (const { key, descriptor: descriptor2 } of getAllMockableProperties(this, false, options.globalConstructors)) {
2077
- if (descriptor2.get) {
2078
- continue;
2079
- }
2080
- const value2 = this[key];
2081
- const type2 = getType(value2);
2082
- const isFunction2 = type2.includes("Function") && typeof value2 === "function";
2083
- if (isFunction2) {
2084
- const original = this[key];
2085
- const mock2 = spyOn(this, key).mockImplementation(original);
2086
- const origMockReset = mock2.mockReset;
2087
- mock2.mockRestore = mock2.mockReset = () => {
2088
- origMockReset.call(mock2);
2089
- mock2.mockImplementation(original);
2090
- return mock2;
2091
- };
2092
- }
2093
- }
2094
- }
2095
- };
2096
- if (!options.spyOn) {
2097
- throw new Error("[@vitest/mocker] `spyOn` is not defined. This is a Vitest error. Please open a new issue with reproduction.");
2098
- }
2099
- const spyOn = options.spyOn;
2100
- const mock = spyOn(newContainer, property);
2101
- if (options.type === "automock") {
2102
- mock.mockImplementation(mockFunction);
2103
- const origMockReset = mock.mockReset;
2104
- mock.mockRestore = mock.mockReset = () => {
2105
- origMockReset.call(mock);
2106
- mock.mockImplementation(mockFunction);
2107
- return mock;
2108
- };
2109
- }
2110
- Object.defineProperty(newContainer[property], "length", { value: 0 });
2111
- }
2112
- refs.track(value, newContainer[property]);
2113
- mockPropertiesOf(value, newContainer[property]);
2114
- }
2115
- };
2116
- const mockedObject = mockExports;
2117
- mockPropertiesOf(object2, mockedObject);
2118
- for (const finalizer of finalizers) {
2119
- finalizer();
2120
- }
2121
- return mockedObject;
2122
- }
2123
- class RefTracker {
2124
- constructor() {
2125
- __publicField(this, "idMap", /* @__PURE__ */ new Map());
2126
- __publicField(this, "mockedValueMap", /* @__PURE__ */ new Map());
2127
- }
2128
- getId(value) {
2129
- return this.idMap.get(value);
2130
- }
2131
- getMockedValue(id) {
2132
- return this.mockedValueMap.get(id);
2133
- }
2134
- track(originalValue, mockedValue) {
2135
- const newId = this.idMap.size;
2136
- this.idMap.set(originalValue, newId);
2137
- this.mockedValueMap.set(newId, mockedValue);
2138
- return newId;
2139
- }
2140
- }
2141
- function getType(value) {
2142
- return Object.prototype.toString.apply(value).slice(8, -1);
2143
- }
2144
- function isSpecialProp(prop, parentType) {
2145
- return parentType.includes("Function") && typeof prop === "string" && [
2146
- "arguments",
2147
- "callee",
2148
- "caller",
2149
- "length",
2150
- "name"
2151
- ].includes(prop);
2152
- }
2153
- function getAllMockableProperties(obj, isModule, constructors) {
2154
- const { Map: Map2, Object: Object2, Function: Function2, RegExp: RegExp2, Array: Array2 } = constructors;
2155
- const allProps = new Map2();
2156
- let curr = obj;
2157
- do {
2158
- if (curr === Object2.prototype || curr === Function2.prototype || curr === RegExp2.prototype) {
2159
- break;
2160
- }
2161
- collectOwnProperties(curr, (key) => {
2162
- const descriptor = Object2.getOwnPropertyDescriptor(curr, key);
2163
- if (descriptor) {
2164
- allProps.set(key, {
2165
- key,
2166
- descriptor
2167
- });
2168
- }
2169
- });
2170
- } while (curr = Object2.getPrototypeOf(curr));
2171
- if (isModule && !allProps.has("default") && "default" in obj) {
2172
- const descriptor = Object2.getOwnPropertyDescriptor(obj, "default");
2173
- if (descriptor) {
2174
- allProps.set("default", {
2175
- key: "default",
2176
- descriptor
2177
- });
2178
- }
2179
- }
2180
- return Array2.from(allProps.values());
2181
- }
2182
- function collectOwnProperties(obj, collector) {
2183
- const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
2184
- Object.getOwnPropertyNames(obj).forEach(collect);
2185
- Object.getOwnPropertySymbols(obj).forEach(collect);
2186
- }
2187
- const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
2188
- function normalizeWindowsPath(input = "") {
2189
- if (!input) {
2190
- return input;
2191
- }
2192
- return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
2193
- }
2194
- const _UNC_REGEX = /^[/\\]{2}/;
2195
- const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
2196
- const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
2197
- const _EXTNAME_RE = /.(\.[^./]+|\.)$/;
2198
- const normalize = function(path) {
2199
- if (path.length === 0) {
2200
- return ".";
2201
- }
2202
- path = normalizeWindowsPath(path);
2203
- const isUNCPath = path.match(_UNC_REGEX);
2204
- const isPathAbsolute = isAbsolute(path);
2205
- const trailingSeparator = path[path.length - 1] === "/";
2206
- path = normalizeString(path, !isPathAbsolute);
2207
- if (path.length === 0) {
2208
- if (isPathAbsolute) {
2209
- return "/";
2210
- }
2211
- return trailingSeparator ? "./" : ".";
2212
- }
2213
- if (trailingSeparator) {
2214
- path += "/";
2215
- }
2216
- if (_DRIVE_LETTER_RE.test(path)) {
2217
- path += "/";
2218
- }
2219
- if (isUNCPath) {
2220
- if (!isPathAbsolute) {
2221
- return `//./${path}`;
2222
- }
2223
- return `//${path}`;
2224
- }
2225
- return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
2226
- };
2227
- const join = function(...segments) {
2228
- let path = "";
2229
- for (const seg of segments) {
2230
- if (!seg) {
2231
- continue;
2232
- }
2233
- if (path.length > 0) {
2234
- const pathTrailing = path[path.length - 1] === "/";
2235
- const segLeading = seg[0] === "/";
2236
- const both = pathTrailing && segLeading;
2237
- if (both) {
2238
- path += seg.slice(1);
2239
- } else {
2240
- path += pathTrailing || segLeading ? seg : `/${seg}`;
2241
- }
2242
- } else {
2243
- path += seg;
2244
- }
2245
- }
2246
- return normalize(path);
2247
- };
2248
- function normalizeString(path, allowAboveRoot) {
2249
- let res = "";
2250
- let lastSegmentLength = 0;
2251
- let lastSlash = -1;
2252
- let dots = 0;
2253
- let char = null;
2254
- for (let index2 = 0; index2 <= path.length; ++index2) {
2255
- if (index2 < path.length) {
2256
- char = path[index2];
2257
- } else if (char === "/") {
2258
- break;
2259
- } else {
2260
- char = "/";
2261
- }
2262
- if (char === "/") {
2263
- if (lastSlash === index2 - 1 || dots === 1) ;
2264
- else if (dots === 2) {
2265
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
2266
- if (res.length > 2) {
2267
- const lastSlashIndex = res.lastIndexOf("/");
2268
- if (lastSlashIndex === -1) {
2269
- res = "";
2270
- lastSegmentLength = 0;
2271
- } else {
2272
- res = res.slice(0, lastSlashIndex);
2273
- lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
2274
- }
2275
- lastSlash = index2;
2276
- dots = 0;
2277
- continue;
2278
- } else if (res.length > 0) {
2279
- res = "";
2280
- lastSegmentLength = 0;
2281
- lastSlash = index2;
2282
- dots = 0;
2283
- continue;
2284
- }
2285
- }
2286
- if (allowAboveRoot) {
2287
- res += res.length > 0 ? "/.." : "..";
2288
- lastSegmentLength = 2;
2289
- }
2290
- } else {
2291
- if (res.length > 0) {
2292
- res += `/${path.slice(lastSlash + 1, index2)}`;
2293
- } else {
2294
- res = path.slice(lastSlash + 1, index2);
2295
- }
2296
- lastSegmentLength = index2 - lastSlash - 1;
2297
- }
2298
- lastSlash = index2;
2299
- dots = 0;
2300
- } else if (char === "." && dots !== -1) {
2301
- ++dots;
2302
- } else {
2303
- dots = -1;
2304
- }
2305
- }
2306
- return res;
2307
- }
2308
- const isAbsolute = function(p2) {
2309
- return _IS_ABSOLUTE_RE.test(p2);
2310
- };
2311
- const extname = function(p2) {
2312
- if (p2 === "..") return "";
2313
- const match = _EXTNAME_RE.exec(normalizeWindowsPath(p2));
2314
- return match && match[1] || "";
2315
- };
2316
- var f = {
2317
- reset: [0, 0],
2318
- bold: [1, 22, "\x1B[22m\x1B[1m"],
2319
- dim: [2, 22, "\x1B[22m\x1B[2m"],
2320
- italic: [3, 23],
2321
- underline: [4, 24],
2322
- inverse: [7, 27],
2323
- hidden: [8, 28],
2324
- strikethrough: [9, 29],
2325
- black: [30, 39],
2326
- red: [31, 39],
2327
- green: [32, 39],
2328
- yellow: [33, 39],
2329
- blue: [34, 39],
2330
- magenta: [35, 39],
2331
- cyan: [36, 39],
2332
- white: [37, 39],
2333
- gray: [90, 39],
2334
- bgBlack: [40, 49],
2335
- bgRed: [41, 49],
2336
- bgGreen: [42, 49],
2337
- bgYellow: [43, 49],
2338
- bgBlue: [44, 49],
2339
- bgMagenta: [45, 49],
2340
- bgCyan: [46, 49],
2341
- bgWhite: [47, 49],
2342
- blackBright: [90, 39],
2343
- redBright: [91, 39],
2344
- greenBright: [92, 39],
2345
- yellowBright: [93, 39],
2346
- blueBright: [94, 39],
2347
- magentaBright: [95, 39],
2348
- cyanBright: [96, 39],
2349
- whiteBright: [97, 39],
2350
- bgBlackBright: [100, 49],
2351
- bgRedBright: [101, 49],
2352
- bgGreenBright: [102, 49],
2353
- bgYellowBright: [103, 49],
2354
- bgBlueBright: [104, 49],
2355
- bgMagentaBright: [105, 49],
2356
- bgCyanBright: [106, 49],
2357
- bgWhiteBright: [107, 49]
2358
- }, h = Object.entries(f);
2359
- function a(n) {
2360
- return String(n);
2361
- }
2362
- a.open = "";
2363
- a.close = "";
2364
- function C(n = false) {
2365
- let e = typeof process != "undefined" ? process : void 0, i = (e == null ? void 0 : e.env) || {}, g = (e == null ? void 0 : e.argv) || [];
2366
- return !("NO_COLOR" in i || g.includes("--no-color")) && ("FORCE_COLOR" in i || g.includes("--color") || (e == null ? void 0 : e.platform) === "win32" || n && i.TERM !== "dumb" || "CI" in i) || typeof window != "undefined" && !!window.chrome;
2367
- }
2368
- function p(n = false) {
2369
- let e = C(n), i = (r, t, c, o) => {
2370
- let l = "", s = 0;
2371
- do
2372
- l += r.substring(s, o) + c, s = o + t.length, o = r.indexOf(t, s);
2373
- while (~o);
2374
- return l + r.substring(s);
2375
- }, g = (r, t, c = r) => {
2376
- let o = (l) => {
2377
- let s = String(l), b = s.indexOf(t, r.length);
2378
- return ~b ? r + i(s, t, c, b) + t : r + s + t;
2379
- };
2380
- return o.open = r, o.close = t, o;
2381
- }, u = {
2382
- isColorSupported: e
2383
- }, d = (r) => `\x1B[${r}m`;
2384
- for (let [r, t] of h)
2385
- u[r] = e ? g(
2386
- d(t[0]),
2387
- d(t[1]),
2388
- t[2]
2389
- ) : a;
2390
- return u;
2391
- }
2392
- p();
2393
- function _mergeNamespaces(n, m) {
2394
- m.forEach(function(e) {
2395
- e && typeof e !== "string" && !Array.isArray(e) && Object.keys(e).forEach(function(k) {
2396
- if (k !== "default" && !(k in n)) {
2397
- var d = Object.getOwnPropertyDescriptor(e, k);
2398
- Object.defineProperty(n, k, d.get ? d : {
2399
- enumerable: true,
2400
- get: function() {
2401
- return e[k];
2402
- }
2403
- });
2404
- }
2405
- });
2406
- });
2407
- return Object.freeze(n);
2408
- }
2409
- function getDefaultExportFromCjs(x) {
2410
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
2411
- }
2412
- var reactIs$1 = { exports: {} };
2413
- var reactIs_production = {};
2414
- /**
2415
- * @license React
2416
- * react-is.production.js
2417
- *
2418
- * Copyright (c) Meta Platforms, Inc. and affiliates.
2419
- *
2420
- * This source code is licensed under the MIT license found in the
2421
- * LICENSE file in the root directory of this source tree.
2422
- */
2423
- var hasRequiredReactIs_production;
2424
- function requireReactIs_production() {
2425
- if (hasRequiredReactIs_production) return reactIs_production;
2426
- hasRequiredReactIs_production = 1;
2427
- 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");
2428
- var 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");
2429
- function typeOf(object2) {
2430
- if ("object" === typeof object2 && null !== object2) {
2431
- var $$typeof = object2.$$typeof;
2432
- switch ($$typeof) {
2433
- case REACT_ELEMENT_TYPE:
2434
- switch (object2 = object2.type, object2) {
2435
- case REACT_FRAGMENT_TYPE:
2436
- case REACT_PROFILER_TYPE:
2437
- case REACT_STRICT_MODE_TYPE:
2438
- case REACT_SUSPENSE_TYPE:
2439
- case REACT_SUSPENSE_LIST_TYPE:
2440
- case REACT_VIEW_TRANSITION_TYPE:
2441
- return object2;
2442
- default:
2443
- switch (object2 = object2 && object2.$$typeof, object2) {
2444
- case REACT_CONTEXT_TYPE:
2445
- case REACT_FORWARD_REF_TYPE:
2446
- case REACT_LAZY_TYPE:
2447
- case REACT_MEMO_TYPE:
2448
- return object2;
2449
- case REACT_CONSUMER_TYPE:
2450
- return object2;
2451
- default:
2452
- return $$typeof;
2453
- }
2454
- }
2455
- case REACT_PORTAL_TYPE:
2456
- return $$typeof;
2457
- }
2458
- }
2459
- }
2460
- reactIs_production.ContextConsumer = REACT_CONSUMER_TYPE;
2461
- reactIs_production.ContextProvider = REACT_CONTEXT_TYPE;
2462
- reactIs_production.Element = REACT_ELEMENT_TYPE;
2463
- reactIs_production.ForwardRef = REACT_FORWARD_REF_TYPE;
2464
- reactIs_production.Fragment = REACT_FRAGMENT_TYPE;
2465
- reactIs_production.Lazy = REACT_LAZY_TYPE;
2466
- reactIs_production.Memo = REACT_MEMO_TYPE;
2467
- reactIs_production.Portal = REACT_PORTAL_TYPE;
2468
- reactIs_production.Profiler = REACT_PROFILER_TYPE;
2469
- reactIs_production.StrictMode = REACT_STRICT_MODE_TYPE;
2470
- reactIs_production.Suspense = REACT_SUSPENSE_TYPE;
2471
- reactIs_production.SuspenseList = REACT_SUSPENSE_LIST_TYPE;
2472
- reactIs_production.isContextConsumer = function(object2) {
2473
- return typeOf(object2) === REACT_CONSUMER_TYPE;
2474
- };
2475
- reactIs_production.isContextProvider = function(object2) {
2476
- return typeOf(object2) === REACT_CONTEXT_TYPE;
2477
- };
2478
- reactIs_production.isElement = function(object2) {
2479
- return "object" === typeof object2 && null !== object2 && object2.$$typeof === REACT_ELEMENT_TYPE;
2480
- };
2481
- reactIs_production.isForwardRef = function(object2) {
2482
- return typeOf(object2) === REACT_FORWARD_REF_TYPE;
2483
- };
2484
- reactIs_production.isFragment = function(object2) {
2485
- return typeOf(object2) === REACT_FRAGMENT_TYPE;
2486
- };
2487
- reactIs_production.isLazy = function(object2) {
2488
- return typeOf(object2) === REACT_LAZY_TYPE;
2489
- };
2490
- reactIs_production.isMemo = function(object2) {
2491
- return typeOf(object2) === REACT_MEMO_TYPE;
2492
- };
2493
- reactIs_production.isPortal = function(object2) {
2494
- return typeOf(object2) === REACT_PORTAL_TYPE;
2495
- };
2496
- reactIs_production.isProfiler = function(object2) {
2497
- return typeOf(object2) === REACT_PROFILER_TYPE;
2498
- };
2499
- reactIs_production.isStrictMode = function(object2) {
2500
- return typeOf(object2) === REACT_STRICT_MODE_TYPE;
2501
- };
2502
- reactIs_production.isSuspense = function(object2) {
2503
- return typeOf(object2) === REACT_SUSPENSE_TYPE;
2504
- };
2505
- reactIs_production.isSuspenseList = function(object2) {
2506
- return typeOf(object2) === REACT_SUSPENSE_LIST_TYPE;
2507
- };
2508
- reactIs_production.isValidElementType = function(type) {
2509
- 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;
2510
- };
2511
- reactIs_production.typeOf = typeOf;
2512
- return reactIs_production;
2513
- }
2514
- var hasRequiredReactIs$1;
2515
- function requireReactIs$1() {
2516
- if (hasRequiredReactIs$1) return reactIs$1.exports;
2517
- hasRequiredReactIs$1 = 1;
2518
- {
2519
- reactIs$1.exports = requireReactIs_production();
2520
- }
2521
- return reactIs$1.exports;
2522
- }
2523
- var reactIsExports$1 = requireReactIs$1();
2524
- var index$1 = /* @__PURE__ */ getDefaultExportFromCjs(reactIsExports$1);
2525
- var ReactIs19 = /* @__PURE__ */ _mergeNamespaces({
2526
- __proto__: null,
2527
- default: index$1
2528
- }, [reactIsExports$1]);
2529
- var reactIs = { exports: {} };
2530
- var reactIs_production_min = {};
2531
- /**
2532
- * @license React
2533
- * react-is.production.min.js
2534
- *
2535
- * Copyright (c) Facebook, Inc. and its affiliates.
2536
- *
2537
- * This source code is licensed under the MIT license found in the
2538
- * LICENSE file in the root directory of this source tree.
2539
- */
2540
- var hasRequiredReactIs_production_min;
2541
- function requireReactIs_production_min() {
2542
- if (hasRequiredReactIs_production_min) return reactIs_production_min;
2543
- hasRequiredReactIs_production_min = 1;
2544
- var b = Symbol.for("react.element"), c = Symbol.for("react.portal"), d = Symbol.for("react.fragment"), e = Symbol.for("react.strict_mode"), f2 = Symbol.for("react.profiler"), g = Symbol.for("react.provider"), h2 = Symbol.for("react.context"), k = Symbol.for("react.server_context"), l = Symbol.for("react.forward_ref"), m = Symbol.for("react.suspense"), n = Symbol.for("react.suspense_list"), p2 = Symbol.for("react.memo"), q = Symbol.for("react.lazy"), t = Symbol.for("react.offscreen"), u;
2545
- u = Symbol.for("react.module.reference");
2546
- function v(a2) {
2547
- if ("object" === typeof a2 && null !== a2) {
2548
- var r = a2.$$typeof;
2549
- switch (r) {
2550
- case b:
2551
- switch (a2 = a2.type, a2) {
2552
- case d:
2553
- case f2:
2554
- case e:
2555
- case m:
2556
- case n:
2557
- return a2;
2558
- default:
2559
- switch (a2 = a2 && a2.$$typeof, a2) {
2560
- case k:
2561
- case h2:
2562
- case l:
2563
- case q:
2564
- case p2:
2565
- case g:
2566
- return a2;
2567
- default:
2568
- return r;
2569
- }
2570
- }
2571
- case c:
2572
- return r;
2573
- }
2574
- }
2575
- }
2576
- reactIs_production_min.ContextConsumer = h2;
2577
- reactIs_production_min.ContextProvider = g;
2578
- reactIs_production_min.Element = b;
2579
- reactIs_production_min.ForwardRef = l;
2580
- reactIs_production_min.Fragment = d;
2581
- reactIs_production_min.Lazy = q;
2582
- reactIs_production_min.Memo = p2;
2583
- reactIs_production_min.Portal = c;
2584
- reactIs_production_min.Profiler = f2;
2585
- reactIs_production_min.StrictMode = e;
2586
- reactIs_production_min.Suspense = m;
2587
- reactIs_production_min.SuspenseList = n;
2588
- reactIs_production_min.isAsyncMode = function() {
2589
- return false;
2590
- };
2591
- reactIs_production_min.isConcurrentMode = function() {
2592
- return false;
2593
- };
2594
- reactIs_production_min.isContextConsumer = function(a2) {
2595
- return v(a2) === h2;
2596
- };
2597
- reactIs_production_min.isContextProvider = function(a2) {
2598
- return v(a2) === g;
2599
- };
2600
- reactIs_production_min.isElement = function(a2) {
2601
- return "object" === typeof a2 && null !== a2 && a2.$$typeof === b;
2602
- };
2603
- reactIs_production_min.isForwardRef = function(a2) {
2604
- return v(a2) === l;
2605
- };
2606
- reactIs_production_min.isFragment = function(a2) {
2607
- return v(a2) === d;
2608
- };
2609
- reactIs_production_min.isLazy = function(a2) {
2610
- return v(a2) === q;
2611
- };
2612
- reactIs_production_min.isMemo = function(a2) {
2613
- return v(a2) === p2;
2614
- };
2615
- reactIs_production_min.isPortal = function(a2) {
2616
- return v(a2) === c;
2617
- };
2618
- reactIs_production_min.isProfiler = function(a2) {
2619
- return v(a2) === f2;
2620
- };
2621
- reactIs_production_min.isStrictMode = function(a2) {
2622
- return v(a2) === e;
2623
- };
2624
- reactIs_production_min.isSuspense = function(a2) {
2625
- return v(a2) === m;
2626
- };
2627
- reactIs_production_min.isSuspenseList = function(a2) {
2628
- return v(a2) === n;
2629
- };
2630
- reactIs_production_min.isValidElementType = function(a2) {
2631
- return "string" === typeof a2 || "function" === typeof a2 || a2 === d || a2 === f2 || a2 === e || a2 === m || a2 === n || a2 === t || "object" === typeof a2 && null !== a2 && (a2.$$typeof === q || a2.$$typeof === p2 || a2.$$typeof === g || a2.$$typeof === h2 || a2.$$typeof === l || a2.$$typeof === u || void 0 !== a2.getModuleId) ? true : false;
2632
- };
2633
- reactIs_production_min.typeOf = v;
2634
- return reactIs_production_min;
2635
- }
2636
- var hasRequiredReactIs;
2637
- function requireReactIs() {
2638
- if (hasRequiredReactIs) return reactIs.exports;
2639
- hasRequiredReactIs = 1;
2640
- {
2641
- reactIs.exports = requireReactIs_production_min();
2642
- }
2643
- return reactIs.exports;
2644
- }
2645
- var reactIsExports = requireReactIs();
2646
- var index = /* @__PURE__ */ getDefaultExportFromCjs(reactIsExports);
2647
- var ReactIs18 = /* @__PURE__ */ _mergeNamespaces({
2648
- __proto__: null,
2649
- default: index
2650
- }, [reactIsExports]);
2651
- const reactIsMethods = [
2652
- "isAsyncMode",
2653
- "isConcurrentMode",
2654
- "isContextConsumer",
2655
- "isContextProvider",
2656
- "isElement",
2657
- "isForwardRef",
2658
- "isFragment",
2659
- "isLazy",
2660
- "isMemo",
2661
- "isPortal",
2662
- "isProfiler",
2663
- "isStrictMode",
2664
- "isSuspense",
2665
- "isSuspenseList",
2666
- "isValidElementType"
2667
- ];
2668
- Object.fromEntries(reactIsMethods.map((m) => [m, (v) => ReactIs18[m](v) || ReactIs19[m](v)]));
2669
- let getPromiseValue = () => "Promise{…}";
2670
- try {
2671
- const { getPromiseDetails, kPending, kRejected } = process.binding("util");
2672
- if (Array.isArray(getPromiseDetails(Promise.resolve()))) {
2673
- getPromiseValue = (value, options) => {
2674
- const [state, innerValue] = getPromiseDetails(value);
2675
- if (state === kPending) {
2676
- return "Promise{<pending>}";
2677
- }
2678
- return `Promise${state === kRejected ? "!" : ""}{${options.inspect(innerValue, options)}}`;
2679
- };
2680
- }
2681
- } catch (notNode) {
2682
- }
2683
- var jsTokens_1;
2684
- var hasRequiredJsTokens;
2685
- function requireJsTokens() {
2686
- if (hasRequiredJsTokens) return jsTokens_1;
2687
- hasRequiredJsTokens = 1;
2688
- var Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
2689
- RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\\]).|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/uy;
2690
- Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
2691
- Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/uy;
2692
- StringLiteral = /(['"])(?:(?!\1)[^\\\n\r]|\\(?:\r\n|[^]))*(\1)?/y;
2693
- NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y;
2694
- Template = /[`}](?:[^`\\$]|\\[^]|\$(?!\{))*(`|\$\{)?/y;
2695
- WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/uy;
2696
- LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
2697
- MultiLineComment = /\/\*(?:[^*]|\*(?!\/))*(\*\/)?/y;
2698
- SingleLineComment = /\/\/.*/y;
2699
- JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
2700
- JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/uy;
2701
- JSXString = /(['"])(?:(?!\1)[^])*(\1)?/y;
2702
- JSXText = /[^<>{}]+/y;
2703
- TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
2704
- TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
2705
- KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
2706
- KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
2707
- Newline = RegExp(LineTerminatorSequence.source);
2708
- jsTokens_1 = function* (input, { jsx = false } = {}) {
2709
- var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
2710
- ({ length } = input);
2711
- lastIndex = 0;
2712
- lastSignificantToken = "";
2713
- stack = [{ tag: "JS" }];
2714
- braces = [];
2715
- parenNesting = 0;
2716
- postfixIncDec = false;
2717
- while (lastIndex < length) {
2718
- mode = stack[stack.length - 1];
2719
- switch (mode.tag) {
2720
- case "JS":
2721
- case "JSNonExpressionParen":
2722
- case "InterpolationInTemplate":
2723
- case "InterpolationInJSX":
2724
- if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
2725
- RegularExpressionLiteral.lastIndex = lastIndex;
2726
- if (match = RegularExpressionLiteral.exec(input)) {
2727
- lastIndex = RegularExpressionLiteral.lastIndex;
2728
- lastSignificantToken = match[0];
2729
- postfixIncDec = true;
2730
- yield {
2731
- type: "RegularExpressionLiteral",
2732
- value: match[0],
2733
- closed: match[1] !== void 0 && match[1] !== "\\"
2734
- };
2735
- continue;
2736
- }
2737
- }
2738
- Punctuator.lastIndex = lastIndex;
2739
- if (match = Punctuator.exec(input)) {
2740
- punctuator = match[0];
2741
- nextLastIndex = Punctuator.lastIndex;
2742
- nextLastSignificantToken = punctuator;
2743
- switch (punctuator) {
2744
- case "(":
2745
- if (lastSignificantToken === "?NonExpressionParenKeyword") {
2746
- stack.push({
2747
- tag: "JSNonExpressionParen",
2748
- nesting: parenNesting
2749
- });
2750
- }
2751
- parenNesting++;
2752
- postfixIncDec = false;
2753
- break;
2754
- case ")":
2755
- parenNesting--;
2756
- postfixIncDec = true;
2757
- if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) {
2758
- stack.pop();
2759
- nextLastSignificantToken = "?NonExpressionParenEnd";
2760
- postfixIncDec = false;
2761
- }
2762
- break;
2763
- case "{":
2764
- Punctuator.lastIndex = 0;
2765
- isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
2766
- braces.push(isExpression);
2767
- postfixIncDec = false;
2768
- break;
2769
- case "}":
2770
- switch (mode.tag) {
2771
- case "InterpolationInTemplate":
2772
- if (braces.length === mode.nesting) {
2773
- Template.lastIndex = lastIndex;
2774
- match = Template.exec(input);
2775
- lastIndex = Template.lastIndex;
2776
- lastSignificantToken = match[0];
2777
- if (match[1] === "${") {
2778
- lastSignificantToken = "?InterpolationInTemplate";
2779
- postfixIncDec = false;
2780
- yield {
2781
- type: "TemplateMiddle",
2782
- value: match[0]
2783
- };
2784
- } else {
2785
- stack.pop();
2786
- postfixIncDec = true;
2787
- yield {
2788
- type: "TemplateTail",
2789
- value: match[0],
2790
- closed: match[1] === "`"
2791
- };
2792
- }
2793
- continue;
2794
- }
2795
- break;
2796
- case "InterpolationInJSX":
2797
- if (braces.length === mode.nesting) {
2798
- stack.pop();
2799
- lastIndex += 1;
2800
- lastSignificantToken = "}";
2801
- yield {
2802
- type: "JSXPunctuator",
2803
- value: "}"
2804
- };
2805
- continue;
2806
- }
2807
- }
2808
- postfixIncDec = braces.pop();
2809
- nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
2810
- break;
2811
- case "]":
2812
- postfixIncDec = true;
2813
- break;
2814
- case "++":
2815
- case "--":
2816
- nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
2817
- break;
2818
- case "<":
2819
- if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
2820
- stack.push({ tag: "JSXTag" });
2821
- lastIndex += 1;
2822
- lastSignificantToken = "<";
2823
- yield {
2824
- type: "JSXPunctuator",
2825
- value: punctuator
2826
- };
2827
- continue;
2828
- }
2829
- postfixIncDec = false;
2830
- break;
2831
- default:
2832
- postfixIncDec = false;
2833
- }
2834
- lastIndex = nextLastIndex;
2835
- lastSignificantToken = nextLastSignificantToken;
2836
- yield {
2837
- type: "Punctuator",
2838
- value: punctuator
2839
- };
2840
- continue;
2841
- }
2842
- Identifier.lastIndex = lastIndex;
2843
- if (match = Identifier.exec(input)) {
2844
- lastIndex = Identifier.lastIndex;
2845
- nextLastSignificantToken = match[0];
2846
- switch (match[0]) {
2847
- case "for":
2848
- case "if":
2849
- case "while":
2850
- case "with":
2851
- if (lastSignificantToken !== "." && lastSignificantToken !== "?.") {
2852
- nextLastSignificantToken = "?NonExpressionParenKeyword";
2853
- }
2854
- }
2855
- lastSignificantToken = nextLastSignificantToken;
2856
- postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]);
2857
- yield {
2858
- type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
2859
- value: match[0]
2860
- };
2861
- continue;
2862
- }
2863
- StringLiteral.lastIndex = lastIndex;
2864
- if (match = StringLiteral.exec(input)) {
2865
- lastIndex = StringLiteral.lastIndex;
2866
- lastSignificantToken = match[0];
2867
- postfixIncDec = true;
2868
- yield {
2869
- type: "StringLiteral",
2870
- value: match[0],
2871
- closed: match[2] !== void 0
2872
- };
2873
- continue;
2874
- }
2875
- NumericLiteral.lastIndex = lastIndex;
2876
- if (match = NumericLiteral.exec(input)) {
2877
- lastIndex = NumericLiteral.lastIndex;
2878
- lastSignificantToken = match[0];
2879
- postfixIncDec = true;
2880
- yield {
2881
- type: "NumericLiteral",
2882
- value: match[0]
2883
- };
2884
- continue;
2885
- }
2886
- Template.lastIndex = lastIndex;
2887
- if (match = Template.exec(input)) {
2888
- lastIndex = Template.lastIndex;
2889
- lastSignificantToken = match[0];
2890
- if (match[1] === "${") {
2891
- lastSignificantToken = "?InterpolationInTemplate";
2892
- stack.push({
2893
- tag: "InterpolationInTemplate",
2894
- nesting: braces.length
2895
- });
2896
- postfixIncDec = false;
2897
- yield {
2898
- type: "TemplateHead",
2899
- value: match[0]
2900
- };
2901
- } else {
2902
- postfixIncDec = true;
2903
- yield {
2904
- type: "NoSubstitutionTemplate",
2905
- value: match[0],
2906
- closed: match[1] === "`"
2907
- };
2908
- }
2909
- continue;
2910
- }
2911
- break;
2912
- case "JSXTag":
2913
- case "JSXTagEnd":
2914
- JSXPunctuator.lastIndex = lastIndex;
2915
- if (match = JSXPunctuator.exec(input)) {
2916
- lastIndex = JSXPunctuator.lastIndex;
2917
- nextLastSignificantToken = match[0];
2918
- switch (match[0]) {
2919
- case "<":
2920
- stack.push({ tag: "JSXTag" });
2921
- break;
2922
- case ">":
2923
- stack.pop();
2924
- if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") {
2925
- nextLastSignificantToken = "?JSX";
2926
- postfixIncDec = true;
2927
- } else {
2928
- stack.push({ tag: "JSXChildren" });
2929
- }
2930
- break;
2931
- case "{":
2932
- stack.push({
2933
- tag: "InterpolationInJSX",
2934
- nesting: braces.length
2935
- });
2936
- nextLastSignificantToken = "?InterpolationInJSX";
2937
- postfixIncDec = false;
2938
- break;
2939
- case "/":
2940
- if (lastSignificantToken === "<") {
2941
- stack.pop();
2942
- if (stack[stack.length - 1].tag === "JSXChildren") {
2943
- stack.pop();
2944
- }
2945
- stack.push({ tag: "JSXTagEnd" });
2946
- }
2947
- }
2948
- lastSignificantToken = nextLastSignificantToken;
2949
- yield {
2950
- type: "JSXPunctuator",
2951
- value: match[0]
2952
- };
2953
- continue;
2954
- }
2955
- JSXIdentifier.lastIndex = lastIndex;
2956
- if (match = JSXIdentifier.exec(input)) {
2957
- lastIndex = JSXIdentifier.lastIndex;
2958
- lastSignificantToken = match[0];
2959
- yield {
2960
- type: "JSXIdentifier",
2961
- value: match[0]
2962
- };
2963
- continue;
2964
- }
2965
- JSXString.lastIndex = lastIndex;
2966
- if (match = JSXString.exec(input)) {
2967
- lastIndex = JSXString.lastIndex;
2968
- lastSignificantToken = match[0];
2969
- yield {
2970
- type: "JSXString",
2971
- value: match[0],
2972
- closed: match[2] !== void 0
2973
- };
2974
- continue;
2975
- }
2976
- break;
2977
- case "JSXChildren":
2978
- JSXText.lastIndex = lastIndex;
2979
- if (match = JSXText.exec(input)) {
2980
- lastIndex = JSXText.lastIndex;
2981
- lastSignificantToken = match[0];
2982
- yield {
2983
- type: "JSXText",
2984
- value: match[0]
2985
- };
2986
- continue;
2987
- }
2988
- switch (input[lastIndex]) {
2989
- case "<":
2990
- stack.push({ tag: "JSXTag" });
2991
- lastIndex++;
2992
- lastSignificantToken = "<";
2993
- yield {
2994
- type: "JSXPunctuator",
2995
- value: "<"
2996
- };
2997
- continue;
2998
- case "{":
2999
- stack.push({
3000
- tag: "InterpolationInJSX",
3001
- nesting: braces.length
3002
- });
3003
- lastIndex++;
3004
- lastSignificantToken = "?InterpolationInJSX";
3005
- postfixIncDec = false;
3006
- yield {
3007
- type: "JSXPunctuator",
3008
- value: "{"
3009
- };
3010
- continue;
3011
- }
3012
- }
3013
- WhiteSpace.lastIndex = lastIndex;
3014
- if (match = WhiteSpace.exec(input)) {
3015
- lastIndex = WhiteSpace.lastIndex;
3016
- yield {
3017
- type: "WhiteSpace",
3018
- value: match[0]
3019
- };
3020
- continue;
3021
- }
3022
- LineTerminatorSequence.lastIndex = lastIndex;
3023
- if (match = LineTerminatorSequence.exec(input)) {
3024
- lastIndex = LineTerminatorSequence.lastIndex;
3025
- postfixIncDec = false;
3026
- if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
3027
- lastSignificantToken = "?NoLineTerminatorHere";
3028
- }
3029
- yield {
3030
- type: "LineTerminatorSequence",
3031
- value: match[0]
3032
- };
3033
- continue;
3034
- }
3035
- MultiLineComment.lastIndex = lastIndex;
3036
- if (match = MultiLineComment.exec(input)) {
3037
- lastIndex = MultiLineComment.lastIndex;
3038
- if (Newline.test(match[0])) {
3039
- postfixIncDec = false;
3040
- if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
3041
- lastSignificantToken = "?NoLineTerminatorHere";
3042
- }
3043
- }
3044
- yield {
3045
- type: "MultiLineComment",
3046
- value: match[0],
3047
- closed: match[1] !== void 0
3048
- };
3049
- continue;
3050
- }
3051
- SingleLineComment.lastIndex = lastIndex;
3052
- if (match = SingleLineComment.exec(input)) {
3053
- lastIndex = SingleLineComment.lastIndex;
3054
- postfixIncDec = false;
3055
- yield {
3056
- type: "SingleLineComment",
3057
- value: match[0]
3058
- };
3059
- continue;
3060
- }
3061
- firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
3062
- lastIndex += firstCodePoint.length;
3063
- lastSignificantToken = firstCodePoint;
3064
- postfixIncDec = false;
3065
- yield {
3066
- type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
3067
- value: firstCodePoint
3068
- };
3069
- }
3070
- return void 0;
3071
- };
3072
- return jsTokens_1;
3073
- }
3074
- requireJsTokens();
3075
- var reservedWords = {
3076
- keyword: [
3077
- "break",
3078
- "case",
3079
- "catch",
3080
- "continue",
3081
- "debugger",
3082
- "default",
3083
- "do",
3084
- "else",
3085
- "finally",
3086
- "for",
3087
- "function",
3088
- "if",
3089
- "return",
3090
- "switch",
3091
- "throw",
3092
- "try",
3093
- "var",
3094
- "const",
3095
- "while",
3096
- "with",
3097
- "new",
3098
- "this",
3099
- "super",
3100
- "class",
3101
- "extends",
3102
- "export",
3103
- "import",
3104
- "null",
3105
- "true",
3106
- "false",
3107
- "in",
3108
- "instanceof",
3109
- "typeof",
3110
- "void",
3111
- "delete"
3112
- ],
3113
- strict: [
3114
- "implements",
3115
- "interface",
3116
- "let",
3117
- "package",
3118
- "private",
3119
- "protected",
3120
- "public",
3121
- "static",
3122
- "yield"
3123
- ]
3124
- };
3125
- new Set(reservedWords.keyword);
3126
- new Set(reservedWords.strict);
3127
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3128
- const intToChar = new Uint8Array(64);
3129
- const charToInt = new Uint8Array(128);
3130
- for (let i = 0; i < chars.length; i++) {
3131
- const c = chars.charCodeAt(i);
3132
- intToChar[i] = c;
3133
- charToInt[c] = i;
3134
- }
3135
- var UrlType;
3136
- (function(UrlType2) {
3137
- UrlType2[UrlType2["Empty"] = 1] = "Empty";
3138
- UrlType2[UrlType2["Hash"] = 2] = "Hash";
3139
- UrlType2[UrlType2["Query"] = 3] = "Query";
3140
- UrlType2[UrlType2["RelativePath"] = 4] = "RelativePath";
3141
- UrlType2[UrlType2["AbsolutePath"] = 5] = "AbsolutePath";
3142
- UrlType2[UrlType2["SchemeRelative"] = 6] = "SchemeRelative";
3143
- UrlType2[UrlType2["Absolute"] = 7] = "Absolute";
3144
- })(UrlType || (UrlType = {}));
3145
- const { now } = Date;
3146
- class ModuleMocker {
3147
- constructor(interceptor, rpc2, spyOn, config) {
3148
- __publicField(this, "registry", new MockerRegistry());
3149
- __publicField(this, "queue", /* @__PURE__ */ new Set());
3150
- __publicField(this, "mockedIds", /* @__PURE__ */ new Set());
3151
- this.interceptor = interceptor;
3152
- this.rpc = rpc2;
3153
- this.spyOn = spyOn;
3154
- this.config = config;
3155
- }
3156
- async prepare() {
3157
- if (!this.queue.size) {
3158
- return;
3159
- }
3160
- await Promise.all([...this.queue.values()]);
3161
- }
3162
- async resolveFactoryModule(id) {
3163
- const mock = this.registry.get(id);
3164
- if (!mock || mock.type !== "manual") {
3165
- throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`);
3166
- }
3167
- const result = await mock.resolve();
3168
- return result;
3169
- }
3170
- getFactoryModule(id) {
3171
- const mock = this.registry.get(id);
3172
- if (!mock || mock.type !== "manual") {
3173
- throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`);
3174
- }
3175
- if (!mock.cache) {
3176
- throw new Error(`Mock ${id} wasn't resolved. This is probably a Vitest error. Please, open a new issue with reproduction.`);
3177
- }
3178
- return mock.cache;
3179
- }
3180
- async invalidate() {
3181
- const ids = Array.from(this.mockedIds);
3182
- if (!ids.length) {
3183
- return;
3184
- }
3185
- await this.rpc.invalidate(ids);
3186
- await this.interceptor.invalidate();
3187
- this.registry.clear();
3188
- }
3189
- async importActual(id, importer) {
3190
- const resolved = await this.rpc.resolveId(id, importer);
3191
- if (resolved == null) {
3192
- throw new Error(`[vitest] Cannot resolve "${id}" imported from "${importer}"`);
3193
- }
3194
- const ext = extname(resolved.id);
3195
- const url2 = new URL(resolved.url, location.href);
3196
- const query = `_vitest_original&ext${ext}`;
3197
- const actualUrl = `${url2.pathname}${url2.search ? `${url2.search}&${query}` : `?${query}`}${url2.hash}`;
3198
- return this.wrapDynamicImport(() => import(
3199
- /* @vite-ignore */
3200
- actualUrl
3201
- )).then((mod) => {
3202
- if (!resolved.optimized || typeof mod.default === "undefined") {
3203
- return mod;
3204
- }
3205
- const m = mod.default;
3206
- return (m === null || m === void 0 ? void 0 : m.__esModule) ? m : {
3207
- ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {},
3208
- default: m
3209
- };
3210
- });
3211
- }
3212
- async importMock(rawId, importer) {
3213
- await this.prepare();
3214
- const { resolvedId, resolvedUrl, redirectUrl } = await this.rpc.resolveMock(rawId, importer, { mock: "auto" });
3215
- const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl));
3216
- let mock = this.registry.get(mockUrl);
3217
- if (!mock) {
3218
- if (redirectUrl) {
3219
- const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString();
3220
- mock = new RedirectedModule(rawId, resolvedId, mockUrl, resolvedRedirect);
3221
- } else {
3222
- mock = new AutomockedModule(rawId, resolvedId, mockUrl);
3223
- }
3224
- }
3225
- if (mock.type === "manual") {
3226
- return await mock.resolve();
3227
- }
3228
- if (mock.type === "automock" || mock.type === "autospy") {
3229
- const url2 = new URL(`/@id/${resolvedId}`, location.href);
3230
- const query = url2.search ? `${url2.search}&t=${now()}` : `?t=${now()}`;
3231
- const moduleObject = await __vitePreload(() => import(
3232
- /* @vite-ignore */
3233
- `${url2.pathname}${query}&mock=${mock.type}${url2.hash}`
3234
- ), true ? [] : void 0);
3235
- return this.mockObject(moduleObject, mock.type);
3236
- }
3237
- return import(
3238
- /* @vite-ignore */
3239
- mock.redirect
3240
- );
3241
- }
3242
- mockObject(object2, moduleType = "automock") {
3243
- return mockObject({
3244
- globalConstructors: {
3245
- Object,
3246
- Function,
3247
- Array,
3248
- Map,
3249
- RegExp
3250
- },
3251
- spyOn: this.spyOn,
3252
- type: moduleType
3253
- }, object2);
3254
- }
3255
- queueMock(rawId, importer, factoryOrOptions) {
3256
- const promise = this.rpc.resolveMock(rawId, importer, { mock: typeof factoryOrOptions === "function" ? "factory" : (factoryOrOptions === null || factoryOrOptions === void 0 ? void 0 : factoryOrOptions.spy) ? "spy" : "auto" }).then(async ({ redirectUrl, resolvedId, resolvedUrl, needsInterop, mockType }) => {
3257
- const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl));
3258
- this.mockedIds.add(resolvedId);
3259
- const factory = typeof factoryOrOptions === "function" ? async () => {
3260
- const data = await factoryOrOptions();
3261
- return needsInterop ? { default: data } : data;
3262
- } : void 0;
3263
- const mockRedirect = typeof redirectUrl === "string" ? new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString() : null;
3264
- let module;
3265
- if (mockType === "manual") {
3266
- module = this.registry.register("manual", rawId, resolvedId, mockUrl, factory);
3267
- } else if (mockType === "autospy") {
3268
- module = this.registry.register("autospy", rawId, resolvedId, mockUrl);
3269
- } else if (mockType === "redirect") {
3270
- module = this.registry.register("redirect", rawId, resolvedId, mockUrl, mockRedirect);
3271
- } else {
3272
- module = this.registry.register("automock", rawId, resolvedId, mockUrl);
3273
- }
3274
- await this.interceptor.register(module);
3275
- }).finally(() => {
3276
- this.queue.delete(promise);
3277
- });
3278
- this.queue.add(promise);
3279
- }
3280
- queueUnmock(id, importer) {
3281
- const promise = this.rpc.resolveId(id, importer).then(async (resolved) => {
3282
- if (!resolved) {
3283
- return;
3284
- }
3285
- const mockUrl = this.resolveMockPath(cleanVersion(resolved.url));
3286
- this.mockedIds.add(resolved.id);
3287
- this.registry.delete(mockUrl);
3288
- await this.interceptor.delete(mockUrl);
3289
- }).finally(() => {
3290
- this.queue.delete(promise);
3291
- });
3292
- this.queue.add(promise);
3293
- }
3294
- // We need to await mock registration before importing the actual module
3295
- // In case there is a mocked module in the import chain
3296
- wrapDynamicImport(moduleFactory) {
3297
- if (typeof moduleFactory === "function") {
3298
- const promise = new Promise((resolve2, reject) => {
3299
- this.prepare().finally(() => {
3300
- moduleFactory().then(resolve2, reject);
3301
- });
3302
- });
3303
- return promise;
3304
- }
3305
- return moduleFactory;
3306
- }
3307
- resolveMockPath(path) {
3308
- const config = this.config;
3309
- const fsRoot = join("/@fs/", config.root);
3310
- if (path.startsWith(config.root)) {
3311
- return path.slice(config.root.length);
3312
- }
3313
- if (path.startsWith(fsRoot)) {
3314
- return path.slice(fsRoot.length);
3315
- }
3316
- return path;
3317
- }
3318
- }
3319
- const versionRegexp = /(\?|&)v=\w{8}/;
3320
- function cleanVersion(url2) {
3321
- return url2.replace(versionRegexp, "");
3322
- }
3323
- class VitestBrowserClientMocker extends ModuleMocker {
3324
- // default "vi" utility tries to access mock context to avoid circular dependencies
3325
- getMockContext() {
3326
- return { callstack: null };
3327
- }
3328
- wrapDynamicImport(moduleFactory) {
3329
- return getBrowserState().wrapModule(moduleFactory);
3330
- }
3331
- }
3332
- function createModuleMockerInterceptor() {
3333
- return {
3334
- async register(module) {
3335
- const state = getBrowserState();
3336
- await rpc().registerMock(state.sessionId, module.toJSON());
3337
- },
3338
- async delete(id) {
3339
- const state = getBrowserState();
3340
- await rpc().unregisterMock(state.sessionId, id);
3341
- },
3342
- async invalidate() {
3343
- const state = getBrowserState();
3344
- await rpc().clearMocks(state.sessionId);
3345
- }
3346
- };
3347
- }
3348
- function rpc() {
3349
- return getWorkerState().rpc;
3350
- }
3351
- getBrowserState().provider;
3352
- class CommandsManager {
3353
- constructor() {
3354
- __publicField(this, "_listeners", []);
3355
- }
3356
- onCommand(listener) {
3357
- this._listeners.push(listener);
3358
- }
3359
- async triggerCommand(command, args, clientError = new Error("empty")) {
3360
- var _a, _b;
3361
- const state = getWorkerState();
3362
- const rpc2 = state.rpc;
3363
- const { sessionId } = getBrowserState();
3364
- const filepath = state.filepath || ((_b = (_a = state.current) == null ? void 0 : _a.file) == null ? void 0 : _b.filepath);
3365
- args = args.filter((arg) => arg !== void 0);
3366
- if (this._listeners.length) {
3367
- await Promise.all(this._listeners.map((listener) => listener(command, args)));
3368
- }
3369
- return rpc2.triggerCommand(sessionId, command, filepath, args).catch((err) => {
3370
- var _a2;
3371
- clientError.message = err.message;
3372
- clientError.name = err.name;
3373
- clientError.stack = (_a2 = clientError.stack) == null ? void 0 : _a2.replace(clientError.message, err.message);
3374
- throw clientError;
3375
- });
3376
- }
3377
- }
3378
- const debugVar = getConfig().env.VITEST_BROWSER_DEBUG;
3379
- const debug = debugVar && debugVar !== "false" ? (...args) => {
3380
- var _a, _b;
3381
- return (_b = (_a = client.rpc).debug) == null ? void 0 : _b.call(_a, ...args.map(String));
3382
- } : void 0;
3383
- channel.addEventListener("message", async (e) => {
3384
- await client.waitForConnection();
3385
- const data = e.data;
3386
- debug == null ? void 0 : debug("event from orchestrator", JSON.stringify(e.data));
3387
- if (!isEvent(data)) {
3388
- const error = new Error(`Unknown message: ${JSON.stringify(e.data)}`);
3389
- unhandledError(error, "Uknown Iframe Message");
3390
- return;
3391
- }
3392
- if (!("iframeId" in data) || data.iframeId !== getBrowserState().iframeId) {
3393
- return;
3394
- }
3395
- switch (data.event) {
3396
- case "execute": {
3397
- const { method, files, context } = data;
3398
- const state = getWorkerState();
3399
- const parsedContext = parse(context);
3400
- state.ctx.providedContext = parsedContext;
3401
- state.providedContext = parsedContext;
3402
- if (method === "collect") {
3403
- await executeTests("collect", files).catch((err) => unhandledError(err, "Collect Error"));
3404
- } else {
3405
- await executeTests("run", files).catch((err) => unhandledError(err, "Run Error"));
3406
- }
3407
- break;
3408
- }
3409
- case "cleanup": {
3410
- await cleanup().catch((err) => unhandledError(err, "Cleanup Error"));
3411
- break;
3412
- }
3413
- case "prepare": {
3414
- await prepare(data).catch((err) => unhandledError(err, "Prepare Error"));
3415
- break;
3416
- }
3417
- case "viewport:done":
3418
- case "viewport:fail":
3419
- case "viewport": {
3420
- break;
3421
- }
3422
- default: {
3423
- const error = new Error(`Unknown event: ${data.event}`);
3424
- unhandledError(error, "Uknown Event");
3425
- }
3426
- }
3427
- channel.postMessage({
3428
- event: `response:${data.event}`,
3429
- iframeId: getBrowserState().iframeId
3430
- });
3431
- });
3432
- const url = new URL(location.href);
3433
- const reloadStart = url.searchParams.get("__reloadStart");
3434
- const iframeId = url.searchParams.get("iframeId");
3435
- const commands = new CommandsManager();
3436
- getBrowserState().commands = commands;
3437
- getBrowserState().iframeId = iframeId;
3438
- let contextSwitched = false;
3439
- async function prepareTestEnvironment(options) {
3440
- debug == null ? void 0 : debug("trying to resolve runner", `${reloadStart}`);
3441
- const config = getConfig();
3442
- const rpc2 = createSafeRpc(client);
3443
- const state = getWorkerState();
3444
- state.onCancel = onCancel;
3445
- state.rpc = rpc2;
3446
- const interceptor = createModuleMockerInterceptor();
3447
- const mocker = new VitestBrowserClientMocker(
3448
- interceptor,
3449
- rpc2,
3450
- SpyModule.spyOn,
3451
- {
3452
- root: getBrowserState().viteConfig.root
3453
- }
3454
- );
3455
- globalThis.__vitest_mocker__ = mocker;
3456
- setupConsoleLogSpy();
3457
- setupDialogsSpy();
3458
- const runner = await initiateRunner(state, mocker, config);
3459
- getBrowserState().runner = runner;
3460
- if (server.provider === "webdriverio") {
3461
- let switchPromise = null;
3462
- commands.onCommand(async () => {
3463
- if (switchPromise) {
3464
- await switchPromise;
3465
- }
3466
- if (!contextSwitched) {
3467
- switchPromise = rpc2.wdioSwitchContext("iframe").finally(() => {
3468
- switchPromise = null;
3469
- contextSwitched = true;
3470
- });
3471
- await switchPromise;
3472
- }
3473
- });
3474
- }
3475
- state.durations.prepare = performance.now() - options.startTime;
3476
- return {
3477
- runner,
3478
- config,
3479
- state
3480
- };
3481
- }
3482
- let preparedData;
3483
- async function executeTests(method, files) {
3484
- if (!preparedData) {
3485
- throw new Error(`Data was not properly initialized. This is a bug in Vitest. Please, open a new issue with reproduction.`);
3486
- }
3487
- debug == null ? void 0 : debug("runner resolved successfully");
3488
- const { runner, state } = preparedData;
3489
- state.ctx.files = files;
3490
- runner.setMethod(method);
3491
- const version = url.searchParams.get("browserv") || "";
3492
- files.forEach((filename) => {
3493
- const currentVersion = browserHashMap.get(filename);
3494
- if (!currentVersion || currentVersion[1] !== version) {
3495
- browserHashMap.set(filename, version);
3496
- }
3497
- });
3498
- debug == null ? void 0 : debug("prepare time", state.durations.prepare, "ms");
3499
- for (const file of files) {
3500
- state.filepath = file;
3501
- if (method === "run") {
3502
- await startTests([file], runner);
3503
- } else {
3504
- await collectTests([file], runner);
3505
- }
3506
- }
3507
- }
3508
- async function prepare(options) {
3509
- preparedData = await prepareTestEnvironment(options);
3510
- debug == null ? void 0 : debug("runner resolved successfully");
3511
- const { config, state } = preparedData;
3512
- state.durations.prepare = performance.now() - state.durations.prepare;
3513
- debug == null ? void 0 : debug("prepare time", state.durations.prepare, "ms");
3514
- await Promise.all([
3515
- setupCommonEnv(config),
3516
- startCoverageInsideWorker(config.coverage, executor, { isolate: config.browser.isolate }),
3517
- (async () => {
3518
- const VitestIndex = await __vitePreload(() => import("vitest"), true ? [] : void 0);
3519
- Object.defineProperty(window, "__vitest_index__", {
3520
- value: VitestIndex,
3521
- enumerable: false
3522
- });
3523
- })()
3524
- ]);
3525
- }
3526
- async function cleanup() {
3527
- const state = getWorkerState();
3528
- const config = getConfig();
3529
- const rpc2 = state.rpc;
3530
- const cleanupSymbol = Symbol.for("vitest:component-cleanup");
3531
- if (cleanupSymbol in page) {
3532
- try {
3533
- await page[cleanupSymbol]();
3534
- } catch (error) {
3535
- await unhandledError(error, "Cleanup Error");
3536
- }
3537
- }
3538
- await userEvent.cleanup().catch((error) => unhandledError(error, "Cleanup Error"));
3539
- await Promise.all(
3540
- getBrowserState().cleanups.map((fn) => fn())
3541
- ).catch((error) => unhandledError(error, "Cleanup Error"));
3542
- if (contextSwitched) {
3543
- await rpc2.wdioSwitchContext("parent").catch((error) => unhandledError(error, "Cleanup Error"));
3544
- }
3545
- state.environmentTeardownRun = true;
3546
- await stopCoverageInsideWorker(config.coverage, executor, { isolate: config.browser.isolate }).catch((error) => {
3547
- return unhandledError(error, "Coverage Error");
3548
- });
3549
- }
3550
- function unhandledError(e, type) {
3551
- return client.rpc.onUnhandledError({
3552
- name: e.name,
3553
- message: e.message,
3554
- stack: e.stack
3555
- }, type).catch(() => {
3556
- });
3557
- }
3558
- function isEvent(data) {
3559
- return typeof data === "object" && !!data && "event" in data;
3560
- }