Debian Codegraph @

addons/web/static/lib/hoot/mock/network.js

raw
1 /** @odoo-module */
2
3 import { delay, tick } from "@odoo/hoot-dom";
4 import {
5 mockedCancelAnimationFrame,
6 mockedRequestAnimationFrame,
7 } from "@web/../lib/hoot-dom/helpers/time";
8 import { isInstanceOf } from "../../hoot-dom/hoot_dom_utils";
9 import { makeNetworkLogger } from "../core/logger";
10 import {
11 ensureArray,
12 getSyncValue,
13 isNil,
14 MIME_TYPE,
15 MockEventTarget,
16 setSyncValue,
17 } from "../hoot_utils";
18 import { ensureTest } from "../main_runner";
19
20 /**
21 * @typedef {ResponseInit & {
22 * type?: ResponseType;
23 * url?: string;
24 * }} MockResponseInit
25 *
26 * @typedef {AbortController
27 * | MockBroadcastChannel
28 * | MockMessageChannel
29 * | MockMessagePort
30 * | MockSharedWorker
31 * | MockWebSocket
32 * | MockWorker
33 * | MockXMLHttpRequest
34 * | ServerWebSocket} NetworkInstance
35 */
36
37 //-----------------------------------------------------------------------------
38 // Global
39 //-----------------------------------------------------------------------------
40
41 const {
42 AbortController,
43 Blob,
44 BroadcastChannel,
45 document,
46 fetch,
47 FormData,
48 Headers,
49 Map,
50 Math: { floor: $floor, max: $max, min: $min, random: $random },
51 Object: {
52 assign: $assign,
53 create: $create,
54 defineProperty: $defineProperty,
55 entries: $entries,
56 },
57 ProgressEvent,
58 ReadableStream,
59 Request,
60 Response,
61 Set,
62 TextEncoder,
63 Uint8Array,
64 URL,
65 WebSocket,
66 XMLHttpRequest,
67 } = globalThis;
68 const { parse: $parse, stringify: $stringify } = globalThis.JSON;
69
70 //-----------------------------------------------------------------------------
71 // Internal
72 //-----------------------------------------------------------------------------
73
74 /**
75 * @param {EventTarget} target
76 * @param {CloseEventInit} eventInit
77 */
78 function dispatchClose(target, eventInit) {
79 if (!isOpen(target)) {
80 return;
81 }
82 markClosed(target);
83 eventInit.code ??= 1000;
84 eventInit.wasClean ??= eventInit.code === 1000;
85 target.dispatchEvent(new CloseEvent("close", eventInit));
86 }
87
88 /**
89 * @param {EventTarget} target
90 * @param {any} data
91 * @param {Transferable[] | StructuredSerializeOptions} [transfer]
92 */
93 async function dispatchMessage(target, data, transfer) {
94 const targets = [];
95 if (transfer) {
96 targets.push(...(transfer?.transfer || transfer));
97 }
98 if (!targets.length) {
99 targets.push(target);
100 }
101 const messageEventInit = { data };
102 let dispatched = false;
103 for (const target of targets) {
104 if (isOpen(target)) {
105 dispatched = true;
106 target.dispatchEvent(new MessageEvent("message", messageEventInit));
107 }
108 }
109 if (dispatched) {
110 await tick();
111 }
112 }
113
114 /**
115 *
116 * @param {{ headers?: HeadersInit } | undefined} object
117 * @param {string} content
118 */
119 function getHeaders(object, content) {
120 /** @type {Headers} */
121 let headers;
122 if (isInstanceOf(object?.headers, Headers)) {
123 headers = object.headers;
124 } else {
125 headers = new Headers(object?.headers);
126 }
127
128 if (content && !headers.has(HEADER.contentType)) {
129 if (typeof content === "string") {
130 headers.set(HEADER.contentType, MIME_TYPE.text);
131 } else if (isInstanceOf(content, Blob)) {
132 headers.set(HEADER.contentType, MIME_TYPE.blob);
133 } else if (isInstanceOf(content, FormData)) {
134 headers.set(HEADER.contentType, MIME_TYPE.formData);
135 } else {
136 headers.set(HEADER.contentType, MIME_TYPE.json);
137 }
138 }
139 return headers;
140 }
141
142 /**
143 * @param {...NetworkInstance} instances
144 */
145 function isOpen(...instances) {
146 return instances.every((i) => openNetworkInstances.has(i));
147 }
148
149 /**
150 * @param {...NetworkInstance} instances
151 */
152 function markClosed(...instances) {
153 for (const instance of instances) {
154 openNetworkInstances.delete(instance);
155 }
156 }
157
158 /**
159 * @param {NetworkInstance} instance
160 * @param {Promise<any> | null} [promise]
161 */
162 function markOpen(instance) {
163 openNetworkInstances.add(instance);
164 return instance;
165 }
166
167 /**
168 * Helper used to parse JSON-RPC request/response parameters, and to make their
169 * "jsonrpc", "id" and "method" properties non-enumerable, as to make them more
170 * inconspicuous in console logs, effectively highlighting the 'params' or 'result'
171 * keys.
172 *
173 * @param {string} stringParams
174 */
175 function parseJsonRpcParams(stringParams) {
176 const jsonParams = $assign($create(null), $parse(stringParams));
177 if (jsonParams && "jsonrpc" in jsonParams) {
178 $defineProperty(jsonParams, "jsonrpc", {
179 value: jsonParams.jsonrpc,
180 enumerable: false,
181 });
182 if ("id" in jsonParams) {
183 $defineProperty(jsonParams, "id", {
184 value: jsonParams.id,
185 enumerable: false,
186 });
187 }
188 if ("method" in jsonParams) {
189 $defineProperty(jsonParams, "method", {
190 value: jsonParams.method,
191 enumerable: false,
192 });
193 }
194 }
195 return jsonParams;
196 }
197
198 /**
199 * @param {number} min
200 * @param {number} [max]
201 */
202 function parseNetworkDelay(min, max) {
203 if (min <= 0) {
204 return null;
205 }
206 if (max) {
207 if (max < min) {
208 [min, max] = [max, min];
209 }
210 const diff = max - min;
211 return () => delay($floor($random() * diff + min));
212 } else {
213 return () => delay(min);
214 }
215 }
216
217 /**
218 * @param {Uint8Array<ArrayBuffer> | string} value
219 * @returns {Uint8Array<ArrayBuffer>}
220 */
221 function toBytes(value) {
222 return isInstanceOf(value, Uint8Array) ? value : new TextEncoder().encode(value);
223 }
224
225 const DEFAULT_URL = "https://www.hoot.test/";
226 const ENDLESS_PROMISE = new Promise(() => {});
227 const HEADER = {
228 contentLength: "Content-Length",
229 contentType: "Content-Type",
230 };
231 const R_EQUAL = /\s*=\s*/;
232 const R_INTERNAL_URL = /^(blob|data):/;
233 const R_SEMICOLON = /\s*;\s*/;
234
235 const requestResponseMixin = {
236 async arrayBuffer() {
237 return toBytes(this._readValue("arrayBuffer", true)).buffer;
238 },
239 async blob() {
240 const value = this._readValue("blob", false);
241 return isInstanceOf(value, Blob) ? value : new MockBlob([value]);
242 },
243 async bytes() {
244 return toBytes(this._readValue("bytes", true));
245 },
246 async formData() {
247 const data = this._readValue("formData", false);
248 if (!isInstanceOf(data, FormData)) {
249 throw new TypeError("Failed to fetch");
250 }
251 return data;
252 },
253 async json() {
254 return $parse(this._readValue("json", true));
255 },
256 async text() {
257 return this._readValue("text", true);
258 },
259 };
260
261 /** @type {Set<NetworkInstance>} */
262 const openNetworkInstances = new Set();
263
264 /** @type {ReturnType<parseNetworkDelay>} */
265 let getNetworkDelay = null;
266 /** @type {(typeof fetch) | null} */
267 let mockFetchFn = null;
268 /** @type {((websocket: ServerWebSocket) => any) | null} */
269 let mockWebSocketConnection = null;
270 /** @type {((worker: MockSharedWorker | MockWorker) => any)[]} */
271 const mockWorkerConnections = [];
272
273 //-----------------------------------------------------------------------------
274 // Exports
275 //-----------------------------------------------------------------------------
276
277 export function cleanupNetwork() {
278 // Mocked functions
279 mockFetchFn = null;
280 mockWebSocketConnection = null;
281 mockWorkerConnections.length = 0;
282
283 // Network instances
284 for (const instance of openNetworkInstances) {
285 if (isInstanceOf(instance, AbortController)) {
286 instance.abort();
287 } else if (
288 instance instanceof MockBroadcastChannel ||
289 instance instanceof MockMessagePort ||
290 instance instanceof MockWebSocket ||
291 instance instanceof ServerWebSocket
292 ) {
293 instance.close();
294 } else if (instance instanceof MockSharedWorker) {
295 instance.port.close(); // Will also close `MockMessageChannel` instances
296 } else if (instance instanceof MockWorker) {
297 instance.terminate();
298 }
299 }
300 openNetworkInstances.clear();
301
302 // Cookie
303 mockCookie._jar = $create(null);
304
305 // History
306 mockHistory._index = 0;
307 mockHistory._stack = [];
308 mockHistory.pushState(null, "", mockHistory._location.href);
309
310 // Location
311 mockLocation.href = DEFAULT_URL;
312 }
313
314 /** @type {typeof fetch} */
315 export async function mockedFetch(input, init) {
316 const strInput = String(input);
317 const isInternalUrl = R_INTERNAL_URL.test(strInput);
318 if (!mockFetchFn) {
319 if (isInternalUrl) {
320 // Internal URL without mocked 'fetch': directly handled by the browser
321 return fetch(input, init);
322 }
323 throw new Error(
324 `Could not fetch "${strInput}": cannot make a request when fetch is not mocked`
325 );
326 }
327 const controller = markOpen(new AbortController());
328
329 init = { ...init };
330 init.headers = getHeaders(init, init.body);
331 init.method = init.method?.toUpperCase() || (isNil(init.body) ? "GET" : "POST");
332
333 // Allows 'signal' to not be logged with 'logRequest'.
334 $defineProperty(init, "signal", {
335 value: controller.signal,
336 enumerable: false,
337 });
338
339 const { logRequest, logResponse } = makeNetworkLogger(init.method, strInput);
340
341 logRequest(() => {
342 const readableInit = {
343 ...init,
344 // Make headers easier to read in the console
345 headers: new Map(init.headers),
346 };
347 if (init.headers.get(HEADER.contentType) === MIME_TYPE.json) {
348 return [parseJsonRpcParams(init.body), readableInit];
349 } else {
350 return [init.body, readableInit];
351 }
352 });
353
354 if (getNetworkDelay) {
355 await getNetworkDelay();
356 }
357
358 // keep separate from 'error', as it can be null or undefined even though the
359 // callback has thrown an error.
360 let failed = false;
361 let error, result;
362 try {
363 result = await mockFetchFn(input, init);
364 } catch (err) {
365 failed = true;
366 error = err;
367 }
368 if (isOpen(controller)) {
369 markClosed(controller);
370 } else {
371 return ENDLESS_PROMISE;
372 }
373 if (failed) {
374 throw error;
375 }
376
377 if (isInternalUrl && isNil(result)) {
378 // Internal URL without mocked result: directly handled by the browser
379 return fetch(input, init);
380 }
381
382 // Result can be a request or the final request value
383 const responseHeaders = getHeaders(result, result);
384
385 if (result instanceof MockResponse) {
386 // Mocked response
387 logResponse(() => {
388 const textValue = getSyncValue(result, true);
389 return [
390 responseHeaders.get(HEADER.contentType) === MIME_TYPE.json
391 ? parseJsonRpcParams(textValue)
392 : textValue,
393 result,
394 ];
395 });
396 return result;
397 }
398
399 if (isInstanceOf(result, Response)) {
400 // Actual fetch
401 logResponse(() => ["(go to network tab for request content)", result]);
402 return result;
403 }
404
405 // Not a response object:
406 // Determine the return type based on:
407 // - the content type header
408 // - or the type of the returned value
409 if (responseHeaders.get(HEADER.contentType) === MIME_TYPE.json) {
410 // JSON response
411 const strBody = $stringify(result ?? null);
412 const response = new MockResponse(strBody, {
413 headers: responseHeaders,
414 statusText: "OK",
415 type: "basic",
416 url: strInput,
417 });
418 logResponse(() => [parseJsonRpcParams(strBody), response]);
419 return response;
420 }
421
422 // Any other type
423 const response = new MockResponse(result, {
424 headers: responseHeaders,
425 statusText: "OK",
426 type: "basic",
427 url: strInput,
428 });
429 logResponse(() => [result, response]);
430 return response;
431 }
432
433 /**
434 * Mocks the fetch function by replacing it with a given `fetchFn`.
435 *
436 * The return value of `fetchFn` is used as the response of the mocked fetch, or
437 * wrapped in a {@link MockResponse} object if it does not meet the required format.
438 *
439 * @param {typeof mockFetchFn} [fetchFn]
440 * @example
441 * mockFetch((input, init) => {
442 * if (input === "/../web_search_read") {
443 * return { records: [{ id: 3, name: "john" }] };
444 * }
445 * // ...
446 * });
447 * @example
448 * mockFetch((input, init) => {
449 * if (input === "/translations") {
450 * const translations = {
451 * "Hello, world!": "Bonjour, monde !",
452 * // ...
453 * };
454 * return new Response(JSON.stringify(translations));
455 * }
456 * });
457 */
458 export function mockFetch(fetchFn) {
459 ensureTest("mockFetch");
460 mockFetchFn = fetchFn;
461 }
462
463 /**
464 * Activates mock WebSocket classe:
465 * - websocket connections will be handled by `window.fetch` (see {@link mockFetch});
466 * - the `onWebSocketConnected` callback will be called after a websocket has been created.
467 *
468 * @param {typeof mockWebSocketConnection} [onWebSocketConnected]
469 */
470 export function mockWebSocket(onWebSocketConnected) {
471 ensureTest("mockWebSocket");
472 mockWebSocketConnection = onWebSocketConnected;
473 }
474
475 /**
476 * Activates mock Worker and SharedWorker classes:
477 * - actual code fetched by worker URLs will then be handled by `window.fetch`
478 * (see {@link mockFetch});
479 * - the `onWorkerConnected` callback will be called after a worker has been created.
480 *
481 * @param {typeof mockWorkerConnections[number]} [onWorkerConnected]
482 * @example
483 * mockWorker((worker) => {
484 * worker.addEventListener("message", (event) => {
485 * expect.step(event.type);
486 * });
487 * });
488 */
489 export function mockWorker(onWorkerConnected) {
490 ensureTest("mockWorker");
491 mockWorkerConnections.push(onWorkerConnected);
492 }
493
494 /**
495 * @param {Parameters<parseNetworkDelay>} args
496 */
497 export function throttleNetwork(...args) {
498 getNetworkDelay = parseNetworkDelay(...args);
499 }
500
501 /**
502 * @param {typeof mockFetchFn} fetchFn
503 * @param {() => void} callback
504 */
505 export async function withFetch(fetchFn, callback) {
506 mockFetchFn = fetchFn;
507 const result = await callback();
508 mockFetchFn = null;
509 return result;
510 }
511
512 export class MockBlob extends Blob {
513 constructor(blobParts, options) {
514 super(blobParts, options);
515
516 setSyncValue(this, blobParts);
517 }
518
519 async arrayBuffer() {
520 return toBytes(getSyncValue(this, true)).buffer;
521 }
522
523 async bytes() {
524 return toBytes(getSyncValue(this, true));
525 }
526
527 async stream() {
528 const value = getSyncValue(this, true);
529 return isInstanceOf(value, ReadableStream) ? value : new ReadableStream(value);
530 }
531
532 async text() {
533 return getSyncValue(this, true);
534 }
535 }
536
537 export class MockBroadcastChannel extends BroadcastChannel {
538 constructor() {
539 super(...arguments);
540
541 markOpen(this);
542 }
543 }
544
545 export class MockCookie {
546 /**
547 * @private
548 * @type {Record<string, string>}
549 */
550 _jar = $create(null);
551
552 get() {
553 return $entries(this._jar)
554 .map((entry) => entry.join("="))
555 .join("; ");
556 }
557
558 /**
559 * @param {string} value
560 */
561 set(value) {
562 for (const cookie of String(value).split(R_SEMICOLON)) {
563 const [key, value] = cookie.split(R_EQUAL);
564 if (value !== "kill" && !["path", "max-age"].includes(key)) {
565 this._jar[key] = value;
566 }
567 }
568 }
569 }
570
571 export class MockDedicatedWorkerGlobalScope {
572 /**
573 * @param {SharedWorker | Worker} worker
574 */
575 constructor(worker) {
576 $assign(
577 this,
578 {
579 cancelanimationframe: mockedCancelAnimationFrame,
580 onconnect: null,
581 requestanimationframe: mockedRequestAnimationFrame,
582 self: this,
583 },
584 worker
585 );
586 if (!("close" in this)) {
587 this.close = worker.terminate.bind(worker);
588 }
589 }
590 }
591
592 export class MockHistory {
593 /**
594 * @private
595 */
596 _index = 0;
597 /**
598 * @private
599 * @type {Location}
600 */
601 _location;
602 /**
603 * @private
604 * @type {[any, string][]}
605 */
606 _stack = [];
607
608 /** @type {History["length"]} */
609 get length() {
610 return this._stack.length;
611 }
612
613 /** @type {History["state"]} */
614 get state() {
615 const entry = this._stack[this._index];
616 return entry && entry[0];
617 }
618
619 /** @type {History["scrollRestoration"]} */
620 get scrollRestoration() {
621 return "auto";
622 }
623
624 /**
625 * @param {Location} location
626 */
627 constructor(location) {
628 this._location = location;
629 this.pushState(null, "", this._location.href);
630 }
631
632 /** @type {History["back"]} */
633 back() {
634 this._index = $max(0, this._index - 1);
635 this._location.assign(this._stack[this._index][1]);
636 this._dispatchPopState();
637 }
638
639 /** @type {History["forward"]} */
640 forward() {
641 this._index = $min(this._stack.length - 1, this._index + 1);
642 this._location.assign(this._stack[this._index][1]);
643 this._dispatchPopState();
644 }
645
646 /** @type {History["go"]} */
647 go(delta) {
648 this._index = $max(0, $min(this._stack.length - 1, this._index + delta));
649 this._location.assign(this._stack[this._index][1]);
650 this._dispatchPopState();
651 }
652
653 /** @type {History["pushState"]} */
654 pushState(data, unused, url) {
655 this._stack = this._stack.slice(0, this._index + 1);
656 this._index = this._stack.push([data ?? null, url]) - 1;
657 this._location.assign(url);
658 }
659
660 /** @type {History["replaceState"]} */
661 replaceState(data, unused, url) {
662 this._stack[this._index] = [data ?? null, url];
663 this._location.assign(url);
664 }
665
666 /**
667 * @private
668 */
669 _dispatchPopState() {
670 window.dispatchEvent(new PopStateEvent("popstate", { state: this.state }));
671 }
672 }
673
674 export class MockLocation extends MockEventTarget {
675 static publicListeners = ["reload"];
676
677 /**
678 * @private
679 */
680 _anchor = document.createElement("a");
681
682 get ancestorOrigins() {
683 return [];
684 }
685
686 get hash() {
687 return this._anchor.hash;
688 }
689 set hash(value) {
690 this._anchor.hash = value;
691 }
692
693 get host() {
694 return this._anchor.host;
695 }
696 set host(value) {
697 this._anchor.host = value;
698 }
699
700 get hostname() {
701 return this._anchor.hostname;
702 }
703 set hostname(value) {
704 this._anchor.hostname = value;
705 }
706
707 get href() {
708 return this._anchor.href;
709 }
710 set href(value) {
711 this._anchor.href = value;
712 }
713
714 get origin() {
715 return this._anchor.origin;
716 }
717 set origin(value) {
718 this._anchor.origin = value;
719 }
720
721 get pathname() {
722 return this._anchor.pathname;
723 }
724 set pathname(value) {
725 this._anchor.pathname = value;
726 }
727
728 get port() {
729 return this._anchor.port;
730 }
731 set port(value) {
732 this._anchor.port = value;
733 }
734
735 get protocol() {
736 return this._anchor.protocol;
737 }
738 set protocol(value) {
739 this._anchor.protocol = value;
740 }
741
742 get search() {
743 return this._anchor.search;
744 }
745 set search(value) {
746 this._anchor.search = value;
747 }
748
749 constructor() {
750 super();
751
752 this.href = DEFAULT_URL;
753 }
754
755 assign(url) {
756 this.href = url;
757 }
758
759 reload() {
760 this.dispatchEvent(new CustomEvent("reload"));
761 }
762
763 replace(url) {
764 this.href = url;
765 }
766
767 toString() {
768 return this._anchor.toString();
769 }
770 }
771
772 export class MockMessageChannel {
773 /**
774 * @protected
775 */
776 _mutex = Promise.resolve();
777
778 constructor() {
779 markOpen(this);
780
781 this.port1 = new MockMessagePort(this);
782 this.port2 = new MockMessagePort(this);
783 this.port1._target = this.port2;
784 this.port2._target = this.port1;
785 }
786 }
787
788 export class MockMessagePort extends MockEventTarget {
789 static publicListeners = ["error", "message"];
790
791 /**
792 * @private
793 * @type {MessageChannel}
794 */
795 _owner;
796 /**
797 * @private
798 * @type {MockMessagePort}
799 */
800 _target = this;
801
802 /**
803 * @param {MessageChannel} owner
804 */
805 constructor(owner) {
806 super();
807
808 this._owner = owner;
809 }
810
811 /** @type {MessagePort["close"]} */
812 close() {
813 // Closing a message port also closes its sibling port & parent channel.
814 markClosed(this, this._target, this._owner);
815 }
816
817 /** @type {MessagePort["postMessage"]} */
818 postMessage(message, transfer) {
819 if (!isOpen(this, this._owner, this._target)) {
820 return;
821 }
822 if (this._owner._mutex) {
823 this._owner._mutex = this._owner._mutex.then(() =>
824 dispatchMessage(this._target, message, transfer)
825 );
826 } else {
827 dispatchMessage(this._target, message, transfer);
828 }
829 }
830
831 /** @type {MessagePort["start"]} */
832 start() {
833 markOpen(this);
834 }
835 }
836
837 export class MockRequest extends Request {
838 static {
839 Object.assign(this.prototype, requestResponseMixin);
840 }
841
842 /**
843 * @param {RequestInfo} input
844 * @param {RequestInit} [init]
845 */
846 constructor(input, init) {
847 super(new MockURL(input), init);
848
849 setSyncValue(this, init?.body ?? null);
850 }
851
852 clone() {
853 const request = new this.constructor(this.url, this);
854 setSyncValue(request, getSyncValue(this, false));
855 return request;
856 }
857
858 /**
859 * In tests, requests objects are expected to be read by multiple network handlers.
860 * As such, their 'body' isn't consumed upon reading.
861 *
862 * @protected
863 * @param {string} reader
864 * @param {boolean} toStringValue
865 */
866 _readValue(reader, toStringValue) {
867 return getSyncValue(this, toStringValue);
868 }
869 }
870
871 export class MockResponse extends Response {
872 static {
873 Object.assign(this.prototype, requestResponseMixin);
874 }
875
876 /**
877 * @param {BodyInit} body
878 * @param {MockResponseInit} [init]
879 */
880 constructor(body, init) {
881 super(body, init);
882
883 if (init?.type) {
884 $defineProperty(this, "type", {
885 value: init.type,
886 configurable: true,
887 enumerable: true,
888 writable: false,
889 });
890 }
891 if (init?.url) {
892 $defineProperty(this, "url", {
893 value: String(new MockURL(init.url)),
894 configurable: true,
895 enumerable: true,
896 writable: false,
897 });
898 }
899
900 setSyncValue(this, body ?? null);
901 }
902
903 clone() {
904 return new this.constructor(getSyncValue(this, false), this);
905 }
906
907 /**
908 * Reading the 'body' of a response always consumes it, as opposed to the {@link MockRequest}
909 * body.
910 *
911 * @protected
912 * @param {string} reader
913 * @param {boolean} toStringValue
914 */
915 _readValue(reader, toStringValue) {
916 if (this.bodyUsed) {
917 throw new TypeError(
918 `Failed to execute '${reader}' on '${this.constructor.name}': body stream already read`
919 );
920 }
921 $defineProperty(this, "bodyUsed", { value: true, configurable: true, enumerable: true });
922 return getSyncValue(this, toStringValue);
923 }
924 }
925
926 export class MockSharedWorker extends MockEventTarget {
927 static publicListeners = ["error"];
928
929 /**
930 * @private
931 */
932 _messageChannel = new MockMessageChannel();
933
934 get port() {
935 return this._messageChannel.port1;
936 }
937
938 /**
939 * @param {string | URL} scriptURL
940 * @param {WorkerOptions} [options]
941 */
942 constructor(scriptURL, options) {
943 super();
944
945 markOpen(this);
946
947 this.url = String(scriptURL);
948 this.name = options?.name || "";
949
950 // First port has to be started manually
951 this._messageChannel.port2.start();
952
953 for (const onWorkerConnected of mockWorkerConnections) {
954 onWorkerConnected(this);
955 }
956 }
957 }
958
959 export class MockURL extends URL {
960 constructor(url, base) {
961 super(url, base || mockLocation);
962 }
963 }
964
965 export class MockWebSocket extends MockEventTarget {
966 static CONNECTING = 0;
967 static OPEN = 1;
968 static CLOSING = 2;
969 static CLOSED = 3;
970 static publicListeners = ["close", "error", "message", "open"];
971
972 /**
973 * @private
974 * @type {ServerWebSocket}
975 */
976 _serverWs;
977 /**
978 * @private
979 * @type {ReturnType<typeof makeNetworkLogger>}
980 */
981 _logger = null;
982 /**
983 * @private
984 */
985 _readyState = WebSocket.CONNECTING;
986
987 get readyState() {
988 return this._readyState;
989 }
990
991 /**
992 * @param {string | URL} url
993 * @param {string | string[]} [protocols]
994 */
995 constructor(url, protocols) {
996 super();
997
998 this.url = String(url);
999 this.protocols = ensureArray(protocols || []);
1000
1001 this._logger = makeNetworkLogger("WS", this.url);
1002 this._serverWs = new ServerWebSocket(this, this._logger);
1003
1004 this.addEventListener("close", (ev) => {
1005 this._readyState = WebSocket.CLOSED;
1006 dispatchClose(this._serverWs, ev);
1007 });
1008
1009 tick().then(() => {
1010 markOpen(this);
1011
1012 this._readyState = WebSocket.OPEN;
1013 this._logger.logRequest(() => ["connection open"]);
1014
1015 this.dispatchEvent(new Event("open"));
1016 });
1017 }
1018
1019 /** @type {WebSocket["close"]} */
1020 close(code, reason) {
1021 if (this.readyState !== WebSocket.OPEN) {
1022 return;
1023 }
1024 this._readyState = WebSocket.CLOSING;
1025 tick().then(() => dispatchClose(this, { code, reason }));
1026 }
1027
1028 /** @type {WebSocket["send"]} */
1029 send(data) {
1030 if (this.readyState !== WebSocket.OPEN) {
1031 return;
1032 }
1033 this._logger.logRequest(() => [data]);
1034 dispatchMessage(this._serverWs, data);
1035 }
1036 }
1037
1038 export class MockWorker extends MockEventTarget {
1039 static publicListeners = ["error", "message"];
1040
1041 /**
1042 * @private
1043 */
1044 _messageChannel = new MockMessageChannel();
1045
1046 /**
1047 * @param {string | URL} scriptURL
1048 * @param {WorkerOptions} [options]
1049 */
1050 constructor(scriptURL, options) {
1051 super();
1052
1053 markOpen(this);
1054
1055 this.url = String(scriptURL);
1056 this.name = options?.name || "";
1057
1058 this._messageChannel.port1.start();
1059 this._messageChannel.port2.start();
1060 this._messageChannel.port1.addEventListener("message", (ev) => {
1061 this.dispatchEvent(new MessageEvent("message", { data: ev.data }));
1062 });
1063
1064 for (const onWorkerConnected of mockWorkerConnections) {
1065 onWorkerConnected(this);
1066 }
1067 }
1068
1069 /** @type {Worker["postMessage"]} */
1070 postMessage(message, transfer) {
1071 if (!isOpen(this, this._messageChannel.port1)) {
1072 return;
1073 }
1074 this._messageChannel.port1.postMessage(message, transfer);
1075 }
1076
1077 /** @type {Worker["terminate"]} */
1078 terminate() {
1079 if (!isOpen(this, this._messageChannel.port1)) {
1080 return;
1081 }
1082 this._messageChannel.port1.close();
1083
1084 markClosed(this);
1085 }
1086 }
1087
1088 export class MockXMLHttpRequest extends MockEventTarget {
1089 static publicListeners = ["error", "load"];
1090 static {
1091 // Assign status codes
1092 Object.assign(this, XMLHttpRequest);
1093 }
1094
1095 /**
1096 * @private
1097 */
1098 _method = "GET";
1099 /**
1100 * @private
1101 */
1102 _readyState = XMLHttpRequest.UNSENT;
1103 /**
1104 * @type {Record<string, string>}
1105 * @private
1106 */
1107 _requestHeaders = Object.create(null);
1108 /**
1109 * @private
1110 */
1111 _requestUrl = "";
1112 /**
1113 * @type {Response | null}
1114 * @private
1115 */
1116 _response = null;
1117 /**
1118 * @private
1119 */
1120 _responseMimeType = "";
1121 /**
1122 * @private
1123 */
1124 _responseValue = null;
1125
1126 get readyState() {
1127 return this._readyState;
1128 }
1129
1130 get response() {
1131 return this._responseValue;
1132 }
1133
1134 get responseText() {
1135 return String(this._responseValue);
1136 }
1137
1138 get responseURL() {
1139 return this._response.url;
1140 }
1141
1142 get responseXML() {
1143 const parser = new DOMParser();
1144 try {
1145 return parser.parseFromString(this._responseValue, this._responseMimeType);
1146 } catch {
1147 return null;
1148 }
1149 }
1150
1151 get status() {
1152 return this._response?.status || 0;
1153 }
1154
1155 get statusText() {
1156 return this._readyState >= XMLHttpRequest.LOADING ? "OK" : "";
1157 }
1158
1159 /**
1160 * @type {XMLHttpRequestResponseType}
1161 */
1162 responseType = "";
1163 upload = new MockXMLHttpRequestUpload();
1164
1165 abort() {
1166 this._setReadyState(XMLHttpRequest.DONE);
1167 markClosed(this);
1168 }
1169
1170 /** @type {XMLHttpRequest["dispatchEvent"]} */
1171 dispatchEvent(event) {
1172 if (!isOpen(this)) {
1173 return false;
1174 }
1175 return super.dispatchEvent(event);
1176 }
1177
1178 getAllResponseHeaders() {
1179 let result = "";
1180 for (const [key, value] of this._response?.headers || []) {
1181 result += `${key}: ${value}\r\n`;
1182 }
1183 return result;
1184 }
1185
1186 /** @type {XMLHttpRequest["getResponseHeader"]} */
1187 getResponseHeader(name) {
1188 return this._response?.headers.get(name) || "";
1189 }
1190
1191 /** @type {XMLHttpRequest["open"]} */
1192 open(method, url) {
1193 markOpen(this);
1194
1195 this._method = method;
1196 this._requestUrl = url;
1197 this._setReadyState(XMLHttpRequest.OPENED);
1198 }
1199
1200 /** @type {XMLHttpRequest["overrideMimeType"]} */
1201 overrideMimeType(mime) {
1202 this._responseMimeType = mime;
1203 }
1204
1205 /** @type {XMLHttpRequest["send"]} */
1206 async send(body) {
1207 if (!isOpen(this)) {
1208 return ENDLESS_PROMISE;
1209 }
1210 this._setReadyState(XMLHttpRequest.HEADERS_RECEIVED);
1211
1212 try {
1213 this._response = await window.fetch(this._requestUrl, {
1214 method: this._method,
1215 body,
1216 headers: this._requestHeaders,
1217 });
1218 this._setReadyState(XMLHttpRequest.LOADING);
1219 if (!this._responseMimeType) {
1220 if (this._response.url.startsWith("blob:")) {
1221 this._responseMimeType = MIME_TYPE.blob;
1222 } else {
1223 this._responseMimeType = this._response.headers.get(HEADER.contentType);
1224 }
1225 }
1226 if (this._response instanceof MockResponse) {
1227 // Mock response: get bound value (synchronously)
1228 this._responseValue = getSyncValue(this._response, false);
1229 } else if (this._responseMimeType === MIME_TYPE.blob) {
1230 // Actual "blob:" response: get array buffer
1231 this._responseValue = await this._response.arrayBuffer();
1232 } else if (this._responseMimeType === MIME_TYPE.json) {
1233 // JSON response: get parsed JSON value
1234 this._responseValue = await this._response.json();
1235 } else {
1236 // Anything else: parse response body as text
1237 this._responseValue = await this._response.text();
1238 }
1239 this.dispatchEvent(new ProgressEvent("load"));
1240 } catch {
1241 this.dispatchEvent(new ProgressEvent("error"));
1242 }
1243
1244 this._setReadyState(XMLHttpRequest.DONE);
1245 markClosed(this);
1246 }
1247
1248 /** @type {XMLHttpRequest["setRequestHeader"]} */
1249 setRequestHeader(name, value) {
1250 this._requestHeaders[name] = value;
1251 }
1252
1253 /**
1254 * @private
1255 * @param {number} readyState
1256 */
1257 _setReadyState(readyState) {
1258 this._readyState = readyState;
1259 this.dispatchEvent(new Event("readystatechange"));
1260 }
1261 }
1262
1263 export class MockXMLHttpRequestUpload extends MockEventTarget {
1264 static publicListeners = [
1265 "abort",
1266 "error",
1267 "load",
1268 "loadend",
1269 "loadstart",
1270 "progress",
1271 "timeout",
1272 ];
1273 }
1274
1275 export class ServerWebSocket extends MockEventTarget {
1276 /**
1277 * @private
1278 * @type {MockWebSocket}
1279 */
1280 _clientWs;
1281 /**
1282 * @private
1283 * @type {ReturnType<typeof makeNetworkLogger>}
1284 */
1285 _logger = null;
1286
1287 get readyState() {
1288 return this._clientWs.readyState;
1289 }
1290
1291 get url() {
1292 return this._clientWs.url;
1293 }
1294
1295 /**
1296 * @param {WebSocket} websocket
1297 * @param {ReturnType<typeof makeNetworkLogger>} logger
1298 */
1299 constructor(websocket, logger) {
1300 super();
1301
1302 markOpen(this);
1303
1304 this._clientWs = websocket;
1305 this._logger = logger;
1306
1307 this.addEventListener("close", (ev) => {
1308 dispatchClose(this._clientWs, ev);
1309 this._logger.logResponse(() => ["connection closed", ev]);
1310 });
1311
1312 mockWebSocketConnection?.(this);
1313 this.dispatchEvent(new Event("open"));
1314 }
1315
1316 /** @type {WebSocket["close"]} */
1317 close(code, reason) {
1318 dispatchClose(this, { code, reason });
1319 }
1320
1321 /** @type {WebSocket["send"]} */
1322 send(data) {
1323 if (!isOpen(this)) {
1324 return;
1325 }
1326 this._logger.logResponse(() => data);
1327 dispatchMessage(this._clientWs, data);
1328 }
1329 }
1330
1331 export const mockCookie = new MockCookie();
1332 export const mockLocation = new MockLocation();
1333 export const mockHistory = new MockHistory(mockLocation);