msw 2.1.3 → 2.1.4

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.
@@ -25,16 +25,119 @@ __export(browser_exports, {
25
25
  });
26
26
  module.exports = __toCommonJS(browser_exports);
27
27
 
28
- // src/browser/setupWorker/setupWorker.ts
29
- var import_outvariant = require("outvariant");
30
- var import_is_node_process = require("is-node-process");
28
+ // node_modules/.pnpm/outvariant@1.4.2/node_modules/outvariant/lib/index.mjs
29
+ var POSITIONALS_EXP = /(%?)(%([sdijo]))/g;
30
+ function serializePositional(positional, flag) {
31
+ switch (flag) {
32
+ case "s":
33
+ return positional;
34
+ case "d":
35
+ case "i":
36
+ return Number(positional);
37
+ case "j":
38
+ return JSON.stringify(positional);
39
+ case "o": {
40
+ if (typeof positional === "string") {
41
+ return positional;
42
+ }
43
+ const json = JSON.stringify(positional);
44
+ if (json === "{}" || json === "[]" || /^\[object .+?\]$/.test(json)) {
45
+ return positional;
46
+ }
47
+ return json;
48
+ }
49
+ }
50
+ }
51
+ function format(message, ...positionals) {
52
+ if (positionals.length === 0) {
53
+ return message;
54
+ }
55
+ let positionalIndex = 0;
56
+ let formattedMessage = message.replace(
57
+ POSITIONALS_EXP,
58
+ (match, isEscaped, _, flag) => {
59
+ const positional = positionals[positionalIndex];
60
+ const value = serializePositional(positional, flag);
61
+ if (!isEscaped) {
62
+ positionalIndex++;
63
+ return value;
64
+ }
65
+ return match;
66
+ }
67
+ );
68
+ if (positionalIndex < positionals.length) {
69
+ formattedMessage += ` ${positionals.slice(positionalIndex).join(" ")}`;
70
+ }
71
+ formattedMessage = formattedMessage.replace(/%{2,2}/g, "%");
72
+ return formattedMessage;
73
+ }
74
+ var STACK_FRAMES_TO_IGNORE = 2;
75
+ function cleanErrorStack(error2) {
76
+ if (!error2.stack) {
77
+ return;
78
+ }
79
+ const nextStack = error2.stack.split("\n");
80
+ nextStack.splice(1, STACK_FRAMES_TO_IGNORE);
81
+ error2.stack = nextStack.join("\n");
82
+ }
83
+ var InvariantError = class extends Error {
84
+ constructor(message, ...positionals) {
85
+ super(message);
86
+ this.message = message;
87
+ this.name = "Invariant Violation";
88
+ this.message = format(message, ...positionals);
89
+ cleanErrorStack(this);
90
+ }
91
+ };
92
+ var invariant = (predicate, message, ...positionals) => {
93
+ if (!predicate) {
94
+ throw new InvariantError(message, ...positionals);
95
+ }
96
+ };
97
+ invariant.as = (ErrorConstructor, predicate, message, ...positionals) => {
98
+ if (!predicate) {
99
+ const formatMessage = positionals.length === 0 ? message : format(message, positionals);
100
+ let error2;
101
+ try {
102
+ error2 = Reflect.construct(ErrorConstructor, [formatMessage]);
103
+ } catch (err) {
104
+ error2 = ErrorConstructor(formatMessage);
105
+ }
106
+ throw error2;
107
+ }
108
+ };
109
+
110
+ // node_modules/.pnpm/is-node-process@1.2.0/node_modules/is-node-process/lib/index.mjs
111
+ function isNodeProcess() {
112
+ if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
113
+ return true;
114
+ }
115
+ if (typeof process !== "undefined") {
116
+ const type = process.type;
117
+ if (type === "renderer" || type === "worker") {
118
+ return false;
119
+ }
120
+ return !!(process.versions && process.versions.node);
121
+ }
122
+ return false;
123
+ }
124
+
125
+ // node_modules/.pnpm/@open-draft+until@2.1.0/node_modules/@open-draft/until/lib/index.mjs
126
+ var until = async (promise) => {
127
+ try {
128
+ const data = await promise().catch((error2) => {
129
+ throw error2;
130
+ });
131
+ return { error: null, data };
132
+ } catch (error2) {
133
+ return { error: error2, data: null };
134
+ }
135
+ };
31
136
 
32
137
  // src/browser/setupWorker/start/createStartHandler.ts
33
- var import_until2 = require("@open-draft/until");
34
138
  var import_devUtils6 = require("../core/utils/internal/devUtils.js");
35
139
 
36
140
  // src/browser/setupWorker/start/utils/getWorkerInstance.ts
37
- var import_until = require("@open-draft/until");
38
141
  var import_devUtils = require("../core/utils/internal/devUtils.js");
39
142
 
40
143
  // src/browser/utils/getAbsoluteWorkerUrl.ts
@@ -82,7 +185,7 @@ var getWorkerInstance = async (url, options = {}, findWorker) => {
82
185
  ];
83
186
  });
84
187
  }
85
- const registrationResult = await (0, import_until.until)(
188
+ const registrationResult = await until(
86
189
  async () => {
87
190
  const registration = await navigator.serviceWorker.register(url, options);
88
191
  return [
@@ -243,8 +346,8 @@ var createRequestListener = (context, options) => {
243
346
  }
244
347
  }
245
348
  );
246
- } catch (error) {
247
- if (error instanceof Error) {
349
+ } catch (error2) {
350
+ if (error2 instanceof Error) {
248
351
  import_devUtils4.devUtils.error(
249
352
  `Uncaught exception in the request handler for "%s %s":
250
353
 
@@ -253,7 +356,7 @@ var createRequestListener = (context, options) => {
253
356
  This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/recipes/mocking-error-responses`,
254
357
  request.method,
255
358
  request.url,
256
- error.stack ?? error
359
+ error2.stack ?? error2
257
360
  );
258
361
  messageChannel.postMessage("MOCK_RESPONSE", {
259
362
  status: 500,
@@ -262,9 +365,9 @@ This exception has been gracefully handled as a 500 response, however, it's stro
262
365
  "Content-Type": "application/json"
263
366
  },
264
367
  body: JSON.stringify({
265
- name: error.name,
266
- message: error.message,
267
- stack: error.stack
368
+ name: error2.name,
369
+ message: error2.message,
370
+ stack: error2.stack
268
371
  })
269
372
  });
270
373
  }
@@ -286,8 +389,658 @@ async function requestIntegrityCheck(context, serviceWorker) {
286
389
  return serviceWorker;
287
390
  }
288
391
 
392
+ // node_modules/.pnpm/@mswjs+interceptors@0.25.14/node_modules/@mswjs/interceptors/lib/browser/chunk-UJZOJSMP.mjs
393
+ var encoder = new TextEncoder();
394
+ function encodeBuffer(text) {
395
+ return encoder.encode(text);
396
+ }
397
+ function decodeBuffer(buffer, encoding) {
398
+ const decoder = new TextDecoder(encoding);
399
+ return decoder.decode(buffer);
400
+ }
401
+ function toArrayBuffer(array) {
402
+ return array.buffer.slice(
403
+ array.byteOffset,
404
+ array.byteOffset + array.byteLength
405
+ );
406
+ }
407
+ var RESPONSE_STATUS_CODES_WITHOUT_BODY = /* @__PURE__ */ new Set([
408
+ 101,
409
+ 103,
410
+ 204,
411
+ 205,
412
+ 304
413
+ ]);
414
+ function isResponseWithoutBody(status) {
415
+ return RESPONSE_STATUS_CODES_WITHOUT_BODY.has(status);
416
+ }
417
+
418
+ // node_modules/.pnpm/@open-draft+logger@0.3.0/node_modules/@open-draft/logger/lib/index.mjs
419
+ var __defProp2 = Object.defineProperty;
420
+ var __export2 = (target, all) => {
421
+ for (var name in all)
422
+ __defProp2(target, name, { get: all[name], enumerable: true });
423
+ };
424
+ var colors_exports = {};
425
+ __export2(colors_exports, {
426
+ blue: () => blue,
427
+ gray: () => gray,
428
+ green: () => green,
429
+ red: () => red,
430
+ yellow: () => yellow
431
+ });
432
+ function yellow(text) {
433
+ return `\x1B[33m${text}\x1B[0m`;
434
+ }
435
+ function blue(text) {
436
+ return `\x1B[34m${text}\x1B[0m`;
437
+ }
438
+ function gray(text) {
439
+ return `\x1B[90m${text}\x1B[0m`;
440
+ }
441
+ function red(text) {
442
+ return `\x1B[31m${text}\x1B[0m`;
443
+ }
444
+ function green(text) {
445
+ return `\x1B[32m${text}\x1B[0m`;
446
+ }
447
+ var IS_NODE = isNodeProcess();
448
+ var Logger = class {
449
+ constructor(name) {
450
+ this.name = name;
451
+ this.prefix = `[${this.name}]`;
452
+ const LOGGER_NAME = getVariable("DEBUG");
453
+ const LOGGER_LEVEL = getVariable("LOG_LEVEL");
454
+ const isLoggingEnabled = LOGGER_NAME === "1" || LOGGER_NAME === "true" || typeof LOGGER_NAME !== "undefined" && this.name.startsWith(LOGGER_NAME);
455
+ if (isLoggingEnabled) {
456
+ this.debug = isDefinedAndNotEquals(LOGGER_LEVEL, "debug") ? noop : this.debug;
457
+ this.info = isDefinedAndNotEquals(LOGGER_LEVEL, "info") ? noop : this.info;
458
+ this.success = isDefinedAndNotEquals(LOGGER_LEVEL, "success") ? noop : this.success;
459
+ this.warning = isDefinedAndNotEquals(LOGGER_LEVEL, "warning") ? noop : this.warning;
460
+ this.error = isDefinedAndNotEquals(LOGGER_LEVEL, "error") ? noop : this.error;
461
+ } else {
462
+ this.info = noop;
463
+ this.success = noop;
464
+ this.warning = noop;
465
+ this.error = noop;
466
+ this.only = noop;
467
+ }
468
+ }
469
+ prefix;
470
+ extend(domain) {
471
+ return new Logger(`${this.name}:${domain}`);
472
+ }
473
+ /**
474
+ * Print a debug message.
475
+ * @example
476
+ * logger.debug('no duplicates found, creating a document...')
477
+ */
478
+ debug(message, ...positionals) {
479
+ this.logEntry({
480
+ level: "debug",
481
+ message: gray(message),
482
+ positionals,
483
+ prefix: this.prefix,
484
+ colors: {
485
+ prefix: "gray"
486
+ }
487
+ });
488
+ }
489
+ /**
490
+ * Print an info message.
491
+ * @example
492
+ * logger.info('start parsing...')
493
+ */
494
+ info(message, ...positionals) {
495
+ this.logEntry({
496
+ level: "info",
497
+ message,
498
+ positionals,
499
+ prefix: this.prefix,
500
+ colors: {
501
+ prefix: "blue"
502
+ }
503
+ });
504
+ const performance2 = new PerformanceEntry();
505
+ return (message2, ...positionals2) => {
506
+ performance2.measure();
507
+ this.logEntry({
508
+ level: "info",
509
+ message: `${message2} ${gray(`${performance2.deltaTime}ms`)}`,
510
+ positionals: positionals2,
511
+ prefix: this.prefix,
512
+ colors: {
513
+ prefix: "blue"
514
+ }
515
+ });
516
+ };
517
+ }
518
+ /**
519
+ * Print a success message.
520
+ * @example
521
+ * logger.success('successfully created document')
522
+ */
523
+ success(message, ...positionals) {
524
+ this.logEntry({
525
+ level: "info",
526
+ message,
527
+ positionals,
528
+ prefix: `\u2714 ${this.prefix}`,
529
+ colors: {
530
+ timestamp: "green",
531
+ prefix: "green"
532
+ }
533
+ });
534
+ }
535
+ /**
536
+ * Print a warning.
537
+ * @example
538
+ * logger.warning('found legacy document format')
539
+ */
540
+ warning(message, ...positionals) {
541
+ this.logEntry({
542
+ level: "warning",
543
+ message,
544
+ positionals,
545
+ prefix: `\u26A0 ${this.prefix}`,
546
+ colors: {
547
+ timestamp: "yellow",
548
+ prefix: "yellow"
549
+ }
550
+ });
551
+ }
552
+ /**
553
+ * Print an error message.
554
+ * @example
555
+ * logger.error('something went wrong')
556
+ */
557
+ error(message, ...positionals) {
558
+ this.logEntry({
559
+ level: "error",
560
+ message,
561
+ positionals,
562
+ prefix: `\u2716 ${this.prefix}`,
563
+ colors: {
564
+ timestamp: "red",
565
+ prefix: "red"
566
+ }
567
+ });
568
+ }
569
+ /**
570
+ * Execute the given callback only when the logging is enabled.
571
+ * This is skipped in its entirety and has no runtime cost otherwise.
572
+ * This executes regardless of the log level.
573
+ * @example
574
+ * logger.only(() => {
575
+ * logger.info('additional info')
576
+ * })
577
+ */
578
+ only(callback) {
579
+ callback();
580
+ }
581
+ createEntry(level, message) {
582
+ return {
583
+ timestamp: /* @__PURE__ */ new Date(),
584
+ level,
585
+ message
586
+ };
587
+ }
588
+ logEntry(args) {
589
+ const {
590
+ level,
591
+ message,
592
+ prefix,
593
+ colors: customColors,
594
+ positionals = []
595
+ } = args;
596
+ const entry = this.createEntry(level, message);
597
+ const timestampColor = customColors?.timestamp || "gray";
598
+ const prefixColor = customColors?.prefix || "gray";
599
+ const colorize = {
600
+ timestamp: colors_exports[timestampColor],
601
+ prefix: colors_exports[prefixColor]
602
+ };
603
+ const write = this.getWriter(level);
604
+ write(
605
+ [colorize.timestamp(this.formatTimestamp(entry.timestamp))].concat(prefix != null ? colorize.prefix(prefix) : []).concat(serializeInput(message)).join(" "),
606
+ ...positionals.map(serializeInput)
607
+ );
608
+ }
609
+ formatTimestamp(timestamp) {
610
+ return `${timestamp.toLocaleTimeString(
611
+ "en-GB"
612
+ )}:${timestamp.getMilliseconds()}`;
613
+ }
614
+ getWriter(level) {
615
+ switch (level) {
616
+ case "debug":
617
+ case "success":
618
+ case "info": {
619
+ return log;
620
+ }
621
+ case "warning": {
622
+ return warn;
623
+ }
624
+ case "error": {
625
+ return error;
626
+ }
627
+ }
628
+ }
629
+ };
630
+ var PerformanceEntry = class {
631
+ startTime;
632
+ endTime;
633
+ deltaTime;
634
+ constructor() {
635
+ this.startTime = performance.now();
636
+ }
637
+ measure() {
638
+ this.endTime = performance.now();
639
+ const deltaTime = this.endTime - this.startTime;
640
+ this.deltaTime = deltaTime.toFixed(2);
641
+ }
642
+ };
643
+ var noop = () => void 0;
644
+ function log(message, ...positionals) {
645
+ if (IS_NODE) {
646
+ process.stdout.write(format(message, ...positionals) + "\n");
647
+ return;
648
+ }
649
+ console.log(message, ...positionals);
650
+ }
651
+ function warn(message, ...positionals) {
652
+ if (IS_NODE) {
653
+ process.stderr.write(format(message, ...positionals) + "\n");
654
+ return;
655
+ }
656
+ console.warn(message, ...positionals);
657
+ }
658
+ function error(message, ...positionals) {
659
+ if (IS_NODE) {
660
+ process.stderr.write(format(message, ...positionals) + "\n");
661
+ return;
662
+ }
663
+ console.error(message, ...positionals);
664
+ }
665
+ function getVariable(variableName) {
666
+ if (IS_NODE) {
667
+ return process.env[variableName];
668
+ }
669
+ return globalThis[variableName]?.toString();
670
+ }
671
+ function isDefinedAndNotEquals(value, expected) {
672
+ return value !== void 0 && value !== expected;
673
+ }
674
+ function serializeInput(message) {
675
+ if (typeof message === "undefined") {
676
+ return "undefined";
677
+ }
678
+ if (message === null) {
679
+ return "null";
680
+ }
681
+ if (typeof message === "string") {
682
+ return message;
683
+ }
684
+ if (typeof message === "object") {
685
+ return JSON.stringify(message);
686
+ }
687
+ return message.toString();
688
+ }
689
+
690
+ // node_modules/.pnpm/strict-event-emitter@0.5.1/node_modules/strict-event-emitter/lib/index.mjs
691
+ var MemoryLeakError = class extends Error {
692
+ constructor(emitter, type, count) {
693
+ super(
694
+ `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`
695
+ );
696
+ this.emitter = emitter;
697
+ this.type = type;
698
+ this.count = count;
699
+ this.name = "MaxListenersExceededWarning";
700
+ }
701
+ };
702
+ var _Emitter = class {
703
+ static listenerCount(emitter, eventName) {
704
+ return emitter.listenerCount(eventName);
705
+ }
706
+ constructor() {
707
+ this.events = /* @__PURE__ */ new Map();
708
+ this.maxListeners = _Emitter.defaultMaxListeners;
709
+ this.hasWarnedAboutPotentialMemoryLeak = false;
710
+ }
711
+ _emitInternalEvent(internalEventName, eventName, listener) {
712
+ this.emit(
713
+ internalEventName,
714
+ ...[eventName, listener]
715
+ );
716
+ }
717
+ _getListeners(eventName) {
718
+ return Array.prototype.concat.apply([], this.events.get(eventName)) || [];
719
+ }
720
+ _removeListener(listeners, listener) {
721
+ const index = listeners.indexOf(listener);
722
+ if (index > -1) {
723
+ listeners.splice(index, 1);
724
+ }
725
+ return [];
726
+ }
727
+ _wrapOnceListener(eventName, listener) {
728
+ const onceListener = (...data) => {
729
+ this.removeListener(eventName, onceListener);
730
+ return listener.apply(this, data);
731
+ };
732
+ Object.defineProperty(onceListener, "name", { value: listener.name });
733
+ return onceListener;
734
+ }
735
+ setMaxListeners(maxListeners) {
736
+ this.maxListeners = maxListeners;
737
+ return this;
738
+ }
739
+ /**
740
+ * Returns the current max listener value for the `Emitter` which is
741
+ * either set by `emitter.setMaxListeners(n)` or defaults to
742
+ * `Emitter.defaultMaxListeners`.
743
+ */
744
+ getMaxListeners() {
745
+ return this.maxListeners;
746
+ }
747
+ /**
748
+ * Returns an array listing the events for which the emitter has registered listeners.
749
+ * The values in the array will be strings or Symbols.
750
+ */
751
+ eventNames() {
752
+ return Array.from(this.events.keys());
753
+ }
754
+ /**
755
+ * Synchronously calls each of the listeners registered for the event named `eventName`,
756
+ * in the order they were registered, passing the supplied arguments to each.
757
+ * Returns `true` if the event has listeners, `false` otherwise.
758
+ *
759
+ * @example
760
+ * const emitter = new Emitter<{ hello: [string] }>()
761
+ * emitter.emit('hello', 'John')
762
+ */
763
+ emit(eventName, ...data) {
764
+ const listeners = this._getListeners(eventName);
765
+ listeners.forEach((listener) => {
766
+ listener.apply(this, data);
767
+ });
768
+ return listeners.length > 0;
769
+ }
770
+ addListener(eventName, listener) {
771
+ this._emitInternalEvent("newListener", eventName, listener);
772
+ const nextListeners = this._getListeners(eventName).concat(listener);
773
+ this.events.set(eventName, nextListeners);
774
+ if (this.maxListeners > 0 && this.listenerCount(eventName) > this.maxListeners && !this.hasWarnedAboutPotentialMemoryLeak) {
775
+ this.hasWarnedAboutPotentialMemoryLeak = true;
776
+ const memoryLeakWarning = new MemoryLeakError(
777
+ this,
778
+ eventName,
779
+ this.listenerCount(eventName)
780
+ );
781
+ console.warn(memoryLeakWarning);
782
+ }
783
+ return this;
784
+ }
785
+ on(eventName, listener) {
786
+ return this.addListener(eventName, listener);
787
+ }
788
+ once(eventName, listener) {
789
+ return this.addListener(
790
+ eventName,
791
+ this._wrapOnceListener(eventName, listener)
792
+ );
793
+ }
794
+ prependListener(eventName, listener) {
795
+ const listeners = this._getListeners(eventName);
796
+ if (listeners.length > 0) {
797
+ const nextListeners = [listener].concat(listeners);
798
+ this.events.set(eventName, nextListeners);
799
+ } else {
800
+ this.events.set(eventName, listeners.concat(listener));
801
+ }
802
+ return this;
803
+ }
804
+ prependOnceListener(eventName, listener) {
805
+ return this.prependListener(
806
+ eventName,
807
+ this._wrapOnceListener(eventName, listener)
808
+ );
809
+ }
810
+ removeListener(eventName, listener) {
811
+ const listeners = this._getListeners(eventName);
812
+ if (listeners.length > 0) {
813
+ this._removeListener(listeners, listener);
814
+ this.events.set(eventName, listeners);
815
+ this._emitInternalEvent("removeListener", eventName, listener);
816
+ }
817
+ return this;
818
+ }
819
+ /**
820
+ * Alias for `emitter.removeListener()`.
821
+ *
822
+ * @example
823
+ * emitter.off('hello', listener)
824
+ */
825
+ off(eventName, listener) {
826
+ return this.removeListener(eventName, listener);
827
+ }
828
+ removeAllListeners(eventName) {
829
+ if (eventName) {
830
+ this.events.delete(eventName);
831
+ } else {
832
+ this.events.clear();
833
+ }
834
+ return this;
835
+ }
836
+ /**
837
+ * Returns a copy of the array of listeners for the event named `eventName`.
838
+ */
839
+ listeners(eventName) {
840
+ return Array.from(this._getListeners(eventName));
841
+ }
842
+ /**
843
+ * Returns the number of listeners listening to the event named `eventName`.
844
+ */
845
+ listenerCount(eventName) {
846
+ return this._getListeners(eventName).length;
847
+ }
848
+ rawListeners(eventName) {
849
+ return this.listeners(eventName);
850
+ }
851
+ };
852
+ var Emitter = _Emitter;
853
+ Emitter.defaultMaxListeners = 10;
854
+
855
+ // node_modules/.pnpm/@mswjs+interceptors@0.25.14/node_modules/@mswjs/interceptors/lib/browser/chunk-WZQN3FMY.mjs
856
+ var IS_PATCHED_MODULE = Symbol("isPatchedModule");
857
+ function getGlobalSymbol(symbol) {
858
+ return (
859
+ // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587
860
+ globalThis[symbol] || void 0
861
+ );
862
+ }
863
+ function setGlobalSymbol(symbol, value) {
864
+ globalThis[symbol] = value;
865
+ }
866
+ function deleteGlobalSymbol(symbol) {
867
+ delete globalThis[symbol];
868
+ }
869
+ var Interceptor = class {
870
+ constructor(symbol) {
871
+ this.symbol = symbol;
872
+ this.readyState = "INACTIVE";
873
+ this.emitter = new Emitter();
874
+ this.subscriptions = [];
875
+ this.logger = new Logger(symbol.description);
876
+ this.emitter.setMaxListeners(0);
877
+ this.logger.info("constructing the interceptor...");
878
+ }
879
+ /**
880
+ * Determine if this interceptor can be applied
881
+ * in the current environment.
882
+ */
883
+ checkEnvironment() {
884
+ return true;
885
+ }
886
+ /**
887
+ * Apply this interceptor to the current process.
888
+ * Returns an already running interceptor instance if it's present.
889
+ */
890
+ apply() {
891
+ const logger = this.logger.extend("apply");
892
+ logger.info("applying the interceptor...");
893
+ if (this.readyState === "APPLIED") {
894
+ logger.info("intercepted already applied!");
895
+ return;
896
+ }
897
+ const shouldApply = this.checkEnvironment();
898
+ if (!shouldApply) {
899
+ logger.info("the interceptor cannot be applied in this environment!");
900
+ return;
901
+ }
902
+ this.readyState = "APPLYING";
903
+ const runningInstance = this.getInstance();
904
+ if (runningInstance) {
905
+ logger.info("found a running instance, reusing...");
906
+ this.on = (event, listener) => {
907
+ logger.info('proxying the "%s" listener', event);
908
+ runningInstance.emitter.addListener(event, listener);
909
+ this.subscriptions.push(() => {
910
+ runningInstance.emitter.removeListener(event, listener);
911
+ logger.info('removed proxied "%s" listener!', event);
912
+ });
913
+ return this;
914
+ };
915
+ this.readyState = "APPLIED";
916
+ return;
917
+ }
918
+ logger.info("no running instance found, setting up a new instance...");
919
+ this.setup();
920
+ this.setInstance();
921
+ this.readyState = "APPLIED";
922
+ }
923
+ /**
924
+ * Setup the module augments and stubs necessary for this interceptor.
925
+ * This method is not run if there's a running interceptor instance
926
+ * to prevent instantiating an interceptor multiple times.
927
+ */
928
+ setup() {
929
+ }
930
+ /**
931
+ * Listen to the interceptor's public events.
932
+ */
933
+ on(event, listener) {
934
+ const logger = this.logger.extend("on");
935
+ if (this.readyState === "DISPOSING" || this.readyState === "DISPOSED") {
936
+ logger.info("cannot listen to events, already disposed!");
937
+ return this;
938
+ }
939
+ logger.info('adding "%s" event listener:', event, listener);
940
+ this.emitter.on(event, listener);
941
+ return this;
942
+ }
943
+ once(event, listener) {
944
+ this.emitter.once(event, listener);
945
+ return this;
946
+ }
947
+ off(event, listener) {
948
+ this.emitter.off(event, listener);
949
+ return this;
950
+ }
951
+ removeAllListeners(event) {
952
+ this.emitter.removeAllListeners(event);
953
+ return this;
954
+ }
955
+ /**
956
+ * Disposes of any side-effects this interceptor has introduced.
957
+ */
958
+ dispose() {
959
+ const logger = this.logger.extend("dispose");
960
+ if (this.readyState === "DISPOSED") {
961
+ logger.info("cannot dispose, already disposed!");
962
+ return;
963
+ }
964
+ logger.info("disposing the interceptor...");
965
+ this.readyState = "DISPOSING";
966
+ if (!this.getInstance()) {
967
+ logger.info("no interceptors running, skipping dispose...");
968
+ return;
969
+ }
970
+ this.clearInstance();
971
+ logger.info("global symbol deleted:", getGlobalSymbol(this.symbol));
972
+ if (this.subscriptions.length > 0) {
973
+ logger.info("disposing of %d subscriptions...", this.subscriptions.length);
974
+ for (const dispose of this.subscriptions) {
975
+ dispose();
976
+ }
977
+ this.subscriptions = [];
978
+ logger.info("disposed of all subscriptions!", this.subscriptions.length);
979
+ }
980
+ this.emitter.removeAllListeners();
981
+ logger.info("destroyed the listener!");
982
+ this.readyState = "DISPOSED";
983
+ }
984
+ getInstance() {
985
+ var _a;
986
+ const instance = getGlobalSymbol(this.symbol);
987
+ this.logger.info("retrieved global instance:", (_a = instance == null ? void 0 : instance.constructor) == null ? void 0 : _a.name);
988
+ return instance;
989
+ }
990
+ setInstance() {
991
+ setGlobalSymbol(this.symbol, this);
992
+ this.logger.info("set global instance!", this.symbol.description);
993
+ }
994
+ clearInstance() {
995
+ deleteGlobalSymbol(this.symbol);
996
+ this.logger.info("cleared global instance!", this.symbol.description);
997
+ }
998
+ };
999
+
1000
+ // node_modules/.pnpm/@mswjs+interceptors@0.25.14/node_modules/@mswjs/interceptors/lib/browser/index.mjs
1001
+ var BatchInterceptor = class extends Interceptor {
1002
+ constructor(options) {
1003
+ BatchInterceptor.symbol = Symbol(options.name);
1004
+ super(BatchInterceptor.symbol);
1005
+ this.interceptors = options.interceptors;
1006
+ }
1007
+ setup() {
1008
+ const logger = this.logger.extend("setup");
1009
+ logger.info("applying all %d interceptors...", this.interceptors.length);
1010
+ for (const interceptor of this.interceptors) {
1011
+ logger.info('applying "%s" interceptor...', interceptor.constructor.name);
1012
+ interceptor.apply();
1013
+ logger.info("adding interceptor dispose subscription");
1014
+ this.subscriptions.push(() => interceptor.dispose());
1015
+ }
1016
+ }
1017
+ on(event, listener) {
1018
+ for (const interceptor of this.interceptors) {
1019
+ interceptor.on(event, listener);
1020
+ }
1021
+ return this;
1022
+ }
1023
+ once(event, listener) {
1024
+ for (const interceptor of this.interceptors) {
1025
+ interceptor.once(event, listener);
1026
+ }
1027
+ return this;
1028
+ }
1029
+ off(event, listener) {
1030
+ for (const interceptor of this.interceptors) {
1031
+ interceptor.off(event, listener);
1032
+ }
1033
+ return this;
1034
+ }
1035
+ removeAllListeners(event) {
1036
+ for (const interceptors of this.interceptors) {
1037
+ interceptors.removeAllListeners(event);
1038
+ }
1039
+ return this;
1040
+ }
1041
+ };
1042
+
289
1043
  // src/browser/setupWorker/start/createResponseListener.ts
290
- var import_interceptors = require("@mswjs/interceptors");
291
1044
  function createResponseListener(context) {
292
1045
  return (_, message) => {
293
1046
  const { payload: responseJson } = message;
@@ -301,7 +1054,7 @@ function createResponseListener(context) {
301
1054
  * throw when passed a non-null body, so ensure it's null here
302
1055
  * for those codes
303
1056
  */
304
- (0, import_interceptors.isResponseWithoutBody)(responseJson.status) ? null : responseJson.body,
1057
+ isResponseWithoutBody(responseJson.status) ? null : responseJson.body,
305
1058
  responseJson
306
1059
  );
307
1060
  context.emitter.emit(
@@ -375,7 +1128,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
375
1128
  }
376
1129
  window.clearInterval(context.keepAliveInterval);
377
1130
  });
378
- const integrityCheckResult = await (0, import_until2.until)(
1131
+ const integrityCheckResult = await until(
379
1132
  () => requestIntegrityCheck(context, worker)
380
1133
  );
381
1134
  if (integrityCheckResult.error) {
@@ -407,8 +1160,8 @@ If this message still persists after updating, please report an issue: https://g
407
1160
  });
408
1161
  });
409
1162
  }
410
- await enableMocking(context, options).catch((error) => {
411
- throw new Error(`Failed to enable mocking: ${error?.message}`);
1163
+ await enableMocking(context, options).catch((error2) => {
1164
+ throw new Error(`Failed to enable mocking: ${error2?.message}`);
412
1165
  });
413
1166
  return registration;
414
1167
  }
@@ -463,15 +1216,992 @@ var DEFAULT_START_OPTIONS = {
463
1216
  }
464
1217
  };
465
1218
 
1219
+ // node_modules/.pnpm/@open-draft+deferred-promise@2.2.0/node_modules/@open-draft/deferred-promise/build/index.mjs
1220
+ function createDeferredExecutor() {
1221
+ const executor = (resolve, reject) => {
1222
+ executor.state = "pending";
1223
+ executor.resolve = (data) => {
1224
+ if (executor.state !== "pending") {
1225
+ return;
1226
+ }
1227
+ executor.result = data;
1228
+ const onFulfilled = (value) => {
1229
+ executor.state = "fulfilled";
1230
+ return value;
1231
+ };
1232
+ return resolve(
1233
+ data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)
1234
+ );
1235
+ };
1236
+ executor.reject = (reason) => {
1237
+ if (executor.state !== "pending") {
1238
+ return;
1239
+ }
1240
+ queueMicrotask(() => {
1241
+ executor.state = "rejected";
1242
+ });
1243
+ return reject(executor.rejectionReason = reason);
1244
+ };
1245
+ };
1246
+ return executor;
1247
+ }
1248
+ var DeferredPromise = class extends Promise {
1249
+ #executor;
1250
+ resolve;
1251
+ reject;
1252
+ constructor(executor = null) {
1253
+ const deferredExecutor = createDeferredExecutor();
1254
+ super((originalResolve, originalReject) => {
1255
+ deferredExecutor(originalResolve, originalReject);
1256
+ executor?.(deferredExecutor.resolve, deferredExecutor.reject);
1257
+ });
1258
+ this.#executor = deferredExecutor;
1259
+ this.resolve = this.#executor.resolve;
1260
+ this.reject = this.#executor.reject;
1261
+ }
1262
+ get state() {
1263
+ return this.#executor.state;
1264
+ }
1265
+ get rejectionReason() {
1266
+ return this.#executor.rejectionReason;
1267
+ }
1268
+ then(onFulfilled, onRejected) {
1269
+ return this.#decorate(super.then(onFulfilled, onRejected));
1270
+ }
1271
+ catch(onRejected) {
1272
+ return this.#decorate(super.catch(onRejected));
1273
+ }
1274
+ finally(onfinally) {
1275
+ return this.#decorate(super.finally(onfinally));
1276
+ }
1277
+ #decorate(promise) {
1278
+ return Object.defineProperties(promise, {
1279
+ resolve: { configurable: true, value: this.resolve },
1280
+ reject: { configurable: true, value: this.reject }
1281
+ });
1282
+ }
1283
+ };
1284
+
1285
+ // node_modules/.pnpm/@mswjs+interceptors@0.25.14/node_modules/@mswjs/interceptors/lib/browser/chunk-72HT65NX.mjs
1286
+ function uuidv4() {
1287
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1288
+ const r = Math.random() * 16 | 0;
1289
+ const v = c == "x" ? r : r & 3 | 8;
1290
+ return v.toString(16);
1291
+ });
1292
+ }
1293
+ var RequestController = class {
1294
+ constructor(request) {
1295
+ this.request = request;
1296
+ this.responsePromise = new DeferredPromise();
1297
+ }
1298
+ respondWith(response) {
1299
+ invariant(
1300
+ this.responsePromise.state === "pending",
1301
+ 'Failed to respond to "%s %s" request: the "request" event has already been responded to.',
1302
+ this.request.method,
1303
+ this.request.url
1304
+ );
1305
+ this.responsePromise.resolve(response);
1306
+ }
1307
+ };
1308
+ function toInteractiveRequest(request) {
1309
+ const requestController = new RequestController(request);
1310
+ Reflect.set(
1311
+ request,
1312
+ "respondWith",
1313
+ requestController.respondWith.bind(requestController)
1314
+ );
1315
+ return {
1316
+ interactiveRequest: request,
1317
+ requestController
1318
+ };
1319
+ }
1320
+ async function emitAsync(emitter, eventName, ...data) {
1321
+ const listners = emitter.listeners(eventName);
1322
+ if (listners.length === 0) {
1323
+ return;
1324
+ }
1325
+ for (const listener of listners) {
1326
+ await listener.apply(emitter, data);
1327
+ }
1328
+ }
1329
+
1330
+ // node_modules/.pnpm/@mswjs+interceptors@0.25.14/node_modules/@mswjs/interceptors/lib/browser/chunk-KDHQ3KDO.mjs
1331
+ function isPropertyAccessible(obj, key) {
1332
+ try {
1333
+ obj[key];
1334
+ return true;
1335
+ } catch (e) {
1336
+ return false;
1337
+ }
1338
+ }
1339
+ var _FetchInterceptor = class extends Interceptor {
1340
+ constructor() {
1341
+ super(_FetchInterceptor.symbol);
1342
+ }
1343
+ checkEnvironment() {
1344
+ return typeof globalThis !== "undefined" && typeof globalThis.fetch !== "undefined";
1345
+ }
1346
+ setup() {
1347
+ const pureFetch = globalThis.fetch;
1348
+ invariant(
1349
+ !pureFetch[IS_PATCHED_MODULE],
1350
+ 'Failed to patch the "fetch" module: already patched.'
1351
+ );
1352
+ globalThis.fetch = async (input, init) => {
1353
+ var _a;
1354
+ const requestId = uuidv4();
1355
+ const request = new Request(input, init);
1356
+ this.logger.info("[%s] %s", request.method, request.url);
1357
+ const { interactiveRequest, requestController } = toInteractiveRequest(request);
1358
+ this.logger.info(
1359
+ 'emitting the "request" event for %d listener(s)...',
1360
+ this.emitter.listenerCount("request")
1361
+ );
1362
+ this.emitter.once("request", ({ requestId: pendingRequestId }) => {
1363
+ if (pendingRequestId !== requestId) {
1364
+ return;
1365
+ }
1366
+ if (requestController.responsePromise.state === "pending") {
1367
+ requestController.responsePromise.resolve(void 0);
1368
+ }
1369
+ });
1370
+ this.logger.info("awaiting for the mocked response...");
1371
+ const signal = interactiveRequest.signal;
1372
+ const requestAborted = new DeferredPromise();
1373
+ signal.addEventListener(
1374
+ "abort",
1375
+ () => {
1376
+ requestAborted.reject(signal.reason);
1377
+ },
1378
+ { once: true }
1379
+ );
1380
+ const resolverResult = await until(async () => {
1381
+ const listenersFinished = emitAsync(this.emitter, "request", {
1382
+ request: interactiveRequest,
1383
+ requestId
1384
+ });
1385
+ await Promise.race([
1386
+ requestAborted,
1387
+ // Put the listeners invocation Promise in the same race condition
1388
+ // with the request abort Promise because otherwise awaiting the listeners
1389
+ // would always yield some response (or undefined).
1390
+ listenersFinished,
1391
+ requestController.responsePromise
1392
+ ]);
1393
+ this.logger.info("all request listeners have been resolved!");
1394
+ const mockedResponse2 = await requestController.responsePromise;
1395
+ this.logger.info("event.respondWith called with:", mockedResponse2);
1396
+ return mockedResponse2;
1397
+ });
1398
+ if (requestAborted.state === "rejected") {
1399
+ return Promise.reject(requestAborted.rejectionReason);
1400
+ }
1401
+ if (resolverResult.error) {
1402
+ return Promise.reject(createNetworkError(resolverResult.error));
1403
+ }
1404
+ const mockedResponse = resolverResult.data;
1405
+ if (mockedResponse && !((_a = request.signal) == null ? void 0 : _a.aborted)) {
1406
+ this.logger.info("received mocked response:", mockedResponse);
1407
+ if (isPropertyAccessible(mockedResponse, "type") && mockedResponse.type === "error") {
1408
+ this.logger.info(
1409
+ "received a network error response, rejecting the request promise..."
1410
+ );
1411
+ return Promise.reject(createNetworkError(mockedResponse));
1412
+ }
1413
+ const responseClone = mockedResponse.clone();
1414
+ this.emitter.emit("response", {
1415
+ response: responseClone,
1416
+ isMockedResponse: true,
1417
+ request: interactiveRequest,
1418
+ requestId
1419
+ });
1420
+ const response = new Response(mockedResponse.body, mockedResponse);
1421
+ Object.defineProperty(response, "url", {
1422
+ writable: false,
1423
+ enumerable: true,
1424
+ configurable: false,
1425
+ value: request.url
1426
+ });
1427
+ return response;
1428
+ }
1429
+ this.logger.info("no mocked response received!");
1430
+ return pureFetch(request).then((response) => {
1431
+ const responseClone = response.clone();
1432
+ this.logger.info("original fetch performed", responseClone);
1433
+ this.emitter.emit("response", {
1434
+ response: responseClone,
1435
+ isMockedResponse: false,
1436
+ request: interactiveRequest,
1437
+ requestId
1438
+ });
1439
+ return response;
1440
+ });
1441
+ };
1442
+ Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {
1443
+ enumerable: true,
1444
+ configurable: true,
1445
+ value: true
1446
+ });
1447
+ this.subscriptions.push(() => {
1448
+ Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {
1449
+ value: void 0
1450
+ });
1451
+ globalThis.fetch = pureFetch;
1452
+ this.logger.info(
1453
+ 'restored native "globalThis.fetch"!',
1454
+ globalThis.fetch.name
1455
+ );
1456
+ });
1457
+ }
1458
+ };
1459
+ var FetchInterceptor = _FetchInterceptor;
1460
+ FetchInterceptor.symbol = Symbol("fetch");
1461
+ function createNetworkError(cause) {
1462
+ return Object.assign(new TypeError("Failed to fetch"), {
1463
+ cause
1464
+ });
1465
+ }
1466
+
1467
+ // node_modules/.pnpm/@mswjs+interceptors@0.25.14/node_modules/@mswjs/interceptors/lib/browser/chunk-DZVB7JEV.mjs
1468
+ function concatArrayBuffer(left, right) {
1469
+ const result = new Uint8Array(left.byteLength + right.byteLength);
1470
+ result.set(left, 0);
1471
+ result.set(right, left.byteLength);
1472
+ return result;
1473
+ }
1474
+ var EventPolyfill = class {
1475
+ constructor(type, options) {
1476
+ this.AT_TARGET = 0;
1477
+ this.BUBBLING_PHASE = 0;
1478
+ this.CAPTURING_PHASE = 0;
1479
+ this.NONE = 0;
1480
+ this.type = "";
1481
+ this.srcElement = null;
1482
+ this.currentTarget = null;
1483
+ this.eventPhase = 0;
1484
+ this.isTrusted = true;
1485
+ this.composed = false;
1486
+ this.cancelable = true;
1487
+ this.defaultPrevented = false;
1488
+ this.bubbles = true;
1489
+ this.lengthComputable = true;
1490
+ this.loaded = 0;
1491
+ this.total = 0;
1492
+ this.cancelBubble = false;
1493
+ this.returnValue = true;
1494
+ this.type = type;
1495
+ this.target = (options == null ? void 0 : options.target) || null;
1496
+ this.currentTarget = (options == null ? void 0 : options.currentTarget) || null;
1497
+ this.timeStamp = Date.now();
1498
+ }
1499
+ composedPath() {
1500
+ return [];
1501
+ }
1502
+ initEvent(type, bubbles, cancelable) {
1503
+ this.type = type;
1504
+ this.bubbles = !!bubbles;
1505
+ this.cancelable = !!cancelable;
1506
+ }
1507
+ preventDefault() {
1508
+ this.defaultPrevented = true;
1509
+ }
1510
+ stopPropagation() {
1511
+ }
1512
+ stopImmediatePropagation() {
1513
+ }
1514
+ };
1515
+ var ProgressEventPolyfill = class extends EventPolyfill {
1516
+ constructor(type, init) {
1517
+ super(type);
1518
+ this.lengthComputable = (init == null ? void 0 : init.lengthComputable) || false;
1519
+ this.composed = (init == null ? void 0 : init.composed) || false;
1520
+ this.loaded = (init == null ? void 0 : init.loaded) || 0;
1521
+ this.total = (init == null ? void 0 : init.total) || 0;
1522
+ }
1523
+ };
1524
+ var SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== "undefined";
1525
+ function createEvent(target, type, init) {
1526
+ const progressEvents = [
1527
+ "error",
1528
+ "progress",
1529
+ "loadstart",
1530
+ "loadend",
1531
+ "load",
1532
+ "timeout",
1533
+ "abort"
1534
+ ];
1535
+ const ProgressEventClass = SUPPORTS_PROGRESS_EVENT ? ProgressEvent : ProgressEventPolyfill;
1536
+ const event = progressEvents.includes(type) ? new ProgressEventClass(type, {
1537
+ lengthComputable: true,
1538
+ loaded: (init == null ? void 0 : init.loaded) || 0,
1539
+ total: (init == null ? void 0 : init.total) || 0
1540
+ }) : new EventPolyfill(type, {
1541
+ target,
1542
+ currentTarget: target
1543
+ });
1544
+ return event;
1545
+ }
1546
+ function findPropertySource(target, propertyName) {
1547
+ if (!(propertyName in target)) {
1548
+ return null;
1549
+ }
1550
+ const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName);
1551
+ if (hasProperty) {
1552
+ return target;
1553
+ }
1554
+ const prototype = Reflect.getPrototypeOf(target);
1555
+ return prototype ? findPropertySource(prototype, propertyName) : null;
1556
+ }
1557
+ function createProxy(target, options) {
1558
+ const proxy = new Proxy(target, optionsToProxyHandler(options));
1559
+ return proxy;
1560
+ }
1561
+ function optionsToProxyHandler(options) {
1562
+ const { constructorCall, methodCall, getProperty, setProperty } = options;
1563
+ const handler = {};
1564
+ if (typeof constructorCall !== "undefined") {
1565
+ handler.construct = function(target, args, newTarget) {
1566
+ const next = Reflect.construct.bind(null, target, args, newTarget);
1567
+ return constructorCall.call(newTarget, args, next);
1568
+ };
1569
+ }
1570
+ handler.set = function(target, propertyName, nextValue) {
1571
+ const next = () => {
1572
+ const propertySource = findPropertySource(target, propertyName) || target;
1573
+ const ownDescriptors = Reflect.getOwnPropertyDescriptor(
1574
+ propertySource,
1575
+ propertyName
1576
+ );
1577
+ if (typeof (ownDescriptors == null ? void 0 : ownDescriptors.set) !== "undefined") {
1578
+ ownDescriptors.set.apply(target, [nextValue]);
1579
+ return true;
1580
+ }
1581
+ return Reflect.defineProperty(propertySource, propertyName, {
1582
+ writable: true,
1583
+ enumerable: true,
1584
+ configurable: true,
1585
+ value: nextValue
1586
+ });
1587
+ };
1588
+ if (typeof setProperty !== "undefined") {
1589
+ return setProperty.call(target, [propertyName, nextValue], next);
1590
+ }
1591
+ return next();
1592
+ };
1593
+ handler.get = function(target, propertyName, receiver) {
1594
+ const next = () => target[propertyName];
1595
+ const value = typeof getProperty !== "undefined" ? getProperty.call(target, [propertyName, receiver], next) : next();
1596
+ if (typeof value === "function") {
1597
+ return (...args) => {
1598
+ const next2 = value.bind(target, ...args);
1599
+ if (typeof methodCall !== "undefined") {
1600
+ return methodCall.call(target, [propertyName, args], next2);
1601
+ }
1602
+ return next2();
1603
+ };
1604
+ }
1605
+ return value;
1606
+ };
1607
+ return handler;
1608
+ }
1609
+ function isDomParserSupportedType(type) {
1610
+ const supportedTypes = [
1611
+ "application/xhtml+xml",
1612
+ "application/xml",
1613
+ "image/svg+xml",
1614
+ "text/html",
1615
+ "text/xml"
1616
+ ];
1617
+ return supportedTypes.some((supportedType) => {
1618
+ return type.startsWith(supportedType);
1619
+ });
1620
+ }
1621
+ function parseJson(data) {
1622
+ try {
1623
+ const json = JSON.parse(data);
1624
+ return json;
1625
+ } catch (_) {
1626
+ return null;
1627
+ }
1628
+ }
1629
+ function createResponse(request, body) {
1630
+ const responseBodyOrNull = isResponseWithoutBody(request.status) ? null : body;
1631
+ return new Response(responseBodyOrNull, {
1632
+ status: request.status,
1633
+ statusText: request.statusText,
1634
+ headers: createHeadersFromXMLHttpReqestHeaders(
1635
+ request.getAllResponseHeaders()
1636
+ )
1637
+ });
1638
+ }
1639
+ function createHeadersFromXMLHttpReqestHeaders(headersString) {
1640
+ const headers = new Headers();
1641
+ const lines = headersString.split(/[\r\n]+/);
1642
+ for (const line of lines) {
1643
+ if (line.trim() === "") {
1644
+ continue;
1645
+ }
1646
+ const [name, ...parts] = line.split(": ");
1647
+ const value = parts.join(": ");
1648
+ headers.append(name, value);
1649
+ }
1650
+ return headers;
1651
+ }
1652
+ var IS_MOCKED_RESPONSE = Symbol("isMockedResponse");
1653
+ var IS_NODE2 = isNodeProcess();
1654
+ var XMLHttpRequestController = class {
1655
+ constructor(initialRequest, logger) {
1656
+ this.initialRequest = initialRequest;
1657
+ this.logger = logger;
1658
+ this.method = "GET";
1659
+ this.url = null;
1660
+ this.events = /* @__PURE__ */ new Map();
1661
+ this.requestId = uuidv4();
1662
+ this.requestHeaders = new Headers();
1663
+ this.responseBuffer = new Uint8Array();
1664
+ this.request = createProxy(initialRequest, {
1665
+ setProperty: ([propertyName, nextValue], invoke) => {
1666
+ switch (propertyName) {
1667
+ case "ontimeout": {
1668
+ const eventName = propertyName.slice(
1669
+ 2
1670
+ );
1671
+ this.request.addEventListener(eventName, nextValue);
1672
+ return invoke();
1673
+ }
1674
+ default: {
1675
+ return invoke();
1676
+ }
1677
+ }
1678
+ },
1679
+ methodCall: ([methodName, args], invoke) => {
1680
+ var _a;
1681
+ switch (methodName) {
1682
+ case "open": {
1683
+ const [method, url] = args;
1684
+ if (typeof url === "undefined") {
1685
+ this.method = "GET";
1686
+ this.url = toAbsoluteUrl(method);
1687
+ } else {
1688
+ this.method = method;
1689
+ this.url = toAbsoluteUrl(url);
1690
+ }
1691
+ this.logger = this.logger.extend(`${this.method} ${this.url.href}`);
1692
+ this.logger.info("open", this.method, this.url.href);
1693
+ return invoke();
1694
+ }
1695
+ case "addEventListener": {
1696
+ const [eventName, listener] = args;
1697
+ this.registerEvent(eventName, listener);
1698
+ this.logger.info("addEventListener", eventName, listener);
1699
+ return invoke();
1700
+ }
1701
+ case "setRequestHeader": {
1702
+ const [name, value] = args;
1703
+ this.requestHeaders.set(name, value);
1704
+ this.logger.info("setRequestHeader", name, value);
1705
+ return invoke();
1706
+ }
1707
+ case "send": {
1708
+ const [body] = args;
1709
+ if (body != null) {
1710
+ this.requestBody = typeof body === "string" ? encodeBuffer(body) : body;
1711
+ }
1712
+ this.request.addEventListener("load", () => {
1713
+ if (typeof this.onResponse !== "undefined") {
1714
+ const fetchResponse = createResponse(
1715
+ this.request,
1716
+ /**
1717
+ * The `response` property is the right way to read
1718
+ * the ambiguous response body, as the request's "responseType" may differ.
1719
+ * @see https://xhr.spec.whatwg.org/#the-response-attribute
1720
+ */
1721
+ this.request.response
1722
+ );
1723
+ this.onResponse.call(this, {
1724
+ response: fetchResponse,
1725
+ isMockedResponse: IS_MOCKED_RESPONSE in this.request,
1726
+ request: fetchRequest,
1727
+ requestId: this.requestId
1728
+ });
1729
+ }
1730
+ });
1731
+ const fetchRequest = this.toFetchApiRequest();
1732
+ const onceRequestSettled = ((_a = this.onRequest) == null ? void 0 : _a.call(this, {
1733
+ request: fetchRequest,
1734
+ requestId: this.requestId
1735
+ })) || Promise.resolve();
1736
+ onceRequestSettled.finally(() => {
1737
+ if (this.request.readyState < this.request.LOADING) {
1738
+ this.logger.info(
1739
+ "request callback settled but request has not been handled (readystate %d), performing as-is...",
1740
+ this.request.readyState
1741
+ );
1742
+ if (IS_NODE2) {
1743
+ this.request.setRequestHeader("X-Request-Id", this.requestId);
1744
+ }
1745
+ return invoke();
1746
+ }
1747
+ });
1748
+ break;
1749
+ }
1750
+ default: {
1751
+ return invoke();
1752
+ }
1753
+ }
1754
+ }
1755
+ });
1756
+ }
1757
+ registerEvent(eventName, listener) {
1758
+ const prevEvents = this.events.get(eventName) || [];
1759
+ const nextEvents = prevEvents.concat(listener);
1760
+ this.events.set(eventName, nextEvents);
1761
+ this.logger.info('registered event "%s"', eventName, listener);
1762
+ }
1763
+ /**
1764
+ * Responds to the current request with the given
1765
+ * Fetch API `Response` instance.
1766
+ */
1767
+ respondWith(response) {
1768
+ this.logger.info(
1769
+ "responding with a mocked response: %d %s",
1770
+ response.status,
1771
+ response.statusText
1772
+ );
1773
+ define(this.request, IS_MOCKED_RESPONSE, true);
1774
+ define(this.request, "status", response.status);
1775
+ define(this.request, "statusText", response.statusText);
1776
+ define(this.request, "responseURL", this.url.href);
1777
+ this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, {
1778
+ apply: (_, __, args) => {
1779
+ this.logger.info("getResponseHeader", args[0]);
1780
+ if (this.request.readyState < this.request.HEADERS_RECEIVED) {
1781
+ this.logger.info("headers not received yet, returning null");
1782
+ return null;
1783
+ }
1784
+ const headerValue = response.headers.get(args[0]);
1785
+ this.logger.info(
1786
+ 'resolved response header "%s" to',
1787
+ args[0],
1788
+ headerValue
1789
+ );
1790
+ return headerValue;
1791
+ }
1792
+ });
1793
+ this.request.getAllResponseHeaders = new Proxy(
1794
+ this.request.getAllResponseHeaders,
1795
+ {
1796
+ apply: () => {
1797
+ this.logger.info("getAllResponseHeaders");
1798
+ if (this.request.readyState < this.request.HEADERS_RECEIVED) {
1799
+ this.logger.info("headers not received yet, returning empty string");
1800
+ return "";
1801
+ }
1802
+ const headersList = Array.from(response.headers.entries());
1803
+ const allHeaders = headersList.map(([headerName, headerValue]) => {
1804
+ return `${headerName}: ${headerValue}`;
1805
+ }).join("\r\n");
1806
+ this.logger.info("resolved all response headers to", allHeaders);
1807
+ return allHeaders;
1808
+ }
1809
+ }
1810
+ );
1811
+ Object.defineProperties(this.request, {
1812
+ response: {
1813
+ enumerable: true,
1814
+ configurable: false,
1815
+ get: () => this.response
1816
+ },
1817
+ responseText: {
1818
+ enumerable: true,
1819
+ configurable: false,
1820
+ get: () => this.responseText
1821
+ },
1822
+ responseXML: {
1823
+ enumerable: true,
1824
+ configurable: false,
1825
+ get: () => this.responseXML
1826
+ }
1827
+ });
1828
+ const totalResponseBodyLength = response.headers.has("Content-Length") ? Number(response.headers.get("Content-Length")) : (
1829
+ /**
1830
+ * @todo Infer the response body length from the response body.
1831
+ */
1832
+ void 0
1833
+ );
1834
+ this.logger.info("calculated response body length", totalResponseBodyLength);
1835
+ this.trigger("loadstart", {
1836
+ loaded: 0,
1837
+ total: totalResponseBodyLength
1838
+ });
1839
+ this.setReadyState(this.request.HEADERS_RECEIVED);
1840
+ this.setReadyState(this.request.LOADING);
1841
+ const finalizeResponse = () => {
1842
+ this.logger.info("finalizing the mocked response...");
1843
+ this.setReadyState(this.request.DONE);
1844
+ this.trigger("load", {
1845
+ loaded: this.responseBuffer.byteLength,
1846
+ total: totalResponseBodyLength
1847
+ });
1848
+ this.trigger("loadend", {
1849
+ loaded: this.responseBuffer.byteLength,
1850
+ total: totalResponseBodyLength
1851
+ });
1852
+ };
1853
+ if (response.body) {
1854
+ this.logger.info("mocked response has body, streaming...");
1855
+ const reader = response.body.getReader();
1856
+ const readNextResponseBodyChunk = async () => {
1857
+ const { value, done } = await reader.read();
1858
+ if (done) {
1859
+ this.logger.info("response body stream done!");
1860
+ finalizeResponse();
1861
+ return;
1862
+ }
1863
+ if (value) {
1864
+ this.logger.info("read response body chunk:", value);
1865
+ this.responseBuffer = concatArrayBuffer(this.responseBuffer, value);
1866
+ this.trigger("progress", {
1867
+ loaded: this.responseBuffer.byteLength,
1868
+ total: totalResponseBodyLength
1869
+ });
1870
+ }
1871
+ readNextResponseBodyChunk();
1872
+ };
1873
+ readNextResponseBodyChunk();
1874
+ } else {
1875
+ finalizeResponse();
1876
+ }
1877
+ }
1878
+ responseBufferToText() {
1879
+ return decodeBuffer(this.responseBuffer);
1880
+ }
1881
+ get response() {
1882
+ this.logger.info(
1883
+ "getResponse (responseType: %s)",
1884
+ this.request.responseType
1885
+ );
1886
+ if (this.request.readyState !== this.request.DONE) {
1887
+ return null;
1888
+ }
1889
+ switch (this.request.responseType) {
1890
+ case "json": {
1891
+ const responseJson = parseJson(this.responseBufferToText());
1892
+ this.logger.info("resolved response JSON", responseJson);
1893
+ return responseJson;
1894
+ }
1895
+ case "arraybuffer": {
1896
+ const arrayBuffer = toArrayBuffer(this.responseBuffer);
1897
+ this.logger.info("resolved response ArrayBuffer", arrayBuffer);
1898
+ return arrayBuffer;
1899
+ }
1900
+ case "blob": {
1901
+ const mimeType = this.request.getResponseHeader("Content-Type") || "text/plain";
1902
+ const responseBlob = new Blob([this.responseBufferToText()], {
1903
+ type: mimeType
1904
+ });
1905
+ this.logger.info(
1906
+ "resolved response Blob (mime type: %s)",
1907
+ responseBlob,
1908
+ mimeType
1909
+ );
1910
+ return responseBlob;
1911
+ }
1912
+ default: {
1913
+ const responseText = this.responseBufferToText();
1914
+ this.logger.info(
1915
+ 'resolving "%s" response type as text',
1916
+ this.request.responseType,
1917
+ responseText
1918
+ );
1919
+ return responseText;
1920
+ }
1921
+ }
1922
+ }
1923
+ get responseText() {
1924
+ invariant(
1925
+ this.request.responseType === "" || this.request.responseType === "text",
1926
+ "InvalidStateError: The object is in invalid state."
1927
+ );
1928
+ if (this.request.readyState !== this.request.LOADING && this.request.readyState !== this.request.DONE) {
1929
+ return "";
1930
+ }
1931
+ const responseText = this.responseBufferToText();
1932
+ this.logger.info('getResponseText: "%s"', responseText);
1933
+ return responseText;
1934
+ }
1935
+ get responseXML() {
1936
+ invariant(
1937
+ this.request.responseType === "" || this.request.responseType === "document",
1938
+ "InvalidStateError: The object is in invalid state."
1939
+ );
1940
+ if (this.request.readyState !== this.request.DONE) {
1941
+ return null;
1942
+ }
1943
+ const contentType = this.request.getResponseHeader("Content-Type") || "";
1944
+ if (typeof DOMParser === "undefined") {
1945
+ console.warn(
1946
+ "Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly."
1947
+ );
1948
+ return null;
1949
+ }
1950
+ if (isDomParserSupportedType(contentType)) {
1951
+ return new DOMParser().parseFromString(
1952
+ this.responseBufferToText(),
1953
+ contentType
1954
+ );
1955
+ }
1956
+ return null;
1957
+ }
1958
+ errorWith(error2) {
1959
+ this.logger.info("responding with an error");
1960
+ this.setReadyState(this.request.DONE);
1961
+ this.trigger("error");
1962
+ this.trigger("loadend");
1963
+ }
1964
+ /**
1965
+ * Transitions this request's `readyState` to the given one.
1966
+ */
1967
+ setReadyState(nextReadyState) {
1968
+ this.logger.info(
1969
+ "setReadyState: %d -> %d",
1970
+ this.request.readyState,
1971
+ nextReadyState
1972
+ );
1973
+ if (this.request.readyState === nextReadyState) {
1974
+ this.logger.info("ready state identical, skipping transition...");
1975
+ return;
1976
+ }
1977
+ define(this.request, "readyState", nextReadyState);
1978
+ this.logger.info("set readyState to: %d", nextReadyState);
1979
+ if (nextReadyState !== this.request.UNSENT) {
1980
+ this.logger.info('triggerring "readystatechange" event...');
1981
+ this.trigger("readystatechange");
1982
+ }
1983
+ }
1984
+ /**
1985
+ * Triggers given event on the `XMLHttpRequest` instance.
1986
+ */
1987
+ trigger(eventName, options) {
1988
+ const callback = this.request[`on${eventName}`];
1989
+ const event = createEvent(this.request, eventName, options);
1990
+ this.logger.info('trigger "%s"', eventName, options || "");
1991
+ if (typeof callback === "function") {
1992
+ this.logger.info('found a direct "%s" callback, calling...', eventName);
1993
+ callback.call(this.request, event);
1994
+ }
1995
+ for (const [registeredEventName, listeners] of this.events) {
1996
+ if (registeredEventName === eventName) {
1997
+ this.logger.info(
1998
+ 'found %d listener(s) for "%s" event, calling...',
1999
+ listeners.length,
2000
+ eventName
2001
+ );
2002
+ listeners.forEach((listener) => listener.call(this.request, event));
2003
+ }
2004
+ }
2005
+ }
2006
+ /**
2007
+ * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.
2008
+ */
2009
+ toFetchApiRequest() {
2010
+ this.logger.info("converting request to a Fetch API Request...");
2011
+ const fetchRequest = new Request(this.url.href, {
2012
+ method: this.method,
2013
+ headers: this.requestHeaders,
2014
+ /**
2015
+ * @see https://xhr.spec.whatwg.org/#cross-origin-credentials
2016
+ */
2017
+ credentials: this.request.withCredentials ? "include" : "same-origin",
2018
+ body: ["GET", "HEAD"].includes(this.method) ? null : this.requestBody
2019
+ });
2020
+ const proxyHeaders = createProxy(fetchRequest.headers, {
2021
+ methodCall: ([methodName, args], invoke) => {
2022
+ switch (methodName) {
2023
+ case "append":
2024
+ case "set": {
2025
+ const [headerName, headerValue] = args;
2026
+ this.request.setRequestHeader(headerName, headerValue);
2027
+ break;
2028
+ }
2029
+ case "delete": {
2030
+ const [headerName] = args;
2031
+ console.warn(
2032
+ `XMLHttpRequest: Cannot remove a "${headerName}" header from the Fetch API representation of the "${fetchRequest.method} ${fetchRequest.url}" request. XMLHttpRequest headers cannot be removed.`
2033
+ );
2034
+ break;
2035
+ }
2036
+ }
2037
+ return invoke();
2038
+ }
2039
+ });
2040
+ define(fetchRequest, "headers", proxyHeaders);
2041
+ this.logger.info("converted request to a Fetch API Request!", fetchRequest);
2042
+ return fetchRequest;
2043
+ }
2044
+ };
2045
+ function toAbsoluteUrl(url) {
2046
+ if (typeof location === "undefined") {
2047
+ return new URL(url);
2048
+ }
2049
+ return new URL(url.toString(), location.href);
2050
+ }
2051
+ function define(target, property, value) {
2052
+ Reflect.defineProperty(target, property, {
2053
+ // Ensure writable properties to allow redefining readonly properties.
2054
+ writable: true,
2055
+ enumerable: true,
2056
+ value
2057
+ });
2058
+ }
2059
+ function createXMLHttpRequestProxy({
2060
+ emitter,
2061
+ logger
2062
+ }) {
2063
+ const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, {
2064
+ construct(target, args, newTarget) {
2065
+ logger.info("constructed new XMLHttpRequest");
2066
+ const originalRequest = Reflect.construct(target, args, newTarget);
2067
+ const prototypeDescriptors = Object.getOwnPropertyDescriptors(
2068
+ target.prototype
2069
+ );
2070
+ for (const propertyName in prototypeDescriptors) {
2071
+ Reflect.defineProperty(
2072
+ originalRequest,
2073
+ propertyName,
2074
+ prototypeDescriptors[propertyName]
2075
+ );
2076
+ }
2077
+ const xhrRequestController = new XMLHttpRequestController(
2078
+ originalRequest,
2079
+ logger
2080
+ );
2081
+ xhrRequestController.onRequest = async function({ request, requestId }) {
2082
+ const { interactiveRequest, requestController } = toInteractiveRequest(request);
2083
+ this.logger.info("awaiting mocked response...");
2084
+ emitter.once("request", ({ requestId: pendingRequestId }) => {
2085
+ if (pendingRequestId !== requestId) {
2086
+ return;
2087
+ }
2088
+ if (requestController.responsePromise.state === "pending") {
2089
+ requestController.respondWith(void 0);
2090
+ }
2091
+ });
2092
+ const resolverResult = await until(async () => {
2093
+ this.logger.info(
2094
+ 'emitting the "request" event for %s listener(s)...',
2095
+ emitter.listenerCount("request")
2096
+ );
2097
+ await emitAsync(emitter, "request", {
2098
+ request: interactiveRequest,
2099
+ requestId
2100
+ });
2101
+ this.logger.info('all "request" listeners settled!');
2102
+ const mockedResponse2 = await requestController.responsePromise;
2103
+ this.logger.info("event.respondWith called with:", mockedResponse2);
2104
+ return mockedResponse2;
2105
+ });
2106
+ if (resolverResult.error) {
2107
+ this.logger.info(
2108
+ "request listener threw an exception, aborting request...",
2109
+ resolverResult.error
2110
+ );
2111
+ xhrRequestController.errorWith(resolverResult.error);
2112
+ return;
2113
+ }
2114
+ const mockedResponse = resolverResult.data;
2115
+ if (typeof mockedResponse !== "undefined") {
2116
+ this.logger.info(
2117
+ "received mocked response: %d %s",
2118
+ mockedResponse.status,
2119
+ mockedResponse.statusText
2120
+ );
2121
+ if (mockedResponse.type === "error") {
2122
+ this.logger.info(
2123
+ "received a network error response, rejecting the request promise..."
2124
+ );
2125
+ xhrRequestController.errorWith(new TypeError("Network error"));
2126
+ return;
2127
+ }
2128
+ return xhrRequestController.respondWith(mockedResponse);
2129
+ }
2130
+ this.logger.info(
2131
+ "no mocked response received, performing request as-is..."
2132
+ );
2133
+ };
2134
+ xhrRequestController.onResponse = async function({
2135
+ response,
2136
+ isMockedResponse,
2137
+ request,
2138
+ requestId
2139
+ }) {
2140
+ this.logger.info(
2141
+ 'emitting the "response" event for %s listener(s)...',
2142
+ emitter.listenerCount("response")
2143
+ );
2144
+ emitter.emit("response", {
2145
+ response,
2146
+ isMockedResponse,
2147
+ request,
2148
+ requestId
2149
+ });
2150
+ };
2151
+ return xhrRequestController.request;
2152
+ }
2153
+ });
2154
+ return XMLHttpRequestProxy;
2155
+ }
2156
+ var _XMLHttpRequestInterceptor = class extends Interceptor {
2157
+ constructor() {
2158
+ super(_XMLHttpRequestInterceptor.interceptorSymbol);
2159
+ }
2160
+ checkEnvironment() {
2161
+ return typeof globalThis.XMLHttpRequest !== "undefined";
2162
+ }
2163
+ setup() {
2164
+ const logger = this.logger.extend("setup");
2165
+ logger.info('patching "XMLHttpRequest" module...');
2166
+ const PureXMLHttpRequest = globalThis.XMLHttpRequest;
2167
+ invariant(
2168
+ !PureXMLHttpRequest[IS_PATCHED_MODULE],
2169
+ 'Failed to patch the "XMLHttpRequest" module: already patched.'
2170
+ );
2171
+ globalThis.XMLHttpRequest = createXMLHttpRequestProxy({
2172
+ emitter: this.emitter,
2173
+ logger: this.logger
2174
+ });
2175
+ logger.info(
2176
+ 'native "XMLHttpRequest" module patched!',
2177
+ globalThis.XMLHttpRequest.name
2178
+ );
2179
+ Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {
2180
+ enumerable: true,
2181
+ configurable: true,
2182
+ value: true
2183
+ });
2184
+ this.subscriptions.push(() => {
2185
+ Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {
2186
+ value: void 0
2187
+ });
2188
+ globalThis.XMLHttpRequest = PureXMLHttpRequest;
2189
+ logger.info(
2190
+ 'native "XMLHttpRequest" module restored!',
2191
+ globalThis.XMLHttpRequest.name
2192
+ );
2193
+ });
2194
+ }
2195
+ };
2196
+ var XMLHttpRequestInterceptor = _XMLHttpRequestInterceptor;
2197
+ XMLHttpRequestInterceptor.interceptorSymbol = Symbol("xhr");
2198
+
466
2199
  // src/browser/setupWorker/start/createFallbackRequestListener.ts
467
- var import_interceptors2 = require("@mswjs/interceptors");
468
- var import_fetch = require("@mswjs/interceptors/fetch");
469
- var import_XMLHttpRequest = require("@mswjs/interceptors/XMLHttpRequest");
470
2200
  var import_handleRequest2 = require("../core/utils/handleRequest.js");
471
2201
  function createFallbackRequestListener(context, options) {
472
- const interceptor = new import_interceptors2.BatchInterceptor({
2202
+ const interceptor = new BatchInterceptor({
473
2203
  name: "fallback",
474
- interceptors: [new import_fetch.FetchInterceptor(), new import_XMLHttpRequest.XMLHttpRequestInterceptor()]
2204
+ interceptors: [new FetchInterceptor(), new XMLHttpRequestInterceptor()]
475
2205
  });
476
2206
  interceptor.on("request", async ({ request, requestId }) => {
477
2207
  const requestCloneForLogs = request.clone();
@@ -553,7 +2283,7 @@ function supportsReadableStreamTransfer() {
553
2283
  const message = new MessageChannel();
554
2284
  message.port1.postMessage(stream, [stream]);
555
2285
  return true;
556
- } catch (error) {
2286
+ } catch (error2) {
557
2287
  return false;
558
2288
  }
559
2289
  }
@@ -566,8 +2296,8 @@ var SetupWorkerApi = class extends import_SetupApi.SetupApi {
566
2296
  listeners;
567
2297
  constructor(...handlers) {
568
2298
  super(...handlers);
569
- (0, import_outvariant.invariant)(
570
- !(0, import_is_node_process.isNodeProcess)(),
2299
+ invariant(
2300
+ !isNodeProcess(),
571
2301
  import_devUtils9.devUtils.formatMessage(
572
2302
  "Failed to execute `setupWorker` in a non-browser environment. Consider using `setupServer` for Node.js environment instead."
573
2303
  )
@@ -631,8 +2361,8 @@ var SetupWorkerApi = class extends import_SetupApi.SetupApi {
631
2361
  if (message.type === eventType) {
632
2362
  resolve(message);
633
2363
  }
634
- } catch (error) {
635
- reject(error);
2364
+ } catch (error2) {
2365
+ reject(error2);
636
2366
  }
637
2367
  };
638
2368
  bindings.push(