msw 0.33.1 → 0.35.0

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.
@@ -2,13 +2,13 @@
2
2
  /* tslint:disable */
3
3
 
4
4
  /**
5
- * Mock Service Worker (0.33.1).
5
+ * Mock Service Worker (0.35.0).
6
6
  * @see https://github.com/mswjs/msw
7
7
  * - Please do NOT modify this file.
8
8
  * - Please do NOT serve this file on production.
9
9
  */
10
10
 
11
- const INTEGRITY_CHECKSUM = 'a615cd395ea10f948a628bce3857a385'
11
+ const INTEGRITY_CHECKSUM = 'f0a916b13c8acc2b526a03a6d26df85f'
12
12
  const bypassHeaderName = 'x-msw-bypass'
13
13
  const activeClientIds = new Set()
14
14
 
@@ -221,13 +221,11 @@ async function getResponse(event, client, requestId) {
221
221
 
222
222
  console.error(
223
223
  `\
224
- [MSW] Request handler function for "%s %s" has thrown the following exception:
224
+ [MSW] Uncaught exception in the request handler for "%s %s":
225
225
 
226
- ${parsedBody.errorType}: ${parsedBody.message}
227
- (see more detailed error stack trace in the mocked response body)
226
+ ${parsedBody.location}
228
227
 
229
- This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error.
230
- If you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses\
228
+ 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\
231
229
  `,
232
230
  request.method,
233
231
  request.url,
@@ -271,11 +269,22 @@ self.addEventListener('fetch', function (event) {
271
269
 
272
270
  return event.respondWith(
273
271
  handleRequest(event, requestId).catch((error) => {
272
+ if (error.name === 'NetworkError') {
273
+ console.warn(
274
+ '[MSW] Successfully emulated a network error for the "%s %s" request.',
275
+ request.method,
276
+ request.url,
277
+ )
278
+ return
279
+ }
280
+
281
+ // At this point, any exception indicates an issue with the original request/response.
274
282
  console.error(
275
- '[MSW] Failed to mock a "%s" request to "%s": %s',
283
+ `\
284
+ [MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
276
285
  request.method,
277
286
  request.url,
278
- error,
287
+ `${error.name}: ${error.message}`,
279
288
  )
280
289
  }),
281
290
  )
@@ -1511,6 +1511,65 @@ var lib = {};
1511
1511
 
1512
1512
  var invariant$2 = {};
1513
1513
 
1514
+ var format$1 = {};
1515
+
1516
+ Object.defineProperty(format$1, "__esModule", { value: true });
1517
+ format$1.format = void 0;
1518
+ var POSITIONALS_EXP = /(%?)(%([sdjo]))/g;
1519
+ function serializePositional(positional, flag) {
1520
+ switch (flag) {
1521
+ // Strings.
1522
+ case 's':
1523
+ return positional;
1524
+ // Digits.
1525
+ case 'd':
1526
+ case 'i':
1527
+ return Number(positional);
1528
+ // JSON.
1529
+ case 'j':
1530
+ return JSON.stringify(positional);
1531
+ // Objects.
1532
+ case 'o': {
1533
+ // Preserve stings to prevent extra quotes around them.
1534
+ if (typeof positional === 'string') {
1535
+ return positional;
1536
+ }
1537
+ var json = JSON.stringify(positional);
1538
+ // If the positional isn't serializable, return it as-is.
1539
+ if (json === '{}' || json === '[]' || /^\[object .+?\]$/.test(json)) {
1540
+ return positional;
1541
+ }
1542
+ return json;
1543
+ }
1544
+ }
1545
+ }
1546
+ function format(message) {
1547
+ var positionals = [];
1548
+ for (var _i = 1; _i < arguments.length; _i++) {
1549
+ positionals[_i - 1] = arguments[_i];
1550
+ }
1551
+ if (positionals.length === 0) {
1552
+ return message;
1553
+ }
1554
+ var positionalIndex = 0;
1555
+ var formattedMessage = message.replace(POSITIONALS_EXP, function (match, isEscaped, _, flag) {
1556
+ var positional = positionals[positionalIndex];
1557
+ var value = serializePositional(positional, flag);
1558
+ if (!isEscaped) {
1559
+ positionalIndex++;
1560
+ return value;
1561
+ }
1562
+ return match;
1563
+ });
1564
+ // Append unresolved positionals to string as-is.
1565
+ if (positionalIndex < positionals.length) {
1566
+ formattedMessage += " " + positionals.slice(positionalIndex).join(' ');
1567
+ }
1568
+ formattedMessage = formattedMessage.replace(/%{2,2}/g, '%');
1569
+ return formattedMessage;
1570
+ }
1571
+ format$1.format = format;
1572
+
1514
1573
  var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
1515
1574
  var extendStatics = function (d, b) {
1516
1575
  extendStatics = Object.setPrototypeOf ||
@@ -1532,21 +1591,9 @@ var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function
1532
1591
  return to;
1533
1592
  };
1534
1593
  Object.defineProperty(invariant$2, "__esModule", { value: true });
1535
- invariant$2.invariant = invariant$2.InvariantError = invariant$2.interpolate = void 0;
1594
+ invariant$2.invariant = invariant$2.InvariantError = void 0;
1595
+ var format_1 = format$1;
1536
1596
  var STACK_FRAMES_TO_IGNORE = 2;
1537
- function interpolate(message) {
1538
- var positionals = [];
1539
- for (var _i = 1; _i < arguments.length; _i++) {
1540
- positionals[_i - 1] = arguments[_i];
1541
- }
1542
- var index = 0;
1543
- return message.replace(/%[s|d|o]/g, function (match) {
1544
- var _a;
1545
- var value = (_a = positionals[index++]) !== null && _a !== void 0 ? _a : match;
1546
- return typeof value === 'object' ? JSON.stringify(value) : value;
1547
- });
1548
- }
1549
- invariant$2.interpolate = interpolate;
1550
1597
  var InvariantError = /** @class */ (function (_super) {
1551
1598
  __extends(InvariantError, _super);
1552
1599
  function InvariantError(message) {
@@ -1556,7 +1603,7 @@ var InvariantError = /** @class */ (function (_super) {
1556
1603
  }
1557
1604
  var _this = _super.call(this, message) || this;
1558
1605
  _this.name = 'Invariant Violation';
1559
- _this.message = interpolate.apply(void 0, __spreadArray([message], positionals));
1606
+ _this.message = format_1.format.apply(void 0, __spreadArray([message], positionals));
1560
1607
  if (_this.stack) {
1561
1608
  var prevStack = _this.stack;
1562
1609
  _this.stack = prevStack
@@ -1593,6 +1640,7 @@ var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m
1593
1640
  };
1594
1641
  Object.defineProperty(exports, "__esModule", { value: true });
1595
1642
  __exportStar(invariant$2, exports);
1643
+ __exportStar(format$1, exports);
1596
1644
  }(lib));
1597
1645
 
1598
1646
  const LIBRARY_PREFIX = '[MSW]';
@@ -1600,7 +1648,7 @@ const LIBRARY_PREFIX = '[MSW]';
1600
1648
  * Formats a given message by appending the library's prefix string.
1601
1649
  */
1602
1650
  function formatMessage(message, ...positionals) {
1603
- const interpolatedMessage = lib.interpolate(message, ...positionals);
1651
+ const interpolatedMessage = lib.format(message, ...positionals);
1604
1652
  return `${LIBRARY_PREFIX} ${interpolatedMessage}`;
1605
1653
  }
1606
1654
  /**
@@ -4861,17 +4909,20 @@ const getPublicUrlFromRequest = (request) => {
4861
4909
  : new URL(request.url.pathname, `${request.url.protocol}//${request.url.host}`).href;
4862
4910
  };
4863
4911
 
4864
- function parseQuery(query) {
4912
+ function parseDocumentNode(node) {
4865
4913
  var _a;
4914
+ const operationDef = node.definitions.find((def) => {
4915
+ return def.kind === 'OperationDefinition';
4916
+ });
4917
+ return {
4918
+ operationType: operationDef === null || operationDef === void 0 ? void 0 : operationDef.operation,
4919
+ operationName: (_a = operationDef === null || operationDef === void 0 ? void 0 : operationDef.name) === null || _a === void 0 ? void 0 : _a.value,
4920
+ };
4921
+ }
4922
+ function parseQuery(query) {
4866
4923
  try {
4867
4924
  const ast = parse(query);
4868
- const operationDef = ast.definitions.find((def) => {
4869
- return def.kind === 'OperationDefinition';
4870
- });
4871
- return {
4872
- operationType: operationDef === null || operationDef === void 0 ? void 0 : operationDef.operation,
4873
- operationName: (_a = operationDef === null || operationDef === void 0 ? void 0 : operationDef.name) === null || _a === void 0 ? void 0 : _a.value,
4874
- };
4925
+ return parseDocumentNode(ast);
4875
4926
  }
4876
4927
  catch (error) {
4877
4928
  return error;
@@ -4951,7 +5002,7 @@ function parseGraphQLRequest(request) {
4951
5002
  const parsedResult = parseQuery(query);
4952
5003
  if (parsedResult instanceof Error) {
4953
5004
  const requestPublicUrl = getPublicUrlFromRequest(request);
4954
- throw new Error(devUtils.formatMessage('Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%o', request.method, requestPublicUrl, parsedResult.message));
5005
+ throw new Error(devUtils.formatMessage('Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%s', request.method, requestPublicUrl, parsedResult.message));
4955
5006
  }
4956
5007
  return {
4957
5008
  operationType: parsedResult.operationType,
@@ -5295,17 +5346,23 @@ const xml = (body) => {
5295
5346
  };
5296
5347
  };
5297
5348
 
5349
+ var StatusCodeColor;
5350
+ (function (StatusCodeColor) {
5351
+ StatusCodeColor["Success"] = "#69AB32";
5352
+ StatusCodeColor["Warning"] = "#F0BB4B";
5353
+ StatusCodeColor["Danger"] = "#E95F5D";
5354
+ })(StatusCodeColor || (StatusCodeColor = {}));
5298
5355
  /**
5299
5356
  * Returns a HEX color for a given response status code number.
5300
5357
  */
5301
5358
  function getStatusCodeColor(status) {
5302
5359
  if (status < 300) {
5303
- return '#69AB32';
5360
+ return StatusCodeColor.Success;
5304
5361
  }
5305
5362
  if (status < 400) {
5306
- return '#F0BB4B';
5363
+ return StatusCodeColor.Warning;
5307
5364
  }
5308
- return '#E95F5D';
5365
+ return StatusCodeColor.Danger;
5309
5366
  }
5310
5367
 
5311
5368
  /**
@@ -5411,7 +5468,10 @@ function getAbsoluteUrl(path, baseUrl) {
5411
5468
  // Resolve a relative request URL against a given custom "baseUrl"
5412
5469
  // or the current location (in the case of browser/browser-like environments).
5413
5470
  const origin = baseUrl || (typeof location !== 'undefined' && location.origin);
5414
- return origin ? new URL(path, origin).href : path;
5471
+ return origin
5472
+ ? // Encode and decode the path to preserve escaped characters.
5473
+ decodeURI(new URL(encodeURI(path), origin).href)
5474
+ : path;
5415
5475
  }
5416
5476
 
5417
5477
  /**
@@ -5691,7 +5751,8 @@ ${queryParams
5691
5751
  const publicUrl = getPublicUrlFromRequest(request);
5692
5752
  const loggedRequest = prepareRequest(request);
5693
5753
  const loggedResponse = prepareResponse(response);
5694
- console.groupCollapsed(devUtils.formatMessage('%s %s %s (%c%s%c)'), getTimestamp(), request.method, publicUrl, `color:${getStatusCodeColor(response.status)} %s`, response.status, response.statusText, 'color:inherit');
5754
+ const statusColor = getStatusCodeColor(response.status);
5755
+ console.groupCollapsed(devUtils.formatMessage('%s %s %s (%c%s%c)'), getTimestamp(), request.method, publicUrl, `color:${statusColor}`, `${response.status} ${response.statusText}`, 'color:inherit');
5695
5756
  console.log('Request', loggedRequest);
5696
5757
  console.log('Handler:', {
5697
5758
  mask: this.info.path,
@@ -5721,16 +5782,33 @@ const graphqlContext = {
5721
5782
  errors,
5722
5783
  cookie,
5723
5784
  };
5785
+ function isDocumentNode(value) {
5786
+ if (value == null) {
5787
+ return false;
5788
+ }
5789
+ return typeof value === 'object' && 'kind' in value && 'definitions' in value;
5790
+ }
5724
5791
  class GraphQLHandler extends RequestHandler {
5725
5792
  constructor(operationType, operationName, endpoint, resolver) {
5793
+ let resolvedOperationName = operationName;
5794
+ if (isDocumentNode(operationName)) {
5795
+ const parsedNode = parseDocumentNode(operationName);
5796
+ if (parsedNode.operationType !== operationType) {
5797
+ throw new Error(`Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "${operationType}", but got "${parsedNode.operationType}").`);
5798
+ }
5799
+ if (!parsedNode.operationName) {
5800
+ throw new Error(`Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`);
5801
+ }
5802
+ resolvedOperationName = parsedNode.operationName;
5803
+ }
5726
5804
  const header = operationType === 'all'
5727
5805
  ? `${operationType} (origin: ${endpoint.toString()})`
5728
- : `${operationType} ${operationName} (origin: ${endpoint.toString()})`;
5806
+ : `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`;
5729
5807
  super({
5730
5808
  info: {
5731
5809
  header,
5732
5810
  operationType,
5733
- operationName,
5811
+ operationName: resolvedOperationName,
5734
5812
  },
5735
5813
  ctx: graphqlContext,
5736
5814
  resolver,
@@ -5769,7 +5847,8 @@ Consider naming this operation or using "graphql.operation" request handler to i
5769
5847
  log(request, response, handler, parsedRequest) {
5770
5848
  const loggedRequest = prepareRequest(request);
5771
5849
  const loggedResponse = prepareResponse(response);
5772
- console.groupCollapsed(devUtils.formatMessage('%s %s (%c%s%c)'), getTimestamp(), `${parsedRequest === null || parsedRequest === void 0 ? void 0 : parsedRequest.operationType} ${parsedRequest === null || parsedRequest === void 0 ? void 0 : parsedRequest.operationName}`, `color:${getStatusCodeColor(response.status)} %s`, response.status, response.statusText, 'color:inherit');
5850
+ const statusColor = getStatusCodeColor(response.status);
5851
+ console.groupCollapsed(devUtils.formatMessage('%s %s (%c%s%c)'), getTimestamp(), `${parsedRequest === null || parsedRequest === void 0 ? void 0 : parsedRequest.operationType} ${parsedRequest === null || parsedRequest === void 0 ? void 0 : parsedRequest.operationName}`, `color:${statusColor}`, `${response.status} ${response.statusText}`, 'color:inherit');
5773
5852
  console.log('Request:', loggedRequest);
5774
5853
  console.log('Handler:', this);
5775
5854
  console.log('Response:', loggedResponse);
@@ -5883,8 +5962,10 @@ Read more: https://mswjs.io/docs/getting-started/mocks\
5883
5962
  const message = messageTemplate.join('\n\n');
5884
5963
  switch (strategy) {
5885
5964
  case 'error': {
5965
+ // Print a developer-friendly error.
5886
5966
  devUtils.error('Error: %s', message);
5887
- break;
5967
+ // Throw an exception to halt request processing and not perform the original request.
5968
+ throw new Error('Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.');
5888
5969
  }
5889
5970
  case 'warn': {
5890
5971
  devUtils.warn('Warning: %s', message);
@@ -5951,6 +6032,23 @@ function handleRequest(request, handlers, options, emitter, handleRequestOptions
5951
6032
  });
5952
6033
  }
5953
6034
 
6035
+ /**
6036
+ * Pipes all emitted events from one emitter to another.
6037
+ */
6038
+ function pipeEvents(source, destination) {
6039
+ const rawEmit = source.emit;
6040
+ // @ts-ignore
6041
+ if (rawEmit._isPiped) {
6042
+ return;
6043
+ }
6044
+ source.emit = function (event, ...data) {
6045
+ destination.emit(event, ...data);
6046
+ return rawEmit.call(this, event, ...data);
6047
+ };
6048
+ // @ts-ignore
6049
+ source.emit._isPiped = true;
6050
+ }
6051
+
5954
6052
  const DEFAULT_LISTEN_OPTIONS = {
5955
6053
  onUnhandledRequest: 'warn',
5956
6054
  };
@@ -5960,6 +6058,8 @@ const DEFAULT_LISTEN_OPTIONS = {
5960
6058
  */
5961
6059
  function createSetupServer(...interceptors$1) {
5962
6060
  const emitter = new lib$3.StrictEventEmitter();
6061
+ const publicEmitter = new lib$3.StrictEventEmitter();
6062
+ pipeEvents(emitter, publicEmitter);
5963
6063
  return function setupServer(...requestHandlers) {
5964
6064
  requestHandlers.forEach((handler) => {
5965
6065
  if (Array.isArray(handler))
@@ -6029,11 +6129,20 @@ ${chalk.bold(`${pragma} ${header}`)}
6029
6129
  `);
6030
6130
  });
6031
6131
  },
6032
- on(eventType, listener) {
6033
- emitter.addListener(eventType, listener);
6132
+ events: {
6133
+ on(...args) {
6134
+ return publicEmitter.on(...args);
6135
+ },
6136
+ removeListener(...args) {
6137
+ return publicEmitter.removeListener(...args);
6138
+ },
6139
+ removeAllListeners(...args) {
6140
+ return publicEmitter.removeAllListeners(...args);
6141
+ },
6034
6142
  },
6035
6143
  close() {
6036
6144
  emitter.removeAllListeners();
6145
+ publicEmitter.removeAllListeners();
6037
6146
  interceptor.restore();
6038
6147
  },
6039
6148
  };
package/node/lib/index.js CHANGED
@@ -3397,6 +3397,65 @@ var lib = {};
3397
3397
 
3398
3398
  var invariant$2 = {};
3399
3399
 
3400
+ var format$1 = {};
3401
+
3402
+ Object.defineProperty(format$1, "__esModule", { value: true });
3403
+ format$1.format = void 0;
3404
+ var POSITIONALS_EXP = /(%?)(%([sdjo]))/g;
3405
+ function serializePositional(positional, flag) {
3406
+ switch (flag) {
3407
+ // Strings.
3408
+ case 's':
3409
+ return positional;
3410
+ // Digits.
3411
+ case 'd':
3412
+ case 'i':
3413
+ return Number(positional);
3414
+ // JSON.
3415
+ case 'j':
3416
+ return JSON.stringify(positional);
3417
+ // Objects.
3418
+ case 'o': {
3419
+ // Preserve stings to prevent extra quotes around them.
3420
+ if (typeof positional === 'string') {
3421
+ return positional;
3422
+ }
3423
+ var json = JSON.stringify(positional);
3424
+ // If the positional isn't serializable, return it as-is.
3425
+ if (json === '{}' || json === '[]' || /^\[object .+?\]$/.test(json)) {
3426
+ return positional;
3427
+ }
3428
+ return json;
3429
+ }
3430
+ }
3431
+ }
3432
+ function format(message) {
3433
+ var positionals = [];
3434
+ for (var _i = 1; _i < arguments.length; _i++) {
3435
+ positionals[_i - 1] = arguments[_i];
3436
+ }
3437
+ if (positionals.length === 0) {
3438
+ return message;
3439
+ }
3440
+ var positionalIndex = 0;
3441
+ var formattedMessage = message.replace(POSITIONALS_EXP, function (match, isEscaped, _, flag) {
3442
+ var positional = positionals[positionalIndex];
3443
+ var value = serializePositional(positional, flag);
3444
+ if (!isEscaped) {
3445
+ positionalIndex++;
3446
+ return value;
3447
+ }
3448
+ return match;
3449
+ });
3450
+ // Append unresolved positionals to string as-is.
3451
+ if (positionalIndex < positionals.length) {
3452
+ formattedMessage += " " + positionals.slice(positionalIndex).join(' ');
3453
+ }
3454
+ formattedMessage = formattedMessage.replace(/%{2,2}/g, '%');
3455
+ return formattedMessage;
3456
+ }
3457
+ format$1.format = format;
3458
+
3400
3459
  var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
3401
3460
  var extendStatics = function (d, b) {
3402
3461
  extendStatics = Object.setPrototypeOf ||
@@ -3418,21 +3477,9 @@ var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function
3418
3477
  return to;
3419
3478
  };
3420
3479
  Object.defineProperty(invariant$2, "__esModule", { value: true });
3421
- invariant$2.invariant = invariant$2.InvariantError = invariant$2.interpolate = void 0;
3480
+ invariant$2.invariant = invariant$2.InvariantError = void 0;
3481
+ var format_1 = format$1;
3422
3482
  var STACK_FRAMES_TO_IGNORE = 2;
3423
- function interpolate(message) {
3424
- var positionals = [];
3425
- for (var _i = 1; _i < arguments.length; _i++) {
3426
- positionals[_i - 1] = arguments[_i];
3427
- }
3428
- var index = 0;
3429
- return message.replace(/%[s|d|o]/g, function (match) {
3430
- var _a;
3431
- var value = (_a = positionals[index++]) !== null && _a !== void 0 ? _a : match;
3432
- return typeof value === 'object' ? JSON.stringify(value) : value;
3433
- });
3434
- }
3435
- invariant$2.interpolate = interpolate;
3436
3483
  var InvariantError = /** @class */ (function (_super) {
3437
3484
  __extends(InvariantError, _super);
3438
3485
  function InvariantError(message) {
@@ -3442,7 +3489,7 @@ var InvariantError = /** @class */ (function (_super) {
3442
3489
  }
3443
3490
  var _this = _super.call(this, message) || this;
3444
3491
  _this.name = 'Invariant Violation';
3445
- _this.message = interpolate.apply(void 0, __spreadArray([message], positionals));
3492
+ _this.message = format_1.format.apply(void 0, __spreadArray([message], positionals));
3446
3493
  if (_this.stack) {
3447
3494
  var prevStack = _this.stack;
3448
3495
  _this.stack = prevStack
@@ -3479,6 +3526,7 @@ var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m
3479
3526
  };
3480
3527
  Object.defineProperty(exports, "__esModule", { value: true });
3481
3528
  __exportStar(invariant$2, exports);
3529
+ __exportStar(format$1, exports);
3482
3530
  }(lib));
3483
3531
 
3484
3532
  const LIBRARY_PREFIX = '[MSW]';
@@ -3486,7 +3534,7 @@ const LIBRARY_PREFIX = '[MSW]';
3486
3534
  * Formats a given message by appending the library's prefix string.
3487
3535
  */
3488
3536
  function formatMessage(message, ...positionals) {
3489
- const interpolatedMessage = lib.interpolate(message, ...positionals);
3537
+ const interpolatedMessage = lib.format(message, ...positionals);
3490
3538
  return `${LIBRARY_PREFIX} ${interpolatedMessage}`;
3491
3539
  }
3492
3540
  /**
@@ -6747,17 +6795,20 @@ const getPublicUrlFromRequest = (request) => {
6747
6795
  : new URL(request.url.pathname, `${request.url.protocol}//${request.url.host}`).href;
6748
6796
  };
6749
6797
 
6750
- function parseQuery(query) {
6798
+ function parseDocumentNode(node) {
6751
6799
  var _a;
6800
+ const operationDef = node.definitions.find((def) => {
6801
+ return def.kind === 'OperationDefinition';
6802
+ });
6803
+ return {
6804
+ operationType: operationDef === null || operationDef === void 0 ? void 0 : operationDef.operation,
6805
+ operationName: (_a = operationDef === null || operationDef === void 0 ? void 0 : operationDef.name) === null || _a === void 0 ? void 0 : _a.value,
6806
+ };
6807
+ }
6808
+ function parseQuery(query) {
6752
6809
  try {
6753
6810
  const ast = parse(query);
6754
- const operationDef = ast.definitions.find((def) => {
6755
- return def.kind === 'OperationDefinition';
6756
- });
6757
- return {
6758
- operationType: operationDef === null || operationDef === void 0 ? void 0 : operationDef.operation,
6759
- operationName: (_a = operationDef === null || operationDef === void 0 ? void 0 : operationDef.name) === null || _a === void 0 ? void 0 : _a.value,
6760
- };
6811
+ return parseDocumentNode(ast);
6761
6812
  }
6762
6813
  catch (error) {
6763
6814
  return error;
@@ -6837,7 +6888,7 @@ function parseGraphQLRequest(request) {
6837
6888
  const parsedResult = parseQuery(query);
6838
6889
  if (parsedResult instanceof Error) {
6839
6890
  const requestPublicUrl = getPublicUrlFromRequest(request);
6840
- throw new Error(devUtils.formatMessage('Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%o', request.method, requestPublicUrl, parsedResult.message));
6891
+ throw new Error(devUtils.formatMessage('Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%s', request.method, requestPublicUrl, parsedResult.message));
6841
6892
  }
6842
6893
  return {
6843
6894
  operationType: parsedResult.operationType,
@@ -7181,17 +7232,23 @@ const xml = (body) => {
7181
7232
  };
7182
7233
  };
7183
7234
 
7235
+ var StatusCodeColor;
7236
+ (function (StatusCodeColor) {
7237
+ StatusCodeColor["Success"] = "#69AB32";
7238
+ StatusCodeColor["Warning"] = "#F0BB4B";
7239
+ StatusCodeColor["Danger"] = "#E95F5D";
7240
+ })(StatusCodeColor || (StatusCodeColor = {}));
7184
7241
  /**
7185
7242
  * Returns a HEX color for a given response status code number.
7186
7243
  */
7187
7244
  function getStatusCodeColor(status) {
7188
7245
  if (status < 300) {
7189
- return '#69AB32';
7246
+ return StatusCodeColor.Success;
7190
7247
  }
7191
7248
  if (status < 400) {
7192
- return '#F0BB4B';
7249
+ return StatusCodeColor.Warning;
7193
7250
  }
7194
- return '#E95F5D';
7251
+ return StatusCodeColor.Danger;
7195
7252
  }
7196
7253
 
7197
7254
  /**
@@ -7297,7 +7354,10 @@ function getAbsoluteUrl(path, baseUrl) {
7297
7354
  // Resolve a relative request URL against a given custom "baseUrl"
7298
7355
  // or the current location (in the case of browser/browser-like environments).
7299
7356
  const origin = baseUrl || (typeof location !== 'undefined' && location.origin);
7300
- return origin ? new URL(path, origin).href : path;
7357
+ return origin
7358
+ ? // Encode and decode the path to preserve escaped characters.
7359
+ decodeURI(new URL(encodeURI(path), origin).href)
7360
+ : path;
7301
7361
  }
7302
7362
 
7303
7363
  /**
@@ -7577,7 +7637,8 @@ ${queryParams
7577
7637
  const publicUrl = getPublicUrlFromRequest(request);
7578
7638
  const loggedRequest = prepareRequest(request);
7579
7639
  const loggedResponse = prepareResponse(response);
7580
- console.groupCollapsed(devUtils.formatMessage('%s %s %s (%c%s%c)'), getTimestamp(), request.method, publicUrl, `color:${getStatusCodeColor(response.status)} %s`, response.status, response.statusText, 'color:inherit');
7640
+ const statusColor = getStatusCodeColor(response.status);
7641
+ console.groupCollapsed(devUtils.formatMessage('%s %s %s (%c%s%c)'), getTimestamp(), request.method, publicUrl, `color:${statusColor}`, `${response.status} ${response.statusText}`, 'color:inherit');
7581
7642
  console.log('Request', loggedRequest);
7582
7643
  console.log('Handler:', {
7583
7644
  mask: this.info.path,
@@ -7607,16 +7668,33 @@ const graphqlContext = {
7607
7668
  errors,
7608
7669
  cookie,
7609
7670
  };
7671
+ function isDocumentNode(value) {
7672
+ if (value == null) {
7673
+ return false;
7674
+ }
7675
+ return typeof value === 'object' && 'kind' in value && 'definitions' in value;
7676
+ }
7610
7677
  class GraphQLHandler extends RequestHandler {
7611
7678
  constructor(operationType, operationName, endpoint, resolver) {
7679
+ let resolvedOperationName = operationName;
7680
+ if (isDocumentNode(operationName)) {
7681
+ const parsedNode = parseDocumentNode(operationName);
7682
+ if (parsedNode.operationType !== operationType) {
7683
+ throw new Error(`Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "${operationType}", but got "${parsedNode.operationType}").`);
7684
+ }
7685
+ if (!parsedNode.operationName) {
7686
+ throw new Error(`Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`);
7687
+ }
7688
+ resolvedOperationName = parsedNode.operationName;
7689
+ }
7612
7690
  const header = operationType === 'all'
7613
7691
  ? `${operationType} (origin: ${endpoint.toString()})`
7614
- : `${operationType} ${operationName} (origin: ${endpoint.toString()})`;
7692
+ : `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`;
7615
7693
  super({
7616
7694
  info: {
7617
7695
  header,
7618
7696
  operationType,
7619
- operationName,
7697
+ operationName: resolvedOperationName,
7620
7698
  },
7621
7699
  ctx: graphqlContext,
7622
7700
  resolver,
@@ -7655,7 +7733,8 @@ Consider naming this operation or using "graphql.operation" request handler to i
7655
7733
  log(request, response, handler, parsedRequest) {
7656
7734
  const loggedRequest = prepareRequest(request);
7657
7735
  const loggedResponse = prepareResponse(response);
7658
- console.groupCollapsed(devUtils.formatMessage('%s %s (%c%s%c)'), getTimestamp(), `${parsedRequest === null || parsedRequest === void 0 ? void 0 : parsedRequest.operationType} ${parsedRequest === null || parsedRequest === void 0 ? void 0 : parsedRequest.operationName}`, `color:${getStatusCodeColor(response.status)} %s`, response.status, response.statusText, 'color:inherit');
7736
+ const statusColor = getStatusCodeColor(response.status);
7737
+ console.groupCollapsed(devUtils.formatMessage('%s %s (%c%s%c)'), getTimestamp(), `${parsedRequest === null || parsedRequest === void 0 ? void 0 : parsedRequest.operationType} ${parsedRequest === null || parsedRequest === void 0 ? void 0 : parsedRequest.operationName}`, `color:${statusColor}`, `${response.status} ${response.statusText}`, 'color:inherit');
7659
7738
  console.log('Request:', loggedRequest);
7660
7739
  console.log('Handler:', this);
7661
7740
  console.log('Response:', loggedResponse);
@@ -7769,8 +7848,10 @@ Read more: https://mswjs.io/docs/getting-started/mocks\
7769
7848
  const message = messageTemplate.join('\n\n');
7770
7849
  switch (strategy) {
7771
7850
  case 'error': {
7851
+ // Print a developer-friendly error.
7772
7852
  devUtils.error('Error: %s', message);
7773
- break;
7853
+ // Throw an exception to halt request processing and not perform the original request.
7854
+ throw new Error('Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.');
7774
7855
  }
7775
7856
  case 'warn': {
7776
7857
  devUtils.warn('Warning: %s', message);
@@ -7837,6 +7918,23 @@ function handleRequest(request, handlers, options, emitter, handleRequestOptions
7837
7918
  });
7838
7919
  }
7839
7920
 
7921
+ /**
7922
+ * Pipes all emitted events from one emitter to another.
7923
+ */
7924
+ function pipeEvents(source, destination) {
7925
+ const rawEmit = source.emit;
7926
+ // @ts-ignore
7927
+ if (rawEmit._isPiped) {
7928
+ return;
7929
+ }
7930
+ source.emit = function (event, ...data) {
7931
+ destination.emit(event, ...data);
7932
+ return rawEmit.call(this, event, ...data);
7933
+ };
7934
+ // @ts-ignore
7935
+ source.emit._isPiped = true;
7936
+ }
7937
+
7840
7938
  const DEFAULT_LISTEN_OPTIONS = {
7841
7939
  onUnhandledRequest: 'warn',
7842
7940
  };
@@ -7846,6 +7944,8 @@ const DEFAULT_LISTEN_OPTIONS = {
7846
7944
  */
7847
7945
  function createSetupServer(...interceptors$1) {
7848
7946
  const emitter = new lib$3.StrictEventEmitter();
7947
+ const publicEmitter = new lib$3.StrictEventEmitter();
7948
+ pipeEvents(emitter, publicEmitter);
7849
7949
  return function setupServer(...requestHandlers) {
7850
7950
  requestHandlers.forEach((handler) => {
7851
7951
  if (Array.isArray(handler))
@@ -7915,11 +8015,20 @@ ${source.bold(`${pragma} ${header}`)}
7915
8015
  `);
7916
8016
  });
7917
8017
  },
7918
- on(eventType, listener) {
7919
- emitter.addListener(eventType, listener);
8018
+ events: {
8019
+ on(...args) {
8020
+ return publicEmitter.on(...args);
8021
+ },
8022
+ removeListener(...args) {
8023
+ return publicEmitter.removeListener(...args);
8024
+ },
8025
+ removeAllListeners(...args) {
8026
+ return publicEmitter.removeAllListeners(...args);
8027
+ },
7920
8028
  },
7921
8029
  close() {
7922
8030
  emitter.removeAllListeners();
8031
+ publicEmitter.removeAllListeners();
7923
8032
  interceptor.restore();
7924
8033
  },
7925
8034
  };