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.
@@ -41,6 +41,65 @@ var lib = {};
41
41
 
42
42
  var invariant$1 = {};
43
43
 
44
+ var format$1 = {};
45
+
46
+ Object.defineProperty(format$1, "__esModule", { value: true });
47
+ format$1.format = void 0;
48
+ var POSITIONALS_EXP = /(%?)(%([sdjo]))/g;
49
+ function serializePositional(positional, flag) {
50
+ switch (flag) {
51
+ // Strings.
52
+ case 's':
53
+ return positional;
54
+ // Digits.
55
+ case 'd':
56
+ case 'i':
57
+ return Number(positional);
58
+ // JSON.
59
+ case 'j':
60
+ return JSON.stringify(positional);
61
+ // Objects.
62
+ case 'o': {
63
+ // Preserve stings to prevent extra quotes around them.
64
+ if (typeof positional === 'string') {
65
+ return positional;
66
+ }
67
+ var json = JSON.stringify(positional);
68
+ // If the positional isn't serializable, return it as-is.
69
+ if (json === '{}' || json === '[]' || /^\[object .+?\]$/.test(json)) {
70
+ return positional;
71
+ }
72
+ return json;
73
+ }
74
+ }
75
+ }
76
+ function format(message) {
77
+ var positionals = [];
78
+ for (var _i = 1; _i < arguments.length; _i++) {
79
+ positionals[_i - 1] = arguments[_i];
80
+ }
81
+ if (positionals.length === 0) {
82
+ return message;
83
+ }
84
+ var positionalIndex = 0;
85
+ var formattedMessage = message.replace(POSITIONALS_EXP, function (match, isEscaped, _, flag) {
86
+ var positional = positionals[positionalIndex];
87
+ var value = serializePositional(positional, flag);
88
+ if (!isEscaped) {
89
+ positionalIndex++;
90
+ return value;
91
+ }
92
+ return match;
93
+ });
94
+ // Append unresolved positionals to string as-is.
95
+ if (positionalIndex < positionals.length) {
96
+ formattedMessage += " " + positionals.slice(positionalIndex).join(' ');
97
+ }
98
+ formattedMessage = formattedMessage.replace(/%{2,2}/g, '%');
99
+ return formattedMessage;
100
+ }
101
+ format$1.format = format;
102
+
44
103
  var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
45
104
  var extendStatics = function (d, b) {
46
105
  extendStatics = Object.setPrototypeOf ||
@@ -62,21 +121,9 @@ var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function
62
121
  return to;
63
122
  };
64
123
  Object.defineProperty(invariant$1, "__esModule", { value: true });
65
- invariant$1.invariant = invariant$1.InvariantError = invariant$1.interpolate = void 0;
124
+ invariant$1.invariant = invariant$1.InvariantError = void 0;
125
+ var format_1 = format$1;
66
126
  var STACK_FRAMES_TO_IGNORE = 2;
67
- function interpolate(message) {
68
- var positionals = [];
69
- for (var _i = 1; _i < arguments.length; _i++) {
70
- positionals[_i - 1] = arguments[_i];
71
- }
72
- var index = 0;
73
- return message.replace(/%[s|d|o]/g, function (match) {
74
- var _a;
75
- var value = (_a = positionals[index++]) !== null && _a !== void 0 ? _a : match;
76
- return typeof value === 'object' ? JSON.stringify(value) : value;
77
- });
78
- }
79
- invariant$1.interpolate = interpolate;
80
127
  var InvariantError = /** @class */ (function (_super) {
81
128
  __extends(InvariantError, _super);
82
129
  function InvariantError(message) {
@@ -86,7 +133,7 @@ var InvariantError = /** @class */ (function (_super) {
86
133
  }
87
134
  var _this = _super.call(this, message) || this;
88
135
  _this.name = 'Invariant Violation';
89
- _this.message = interpolate.apply(void 0, __spreadArray([message], positionals));
136
+ _this.message = format_1.format.apply(void 0, __spreadArray([message], positionals));
90
137
  if (_this.stack) {
91
138
  var prevStack = _this.stack;
92
139
  _this.stack = prevStack
@@ -123,6 +170,7 @@ var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m
123
170
  };
124
171
  Object.defineProperty(exports, "__esModule", { value: true });
125
172
  __exportStar(invariant$1, exports);
173
+ __exportStar(format$1, exports);
126
174
  }(lib));
127
175
 
128
176
  const LIBRARY_PREFIX = '[MSW]';
@@ -130,7 +178,7 @@ const LIBRARY_PREFIX = '[MSW]';
130
178
  * Formats a given message by appending the library's prefix string.
131
179
  */
132
180
  function formatMessage(message, ...positionals) {
133
- const interpolatedMessage = lib.interpolate(message, ...positionals);
181
+ const interpolatedMessage = lib.format(message, ...positionals);
134
182
  return `${LIBRARY_PREFIX} ${interpolatedMessage}`;
135
183
  }
136
184
  /**
@@ -265,17 +313,23 @@ const getPublicUrlFromRequest = (request) => {
265
313
  : new URL(request.url.pathname, `${request.url.protocol}//${request.url.host}`).href;
266
314
  };
267
315
 
316
+ var StatusCodeColor;
317
+ (function (StatusCodeColor) {
318
+ StatusCodeColor["Success"] = "#69AB32";
319
+ StatusCodeColor["Warning"] = "#F0BB4B";
320
+ StatusCodeColor["Danger"] = "#E95F5D";
321
+ })(StatusCodeColor || (StatusCodeColor = {}));
268
322
  /**
269
323
  * Returns a HEX color for a given response status code number.
270
324
  */
271
325
  function getStatusCodeColor(status) {
272
326
  if (status < 300) {
273
- return '#69AB32';
327
+ return StatusCodeColor.Success;
274
328
  }
275
329
  if (status < 400) {
276
- return '#F0BB4B';
330
+ return StatusCodeColor.Warning;
277
331
  }
278
- return '#E95F5D';
332
+ return StatusCodeColor.Danger;
279
333
  }
280
334
 
281
335
  /**
@@ -381,7 +435,10 @@ function getAbsoluteUrl(path, baseUrl) {
381
435
  // Resolve a relative request URL against a given custom "baseUrl"
382
436
  // or the current location (in the case of browser/browser-like environments).
383
437
  const origin = baseUrl || (typeof location !== 'undefined' && location.origin);
384
- return origin ? new URL(path, origin).href : path;
438
+ return origin
439
+ ? // Encode and decode the path to preserve escaped characters.
440
+ decodeURI(new URL(encodeURI(path), origin).href)
441
+ : path;
385
442
  }
386
443
 
387
444
  /**
@@ -576,4 +633,4 @@ class RequestHandler {
576
633
  }
577
634
  }
578
635
 
579
- export { NetworkError as N, RequestHandler as R, __awaiter as _, getCleanUrl$1 as a, defaultResponse as b, createResponseComposition as c, devUtils as d, defaultContext as e, compose as f, getPublicUrlFromRequest as g, cleanUrl as h, getSearchParams as i, prepareRequest as j, prepareResponse as k, lib as l, matchRequestUrl as m, getTimestamp as n, getStatusCodeColor as o, parseBody as p, __rest as q, response as r };
636
+ export { NetworkError as N, RequestHandler as R, __awaiter as _, getCleanUrl$1 as a, defaultResponse as b, createResponseComposition as c, devUtils as d, defaultContext as e, compose as f, getPublicUrlFromRequest as g, cleanUrl as h, getSearchParams as i, prepareRequest as j, prepareResponse as k, lib as l, matchRequestUrl as m, getStatusCodeColor as n, getTimestamp as o, parseBody as p, __rest as q, response as r };
@@ -1,6 +1,6 @@
1
1
  import { j as jsonParse, b as set, s as status, e as delay, f as fetch, d as cookie } from './fetch-deps.js';
2
2
  import { d as data, e as errors } from './errors-deps.js';
3
- import { g as getPublicUrlFromRequest, d as devUtils, q as __rest, R as RequestHandler, m as matchRequestUrl, j as prepareRequest, k as prepareResponse, n as getTimestamp, o as getStatusCodeColor } from './RequestHandler-deps.js';
3
+ import { g as getPublicUrlFromRequest, d as devUtils, q as __rest, R as RequestHandler, m as matchRequestUrl, j as prepareRequest, k as prepareResponse, n as getStatusCodeColor, o as getTimestamp } from './RequestHandler-deps.js';
4
4
 
5
5
  function _typeof$3(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$3 = function _typeof(obj) { return typeof obj; }; } else { _typeof$3 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$3(obj); }
6
6
 
@@ -3124,17 +3124,20 @@ function getTokenKindDesc(kind) {
3124
3124
  return isPunctuatorTokenKind(kind) ? "\"".concat(kind, "\"") : kind;
3125
3125
  }
3126
3126
 
3127
- function parseQuery(query) {
3127
+ function parseDocumentNode(node) {
3128
3128
  var _a;
3129
+ const operationDef = node.definitions.find((def) => {
3130
+ return def.kind === 'OperationDefinition';
3131
+ });
3132
+ return {
3133
+ operationType: operationDef === null || operationDef === void 0 ? void 0 : operationDef.operation,
3134
+ operationName: (_a = operationDef === null || operationDef === void 0 ? void 0 : operationDef.name) === null || _a === void 0 ? void 0 : _a.value,
3135
+ };
3136
+ }
3137
+ function parseQuery(query) {
3129
3138
  try {
3130
3139
  const ast = parse(query);
3131
- const operationDef = ast.definitions.find((def) => {
3132
- return def.kind === 'OperationDefinition';
3133
- });
3134
- return {
3135
- operationType: operationDef === null || operationDef === void 0 ? void 0 : operationDef.operation,
3136
- operationName: (_a = operationDef === null || operationDef === void 0 ? void 0 : operationDef.name) === null || _a === void 0 ? void 0 : _a.value,
3137
- };
3140
+ return parseDocumentNode(ast);
3138
3141
  }
3139
3142
  catch (error) {
3140
3143
  return error;
@@ -3214,7 +3217,7 @@ function parseGraphQLRequest(request) {
3214
3217
  const parsedResult = parseQuery(query);
3215
3218
  if (parsedResult instanceof Error) {
3216
3219
  const requestPublicUrl = getPublicUrlFromRequest(request);
3217
- 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));
3220
+ 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));
3218
3221
  }
3219
3222
  return {
3220
3223
  operationType: parsedResult.operationType,
@@ -3242,16 +3245,33 @@ const graphqlContext = {
3242
3245
  errors,
3243
3246
  cookie,
3244
3247
  };
3248
+ function isDocumentNode(value) {
3249
+ if (value == null) {
3250
+ return false;
3251
+ }
3252
+ return typeof value === 'object' && 'kind' in value && 'definitions' in value;
3253
+ }
3245
3254
  class GraphQLHandler extends RequestHandler {
3246
3255
  constructor(operationType, operationName, endpoint, resolver) {
3256
+ let resolvedOperationName = operationName;
3257
+ if (isDocumentNode(operationName)) {
3258
+ const parsedNode = parseDocumentNode(operationName);
3259
+ if (parsedNode.operationType !== operationType) {
3260
+ throw new Error(`Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "${operationType}", but got "${parsedNode.operationType}").`);
3261
+ }
3262
+ if (!parsedNode.operationName) {
3263
+ throw new Error(`Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`);
3264
+ }
3265
+ resolvedOperationName = parsedNode.operationName;
3266
+ }
3247
3267
  const header = operationType === 'all'
3248
3268
  ? `${operationType} (origin: ${endpoint.toString()})`
3249
- : `${operationType} ${operationName} (origin: ${endpoint.toString()})`;
3269
+ : `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`;
3250
3270
  super({
3251
3271
  info: {
3252
3272
  header,
3253
3273
  operationType,
3254
- operationName,
3274
+ operationName: resolvedOperationName,
3255
3275
  },
3256
3276
  ctx: graphqlContext,
3257
3277
  resolver,
@@ -3290,7 +3310,8 @@ Consider naming this operation or using "graphql.operation" request handler to i
3290
3310
  log(request, response, handler, parsedRequest) {
3291
3311
  const loggedRequest = prepareRequest(request);
3292
3312
  const loggedResponse = prepareResponse(response);
3293
- 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');
3313
+ const statusColor = getStatusCodeColor(response.status);
3314
+ 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');
3294
3315
  console.log('Request:', loggedRequest);
3295
3316
  console.log('Handler:', this);
3296
3317
  console.log('Response:', loggedResponse);