msw 2.4.3 → 2.4.5

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.
package/lib/iife/index.js CHANGED
@@ -77,7 +77,7 @@ var MockServiceWorker = (() => {
77
77
  });
78
78
 
79
79
  // node_modules/.pnpm/graphql@16.9.0/node_modules/graphql/jsutils/invariant.mjs
80
- function invariant2(condition, message3) {
80
+ function invariant3(condition, message3) {
81
81
  const booleanCondition = Boolean(condition);
82
82
  if (!booleanCondition) {
83
83
  throw new Error(
@@ -96,7 +96,7 @@ var MockServiceWorker = (() => {
96
96
  let lastLineStart = 0;
97
97
  let line = 1;
98
98
  for (const match2 of source.body.matchAll(LineRegExp)) {
99
- typeof match2.index === "number" || invariant2(false);
99
+ typeof match2.index === "number" || invariant3(false);
100
100
  if (match2.index >= position) {
101
101
  break;
102
102
  }
@@ -4968,7 +4968,7 @@ spurious results.`);
4968
4968
  }
4969
4969
  throw new TypeError(`Cannot convert value to AST: ${inspect(serialized)}.`);
4970
4970
  }
4971
- invariant2(false, "Unexpected input type: " + inspect(type));
4971
+ invariant3(false, "Unexpected input type: " + inspect(type));
4972
4972
  }
4973
4973
  var integerStringRegExp;
4974
4974
  var init_astFromValue = __esm({
@@ -5190,7 +5190,7 @@ spurious results.`);
5190
5190
  if (isNonNullType(type)) {
5191
5191
  return TypeKind.NON_NULL;
5192
5192
  }
5193
- invariant2(false, `Unexpected type: "${inspect(type)}".`);
5193
+ invariant3(false, `Unexpected type: "${inspect(type)}".`);
5194
5194
  }
5195
5195
  },
5196
5196
  name: {
@@ -6760,7 +6760,7 @@ spurious results.`);
6760
6760
  }
6761
6761
  function getDirectiveLocationForASTPath(ancestors) {
6762
6762
  const appliedTo = ancestors[ancestors.length - 1];
6763
- "kind" in appliedTo || invariant2(false);
6763
+ "kind" in appliedTo || invariant3(false);
6764
6764
  switch (appliedTo.kind) {
6765
6765
  case Kind.OPERATION_DEFINITION:
6766
6766
  return getDirectiveLocationForOperation(appliedTo.operation);
@@ -6801,11 +6801,11 @@ spurious results.`);
6801
6801
  return DirectiveLocation.INPUT_OBJECT;
6802
6802
  case Kind.INPUT_VALUE_DEFINITION: {
6803
6803
  const parentNode = ancestors[ancestors.length - 3];
6804
- "kind" in parentNode || invariant2(false);
6804
+ "kind" in parentNode || invariant3(false);
6805
6805
  return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION ? DirectiveLocation.INPUT_FIELD_DEFINITION : DirectiveLocation.ARGUMENT_DEFINITION;
6806
6806
  }
6807
6807
  default:
6808
- invariant2(false, "Unexpected kind: " + inspect(appliedTo.kind));
6808
+ invariant3(false, "Unexpected kind: " + inspect(appliedTo.kind));
6809
6809
  }
6810
6810
  }
6811
6811
  function getDirectiveLocationForOperation(operation) {
@@ -7875,7 +7875,7 @@ spurious results.`);
7875
7875
  if (isInputObjectType(type)) {
7876
7876
  return Kind.INPUT_OBJECT_TYPE_EXTENSION;
7877
7877
  }
7878
- invariant2(false, "Unexpected type: " + inspect(type));
7878
+ invariant3(false, "Unexpected type: " + inspect(type));
7879
7879
  }
7880
7880
  function extensionKindToTypeName(kind) {
7881
7881
  switch (kind) {
@@ -7892,7 +7892,7 @@ spurious results.`);
7892
7892
  case Kind.INPUT_OBJECT_TYPE_EXTENSION:
7893
7893
  return "input object";
7894
7894
  default:
7895
- invariant2(false, "Unexpected kind: " + inspect(kind));
7895
+ invariant3(false, "Unexpected kind: " + inspect(kind));
7896
7896
  }
7897
7897
  }
7898
7898
  var defKindToExtKind;
@@ -8238,7 +8238,7 @@ spurious results.`);
8238
8238
  }
8239
8239
  return parseResult;
8240
8240
  }
8241
- invariant2(false, "Unexpected input type: " + inspect(type));
8241
+ invariant3(false, "Unexpected input type: " + inspect(type));
8242
8242
  }
8243
8243
  var init_coerceInputValue = __esm({
8244
8244
  "node_modules/.pnpm/graphql@16.9.0/node_modules/graphql/utilities/coerceInputValue.mjs"() {
@@ -8352,7 +8352,7 @@ spurious results.`);
8352
8352
  }
8353
8353
  return result;
8354
8354
  }
8355
- invariant2(false, "Unexpected input type: " + inspect(type));
8355
+ invariant3(false, "Unexpected input type: " + inspect(type));
8356
8356
  }
8357
8357
  function isMissingVariable(valueNode, variables) {
8358
8358
  return valueNode.kind === Kind.VARIABLE && (variables == null || variables[valueNode.name.value] === void 0);
@@ -9114,7 +9114,7 @@ spurious results.`);
9114
9114
  },
9115
9115
  leave() {
9116
9116
  const prevKnownNames = knownNameStack.pop();
9117
- prevKnownNames || invariant2(false);
9117
+ prevKnownNames || invariant3(false);
9118
9118
  knownNames = prevKnownNames;
9119
9119
  }
9120
9120
  },
@@ -10383,7 +10383,7 @@ spurious results.`);
10383
10383
  result
10384
10384
  );
10385
10385
  }
10386
- invariant2(
10386
+ invariant3(
10387
10387
  false,
10388
10388
  "Cannot complete value of unexpected output type: " + inspect(returnType)
10389
10389
  );
@@ -10950,7 +10950,7 @@ spurious results.`);
10950
10950
  const deprecationReason = fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.deprecationReason;
10951
10951
  if (fieldDef && deprecationReason != null) {
10952
10952
  const parentType = context.getParentType();
10953
- parentType != null || invariant2(false);
10953
+ parentType != null || invariant3(false);
10954
10954
  context.reportError(
10955
10955
  new GraphQLError(
10956
10956
  `The field ${parentType.name}.${fieldDef.name} is deprecated. ${deprecationReason}`,
@@ -10978,7 +10978,7 @@ spurious results.`);
10978
10978
  } else {
10979
10979
  const parentType = context.getParentType();
10980
10980
  const fieldDef = context.getFieldDef();
10981
- parentType != null && fieldDef != null || invariant2(false);
10981
+ parentType != null && fieldDef != null || invariant3(false);
10982
10982
  context.reportError(
10983
10983
  new GraphQLError(
10984
10984
  `Field "${parentType.name}.${fieldDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`,
@@ -11012,7 +11012,7 @@ spurious results.`);
11012
11012
  const deprecationReason = enumValueDef === null || enumValueDef === void 0 ? void 0 : enumValueDef.deprecationReason;
11013
11013
  if (enumValueDef && deprecationReason != null) {
11014
11014
  const enumTypeDef = getNamedType(context.getInputType());
11015
- enumTypeDef != null || invariant2(false);
11015
+ enumTypeDef != null || invariant3(false);
11016
11016
  context.reportError(
11017
11017
  new GraphQLError(
11018
11018
  `The enum value "${enumTypeDef.name}.${enumValueDef.name}" is deprecated. ${deprecationReason}`,
@@ -11337,7 +11337,7 @@ spurious results.`);
11337
11337
  schema,
11338
11338
  document: document2
11339
11339
  });
11340
- !result.errors && result.data || invariant2(false);
11340
+ !result.errors && result.data || invariant3(false);
11341
11341
  return result.data;
11342
11342
  }
11343
11343
  var init_introspectionFromSchema = __esm({
@@ -11726,7 +11726,7 @@ spurious results.`);
11726
11726
  if (isInputObjectType(type)) {
11727
11727
  return extendInputObjectType(type);
11728
11728
  }
11729
- invariant2(false, "Unexpected type: " + inspect(type));
11729
+ invariant3(false, "Unexpected type: " + inspect(type));
11730
11730
  }
11731
11731
  function extendInputObjectType(type) {
11732
11732
  var _typeExtensionsMap$co;
@@ -12253,7 +12253,7 @@ spurious results.`);
12253
12253
  fields: () => sortInputFields(config.fields)
12254
12254
  });
12255
12255
  }
12256
- invariant2(false, "Unexpected type: " + inspect(type));
12256
+ invariant3(false, "Unexpected type: " + inspect(type));
12257
12257
  }
12258
12258
  }
12259
12259
  function sortObjMap(map, sortValueFn) {
@@ -12365,7 +12365,7 @@ ${operationTypes.join("\n")}
12365
12365
  if (isInputObjectType(type)) {
12366
12366
  return printInputObject(type);
12367
12367
  }
12368
- invariant2(false, "Unexpected type: " + inspect(type));
12368
+ invariant3(false, "Unexpected type: " + inspect(type));
12369
12369
  }
12370
12370
  function printScalar(type) {
12371
12371
  return printDescription(type) + `scalar ${type.name}` + printSpecifiedByURL(type);
@@ -12952,11 +12952,11 @@ ${operationTypes.join("\n")}
12952
12952
  if (isInputObjectType(type)) {
12953
12953
  return "an Input type";
12954
12954
  }
12955
- invariant2(false, "Unexpected type: " + inspect(type));
12955
+ invariant3(false, "Unexpected type: " + inspect(type));
12956
12956
  }
12957
12957
  function stringifyValue2(value, type) {
12958
12958
  const ast = astFromValue(value, type);
12959
- ast != null || invariant2(false);
12959
+ ast != null || invariant3(false);
12960
12960
  return print(sortValueNode(ast));
12961
12961
  }
12962
12962
  function diff(oldArray, newArray) {
@@ -14388,7 +14388,7 @@ ${operationTypes.join("\n")}
14388
14388
  return stringToRegexp(path, keys, options);
14389
14389
  }
14390
14390
 
14391
- // node_modules/.pnpm/@mswjs+interceptors@0.29.0/node_modules/@mswjs/interceptors/lib/browser/chunk-6HYIRFX2.mjs
14391
+ // node_modules/.pnpm/@mswjs+interceptors@0.35.0/node_modules/@mswjs/interceptors/lib/browser/chunk-6HYIRFX2.mjs
14392
14392
  var encoder = new TextEncoder();
14393
14393
  function encodeBuffer(text) {
14394
14394
  return encoder.encode(text);
@@ -14404,7 +14404,7 @@ ${operationTypes.join("\n")}
14404
14404
  );
14405
14405
  }
14406
14406
 
14407
- // node_modules/.pnpm/@mswjs+interceptors@0.29.0/node_modules/@mswjs/interceptors/lib/browser/chunk-OMISYKWR.mjs
14407
+ // node_modules/.pnpm/@mswjs+interceptors@0.35.0/node_modules/@mswjs/interceptors/lib/browser/chunk-XVPRNJO7.mjs
14408
14408
  var IS_PATCHED_MODULE = Symbol("isPatchedModule");
14409
14409
  function isPropertyAccessible(obj, key) {
14410
14410
  try {
@@ -14421,6 +14421,13 @@ ${operationTypes.join("\n")}
14421
14421
  205,
14422
14422
  304
14423
14423
  ]);
14424
+ var RESPONSE_STATUS_CODES_WITH_REDIRECT = /* @__PURE__ */ new Set([
14425
+ 301,
14426
+ 302,
14427
+ 303,
14428
+ 307,
14429
+ 308
14430
+ ]);
14424
14431
  function isResponseWithoutBody(status) {
14425
14432
  return RESPONSE_STATUS_CODES_WITHOUT_BODY.has(status);
14426
14433
  }
@@ -14461,6 +14468,90 @@ ${operationTypes.join("\n")}
14461
14468
  return false;
14462
14469
  }
14463
14470
 
14471
+ // node_modules/.pnpm/outvariant@1.4.3/node_modules/outvariant/lib/index.mjs
14472
+ var POSITIONALS_EXP2 = /(%?)(%([sdijo]))/g;
14473
+ function serializePositional2(positional, flag) {
14474
+ switch (flag) {
14475
+ case "s":
14476
+ return positional;
14477
+ case "d":
14478
+ case "i":
14479
+ return Number(positional);
14480
+ case "j":
14481
+ return JSON.stringify(positional);
14482
+ case "o": {
14483
+ if (typeof positional === "string") {
14484
+ return positional;
14485
+ }
14486
+ const json = JSON.stringify(positional);
14487
+ if (json === "{}" || json === "[]" || /^\[object .+?\]$/.test(json)) {
14488
+ return positional;
14489
+ }
14490
+ return json;
14491
+ }
14492
+ }
14493
+ }
14494
+ function format2(message3, ...positionals) {
14495
+ if (positionals.length === 0) {
14496
+ return message3;
14497
+ }
14498
+ let positionalIndex = 0;
14499
+ let formattedMessage = message3.replace(
14500
+ POSITIONALS_EXP2,
14501
+ (match2, isEscaped, _, flag) => {
14502
+ const positional = positionals[positionalIndex];
14503
+ const value = serializePositional2(positional, flag);
14504
+ if (!isEscaped) {
14505
+ positionalIndex++;
14506
+ return value;
14507
+ }
14508
+ return match2;
14509
+ }
14510
+ );
14511
+ if (positionalIndex < positionals.length) {
14512
+ formattedMessage += ` ${positionals.slice(positionalIndex).join(" ")}`;
14513
+ }
14514
+ formattedMessage = formattedMessage.replace(/%{2,2}/g, "%");
14515
+ return formattedMessage;
14516
+ }
14517
+ var STACK_FRAMES_TO_IGNORE2 = 2;
14518
+ function cleanErrorStack2(error3) {
14519
+ if (!error3.stack) {
14520
+ return;
14521
+ }
14522
+ const nextStack = error3.stack.split("\n");
14523
+ nextStack.splice(1, STACK_FRAMES_TO_IGNORE2);
14524
+ error3.stack = nextStack.join("\n");
14525
+ }
14526
+ var InvariantError2 = class extends Error {
14527
+ constructor(message3, ...positionals) {
14528
+ super(message3);
14529
+ this.message = message3;
14530
+ this.name = "Invariant Violation";
14531
+ this.message = format2(message3, ...positionals);
14532
+ cleanErrorStack2(this);
14533
+ }
14534
+ };
14535
+ var invariant2 = (predicate, message3, ...positionals) => {
14536
+ if (!predicate) {
14537
+ throw new InvariantError2(message3, ...positionals);
14538
+ }
14539
+ };
14540
+ invariant2.as = (ErrorConstructor, predicate, message3, ...positionals) => {
14541
+ if (!predicate) {
14542
+ const formatMessage2 = positionals.length === 0 ? message3 : format2(message3, ...positionals);
14543
+ let error3;
14544
+ try {
14545
+ error3 = Reflect.construct(ErrorConstructor, [
14546
+ formatMessage2
14547
+ ]);
14548
+ } catch (err) {
14549
+ error3 = ErrorConstructor(formatMessage2);
14550
+ }
14551
+ throw error3;
14552
+ }
14553
+ };
14554
+
14464
14555
  // node_modules/.pnpm/@open-draft+logger@0.3.0/node_modules/@open-draft/logger/lib/index.mjs
14465
14556
  var __defProp3 = Object.defineProperty;
14466
14557
  var __export2 = (target, all) => {
@@ -14689,21 +14780,21 @@ ${operationTypes.join("\n")}
14689
14780
  var noop = () => void 0;
14690
14781
  function log(message3, ...positionals) {
14691
14782
  if (IS_NODE) {
14692
- process.stdout.write(format(message3, ...positionals) + "\n");
14783
+ process.stdout.write(format2(message3, ...positionals) + "\n");
14693
14784
  return;
14694
14785
  }
14695
14786
  console.log(message3, ...positionals);
14696
14787
  }
14697
14788
  function warn2(message3, ...positionals) {
14698
14789
  if (IS_NODE) {
14699
- process.stderr.write(format(message3, ...positionals) + "\n");
14790
+ process.stderr.write(format2(message3, ...positionals) + "\n");
14700
14791
  return;
14701
14792
  }
14702
14793
  console.warn(message3, ...positionals);
14703
14794
  }
14704
14795
  function error2(message3, ...positionals) {
14705
14796
  if (IS_NODE) {
14706
- process.stderr.write(format(message3, ...positionals) + "\n");
14797
+ process.stderr.write(format2(message3, ...positionals) + "\n");
14707
14798
  return;
14708
14799
  }
14709
14800
  console.error(message3, ...positionals);
@@ -14733,7 +14824,7 @@ ${operationTypes.join("\n")}
14733
14824
  return message3.toString();
14734
14825
  }
14735
14826
 
14736
- // node_modules/.pnpm/@mswjs+interceptors@0.29.0/node_modules/@mswjs/interceptors/lib/browser/chunk-QED3Q6Z2.mjs
14827
+ // node_modules/.pnpm/@mswjs+interceptors@0.35.0/node_modules/@mswjs/interceptors/lib/browser/chunk-QED3Q6Z2.mjs
14737
14828
  var INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id";
14738
14829
  function getGlobalSymbol(symbol) {
14739
14830
  return (
@@ -14881,7 +14972,7 @@ ${operationTypes.join("\n")}
14881
14972
  return Math.random().toString(16).slice(2);
14882
14973
  }
14883
14974
 
14884
- // node_modules/.pnpm/@mswjs+interceptors@0.29.0/node_modules/@mswjs/interceptors/lib/browser/index.mjs
14975
+ // node_modules/.pnpm/@mswjs+interceptors@0.35.0/node_modules/@mswjs/interceptors/lib/browser/index.mjs
14885
14976
  var BatchInterceptor = class extends Interceptor {
14886
14977
  constructor(options) {
14887
14978
  BatchInterceptor.symbol = Symbol(options.name);
@@ -27060,6 +27151,9 @@ ${operationTypes.join("\n")}
27060
27151
  }
27061
27152
  putCookie(cookie, callback) {
27062
27153
  try {
27154
+ if (cookie.maxAge === 0) {
27155
+ return;
27156
+ }
27063
27157
  const store2 = this.getStore();
27064
27158
  store2.push(cookie);
27065
27159
  this.updateStore(store2);
@@ -27070,6 +27164,15 @@ ${operationTypes.join("\n")}
27070
27164
  }
27071
27165
  }
27072
27166
  updateCookie(oldCookie, newCookie, callback) {
27167
+ if (newCookie.maxAge === 0) {
27168
+ this.removeCookie(
27169
+ newCookie.domain || "",
27170
+ newCookie.path || "",
27171
+ newCookie.key,
27172
+ callback
27173
+ );
27174
+ return;
27175
+ }
27073
27176
  this.putCookie(newCookie, callback);
27074
27177
  }
27075
27178
  removeCookie(domain, path, key, callback) {
@@ -29010,34 +29113,58 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29010
29113
  }
29011
29114
  };
29012
29115
 
29013
- // node_modules/.pnpm/@mswjs+interceptors@0.29.0/node_modules/@mswjs/interceptors/lib/browser/chunk-OUWBQF3Z.mjs
29116
+ // node_modules/.pnpm/@mswjs+interceptors@0.35.0/node_modules/@mswjs/interceptors/lib/browser/chunk-THPGBWJQ.mjs
29117
+ var InterceptorError = class extends Error {
29118
+ constructor(message3) {
29119
+ super(message3);
29120
+ this.name = "InterceptorError";
29121
+ Object.setPrototypeOf(this, InterceptorError.prototype);
29122
+ }
29123
+ };
29124
+ var kRequestHandled = Symbol("kRequestHandled");
29125
+ var kResponsePromise = Symbol("kResponsePromise");
29014
29126
  var RequestController = class {
29015
29127
  constructor(request) {
29016
29128
  this.request = request;
29017
- this.responsePromise = new DeferredPromise();
29129
+ this[kRequestHandled] = false;
29130
+ this[kResponsePromise] = new DeferredPromise();
29018
29131
  }
29132
+ /**
29133
+ * Respond to this request with the given `Response` instance.
29134
+ * @example
29135
+ * controller.respondWith(new Response())
29136
+ * controller.respondWith(Response.json({ id }))
29137
+ * controller.respondWith(Response.error())
29138
+ */
29019
29139
  respondWith(response) {
29020
- invariant(
29021
- this.responsePromise.state === "pending",
29022
- 'Failed to respond to "%s %s" request: the "request" event has already been responded to.',
29140
+ invariant2.as(
29141
+ InterceptorError,
29142
+ !this[kRequestHandled],
29143
+ 'Failed to respond to the "%s %s" request: the "request" event has already been handled.',
29144
+ this.request.method,
29145
+ this.request.url
29146
+ );
29147
+ this[kRequestHandled] = true;
29148
+ this[kResponsePromise].resolve(response);
29149
+ }
29150
+ /**
29151
+ * Error this request with the given error.
29152
+ * @example
29153
+ * controller.errorWith()
29154
+ * controller.errorWith(new Error('Oops!'))
29155
+ */
29156
+ errorWith(error3) {
29157
+ invariant2.as(
29158
+ InterceptorError,
29159
+ !this[kRequestHandled],
29160
+ 'Failed to error the "%s %s" request: the "request" event has already been handled.',
29023
29161
  this.request.method,
29024
29162
  this.request.url
29025
29163
  );
29026
- this.responsePromise.resolve(response);
29164
+ this[kRequestHandled] = true;
29165
+ this[kResponsePromise].resolve(error3);
29027
29166
  }
29028
29167
  };
29029
- function toInteractiveRequest(request) {
29030
- const requestController = new RequestController(request);
29031
- Reflect.set(
29032
- request,
29033
- "respondWith",
29034
- requestController.respondWith.bind(requestController)
29035
- );
29036
- return {
29037
- interactiveRequest: request,
29038
- requestController
29039
- };
29040
- }
29041
29168
  async function emitAsync(emitter, eventName, ...data) {
29042
29169
  const listners = emitter.listeners(eventName);
29043
29170
  if (listners.length === 0) {
@@ -29047,8 +29174,114 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29047
29174
  await listener.apply(emitter, data);
29048
29175
  }
29049
29176
  }
29177
+ function isNodeLikeError(error3) {
29178
+ if (error3 == null) {
29179
+ return false;
29180
+ }
29181
+ if (!(error3 instanceof Error)) {
29182
+ return false;
29183
+ }
29184
+ return "code" in error3 && "errno" in error3;
29185
+ }
29186
+ async function handleRequest2(options) {
29187
+ const handleResponse = async (response) => {
29188
+ if (response instanceof Error) {
29189
+ options.onError(response);
29190
+ } else if (isResponseError(response)) {
29191
+ options.onRequestError(response);
29192
+ } else {
29193
+ await options.onResponse(response);
29194
+ }
29195
+ return true;
29196
+ };
29197
+ const handleResponseError = async (error3) => {
29198
+ if (error3 instanceof InterceptorError) {
29199
+ throw result.error;
29200
+ }
29201
+ if (isNodeLikeError(error3)) {
29202
+ options.onError(error3);
29203
+ return true;
29204
+ }
29205
+ if (error3 instanceof Response) {
29206
+ return await handleResponse(error3);
29207
+ }
29208
+ return false;
29209
+ };
29210
+ options.emitter.once("request", ({ requestId: pendingRequestId }) => {
29211
+ if (pendingRequestId !== options.requestId) {
29212
+ return;
29213
+ }
29214
+ if (options.controller[kResponsePromise].state === "pending") {
29215
+ options.controller[kResponsePromise].resolve(void 0);
29216
+ }
29217
+ });
29218
+ const requestAbortPromise = new DeferredPromise();
29219
+ if (options.request.signal) {
29220
+ options.request.signal.addEventListener(
29221
+ "abort",
29222
+ () => {
29223
+ requestAbortPromise.reject(options.request.signal.reason);
29224
+ },
29225
+ { once: true }
29226
+ );
29227
+ }
29228
+ const result = await until(async () => {
29229
+ const requestListtenersPromise = emitAsync(options.emitter, "request", {
29230
+ requestId: options.requestId,
29231
+ request: options.request,
29232
+ controller: options.controller
29233
+ });
29234
+ await Promise.race([
29235
+ // Short-circuit the request handling promise if the request gets aborted.
29236
+ requestAbortPromise,
29237
+ requestListtenersPromise,
29238
+ options.controller[kResponsePromise]
29239
+ ]);
29240
+ const mockedResponse = await options.controller[kResponsePromise];
29241
+ return mockedResponse;
29242
+ });
29243
+ if (requestAbortPromise.state === "rejected") {
29244
+ options.onError(requestAbortPromise.rejectionReason);
29245
+ return true;
29246
+ }
29247
+ if (result.error) {
29248
+ if (await handleResponseError(result.error)) {
29249
+ return true;
29250
+ }
29251
+ if (options.emitter.listenerCount("unhandledException") > 0) {
29252
+ const unhandledExceptionController = new RequestController(
29253
+ options.request
29254
+ );
29255
+ await emitAsync(options.emitter, "unhandledException", {
29256
+ error: result.error,
29257
+ request: options.request,
29258
+ requestId: options.requestId,
29259
+ controller: unhandledExceptionController
29260
+ }).then(() => {
29261
+ if (unhandledExceptionController[kResponsePromise].state === "pending") {
29262
+ unhandledExceptionController[kResponsePromise].resolve(void 0);
29263
+ }
29264
+ });
29265
+ const nextResult = await until(
29266
+ () => unhandledExceptionController[kResponsePromise]
29267
+ );
29268
+ if (nextResult.error) {
29269
+ return handleResponseError(nextResult.error);
29270
+ }
29271
+ if (nextResult.data) {
29272
+ return handleResponse(nextResult.data);
29273
+ }
29274
+ }
29275
+ options.onResponse(createServerErrorResponse(result.error));
29276
+ return true;
29277
+ }
29278
+ if (result.data) {
29279
+ return handleResponse(result.data);
29280
+ }
29281
+ return false;
29282
+ }
29050
29283
 
29051
- // node_modules/.pnpm/@mswjs+interceptors@0.29.0/node_modules/@mswjs/interceptors/lib/browser/chunk-MAEPOYB6.mjs
29284
+ // node_modules/.pnpm/@mswjs+interceptors@0.35.0/node_modules/@mswjs/interceptors/lib/browser/chunk-DZCGGRSJ.mjs
29052
29285
  function canParseUrl(url) {
29053
29286
  try {
29054
29287
  new URL(url);
@@ -29057,6 +29290,72 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29057
29290
  return false;
29058
29291
  }
29059
29292
  }
29293
+ function createNetworkError(cause) {
29294
+ return Object.assign(new TypeError("Failed to fetch"), {
29295
+ cause
29296
+ });
29297
+ }
29298
+ var REQUEST_BODY_HEADERS = [
29299
+ "content-encoding",
29300
+ "content-language",
29301
+ "content-location",
29302
+ "content-type",
29303
+ "content-length"
29304
+ ];
29305
+ var kRedirectCount = Symbol("kRedirectCount");
29306
+ async function followFetchRedirect(request, response) {
29307
+ if (response.status !== 303 && request.body != null) {
29308
+ return Promise.reject(createNetworkError());
29309
+ }
29310
+ const requestUrl = new URL(request.url);
29311
+ let locationUrl;
29312
+ try {
29313
+ locationUrl = new URL(response.headers.get("location"));
29314
+ } catch (error3) {
29315
+ return Promise.reject(createNetworkError(error3));
29316
+ }
29317
+ if (!(locationUrl.protocol === "http:" || locationUrl.protocol === "https:")) {
29318
+ return Promise.reject(
29319
+ createNetworkError("URL scheme must be a HTTP(S) scheme")
29320
+ );
29321
+ }
29322
+ if (Reflect.get(request, kRedirectCount) > 20) {
29323
+ return Promise.reject(createNetworkError("redirect count exceeded"));
29324
+ }
29325
+ Object.defineProperty(request, kRedirectCount, {
29326
+ value: (Reflect.get(request, kRedirectCount) || 0) + 1
29327
+ });
29328
+ if (request.mode === "cors" && (locationUrl.username || locationUrl.password) && !sameOrigin(requestUrl, locationUrl)) {
29329
+ return Promise.reject(
29330
+ createNetworkError('cross origin not allowed for request mode "cors"')
29331
+ );
29332
+ }
29333
+ const requestInit = {};
29334
+ if ([301, 302].includes(response.status) && request.method === "POST" || response.status === 303 && !["HEAD", "GET"].includes(request.method)) {
29335
+ requestInit.method = "GET";
29336
+ requestInit.body = null;
29337
+ REQUEST_BODY_HEADERS.forEach((headerName) => {
29338
+ request.headers.delete(headerName);
29339
+ });
29340
+ }
29341
+ if (!sameOrigin(requestUrl, locationUrl)) {
29342
+ request.headers.delete("authorization");
29343
+ request.headers.delete("proxy-authorization");
29344
+ request.headers.delete("cookie");
29345
+ request.headers.delete("host");
29346
+ }
29347
+ requestInit.headers = request.headers;
29348
+ return fetch(new Request(locationUrl, requestInit));
29349
+ }
29350
+ function sameOrigin(left, right) {
29351
+ if (left.origin === right.origin && left.origin === "null") {
29352
+ return true;
29353
+ }
29354
+ if (left.protocol === right.protocol && left.hostname === right.hostname && left.port === right.port) {
29355
+ return true;
29356
+ }
29357
+ return false;
29358
+ }
29060
29359
  var _FetchInterceptor = class extends Interceptor {
29061
29360
  constructor() {
29062
29361
  super(_FetchInterceptor.symbol);
@@ -29066,136 +29365,84 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29066
29365
  }
29067
29366
  async setup() {
29068
29367
  const pureFetch = globalThis.fetch;
29069
- invariant(
29368
+ invariant2(
29070
29369
  !pureFetch[IS_PATCHED_MODULE],
29071
29370
  'Failed to patch the "fetch" module: already patched.'
29072
29371
  );
29073
29372
  globalThis.fetch = async (input, init) => {
29074
- var _a2;
29075
29373
  const requestId = createRequestId();
29076
29374
  const resolvedInput = typeof input === "string" && typeof location !== "undefined" && !canParseUrl(input) ? new URL(input, location.origin) : input;
29077
29375
  const request = new Request(resolvedInput, init);
29376
+ const responsePromise = new DeferredPromise();
29377
+ const controller = new RequestController(request);
29078
29378
  this.logger.info("[%s] %s", request.method, request.url);
29079
- const { interactiveRequest, requestController } = toInteractiveRequest(request);
29379
+ this.logger.info("awaiting for the mocked response...");
29080
29380
  this.logger.info(
29081
- 'emitting the "request" event for %d listener(s)...',
29381
+ 'emitting the "request" event for %s listener(s)...',
29082
29382
  this.emitter.listenerCount("request")
29083
29383
  );
29084
- this.emitter.once("request", ({ requestId: pendingRequestId }) => {
29085
- if (pendingRequestId !== requestId) {
29086
- return;
29087
- }
29088
- if (requestController.responsePromise.state === "pending") {
29089
- requestController.responsePromise.resolve(void 0);
29090
- }
29091
- });
29092
- this.logger.info("awaiting for the mocked response...");
29093
- const signal = interactiveRequest.signal;
29094
- const requestAborted = new DeferredPromise();
29095
- if (signal) {
29096
- signal.addEventListener(
29097
- "abort",
29098
- () => {
29099
- requestAborted.reject(signal.reason);
29100
- },
29101
- { once: true }
29102
- );
29103
- }
29104
- const responsePromise = new DeferredPromise();
29105
- const respondWith = (response) => {
29106
- this.logger.info("responding with a mock response:", response);
29107
- if (this.emitter.listenerCount("response") > 0) {
29108
- this.logger.info('emitting the "response" event...');
29109
- const responseClone = response.clone();
29110
- this.emitter.emit("response", {
29111
- response: responseClone,
29112
- isMockedResponse: true,
29113
- request: interactiveRequest,
29114
- requestId
29115
- });
29116
- }
29117
- Object.defineProperty(response, "url", {
29118
- writable: false,
29119
- enumerable: true,
29120
- configurable: false,
29121
- value: request.url
29122
- });
29123
- responsePromise.resolve(response);
29124
- };
29125
- const errorWith = (reason) => {
29126
- responsePromise.reject(reason);
29127
- };
29128
- const resolverResult = await until(
29129
- async () => {
29130
- const listenersFinished = emitAsync(this.emitter, "request", {
29131
- request: interactiveRequest,
29132
- requestId
29384
+ const isRequestHandled = await handleRequest2({
29385
+ request,
29386
+ requestId,
29387
+ emitter: this.emitter,
29388
+ controller,
29389
+ onResponse: async (response) => {
29390
+ this.logger.info("received mocked response!", {
29391
+ response
29133
29392
  });
29134
- await Promise.race([
29135
- requestAborted,
29136
- // Put the listeners invocation Promise in the same race condition
29137
- // with the request abort Promise because otherwise awaiting the listeners
29138
- // would always yield some response (or undefined).
29139
- listenersFinished,
29140
- requestController.responsePromise
29141
- ]);
29142
- this.logger.info("all request listeners have been resolved!");
29143
- const mockedResponse2 = await requestController.responsePromise;
29144
- this.logger.info("event.respondWith called with:", mockedResponse2);
29145
- return mockedResponse2;
29146
- }
29147
- );
29148
- if (requestAborted.state === "rejected") {
29149
- this.logger.info(
29150
- "request has been aborted:",
29151
- requestAborted.rejectionReason
29152
- );
29153
- responsePromise.reject(requestAborted.rejectionReason);
29154
- return responsePromise;
29155
- }
29156
- if (resolverResult.error) {
29157
- this.logger.info(
29158
- "request listerner threw an error:",
29159
- resolverResult.error
29160
- );
29161
- if (resolverResult.error instanceof Response) {
29162
- if (isResponseError(resolverResult.error)) {
29163
- errorWith(createNetworkError(resolverResult.error));
29164
- } else {
29165
- respondWith(resolverResult.error);
29166
- }
29167
- }
29168
- if (this.emitter.listenerCount("unhandledException") > 0) {
29169
- await emitAsync(this.emitter, "unhandledException", {
29170
- error: resolverResult.error,
29171
- request,
29172
- requestId,
29173
- controller: {
29174
- respondWith,
29175
- errorWith
29393
+ if (RESPONSE_STATUS_CODES_WITH_REDIRECT.has(response.status)) {
29394
+ if (request.redirect === "error") {
29395
+ responsePromise.reject(createNetworkError("unexpected redirect"));
29396
+ return;
29397
+ }
29398
+ if (request.redirect === "follow") {
29399
+ followFetchRedirect(request, response).then(
29400
+ (response2) => {
29401
+ responsePromise.resolve(response2);
29402
+ },
29403
+ (reason) => {
29404
+ responsePromise.reject(reason);
29405
+ }
29406
+ );
29407
+ return;
29176
29408
  }
29177
- });
29178
- if (responsePromise.state !== "pending") {
29179
- return responsePromise;
29180
29409
  }
29410
+ if (this.emitter.listenerCount("response") > 0) {
29411
+ this.logger.info('emitting the "response" event...');
29412
+ await emitAsync(this.emitter, "response", {
29413
+ // Clone the mocked response for the "response" event listener.
29414
+ // This way, the listener can read the response and not lock its body
29415
+ // for the actual fetch consumer.
29416
+ response: response.clone(),
29417
+ isMockedResponse: true,
29418
+ request,
29419
+ requestId
29420
+ });
29421
+ }
29422
+ Object.defineProperty(response, "url", {
29423
+ writable: false,
29424
+ enumerable: true,
29425
+ configurable: false,
29426
+ value: request.url
29427
+ });
29428
+ responsePromise.resolve(response);
29429
+ },
29430
+ onRequestError: (response) => {
29431
+ this.logger.info("request has errored!", { response });
29432
+ responsePromise.reject(createNetworkError(response));
29433
+ },
29434
+ onError: (error3) => {
29435
+ this.logger.info("request has been aborted!", { error: error3 });
29436
+ responsePromise.reject(error3);
29181
29437
  }
29182
- respondWith(createServerErrorResponse(resolverResult.error));
29183
- return responsePromise;
29184
- }
29185
- const mockedResponse = resolverResult.data;
29186
- if (mockedResponse && !((_a2 = request.signal) == null ? void 0 : _a2.aborted)) {
29187
- this.logger.info("received mocked response:", mockedResponse);
29188
- if (isResponseError(mockedResponse)) {
29189
- this.logger.info(
29190
- "received a network error response, rejecting the request promise..."
29191
- );
29192
- errorWith(createNetworkError(mockedResponse));
29193
- } else {
29194
- respondWith(mockedResponse);
29195
- }
29438
+ });
29439
+ if (isRequestHandled) {
29440
+ this.logger.info("request has been handled, returning mock promise...");
29196
29441
  return responsePromise;
29197
29442
  }
29198
- this.logger.info("no mocked response received!");
29443
+ this.logger.info(
29444
+ "no mocked response received, performing request as-is..."
29445
+ );
29199
29446
  return pureFetch(request).then((response) => {
29200
29447
  this.logger.info("original fetch performed", response);
29201
29448
  if (this.emitter.listenerCount("response") > 0) {
@@ -29204,7 +29451,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29204
29451
  this.emitter.emit("response", {
29205
29452
  response: responseClone,
29206
29453
  isMockedResponse: false,
29207
- request: interactiveRequest,
29454
+ request,
29208
29455
  requestId
29209
29456
  });
29210
29457
  }
@@ -29230,13 +29477,8 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29230
29477
  };
29231
29478
  var FetchInterceptor = _FetchInterceptor;
29232
29479
  FetchInterceptor.symbol = Symbol("fetch");
29233
- function createNetworkError(cause) {
29234
- return Object.assign(new TypeError("Failed to fetch"), {
29235
- cause
29236
- });
29237
- }
29238
29480
 
29239
- // node_modules/.pnpm/@mswjs+interceptors@0.29.0/node_modules/@mswjs/interceptors/lib/browser/chunk-732REFPX.mjs
29481
+ // node_modules/.pnpm/@mswjs+interceptors@0.35.0/node_modules/@mswjs/interceptors/lib/browser/chunk-PRBA3ES4.mjs
29240
29482
  function concatArrayBuffer(left, right) {
29241
29483
  const result = new Uint8Array(left.byteLength + right.byteLength);
29242
29484
  result.set(left, 0);
@@ -29245,10 +29487,10 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29245
29487
  }
29246
29488
  var EventPolyfill = class {
29247
29489
  constructor(type, options) {
29248
- this.AT_TARGET = 0;
29249
- this.BUBBLING_PHASE = 0;
29250
- this.CAPTURING_PHASE = 0;
29251
29490
  this.NONE = 0;
29491
+ this.CAPTURING_PHASE = 1;
29492
+ this.AT_TARGET = 2;
29493
+ this.BUBBLING_PHASE = 3;
29252
29494
  this.type = "";
29253
29495
  this.srcElement = null;
29254
29496
  this.currentTarget = null;
@@ -29421,15 +29663,26 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29421
29663
  }
29422
29664
  return headers;
29423
29665
  }
29424
- var IS_MOCKED_RESPONSE = Symbol("isMockedResponse");
29666
+ async function getBodyByteLength(input) {
29667
+ const explicitContentLength = input.headers.get("content-length");
29668
+ if (explicitContentLength != null && explicitContentLength !== "") {
29669
+ return Number(explicitContentLength);
29670
+ }
29671
+ const buffer = await input.arrayBuffer();
29672
+ return buffer.byteLength;
29673
+ }
29674
+ var kIsRequestHandled = Symbol("kIsRequestHandled");
29425
29675
  var IS_NODE2 = isNodeProcess();
29676
+ var kFetchRequest = Symbol("kFetchRequest");
29426
29677
  var XMLHttpRequestController = class {
29427
29678
  constructor(initialRequest, logger) {
29428
29679
  this.initialRequest = initialRequest;
29429
29680
  this.logger = logger;
29430
29681
  this.method = "GET";
29431
29682
  this.url = null;
29683
+ this[kIsRequestHandled] = false;
29432
29684
  this.events = /* @__PURE__ */ new Map();
29685
+ this.uploadEvents = /* @__PURE__ */ new Map();
29433
29686
  this.requestId = createRequestId();
29434
29687
  this.requestHeaders = new Headers();
29435
29688
  this.responseBuffer = new Uint8Array();
@@ -29478,9 +29731,6 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29478
29731
  }
29479
29732
  case "send": {
29480
29733
  const [body] = args;
29481
- if (body != null) {
29482
- this.requestBody = typeof body === "string" ? encodeBuffer(body) : body;
29483
- }
29484
29734
  this.request.addEventListener("load", () => {
29485
29735
  if (typeof this.onResponse !== "undefined") {
29486
29736
  const fetchResponse = createResponse(
@@ -29494,19 +29744,21 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29494
29744
  );
29495
29745
  this.onResponse.call(this, {
29496
29746
  response: fetchResponse,
29497
- isMockedResponse: IS_MOCKED_RESPONSE in this.request,
29747
+ isMockedResponse: this[kIsRequestHandled],
29498
29748
  request: fetchRequest,
29499
29749
  requestId: this.requestId
29500
29750
  });
29501
29751
  }
29502
29752
  });
29503
- const fetchRequest = this.toFetchApiRequest();
29753
+ const requestBody = typeof body === "string" ? encodeBuffer(body) : body;
29754
+ const fetchRequest = this.toFetchApiRequest(requestBody);
29755
+ this[kFetchRequest] = fetchRequest;
29504
29756
  const onceRequestSettled = ((_a2 = this.onRequest) == null ? void 0 : _a2.call(this, {
29505
29757
  request: fetchRequest,
29506
29758
  requestId: this.requestId
29507
29759
  })) || Promise.resolve();
29508
29760
  onceRequestSettled.finally(() => {
29509
- if (this.request.readyState < this.request.LOADING) {
29761
+ if (!this[kIsRequestHandled]) {
29510
29762
  this.logger.info(
29511
29763
  "request callback settled but request has not been handled (readystate %d), performing as-is...",
29512
29764
  this.request.readyState
@@ -29528,6 +29780,39 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29528
29780
  }
29529
29781
  }
29530
29782
  });
29783
+ define(
29784
+ this.request,
29785
+ "upload",
29786
+ createProxy(this.request.upload, {
29787
+ setProperty: ([propertyName, nextValue], invoke) => {
29788
+ switch (propertyName) {
29789
+ case "onloadstart":
29790
+ case "onprogress":
29791
+ case "onaboart":
29792
+ case "onerror":
29793
+ case "onload":
29794
+ case "ontimeout":
29795
+ case "onloadend": {
29796
+ const eventName = propertyName.slice(
29797
+ 2
29798
+ );
29799
+ this.registerUploadEvent(eventName, nextValue);
29800
+ }
29801
+ }
29802
+ return invoke();
29803
+ },
29804
+ methodCall: ([methodName, args], invoke) => {
29805
+ switch (methodName) {
29806
+ case "addEventListener": {
29807
+ const [eventName, listener] = args;
29808
+ this.registerUploadEvent(eventName, listener);
29809
+ this.logger.info("upload.addEventListener", eventName, listener);
29810
+ return invoke();
29811
+ }
29812
+ }
29813
+ }
29814
+ })
29815
+ );
29531
29816
  }
29532
29817
  registerEvent(eventName, listener) {
29533
29818
  const prevEvents = this.events.get(eventName) || [];
@@ -29535,17 +29820,44 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29535
29820
  this.events.set(eventName, nextEvents);
29536
29821
  this.logger.info('registered event "%s"', eventName, listener);
29537
29822
  }
29823
+ registerUploadEvent(eventName, listener) {
29824
+ const prevEvents = this.uploadEvents.get(eventName) || [];
29825
+ const nextEvents = prevEvents.concat(listener);
29826
+ this.uploadEvents.set(eventName, nextEvents);
29827
+ this.logger.info('registered upload event "%s"', eventName, listener);
29828
+ }
29538
29829
  /**
29539
29830
  * Responds to the current request with the given
29540
29831
  * Fetch API `Response` instance.
29541
29832
  */
29542
- respondWith(response) {
29833
+ async respondWith(response) {
29834
+ this[kIsRequestHandled] = true;
29835
+ if (this[kFetchRequest]) {
29836
+ const totalRequestBodyLength = await getBodyByteLength(
29837
+ this[kFetchRequest].clone()
29838
+ );
29839
+ this.trigger("loadstart", this.request.upload, {
29840
+ loaded: 0,
29841
+ total: totalRequestBodyLength
29842
+ });
29843
+ this.trigger("progress", this.request.upload, {
29844
+ loaded: totalRequestBodyLength,
29845
+ total: totalRequestBodyLength
29846
+ });
29847
+ this.trigger("load", this.request.upload, {
29848
+ loaded: totalRequestBodyLength,
29849
+ total: totalRequestBodyLength
29850
+ });
29851
+ this.trigger("loadend", this.request.upload, {
29852
+ loaded: totalRequestBodyLength,
29853
+ total: totalRequestBodyLength
29854
+ });
29855
+ }
29543
29856
  this.logger.info(
29544
29857
  "responding with a mocked response: %d %s",
29545
29858
  response.status,
29546
29859
  response.statusText
29547
29860
  );
29548
- define(this.request, IS_MOCKED_RESPONSE, true);
29549
29861
  define(this.request, "status", response.status);
29550
29862
  define(this.request, "statusText", response.statusText);
29551
29863
  define(this.request, "responseURL", this.url.href);
@@ -29600,14 +29912,9 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29600
29912
  get: () => this.responseXML
29601
29913
  }
29602
29914
  });
29603
- const totalResponseBodyLength = response.headers.has("Content-Length") ? Number(response.headers.get("Content-Length")) : (
29604
- /**
29605
- * @todo Infer the response body length from the response body.
29606
- */
29607
- void 0
29608
- );
29915
+ const totalResponseBodyLength = await getBodyByteLength(response.clone());
29609
29916
  this.logger.info("calculated response body length", totalResponseBodyLength);
29610
- this.trigger("loadstart", {
29917
+ this.trigger("loadstart", this.request, {
29611
29918
  loaded: 0,
29612
29919
  total: totalResponseBodyLength
29613
29920
  });
@@ -29616,11 +29923,11 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29616
29923
  const finalizeResponse = () => {
29617
29924
  this.logger.info("finalizing the mocked response...");
29618
29925
  this.setReadyState(this.request.DONE);
29619
- this.trigger("load", {
29926
+ this.trigger("load", this.request, {
29620
29927
  loaded: this.responseBuffer.byteLength,
29621
29928
  total: totalResponseBodyLength
29622
29929
  });
29623
- this.trigger("loadend", {
29930
+ this.trigger("loadend", this.request, {
29624
29931
  loaded: this.responseBuffer.byteLength,
29625
29932
  total: totalResponseBodyLength
29626
29933
  });
@@ -29638,7 +29945,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29638
29945
  if (value) {
29639
29946
  this.logger.info("read response body chunk:", value);
29640
29947
  this.responseBuffer = concatArrayBuffer(this.responseBuffer, value);
29641
- this.trigger("progress", {
29948
+ this.trigger("progress", this.request, {
29642
29949
  loaded: this.responseBuffer.byteLength,
29643
29950
  total: totalResponseBodyLength
29644
29951
  });
@@ -29696,7 +30003,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29696
30003
  }
29697
30004
  }
29698
30005
  get responseText() {
29699
- invariant(
30006
+ invariant2(
29700
30007
  this.request.responseType === "" || this.request.responseType === "text",
29701
30008
  "InvalidStateError: The object is in invalid state."
29702
30009
  );
@@ -29708,7 +30015,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29708
30015
  return responseText;
29709
30016
  }
29710
30017
  get responseXML() {
29711
- invariant(
30018
+ invariant2(
29712
30019
  this.request.responseType === "" || this.request.responseType === "document",
29713
30020
  "InvalidStateError: The object is in invalid state."
29714
30021
  );
@@ -29731,10 +30038,11 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29731
30038
  return null;
29732
30039
  }
29733
30040
  errorWith(error3) {
30041
+ this[kIsRequestHandled] = true;
29734
30042
  this.logger.info("responding with an error");
29735
30043
  this.setReadyState(this.request.DONE);
29736
- this.trigger("error");
29737
- this.trigger("loadend");
30044
+ this.trigger("error", this.request);
30045
+ this.trigger("loadend", this.request);
29738
30046
  }
29739
30047
  /**
29740
30048
  * Transitions this request's `readyState` to the given one.
@@ -29753,36 +30061,38 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29753
30061
  this.logger.info("set readyState to: %d", nextReadyState);
29754
30062
  if (nextReadyState !== this.request.UNSENT) {
29755
30063
  this.logger.info('triggerring "readystatechange" event...');
29756
- this.trigger("readystatechange");
30064
+ this.trigger("readystatechange", this.request);
29757
30065
  }
29758
30066
  }
29759
30067
  /**
29760
30068
  * Triggers given event on the `XMLHttpRequest` instance.
29761
30069
  */
29762
- trigger(eventName, options) {
29763
- const callback = this.request[`on${eventName}`];
29764
- const event = createEvent(this.request, eventName, options);
30070
+ trigger(eventName, target, options) {
30071
+ const callback = target[`on${eventName}`];
30072
+ const event = createEvent(target, eventName, options);
29765
30073
  this.logger.info('trigger "%s"', eventName, options || "");
29766
30074
  if (typeof callback === "function") {
29767
30075
  this.logger.info('found a direct "%s" callback, calling...', eventName);
29768
- callback.call(this.request, event);
30076
+ callback.call(target, event);
29769
30077
  }
29770
- for (const [registeredEventName, listeners] of this.events) {
30078
+ const events = target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events;
30079
+ for (const [registeredEventName, listeners] of events) {
29771
30080
  if (registeredEventName === eventName) {
29772
30081
  this.logger.info(
29773
30082
  'found %d listener(s) for "%s" event, calling...',
29774
30083
  listeners.length,
29775
30084
  eventName
29776
30085
  );
29777
- listeners.forEach((listener) => listener.call(this.request, event));
30086
+ listeners.forEach((listener) => listener.call(target, event));
29778
30087
  }
29779
30088
  }
29780
30089
  }
29781
30090
  /**
29782
30091
  * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.
29783
30092
  */
29784
- toFetchApiRequest() {
30093
+ toFetchApiRequest(body) {
29785
30094
  this.logger.info("converting request to a Fetch API Request...");
30095
+ const resolvedBody = body instanceof Document ? body.documentElement.innerText : body;
29786
30096
  const fetchRequest = new Request(this.url.href, {
29787
30097
  method: this.method,
29788
30098
  headers: this.requestHeaders,
@@ -29790,7 +30100,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29790
30100
  * @see https://xhr.spec.whatwg.org/#cross-origin-credentials
29791
30101
  */
29792
30102
  credentials: this.request.withCredentials ? "include" : "same-origin",
29793
- body: ["GET", "HEAD"].includes(this.method) ? null : this.requestBody
30103
+ body: ["GET", "HEAD"].includes(this.method.toUpperCase()) ? null : resolvedBody
29794
30104
  });
29795
30105
  const proxyHeaders = createProxy(fetchRequest.headers, {
29796
30106
  methodCall: ([methodName, args], invoke) => {
@@ -29858,81 +30168,35 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29858
30168
  logger
29859
30169
  );
29860
30170
  xhrRequestController.onRequest = async function({ request, requestId }) {
29861
- const { interactiveRequest, requestController } = toInteractiveRequest(request);
30171
+ const controller = new RequestController(request);
29862
30172
  this.logger.info("awaiting mocked response...");
29863
- emitter.once("request", ({ requestId: pendingRequestId }) => {
29864
- if (pendingRequestId !== requestId) {
29865
- return;
29866
- }
29867
- if (requestController.responsePromise.state === "pending") {
29868
- requestController.respondWith(void 0);
29869
- }
29870
- });
29871
- const resolverResult = await until(async () => {
29872
- this.logger.info(
29873
- 'emitting the "request" event for %s listener(s)...',
29874
- emitter.listenerCount("request")
29875
- );
29876
- await emitAsync(emitter, "request", {
29877
- request: interactiveRequest,
29878
- requestId
29879
- });
29880
- this.logger.info('all "request" listeners settled!');
29881
- const mockedResponse2 = await requestController.responsePromise;
29882
- this.logger.info("event.respondWith called with:", mockedResponse2);
29883
- return mockedResponse2;
29884
- });
29885
- if (resolverResult.error) {
29886
- this.logger.info(
29887
- "request listener threw an exception, aborting request...",
29888
- resolverResult.error
29889
- );
29890
- if (resolverResult.error instanceof Response) {
29891
- if (isResponseError(resolverResult.error)) {
29892
- xhrRequestController.errorWith(new TypeError("Network error"));
29893
- } else {
29894
- this.respondWith(resolverResult.error);
29895
- }
29896
- return;
29897
- }
29898
- if (emitter.listenerCount("unhandledException") > 0) {
29899
- await emitAsync(emitter, "unhandledException", {
29900
- error: resolverResult.error,
29901
- request,
29902
- requestId,
29903
- controller: {
29904
- respondWith: xhrRequestController.respondWith.bind(xhrRequestController),
29905
- errorWith: xhrRequestController.errorWith.bind(xhrRequestController)
29906
- }
29907
- });
29908
- if (originalRequest.readyState > XMLHttpRequest.OPENED) {
29909
- return;
30173
+ this.logger.info(
30174
+ 'emitting the "request" event for %s listener(s)...',
30175
+ emitter.listenerCount("request")
30176
+ );
30177
+ const isRequestHandled = await handleRequest2({
30178
+ request,
30179
+ requestId,
30180
+ controller,
30181
+ emitter,
30182
+ onResponse: async (response) => {
30183
+ await this.respondWith(response);
30184
+ },
30185
+ onRequestError: () => {
30186
+ this.errorWith(new TypeError("Network error"));
30187
+ },
30188
+ onError: (error3) => {
30189
+ this.logger.info("request errored!", { error: error3 });
30190
+ if (error3 instanceof Error) {
30191
+ this.errorWith(error3);
29910
30192
  }
29911
30193
  }
29912
- xhrRequestController.respondWith(
29913
- createServerErrorResponse(resolverResult.error)
29914
- );
29915
- return;
29916
- }
29917
- const mockedResponse = resolverResult.data;
29918
- if (typeof mockedResponse !== "undefined") {
30194
+ });
30195
+ if (!isRequestHandled) {
29919
30196
  this.logger.info(
29920
- "received mocked response: %d %s",
29921
- mockedResponse.status,
29922
- mockedResponse.statusText
30197
+ "no mocked response received, performing request as-is..."
29923
30198
  );
29924
- if (isResponseError(mockedResponse)) {
29925
- this.logger.info(
29926
- "received a network error response, rejecting the request promise..."
29927
- );
29928
- xhrRequestController.errorWith(new TypeError("Network error"));
29929
- return;
29930
- }
29931
- return xhrRequestController.respondWith(mockedResponse);
29932
30199
  }
29933
- this.logger.info(
29934
- "no mocked response received, performing request as-is..."
29935
- );
29936
30200
  };
29937
30201
  xhrRequestController.onResponse = async function({
29938
30202
  response,
@@ -29967,7 +30231,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
29967
30231
  const logger = this.logger.extend("setup");
29968
30232
  logger.info('patching "XMLHttpRequest" module...');
29969
30233
  const PureXMLHttpRequest = globalThis.XMLHttpRequest;
29970
- invariant(
30234
+ invariant2(
29971
30235
  !PureXMLHttpRequest[IS_PATCHED_MODULE],
29972
30236
  'Failed to patch the "XMLHttpRequest" module: already patched.'
29973
30237
  );
@@ -30005,7 +30269,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
30005
30269
  name: "fallback",
30006
30270
  interceptors: [new FetchInterceptor(), new XMLHttpRequestInterceptor()]
30007
30271
  });
30008
- interceptor.on("request", async ({ request, requestId }) => {
30272
+ interceptor.on("request", async ({ request, requestId, controller }) => {
30009
30273
  const requestCloneForLogs = request.clone();
30010
30274
  const response = await handleRequest(
30011
30275
  request,
@@ -30028,7 +30292,7 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
30028
30292
  }
30029
30293
  );
30030
30294
  if (response) {
30031
- request.respondWith(response);
30295
+ controller.respondWith(response);
30032
30296
  }
30033
30297
  });
30034
30298
  interceptor.on(