msw 2.0.14 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/cli/index.js +11 -3
  2. package/cli/init.js +126 -73
  3. package/config/scripts/postinstall.js +8 -20
  4. package/lib/browser/index.js +111 -176
  5. package/lib/browser/index.js.map +1 -1
  6. package/lib/browser/index.mjs +111 -179
  7. package/lib/browser/index.mjs.map +1 -1
  8. package/lib/core/{GraphQLHandler-JB4bsrLF.d.ts → GraphQLHandler-2guuZL5R.d.ts} +1 -1
  9. package/lib/core/{GraphQLHandler-mT-MmgeB.d.mts → GraphQLHandler-fe5IYUg3.d.mts} +1 -1
  10. package/lib/core/HttpResponse.d.mts +1 -1
  11. package/lib/core/HttpResponse.d.ts +1 -1
  12. package/lib/core/{RequestHandler-rmY-HeFN.d.ts → RequestHandler-TRh8Eh4H.d.ts} +9 -1
  13. package/lib/core/{RequestHandler-YiqamK0M.d.mts → RequestHandler-nfjVJ8Tp.d.mts} +9 -1
  14. package/lib/core/SetupApi.d.mts +1 -1
  15. package/lib/core/SetupApi.d.ts +1 -1
  16. package/lib/core/SetupApi.js +5 -0
  17. package/lib/core/SetupApi.js.map +1 -1
  18. package/lib/core/SetupApi.mjs +5 -0
  19. package/lib/core/SetupApi.mjs.map +1 -1
  20. package/lib/core/delay.js +24 -46
  21. package/lib/core/delay.js.map +1 -1
  22. package/lib/core/delay.mjs +24 -46
  23. package/lib/core/delay.mjs.map +1 -1
  24. package/lib/core/graphql.d.mts +2 -2
  25. package/lib/core/graphql.d.ts +2 -2
  26. package/lib/core/graphql.js +3 -19
  27. package/lib/core/graphql.js.map +1 -1
  28. package/lib/core/graphql.mjs +3 -21
  29. package/lib/core/graphql.mjs.map +1 -1
  30. package/lib/core/handlers/GraphQLHandler.d.mts +2 -2
  31. package/lib/core/handlers/GraphQLHandler.d.ts +2 -2
  32. package/lib/core/handlers/GraphQLHandler.js +51 -77
  33. package/lib/core/handlers/GraphQLHandler.js.map +1 -1
  34. package/lib/core/handlers/GraphQLHandler.mjs +51 -77
  35. package/lib/core/handlers/GraphQLHandler.mjs.map +1 -1
  36. package/lib/core/handlers/HttpHandler.d.mts +1 -1
  37. package/lib/core/handlers/HttpHandler.d.ts +1 -1
  38. package/lib/core/handlers/HttpHandler.js +29 -55
  39. package/lib/core/handlers/HttpHandler.js.map +1 -1
  40. package/lib/core/handlers/HttpHandler.mjs +29 -55
  41. package/lib/core/handlers/HttpHandler.mjs.map +1 -1
  42. package/lib/core/handlers/RequestHandler.d.mts +1 -1
  43. package/lib/core/handlers/RequestHandler.d.ts +1 -1
  44. package/lib/core/handlers/RequestHandler.js +79 -103
  45. package/lib/core/handlers/RequestHandler.js.map +1 -1
  46. package/lib/core/handlers/RequestHandler.mjs +79 -105
  47. package/lib/core/handlers/RequestHandler.mjs.map +1 -1
  48. package/lib/core/http.d.mts +1 -1
  49. package/lib/core/http.d.ts +1 -1
  50. package/lib/core/index.d.mts +2 -2
  51. package/lib/core/index.d.ts +2 -2
  52. package/lib/core/sharedOptions.d.mts +1 -1
  53. package/lib/core/sharedOptions.d.ts +1 -1
  54. package/lib/core/utils/HttpResponse/decorators.d.mts +1 -1
  55. package/lib/core/utils/HttpResponse/decorators.d.ts +1 -1
  56. package/lib/core/utils/HttpResponse/decorators.js +7 -24
  57. package/lib/core/utils/HttpResponse/decorators.js.map +1 -1
  58. package/lib/core/utils/HttpResponse/decorators.mjs +7 -26
  59. package/lib/core/utils/HttpResponse/decorators.mjs.map +1 -1
  60. package/lib/core/utils/getResponse.d.mts +1 -1
  61. package/lib/core/utils/getResponse.d.ts +1 -1
  62. package/lib/core/utils/getResponse.js +11 -26
  63. package/lib/core/utils/getResponse.js.map +1 -1
  64. package/lib/core/utils/getResponse.mjs +11 -26
  65. package/lib/core/utils/getResponse.mjs.map +1 -1
  66. package/lib/core/utils/handleRequest.d.mts +1 -1
  67. package/lib/core/utils/handleRequest.d.ts +1 -1
  68. package/lib/core/utils/handleRequest.js +49 -72
  69. package/lib/core/utils/handleRequest.js.map +1 -1
  70. package/lib/core/utils/handleRequest.mjs +49 -72
  71. package/lib/core/utils/handleRequest.mjs.map +1 -1
  72. package/lib/core/utils/internal/Disposable.js +3 -27
  73. package/lib/core/utils/internal/Disposable.js.map +1 -1
  74. package/lib/core/utils/internal/Disposable.mjs +3 -27
  75. package/lib/core/utils/internal/Disposable.mjs.map +1 -1
  76. package/lib/core/utils/internal/parseGraphQLRequest.d.mts +2 -2
  77. package/lib/core/utils/internal/parseGraphQLRequest.d.ts +2 -2
  78. package/lib/core/utils/internal/parseGraphQLRequest.js +72 -112
  79. package/lib/core/utils/internal/parseGraphQLRequest.js.map +1 -1
  80. package/lib/core/utils/internal/parseGraphQLRequest.mjs +72 -113
  81. package/lib/core/utils/internal/parseGraphQLRequest.mjs.map +1 -1
  82. package/lib/core/utils/internal/parseMultipartData.d.mts +1 -1
  83. package/lib/core/utils/internal/parseMultipartData.d.ts +1 -1
  84. package/lib/core/utils/internal/parseMultipartData.js +3 -4
  85. package/lib/core/utils/internal/parseMultipartData.js.map +1 -1
  86. package/lib/core/utils/internal/parseMultipartData.mjs +3 -4
  87. package/lib/core/utils/internal/parseMultipartData.mjs.map +1 -1
  88. package/lib/core/utils/internal/requestHandlerUtils.d.mts +1 -1
  89. package/lib/core/utils/internal/requestHandlerUtils.d.ts +1 -1
  90. package/lib/core/utils/internal/tryCatch.js +1 -1
  91. package/lib/core/utils/internal/tryCatch.js.map +1 -1
  92. package/lib/core/utils/internal/tryCatch.mjs +1 -1
  93. package/lib/core/utils/internal/tryCatch.mjs.map +1 -1
  94. package/lib/core/utils/logging/serializeRequest.js +9 -31
  95. package/lib/core/utils/logging/serializeRequest.js.map +1 -1
  96. package/lib/core/utils/logging/serializeRequest.mjs +9 -31
  97. package/lib/core/utils/logging/serializeRequest.mjs.map +1 -1
  98. package/lib/core/utils/logging/serializeResponse.js +11 -33
  99. package/lib/core/utils/logging/serializeResponse.js.map +1 -1
  100. package/lib/core/utils/logging/serializeResponse.mjs +11 -33
  101. package/lib/core/utils/logging/serializeResponse.mjs.map +1 -1
  102. package/lib/core/utils/request/getRequestCookies.js +9 -18
  103. package/lib/core/utils/request/getRequestCookies.js.map +1 -1
  104. package/lib/core/utils/request/getRequestCookies.mjs +9 -20
  105. package/lib/core/utils/request/getRequestCookies.mjs.map +1 -1
  106. package/lib/core/utils/request/onUnhandledRequest.d.mts +1 -1
  107. package/lib/core/utils/request/onUnhandledRequest.d.ts +1 -1
  108. package/lib/core/utils/request/onUnhandledRequest.js +62 -84
  109. package/lib/core/utils/request/onUnhandledRequest.js.map +1 -1
  110. package/lib/core/utils/request/onUnhandledRequest.mjs +62 -84
  111. package/lib/core/utils/request/onUnhandledRequest.mjs.map +1 -1
  112. package/lib/core/utils/request/readResponseCookies.js +1 -18
  113. package/lib/core/utils/request/readResponseCookies.js.map +1 -1
  114. package/lib/core/utils/request/readResponseCookies.mjs +1 -20
  115. package/lib/core/utils/request/readResponseCookies.mjs.map +1 -1
  116. package/lib/iife/index.js +678 -958
  117. package/lib/iife/index.js.map +1 -1
  118. package/lib/mockServiceWorker.js +2 -2
  119. package/lib/native/index.js +5 -23
  120. package/lib/native/index.js.map +1 -1
  121. package/lib/native/index.mjs +5 -24
  122. package/lib/native/index.mjs.map +1 -1
  123. package/lib/node/index.js +5 -23
  124. package/lib/node/index.js.map +1 -1
  125. package/lib/node/index.mjs +5 -24
  126. package/lib/node/index.mjs.map +1 -1
  127. package/package.json +32 -37
  128. package/src/browser/setupWorker/setupWorker.ts +6 -0
  129. package/src/browser/setupWorker/start/createStartHandler.ts +0 -8
  130. package/src/core/handlers/GraphQLHandler.test.ts +7 -3
  131. package/src/core/handlers/HttpHandler.test.ts +7 -2
  132. package/src/core/handlers/RequestHandler.ts +24 -4
  133. package/src/core/utils/getResponse.ts +12 -6
  134. package/src/core/utils/handleRequest.test.ts +20 -0
  135. package/src/core/utils/handleRequest.ts +4 -3
package/lib/iife/index.js CHANGED
@@ -1,38 +1,9 @@
1
1
  "use strict";
2
2
  var MockServiceWorker = (() => {
3
3
  var __defProp = Object.defineProperty;
4
- var __defProps = Object.defineProperties;
5
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
8
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
10
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
- var __spreadValues = (a, b) => {
13
- for (var prop in b || (b = {}))
14
- if (__hasOwnProp.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- if (__getOwnPropSymbols)
17
- for (var prop of __getOwnPropSymbols(b)) {
18
- if (__propIsEnum.call(b, prop))
19
- __defNormalProp(a, prop, b[prop]);
20
- }
21
- return a;
22
- };
23
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
- var __objRest = (source, exclude) => {
25
- var target = {};
26
- for (var prop in source)
27
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
28
- target[prop] = source[prop];
29
- if (source != null && __getOwnPropSymbols)
30
- for (var prop of __getOwnPropSymbols(source)) {
31
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
32
- target[prop] = source[prop];
33
- }
34
- return target;
35
- };
36
7
  var __export = (target, all) => {
37
8
  for (var name in all)
38
9
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -46,52 +17,6 @@ var MockServiceWorker = (() => {
46
17
  return to;
47
18
  };
48
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
49
- var __publicField = (obj, key, value) => {
50
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
51
- return value;
52
- };
53
- var __accessCheck = (obj, member, msg) => {
54
- if (!member.has(obj))
55
- throw TypeError("Cannot " + msg);
56
- };
57
- var __privateGet = (obj, member, getter) => {
58
- __accessCheck(obj, member, "read from private field");
59
- return getter ? getter.call(obj) : member.get(obj);
60
- };
61
- var __privateAdd = (obj, member, value) => {
62
- if (member.has(obj))
63
- throw TypeError("Cannot add the same private member more than once");
64
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
65
- };
66
- var __privateSet = (obj, member, value, setter) => {
67
- __accessCheck(obj, member, "write to private field");
68
- setter ? setter.call(obj, value) : member.set(obj, value);
69
- return value;
70
- };
71
- var __privateMethod = (obj, member, method) => {
72
- __accessCheck(obj, member, "access private method");
73
- return method;
74
- };
75
- var __async = (__this, __arguments, generator) => {
76
- return new Promise((resolve, reject) => {
77
- var fulfilled = (value) => {
78
- try {
79
- step(generator.next(value));
80
- } catch (e) {
81
- reject(e);
82
- }
83
- };
84
- var rejected = (value) => {
85
- try {
86
- step(generator.throw(value));
87
- } catch (e) {
88
- reject(e);
89
- }
90
- };
91
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
92
- step((generator = generator.apply(__this, __arguments)).next());
93
- });
94
- };
95
20
 
96
21
  // src/iife/index.ts
97
22
  var iife_exports = {};
@@ -118,8 +43,8 @@ var MockServiceWorker = (() => {
118
43
  setupWorker: () => setupWorker
119
44
  });
120
45
 
121
- // node_modules/.pnpm/outvariant@1.4.0/node_modules/outvariant/lib/index.mjs
122
- var POSITIONALS_EXP = /(%?)(%([sdjo]))/g;
46
+ // node_modules/.pnpm/outvariant@1.4.2/node_modules/outvariant/lib/index.mjs
47
+ var POSITIONALS_EXP = /(%?)(%([sdijo]))/g;
123
48
  function serializePositional(positional, flag) {
124
49
  switch (flag) {
125
50
  case "s":
@@ -189,8 +114,13 @@ var MockServiceWorker = (() => {
189
114
  };
190
115
  invariant.as = (ErrorConstructor, predicate, message3, ...positionals) => {
191
116
  if (!predicate) {
192
- const isConstructor = ErrorConstructor.prototype.name != null;
193
- const error3 = isConstructor ? new ErrorConstructor(format(message3, positionals)) : ErrorConstructor(format(message3, positionals));
117
+ const formatMessage2 = positionals.length === 0 ? message3 : format(message3, positionals);
118
+ let error3;
119
+ try {
120
+ error3 = Reflect.construct(ErrorConstructor, [formatMessage2]);
121
+ } catch (err) {
122
+ error3 = ErrorConstructor(formatMessage2);
123
+ }
194
124
  throw error3;
195
125
  }
196
126
  };
@@ -223,7 +153,7 @@ var MockServiceWorker = (() => {
223
153
  );
224
154
  }
225
155
 
226
- // node_modules/.pnpm/strict-event-emitter@0.5.0/node_modules/strict-event-emitter/lib/index.mjs
156
+ // node_modules/.pnpm/strict-event-emitter@0.5.1/node_modules/strict-event-emitter/lib/index.mjs
227
157
  var MemoryLeakError = class extends Error {
228
158
  constructor(emitter, type, count) {
229
159
  super(
@@ -251,7 +181,7 @@ var MockServiceWorker = (() => {
251
181
  );
252
182
  }
253
183
  _getListeners(eventName) {
254
- return this.events.get(eventName) || [];
184
+ return Array.prototype.concat.apply([], this.events.get(eventName)) || [];
255
185
  }
256
186
  _removeListener(listeners, listener) {
257
187
  const index = listeners.indexOf(listener);
@@ -263,8 +193,9 @@ var MockServiceWorker = (() => {
263
193
  _wrapOnceListener(eventName, listener) {
264
194
  const onceListener = (...data) => {
265
195
  this.removeListener(eventName, onceListener);
266
- listener.apply(this, data);
196
+ return listener.apply(this, data);
267
197
  };
198
+ Object.defineProperty(onceListener, "name", { value: listener.name });
268
199
  return onceListener;
269
200
  }
270
201
  setMaxListeners(maxListeners) {
@@ -410,18 +341,19 @@ var MockServiceWorker = (() => {
410
341
 
411
342
  // src/core/utils/internal/Disposable.ts
412
343
  var Disposable = class {
413
- constructor() {
414
- this.subscriptions = [];
415
- }
416
- dispose() {
417
- return __async(this, null, function* () {
418
- yield Promise.all(this.subscriptions.map((subscription) => subscription()));
419
- });
344
+ subscriptions = [];
345
+ async dispose() {
346
+ await Promise.all(this.subscriptions.map((subscription) => subscription()));
420
347
  }
421
348
  };
422
349
 
423
350
  // src/core/SetupApi.ts
424
351
  var SetupApi = class extends Disposable {
352
+ initialHandlers;
353
+ currentHandlers;
354
+ emitter;
355
+ publicEmitter;
356
+ events;
425
357
  constructor(...initialHandlers) {
426
358
  super();
427
359
  invariant(
@@ -507,24 +439,34 @@ var MockServiceWorker = (() => {
507
439
  }
508
440
 
509
441
  // src/core/handlers/RequestHandler.ts
510
- var _RequestHandler = class _RequestHandler {
442
+ var RequestHandler = class _RequestHandler {
443
+ static cache = /* @__PURE__ */ new WeakMap();
444
+ info;
445
+ /**
446
+ * Indicates whether this request handler has been used
447
+ * (its resolver has successfully executed).
448
+ */
449
+ isUsed;
450
+ resolver;
451
+ resolverGenerator;
452
+ resolverGeneratorResult;
453
+ options;
511
454
  constructor(args) {
512
455
  this.resolver = args.resolver;
513
456
  this.options = args.options;
514
457
  const callFrame = getCallFrame(new Error());
515
- this.info = __spreadProps(__spreadValues({}, args.info), {
458
+ this.info = {
459
+ ...args.info,
516
460
  callFrame
517
- });
461
+ };
518
462
  this.isUsed = false;
519
463
  }
520
464
  /**
521
465
  * Parse the intercepted request to extract additional information from it.
522
466
  * Parsed result is then exposed to other methods of this request handler.
523
467
  */
524
- parse(_args) {
525
- return __async(this, null, function* () {
526
- return {};
527
- });
468
+ async parse(_args) {
469
+ return {};
528
470
  }
529
471
  /**
530
472
  * Test if this handler matches the given request.
@@ -533,17 +475,15 @@ var MockServiceWorker = (() => {
533
475
  * as a convenience method for consumers writing custom
534
476
  * handlers.
535
477
  */
536
- test(args) {
537
- return __async(this, null, function* () {
538
- const parsedResult = yield this.parse({
539
- request: args.request,
540
- resolutionContext: args.resolutionContext
541
- });
542
- return this.predicate({
543
- request: args.request,
544
- parsedResult,
545
- resolutionContext: args.resolutionContext
546
- });
478
+ async test(args) {
479
+ const parsedResult = await this.parse({
480
+ request: args.request,
481
+ resolutionContext: args.resolutionContext
482
+ });
483
+ return this.predicate({
484
+ request: args.request,
485
+ parsedResult,
486
+ resolutionContext: args.resolutionContext
547
487
  });
548
488
  }
549
489
  extendResolverArgs(_args) {
@@ -565,54 +505,60 @@ var MockServiceWorker = (() => {
565
505
  * Execute this request handler and produce a mocked response
566
506
  * using the given resolver function.
567
507
  */
568
- run(args) {
569
- return __async(this, null, function* () {
570
- var _a3, _b2;
571
- if (this.isUsed && ((_a3 = this.options) == null ? void 0 : _a3.once)) {
572
- return null;
573
- }
574
- const requestClone = this.cloneRequestOrGetFromCache(args.request);
575
- const parsedResult = yield this.parse({
576
- request: args.request,
577
- resolutionContext: args.resolutionContext
578
- });
579
- const shouldInterceptRequest = this.predicate({
580
- request: args.request,
581
- parsedResult,
582
- resolutionContext: args.resolutionContext
583
- });
584
- if (!shouldInterceptRequest) {
585
- return null;
586
- }
587
- if (this.isUsed && ((_b2 = this.options) == null ? void 0 : _b2.once)) {
588
- return null;
508
+ async run(args) {
509
+ if (this.isUsed && this.options?.once) {
510
+ return null;
511
+ }
512
+ const requestClone = this.cloneRequestOrGetFromCache(args.request);
513
+ const parsedResult = await this.parse({
514
+ request: args.request,
515
+ resolutionContext: args.resolutionContext
516
+ });
517
+ const shouldInterceptRequest = this.predicate({
518
+ request: args.request,
519
+ parsedResult,
520
+ resolutionContext: args.resolutionContext
521
+ });
522
+ if (!shouldInterceptRequest) {
523
+ return null;
524
+ }
525
+ if (this.isUsed && this.options?.once) {
526
+ return null;
527
+ }
528
+ this.isUsed = true;
529
+ const executeResolver = this.wrapResolver(this.resolver);
530
+ const resolverExtras = this.extendResolverArgs({
531
+ request: args.request,
532
+ parsedResult
533
+ });
534
+ const mockedResponsePromise = executeResolver({
535
+ ...resolverExtras,
536
+ requestId: args.requestId,
537
+ request: args.request
538
+ }).catch((errorOrResponse) => {
539
+ if (errorOrResponse instanceof Response) {
540
+ return errorOrResponse;
589
541
  }
590
- this.isUsed = true;
591
- const executeResolver = this.wrapResolver(this.resolver);
592
- const resolverExtras = this.extendResolverArgs({
593
- request: args.request,
594
- parsedResult
595
- });
596
- const mockedResponse = yield executeResolver(__spreadProps(__spreadValues({}, resolverExtras), {
597
- request: args.request
598
- }));
599
- const executionResult = this.createExecutionResult({
600
- // Pass the cloned request to the result so that logging
601
- // and other consumers could read its body once more.
602
- request: requestClone,
603
- response: mockedResponse,
604
- parsedResult
605
- });
606
- return executionResult;
542
+ throw errorOrResponse;
607
543
  });
544
+ const mockedResponse = await mockedResponsePromise;
545
+ const executionResult = this.createExecutionResult({
546
+ // Pass the cloned request to the result so that logging
547
+ // and other consumers could read its body once more.
548
+ request: requestClone,
549
+ requestId: args.requestId,
550
+ response: mockedResponse,
551
+ parsedResult
552
+ });
553
+ return executionResult;
608
554
  }
609
555
  wrapResolver(resolver) {
610
- return (info) => __async(this, null, function* () {
611
- const result = this.resolverGenerator || (yield resolver(info));
556
+ return async (info) => {
557
+ const result = this.resolverGenerator || await resolver(info);
612
558
  if (isIterable(result)) {
613
559
  this.isUsed = false;
614
560
  const { value, done } = result[Symbol.iterator]().next();
615
- const nextResponse = yield value;
561
+ const nextResponse = await value;
616
562
  if (done) {
617
563
  this.isUsed = true;
618
564
  }
@@ -627,24 +573,23 @@ var MockServiceWorker = (() => {
627
573
  this.resolverGenerator = result;
628
574
  }
629
575
  if (nextResponse) {
630
- this.resolverGeneratorResult = nextResponse == null ? void 0 : nextResponse.clone();
576
+ this.resolverGeneratorResult = nextResponse?.clone();
631
577
  }
632
578
  return nextResponse;
633
579
  }
634
580
  return result;
635
- });
581
+ };
636
582
  }
637
583
  createExecutionResult(args) {
638
584
  return {
639
585
  handler: this,
640
586
  request: args.request,
587
+ requestId: args.requestId,
641
588
  response: args.response,
642
589
  parsedResult: args.parsedResult
643
590
  };
644
591
  }
645
592
  };
646
- _RequestHandler.cache = /* @__PURE__ */ new WeakMap();
647
- var RequestHandler = _RequestHandler;
648
593
 
649
594
  // src/core/utils/internal/isStringEqual.ts
650
595
  function isStringEqual(actual, expected) {
@@ -669,17 +614,15 @@ var MockServiceWorker = (() => {
669
614
  }
670
615
 
671
616
  // src/core/utils/logging/serializeRequest.ts
672
- function serializeRequest(request) {
673
- return __async(this, null, function* () {
674
- const requestClone = request.clone();
675
- const requestText = yield requestClone.text();
676
- return {
677
- url: new URL(request.url),
678
- method: request.method,
679
- headers: Object.fromEntries(request.headers.entries()),
680
- body: requestText
681
- };
682
- });
617
+ async function serializeRequest(request) {
618
+ const requestClone = request.clone();
619
+ const requestText = await requestClone.text();
620
+ return {
621
+ url: new URL(request.url),
622
+ method: request.method,
623
+ headers: Object.fromEntries(request.headers.entries()),
624
+ body: requestText
625
+ };
683
626
  }
684
627
 
685
628
  // node_modules/.pnpm/@bundled-es-modules+statuses@1.0.1/node_modules/@bundled-es-modules/statuses/index-esm.js
@@ -851,19 +794,17 @@ var MockServiceWorker = (() => {
851
794
 
852
795
  // src/core/utils/logging/serializeResponse.ts
853
796
  var { message } = source_default;
854
- function serializeResponse(response) {
855
- return __async(this, null, function* () {
856
- const responseClone = response.clone();
857
- const responseText = yield responseClone.text();
858
- const responseStatus = responseClone.status || 200;
859
- const responseStatusText = responseClone.statusText || message[responseStatus] || "OK";
860
- return {
861
- status: responseStatus,
862
- statusText: responseStatusText,
863
- headers: Object.fromEntries(responseClone.headers.entries()),
864
- body: responseText
865
- };
866
- });
797
+ async function serializeResponse(response) {
798
+ const responseClone = response.clone();
799
+ const responseText = await responseClone.text();
800
+ const responseStatus = responseClone.status || 200;
801
+ const responseStatusText = responseClone.statusText || message[responseStatus] || "OK";
802
+ return {
803
+ status: responseStatus,
804
+ statusText: responseStatusText,
805
+ headers: Object.fromEntries(responseClone.headers.entries()),
806
+ body: responseText
807
+ };
867
808
  }
868
809
 
869
810
  // node_modules/.pnpm/path-to-regexp@6.2.1/node_modules/path-to-regexp/dist.es2015/index.js
@@ -955,7 +896,7 @@ var MockServiceWorker = (() => {
955
896
  options = {};
956
897
  }
957
898
  var tokens = lexer(str);
958
- var _a3 = options.prefixes, prefixes = _a3 === void 0 ? "./" : _a3;
899
+ var _a2 = options.prefixes, prefixes = _a2 === void 0 ? "./" : _a2;
959
900
  var defaultPattern = "[^".concat(escapeString(options.delimiter || "/#?"), "]+?");
960
901
  var result = [];
961
902
  var key = 0;
@@ -969,7 +910,7 @@ var MockServiceWorker = (() => {
969
910
  var value2 = tryConsume(type);
970
911
  if (value2 !== void 0)
971
912
  return value2;
972
- var _a4 = tokens[i], nextType = _a4.type, index = _a4.index;
913
+ var _a3 = tokens[i], nextType = _a3.type, index = _a3.index;
973
914
  throw new TypeError("Unexpected ".concat(nextType, " at ").concat(index, ", expected ").concat(type));
974
915
  };
975
916
  var consumeText = function() {
@@ -1041,9 +982,9 @@ var MockServiceWorker = (() => {
1041
982
  if (options === void 0) {
1042
983
  options = {};
1043
984
  }
1044
- var _a3 = options.decode, decode = _a3 === void 0 ? function(x) {
985
+ var _a2 = options.decode, decode = _a2 === void 0 ? function(x) {
1045
986
  return x;
1046
- } : _a3;
987
+ } : _a2;
1047
988
  return function(pathname) {
1048
989
  var m = re.exec(pathname);
1049
990
  if (!m)
@@ -1106,7 +1047,7 @@ var MockServiceWorker = (() => {
1106
1047
  if (options === void 0) {
1107
1048
  options = {};
1108
1049
  }
1109
- var _a3 = options.strict, strict = _a3 === void 0 ? false : _a3, _b2 = options.start, start = _b2 === void 0 ? true : _b2, _c = options.end, end = _c === void 0 ? true : _c, _d = options.encode, encode = _d === void 0 ? function(x) {
1050
+ var _a2 = options.strict, strict = _a2 === void 0 ? false : _a2, _b2 = options.start, start = _b2 === void 0 ? true : _b2, _c = options.end, end = _c === void 0 ? true : _c, _d = options.encode, encode = _d === void 0 ? function(x) {
1110
1051
  return x;
1111
1052
  } : _d, _e = options.delimiter, delimiter = _e === void 0 ? "/#?" : _e, _f = options.endsWith, endsWith = _f === void 0 ? "" : _f;
1112
1053
  var endsWithRe = "[".concat(escapeString(endsWith), "]|$");
@@ -1238,7 +1179,6 @@ var MockServiceWorker = (() => {
1238
1179
  var IS_NODE = isNodeProcess();
1239
1180
  var Logger = class {
1240
1181
  constructor(name) {
1241
- __publicField(this, "prefix");
1242
1182
  this.name = name;
1243
1183
  this.prefix = `[${this.name}]`;
1244
1184
  const LOGGER_NAME = getVariable("DEBUG");
@@ -1258,6 +1198,7 @@ var MockServiceWorker = (() => {
1258
1198
  this.only = noop;
1259
1199
  }
1260
1200
  }
1201
+ prefix;
1261
1202
  extend(domain) {
1262
1203
  return new Logger(`${this.name}:${domain}`);
1263
1204
  }
@@ -1385,8 +1326,8 @@ var MockServiceWorker = (() => {
1385
1326
  positionals = []
1386
1327
  } = args;
1387
1328
  const entry = this.createEntry(level, message3);
1388
- const timestampColor = (customColors == null ? void 0 : customColors.timestamp) || "gray";
1389
- const prefixColor = (customColors == null ? void 0 : customColors.prefix) || "gray";
1329
+ const timestampColor = customColors?.timestamp || "gray";
1330
+ const prefixColor = customColors?.prefix || "gray";
1390
1331
  const colorize = {
1391
1332
  timestamp: colors_exports[timestampColor],
1392
1333
  prefix: colors_exports[prefixColor]
@@ -1419,10 +1360,10 @@ var MockServiceWorker = (() => {
1419
1360
  }
1420
1361
  };
1421
1362
  var PerformanceEntry = class {
1363
+ startTime;
1364
+ endTime;
1365
+ deltaTime;
1422
1366
  constructor() {
1423
- __publicField(this, "startTime");
1424
- __publicField(this, "endTime");
1425
- __publicField(this, "deltaTime");
1426
1367
  this.startTime = performance.now();
1427
1368
  }
1428
1369
  measure() {
@@ -1454,11 +1395,10 @@ var MockServiceWorker = (() => {
1454
1395
  console.error(message3, ...positionals);
1455
1396
  }
1456
1397
  function getVariable(variableName) {
1457
- var _a3;
1458
1398
  if (IS_NODE) {
1459
1399
  return process.env[variableName];
1460
1400
  }
1461
- return (_a3 = globalThis[variableName]) == null ? void 0 : _a3.toString();
1401
+ return globalThis[variableName]?.toString();
1462
1402
  }
1463
1403
  function isDefinedAndNotEquals(value, expected) {
1464
1404
  return value !== void 0 && value !== expected;
@@ -1479,171 +1419,6 @@ var MockServiceWorker = (() => {
1479
1419
  return message3.toString();
1480
1420
  }
1481
1421
 
1482
- // node_modules/.pnpm/strict-event-emitter@0.5.1/node_modules/strict-event-emitter/lib/index.mjs
1483
- var MemoryLeakError2 = class extends Error {
1484
- constructor(emitter, type, count) {
1485
- super(
1486
- `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`
1487
- );
1488
- this.emitter = emitter;
1489
- this.type = type;
1490
- this.count = count;
1491
- this.name = "MaxListenersExceededWarning";
1492
- }
1493
- };
1494
- var _Emitter2 = class {
1495
- static listenerCount(emitter, eventName) {
1496
- return emitter.listenerCount(eventName);
1497
- }
1498
- constructor() {
1499
- this.events = /* @__PURE__ */ new Map();
1500
- this.maxListeners = _Emitter2.defaultMaxListeners;
1501
- this.hasWarnedAboutPotentialMemoryLeak = false;
1502
- }
1503
- _emitInternalEvent(internalEventName, eventName, listener) {
1504
- this.emit(
1505
- internalEventName,
1506
- ...[eventName, listener]
1507
- );
1508
- }
1509
- _getListeners(eventName) {
1510
- return Array.prototype.concat.apply([], this.events.get(eventName)) || [];
1511
- }
1512
- _removeListener(listeners, listener) {
1513
- const index = listeners.indexOf(listener);
1514
- if (index > -1) {
1515
- listeners.splice(index, 1);
1516
- }
1517
- return [];
1518
- }
1519
- _wrapOnceListener(eventName, listener) {
1520
- const onceListener = (...data) => {
1521
- this.removeListener(eventName, onceListener);
1522
- return listener.apply(this, data);
1523
- };
1524
- Object.defineProperty(onceListener, "name", { value: listener.name });
1525
- return onceListener;
1526
- }
1527
- setMaxListeners(maxListeners) {
1528
- this.maxListeners = maxListeners;
1529
- return this;
1530
- }
1531
- /**
1532
- * Returns the current max listener value for the `Emitter` which is
1533
- * either set by `emitter.setMaxListeners(n)` or defaults to
1534
- * `Emitter.defaultMaxListeners`.
1535
- */
1536
- getMaxListeners() {
1537
- return this.maxListeners;
1538
- }
1539
- /**
1540
- * Returns an array listing the events for which the emitter has registered listeners.
1541
- * The values in the array will be strings or Symbols.
1542
- */
1543
- eventNames() {
1544
- return Array.from(this.events.keys());
1545
- }
1546
- /**
1547
- * Synchronously calls each of the listeners registered for the event named `eventName`,
1548
- * in the order they were registered, passing the supplied arguments to each.
1549
- * Returns `true` if the event has listeners, `false` otherwise.
1550
- *
1551
- * @example
1552
- * const emitter = new Emitter<{ hello: [string] }>()
1553
- * emitter.emit('hello', 'John')
1554
- */
1555
- emit(eventName, ...data) {
1556
- const listeners = this._getListeners(eventName);
1557
- listeners.forEach((listener) => {
1558
- listener.apply(this, data);
1559
- });
1560
- return listeners.length > 0;
1561
- }
1562
- addListener(eventName, listener) {
1563
- this._emitInternalEvent("newListener", eventName, listener);
1564
- const nextListeners = this._getListeners(eventName).concat(listener);
1565
- this.events.set(eventName, nextListeners);
1566
- if (this.maxListeners > 0 && this.listenerCount(eventName) > this.maxListeners && !this.hasWarnedAboutPotentialMemoryLeak) {
1567
- this.hasWarnedAboutPotentialMemoryLeak = true;
1568
- const memoryLeakWarning = new MemoryLeakError2(
1569
- this,
1570
- eventName,
1571
- this.listenerCount(eventName)
1572
- );
1573
- console.warn(memoryLeakWarning);
1574
- }
1575
- return this;
1576
- }
1577
- on(eventName, listener) {
1578
- return this.addListener(eventName, listener);
1579
- }
1580
- once(eventName, listener) {
1581
- return this.addListener(
1582
- eventName,
1583
- this._wrapOnceListener(eventName, listener)
1584
- );
1585
- }
1586
- prependListener(eventName, listener) {
1587
- const listeners = this._getListeners(eventName);
1588
- if (listeners.length > 0) {
1589
- const nextListeners = [listener].concat(listeners);
1590
- this.events.set(eventName, nextListeners);
1591
- } else {
1592
- this.events.set(eventName, listeners.concat(listener));
1593
- }
1594
- return this;
1595
- }
1596
- prependOnceListener(eventName, listener) {
1597
- return this.prependListener(
1598
- eventName,
1599
- this._wrapOnceListener(eventName, listener)
1600
- );
1601
- }
1602
- removeListener(eventName, listener) {
1603
- const listeners = this._getListeners(eventName);
1604
- if (listeners.length > 0) {
1605
- this._removeListener(listeners, listener);
1606
- this.events.set(eventName, listeners);
1607
- this._emitInternalEvent("removeListener", eventName, listener);
1608
- }
1609
- return this;
1610
- }
1611
- /**
1612
- * Alias for `emitter.removeListener()`.
1613
- *
1614
- * @example
1615
- * emitter.off('hello', listener)
1616
- */
1617
- off(eventName, listener) {
1618
- return this.removeListener(eventName, listener);
1619
- }
1620
- removeAllListeners(eventName) {
1621
- if (eventName) {
1622
- this.events.delete(eventName);
1623
- } else {
1624
- this.events.clear();
1625
- }
1626
- return this;
1627
- }
1628
- /**
1629
- * Returns a copy of the array of listeners for the event named `eventName`.
1630
- */
1631
- listeners(eventName) {
1632
- return Array.from(this._getListeners(eventName));
1633
- }
1634
- /**
1635
- * Returns the number of listeners listening to the event named `eventName`.
1636
- */
1637
- listenerCount(eventName) {
1638
- return this._getListeners(eventName).length;
1639
- }
1640
- rawListeners(eventName) {
1641
- return this.listeners(eventName);
1642
- }
1643
- };
1644
- var Emitter2 = _Emitter2;
1645
- Emitter2.defaultMaxListeners = 10;
1646
-
1647
1422
  // node_modules/.pnpm/@mswjs+interceptors@0.25.14/node_modules/@mswjs/interceptors/lib/browser/chunk-WZQN3FMY.mjs
1648
1423
  var IS_PATCHED_MODULE = Symbol("isPatchedModule");
1649
1424
  function getGlobalSymbol(symbol) {
@@ -1662,7 +1437,7 @@ var MockServiceWorker = (() => {
1662
1437
  constructor(symbol) {
1663
1438
  this.symbol = symbol;
1664
1439
  this.readyState = "INACTIVE";
1665
- this.emitter = new Emitter2();
1440
+ this.emitter = new Emitter();
1666
1441
  this.subscriptions = [];
1667
1442
  this.logger = new Logger(symbol.description);
1668
1443
  this.emitter.setMaxListeners(0);
@@ -1774,9 +1549,9 @@ var MockServiceWorker = (() => {
1774
1549
  this.readyState = "DISPOSED";
1775
1550
  }
1776
1551
  getInstance() {
1777
- var _a3;
1552
+ var _a2;
1778
1553
  const instance = getGlobalSymbol(this.symbol);
1779
- this.logger.info("retrieved global instance:", (_a3 = instance == null ? void 0 : instance.constructor) == null ? void 0 : _a3.name);
1554
+ this.logger.info("retrieved global instance:", (_a2 = instance == null ? void 0 : instance.constructor) == null ? void 0 : _a2.name);
1780
1555
  return instance;
1781
1556
  }
1782
1557
  setInstance() {
@@ -2284,7 +2059,7 @@ var MockServiceWorker = (() => {
2284
2059
  try {
2285
2060
  object[method];
2286
2061
  return true;
2287
- } catch (e) {
2062
+ } catch {
2288
2063
  return false;
2289
2064
  }
2290
2065
  }
@@ -2303,13 +2078,11 @@ var MockServiceWorker = (() => {
2303
2078
  }
2304
2079
  const now = Date.now();
2305
2080
  const parsedResponseCookies = (0, import_set_cookie_parser.parse)(responseCookies).map(
2306
- (_a3) => {
2307
- var _b2 = _a3, { maxAge } = _b2, cookie = __objRest(_b2, ["maxAge"]);
2308
- return __spreadProps(__spreadValues({}, cookie), {
2309
- expires: maxAge === void 0 ? cookie.expires : new Date(now + maxAge * 1e3),
2310
- maxAge
2311
- });
2312
- }
2081
+ ({ maxAge, ...cookie }) => ({
2082
+ ...cookie,
2083
+ expires: maxAge === void 0 ? cookie.expires : new Date(now + maxAge * 1e3),
2084
+ maxAge
2085
+ })
2313
2086
  );
2314
2087
  const prevCookies = this.store.get(requestUrl.origin) || /* @__PURE__ */ new Map();
2315
2088
  parsedResponseCookies.forEach((cookie) => {
@@ -2366,13 +2139,10 @@ var MockServiceWorker = (() => {
2366
2139
  this.store.set(
2367
2140
  origin,
2368
2141
  new Map(
2369
- cookies.map((_a3) => {
2370
- var [token, _b2] = _a3, _c = _b2, { expires } = _c, cookie = __objRest(_c, ["expires"]);
2371
- return [
2372
- token,
2373
- expires === void 0 ? cookie : __spreadProps(__spreadValues({}, cookie), { expires: new Date(expires) })
2374
- ];
2375
- })
2142
+ cookies.map(([token, { expires, ...cookie }]) => [
2143
+ token,
2144
+ expires === void 0 ? cookie : { ...cookie, expires: new Date(expires) }
2145
+ ])
2376
2146
  )
2377
2147
  );
2378
2148
  });
@@ -2439,19 +2209,24 @@ Invalid value has been removed from localStorage to prevent subsequent failed pa
2439
2209
  }
2440
2210
  }
2441
2211
  function getAllRequestCookies(request) {
2442
- var _a3;
2443
2212
  const requestCookiesString = request.headers.get("cookie");
2444
2213
  const cookiesFromHeaders = requestCookiesString ? source_default2.parse(requestCookiesString) : {};
2445
2214
  store.hydrate();
2446
- const cookiesFromStore = Array.from((_a3 = store.get(request)) == null ? void 0 : _a3.entries()).reduce((cookies, [name, { value }]) => {
2215
+ const cookiesFromStore = Array.from(store.get(request)?.entries()).reduce((cookies, [name, { value }]) => {
2447
2216
  return Object.assign(cookies, { [name.trim()]: value });
2448
2217
  }, {});
2449
2218
  const cookiesFromDocument = getRequestCookies(request);
2450
- const forwardedCookies = __spreadValues(__spreadValues({}, cookiesFromDocument), cookiesFromStore);
2219
+ const forwardedCookies = {
2220
+ ...cookiesFromDocument,
2221
+ ...cookiesFromStore
2222
+ };
2451
2223
  for (const [name, value] of Object.entries(forwardedCookies)) {
2452
2224
  request.headers.append("cookie", source_default2.serialize(name, value));
2453
2225
  }
2454
- return __spreadValues(__spreadValues({}, forwardedCookies), cookiesFromHeaders);
2226
+ return {
2227
+ ...forwardedCookies,
2228
+ ...cookiesFromHeaders
2229
+ };
2455
2230
  }
2456
2231
 
2457
2232
  // src/core/handlers/HttpHandler.ts
@@ -2496,21 +2271,18 @@ Invalid value has been removed from localStorage to prevent subsequent failed pa
2496
2271
  `Found a redundant usage of query parameters in the request handler URL for "${method} ${path}". Please match against a path instead and access query parameters in the response resolver function using "req.url.searchParams".`
2497
2272
  );
2498
2273
  }
2499
- parse(args) {
2500
- return __async(this, null, function* () {
2501
- var _a3;
2502
- const url = new URL(args.request.url);
2503
- const match2 = matchRequestUrl(
2504
- url,
2505
- this.info.path,
2506
- (_a3 = args.resolutionContext) == null ? void 0 : _a3.baseUrl
2507
- );
2508
- const cookies = getAllRequestCookies(args.request);
2509
- return {
2510
- match: match2,
2511
- cookies
2512
- };
2513
- });
2274
+ async parse(args) {
2275
+ const url = new URL(args.request.url);
2276
+ const match2 = matchRequestUrl(
2277
+ url,
2278
+ this.info.path,
2279
+ args.resolutionContext?.baseUrl
2280
+ );
2281
+ const cookies = getAllRequestCookies(args.request);
2282
+ return {
2283
+ match: match2,
2284
+ cookies
2285
+ };
2514
2286
  }
2515
2287
  predicate(args) {
2516
2288
  const hasMatchingMethod = this.matchMethod(args.request.method);
@@ -2521,30 +2293,27 @@ Invalid value has been removed from localStorage to prevent subsequent failed pa
2521
2293
  return this.info.method instanceof RegExp ? this.info.method.test(actualMethod) : isStringEqual(this.info.method, actualMethod);
2522
2294
  }
2523
2295
  extendResolverArgs(args) {
2524
- var _a3;
2525
2296
  return {
2526
- params: ((_a3 = args.parsedResult.match) == null ? void 0 : _a3.params) || {},
2297
+ params: args.parsedResult.match?.params || {},
2527
2298
  cookies: args.parsedResult.cookies
2528
2299
  };
2529
2300
  }
2530
- log(args) {
2531
- return __async(this, null, function* () {
2532
- const publicUrl = getPublicUrlFromRequest(args.request);
2533
- const loggedRequest = yield serializeRequest(args.request);
2534
- const loggedResponse = yield serializeResponse(args.response);
2535
- const statusColor = getStatusCodeColor(loggedResponse.status);
2536
- console.groupCollapsed(
2537
- devUtils.formatMessage(
2538
- `${getTimestamp()} ${args.request.method} ${publicUrl} (%c${loggedResponse.status} ${loggedResponse.statusText}%c)`
2539
- ),
2540
- `color:${statusColor}`,
2541
- "color:inherit"
2542
- );
2543
- console.log("Request", loggedRequest);
2544
- console.log("Handler:", this);
2545
- console.log("Response", loggedResponse);
2546
- console.groupEnd();
2547
- });
2301
+ async log(args) {
2302
+ const publicUrl = getPublicUrlFromRequest(args.request);
2303
+ const loggedRequest = await serializeRequest(args.request);
2304
+ const loggedResponse = await serializeResponse(args.response);
2305
+ const statusColor = getStatusCodeColor(loggedResponse.status);
2306
+ console.groupCollapsed(
2307
+ devUtils.formatMessage(
2308
+ `${getTimestamp()} ${args.request.method} ${publicUrl} (%c${loggedResponse.status} ${loggedResponse.statusText}%c)`
2309
+ ),
2310
+ `color:${statusColor}`,
2311
+ "color:inherit"
2312
+ );
2313
+ console.log("Request", loggedRequest);
2314
+ console.log("Handler:", this);
2315
+ console.log("Response", loggedResponse);
2316
+ console.groupEnd();
2548
2317
  }
2549
2318
  };
2550
2319
 
@@ -5032,7 +4801,7 @@ spurious results.`);
5032
4801
  }
5033
4802
  }
5034
4803
 
5035
- // node_modules/.pnpm/headers-polyfill@4.0.1/node_modules/headers-polyfill/lib/index.mjs
4804
+ // node_modules/.pnpm/headers-polyfill@4.0.2/node_modules/headers-polyfill/lib/index.mjs
5036
4805
  var __create4 = Object.create;
5037
4806
  var __defProp6 = Object.defineProperty;
5038
4807
  var __getOwnPropDesc5 = Object.getOwnPropertyDescriptor;
@@ -5312,7 +5081,7 @@ spurious results.`);
5312
5081
  constructor(init) {
5313
5082
  this[_a] = {};
5314
5083
  this[_b] = /* @__PURE__ */ new Map();
5315
- if (["Headers", "HeadersPolyfill"].includes(init == null ? void 0 : init.constructor.name) || init instanceof _Headers) {
5084
+ if (["Headers", "HeadersPolyfill"].includes(init?.constructor.name) || init instanceof _Headers || typeof globalThis.Headers !== "undefined" && init instanceof globalThis.Headers) {
5316
5085
  const initialHeaders = init;
5317
5086
  initialHeaders.forEach((value, name) => {
5318
5087
  this.append(name, value);
@@ -5374,11 +5143,10 @@ spurious results.`);
5374
5143
  * Returns a `ByteString` sequence of all the values of a header with a given name.
5375
5144
  */
5376
5145
  get(name) {
5377
- var _a3;
5378
5146
  if (!isValidHeaderName(name)) {
5379
5147
  throw TypeError(`Invalid header name "${name}"`);
5380
5148
  }
5381
- return (_a3 = this[NORMALIZED_HEADERS][normalizeHeaderName(name)]) != null ? _a3 : null;
5149
+ return this[NORMALIZED_HEADERS][normalizeHeaderName(name)] ?? null;
5382
5150
  }
5383
5151
  /**
5384
5152
  * Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist.
@@ -5459,7 +5227,6 @@ spurious results.`);
5459
5227
 
5460
5228
  // src/core/utils/internal/parseMultipartData.ts
5461
5229
  function parseContentHeaders(headersString) {
5462
- var _a3, _b2;
5463
5230
  const headers = stringToHeaders(headersString);
5464
5231
  const contentType = headers.get("content-type") || "text/plain";
5465
5232
  const disposition = headers.get("content-disposition");
@@ -5471,8 +5238,8 @@ spurious results.`);
5471
5238
  acc[name2] = rest.join("=");
5472
5239
  return acc;
5473
5240
  }, {});
5474
- const name = (_a3 = directives.name) == null ? void 0 : _a3.slice(1, -1);
5475
- const filename = (_b2 = directives.filename) == null ? void 0 : _b2.slice(1, -1);
5241
+ const name = directives.name?.slice(1, -1);
5242
+ const filename = directives.filename?.slice(1, -1);
5476
5243
  return {
5477
5244
  name,
5478
5245
  filename,
@@ -5480,7 +5247,7 @@ spurious results.`);
5480
5247
  };
5481
5248
  }
5482
5249
  function parseMultipartData(data, headers) {
5483
- const contentType = headers == null ? void 0 : headers.get("content-type");
5250
+ const contentType = headers?.get("content-type");
5484
5251
  if (!contentType) {
5485
5252
  return void 0;
5486
5253
  }
@@ -5518,13 +5285,12 @@ spurious results.`);
5518
5285
 
5519
5286
  // src/core/utils/internal/parseGraphQLRequest.ts
5520
5287
  function parseDocumentNode(node) {
5521
- var _a3;
5522
5288
  const operationDef = node.definitions.find((definition) => {
5523
5289
  return definition.kind === "OperationDefinition";
5524
5290
  });
5525
5291
  return {
5526
- operationType: operationDef == null ? void 0 : operationDef.operation,
5527
- operationName: (_a3 = operationDef == null ? void 0 : operationDef.name) == null ? void 0 : _a3.value
5292
+ operationType: operationDef?.operation,
5293
+ operationName: operationDef?.name?.value
5528
5294
  };
5529
5295
  }
5530
5296
  function parseQuery(query) {
@@ -5556,87 +5322,82 @@ spurious results.`);
5556
5322
  }
5557
5323
  return operations.variables;
5558
5324
  }
5559
- function getGraphQLInput(request) {
5560
- return __async(this, null, function* () {
5561
- var _a3;
5562
- switch (request.method) {
5563
- case "GET": {
5564
- const url = new URL(request.url);
5565
- const query = url.searchParams.get("query");
5566
- const variables = url.searchParams.get("variables") || "";
5567
- return {
5568
- query,
5569
- variables: jsonParse(variables)
5570
- };
5571
- }
5572
- case "POST": {
5573
- const requestClone = request.clone();
5574
- if ((_a3 = request.headers.get("content-type")) == null ? void 0 : _a3.includes("multipart/form-data")) {
5575
- const responseJson = parseMultipartData(
5576
- yield requestClone.text(),
5577
- request.headers
5578
- );
5579
- if (!responseJson) {
5580
- return null;
5581
- }
5582
- const _b2 = responseJson, { operations, map } = _b2, files = __objRest(_b2, ["operations", "map"]);
5583
- const parsedOperations = jsonParse(
5584
- operations
5585
- ) || {};
5586
- if (!parsedOperations.query) {
5587
- return null;
5588
- }
5589
- const parsedMap = jsonParse(map || "") || {};
5590
- const variables = parsedOperations.variables ? extractMultipartVariables(
5591
- parsedOperations.variables,
5592
- parsedMap,
5593
- files
5594
- ) : {};
5595
- return {
5596
- query: parsedOperations.query,
5597
- variables
5598
- };
5325
+ async function getGraphQLInput(request) {
5326
+ switch (request.method) {
5327
+ case "GET": {
5328
+ const url = new URL(request.url);
5329
+ const query = url.searchParams.get("query");
5330
+ const variables = url.searchParams.get("variables") || "";
5331
+ return {
5332
+ query,
5333
+ variables: jsonParse(variables)
5334
+ };
5335
+ }
5336
+ case "POST": {
5337
+ const requestClone = request.clone();
5338
+ if (request.headers.get("content-type")?.includes("multipart/form-data")) {
5339
+ const responseJson = parseMultipartData(
5340
+ await requestClone.text(),
5341
+ request.headers
5342
+ );
5343
+ if (!responseJson) {
5344
+ return null;
5599
5345
  }
5600
- const requestJson = yield requestClone.json().catch(() => null);
5601
- if (requestJson == null ? void 0 : requestJson.query) {
5602
- const { query, variables } = requestJson;
5603
- return {
5604
- query,
5605
- variables
5606
- };
5346
+ const { operations, map, ...files } = responseJson;
5347
+ const parsedOperations = jsonParse(
5348
+ operations
5349
+ ) || {};
5350
+ if (!parsedOperations.query) {
5351
+ return null;
5607
5352
  }
5353
+ const parsedMap = jsonParse(map || "") || {};
5354
+ const variables = parsedOperations.variables ? extractMultipartVariables(
5355
+ parsedOperations.variables,
5356
+ parsedMap,
5357
+ files
5358
+ ) : {};
5359
+ return {
5360
+ query: parsedOperations.query,
5361
+ variables
5362
+ };
5363
+ }
5364
+ const requestJson = await requestClone.json().catch(() => null);
5365
+ if (requestJson?.query) {
5366
+ const { query, variables } = requestJson;
5367
+ return {
5368
+ query,
5369
+ variables
5370
+ };
5608
5371
  }
5609
- default:
5610
- return null;
5611
5372
  }
5612
- });
5373
+ default:
5374
+ return null;
5375
+ }
5613
5376
  }
5614
- function parseGraphQLRequest(request) {
5615
- return __async(this, null, function* () {
5616
- const input = yield getGraphQLInput(request);
5617
- if (!input || !input.query) {
5618
- return;
5619
- }
5620
- const { query, variables } = input;
5621
- const parsedResult = parseQuery(query);
5622
- if (parsedResult instanceof Error) {
5623
- const requestPublicUrl = getPublicUrlFromRequest(request);
5624
- throw new Error(
5625
- devUtils.formatMessage(
5626
- 'Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%s',
5627
- request.method,
5628
- requestPublicUrl,
5629
- parsedResult.message
5630
- )
5631
- );
5632
- }
5633
- return {
5634
- query: input.query,
5635
- operationType: parsedResult.operationType,
5636
- operationName: parsedResult.operationName,
5637
- variables
5638
- };
5639
- });
5377
+ async function parseGraphQLRequest(request) {
5378
+ const input = await getGraphQLInput(request);
5379
+ if (!input || !input.query) {
5380
+ return;
5381
+ }
5382
+ const { query, variables } = input;
5383
+ const parsedResult = parseQuery(query);
5384
+ if (parsedResult instanceof Error) {
5385
+ const requestPublicUrl = getPublicUrlFromRequest(request);
5386
+ throw new Error(
5387
+ devUtils.formatMessage(
5388
+ 'Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%s',
5389
+ request.method,
5390
+ requestPublicUrl,
5391
+ parsedResult.message
5392
+ )
5393
+ );
5394
+ }
5395
+ return {
5396
+ query: input.query,
5397
+ operationType: parsedResult.operationType,
5398
+ operationName: parsedResult.operationName,
5399
+ variables
5400
+ };
5640
5401
  }
5641
5402
 
5642
5403
  // src/core/handlers/GraphQLHandler.ts
@@ -5646,7 +5407,9 @@ spurious results.`);
5646
5407
  }
5647
5408
  return typeof value === "object" && "kind" in value && "definitions" in value;
5648
5409
  }
5649
- var _GraphQLHandler = class _GraphQLHandler extends RequestHandler {
5410
+ var GraphQLHandler = class _GraphQLHandler extends RequestHandler {
5411
+ endpoint;
5412
+ static parsedRequestCache = /* @__PURE__ */ new WeakMap();
5650
5413
  constructor(operationType, operationName, endpoint, resolver, options) {
5651
5414
  let resolvedOperationName = operationName;
5652
5415
  if (isDocumentNode(operationName)) {
@@ -5680,42 +5443,38 @@ spurious results.`);
5680
5443
  * GraphQL handlers. This is done to avoid multiple parsing of the
5681
5444
  * request body, which each requires a clone of the request.
5682
5445
  */
5683
- parseGraphQLRequestOrGetFromCache(request) {
5684
- return __async(this, null, function* () {
5685
- if (!_GraphQLHandler.parsedRequestCache.has(request)) {
5686
- _GraphQLHandler.parsedRequestCache.set(
5687
- request,
5688
- yield parseGraphQLRequest(request).catch((error3) => {
5689
- console.error(error3);
5690
- return void 0;
5691
- })
5692
- );
5693
- }
5694
- return _GraphQLHandler.parsedRequestCache.get(request);
5695
- });
5696
- }
5697
- parse(args) {
5698
- return __async(this, null, function* () {
5699
- const match2 = matchRequestUrl(new URL(args.request.url), this.endpoint);
5700
- const cookies = getAllRequestCookies(args.request);
5701
- if (!match2.matches) {
5702
- return { match: match2, cookies };
5703
- }
5704
- const parsedResult = yield this.parseGraphQLRequestOrGetFromCache(
5705
- args.request
5446
+ async parseGraphQLRequestOrGetFromCache(request) {
5447
+ if (!_GraphQLHandler.parsedRequestCache.has(request)) {
5448
+ _GraphQLHandler.parsedRequestCache.set(
5449
+ request,
5450
+ await parseGraphQLRequest(request).catch((error3) => {
5451
+ console.error(error3);
5452
+ return void 0;
5453
+ })
5706
5454
  );
5707
- if (typeof parsedResult === "undefined") {
5708
- return { match: match2, cookies };
5709
- }
5710
- return {
5711
- match: match2,
5712
- cookies,
5713
- query: parsedResult.query,
5714
- operationType: parsedResult.operationType,
5715
- operationName: parsedResult.operationName,
5716
- variables: parsedResult.variables
5717
- };
5718
- });
5455
+ }
5456
+ return _GraphQLHandler.parsedRequestCache.get(request);
5457
+ }
5458
+ async parse(args) {
5459
+ const match2 = matchRequestUrl(new URL(args.request.url), this.endpoint);
5460
+ const cookies = getAllRequestCookies(args.request);
5461
+ if (!match2.matches) {
5462
+ return { match: match2, cookies };
5463
+ }
5464
+ const parsedResult = await this.parseGraphQLRequestOrGetFromCache(
5465
+ args.request
5466
+ );
5467
+ if (typeof parsedResult === "undefined") {
5468
+ return { match: match2, cookies };
5469
+ }
5470
+ return {
5471
+ match: match2,
5472
+ cookies,
5473
+ query: parsedResult.query,
5474
+ operationType: parsedResult.operationType,
5475
+ operationName: parsedResult.operationName,
5476
+ variables: parsedResult.variables
5477
+ };
5719
5478
  }
5720
5479
  predicate(args) {
5721
5480
  if (args.parsedResult.operationType === void 0) {
@@ -5740,28 +5499,24 @@ Consider naming this operation or using "graphql.operation()" request handler to
5740
5499
  cookies: args.parsedResult.cookies
5741
5500
  };
5742
5501
  }
5743
- log(args) {
5744
- return __async(this, null, function* () {
5745
- const loggedRequest = yield serializeRequest(args.request);
5746
- const loggedResponse = yield serializeResponse(args.response);
5747
- const statusColor = getStatusCodeColor(loggedResponse.status);
5748
- const requestInfo = args.parsedResult.operationName ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}` : `anonymous ${args.parsedResult.operationType}`;
5749
- console.groupCollapsed(
5750
- devUtils.formatMessage(
5751
- `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${loggedResponse.statusText}%c)`
5752
- ),
5753
- `color:${statusColor}`,
5754
- "color:inherit"
5755
- );
5756
- console.log("Request:", loggedRequest);
5757
- console.log("Handler:", this);
5758
- console.log("Response:", loggedResponse);
5759
- console.groupEnd();
5760
- });
5502
+ async log(args) {
5503
+ const loggedRequest = await serializeRequest(args.request);
5504
+ const loggedResponse = await serializeResponse(args.response);
5505
+ const statusColor = getStatusCodeColor(loggedResponse.status);
5506
+ const requestInfo = args.parsedResult.operationName ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}` : `anonymous ${args.parsedResult.operationType}`;
5507
+ console.groupCollapsed(
5508
+ devUtils.formatMessage(
5509
+ `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${loggedResponse.statusText}%c)`
5510
+ ),
5511
+ `color:${statusColor}`,
5512
+ "color:inherit"
5513
+ );
5514
+ console.log("Request:", loggedRequest);
5515
+ console.log("Handler:", this);
5516
+ console.log("Response:", loggedResponse);
5517
+ console.groupEnd();
5761
5518
  }
5762
5519
  };
5763
- _GraphQLHandler.parsedRequestCache = /* @__PURE__ */ new WeakMap();
5764
- var GraphQLHandler = _GraphQLHandler;
5765
5520
 
5766
5521
  // src/core/graphql.ts
5767
5522
  function createScopedGraphQLHandler(operationType, url) {
@@ -5823,7 +5578,8 @@ Consider naming this operation or using "graphql.operation()" request handler to
5823
5578
  mutation: createScopedGraphQLHandler("mutation", url)
5824
5579
  };
5825
5580
  }
5826
- var graphql = __spreadProps(__spreadValues({}, standardGraphQLHandlers), {
5581
+ var graphql = {
5582
+ ...standardGraphQLHandlers,
5827
5583
  /**
5828
5584
  * Intercepts GraphQL operations scoped by the given URL.
5829
5585
  *
@@ -5834,42 +5590,47 @@ Consider naming this operation or using "graphql.operation()" request handler to
5834
5590
  * @see {@link https://mswjs.io/docs/api/graphql#graphqllinkurl `graphql.link()` API reference}
5835
5591
  */
5836
5592
  link: createGraphQLLink
5837
- });
5593
+ };
5838
5594
 
5839
5595
  // node_modules/.pnpm/@open-draft+until@2.1.0/node_modules/@open-draft/until/lib/index.mjs
5840
- var until = (promise) => __async(void 0, null, function* () {
5596
+ var until = async (promise) => {
5841
5597
  try {
5842
- const data = yield promise().catch((error3) => {
5598
+ const data = await promise().catch((error3) => {
5843
5599
  throw error3;
5844
5600
  });
5845
5601
  return { error: null, data };
5846
5602
  } catch (error3) {
5847
5603
  return { error: error3, data: null };
5848
5604
  }
5849
- });
5605
+ };
5850
5606
 
5851
5607
  // src/core/utils/getResponse.ts
5852
- var getResponse = (request, handlers, resolutionContext) => __async(void 0, null, function* () {
5608
+ var getResponse = async ({
5609
+ request,
5610
+ requestId,
5611
+ handlers,
5612
+ resolutionContext
5613
+ }) => {
5853
5614
  let matchingHandler = null;
5854
5615
  let result = null;
5855
5616
  for (const handler of handlers) {
5856
- result = yield handler.run({ request, resolutionContext });
5617
+ result = await handler.run({ request, requestId, resolutionContext });
5857
5618
  if (result !== null) {
5858
5619
  matchingHandler = handler;
5859
5620
  }
5860
- if (result == null ? void 0 : result.response) {
5621
+ if (result?.response) {
5861
5622
  break;
5862
5623
  }
5863
5624
  }
5864
5625
  if (matchingHandler) {
5865
5626
  return {
5866
5627
  handler: matchingHandler,
5867
- parsedResult: result == null ? void 0 : result.parsedResult,
5868
- response: result == null ? void 0 : result.response
5628
+ parsedResult: result?.parsedResult,
5629
+ response: result?.response
5869
5630
  };
5870
5631
  }
5871
5632
  return null;
5872
- });
5633
+ };
5873
5634
 
5874
5635
  // node_modules/.pnpm/@bundled-es-modules+js-levenshtein@2.0.1/node_modules/@bundled-es-modules/js-levenshtein/index-esm.js
5875
5636
  var __create5 = Object.create;
@@ -6049,154 +5810,149 @@ ${handlers.map((handler) => ` \u2022 ${handler.info.header}`).join("\n")}`;
6049
5810
  }
6050
5811
  return `Did you mean to request "${handlers[0].info.header}" instead?`;
6051
5812
  }
6052
- function onUnhandledRequest(request, handlers, strategy = "warn") {
6053
- return __async(this, null, function* () {
6054
- const parsedGraphQLQuery = yield parseGraphQLRequest(request).catch(
6055
- () => null
5813
+ async function onUnhandledRequest(request, handlers, strategy = "warn") {
5814
+ const parsedGraphQLQuery = await parseGraphQLRequest(request).catch(
5815
+ () => null
5816
+ );
5817
+ const publicUrl = getPublicUrlFromRequest(request);
5818
+ function generateHandlerSuggestion() {
5819
+ const handlerGroups = groupHandlersByType(handlers);
5820
+ const relevantHandlers = parsedGraphQLQuery ? handlerGroups.graphql : handlerGroups.http;
5821
+ const suggestedHandlers = getSuggestedHandler(
5822
+ request,
5823
+ relevantHandlers,
5824
+ parsedGraphQLQuery ? getGraphQLHandlerScore(parsedGraphQLQuery) : getHttpHandlerScore()
6056
5825
  );
6057
- const publicUrl = getPublicUrlFromRequest(request);
6058
- function generateHandlerSuggestion() {
6059
- const handlerGroups = groupHandlersByType(handlers);
6060
- const relevantHandlers = parsedGraphQLQuery ? handlerGroups.graphql : handlerGroups.http;
6061
- const suggestedHandlers = getSuggestedHandler(
6062
- request,
6063
- relevantHandlers,
6064
- parsedGraphQLQuery ? getGraphQLHandlerScore(parsedGraphQLQuery) : getHttpHandlerScore()
6065
- );
6066
- return suggestedHandlers.length > 0 ? getSuggestedHandlersMessage(suggestedHandlers) : "";
6067
- }
6068
- function getGraphQLRequestHeader(parsedGraphQLRequest) {
6069
- if (!(parsedGraphQLRequest == null ? void 0 : parsedGraphQLRequest.operationName)) {
6070
- return `anonymous ${parsedGraphQLRequest == null ? void 0 : parsedGraphQLRequest.operationType} (${request.method} ${publicUrl})`;
6071
- }
6072
- return `${parsedGraphQLRequest.operationType} ${parsedGraphQLRequest.operationName} (${request.method} ${publicUrl})`;
6073
- }
6074
- function generateUnhandledRequestMessage() {
6075
- const requestHeader = parsedGraphQLQuery ? getGraphQLRequestHeader(parsedGraphQLQuery) : `${request.method} ${publicUrl}`;
6076
- const handlerSuggestion = generateHandlerSuggestion();
6077
- const messageTemplate = [
6078
- `intercepted a request without a matching request handler:`,
6079
- ` \u2022 ${requestHeader}`,
6080
- handlerSuggestion,
6081
- `If you still wish to intercept this unhandled request, please create a request handler for it.
5826
+ return suggestedHandlers.length > 0 ? getSuggestedHandlersMessage(suggestedHandlers) : "";
5827
+ }
5828
+ function getGraphQLRequestHeader(parsedGraphQLRequest) {
5829
+ if (!parsedGraphQLRequest?.operationName) {
5830
+ return `anonymous ${parsedGraphQLRequest?.operationType} (${request.method} ${publicUrl})`;
5831
+ }
5832
+ return `${parsedGraphQLRequest.operationType} ${parsedGraphQLRequest.operationName} (${request.method} ${publicUrl})`;
5833
+ }
5834
+ function generateUnhandledRequestMessage() {
5835
+ const requestHeader = parsedGraphQLQuery ? getGraphQLRequestHeader(parsedGraphQLQuery) : `${request.method} ${publicUrl}`;
5836
+ const handlerSuggestion = generateHandlerSuggestion();
5837
+ const messageTemplate = [
5838
+ `intercepted a request without a matching request handler:`,
5839
+ ` \u2022 ${requestHeader}`,
5840
+ handlerSuggestion,
5841
+ `If you still wish to intercept this unhandled request, please create a request handler for it.
6082
5842
  Read more: https://mswjs.io/docs/getting-started/mocks`
6083
- ].filter(Boolean);
6084
- return messageTemplate.join("\n\n");
6085
- }
6086
- function applyStrategy(strategy2) {
6087
- const message3 = generateUnhandledRequestMessage();
6088
- switch (strategy2) {
6089
- case "error": {
6090
- devUtils.error("Error: %s", message3);
6091
- throw new Error(
6092
- devUtils.formatMessage(
6093
- 'Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.'
6094
- )
6095
- );
6096
- }
6097
- case "warn": {
6098
- devUtils.warn("Warning: %s", message3);
6099
- break;
6100
- }
6101
- case "bypass":
6102
- break;
6103
- default:
6104
- throw new Error(
6105
- devUtils.formatMessage(
6106
- 'Failed to react to an unhandled request: unknown strategy "%s". Please provide one of the supported strategies ("bypass", "warn", "error") or a custom callback function as the value of the "onUnhandledRequest" option.',
6107
- strategy2
6108
- )
6109
- );
5843
+ ].filter(Boolean);
5844
+ return messageTemplate.join("\n\n");
5845
+ }
5846
+ function applyStrategy(strategy2) {
5847
+ const message3 = generateUnhandledRequestMessage();
5848
+ switch (strategy2) {
5849
+ case "error": {
5850
+ devUtils.error("Error: %s", message3);
5851
+ throw new Error(
5852
+ devUtils.formatMessage(
5853
+ 'Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.'
5854
+ )
5855
+ );
6110
5856
  }
5857
+ case "warn": {
5858
+ devUtils.warn("Warning: %s", message3);
5859
+ break;
5860
+ }
5861
+ case "bypass":
5862
+ break;
5863
+ default:
5864
+ throw new Error(
5865
+ devUtils.formatMessage(
5866
+ 'Failed to react to an unhandled request: unknown strategy "%s". Please provide one of the supported strategies ("bypass", "warn", "error") or a custom callback function as the value of the "onUnhandledRequest" option.',
5867
+ strategy2
5868
+ )
5869
+ );
6111
5870
  }
6112
- if (typeof strategy === "function") {
6113
- strategy(request, {
6114
- warning: applyStrategy.bind(null, "warn"),
6115
- error: applyStrategy.bind(null, "error")
6116
- });
6117
- return;
6118
- }
6119
- applyStrategy(strategy);
6120
- });
5871
+ }
5872
+ if (typeof strategy === "function") {
5873
+ strategy(request, {
5874
+ warning: applyStrategy.bind(null, "warn"),
5875
+ error: applyStrategy.bind(null, "error")
5876
+ });
5877
+ return;
5878
+ }
5879
+ applyStrategy(strategy);
6121
5880
  }
6122
5881
 
6123
5882
  // src/core/utils/request/readResponseCookies.ts
6124
5883
  function readResponseCookies(request, response) {
6125
- store.add(__spreadProps(__spreadValues({}, request), { url: request.url.toString() }), response);
5884
+ store.add({ ...request, url: request.url.toString() }, response);
6126
5885
  store.persist();
6127
5886
  }
6128
5887
 
6129
5888
  // src/core/utils/handleRequest.ts
6130
- function handleRequest(request, requestId, handlers, options, emitter, handleRequestOptions) {
6131
- return __async(this, null, function* () {
6132
- var _a3, _b2, _c, _d, _e, _f;
6133
- emitter.emit("request:start", { request, requestId });
6134
- if (request.headers.get("x-msw-intention") === "bypass") {
6135
- emitter.emit("request:end", { request, requestId });
6136
- (_a3 = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _a3.call(handleRequestOptions, request);
6137
- return;
6138
- }
6139
- const lookupResult = yield until(() => {
6140
- return getResponse(
6141
- request,
6142
- handlers,
6143
- handleRequestOptions == null ? void 0 : handleRequestOptions.resolutionContext
6144
- );
6145
- });
6146
- if (lookupResult.error) {
6147
- emitter.emit("unhandledException", {
6148
- error: lookupResult.error,
6149
- request,
6150
- requestId
6151
- });
6152
- throw lookupResult.error;
6153
- }
6154
- if (!lookupResult.data) {
6155
- yield onUnhandledRequest(request, handlers, options.onUnhandledRequest);
6156
- emitter.emit("request:unhandled", { request, requestId });
6157
- emitter.emit("request:end", { request, requestId });
6158
- (_b2 = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _b2.call(handleRequestOptions, request);
6159
- return;
6160
- }
6161
- const { response } = lookupResult.data;
6162
- if (!response) {
6163
- emitter.emit("request:end", { request, requestId });
6164
- (_c = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _c.call(handleRequestOptions, request);
6165
- return;
6166
- }
6167
- if (response.status === 302 && response.headers.get("x-msw-intention") === "passthrough") {
6168
- emitter.emit("request:end", { request, requestId });
6169
- (_d = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _d.call(handleRequestOptions, request);
6170
- return;
6171
- }
6172
- readResponseCookies(request, response);
6173
- emitter.emit("request:match", { request, requestId });
6174
- const requiredLookupResult = lookupResult.data;
6175
- const transformedResponse = ((_e = handleRequestOptions == null ? void 0 : handleRequestOptions.transformResponse) == null ? void 0 : _e.call(handleRequestOptions, response)) || response;
6176
- (_f = handleRequestOptions == null ? void 0 : handleRequestOptions.onMockedResponse) == null ? void 0 : _f.call(
6177
- handleRequestOptions,
6178
- transformedResponse,
6179
- requiredLookupResult
6180
- );
5889
+ async function handleRequest(request, requestId, handlers, options, emitter, handleRequestOptions) {
5890
+ emitter.emit("request:start", { request, requestId });
5891
+ if (request.headers.get("x-msw-intention") === "bypass") {
6181
5892
  emitter.emit("request:end", { request, requestId });
6182
- return transformedResponse;
5893
+ handleRequestOptions?.onPassthroughResponse?.(request);
5894
+ return;
5895
+ }
5896
+ const lookupResult = await until(() => {
5897
+ return getResponse({
5898
+ request,
5899
+ requestId,
5900
+ handlers,
5901
+ resolutionContext: handleRequestOptions?.resolutionContext
5902
+ });
6183
5903
  });
5904
+ if (lookupResult.error) {
5905
+ emitter.emit("unhandledException", {
5906
+ error: lookupResult.error,
5907
+ request,
5908
+ requestId
5909
+ });
5910
+ throw lookupResult.error;
5911
+ }
5912
+ if (!lookupResult.data) {
5913
+ await onUnhandledRequest(request, handlers, options.onUnhandledRequest);
5914
+ emitter.emit("request:unhandled", { request, requestId });
5915
+ emitter.emit("request:end", { request, requestId });
5916
+ handleRequestOptions?.onPassthroughResponse?.(request);
5917
+ return;
5918
+ }
5919
+ const { response } = lookupResult.data;
5920
+ if (!response) {
5921
+ emitter.emit("request:end", { request, requestId });
5922
+ handleRequestOptions?.onPassthroughResponse?.(request);
5923
+ return;
5924
+ }
5925
+ if (response.status === 302 && response.headers.get("x-msw-intention") === "passthrough") {
5926
+ emitter.emit("request:end", { request, requestId });
5927
+ handleRequestOptions?.onPassthroughResponse?.(request);
5928
+ return;
5929
+ }
5930
+ readResponseCookies(request, response);
5931
+ emitter.emit("request:match", { request, requestId });
5932
+ const requiredLookupResult = lookupResult.data;
5933
+ const transformedResponse = handleRequestOptions?.transformResponse?.(response) || response;
5934
+ handleRequestOptions?.onMockedResponse?.(
5935
+ transformedResponse,
5936
+ requiredLookupResult
5937
+ );
5938
+ emitter.emit("request:end", { request, requestId });
5939
+ return transformedResponse;
6184
5940
  }
6185
5941
 
6186
5942
  // src/core/utils/HttpResponse/decorators.ts
6187
5943
  var { message: message2 } = source_default;
6188
5944
  function normalizeResponseInit(init = {}) {
6189
- const status = (init == null ? void 0 : init.status) || 200;
6190
- const statusText = (init == null ? void 0 : init.statusText) || message2[status] || "";
6191
- const headers = new Headers(init == null ? void 0 : init.headers);
6192
- return __spreadProps(__spreadValues({}, init), {
5945
+ const status = init?.status || 200;
5946
+ const statusText = init?.statusText || message2[status] || "";
5947
+ const headers = new Headers(init?.headers);
5948
+ return {
5949
+ ...init,
6193
5950
  headers,
6194
5951
  status,
6195
5952
  statusText
6196
- });
5953
+ };
6197
5954
  }
6198
5955
  function decorateResponse(response, init) {
6199
- var _a3;
6200
5956
  if (init.type) {
6201
5957
  Object.defineProperty(response, "type", {
6202
5958
  value: init.type,
@@ -6205,7 +5961,7 @@ Read more: https://mswjs.io/docs/getting-started/mocks`
6205
5961
  });
6206
5962
  }
6207
5963
  if (typeof document !== "undefined") {
6208
- const responseCookies = ((_a3 = init.headers.get("Set-Cookie")) == null ? void 0 : _a3.split(",")) || [];
5964
+ const responseCookies = init.headers.get("Set-Cookie")?.split(",") || [];
6209
5965
  for (const cookieString of responseCookies) {
6210
5966
  document.cookie = cookieString;
6211
5967
  }
@@ -6304,37 +6060,35 @@ Read more: https://mswjs.io/docs/getting-started/mocks`
6304
6060
  Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) + MIN_SERVER_RESPONSE_TIME
6305
6061
  );
6306
6062
  }
6307
- function delay(durationOrMode) {
6308
- return __async(this, null, function* () {
6309
- let delayTime;
6310
- if (typeof durationOrMode === "string") {
6311
- switch (durationOrMode) {
6312
- case "infinite": {
6313
- delayTime = SET_TIMEOUT_MAX_ALLOWED_INT;
6314
- break;
6315
- }
6316
- case "real": {
6317
- delayTime = getRealisticResponseTime();
6318
- break;
6319
- }
6320
- default: {
6321
- throw new Error(
6322
- `Failed to delay a response: unknown delay mode "${durationOrMode}". Please make sure you provide one of the supported modes ("real", "infinite") or a number.`
6323
- );
6324
- }
6063
+ async function delay(durationOrMode) {
6064
+ let delayTime;
6065
+ if (typeof durationOrMode === "string") {
6066
+ switch (durationOrMode) {
6067
+ case "infinite": {
6068
+ delayTime = SET_TIMEOUT_MAX_ALLOWED_INT;
6069
+ break;
6325
6070
  }
6326
- } else if (typeof durationOrMode === "undefined") {
6327
- delayTime = getRealisticResponseTime();
6328
- } else {
6329
- if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {
6071
+ case "real": {
6072
+ delayTime = getRealisticResponseTime();
6073
+ break;
6074
+ }
6075
+ default: {
6330
6076
  throw new Error(
6331
- `Failed to delay a response: provided delay duration (${durationOrMode}) exceeds the maximum allowed duration for "setTimeout" (${SET_TIMEOUT_MAX_ALLOWED_INT}). This will cause the response to be returned immediately. Please use a number within the allowed range to delay the response by exact duration, or consider the "infinite" delay mode to delay the response indefinitely.`
6077
+ `Failed to delay a response: unknown delay mode "${durationOrMode}". Please make sure you provide one of the supported modes ("real", "infinite") or a number.`
6332
6078
  );
6333
6079
  }
6334
- delayTime = durationOrMode;
6335
6080
  }
6336
- return new Promise((resolve) => setTimeout(resolve, delayTime));
6337
- });
6081
+ } else if (typeof durationOrMode === "undefined") {
6082
+ delayTime = getRealisticResponseTime();
6083
+ } else {
6084
+ if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {
6085
+ throw new Error(
6086
+ `Failed to delay a response: provided delay duration (${durationOrMode}) exceeds the maximum allowed duration for "setTimeout" (${SET_TIMEOUT_MAX_ALLOWED_INT}). This will cause the response to be returned immediately. Please use a number within the allowed range to delay the response by exact duration, or consider the "infinite" delay mode to delay the response indefinitely.`
6087
+ );
6088
+ }
6089
+ delayTime = durationOrMode;
6090
+ }
6091
+ return new Promise((resolve) => setTimeout(resolve, delayTime));
6338
6092
  }
6339
6093
 
6340
6094
  // src/core/bypass.ts
@@ -6387,9 +6141,9 @@ Read more: https://mswjs.io/docs/getting-started/mocks`
6387
6141
  }
6388
6142
 
6389
6143
  // src/browser/setupWorker/start/utils/getWorkerInstance.ts
6390
- var getWorkerInstance = (_0, ..._1) => __async(void 0, [_0, ..._1], function* (url, options = {}, findWorker) {
6144
+ var getWorkerInstance = async (url, options = {}, findWorker) => {
6391
6145
  const absoluteWorkerUrl = getAbsoluteWorkerUrl(url);
6392
- const mockRegistrations = yield navigator.serviceWorker.getRegistrations().then(
6146
+ const mockRegistrations = await navigator.serviceWorker.getRegistrations().then(
6393
6147
  (registrations) => registrations.filter(
6394
6148
  (registration) => getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker)
6395
6149
  )
@@ -6410,21 +6164,21 @@ Read more: https://mswjs.io/docs/getting-started/mocks`
6410
6164
  ];
6411
6165
  });
6412
6166
  }
6413
- const registrationResult = yield until(
6414
- () => __async(void 0, null, function* () {
6415
- const registration = yield navigator.serviceWorker.register(url, options);
6167
+ const registrationResult = await until(
6168
+ async () => {
6169
+ const registration = await navigator.serviceWorker.register(url, options);
6416
6170
  return [
6417
6171
  // Compare existing worker registration by its worker URL,
6418
6172
  // to prevent irrelevant workers to resolve here (such as Codesandbox worker).
6419
6173
  getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),
6420
6174
  registration
6421
6175
  ];
6422
- })
6176
+ }
6423
6177
  );
6424
6178
  if (registrationResult.error) {
6425
6179
  const isWorkerMissing = registrationResult.error.message.includes("(404)");
6426
6180
  if (isWorkerMissing) {
6427
- const scopeUrl = new URL((options == null ? void 0 : options.scope) || "/", location.href);
6181
+ const scopeUrl = new URL(options?.scope || "/", location.href);
6428
6182
  throw new Error(
6429
6183
  devUtils.formatMessage(`Failed to register a Service Worker for scope ('${scopeUrl.href}') with script ('${absoluteWorkerUrl}'): Service Worker script does not exist at the given path.
6430
6184
 
@@ -6441,7 +6195,7 @@ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/i
6441
6195
  );
6442
6196
  }
6443
6197
  return registrationResult.data;
6444
- });
6198
+ };
6445
6199
 
6446
6200
  // src/browser/setupWorker/start/utils/printStartMessage.ts
6447
6201
  function printStartMessage(args = {}) {
@@ -6469,23 +6223,20 @@ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/i
6469
6223
  }
6470
6224
 
6471
6225
  // src/browser/setupWorker/start/utils/enableMocking.ts
6472
- function enableMocking(context, options) {
6473
- return __async(this, null, function* () {
6474
- var _a3, _b2;
6475
- context.workerChannel.send("MOCK_ACTIVATE");
6476
- yield context.events.once("MOCKING_ENABLED");
6477
- if (context.isMockingEnabled) {
6478
- devUtils.warn(
6479
- `Found a redundant "worker.start()" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this "worker.start()" call.`
6480
- );
6481
- return;
6482
- }
6483
- context.isMockingEnabled = true;
6484
- printStartMessage({
6485
- quiet: options.quiet,
6486
- workerScope: (_a3 = context.registration) == null ? void 0 : _a3.scope,
6487
- workerUrl: (_b2 = context.worker) == null ? void 0 : _b2.scriptURL
6488
- });
6226
+ async function enableMocking(context, options) {
6227
+ context.workerChannel.send("MOCK_ACTIVATE");
6228
+ await context.events.once("MOCKING_ENABLED");
6229
+ if (context.isMockingEnabled) {
6230
+ devUtils.warn(
6231
+ `Found a redundant "worker.start()" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this "worker.start()" call.`
6232
+ );
6233
+ return;
6234
+ }
6235
+ context.isMockingEnabled = true;
6236
+ printStartMessage({
6237
+ quiet: options.quiet,
6238
+ workerScope: context.registration?.scope,
6239
+ workerUrl: context.worker?.scriptURL
6489
6240
  });
6490
6241
  }
6491
6242
 
@@ -6510,9 +6261,10 @@ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/i
6510
6261
 
6511
6262
  // src/browser/utils/parseWorkerRequest.ts
6512
6263
  function parseWorkerRequest(incomingRequest) {
6513
- return new Request(incomingRequest.url, __spreadProps(__spreadValues({}, incomingRequest), {
6264
+ return new Request(incomingRequest.url, {
6265
+ ...incomingRequest,
6514
6266
  body: pruneGetRequestBody(incomingRequest)
6515
- }));
6267
+ });
6516
6268
  }
6517
6269
 
6518
6270
  // src/core/utils/toResponseInit.ts
@@ -6526,15 +6278,13 @@ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/i
6526
6278
 
6527
6279
  // src/browser/setupWorker/start/createRequestListener.ts
6528
6280
  var createRequestListener = (context, options) => {
6529
- return (event, message3) => __async(void 0, null, function* () {
6530
- var _b2;
6281
+ return async (event, message3) => {
6531
6282
  const messageChannel = new WorkerChannel(event.ports[0]);
6532
6283
  const requestId = message3.payload.id;
6533
6284
  const request = parseWorkerRequest(message3.payload);
6534
6285
  const requestCloneForLogs = request.clone();
6535
6286
  try {
6536
- let _a3;
6537
- yield handleRequest(
6287
+ await handleRequest(
6538
6288
  request,
6539
6289
  requestId,
6540
6290
  context.requestHandlers,
@@ -6544,36 +6294,36 @@ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/i
6544
6294
  onPassthroughResponse() {
6545
6295
  messageChannel.postMessage("NOT_FOUND");
6546
6296
  },
6547
- onMockedResponse(_0, _1) {
6548
- return __async(this, arguments, function* (response, { handler, parsedResult }) {
6549
- const responseClone = response.clone();
6550
- const responseCloneForLogs = response.clone();
6551
- const responseInit = toResponseInit(response);
6552
- if (context.supports.readableStreamTransfer) {
6553
- const responseStreamOrNull = response.body;
6554
- messageChannel.postMessage(
6555
- "MOCK_RESPONSE",
6556
- __spreadProps(__spreadValues({}, responseInit), {
6557
- body: responseStreamOrNull
6558
- }),
6559
- responseStreamOrNull ? [responseStreamOrNull] : void 0
6560
- );
6561
- } else {
6562
- const responseBufferOrNull = response.body === null ? null : yield responseClone.arrayBuffer();
6563
- messageChannel.postMessage("MOCK_RESPONSE", __spreadProps(__spreadValues({}, responseInit), {
6564
- body: responseBufferOrNull
6565
- }));
6566
- }
6567
- if (!options.quiet) {
6568
- context.emitter.once("response:mocked", () => {
6569
- handler.log({
6570
- request: requestCloneForLogs,
6571
- response: responseCloneForLogs,
6572
- parsedResult
6573
- });
6297
+ async onMockedResponse(response, { handler, parsedResult }) {
6298
+ const responseClone = response.clone();
6299
+ const responseCloneForLogs = response.clone();
6300
+ const responseInit = toResponseInit(response);
6301
+ if (context.supports.readableStreamTransfer) {
6302
+ const responseStreamOrNull = response.body;
6303
+ messageChannel.postMessage(
6304
+ "MOCK_RESPONSE",
6305
+ {
6306
+ ...responseInit,
6307
+ body: responseStreamOrNull
6308
+ },
6309
+ responseStreamOrNull ? [responseStreamOrNull] : void 0
6310
+ );
6311
+ } else {
6312
+ const responseBufferOrNull = response.body === null ? null : await responseClone.arrayBuffer();
6313
+ messageChannel.postMessage("MOCK_RESPONSE", {
6314
+ ...responseInit,
6315
+ body: responseBufferOrNull
6316
+ });
6317
+ }
6318
+ if (!options.quiet) {
6319
+ context.emitter.once("response:mocked", () => {
6320
+ handler.log({
6321
+ request: requestCloneForLogs,
6322
+ response: responseCloneForLogs,
6323
+ parsedResult
6574
6324
  });
6575
- }
6576
- });
6325
+ });
6326
+ }
6577
6327
  }
6578
6328
  }
6579
6329
  );
@@ -6587,7 +6337,7 @@ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/i
6587
6337
  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`,
6588
6338
  request.method,
6589
6339
  request.url,
6590
- (_b2 = error3.stack) != null ? _b2 : error3
6340
+ error3.stack ?? error3
6591
6341
  );
6592
6342
  messageChannel.postMessage("MOCK_RESPONSE", {
6593
6343
  status: 500,
@@ -6603,48 +6353,28 @@ This exception has been gracefully handled as a 500 response, however, it's stro
6603
6353
  });
6604
6354
  }
6605
6355
  }
6606
- });
6356
+ };
6607
6357
  };
6608
6358
 
6609
6359
  // src/browser/utils/requestIntegrityCheck.ts
6610
- function requestIntegrityCheck(context, serviceWorker) {
6611
- return __async(this, null, function* () {
6612
- context.workerChannel.send("INTEGRITY_CHECK_REQUEST");
6613
- const { payload: actualChecksum } = yield context.events.once(
6614
- "INTEGRITY_CHECK_RESPONSE"
6360
+ async function requestIntegrityCheck(context, serviceWorker) {
6361
+ context.workerChannel.send("INTEGRITY_CHECK_REQUEST");
6362
+ const { payload: actualChecksum } = await context.events.once(
6363
+ "INTEGRITY_CHECK_RESPONSE"
6364
+ );
6365
+ if (actualChecksum !== "223d191a56023cd36aa88c802961b911") {
6366
+ throw new Error(
6367
+ `Currently active Service Worker (${actualChecksum}) is behind the latest published one (${"223d191a56023cd36aa88c802961b911"}).`
6615
6368
  );
6616
- if (actualChecksum !== "c5f7f8e188b673ea4e677df7ea3c5a39") {
6617
- throw new Error(
6618
- `Currently active Service Worker (${actualChecksum}) is behind the latest published one (${"c5f7f8e188b673ea4e677df7ea3c5a39"}).`
6619
- );
6620
- }
6621
- return serviceWorker;
6622
- });
6623
- }
6624
-
6625
- // src/browser/utils/deferNetworkRequestsUntil.ts
6626
- function deferNetworkRequestsUntil(predicatePromise) {
6627
- const originalXhrSend = window.XMLHttpRequest.prototype.send;
6628
- window.XMLHttpRequest.prototype.send = function(...args) {
6629
- until(() => predicatePromise).then(() => {
6630
- window.XMLHttpRequest.prototype.send = originalXhrSend;
6631
- this.send(...args);
6632
- });
6633
- };
6634
- const originalFetch = window.fetch;
6635
- window.fetch = (...args) => __async(this, null, function* () {
6636
- yield until(() => predicatePromise);
6637
- window.fetch = originalFetch;
6638
- return window.fetch(...args);
6639
- });
6369
+ }
6370
+ return serviceWorker;
6640
6371
  }
6641
6372
 
6642
6373
  // src/browser/setupWorker/start/createResponseListener.ts
6643
6374
  function createResponseListener(context) {
6644
6375
  return (_, message3) => {
6645
- var _a3;
6646
6376
  const { payload: responseJson } = message3;
6647
- if ((_a3 = responseJson.type) == null ? void 0 : _a3.includes("opaque")) {
6377
+ if (responseJson.type?.includes("opaque")) {
6648
6378
  return;
6649
6379
  }
6650
6380
  const response = responseJson.status === 0 ? Response.error() : new Response(
@@ -6674,7 +6404,7 @@ This exception has been gracefully handled as a 500 response, however, it's stro
6674
6404
 
6675
6405
  // src/browser/setupWorker/start/utils/validateWorkerScope.ts
6676
6406
  function validateWorkerScope(registration, options) {
6677
- if (!(options == null ? void 0 : options.quiet) && !location.href.startsWith(registration.scope)) {
6407
+ if (!options?.quiet && !location.href.startsWith(registration.scope)) {
6678
6408
  devUtils.warn(
6679
6409
  `Cannot intercept requests on this page because it's outside of the worker's scope ("${registration.scope}"). If you wish to mock API requests on this page, you must resolve this scope issue.
6680
6410
 
@@ -6687,21 +6417,21 @@ This exception has been gracefully handled as a 500 response, however, it's stro
6687
6417
  // src/browser/setupWorker/start/createStartHandler.ts
6688
6418
  var createStartHandler = (context) => {
6689
6419
  return function start(options, customOptions) {
6690
- const startWorkerInstance = () => __async(this, null, function* () {
6420
+ const startWorkerInstance = async () => {
6691
6421
  context.events.removeAllListeners();
6692
6422
  context.workerChannel.on(
6693
6423
  "REQUEST",
6694
6424
  createRequestListener(context, options)
6695
6425
  );
6696
6426
  context.workerChannel.on("RESPONSE", createResponseListener(context));
6697
- const instance = yield getWorkerInstance(
6427
+ const instance = await getWorkerInstance(
6698
6428
  options.serviceWorker.url,
6699
6429
  options.serviceWorker.options,
6700
6430
  options.findWorker
6701
6431
  );
6702
6432
  const [worker, registration] = instance;
6703
6433
  if (!worker) {
6704
- const missingWorkerMessage = (customOptions == null ? void 0 : customOptions.findWorker) ? devUtils.formatMessage(
6434
+ const missingWorkerMessage = customOptions?.findWorker ? devUtils.formatMessage(
6705
6435
  `Failed to locate the Service Worker registration using a custom "findWorker" predicate.
6706
6436
 
6707
6437
  Please ensure that the custom predicate properly locates the Service Worker registration at "%s".
@@ -6727,7 +6457,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
6727
6457
  }
6728
6458
  window.clearInterval(context.keepAliveInterval);
6729
6459
  });
6730
- const integrityCheckResult = yield until(
6460
+ const integrityCheckResult = await until(
6731
6461
  () => requestIntegrityCheck(context, worker)
6732
6462
  );
6733
6463
  if (integrityCheckResult.error) {
@@ -6746,12 +6476,12 @@ If this message still persists after updating, please report an issue: https://g
6746
6476
  );
6747
6477
  validateWorkerScope(registration, context.startOptions);
6748
6478
  return registration;
6749
- });
6479
+ };
6750
6480
  const workerRegistration = startWorkerInstance().then(
6751
- (registration) => __async(this, null, function* () {
6481
+ async (registration) => {
6752
6482
  const pendingInstance = registration.installing || registration.waiting;
6753
6483
  if (pendingInstance) {
6754
- yield new Promise((resolve) => {
6484
+ await new Promise((resolve) => {
6755
6485
  pendingInstance.addEventListener("statechange", () => {
6756
6486
  if (pendingInstance.state === "activated") {
6757
6487
  return resolve();
@@ -6759,15 +6489,12 @@ If this message still persists after updating, please report an issue: https://g
6759
6489
  });
6760
6490
  });
6761
6491
  }
6762
- yield enableMocking(context, options).catch((error3) => {
6763
- throw new Error(`Failed to enable mocking: ${error3 == null ? void 0 : error3.message}`);
6492
+ await enableMocking(context, options).catch((error3) => {
6493
+ throw new Error(`Failed to enable mocking: ${error3?.message}`);
6764
6494
  });
6765
6495
  return registration;
6766
- })
6496
+ }
6767
6497
  );
6768
- if (options.waitUntilReady) {
6769
- deferNetworkRequestsUntil(workerRegistration);
6770
- }
6771
6498
  return workerRegistration;
6772
6499
  };
6773
6500
  };
@@ -6786,7 +6513,6 @@ If this message still persists after updating, please report an issue: https://g
6786
6513
  // src/browser/setupWorker/stop/createStop.ts
6787
6514
  var createStop = (context) => {
6788
6515
  return function stop() {
6789
- var _a3;
6790
6516
  if (!context.isMockingEnabled) {
6791
6517
  devUtils.warn(
6792
6518
  'Found a redundant "worker.stop()" call. Note that stopping the worker while mocking already stopped has no effect. Consider removing this "worker.stop()" call.'
@@ -6796,7 +6522,7 @@ If this message still persists after updating, please report an issue: https://g
6796
6522
  context.workerChannel.send("MOCK_DEACTIVATE");
6797
6523
  context.isMockingEnabled = false;
6798
6524
  window.clearInterval(context.keepAliveInterval);
6799
- printStopMessage({ quiet: (_a3 = context.startOptions) == null ? void 0 : _a3.quiet });
6525
+ printStopMessage({ quiet: context.startOptions?.quiet });
6800
6526
  };
6801
6527
  };
6802
6528
 
@@ -6865,43 +6591,42 @@ If this message still persists after updating, please report an issue: https://g
6865
6591
  };
6866
6592
  return executor;
6867
6593
  }
6868
- var _executor, _decorate, decorate_fn, _a2;
6869
- var DeferredPromise = (_a2 = class extends Promise {
6594
+ var DeferredPromise = class extends Promise {
6595
+ #executor;
6596
+ resolve;
6597
+ reject;
6870
6598
  constructor(executor = null) {
6871
6599
  const deferredExecutor = createDeferredExecutor();
6872
6600
  super((originalResolve, originalReject) => {
6873
6601
  deferredExecutor(originalResolve, originalReject);
6874
- executor == null ? void 0 : executor(deferredExecutor.resolve, deferredExecutor.reject);
6602
+ executor?.(deferredExecutor.resolve, deferredExecutor.reject);
6875
6603
  });
6876
- __privateAdd(this, _decorate);
6877
- __privateAdd(this, _executor, void 0);
6878
- __publicField(this, "resolve");
6879
- __publicField(this, "reject");
6880
- __privateSet(this, _executor, deferredExecutor);
6881
- this.resolve = __privateGet(this, _executor).resolve;
6882
- this.reject = __privateGet(this, _executor).reject;
6604
+ this.#executor = deferredExecutor;
6605
+ this.resolve = this.#executor.resolve;
6606
+ this.reject = this.#executor.reject;
6883
6607
  }
6884
6608
  get state() {
6885
- return __privateGet(this, _executor).state;
6609
+ return this.#executor.state;
6886
6610
  }
6887
6611
  get rejectionReason() {
6888
- return __privateGet(this, _executor).rejectionReason;
6612
+ return this.#executor.rejectionReason;
6889
6613
  }
6890
6614
  then(onFulfilled, onRejected) {
6891
- return __privateMethod(this, _decorate, decorate_fn).call(this, super.then(onFulfilled, onRejected));
6615
+ return this.#decorate(super.then(onFulfilled, onRejected));
6892
6616
  }
6893
6617
  catch(onRejected) {
6894
- return __privateMethod(this, _decorate, decorate_fn).call(this, super.catch(onRejected));
6618
+ return this.#decorate(super.catch(onRejected));
6895
6619
  }
6896
6620
  finally(onfinally) {
6897
- return __privateMethod(this, _decorate, decorate_fn).call(this, super.finally(onfinally));
6621
+ return this.#decorate(super.finally(onfinally));
6898
6622
  }
6899
- }, _executor = new WeakMap(), _decorate = new WeakSet(), decorate_fn = function(promise) {
6900
- return Object.defineProperties(promise, {
6901
- resolve: { configurable: true, value: this.resolve },
6902
- reject: { configurable: true, value: this.reject }
6903
- });
6904
- }, _a2);
6623
+ #decorate(promise) {
6624
+ return Object.defineProperties(promise, {
6625
+ resolve: { configurable: true, value: this.resolve },
6626
+ reject: { configurable: true, value: this.reject }
6627
+ });
6628
+ }
6629
+ };
6905
6630
 
6906
6631
  // node_modules/.pnpm/@mswjs+interceptors@0.25.14/node_modules/@mswjs/interceptors/lib/browser/chunk-72HT65NX.mjs
6907
6632
  function uuidv4() {
@@ -6938,16 +6663,14 @@ If this message still persists after updating, please report an issue: https://g
6938
6663
  requestController
6939
6664
  };
6940
6665
  }
6941
- function emitAsync(emitter, eventName, ...data) {
6942
- return __async(this, null, function* () {
6943
- const listners = emitter.listeners(eventName);
6944
- if (listners.length === 0) {
6945
- return;
6946
- }
6947
- for (const listener of listners) {
6948
- yield listener.apply(emitter, data);
6949
- }
6950
- });
6666
+ async function emitAsync(emitter, eventName, ...data) {
6667
+ const listners = emitter.listeners(eventName);
6668
+ if (listners.length === 0) {
6669
+ return;
6670
+ }
6671
+ for (const listener of listners) {
6672
+ await listener.apply(emitter, data);
6673
+ }
6951
6674
  }
6952
6675
 
6953
6676
  // node_modules/.pnpm/@mswjs+interceptors@0.25.14/node_modules/@mswjs/interceptors/lib/browser/chunk-KDHQ3KDO.mjs
@@ -6972,8 +6695,8 @@ If this message still persists after updating, please report an issue: https://g
6972
6695
  !pureFetch[IS_PATCHED_MODULE],
6973
6696
  'Failed to patch the "fetch" module: already patched.'
6974
6697
  );
6975
- globalThis.fetch = (input, init) => __async(this, null, function* () {
6976
- var _a3;
6698
+ globalThis.fetch = async (input, init) => {
6699
+ var _a2;
6977
6700
  const requestId = uuidv4();
6978
6701
  const request = new Request(input, init);
6979
6702
  this.logger.info("[%s] %s", request.method, request.url);
@@ -7000,12 +6723,12 @@ If this message still persists after updating, please report an issue: https://g
7000
6723
  },
7001
6724
  { once: true }
7002
6725
  );
7003
- const resolverResult = yield until(() => __async(this, null, function* () {
6726
+ const resolverResult = await until(async () => {
7004
6727
  const listenersFinished = emitAsync(this.emitter, "request", {
7005
6728
  request: interactiveRequest,
7006
6729
  requestId
7007
6730
  });
7008
- yield Promise.race([
6731
+ await Promise.race([
7009
6732
  requestAborted,
7010
6733
  // Put the listeners invocation Promise in the same race condition
7011
6734
  // with the request abort Promise because otherwise awaiting the listeners
@@ -7014,10 +6737,10 @@ If this message still persists after updating, please report an issue: https://g
7014
6737
  requestController.responsePromise
7015
6738
  ]);
7016
6739
  this.logger.info("all request listeners have been resolved!");
7017
- const mockedResponse2 = yield requestController.responsePromise;
6740
+ const mockedResponse2 = await requestController.responsePromise;
7018
6741
  this.logger.info("event.respondWith called with:", mockedResponse2);
7019
6742
  return mockedResponse2;
7020
- }));
6743
+ });
7021
6744
  if (requestAborted.state === "rejected") {
7022
6745
  return Promise.reject(requestAborted.rejectionReason);
7023
6746
  }
@@ -7025,7 +6748,7 @@ If this message still persists after updating, please report an issue: https://g
7025
6748
  return Promise.reject(createNetworkError(resolverResult.error));
7026
6749
  }
7027
6750
  const mockedResponse = resolverResult.data;
7028
- if (mockedResponse && !((_a3 = request.signal) == null ? void 0 : _a3.aborted)) {
6751
+ if (mockedResponse && !((_a2 = request.signal) == null ? void 0 : _a2.aborted)) {
7029
6752
  this.logger.info("received mocked response:", mockedResponse);
7030
6753
  if (isPropertyAccessible2(mockedResponse, "type") && mockedResponse.type === "error") {
7031
6754
  this.logger.info(
@@ -7061,7 +6784,7 @@ If this message still persists after updating, please report an issue: https://g
7061
6784
  });
7062
6785
  return response;
7063
6786
  });
7064
- });
6787
+ };
7065
6788
  Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {
7066
6789
  enumerable: true,
7067
6790
  configurable: true,
@@ -7300,7 +7023,7 @@ If this message still persists after updating, please report an issue: https://g
7300
7023
  }
7301
7024
  },
7302
7025
  methodCall: ([methodName, args], invoke) => {
7303
- var _a3;
7026
+ var _a2;
7304
7027
  switch (methodName) {
7305
7028
  case "open": {
7306
7029
  const [method, url] = args;
@@ -7352,7 +7075,7 @@ If this message still persists after updating, please report an issue: https://g
7352
7075
  }
7353
7076
  });
7354
7077
  const fetchRequest = this.toFetchApiRequest();
7355
- const onceRequestSettled = ((_a3 = this.onRequest) == null ? void 0 : _a3.call(this, {
7078
+ const onceRequestSettled = ((_a2 = this.onRequest) == null ? void 0 : _a2.call(this, {
7356
7079
  request: fetchRequest,
7357
7080
  requestId: this.requestId
7358
7081
  })) || Promise.resolve();
@@ -7476,8 +7199,8 @@ If this message still persists after updating, please report an issue: https://g
7476
7199
  if (response.body) {
7477
7200
  this.logger.info("mocked response has body, streaming...");
7478
7201
  const reader = response.body.getReader();
7479
- const readNextResponseBodyChunk = () => __async(this, null, function* () {
7480
- const { value, done } = yield reader.read();
7202
+ const readNextResponseBodyChunk = async () => {
7203
+ const { value, done } = await reader.read();
7481
7204
  if (done) {
7482
7205
  this.logger.info("response body stream done!");
7483
7206
  finalizeResponse();
@@ -7492,7 +7215,7 @@ If this message still persists after updating, please report an issue: https://g
7492
7215
  });
7493
7216
  }
7494
7217
  readNextResponseBodyChunk();
7495
- });
7218
+ };
7496
7219
  readNextResponseBodyChunk();
7497
7220
  } else {
7498
7221
  finalizeResponse();
@@ -7701,78 +7424,74 @@ If this message still persists after updating, please report an issue: https://g
7701
7424
  originalRequest,
7702
7425
  logger
7703
7426
  );
7704
- xhrRequestController.onRequest = function(_0) {
7705
- return __async(this, arguments, function* ({ request, requestId }) {
7706
- const { interactiveRequest, requestController } = toInteractiveRequest(request);
7707
- this.logger.info("awaiting mocked response...");
7708
- emitter.once("request", ({ requestId: pendingRequestId }) => {
7709
- if (pendingRequestId !== requestId) {
7710
- return;
7711
- }
7712
- if (requestController.responsePromise.state === "pending") {
7713
- requestController.respondWith(void 0);
7714
- }
7715
- });
7716
- const resolverResult = yield until(() => __async(this, null, function* () {
7717
- this.logger.info(
7718
- 'emitting the "request" event for %s listener(s)...',
7719
- emitter.listenerCount("request")
7720
- );
7721
- yield emitAsync(emitter, "request", {
7722
- request: interactiveRequest,
7723
- requestId
7724
- });
7725
- this.logger.info('all "request" listeners settled!');
7726
- const mockedResponse2 = yield requestController.responsePromise;
7727
- this.logger.info("event.respondWith called with:", mockedResponse2);
7728
- return mockedResponse2;
7729
- }));
7730
- if (resolverResult.error) {
7731
- this.logger.info(
7732
- "request listener threw an exception, aborting request...",
7733
- resolverResult.error
7734
- );
7735
- xhrRequestController.errorWith(resolverResult.error);
7427
+ xhrRequestController.onRequest = async function({ request, requestId }) {
7428
+ const { interactiveRequest, requestController } = toInteractiveRequest(request);
7429
+ this.logger.info("awaiting mocked response...");
7430
+ emitter.once("request", ({ requestId: pendingRequestId }) => {
7431
+ if (pendingRequestId !== requestId) {
7736
7432
  return;
7737
7433
  }
7738
- const mockedResponse = resolverResult.data;
7739
- if (typeof mockedResponse !== "undefined") {
7740
- this.logger.info(
7741
- "received mocked response: %d %s",
7742
- mockedResponse.status,
7743
- mockedResponse.statusText
7744
- );
7745
- if (mockedResponse.type === "error") {
7746
- this.logger.info(
7747
- "received a network error response, rejecting the request promise..."
7748
- );
7749
- xhrRequestController.errorWith(new TypeError("Network error"));
7750
- return;
7751
- }
7752
- return xhrRequestController.respondWith(mockedResponse);
7434
+ if (requestController.responsePromise.state === "pending") {
7435
+ requestController.respondWith(void 0);
7753
7436
  }
7437
+ });
7438
+ const resolverResult = await until(async () => {
7754
7439
  this.logger.info(
7755
- "no mocked response received, performing request as-is..."
7440
+ 'emitting the "request" event for %s listener(s)...',
7441
+ emitter.listenerCount("request")
7756
7442
  );
7443
+ await emitAsync(emitter, "request", {
7444
+ request: interactiveRequest,
7445
+ requestId
7446
+ });
7447
+ this.logger.info('all "request" listeners settled!');
7448
+ const mockedResponse2 = await requestController.responsePromise;
7449
+ this.logger.info("event.respondWith called with:", mockedResponse2);
7450
+ return mockedResponse2;
7757
7451
  });
7452
+ if (resolverResult.error) {
7453
+ this.logger.info(
7454
+ "request listener threw an exception, aborting request...",
7455
+ resolverResult.error
7456
+ );
7457
+ xhrRequestController.errorWith(resolverResult.error);
7458
+ return;
7459
+ }
7460
+ const mockedResponse = resolverResult.data;
7461
+ if (typeof mockedResponse !== "undefined") {
7462
+ this.logger.info(
7463
+ "received mocked response: %d %s",
7464
+ mockedResponse.status,
7465
+ mockedResponse.statusText
7466
+ );
7467
+ if (mockedResponse.type === "error") {
7468
+ this.logger.info(
7469
+ "received a network error response, rejecting the request promise..."
7470
+ );
7471
+ xhrRequestController.errorWith(new TypeError("Network error"));
7472
+ return;
7473
+ }
7474
+ return xhrRequestController.respondWith(mockedResponse);
7475
+ }
7476
+ this.logger.info(
7477
+ "no mocked response received, performing request as-is..."
7478
+ );
7758
7479
  };
7759
- xhrRequestController.onResponse = function(_0) {
7760
- return __async(this, arguments, function* ({
7480
+ xhrRequestController.onResponse = async function({
7481
+ response,
7482
+ isMockedResponse,
7483
+ request,
7484
+ requestId
7485
+ }) {
7486
+ this.logger.info(
7487
+ 'emitting the "response" event for %s listener(s)...',
7488
+ emitter.listenerCount("response")
7489
+ );
7490
+ emitter.emit("response", {
7761
7491
  response,
7762
7492
  isMockedResponse,
7763
7493
  request,
7764
7494
  requestId
7765
- }) {
7766
- this.logger.info(
7767
- 'emitting the "response" event for %s listener(s)...',
7768
- emitter.listenerCount("response")
7769
- );
7770
- emitter.emit("response", {
7771
- response,
7772
- isMockedResponse,
7773
- request,
7774
- requestId
7775
- });
7776
7495
  });
7777
7496
  };
7778
7497
  return xhrRequestController.request;
@@ -7829,9 +7548,9 @@ If this message still persists after updating, please report an issue: https://g
7829
7548
  name: "fallback",
7830
7549
  interceptors: [new FetchInterceptor(), new XMLHttpRequestInterceptor()]
7831
7550
  });
7832
- interceptor.on("request", (_0) => __async(this, [_0], function* ({ request, requestId }) {
7551
+ interceptor.on("request", async ({ request, requestId }) => {
7833
7552
  const requestCloneForLogs = request.clone();
7834
- const response = yield handleRequest(
7553
+ const response = await handleRequest(
7835
7554
  request,
7836
7555
  requestId,
7837
7556
  context.requestHandlers,
@@ -7854,7 +7573,7 @@ If this message still persists after updating, please report an issue: https://g
7854
7573
  if (response) {
7855
7574
  request.respondWith(response);
7856
7575
  }
7857
- }));
7576
+ });
7858
7577
  interceptor.on(
7859
7578
  "response",
7860
7579
  ({ response, isMockedResponse, request, requestId }) => {
@@ -7874,27 +7593,24 @@ If this message still persists after updating, please report an issue: https://g
7874
7593
 
7875
7594
  // src/browser/setupWorker/start/createFallbackStart.ts
7876
7595
  function createFallbackStart(context) {
7877
- return function start(options) {
7878
- return __async(this, null, function* () {
7879
- context.fallbackInterceptor = createFallbackRequestListener(
7880
- context,
7881
- options
7882
- );
7883
- printStartMessage({
7884
- message: "Mocking enabled (fallback mode).",
7885
- quiet: options.quiet
7886
- });
7887
- return void 0;
7596
+ return async function start(options) {
7597
+ context.fallbackInterceptor = createFallbackRequestListener(
7598
+ context,
7599
+ options
7600
+ );
7601
+ printStartMessage({
7602
+ message: "Mocking enabled (fallback mode).",
7603
+ quiet: options.quiet
7888
7604
  });
7605
+ return void 0;
7889
7606
  };
7890
7607
  }
7891
7608
 
7892
7609
  // src/browser/setupWorker/stop/createFallbackStop.ts
7893
7610
  function createFallbackStop(context) {
7894
7611
  return function stop() {
7895
- var _a3, _b2;
7896
- (_a3 = context.fallbackInterceptor) == null ? void 0 : _a3.dispose();
7897
- printStopMessage({ quiet: (_b2 = context.startOptions) == null ? void 0 : _b2.quiet });
7612
+ context.fallbackInterceptor?.dispose();
7613
+ printStopMessage({ quiet: context.startOptions?.quiet });
7898
7614
  };
7899
7615
  }
7900
7616
 
@@ -7914,10 +7630,12 @@ If this message still persists after updating, please report an issue: https://g
7914
7630
 
7915
7631
  // src/browser/setupWorker/setupWorker.ts
7916
7632
  var SetupWorkerApi = class extends SetupApi {
7633
+ context;
7634
+ startHandler = null;
7635
+ stopHandler = null;
7636
+ listeners;
7917
7637
  constructor(...handlers) {
7918
7638
  super(...handlers);
7919
- this.startHandler = null;
7920
- this.stopHandler = null;
7921
7639
  invariant(
7922
7640
  !isNodeProcess(),
7923
7641
  devUtils.formatMessage(
@@ -7953,8 +7671,7 @@ If this message still persists after updating, please report an issue: https://g
7953
7671
  });
7954
7672
  },
7955
7673
  send: (type) => {
7956
- var _a3;
7957
- (_a3 = this.context.worker) == null ? void 0 : _a3.postMessage(type);
7674
+ this.context.worker?.postMessage(type);
7958
7675
  }
7959
7676
  },
7960
7677
  events: {
@@ -8019,14 +7736,17 @@ If this message still persists after updating, please report an issue: https://g
8019
7736
  this.stopHandler = context.supports.serviceWorkerApi ? createFallbackStop(context) : createStop(context);
8020
7737
  return context;
8021
7738
  }
8022
- start() {
8023
- return __async(this, arguments, function* (options = {}) {
8024
- this.context.startOptions = mergeRight(
8025
- DEFAULT_START_OPTIONS,
8026
- options
7739
+ async start(options = {}) {
7740
+ if (options.waitUntilReady === true) {
7741
+ devUtils.warn(
7742
+ 'The "waitUntilReady" option has been deprecated. Please remove it from this "worker.start()" call. Follow the recommended Browser integration (https://mswjs.io/docs/integrations/browser) to eliminate any race conditions between the Service Worker registration and any requests made by your application on initial render.'
8027
7743
  );
8028
- return yield this.startHandler(this.context.startOptions, options);
8029
- });
7744
+ }
7745
+ this.context.startOptions = mergeRight(
7746
+ DEFAULT_START_OPTIONS,
7747
+ options
7748
+ );
7749
+ return await this.startHandler(this.context.startOptions, options);
8030
7750
  }
8031
7751
  stop() {
8032
7752
  super.dispose();