@vitest/browser 2.0.1 → 2.0.3

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.
@@ -1,540 +0,0 @@
1
- (function polyfill() {
2
- const relList = document.createElement("link").relList;
3
- if (relList && relList.supports && relList.supports("modulepreload")) {
4
- return;
5
- }
6
- for (const link of document.querySelectorAll('link[rel="modulepreload"]')) {
7
- processPreload(link);
8
- }
9
- new MutationObserver((mutations) => {
10
- for (const mutation of mutations) {
11
- if (mutation.type !== "childList") {
12
- continue;
13
- }
14
- for (const node of mutation.addedNodes) {
15
- if (node.tagName === "LINK" && node.rel === "modulepreload")
16
- processPreload(node);
17
- }
18
- }
19
- }).observe(document, { childList: true, subtree: true });
20
- function getFetchOpts(link) {
21
- const fetchOpts = {};
22
- if (link.integrity) fetchOpts.integrity = link.integrity;
23
- if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy;
24
- if (link.crossOrigin === "use-credentials")
25
- fetchOpts.credentials = "include";
26
- else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit";
27
- else fetchOpts.credentials = "same-origin";
28
- return fetchOpts;
29
- }
30
- function processPreload(link) {
31
- if (link.ep)
32
- return;
33
- link.ep = true;
34
- const fetchOpts = getFetchOpts(link);
35
- fetch(link.href, fetchOpts);
36
- }
37
- })();
38
- const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
39
- function normalizeWindowsPath(input = "") {
40
- if (!input) {
41
- return input;
42
- }
43
- return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
44
- }
45
- const _UNC_REGEX = /^[/\\]{2}/;
46
- const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
47
- const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
48
- const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
49
- const normalize = function(path) {
50
- if (path.length === 0) {
51
- return ".";
52
- }
53
- path = normalizeWindowsPath(path);
54
- const isUNCPath = path.match(_UNC_REGEX);
55
- const isPathAbsolute = isAbsolute(path);
56
- const trailingSeparator = path[path.length - 1] === "/";
57
- path = normalizeString(path, !isPathAbsolute);
58
- if (path.length === 0) {
59
- if (isPathAbsolute) {
60
- return "/";
61
- }
62
- return trailingSeparator ? "./" : ".";
63
- }
64
- if (trailingSeparator) {
65
- path += "/";
66
- }
67
- if (_DRIVE_LETTER_RE.test(path)) {
68
- path += "/";
69
- }
70
- if (isUNCPath) {
71
- if (!isPathAbsolute) {
72
- return `//./${path}`;
73
- }
74
- return `//${path}`;
75
- }
76
- return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
77
- };
78
- const join = function(...arguments_) {
79
- if (arguments_.length === 0) {
80
- return ".";
81
- }
82
- let joined;
83
- for (const argument of arguments_) {
84
- if (argument && argument.length > 0) {
85
- if (joined === void 0) {
86
- joined = argument;
87
- } else {
88
- joined += `/${argument}`;
89
- }
90
- }
91
- }
92
- if (joined === void 0) {
93
- return ".";
94
- }
95
- return normalize(joined.replace(/\/\/+/g, "/"));
96
- };
97
- function cwd() {
98
- if (typeof process !== "undefined" && typeof process.cwd === "function") {
99
- return process.cwd().replace(/\\/g, "/");
100
- }
101
- return "/";
102
- }
103
- const resolve = function(...arguments_) {
104
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
105
- let resolvedPath = "";
106
- let resolvedAbsolute = false;
107
- for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
108
- const path = index >= 0 ? arguments_[index] : cwd();
109
- if (!path || path.length === 0) {
110
- continue;
111
- }
112
- resolvedPath = `${path}/${resolvedPath}`;
113
- resolvedAbsolute = isAbsolute(path);
114
- }
115
- resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
116
- if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
117
- return `/${resolvedPath}`;
118
- }
119
- return resolvedPath.length > 0 ? resolvedPath : ".";
120
- };
121
- function normalizeString(path, allowAboveRoot) {
122
- let res = "";
123
- let lastSegmentLength = 0;
124
- let lastSlash = -1;
125
- let dots = 0;
126
- let char = null;
127
- for (let index = 0; index <= path.length; ++index) {
128
- if (index < path.length) {
129
- char = path[index];
130
- } else if (char === "/") {
131
- break;
132
- } else {
133
- char = "/";
134
- }
135
- if (char === "/") {
136
- if (lastSlash === index - 1 || dots === 1) ;
137
- else if (dots === 2) {
138
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
139
- if (res.length > 2) {
140
- const lastSlashIndex = res.lastIndexOf("/");
141
- if (lastSlashIndex === -1) {
142
- res = "";
143
- lastSegmentLength = 0;
144
- } else {
145
- res = res.slice(0, lastSlashIndex);
146
- lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
147
- }
148
- lastSlash = index;
149
- dots = 0;
150
- continue;
151
- } else if (res.length > 0) {
152
- res = "";
153
- lastSegmentLength = 0;
154
- lastSlash = index;
155
- dots = 0;
156
- continue;
157
- }
158
- }
159
- if (allowAboveRoot) {
160
- res += res.length > 0 ? "/.." : "..";
161
- lastSegmentLength = 2;
162
- }
163
- } else {
164
- if (res.length > 0) {
165
- res += `/${path.slice(lastSlash + 1, index)}`;
166
- } else {
167
- res = path.slice(lastSlash + 1, index);
168
- }
169
- lastSegmentLength = index - lastSlash - 1;
170
- }
171
- lastSlash = index;
172
- dots = 0;
173
- } else if (char === "." && dots !== -1) {
174
- ++dots;
175
- } else {
176
- dots = -1;
177
- }
178
- }
179
- return res;
180
- }
181
- const isAbsolute = function(p) {
182
- return _IS_ABSOLUTE_RE.test(p);
183
- };
184
- const _EXTNAME_RE = /.(\.[^./]+)$/;
185
- const extname = function(p) {
186
- const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
187
- return match && match[1] || "";
188
- };
189
- const relative = function(from, to) {
190
- const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
191
- const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
192
- if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) {
193
- return _to.join("/");
194
- }
195
- const _fromCopy = [..._from];
196
- for (const segment of _fromCopy) {
197
- if (_to[0] !== segment) {
198
- break;
199
- }
200
- _from.shift();
201
- _to.shift();
202
- }
203
- return [..._from.map(() => ".."), ..._to].join("/");
204
- };
205
- const DEFAULT_TIMEOUT = 6e4;
206
- function defaultSerialize(i) {
207
- return i;
208
- }
209
- const defaultDeserialize = defaultSerialize;
210
- const { clearTimeout: clearTimeout$1, setTimeout: setTimeout$1 } = globalThis;
211
- const random = Math.random.bind(Math);
212
- function createBirpc(functions, options) {
213
- const {
214
- post,
215
- on,
216
- eventNames = [],
217
- serialize = defaultSerialize,
218
- deserialize = defaultDeserialize,
219
- resolver,
220
- timeout = DEFAULT_TIMEOUT
221
- } = options;
222
- const rpcPromiseMap = /* @__PURE__ */ new Map();
223
- let _promise;
224
- const rpc = new Proxy({}, {
225
- get(_, method) {
226
- if (method === "$functions")
227
- return functions;
228
- if (method === "then" && !eventNames.includes("then") && !("then" in functions))
229
- return void 0;
230
- const sendEvent = (...args) => {
231
- post(serialize({ m: method, a: args, t: "q" }));
232
- };
233
- if (eventNames.includes(method)) {
234
- sendEvent.asEvent = sendEvent;
235
- return sendEvent;
236
- }
237
- const sendCall = async (...args) => {
238
- await _promise;
239
- return new Promise((resolve2, reject) => {
240
- var _a;
241
- const id = nanoid();
242
- let timeoutId;
243
- if (timeout >= 0) {
244
- timeoutId = setTimeout$1(() => {
245
- var _a2;
246
- try {
247
- (_a2 = options.onTimeoutError) == null ? void 0 : _a2.call(options, method, args);
248
- throw new Error(`[birpc] timeout on calling "${method}"`);
249
- } catch (e) {
250
- reject(e);
251
- }
252
- rpcPromiseMap.delete(id);
253
- }, timeout);
254
- if (typeof timeoutId === "object")
255
- timeoutId = (_a = timeoutId.unref) == null ? void 0 : _a.call(timeoutId);
256
- }
257
- rpcPromiseMap.set(id, { resolve: resolve2, reject, timeoutId });
258
- post(serialize({ m: method, a: args, i: id, t: "q" }));
259
- });
260
- };
261
- sendCall.asEvent = sendEvent;
262
- return sendCall;
263
- }
264
- });
265
- _promise = on(async (data, ...extra) => {
266
- const msg = deserialize(data);
267
- if (msg.t === "q") {
268
- const { m: method, a: args } = msg;
269
- let result, error;
270
- const fn = resolver ? resolver(method, functions[method]) : functions[method];
271
- if (!fn) {
272
- error = new Error(`[birpc] function "${method}" not found`);
273
- } else {
274
- try {
275
- result = await fn.apply(rpc, args);
276
- } catch (e) {
277
- error = e;
278
- }
279
- }
280
- if (msg.i) {
281
- if (error && options.onError)
282
- options.onError(error, method, args);
283
- post(serialize({ t: "s", i: msg.i, r: result, e: error }), ...extra);
284
- }
285
- } else {
286
- const { i: ack, r: result, e: error } = msg;
287
- const promise = rpcPromiseMap.get(ack);
288
- if (promise) {
289
- clearTimeout$1(promise.timeoutId);
290
- if (error)
291
- promise.reject(error);
292
- else
293
- promise.resolve(result);
294
- }
295
- rpcPromiseMap.delete(ack);
296
- }
297
- });
298
- return rpc;
299
- }
300
- const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
301
- function nanoid(size = 21) {
302
- let id = "";
303
- let i = size;
304
- while (i--)
305
- id += urlAlphabet[random() * 64 | 0];
306
- return id;
307
- }
308
- const { parse: $parse, stringify: $stringify } = JSON;
309
- const { keys } = Object;
310
- const Primitive = String;
311
- const primitive = "string";
312
- const ignore = {};
313
- const object = "object";
314
- const noop = (_, value) => value;
315
- const primitives = (value) => value instanceof Primitive ? Primitive(value) : value;
316
- const Primitives = (_, value) => typeof value === primitive ? new Primitive(value) : value;
317
- const revive = (input, parsed, output, $) => {
318
- const lazy = [];
319
- for (let ke = keys(output), { length } = ke, y = 0; y < length; y++) {
320
- const k = ke[y];
321
- const value = output[k];
322
- if (value instanceof Primitive) {
323
- const tmp = input[value];
324
- if (typeof tmp === object && !parsed.has(tmp)) {
325
- parsed.add(tmp);
326
- output[k] = ignore;
327
- lazy.push({ k, a: [input, parsed, tmp, $] });
328
- } else
329
- output[k] = $.call(output, k, tmp);
330
- } else if (output[k] !== ignore)
331
- output[k] = $.call(output, k, value);
332
- }
333
- for (let { length } = lazy, i = 0; i < length; i++) {
334
- const { k, a } = lazy[i];
335
- output[k] = $.call(output, k, revive.apply(null, a));
336
- }
337
- return output;
338
- };
339
- const set = (known, input, value) => {
340
- const index = Primitive(input.push(value) - 1);
341
- known.set(value, index);
342
- return index;
343
- };
344
- const parse = (text, reviver) => {
345
- const input = $parse(text, Primitives).map(primitives);
346
- const value = input[0];
347
- const $ = reviver || noop;
348
- const tmp = typeof value === object && value ? revive(input, /* @__PURE__ */ new Set(), value, $) : value;
349
- return $.call({ "": tmp }, "", tmp);
350
- };
351
- const stringify = (value, replacer, space) => {
352
- const $ = replacer && typeof replacer === object ? (k, v) => k === "" || -1 < replacer.indexOf(k) ? v : void 0 : replacer || noop;
353
- const known = /* @__PURE__ */ new Map();
354
- const input = [];
355
- const output = [];
356
- let i = +set(known, input, $.call({ "": value }, "", value));
357
- let firstRun = !i;
358
- while (i < input.length) {
359
- firstRun = true;
360
- output[i] = $stringify(input[i++], replace, space);
361
- }
362
- return "[" + output.join(",") + "]";
363
- function replace(key, value2) {
364
- if (firstRun) {
365
- firstRun = !firstRun;
366
- return value2;
367
- }
368
- const after = $.call(this, key, value2);
369
- switch (typeof after) {
370
- case object:
371
- if (after === null) return after;
372
- case primitive:
373
- return known.get(after) || set(known, input, after);
374
- }
375
- return after;
376
- }
377
- };
378
- async function importId(id) {
379
- const name = `/@id/${id}`.replace(/\\/g, "/");
380
- return (/* @__PURE__ */ getBrowserState()).wrapModule(() => import(
381
- /* @vite-ignore */
382
- name
383
- ));
384
- }
385
- async function importFs(id) {
386
- const name = `/@fs/${id}`.replace(/\\/g, "/");
387
- return (/* @__PURE__ */ getBrowserState()).wrapModule(() => import(
388
- /* @vite-ignore */
389
- name
390
- ));
391
- }
392
- function getConfig() {
393
- return (/* @__PURE__ */ getBrowserState()).config;
394
- }
395
- // @__NO_SIDE_EFFECTS__
396
- function getBrowserState() {
397
- return window.__vitest_browser_runner__;
398
- }
399
- // @__NO_SIDE_EFFECTS__
400
- function getWorkerState() {
401
- const state = window.__vitest_worker__;
402
- if (!state) {
403
- throw new Error("Worker state is not found. This is an issue with Vitest. Please, open an issue.");
404
- }
405
- return state;
406
- }
407
- const channel = new BroadcastChannel(
408
- `vitest:${(/* @__PURE__ */ getBrowserState()).contextId}`
409
- );
410
- const globalChannel = new BroadcastChannel("vitest:global");
411
- function waitForChannel(event) {
412
- return new Promise((resolve2) => {
413
- channel.addEventListener(
414
- "message",
415
- (e) => {
416
- var _a;
417
- if (((_a = e.data) == null ? void 0 : _a.type) === event) {
418
- resolve2();
419
- }
420
- },
421
- { once: true }
422
- );
423
- });
424
- }
425
- const PAGE_TYPE = (/* @__PURE__ */ getBrowserState()).type;
426
- const PORT = location.port;
427
- const HOST = [location.hostname, PORT].filter(Boolean).join(":");
428
- const SESSION_ID = PAGE_TYPE === "orchestrator" ? (/* @__PURE__ */ getBrowserState()).contextId : crypto.randomUUID();
429
- const ENTRY_URL = `${location.protocol === "https:" ? "wss:" : "ws:"}//${HOST}/__vitest_browser_api__?type=${PAGE_TYPE}&sessionId=${SESSION_ID}`;
430
- let setCancel = (_) => {
431
- };
432
- const onCancel = new Promise((resolve2) => {
433
- setCancel = resolve2;
434
- });
435
- function createClient() {
436
- const reconnectInterval = 2e3;
437
- const reconnectTries = 10;
438
- const connectTimeout = 6e4;
439
- let tries = reconnectTries;
440
- const ctx = {
441
- ws: new WebSocket(ENTRY_URL),
442
- waitForConnection
443
- };
444
- let onMessage;
445
- ctx.rpc = createBirpc(
446
- {
447
- onCancel: setCancel,
448
- async createTesters(files) {
449
- var _a, _b;
450
- if (PAGE_TYPE !== "orchestrator") {
451
- return;
452
- }
453
- (_b = (_a = /* @__PURE__ */ getBrowserState()).createTesters) == null ? void 0 : _b.call(_a, files);
454
- },
455
- cdpEvent(event, payload) {
456
- const cdp = (/* @__PURE__ */ getBrowserState()).cdp;
457
- if (!cdp) {
458
- return;
459
- }
460
- cdp.emit(event, payload);
461
- }
462
- },
463
- {
464
- post: (msg) => ctx.ws.send(msg),
465
- on: (fn) => onMessage = fn,
466
- serialize: (e) => stringify(e, (_, v) => {
467
- if (v instanceof Error) {
468
- return {
469
- name: v.name,
470
- message: v.message,
471
- stack: v.stack
472
- };
473
- }
474
- return v;
475
- }),
476
- deserialize: parse,
477
- onTimeoutError(functionName) {
478
- throw new Error(`[vitest-browser]: Timeout calling "${functionName}"`);
479
- }
480
- }
481
- );
482
- let openPromise;
483
- function reconnect(reset = false) {
484
- if (reset) {
485
- tries = reconnectTries;
486
- }
487
- ctx.ws = new WebSocket(ENTRY_URL);
488
- registerWS();
489
- }
490
- function registerWS() {
491
- openPromise = new Promise((resolve2, reject) => {
492
- var _a, _b;
493
- const timeout = (_b = (_a = setTimeout(() => {
494
- reject(
495
- new Error(
496
- `Cannot connect to the server in ${connectTimeout / 1e3} seconds`
497
- )
498
- );
499
- }, connectTimeout)) == null ? void 0 : _a.unref) == null ? void 0 : _b.call(_a);
500
- if (ctx.ws.OPEN === ctx.ws.readyState) {
501
- resolve2();
502
- }
503
- ctx.ws.addEventListener("open", () => {
504
- tries = reconnectTries;
505
- resolve2();
506
- clearTimeout(timeout);
507
- });
508
- });
509
- ctx.ws.addEventListener("message", (v) => {
510
- onMessage(v.data);
511
- });
512
- ctx.ws.addEventListener("close", () => {
513
- tries -= 1;
514
- if (tries > 0) {
515
- setTimeout(reconnect, reconnectInterval);
516
- }
517
- });
518
- }
519
- registerWS();
520
- function waitForConnection() {
521
- return openPromise;
522
- }
523
- return ctx;
524
- }
525
- const client = createClient();
526
- export {
527
- client as a,
528
- globalChannel as b,
529
- channel as c,
530
- getConfig as d,
531
- importId as e,
532
- extname as f,
533
- getBrowserState as g,
534
- getWorkerState as h,
535
- importFs as i,
536
- join as j,
537
- onCancel as o,
538
- relative as r,
539
- waitForChannel as w
540
- };