msw 0.40.2 → 0.41.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.
Files changed (119) hide show
  1. package/config/constants.js +1 -3
  2. package/config/scripts/postinstall.js +32 -25
  3. package/lib/esm/index.js +1967 -1589
  4. package/lib/esm/index.js.map +1 -0
  5. package/lib/glossary-36cf4e2d.d.ts +331 -0
  6. package/lib/iife/index.js +9773 -21
  7. package/lib/iife/index.js.map +1 -0
  8. package/lib/index.d.ts +353 -0
  9. package/lib/index.js +2125 -0
  10. package/lib/index.js.map +1 -0
  11. package/lib/{esm/mockServiceWorker.js → mockServiceWorker.js} +1 -1
  12. package/lib/native/index.d.ts +9 -0
  13. package/lib/native/index.js +1532 -0
  14. package/lib/native/index.mjs +1532 -0
  15. package/lib/node/index.d.ts +15 -0
  16. package/lib/node/index.js +1601 -0
  17. package/lib/node/index.js.map +1 -0
  18. package/lib/node/index.mjs +1601 -0
  19. package/lib/node/index.mjs.map +1 -0
  20. package/native/package.json +3 -2
  21. package/node/package.json +3 -2
  22. package/package.json +11 -20
  23. package/lib/esm/errors-deps.js +0 -74
  24. package/lib/esm/fetch-deps.js +0 -1005
  25. package/lib/esm/graphql-deps.js +0 -3545
  26. package/lib/esm/graphql.js +0 -5
  27. package/lib/esm/index-deps.js +0 -21
  28. package/lib/esm/index2.js +0 -3
  29. package/lib/esm/matchRequestUrl-deps.js +0 -992
  30. package/lib/esm/rest-deps.js +0 -103
  31. package/lib/esm/rest.js +0 -5
  32. package/lib/esm/xml-deps.js +0 -44
  33. package/lib/iife/mockServiceWorker.js +0 -338
  34. package/lib/types/context/body.d.ts +0 -9
  35. package/lib/types/context/cookie.d.ts +0 -7
  36. package/lib/types/context/data.d.ts +0 -8
  37. package/lib/types/context/delay.d.ts +0 -15
  38. package/lib/types/context/errors.d.ts +0 -8
  39. package/lib/types/context/extensions.d.ts +0 -8
  40. package/lib/types/context/fetch.d.ts +0 -9
  41. package/lib/types/context/index.d.ts +0 -12
  42. package/lib/types/context/json.d.ts +0 -12
  43. package/lib/types/context/set.d.ts +0 -18
  44. package/lib/types/context/status.d.ts +0 -9
  45. package/lib/types/context/text.d.ts +0 -8
  46. package/lib/types/context/xml.d.ts +0 -9
  47. package/lib/types/graphql.d.ts +0 -74
  48. package/lib/types/handlers/GraphQLHandler.d.ts +0 -39
  49. package/lib/types/handlers/RequestHandler.d.ts +0 -103
  50. package/lib/types/handlers/RestHandler.d.ts +0 -47
  51. package/lib/types/index.d.ts +0 -26
  52. package/lib/types/native/index.d.ts +0 -1
  53. package/lib/types/node/createSetupServer.d.ts +0 -8
  54. package/lib/types/node/glossary.d.ts +0 -38
  55. package/lib/types/node/index.d.ts +0 -2
  56. package/lib/types/node/setupServer.d.ts +0 -6
  57. package/lib/types/response.d.ts +0 -35
  58. package/lib/types/rest.d.ts +0 -13
  59. package/lib/types/setupWorker/glossary.d.ts +0 -161
  60. package/lib/types/setupWorker/setupWorker.d.ts +0 -9
  61. package/lib/types/setupWorker/start/createFallbackStart.d.ts +0 -2
  62. package/lib/types/setupWorker/start/createStartHandler.d.ts +0 -2
  63. package/lib/types/setupWorker/start/utils/enableMocking.d.ts +0 -5
  64. package/lib/types/setupWorker/start/utils/getWorkerByRegistration.d.ts +0 -6
  65. package/lib/types/setupWorker/start/utils/getWorkerInstance.d.ts +0 -6
  66. package/lib/types/setupWorker/start/utils/prepareStartHandler.d.ts +0 -9
  67. package/lib/types/setupWorker/start/utils/printStartMessage.d.ts +0 -10
  68. package/lib/types/setupWorker/start/utils/validateWorkerScope.d.ts +0 -2
  69. package/lib/types/setupWorker/stop/createFallbackStop.d.ts +0 -2
  70. package/lib/types/setupWorker/stop/createStop.d.ts +0 -2
  71. package/lib/types/setupWorker/stop/utils/printStopMessage.d.ts +0 -3
  72. package/lib/types/sharedOptions.d.ts +0 -24
  73. package/lib/types/typeUtils.d.ts +0 -7
  74. package/lib/types/utils/NetworkError.d.ts +0 -3
  75. package/lib/types/utils/createBroadcastChannel.d.ts +0 -18
  76. package/lib/types/utils/deferNetworkRequestsUntil.d.ts +0 -6
  77. package/lib/types/utils/getResponse.d.ts +0 -15
  78. package/lib/types/utils/handleRequest.d.ts +0 -34
  79. package/lib/types/utils/internal/compose.d.ts +0 -14
  80. package/lib/types/utils/internal/devUtils.d.ts +0 -18
  81. package/lib/types/utils/internal/getCallFrame.d.ts +0 -4
  82. package/lib/types/utils/internal/isIterable.d.ts +0 -4
  83. package/lib/types/utils/internal/isObject.d.ts +0 -4
  84. package/lib/types/utils/internal/isStringEqual.d.ts +0 -4
  85. package/lib/types/utils/internal/jsonParse.d.ts +0 -5
  86. package/lib/types/utils/internal/mergeRight.d.ts +0 -5
  87. package/lib/types/utils/internal/parseGraphQLRequest.d.ts +0 -23
  88. package/lib/types/utils/internal/parseMultipartData.d.ts +0 -6
  89. package/lib/types/utils/internal/pipeEvents.d.ts +0 -6
  90. package/lib/types/utils/internal/requestHandlerUtils.d.ts +0 -4
  91. package/lib/types/utils/internal/requestIntegrityCheck.d.ts +0 -2
  92. package/lib/types/utils/internal/tryCatch.d.ts +0 -1
  93. package/lib/types/utils/internal/uuidv4.d.ts +0 -1
  94. package/lib/types/utils/logging/getStatusCodeColor.d.ts +0 -9
  95. package/lib/types/utils/logging/getTimestamp.d.ts +0 -4
  96. package/lib/types/utils/logging/prepareRequest.d.ts +0 -23
  97. package/lib/types/utils/logging/prepareResponse.d.ts +0 -10
  98. package/lib/types/utils/matching/matchRequestUrl.d.ts +0 -17
  99. package/lib/types/utils/matching/normalizePath.d.ts +0 -9
  100. package/lib/types/utils/request/getPublicUrlFromRequest.d.ts +0 -6
  101. package/lib/types/utils/request/getRequestCookies.d.ts +0 -7
  102. package/lib/types/utils/request/onUnhandledRequest.d.ts +0 -8
  103. package/lib/types/utils/request/parseBody.d.ts +0 -5
  104. package/lib/types/utils/request/parseIsomorphicRequest.d.ts +0 -6
  105. package/lib/types/utils/request/parseWorkerRequest.d.ts +0 -7
  106. package/lib/types/utils/request/pruneGetRequestBody.d.ts +0 -7
  107. package/lib/types/utils/request/readResponseCookies.d.ts +0 -3
  108. package/lib/types/utils/request/setRequestCookies.d.ts +0 -9
  109. package/lib/types/utils/url/cleanUrl.d.ts +0 -5
  110. package/lib/types/utils/url/getAbsoluteUrl.d.ts +0 -4
  111. package/lib/types/utils/url/getAbsoluteWorkerUrl.d.ts +0 -5
  112. package/lib/types/utils/url/isAbsoluteUrl.d.ts +0 -4
  113. package/lib/types/utils/worker/createFallbackRequestListener.d.ts +0 -4
  114. package/lib/types/utils/worker/createRequestListener.d.ts +0 -4
  115. package/lib/types/utils/worker/createResponseListener.d.ts +0 -3
  116. package/lib/umd/index.js +0 -31617
  117. package/lib/umd/mockServiceWorker.js +0 -338
  118. package/native/lib/index.js +0 -6384
  119. package/node/lib/index.js +0 -8276
@@ -1,992 +0,0 @@
1
- import { c as commonjsGlobal, l as lib$1, s as status, b as set, e as delay, f as fetch, j as jsonParse } from './fetch-deps.js';
2
- import { getCleanUrl } from '@mswjs/interceptors/lib/utils/getCleanUrl';
3
-
4
- /*! *****************************************************************************
5
- Copyright (c) Microsoft Corporation.
6
-
7
- Permission to use, copy, modify, and/or distribute this software for any
8
- purpose with or without fee is hereby granted.
9
-
10
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
11
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
12
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
13
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
14
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
15
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
16
- PERFORMANCE OF THIS SOFTWARE.
17
- ***************************************************************************** */
18
-
19
- function __rest(s, e) {
20
- var t = {};
21
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
22
- t[p] = s[p];
23
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
24
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
25
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
26
- t[p[i]] = s[p[i]];
27
- }
28
- return t;
29
- }
30
-
31
- function __awaiter(thisArg, _arguments, P, generator) {
32
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
33
- return new (P || (P = Promise))(function (resolve, reject) {
34
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
35
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
36
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
37
- step((generator = generator.apply(thisArg, _arguments || [])).next());
38
- });
39
- }
40
-
41
- var lib = {};
42
-
43
- var invariant$1 = {};
44
-
45
- var format$1 = {};
46
-
47
- Object.defineProperty(format$1, "__esModule", { value: true });
48
- format$1.format = void 0;
49
- var POSITIONALS_EXP = /(%?)(%([sdjo]))/g;
50
- function serializePositional(positional, flag) {
51
- switch (flag) {
52
- // Strings.
53
- case 's':
54
- return positional;
55
- // Digits.
56
- case 'd':
57
- case 'i':
58
- return Number(positional);
59
- // JSON.
60
- case 'j':
61
- return JSON.stringify(positional);
62
- // Objects.
63
- case 'o': {
64
- // Preserve stings to prevent extra quotes around them.
65
- if (typeof positional === 'string') {
66
- return positional;
67
- }
68
- var json = JSON.stringify(positional);
69
- // If the positional isn't serializable, return it as-is.
70
- if (json === '{}' || json === '[]' || /^\[object .+?\]$/.test(json)) {
71
- return positional;
72
- }
73
- return json;
74
- }
75
- }
76
- }
77
- function format(message) {
78
- var positionals = [];
79
- for (var _i = 1; _i < arguments.length; _i++) {
80
- positionals[_i - 1] = arguments[_i];
81
- }
82
- if (positionals.length === 0) {
83
- return message;
84
- }
85
- var positionalIndex = 0;
86
- var formattedMessage = message.replace(POSITIONALS_EXP, function (match, isEscaped, _, flag) {
87
- var positional = positionals[positionalIndex];
88
- var value = serializePositional(positional, flag);
89
- if (!isEscaped) {
90
- positionalIndex++;
91
- return value;
92
- }
93
- return match;
94
- });
95
- // Append unresolved positionals to string as-is.
96
- if (positionalIndex < positionals.length) {
97
- formattedMessage += " " + positionals.slice(positionalIndex).join(' ');
98
- }
99
- formattedMessage = formattedMessage.replace(/%{2,2}/g, '%');
100
- return formattedMessage;
101
- }
102
- format$1.format = format;
103
-
104
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
105
- var extendStatics = function (d, b) {
106
- extendStatics = Object.setPrototypeOf ||
107
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
108
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
109
- return extendStatics(d, b);
110
- };
111
- return function (d, b) {
112
- if (typeof b !== "function" && b !== null)
113
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
114
- extendStatics(d, b);
115
- function __() { this.constructor = d; }
116
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
117
- };
118
- })();
119
- var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
120
- for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
121
- to[j] = from[i];
122
- return to;
123
- };
124
- Object.defineProperty(invariant$1, "__esModule", { value: true });
125
- invariant$1.invariant = invariant$1.InvariantError = void 0;
126
- var format_1 = format$1;
127
- var STACK_FRAMES_TO_IGNORE = 2;
128
- var InvariantError = /** @class */ (function (_super) {
129
- __extends(InvariantError, _super);
130
- function InvariantError(message) {
131
- var positionals = [];
132
- for (var _i = 1; _i < arguments.length; _i++) {
133
- positionals[_i - 1] = arguments[_i];
134
- }
135
- var _this = _super.call(this, message) || this;
136
- _this.name = 'Invariant Violation';
137
- _this.message = format_1.format.apply(void 0, __spreadArray([message], positionals));
138
- if (_this.stack) {
139
- var nextStack = _this.stack.split('\n');
140
- nextStack.splice(1, STACK_FRAMES_TO_IGNORE);
141
- _this.stack = nextStack.join('\n');
142
- }
143
- return _this;
144
- }
145
- return InvariantError;
146
- }(Error));
147
- invariant$1.InvariantError = InvariantError;
148
- function invariant(predicate, message) {
149
- var positionals = [];
150
- for (var _i = 2; _i < arguments.length; _i++) {
151
- positionals[_i - 2] = arguments[_i];
152
- }
153
- if (!predicate) {
154
- throw new (InvariantError.bind.apply(InvariantError, __spreadArray([void 0, message], positionals)))();
155
- }
156
- }
157
- invariant$1.invariant = invariant;
158
-
159
- (function (exports) {
160
- var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
161
- if (k2 === undefined) k2 = k;
162
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
163
- }) : (function(o, m, k, k2) {
164
- if (k2 === undefined) k2 = k;
165
- o[k2] = m[k];
166
- }));
167
- var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
168
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
169
- };
170
- Object.defineProperty(exports, "__esModule", { value: true });
171
- __exportStar(invariant$1, exports);
172
- __exportStar(format$1, exports);
173
- }(lib));
174
-
175
- const LIBRARY_PREFIX = '[MSW]';
176
- /**
177
- * Formats a given message by appending the library's prefix string.
178
- */
179
- function formatMessage(message, ...positionals) {
180
- const interpolatedMessage = lib.format(message, ...positionals);
181
- return `${LIBRARY_PREFIX} ${interpolatedMessage}`;
182
- }
183
- /**
184
- * Prints a library-specific warning.
185
- */
186
- function warn(message, ...positionals) {
187
- console.warn(formatMessage(message, ...positionals));
188
- }
189
- /**
190
- * Prints a library-specific error.
191
- */
192
- function error(message, ...positionals) {
193
- console.error(formatMessage(message, ...positionals));
194
- }
195
- const devUtils = {
196
- formatMessage,
197
- warn,
198
- error,
199
- };
200
-
201
- class NetworkError extends Error {
202
- constructor(message) {
203
- super(message);
204
- this.name = 'NetworkError';
205
- }
206
- }
207
-
208
- /**
209
- * Composes a given list of functions into a new function that
210
- * executes from right to left.
211
- */
212
- function compose(...fns) {
213
- return (...args) => {
214
- return fns.reduceRight((leftFn, rightFn) => {
215
- return leftFn instanceof Promise
216
- ? Promise.resolve(leftFn).then(rightFn)
217
- : rightFn(leftFn);
218
- }, args[0]);
219
- };
220
- }
221
-
222
- const defaultResponse = {
223
- status: 200,
224
- statusText: 'OK',
225
- body: null,
226
- delay: 0,
227
- once: false,
228
- passthrough: false,
229
- };
230
- const defaultResponseTransformers = [];
231
- function createResponseComposition(responseOverrides, defaultTransformers = defaultResponseTransformers) {
232
- return (...transformers) => __awaiter(this, void 0, void 0, function* () {
233
- const initialResponse = Object.assign({}, defaultResponse, {
234
- headers: new lib$1.Headers({
235
- 'x-powered-by': 'msw',
236
- }),
237
- }, responseOverrides);
238
- const resolvedTransformers = [
239
- ...defaultTransformers,
240
- ...transformers,
241
- ].filter(Boolean);
242
- const resolvedResponse = resolvedTransformers.length > 0
243
- ? compose(...resolvedTransformers)(initialResponse)
244
- : initialResponse;
245
- return resolvedResponse;
246
- });
247
- }
248
- const response = Object.assign(createResponseComposition(), {
249
- once: createResponseComposition({ once: true }),
250
- networkError(message) {
251
- throw new NetworkError(message);
252
- },
253
- });
254
-
255
- const BUILD_FRAME = /(node_modules)?[\/\\]lib[\/\\](umd|esm|iief|cjs)[\/\\]|^[^\/\\]*$/;
256
- /**
257
- * Return the stack trace frame of a function's invocation.
258
- */
259
- function getCallFrame(error) {
260
- // In <IE11, new Error may return an undefined stack
261
- const stack = error.stack;
262
- if (!stack) {
263
- return;
264
- }
265
- const frames = stack.split('\n').slice(1);
266
- // Get the first frame that doesn't reference the library's internal trace.
267
- // Assume that frame is the invocation frame.
268
- const declarationFrame = frames.find((frame) => {
269
- return !BUILD_FRAME.test(frame);
270
- });
271
- if (!declarationFrame) {
272
- return;
273
- }
274
- // Extract file reference from the stack frame.
275
- const declarationPath = declarationFrame
276
- .replace(/\s*at [^()]*\(([^)]+)\)/, '$1')
277
- .replace(/^@/, '');
278
- return declarationPath;
279
- }
280
-
281
- /**
282
- * Determines if the given function is an iterator.
283
- */
284
- function isIterable(fn) {
285
- if (!fn) {
286
- return false;
287
- }
288
- return typeof fn[Symbol.iterator] == 'function';
289
- }
290
-
291
- const defaultContext = {
292
- status,
293
- set,
294
- delay,
295
- fetch,
296
- };
297
- class RequestHandler {
298
- constructor(options) {
299
- this.shouldSkip = false;
300
- this.ctx = options.ctx || defaultContext;
301
- this.resolver = options.resolver;
302
- const callFrame = getCallFrame(new Error());
303
- this.info = Object.assign(Object.assign({}, options.info), { callFrame });
304
- }
305
- /**
306
- * Parse the captured request to extract additional information from it.
307
- * Parsed result is then exposed to other methods of this request handler.
308
- */
309
- parse(_request, _resolutionContext) {
310
- return null;
311
- }
312
- /**
313
- * Test if this handler matches the given request.
314
- */
315
- test(request, resolutionContext) {
316
- return this.predicate(request, this.parse(request, resolutionContext), resolutionContext);
317
- }
318
- /**
319
- * Derive the publicly exposed request (`req`) instance of the response resolver
320
- * from the captured request and its parsed result.
321
- */
322
- getPublicRequest(request, _parsedResult) {
323
- return request;
324
- }
325
- markAsSkipped(shouldSkip = true) {
326
- this.shouldSkip = shouldSkip;
327
- }
328
- /**
329
- * Execute this request handler and produce a mocked response
330
- * using the given resolver function.
331
- */
332
- run(request, resolutionContext) {
333
- return __awaiter(this, void 0, void 0, function* () {
334
- if (this.shouldSkip) {
335
- return null;
336
- }
337
- const parsedResult = this.parse(request, resolutionContext);
338
- const shouldIntercept = this.predicate(request, parsedResult, resolutionContext);
339
- if (!shouldIntercept) {
340
- return null;
341
- }
342
- const publicRequest = this.getPublicRequest(request, parsedResult);
343
- // Create a response extraction wrapper around the resolver
344
- // since it can be both an async function and a generator.
345
- const executeResolver = this.wrapResolver(this.resolver);
346
- const mockedResponse = yield executeResolver(publicRequest, response, this.ctx);
347
- return this.createExecutionResult(parsedResult, publicRequest, mockedResponse);
348
- });
349
- }
350
- wrapResolver(resolver) {
351
- return (req, res, ctx) => __awaiter(this, void 0, void 0, function* () {
352
- const result = this.resolverGenerator || (yield resolver(req, res, ctx));
353
- if (isIterable(result)) {
354
- const { value, done } = result[Symbol.iterator]().next();
355
- const nextResponse = yield value;
356
- // If the generator is done and there is no next value,
357
- // return the previous generator's value.
358
- if (!nextResponse && done) {
359
- return this.resolverGeneratorResult;
360
- }
361
- if (!this.resolverGenerator) {
362
- this.resolverGenerator = result;
363
- }
364
- this.resolverGeneratorResult = nextResponse;
365
- return nextResponse;
366
- }
367
- return result;
368
- });
369
- }
370
- createExecutionResult(parsedResult, request, response) {
371
- return {
372
- handler: this,
373
- parsedResult: parsedResult || null,
374
- request,
375
- response: response || null,
376
- };
377
- }
378
- }
379
- /**
380
- * Bypass this intercepted request.
381
- * This will make a call to the actual endpoint requested.
382
- */
383
- function passthrough() {
384
- // Constructing a dummy "101 Continue" mocked response
385
- // to keep the return type of the resolver consistent.
386
- return {
387
- status: 101,
388
- statusText: 'Continue',
389
- headers: new lib$1.Headers(),
390
- body: null,
391
- // Setting "passthrough" to true will signal the response pipeline
392
- // to perform this intercepted request as-is.
393
- passthrough: true,
394
- once: false,
395
- };
396
- }
397
-
398
- function parseContentHeaders(headersString) {
399
- var _a, _b;
400
- const headers = lib$1.stringToHeaders(headersString);
401
- const contentType = headers.get('content-type') || 'text/plain';
402
- const disposition = headers.get('content-disposition');
403
- if (!disposition) {
404
- throw new Error('"Content-Disposition" header is required.');
405
- }
406
- const directives = disposition.split(';').reduce((acc, chunk) => {
407
- const [name, ...rest] = chunk.trim().split('=');
408
- acc[name] = rest.join('=');
409
- return acc;
410
- }, {});
411
- const name = (_a = directives.name) === null || _a === void 0 ? void 0 : _a.slice(1, -1);
412
- const filename = (_b = directives.filename) === null || _b === void 0 ? void 0 : _b.slice(1, -1);
413
- return {
414
- name,
415
- filename,
416
- contentType,
417
- };
418
- }
419
- /**
420
- * Parses a given string as a multipart/form-data.
421
- * Does not throw an exception on an invalid multipart string.
422
- */
423
- function parseMultipartData(data, headers) {
424
- const contentType = headers === null || headers === void 0 ? void 0 : headers.get('content-type');
425
- if (!contentType) {
426
- return undefined;
427
- }
428
- const [, ...directives] = contentType.split(/; */);
429
- const boundary = directives
430
- .filter((d) => d.startsWith('boundary='))
431
- .map((s) => s.replace(/^boundary=/, ''))[0];
432
- if (!boundary) {
433
- return undefined;
434
- }
435
- const boundaryRegExp = new RegExp(`--+${boundary}`);
436
- const fields = data
437
- .split(boundaryRegExp)
438
- .filter((chunk) => chunk.startsWith('\r\n') && chunk.endsWith('\r\n'))
439
- .map((chunk) => chunk.trimStart().replace(/\r\n$/, ''));
440
- if (!fields.length) {
441
- return undefined;
442
- }
443
- const parsedBody = {};
444
- try {
445
- for (const field of fields) {
446
- const [contentHeaders, ...rest] = field.split('\r\n\r\n');
447
- const contentBody = rest.join('\r\n\r\n');
448
- const { contentType, filename, name } = parseContentHeaders(contentHeaders);
449
- const value = filename === undefined
450
- ? contentBody
451
- : new File([contentBody], filename, { type: contentType });
452
- const parsedValue = parsedBody[name];
453
- if (parsedValue === undefined) {
454
- parsedBody[name] = value;
455
- }
456
- else if (Array.isArray(parsedValue)) {
457
- parsedBody[name] = [...parsedValue, value];
458
- }
459
- else {
460
- parsedBody[name] = [parsedValue, value];
461
- }
462
- }
463
- return parsedBody;
464
- }
465
- catch (error) {
466
- return undefined;
467
- }
468
- }
469
-
470
- /**
471
- * Parses a given request/response body based on the "Content-Type" header.
472
- */
473
- function parseBody(body, headers) {
474
- var _a;
475
- // Return whatever falsey body value is given.
476
- if (!body) {
477
- return body;
478
- }
479
- const contentType = ((_a = headers === null || headers === void 0 ? void 0 : headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || '';
480
- // If the body has a Multipart Content-Type
481
- // parse it into an object.
482
- const hasMultipartContent = contentType.startsWith('multipart/form-data');
483
- if (hasMultipartContent && typeof body !== 'object') {
484
- return parseMultipartData(body.toString(), headers) || body;
485
- }
486
- // If the intercepted request's body has a JSON Content-Type
487
- // parse it into an object.
488
- const hasJsonContent = contentType.includes('json');
489
- if (hasJsonContent && typeof body !== 'object') {
490
- return jsonParse(body.toString()) || body;
491
- }
492
- // Otherwise leave as-is.
493
- return body;
494
- }
495
-
496
- /**
497
- * Returns a relative URL if the given request URL is relative to the current origin.
498
- * Otherwise returns an absolute URL.
499
- */
500
- const getPublicUrlFromRequest = (request) => {
501
- return request.referrer.startsWith(request.url.origin)
502
- ? request.url.pathname
503
- : new URL(request.url.pathname, `${request.url.protocol}//${request.url.host}`).href;
504
- };
505
-
506
- var StatusCodeColor;
507
- (function (StatusCodeColor) {
508
- StatusCodeColor["Success"] = "#69AB32";
509
- StatusCodeColor["Warning"] = "#F0BB4B";
510
- StatusCodeColor["Danger"] = "#E95F5D";
511
- })(StatusCodeColor || (StatusCodeColor = {}));
512
- /**
513
- * Returns a HEX color for a given response status code number.
514
- */
515
- function getStatusCodeColor(status) {
516
- if (status < 300) {
517
- return StatusCodeColor.Success;
518
- }
519
- if (status < 400) {
520
- return StatusCodeColor.Warning;
521
- }
522
- return StatusCodeColor.Danger;
523
- }
524
-
525
- /**
526
- * Returns a timestamp string in a "HH:MM:SS" format.
527
- */
528
- function getTimestamp() {
529
- const now = new Date();
530
- return [now.getHours(), now.getMinutes(), now.getSeconds()]
531
- .map(String)
532
- .map((chunk) => chunk.slice(0, 2))
533
- .map((chunk) => chunk.padStart(2, '0'))
534
- .join(':');
535
- }
536
-
537
- /**
538
- * Formats a mocked request for introspection in browser's console.
539
- */
540
- function prepareRequest(request) {
541
- return Object.assign(Object.assign({}, request), { headers: request.headers.all() });
542
- }
543
-
544
- /**
545
- * Formats a mocked response for introspection in the browser's console.
546
- */
547
- function prepareResponse(res) {
548
- const responseHeaders = lib$1.objectToHeaders(res.headers);
549
- return Object.assign(Object.assign({}, res), {
550
- // Parse a response JSON body for preview in the logs
551
- body: parseBody(res.body, responseHeaders) });
552
- }
553
-
554
- /**
555
- * Tokenize input string.
556
- */
557
- function lexer(str) {
558
- var tokens = [];
559
- var i = 0;
560
- while (i < str.length) {
561
- var char = str[i];
562
- if (char === "*" || char === "+" || char === "?") {
563
- tokens.push({ type: "MODIFIER", index: i, value: str[i++] });
564
- continue;
565
- }
566
- if (char === "\\") {
567
- tokens.push({ type: "ESCAPED_CHAR", index: i++, value: str[i++] });
568
- continue;
569
- }
570
- if (char === "{") {
571
- tokens.push({ type: "OPEN", index: i, value: str[i++] });
572
- continue;
573
- }
574
- if (char === "}") {
575
- tokens.push({ type: "CLOSE", index: i, value: str[i++] });
576
- continue;
577
- }
578
- if (char === ":") {
579
- var name = "";
580
- var j = i + 1;
581
- while (j < str.length) {
582
- var code = str.charCodeAt(j);
583
- if (
584
- // `0-9`
585
- (code >= 48 && code <= 57) ||
586
- // `A-Z`
587
- (code >= 65 && code <= 90) ||
588
- // `a-z`
589
- (code >= 97 && code <= 122) ||
590
- // `_`
591
- code === 95) {
592
- name += str[j++];
593
- continue;
594
- }
595
- break;
596
- }
597
- if (!name)
598
- throw new TypeError("Missing parameter name at " + i);
599
- tokens.push({ type: "NAME", index: i, value: name });
600
- i = j;
601
- continue;
602
- }
603
- if (char === "(") {
604
- var count = 1;
605
- var pattern = "";
606
- var j = i + 1;
607
- if (str[j] === "?") {
608
- throw new TypeError("Pattern cannot start with \"?\" at " + j);
609
- }
610
- while (j < str.length) {
611
- if (str[j] === "\\") {
612
- pattern += str[j++] + str[j++];
613
- continue;
614
- }
615
- if (str[j] === ")") {
616
- count--;
617
- if (count === 0) {
618
- j++;
619
- break;
620
- }
621
- }
622
- else if (str[j] === "(") {
623
- count++;
624
- if (str[j + 1] !== "?") {
625
- throw new TypeError("Capturing groups are not allowed at " + j);
626
- }
627
- }
628
- pattern += str[j++];
629
- }
630
- if (count)
631
- throw new TypeError("Unbalanced pattern at " + i);
632
- if (!pattern)
633
- throw new TypeError("Missing pattern at " + i);
634
- tokens.push({ type: "PATTERN", index: i, value: pattern });
635
- i = j;
636
- continue;
637
- }
638
- tokens.push({ type: "CHAR", index: i, value: str[i++] });
639
- }
640
- tokens.push({ type: "END", index: i, value: "" });
641
- return tokens;
642
- }
643
- /**
644
- * Parse a string for the raw tokens.
645
- */
646
- function parse(str, options) {
647
- if (options === void 0) { options = {}; }
648
- var tokens = lexer(str);
649
- var _a = options.prefixes, prefixes = _a === void 0 ? "./" : _a;
650
- var defaultPattern = "[^" + escapeString(options.delimiter || "/#?") + "]+?";
651
- var result = [];
652
- var key = 0;
653
- var i = 0;
654
- var path = "";
655
- var tryConsume = function (type) {
656
- if (i < tokens.length && tokens[i].type === type)
657
- return tokens[i++].value;
658
- };
659
- var mustConsume = function (type) {
660
- var value = tryConsume(type);
661
- if (value !== undefined)
662
- return value;
663
- var _a = tokens[i], nextType = _a.type, index = _a.index;
664
- throw new TypeError("Unexpected " + nextType + " at " + index + ", expected " + type);
665
- };
666
- var consumeText = function () {
667
- var result = "";
668
- var value;
669
- // tslint:disable-next-line
670
- while ((value = tryConsume("CHAR") || tryConsume("ESCAPED_CHAR"))) {
671
- result += value;
672
- }
673
- return result;
674
- };
675
- while (i < tokens.length) {
676
- var char = tryConsume("CHAR");
677
- var name = tryConsume("NAME");
678
- var pattern = tryConsume("PATTERN");
679
- if (name || pattern) {
680
- var prefix = char || "";
681
- if (prefixes.indexOf(prefix) === -1) {
682
- path += prefix;
683
- prefix = "";
684
- }
685
- if (path) {
686
- result.push(path);
687
- path = "";
688
- }
689
- result.push({
690
- name: name || key++,
691
- prefix: prefix,
692
- suffix: "",
693
- pattern: pattern || defaultPattern,
694
- modifier: tryConsume("MODIFIER") || ""
695
- });
696
- continue;
697
- }
698
- var value = char || tryConsume("ESCAPED_CHAR");
699
- if (value) {
700
- path += value;
701
- continue;
702
- }
703
- if (path) {
704
- result.push(path);
705
- path = "";
706
- }
707
- var open = tryConsume("OPEN");
708
- if (open) {
709
- var prefix = consumeText();
710
- var name_1 = tryConsume("NAME") || "";
711
- var pattern_1 = tryConsume("PATTERN") || "";
712
- var suffix = consumeText();
713
- mustConsume("CLOSE");
714
- result.push({
715
- name: name_1 || (pattern_1 ? key++ : ""),
716
- pattern: name_1 && !pattern_1 ? defaultPattern : pattern_1,
717
- prefix: prefix,
718
- suffix: suffix,
719
- modifier: tryConsume("MODIFIER") || ""
720
- });
721
- continue;
722
- }
723
- mustConsume("END");
724
- }
725
- return result;
726
- }
727
- /**
728
- * Create path match function from `path-to-regexp` spec.
729
- */
730
- function match(str, options) {
731
- var keys = [];
732
- var re = pathToRegexp(str, keys, options);
733
- return regexpToFunction(re, keys, options);
734
- }
735
- /**
736
- * Create a path match function from `path-to-regexp` output.
737
- */
738
- function regexpToFunction(re, keys, options) {
739
- if (options === void 0) { options = {}; }
740
- var _a = options.decode, decode = _a === void 0 ? function (x) { return x; } : _a;
741
- return function (pathname) {
742
- var m = re.exec(pathname);
743
- if (!m)
744
- return false;
745
- var path = m[0], index = m.index;
746
- var params = Object.create(null);
747
- var _loop_1 = function (i) {
748
- // tslint:disable-next-line
749
- if (m[i] === undefined)
750
- return "continue";
751
- var key = keys[i - 1];
752
- if (key.modifier === "*" || key.modifier === "+") {
753
- params[key.name] = m[i].split(key.prefix + key.suffix).map(function (value) {
754
- return decode(value, key);
755
- });
756
- }
757
- else {
758
- params[key.name] = decode(m[i], key);
759
- }
760
- };
761
- for (var i = 1; i < m.length; i++) {
762
- _loop_1(i);
763
- }
764
- return { path: path, index: index, params: params };
765
- };
766
- }
767
- /**
768
- * Escape a regular expression string.
769
- */
770
- function escapeString(str) {
771
- return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1");
772
- }
773
- /**
774
- * Get the flags for a regexp from the options.
775
- */
776
- function flags(options) {
777
- return options && options.sensitive ? "" : "i";
778
- }
779
- /**
780
- * Pull out keys from a regexp.
781
- */
782
- function regexpToRegexp(path, keys) {
783
- if (!keys)
784
- return path;
785
- var groupsRegex = /\((?:\?<(.*?)>)?(?!\?)/g;
786
- var index = 0;
787
- var execResult = groupsRegex.exec(path.source);
788
- while (execResult) {
789
- keys.push({
790
- // Use parenthesized substring match if available, index otherwise
791
- name: execResult[1] || index++,
792
- prefix: "",
793
- suffix: "",
794
- modifier: "",
795
- pattern: ""
796
- });
797
- execResult = groupsRegex.exec(path.source);
798
- }
799
- return path;
800
- }
801
- /**
802
- * Transform an array into a regexp.
803
- */
804
- function arrayToRegexp(paths, keys, options) {
805
- var parts = paths.map(function (path) { return pathToRegexp(path, keys, options).source; });
806
- return new RegExp("(?:" + parts.join("|") + ")", flags(options));
807
- }
808
- /**
809
- * Create a path regexp from string input.
810
- */
811
- function stringToRegexp(path, keys, options) {
812
- return tokensToRegexp(parse(path, options), keys, options);
813
- }
814
- /**
815
- * Expose a function for taking tokens and returning a RegExp.
816
- */
817
- function tokensToRegexp(tokens, keys, options) {
818
- if (options === void 0) { options = {}; }
819
- var _a = options.strict, strict = _a === void 0 ? false : _a, _b = options.start, start = _b === void 0 ? true : _b, _c = options.end, end = _c === void 0 ? true : _c, _d = options.encode, encode = _d === void 0 ? function (x) { return x; } : _d;
820
- var endsWith = "[" + escapeString(options.endsWith || "") + "]|$";
821
- var delimiter = "[" + escapeString(options.delimiter || "/#?") + "]";
822
- var route = start ? "^" : "";
823
- // Iterate over the tokens and create our regexp string.
824
- for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
825
- var token = tokens_1[_i];
826
- if (typeof token === "string") {
827
- route += escapeString(encode(token));
828
- }
829
- else {
830
- var prefix = escapeString(encode(token.prefix));
831
- var suffix = escapeString(encode(token.suffix));
832
- if (token.pattern) {
833
- if (keys)
834
- keys.push(token);
835
- if (prefix || suffix) {
836
- if (token.modifier === "+" || token.modifier === "*") {
837
- var mod = token.modifier === "*" ? "?" : "";
838
- route += "(?:" + prefix + "((?:" + token.pattern + ")(?:" + suffix + prefix + "(?:" + token.pattern + "))*)" + suffix + ")" + mod;
839
- }
840
- else {
841
- route += "(?:" + prefix + "(" + token.pattern + ")" + suffix + ")" + token.modifier;
842
- }
843
- }
844
- else {
845
- route += "(" + token.pattern + ")" + token.modifier;
846
- }
847
- }
848
- else {
849
- route += "(?:" + prefix + suffix + ")" + token.modifier;
850
- }
851
- }
852
- }
853
- if (end) {
854
- if (!strict)
855
- route += delimiter + "?";
856
- route += !options.endsWith ? "$" : "(?=" + endsWith + ")";
857
- }
858
- else {
859
- var endToken = tokens[tokens.length - 1];
860
- var isEndDelimited = typeof endToken === "string"
861
- ? delimiter.indexOf(endToken[endToken.length - 1]) > -1
862
- : // tslint:disable-next-line
863
- endToken === undefined;
864
- if (!strict) {
865
- route += "(?:" + delimiter + "(?=" + endsWith + "))?";
866
- }
867
- if (!isEndDelimited) {
868
- route += "(?=" + delimiter + "|" + endsWith + ")";
869
- }
870
- }
871
- return new RegExp(route, flags(options));
872
- }
873
- /**
874
- * Normalize the given path string, returning a regular expression.
875
- *
876
- * An empty array can be passed in for the keys, which will hold the
877
- * placeholder key descriptions. For example, using `/user/:id`, `keys` will
878
- * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
879
- */
880
- function pathToRegexp(path, keys, options) {
881
- if (path instanceof RegExp)
882
- return regexpToRegexp(path, keys);
883
- if (Array.isArray(path))
884
- return arrayToRegexp(path, keys, options);
885
- return stringToRegexp(path, keys, options);
886
- }
887
-
888
- const REDUNDANT_CHARACTERS_EXP = /[\?|#].*$/g;
889
- function getSearchParams(path) {
890
- return new URL(`/${path}`, 'http://localhost').searchParams;
891
- }
892
- /**
893
- * Removes query parameters and hashes from a given URL string.
894
- */
895
- function cleanUrl(path) {
896
- return path.replace(REDUNDANT_CHARACTERS_EXP, '');
897
- }
898
-
899
- /**
900
- * Determines if the given URL string is an absolute URL.
901
- */
902
- function isAbsoluteUrl(url) {
903
- return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
904
- }
905
-
906
- /**
907
- * Returns an absolute URL based on the given path.
908
- */
909
- function getAbsoluteUrl(path, baseUrl) {
910
- // already absolute URL
911
- if (isAbsoluteUrl(path)) {
912
- return path;
913
- }
914
- // Ignore path with pattern start with *
915
- if (path.startsWith('*')) {
916
- return path;
917
- }
918
- // Resolve a relative request URL against a given custom "baseUrl"
919
- // or the document baseURI (in the case of browser/browser-like environments).
920
- const origin = baseUrl || (typeof document !== 'undefined' && document.baseURI);
921
- return origin
922
- ? // Encode and decode the path to preserve escaped characters.
923
- decodeURI(new URL(encodeURI(path), origin).href)
924
- : path;
925
- }
926
-
927
- /**
928
- * Normalizes a given request handler path:
929
- * - Preserves RegExp.
930
- * - Removes query parameters and hashes.
931
- * - Rebases relative URLs against the "baseUrl" or the current location.
932
- * - Preserves relative URLs in Node.js, unless specified otherwise.
933
- */
934
- function normalizePath(path, baseUrl) {
935
- // RegExp paths do not need normalization.
936
- if (path instanceof RegExp) {
937
- return path;
938
- }
939
- const maybeAbsoluteUrl = getAbsoluteUrl(path, baseUrl);
940
- return cleanUrl(maybeAbsoluteUrl);
941
- }
942
-
943
- /**
944
- * Coerce a path supported by MSW into a path
945
- * supported by "path-to-regexp".
946
- */
947
- function coercePath(path) {
948
- return (path
949
- /**
950
- * Replace wildcards ("*") with unnamed capturing groups
951
- * because "path-to-regexp" doesn't support wildcards.
952
- * Ignore path parameter' modifiers (i.e. ":name*").
953
- */
954
- .replace(/([:a-zA-Z_-]*)(\*{1,2})+/g, (_, parameterName, wildcard) => {
955
- const expression = '(.*)';
956
- if (!parameterName) {
957
- return expression;
958
- }
959
- return parameterName.startsWith(':')
960
- ? `${parameterName}${wildcard}`
961
- : `${parameterName}${expression}`;
962
- })
963
- /**
964
- * Escape the port so that "path-to-regexp" can match
965
- * absolute URLs including port numbers.
966
- */
967
- .replace(/([^\/])(:)(?=\d+)/, '$1\\$2')
968
- /**
969
- * Escape the protocol so that "path-to-regexp" could match
970
- * absolute URL.
971
- * @see https://github.com/pillarjs/path-to-regexp/issues/259
972
- */
973
- .replace(/^([^\/]+)(:)(?=\/\/)/, '$1\\$2'));
974
- }
975
- /**
976
- * Returns the result of matching given request URL against a mask.
977
- */
978
- function matchRequestUrl(url, path, baseUrl) {
979
- const normalizedPath = normalizePath(path, baseUrl);
980
- const cleanPath = typeof normalizedPath === 'string'
981
- ? coercePath(normalizedPath)
982
- : normalizedPath;
983
- const cleanUrl = getCleanUrl(url);
984
- const result = match(cleanPath, { decode: decodeURIComponent })(cleanUrl);
985
- const params = (result && result.params) || {};
986
- return {
987
- matches: result !== false,
988
- params,
989
- };
990
- }
991
-
992
- export { NetworkError as N, RequestHandler as R, __awaiter as _, parseBody 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, getStatusCodeColor as l, matchRequestUrl as m, getTimestamp as n, __rest as o, passthrough as p, response as r };