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
package/lib/esm/index.js CHANGED
@@ -1,1731 +1,2109 @@
1
- export { i as context } from './index-deps.js';
2
- import { c as commonjsGlobal, p as parse_1, l as lib$2, a as lib$3, j as jsonParse } from './fetch-deps.js';
3
- import { _ as __awaiter, d as devUtils, p as passthrough, a as parseBody, g as getPublicUrlFromRequest, N as NetworkError } from './matchRequestUrl-deps.js';
4
- export { R as RequestHandler, h as cleanUrl, f as compose, c as createResponseComposition, e as defaultContext, b as defaultResponse, m as matchRequestUrl, r as response } from './matchRequestUrl-deps.js';
5
- import { store } from '@mswjs/cookies';
6
- import { i as isStringEqual, R as RestHandler } from './rest-deps.js';
7
- export { a as RESTMethods, R as RestHandler, r as rest, b as restContext } from './rest-deps.js';
8
- import { t as tryCatch, p as parseGraphQLRequest, G as GraphQLHandler } from './graphql-deps.js';
9
- export { G as GraphQLHandler, g as graphql, a as graphqlContext } from './graphql-deps.js';
10
- import { m as mergeRight } from './errors-deps.js';
11
- import { createInterceptor } from '@mswjs/interceptors';
12
- import { interceptFetch } from '@mswjs/interceptors/lib/interceptors/fetch';
13
- import { interceptXMLHttpRequest } from '@mswjs/interceptors/lib/interceptors/XMLHttpRequest';
14
- import './xml-deps.js';
15
- import '@mswjs/interceptors/lib/utils/getCleanUrl';
16
-
17
- var lib$1 = {};
18
-
19
- var StrictEventEmitter$1 = {};
20
-
21
- var events = {exports: {}};
22
-
23
- var R = typeof Reflect === 'object' ? Reflect : null;
24
- var ReflectApply = R && typeof R.apply === 'function'
25
- ? R.apply
26
- : function ReflectApply(target, receiver, args) {
27
- return Function.prototype.apply.call(target, receiver, args);
28
- };
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
25
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
26
+ }) : x)(function(x) {
27
+ if (typeof require !== "undefined")
28
+ return require.apply(this, arguments);
29
+ throw new Error('Dynamic require of "' + x + '" is not supported');
30
+ });
31
+ var __objRest = (source, exclude) => {
32
+ var target = {};
33
+ for (var prop in source)
34
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
35
+ target[prop] = source[prop];
36
+ if (source != null && __getOwnPropSymbols)
37
+ for (var prop of __getOwnPropSymbols(source)) {
38
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
39
+ target[prop] = source[prop];
40
+ }
41
+ return target;
42
+ };
43
+ var __esm = (fn, res) => function __init() {
44
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
45
+ };
46
+ var __commonJS = (cb, mod) => function __require2() {
47
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
48
+ };
49
+ var __export = (target, all) => {
50
+ for (var name in all)
51
+ __defProp(target, name, { get: all[name], enumerable: true });
52
+ };
53
+ var __copyProps = (to, from, except, desc) => {
54
+ if (from && typeof from === "object" || typeof from === "function") {
55
+ for (let key of __getOwnPropNames(from))
56
+ if (!__hasOwnProp.call(to, key) && key !== except)
57
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
58
+ }
59
+ return to;
60
+ };
61
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
29
62
 
30
- var ReflectOwnKeys;
31
- if (R && typeof R.ownKeys === 'function') {
32
- ReflectOwnKeys = R.ownKeys;
33
- } else if (Object.getOwnPropertySymbols) {
34
- ReflectOwnKeys = function ReflectOwnKeys(target) {
35
- return Object.getOwnPropertyNames(target)
36
- .concat(Object.getOwnPropertySymbols(target));
37
- };
38
- } else {
39
- ReflectOwnKeys = function ReflectOwnKeys(target) {
40
- return Object.getOwnPropertyNames(target);
41
- };
42
- }
63
+ // node_modules/tsup/assets/esm_shims.js
64
+ var init_esm_shims = __esm({
65
+ "node_modules/tsup/assets/esm_shims.js"() {
66
+ }
67
+ });
43
68
 
44
- function ProcessEmitWarning(warning) {
45
- if (console && console.warn) console.warn(warning);
46
- }
69
+ // node_modules/outvariant/lib/format.js
70
+ var require_format = __commonJS({
71
+ "node_modules/outvariant/lib/format.js"(exports) {
72
+ "use strict";
73
+ init_esm_shims();
74
+ Object.defineProperty(exports, "__esModule", { value: true });
75
+ exports.format = void 0;
76
+ var POSITIONALS_EXP = /(%?)(%([sdjo]))/g;
77
+ function serializePositional(positional, flag) {
78
+ switch (flag) {
79
+ case "s":
80
+ return positional;
81
+ case "d":
82
+ case "i":
83
+ return Number(positional);
84
+ case "j":
85
+ return JSON.stringify(positional);
86
+ case "o": {
87
+ if (typeof positional === "string") {
88
+ return positional;
89
+ }
90
+ var json2 = JSON.stringify(positional);
91
+ if (json2 === "{}" || json2 === "[]" || /^\[object .+?\]$/.test(json2)) {
92
+ return positional;
93
+ }
94
+ return json2;
95
+ }
96
+ }
97
+ }
98
+ function format2(message) {
99
+ var positionals = [];
100
+ for (var _i = 1; _i < arguments.length; _i++) {
101
+ positionals[_i - 1] = arguments[_i];
102
+ }
103
+ if (positionals.length === 0) {
104
+ return message;
105
+ }
106
+ var positionalIndex = 0;
107
+ var formattedMessage = message.replace(POSITIONALS_EXP, function(match2, isEscaped, _, flag) {
108
+ var positional = positionals[positionalIndex];
109
+ var value = serializePositional(positional, flag);
110
+ if (!isEscaped) {
111
+ positionalIndex++;
112
+ return value;
113
+ }
114
+ return match2;
115
+ });
116
+ if (positionalIndex < positionals.length) {
117
+ formattedMessage += " " + positionals.slice(positionalIndex).join(" ");
118
+ }
119
+ formattedMessage = formattedMessage.replace(/%{2,2}/g, "%");
120
+ return formattedMessage;
121
+ }
122
+ exports.format = format2;
123
+ }
124
+ });
125
+
126
+ // node_modules/outvariant/lib/invariant.js
127
+ var require_invariant = __commonJS({
128
+ "node_modules/outvariant/lib/invariant.js"(exports) {
129
+ "use strict";
130
+ init_esm_shims();
131
+ var __extends = exports && exports.__extends || function() {
132
+ var extendStatics = function(d, b) {
133
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
134
+ d2.__proto__ = b2;
135
+ } || function(d2, b2) {
136
+ for (var p in b2)
137
+ if (Object.prototype.hasOwnProperty.call(b2, p))
138
+ d2[p] = b2[p];
139
+ };
140
+ return extendStatics(d, b);
141
+ };
142
+ return function(d, b) {
143
+ if (typeof b !== "function" && b !== null)
144
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
145
+ extendStatics(d, b);
146
+ function __() {
147
+ this.constructor = d;
148
+ }
149
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
150
+ };
151
+ }();
152
+ var __spreadArray = exports && exports.__spreadArray || function(to, from) {
153
+ for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
154
+ to[j] = from[i];
155
+ return to;
156
+ };
157
+ Object.defineProperty(exports, "__esModule", { value: true });
158
+ exports.invariant = exports.InvariantError = void 0;
159
+ var format_1 = require_format();
160
+ var STACK_FRAMES_TO_IGNORE = 2;
161
+ var InvariantError = function(_super) {
162
+ __extends(InvariantError2, _super);
163
+ function InvariantError2(message) {
164
+ var positionals = [];
165
+ for (var _i = 1; _i < arguments.length; _i++) {
166
+ positionals[_i - 1] = arguments[_i];
167
+ }
168
+ var _this = _super.call(this, message) || this;
169
+ _this.name = "Invariant Violation";
170
+ _this.message = format_1.format.apply(void 0, __spreadArray([message], positionals));
171
+ if (_this.stack) {
172
+ var nextStack = _this.stack.split("\n");
173
+ nextStack.splice(1, STACK_FRAMES_TO_IGNORE);
174
+ _this.stack = nextStack.join("\n");
175
+ }
176
+ return _this;
177
+ }
178
+ return InvariantError2;
179
+ }(Error);
180
+ exports.InvariantError = InvariantError;
181
+ function invariant(predicate, message) {
182
+ var positionals = [];
183
+ for (var _i = 2; _i < arguments.length; _i++) {
184
+ positionals[_i - 2] = arguments[_i];
185
+ }
186
+ if (!predicate) {
187
+ throw new (InvariantError.bind.apply(InvariantError, __spreadArray([void 0, message], positionals)))();
188
+ }
189
+ }
190
+ exports.invariant = invariant;
191
+ }
192
+ });
193
+
194
+ // node_modules/outvariant/lib/index.js
195
+ var require_lib = __commonJS({
196
+ "node_modules/outvariant/lib/index.js"(exports) {
197
+ "use strict";
198
+ init_esm_shims();
199
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
200
+ if (k2 === void 0)
201
+ k2 = k;
202
+ Object.defineProperty(o, k2, { enumerable: true, get: function() {
203
+ return m[k];
204
+ } });
205
+ } : function(o, m, k, k2) {
206
+ if (k2 === void 0)
207
+ k2 = k;
208
+ o[k2] = m[k];
209
+ });
210
+ var __exportStar = exports && exports.__exportStar || function(m, exports2) {
211
+ for (var p in m)
212
+ if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
213
+ __createBinding(exports2, m, p);
214
+ };
215
+ Object.defineProperty(exports, "__esModule", { value: true });
216
+ __exportStar(require_invariant(), exports);
217
+ __exportStar(require_format(), exports);
218
+ }
219
+ });
47
220
 
48
- var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
49
- return value !== value;
221
+ // src/index.ts
222
+ init_esm_shims();
223
+
224
+ // src/context/index.ts
225
+ var context_exports = {};
226
+ __export(context_exports, {
227
+ body: () => body,
228
+ cookie: () => cookie,
229
+ data: () => data,
230
+ delay: () => delay,
231
+ errors: () => errors,
232
+ extensions: () => extensions,
233
+ fetch: () => fetch,
234
+ json: () => json,
235
+ set: () => set,
236
+ status: () => status,
237
+ text: () => text,
238
+ xml: () => xml
239
+ });
240
+ init_esm_shims();
241
+
242
+ // src/context/status.ts
243
+ init_esm_shims();
244
+ import statuses from "statuses/codes.json";
245
+ var status = (statusCode, statusText) => {
246
+ return (res) => {
247
+ res.status = statusCode;
248
+ res.statusText = statusText || statuses[String(statusCode)];
249
+ return res;
250
+ };
50
251
  };
51
252
 
52
- function EventEmitter() {
53
- EventEmitter.init.call(this);
253
+ // src/context/set.ts
254
+ init_esm_shims();
255
+ import { objectToHeaders } from "headers-polyfill";
256
+ function set(...args) {
257
+ return (res) => {
258
+ const [name, value] = args;
259
+ if (typeof name === "string") {
260
+ res.headers.append(name, value);
261
+ } else {
262
+ const headers = objectToHeaders(name);
263
+ headers.forEach((value2, name2) => {
264
+ res.headers.append(name2, value2);
265
+ });
266
+ }
267
+ return res;
268
+ };
54
269
  }
55
- events.exports = EventEmitter;
56
- events.exports.once = once;
57
270
 
58
- // Backwards-compat with node 0.10.x
59
- EventEmitter.EventEmitter = EventEmitter;
271
+ // src/context/cookie.ts
272
+ init_esm_shims();
273
+ import * as cookieUtils from "cookie";
274
+ var cookie = (name, value, options) => {
275
+ return (res) => {
276
+ const serializedCookie = cookieUtils.serialize(name, value, options);
277
+ res.headers.set("Set-Cookie", serializedCookie);
278
+ if (typeof document !== "undefined") {
279
+ document.cookie = serializedCookie;
280
+ }
281
+ return res;
282
+ };
283
+ };
60
284
 
61
- EventEmitter.prototype._events = undefined;
62
- EventEmitter.prototype._eventsCount = 0;
63
- EventEmitter.prototype._maxListeners = undefined;
285
+ // src/context/body.ts
286
+ init_esm_shims();
287
+ var body = (value) => {
288
+ return (res) => {
289
+ res.body = value;
290
+ return res;
291
+ };
292
+ };
64
293
 
65
- // By default EventEmitters will print a warning if more than 10 listeners are
66
- // added to it. This is a useful default which helps finding memory leaks.
67
- var defaultMaxListeners = 10;
294
+ // src/context/data.ts
295
+ init_esm_shims();
68
296
 
69
- function checkListener(listener) {
70
- if (typeof listener !== 'function') {
71
- throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
297
+ // src/utils/internal/jsonParse.ts
298
+ init_esm_shims();
299
+ function jsonParse(value) {
300
+ try {
301
+ return JSON.parse(value);
302
+ } catch (error2) {
303
+ return void 0;
72
304
  }
73
305
  }
74
306
 
75
- Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
76
- enumerable: true,
77
- get: function() {
78
- return defaultMaxListeners;
79
- },
80
- set: function(arg) {
81
- if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
82
- throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
307
+ // src/utils/internal/mergeRight.ts
308
+ init_esm_shims();
309
+
310
+ // src/utils/internal/isObject.ts
311
+ init_esm_shims();
312
+ function isObject(value) {
313
+ return value != null && typeof value === "object" && !Array.isArray(value);
314
+ }
315
+
316
+ // src/utils/internal/mergeRight.ts
317
+ function mergeRight(left, right) {
318
+ return Object.entries(right).reduce((result, [key, rightValue]) => {
319
+ const leftValue = result[key];
320
+ if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
321
+ result[key] = leftValue.concat(rightValue);
322
+ return result;
83
323
  }
84
- defaultMaxListeners = arg;
85
- }
86
- });
324
+ if (isObject(leftValue) && isObject(rightValue)) {
325
+ result[key] = mergeRight(leftValue, rightValue);
326
+ return result;
327
+ }
328
+ result[key] = rightValue;
329
+ return result;
330
+ }, Object.assign({}, left));
331
+ }
87
332
 
88
- EventEmitter.init = function() {
333
+ // src/context/json.ts
334
+ init_esm_shims();
335
+ var json = (body2) => {
336
+ return (res) => {
337
+ res.headers.set("Content-Type", "application/json");
338
+ res.body = JSON.stringify(body2);
339
+ return res;
340
+ };
341
+ };
89
342
 
90
- if (this._events === undefined ||
91
- this._events === Object.getPrototypeOf(this)._events) {
92
- this._events = Object.create(null);
93
- this._eventsCount = 0;
94
- }
343
+ // src/context/data.ts
344
+ var data = (payload) => {
345
+ return (res) => {
346
+ const prevBody = jsonParse(res.body) || {};
347
+ const nextBody = mergeRight(prevBody, { data: payload });
348
+ return json(nextBody)(res);
349
+ };
350
+ };
95
351
 
96
- this._maxListeners = this._maxListeners || undefined;
352
+ // src/context/extensions.ts
353
+ init_esm_shims();
354
+ var extensions = (payload) => {
355
+ return (res) => {
356
+ const prevBody = jsonParse(res.body) || {};
357
+ const nextBody = mergeRight(prevBody, { extensions: payload });
358
+ return json(nextBody)(res);
359
+ };
97
360
  };
98
361
 
99
- // Obviously not all Emitters should be limited to 10. This function allows
100
- // that to be increased. Set to zero for unlimited.
101
- EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
102
- if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
103
- throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
362
+ // src/context/delay.ts
363
+ init_esm_shims();
364
+ import { isNodeProcess } from "is-node-process";
365
+ var SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647;
366
+ var MIN_SERVER_RESPONSE_TIME = 100;
367
+ var MAX_SERVER_RESPONSE_TIME = 400;
368
+ var NODE_SERVER_RESPONSE_TIME = 5;
369
+ var getRandomServerResponseTime = () => {
370
+ if (isNodeProcess()) {
371
+ return NODE_SERVER_RESPONSE_TIME;
104
372
  }
105
- this._maxListeners = n;
106
- return this;
373
+ return Math.floor(Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) + MIN_SERVER_RESPONSE_TIME);
374
+ };
375
+ var delay = (durationOrMode) => {
376
+ return (res) => {
377
+ let delayTime;
378
+ if (typeof durationOrMode === "string") {
379
+ switch (durationOrMode) {
380
+ case "infinite": {
381
+ delayTime = SET_TIMEOUT_MAX_ALLOWED_INT;
382
+ break;
383
+ }
384
+ case "real": {
385
+ delayTime = getRandomServerResponseTime();
386
+ break;
387
+ }
388
+ default: {
389
+ throw new Error(`Failed to delay a response: unknown delay mode "${durationOrMode}". Please make sure you provide one of the supported modes ("real", "infinite") or a number to "ctx.delay".`);
390
+ }
391
+ }
392
+ } else if (typeof durationOrMode === "undefined") {
393
+ delayTime = getRandomServerResponseTime();
394
+ } else {
395
+ if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {
396
+ throw new Error(`Failed to delay a response: provided delay duration (${durationOrMode}) exceeds the maximum allowed duration for "setTimeout" (${SET_TIMEOUT_MAX_ALLOWED_INT}). This will cause the response to be returned immediately. Please use a number within the allowed range to delay the response by exact duration, or consider the "infinite" delay mode to delay the response indefinitely.`);
397
+ }
398
+ delayTime = durationOrMode;
399
+ }
400
+ res.delay = delayTime;
401
+ return res;
402
+ };
107
403
  };
108
404
 
109
- function _getMaxListeners(that) {
110
- if (that._maxListeners === undefined)
111
- return EventEmitter.defaultMaxListeners;
112
- return that._maxListeners;
113
- }
405
+ // src/context/errors.ts
406
+ init_esm_shims();
407
+ var errors = (errorsList) => {
408
+ return (res) => {
409
+ if (errorsList == null) {
410
+ return res;
411
+ }
412
+ const prevBody = jsonParse(res.body) || {};
413
+ const nextBody = mergeRight(prevBody, { errors: errorsList });
414
+ return json(nextBody)(res);
415
+ };
416
+ };
114
417
 
115
- EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
116
- return _getMaxListeners(this);
418
+ // src/context/fetch.ts
419
+ init_esm_shims();
420
+ import { isNodeProcess as isNodeProcess2 } from "is-node-process";
421
+ import { Headers } from "headers-polyfill";
422
+ var useFetch = isNodeProcess2() ? __require("node-fetch") : window.fetch;
423
+ var augmentRequestInit = (requestInit) => {
424
+ const headers = new Headers(requestInit.headers);
425
+ headers.set("x-msw-bypass", "true");
426
+ return __spreadProps(__spreadValues({}, requestInit), {
427
+ headers: headers.all()
428
+ });
429
+ };
430
+ var createFetchRequestParameters = (input) => {
431
+ const { body: body2, method } = input;
432
+ const requestParameters = __spreadProps(__spreadValues({}, input), {
433
+ body: void 0
434
+ });
435
+ if (["GET", "HEAD"].includes(method)) {
436
+ return requestParameters;
437
+ }
438
+ if (typeof body2 === "object" || typeof body2 === "number" || typeof body2 === "boolean") {
439
+ requestParameters.body = JSON.stringify(body2);
440
+ } else {
441
+ requestParameters.body = body2;
442
+ }
443
+ return requestParameters;
444
+ };
445
+ var fetch = (input, requestInit = {}) => {
446
+ if (typeof input === "string") {
447
+ return useFetch(input, augmentRequestInit(requestInit));
448
+ }
449
+ const requestParameters = createFetchRequestParameters(input);
450
+ const derivedRequestInit = augmentRequestInit(requestParameters);
451
+ return useFetch(input.url.href, derivedRequestInit);
117
452
  };
118
453
 
119
- EventEmitter.prototype.emit = function emit(type) {
120
- var args = [];
121
- for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
122
- var doError = (type === 'error');
454
+ // src/context/text.ts
455
+ init_esm_shims();
456
+ var text = (body2) => {
457
+ return (res) => {
458
+ res.headers.set("Content-Type", "text/plain");
459
+ res.body = body2;
460
+ return res;
461
+ };
462
+ };
123
463
 
124
- var events = this._events;
125
- if (events !== undefined)
126
- doError = (doError && events.error === undefined);
127
- else if (!doError)
128
- return false;
464
+ // src/context/xml.ts
465
+ init_esm_shims();
466
+ var xml = (body2) => {
467
+ return (res) => {
468
+ res.headers.set("Content-Type", "text/xml");
469
+ res.body = body2;
470
+ return res;
471
+ };
472
+ };
129
473
 
130
- // If there is no 'error' event listener then throw.
131
- if (doError) {
132
- var er;
133
- if (args.length > 0)
134
- er = args[0];
135
- if (er instanceof Error) {
136
- // Note: The comments on the `throw` lines are intentional, they show
137
- // up in Node's output if this results in an unhandled exception.
138
- throw er; // Unhandled 'error' event
139
- }
140
- // At least give some kind of context to the user
141
- var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
142
- err.context = er;
143
- throw err; // Unhandled 'error' event
144
- }
474
+ // src/setupWorker/setupWorker.ts
475
+ init_esm_shims();
476
+ import { isNodeProcess as isNodeProcess3 } from "is-node-process";
477
+ import { StrictEventEmitter } from "strict-event-emitter";
478
+
479
+ // src/setupWorker/start/createStartHandler.ts
480
+ init_esm_shims();
481
+ import { until as until4 } from "@open-draft/until";
482
+
483
+ // src/setupWorker/start/utils/getWorkerInstance.ts
484
+ init_esm_shims();
485
+ import { until } from "@open-draft/until";
486
+
487
+ // src/setupWorker/start/utils/getWorkerByRegistration.ts
488
+ init_esm_shims();
489
+ var getWorkerByRegistration = (registration, absoluteWorkerUrl, findWorker) => {
490
+ const allStates = [
491
+ registration.active,
492
+ registration.installing,
493
+ registration.waiting
494
+ ];
495
+ const existingStates = allStates.filter(Boolean);
496
+ const mockWorker = existingStates.find((worker) => {
497
+ return findWorker(worker.scriptURL, absoluteWorkerUrl);
498
+ });
499
+ return mockWorker || null;
500
+ };
145
501
 
146
- var handler = events[type];
502
+ // src/utils/url/getAbsoluteWorkerUrl.ts
503
+ init_esm_shims();
504
+ function getAbsoluteWorkerUrl(relativeUrl) {
505
+ return new URL(relativeUrl, location.origin).href;
506
+ }
147
507
 
148
- if (handler === undefined)
149
- return false;
508
+ // src/utils/internal/devUtils.ts
509
+ init_esm_shims();
510
+ var import_outvariant = __toESM(require_lib());
511
+ var LIBRARY_PREFIX = "[MSW]";
512
+ function formatMessage(message, ...positionals) {
513
+ const interpolatedMessage = (0, import_outvariant.format)(message, ...positionals);
514
+ return `${LIBRARY_PREFIX} ${interpolatedMessage}`;
515
+ }
516
+ function warn(message, ...positionals) {
517
+ console.warn(formatMessage(message, ...positionals));
518
+ }
519
+ function error(message, ...positionals) {
520
+ console.error(formatMessage(message, ...positionals));
521
+ }
522
+ var devUtils = {
523
+ formatMessage,
524
+ warn,
525
+ error
526
+ };
150
527
 
151
- if (typeof handler === 'function') {
152
- ReflectApply(handler, this, args);
153
- } else {
154
- var len = handler.length;
155
- var listeners = arrayClone(handler, len);
156
- for (var i = 0; i < len; ++i)
157
- ReflectApply(listeners[i], this, args);
528
+ // src/setupWorker/start/utils/getWorkerInstance.ts
529
+ var getWorkerInstance = async (url, options = {}, findWorker) => {
530
+ const absoluteWorkerUrl = getAbsoluteWorkerUrl(url);
531
+ const mockRegistrations = await navigator.serviceWorker.getRegistrations().then((registrations) => registrations.filter((registration) => getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker)));
532
+ if (!navigator.serviceWorker.controller && mockRegistrations.length > 0) {
533
+ location.reload();
534
+ }
535
+ const [existingRegistration] = mockRegistrations;
536
+ if (existingRegistration) {
537
+ return existingRegistration.update().then(() => {
538
+ return [
539
+ getWorkerByRegistration(existingRegistration, absoluteWorkerUrl, findWorker),
540
+ existingRegistration
541
+ ];
542
+ });
158
543
  }
544
+ const [error2, instance] = await until(async () => {
545
+ const registration = await navigator.serviceWorker.register(url, options);
546
+ return [
547
+ getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),
548
+ registration
549
+ ];
550
+ });
551
+ if (error2) {
552
+ const isWorkerMissing = error2.message.includes("(404)");
553
+ if (isWorkerMissing) {
554
+ const scopeUrl = new URL((options == null ? void 0 : options.scope) || "/", location.href);
555
+ throw new Error(devUtils.formatMessage(`Failed to register a Service Worker for scope ('${scopeUrl.href}') with script ('${absoluteWorkerUrl}'): Service Worker script does not exist at the given path.
556
+
557
+ Did you forget to run "npx msw init <PUBLIC_DIR>"?
159
558
 
160
- return true;
559
+ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/init`));
560
+ }
561
+ throw new Error(devUtils.formatMessage("Failed to register the Service Worker:\n\n%s", error2.message));
562
+ }
563
+ return instance;
161
564
  };
162
565
 
163
- function _addListener(target, type, listener, prepend) {
164
- var m;
165
- var events;
166
- var existing;
566
+ // src/setupWorker/start/utils/enableMocking.ts
567
+ init_esm_shims();
167
568
 
168
- checkListener(listener);
569
+ // src/setupWorker/start/utils/printStartMessage.ts
570
+ init_esm_shims();
571
+ function printStartMessage(args = {}) {
572
+ if (args.quiet) {
573
+ return;
574
+ }
575
+ const message = args.message || "Mocking enabled.";
576
+ console.groupCollapsed(`%c${devUtils.formatMessage(message)}`, "color:orangered;font-weight:bold;");
577
+ console.log("%cDocumentation: %chttps://mswjs.io/docs", "font-weight:bold", "font-weight:normal");
578
+ console.log("Found an issue? https://github.com/mswjs/msw/issues");
579
+ if (args.workerUrl) {
580
+ console.log("Worker script URL:", args.workerUrl);
581
+ }
582
+ if (args.workerScope) {
583
+ console.log("Worker scope:", args.workerScope);
584
+ }
585
+ console.groupEnd();
586
+ }
169
587
 
170
- events = target._events;
171
- if (events === undefined) {
172
- events = target._events = Object.create(null);
173
- target._eventsCount = 0;
174
- } else {
175
- // To avoid recursion in the case that type === "newListener"! Before
176
- // adding it to the listeners, first emit "newListener".
177
- if (events.newListener !== undefined) {
178
- target.emit('newListener', type,
179
- listener.listener ? listener.listener : listener);
180
-
181
- // Re-assign `events` because a newListener handler could have caused the
182
- // this._events to be assigned to a new object
183
- events = target._events;
184
- }
185
- existing = events[type];
588
+ // src/setupWorker/start/utils/enableMocking.ts
589
+ async function enableMocking(context, options) {
590
+ var _a, _b;
591
+ context.workerChannel.send("MOCK_ACTIVATE");
592
+ await context.events.once("MOCKING_ENABLED");
593
+ if (context.isMockingEnabled) {
594
+ devUtils.warn(`Found a redundant "worker.start()" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this "worker.start()" call.`);
595
+ return;
186
596
  }
597
+ context.isMockingEnabled = true;
598
+ printStartMessage({
599
+ quiet: options.quiet,
600
+ workerScope: (_a = context.registration) == null ? void 0 : _a.scope,
601
+ workerUrl: (_b = context.worker) == null ? void 0 : _b.scriptURL
602
+ });
603
+ }
187
604
 
188
- if (existing === undefined) {
189
- // Optimize the case of one listener. Don't need the extra array object.
190
- existing = events[type] = listener;
191
- ++target._eventsCount;
192
- } else {
193
- if (typeof existing === 'function') {
194
- // Adding the second element, need to change to array.
195
- existing = events[type] =
196
- prepend ? [listener, existing] : [existing, listener];
197
- // If we've already got an array, just append.
198
- } else if (prepend) {
199
- existing.unshift(listener);
200
- } else {
201
- existing.push(listener);
605
+ // src/utils/worker/createRequestListener.ts
606
+ init_esm_shims();
607
+
608
+ // src/utils/createBroadcastChannel.ts
609
+ init_esm_shims();
610
+ var createBroadcastChannel = (event) => {
611
+ const port = event.ports[0];
612
+ return {
613
+ send(message) {
614
+ if (port) {
615
+ port.postMessage(message);
616
+ }
202
617
  }
618
+ };
619
+ };
203
620
 
204
- // Check for listener leak
205
- m = _getMaxListeners(target);
206
- if (m > 0 && existing.length > m && !existing.warned) {
207
- existing.warned = true;
208
- // No error code for this since it is a Warning
209
- // eslint-disable-next-line no-restricted-syntax
210
- var w = new Error('Possible EventEmitter memory leak detected. ' +
211
- existing.length + ' ' + String(type) + ' listeners ' +
212
- 'added. Use emitter.setMaxListeners() to ' +
213
- 'increase limit');
214
- w.name = 'MaxListenersExceededWarning';
215
- w.emitter = target;
216
- w.type = type;
217
- w.count = existing.length;
218
- ProcessEmitWarning(w);
219
- }
621
+ // src/utils/NetworkError.ts
622
+ init_esm_shims();
623
+ var NetworkError = class extends Error {
624
+ constructor(message) {
625
+ super(message);
626
+ this.name = "NetworkError";
220
627
  }
628
+ };
221
629
 
222
- return target;
630
+ // src/utils/request/parseWorkerRequest.ts
631
+ init_esm_shims();
632
+ import { Headers as Headers4 } from "headers-polyfill";
633
+
634
+ // src/handlers/RequestHandler.ts
635
+ init_esm_shims();
636
+ import { Headers as Headers3 } from "headers-polyfill";
637
+
638
+ // src/response.ts
639
+ init_esm_shims();
640
+ import { Headers as Headers2 } from "headers-polyfill";
641
+
642
+ // src/utils/internal/compose.ts
643
+ init_esm_shims();
644
+ function compose(...fns) {
645
+ return (...args) => {
646
+ return fns.reduceRight((leftFn, rightFn) => {
647
+ return leftFn instanceof Promise ? Promise.resolve(leftFn).then(rightFn) : rightFn(leftFn);
648
+ }, args[0]);
649
+ };
223
650
  }
224
651
 
225
- EventEmitter.prototype.addListener = function addListener(type, listener) {
226
- return _addListener(this, type, listener, false);
652
+ // src/response.ts
653
+ var defaultResponse = {
654
+ status: 200,
655
+ statusText: "OK",
656
+ body: null,
657
+ delay: 0,
658
+ once: false,
659
+ passthrough: false
227
660
  };
661
+ var defaultResponseTransformers = [];
662
+ function createResponseComposition(responseOverrides, defaultTransformers = defaultResponseTransformers) {
663
+ return async (...transformers) => {
664
+ const initialResponse = Object.assign({}, defaultResponse, {
665
+ headers: new Headers2({
666
+ "x-powered-by": "msw"
667
+ })
668
+ }, responseOverrides);
669
+ const resolvedTransformers = [
670
+ ...defaultTransformers,
671
+ ...transformers
672
+ ].filter(Boolean);
673
+ const resolvedResponse = resolvedTransformers.length > 0 ? compose(...resolvedTransformers)(initialResponse) : initialResponse;
674
+ return resolvedResponse;
675
+ };
676
+ }
677
+ var response = Object.assign(createResponseComposition(), {
678
+ once: createResponseComposition({ once: true }),
679
+ networkError(message) {
680
+ throw new NetworkError(message);
681
+ }
682
+ });
228
683
 
229
- EventEmitter.prototype.on = EventEmitter.prototype.addListener;
230
-
231
- EventEmitter.prototype.prependListener =
232
- function prependListener(type, listener) {
233
- return _addListener(this, type, listener, true);
234
- };
235
-
236
- function onceWrapper() {
237
- if (!this.fired) {
238
- this.target.removeListener(this.type, this.wrapFn);
239
- this.fired = true;
240
- if (arguments.length === 0)
241
- return this.listener.call(this.target);
242
- return this.listener.apply(this.target, arguments);
684
+ // src/utils/internal/getCallFrame.ts
685
+ init_esm_shims();
686
+ var SOURCE_FRAME = /\/msw\/src\/(.+)/;
687
+ var BUILD_FRAME = /(node_modules)?[\/\\]lib[\/\\](umd|esm|iief|cjs)[\/\\]|^[^\/\\]*$/;
688
+ function getCallFrame(error2) {
689
+ const stack = error2.stack;
690
+ if (!stack) {
691
+ return;
243
692
  }
693
+ const frames = stack.split("\n").slice(1);
694
+ const declarationFrame = frames.find((frame) => {
695
+ return !(SOURCE_FRAME.test(frame) || BUILD_FRAME.test(frame));
696
+ });
697
+ if (!declarationFrame) {
698
+ return;
699
+ }
700
+ const declarationPath = declarationFrame.replace(/\s*at [^()]*\(([^)]+)\)/, "$1").replace(/^@/, "");
701
+ return declarationPath;
244
702
  }
245
703
 
246
- function _onceWrap(target, type, listener) {
247
- var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
248
- var wrapped = onceWrapper.bind(state);
249
- wrapped.listener = listener;
250
- state.wrapFn = wrapped;
251
- return wrapped;
704
+ // src/utils/internal/isIterable.ts
705
+ init_esm_shims();
706
+ function isIterable(fn) {
707
+ if (!fn) {
708
+ return false;
709
+ }
710
+ return typeof fn[Symbol.iterator] == "function";
252
711
  }
253
712
 
254
- EventEmitter.prototype.once = function once(type, listener) {
255
- checkListener(listener);
256
- this.on(type, _onceWrap(this, type, listener));
257
- return this;
713
+ // src/handlers/RequestHandler.ts
714
+ var defaultContext = {
715
+ status,
716
+ set,
717
+ delay,
718
+ fetch
258
719
  };
259
-
260
- EventEmitter.prototype.prependOnceListener =
261
- function prependOnceListener(type, listener) {
262
- checkListener(listener);
263
- this.prependListener(type, _onceWrap(this, type, listener));
264
- return this;
720
+ var RequestHandler = class {
721
+ constructor(options) {
722
+ this.shouldSkip = false;
723
+ this.ctx = options.ctx || defaultContext;
724
+ this.resolver = options.resolver;
725
+ const callFrame = getCallFrame(new Error());
726
+ this.info = __spreadProps(__spreadValues({}, options.info), {
727
+ callFrame
728
+ });
729
+ }
730
+ parse(_request, _resolutionContext) {
731
+ return null;
732
+ }
733
+ test(request, resolutionContext) {
734
+ return this.predicate(request, this.parse(request, resolutionContext), resolutionContext);
735
+ }
736
+ getPublicRequest(request, _parsedResult) {
737
+ return request;
738
+ }
739
+ markAsSkipped(shouldSkip = true) {
740
+ this.shouldSkip = shouldSkip;
741
+ }
742
+ async run(request, resolutionContext) {
743
+ if (this.shouldSkip) {
744
+ return null;
745
+ }
746
+ const parsedResult = this.parse(request, resolutionContext);
747
+ const shouldIntercept = this.predicate(request, parsedResult, resolutionContext);
748
+ if (!shouldIntercept) {
749
+ return null;
750
+ }
751
+ const publicRequest = this.getPublicRequest(request, parsedResult);
752
+ const executeResolver = this.wrapResolver(this.resolver);
753
+ const mockedResponse = await executeResolver(publicRequest, response, this.ctx);
754
+ return this.createExecutionResult(parsedResult, publicRequest, mockedResponse);
755
+ }
756
+ wrapResolver(resolver) {
757
+ return async (req, res, ctx) => {
758
+ const result = this.resolverGenerator || await resolver(req, res, ctx);
759
+ if (isIterable(result)) {
760
+ const { value, done } = result[Symbol.iterator]().next();
761
+ const nextResponse = await value;
762
+ if (!nextResponse && done) {
763
+ return this.resolverGeneratorResult;
764
+ }
765
+ if (!this.resolverGenerator) {
766
+ this.resolverGenerator = result;
767
+ }
768
+ this.resolverGeneratorResult = nextResponse;
769
+ return nextResponse;
770
+ }
771
+ return result;
265
772
  };
773
+ }
774
+ createExecutionResult(parsedResult, request, response2) {
775
+ return {
776
+ handler: this,
777
+ parsedResult: parsedResult || null,
778
+ request,
779
+ response: response2 || null
780
+ };
781
+ }
782
+ };
783
+ function passthrough() {
784
+ return {
785
+ status: 101,
786
+ statusText: "Continue",
787
+ headers: new Headers3(),
788
+ body: null,
789
+ passthrough: true,
790
+ once: false
791
+ };
792
+ }
266
793
 
267
- // Emits a 'removeListener' event if and only if the listener was removed.
268
- EventEmitter.prototype.removeListener =
269
- function removeListener(type, listener) {
270
- var list, events, position, i, originalListener;
794
+ // src/utils/request/setRequestCookies.ts
795
+ init_esm_shims();
796
+ import * as cookieUtils3 from "cookie";
797
+ import { store } from "@mswjs/cookies";
271
798
 
272
- checkListener(listener);
799
+ // src/utils/request/getRequestCookies.ts
800
+ init_esm_shims();
801
+ import * as cookieUtils2 from "cookie";
802
+ function getAllCookies() {
803
+ return cookieUtils2.parse(document.cookie);
804
+ }
805
+ function getRequestCookies(request) {
806
+ if (typeof document === "undefined" || typeof location === "undefined") {
807
+ return {};
808
+ }
809
+ switch (request.credentials) {
810
+ case "same-origin": {
811
+ return location.origin === request.url.origin ? getAllCookies() : {};
812
+ }
813
+ case "include": {
814
+ return getAllCookies();
815
+ }
816
+ default: {
817
+ return {};
818
+ }
819
+ }
820
+ }
273
821
 
274
- events = this._events;
275
- if (events === undefined)
276
- return this;
822
+ // src/utils/request/setRequestCookies.ts
823
+ function setRequestCookies(request) {
824
+ var _a;
825
+ const requestCookiesString = request.headers.get("cookie");
826
+ store.hydrate();
827
+ const cookiesFromStore = Array.from((_a = store.get(__spreadProps(__spreadValues({}, request), { url: request.url.toString() }))) == null ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => {
828
+ return Object.assign(cookies, { [name.trim()]: value });
829
+ }, {});
830
+ const cookiesFromDocument = getRequestCookies(request);
831
+ const forwardedCookies = __spreadValues(__spreadValues({}, cookiesFromDocument), cookiesFromStore);
832
+ for (const [name, value] of Object.entries(forwardedCookies)) {
833
+ request.headers.append("cookie", `${name}=${value}`);
834
+ }
835
+ const ownCookies = requestCookiesString ? cookieUtils3.parse(requestCookiesString) : {};
836
+ request.cookies = __spreadValues(__spreadValues(__spreadValues({}, request.cookies), forwardedCookies), ownCookies);
837
+ }
277
838
 
278
- list = events[type];
279
- if (list === undefined)
280
- return this;
839
+ // src/utils/request/parseBody.ts
840
+ init_esm_shims();
841
+
842
+ // src/utils/internal/parseMultipartData.ts
843
+ init_esm_shims();
844
+ import { stringToHeaders } from "headers-polyfill";
845
+ function parseContentHeaders(headersString) {
846
+ var _a, _b;
847
+ const headers = stringToHeaders(headersString);
848
+ const contentType = headers.get("content-type") || "text/plain";
849
+ const disposition = headers.get("content-disposition");
850
+ if (!disposition) {
851
+ throw new Error('"Content-Disposition" header is required.');
852
+ }
853
+ const directives = disposition.split(";").reduce((acc, chunk) => {
854
+ const [name2, ...rest2] = chunk.trim().split("=");
855
+ acc[name2] = rest2.join("=");
856
+ return acc;
857
+ }, {});
858
+ const name = (_a = directives.name) == null ? void 0 : _a.slice(1, -1);
859
+ const filename = (_b = directives.filename) == null ? void 0 : _b.slice(1, -1);
860
+ return {
861
+ name,
862
+ filename,
863
+ contentType
864
+ };
865
+ }
866
+ function parseMultipartData(data2, headers) {
867
+ const contentType = headers == null ? void 0 : headers.get("content-type");
868
+ if (!contentType) {
869
+ return void 0;
870
+ }
871
+ const [, ...directives] = contentType.split(/; */);
872
+ const boundary = directives.filter((d) => d.startsWith("boundary=")).map((s) => s.replace(/^boundary=/, ""))[0];
873
+ if (!boundary) {
874
+ return void 0;
875
+ }
876
+ const boundaryRegExp = new RegExp(`--+${boundary}`);
877
+ const fields = data2.split(boundaryRegExp).filter((chunk) => chunk.startsWith("\r\n") && chunk.endsWith("\r\n")).map((chunk) => chunk.trimStart().replace(/\r\n$/, ""));
878
+ if (!fields.length) {
879
+ return void 0;
880
+ }
881
+ const parsedBody = {};
882
+ try {
883
+ for (const field of fields) {
884
+ const [contentHeaders, ...rest2] = field.split("\r\n\r\n");
885
+ const contentBody = rest2.join("\r\n\r\n");
886
+ const { contentType: contentType2, filename, name } = parseContentHeaders(contentHeaders);
887
+ const value = filename === void 0 ? contentBody : new File([contentBody], filename, { type: contentType2 });
888
+ const parsedValue = parsedBody[name];
889
+ if (parsedValue === void 0) {
890
+ parsedBody[name] = value;
891
+ } else if (Array.isArray(parsedValue)) {
892
+ parsedBody[name] = [...parsedValue, value];
893
+ } else {
894
+ parsedBody[name] = [parsedValue, value];
895
+ }
896
+ }
897
+ return parsedBody;
898
+ } catch (error2) {
899
+ return void 0;
900
+ }
901
+ }
281
902
 
282
- if (list === listener || list.listener === listener) {
283
- if (--this._eventsCount === 0)
284
- this._events = Object.create(null);
285
- else {
286
- delete events[type];
287
- if (events.removeListener)
288
- this.emit('removeListener', type, list.listener || listener);
289
- }
290
- } else if (typeof list !== 'function') {
291
- position = -1;
292
-
293
- for (i = list.length - 1; i >= 0; i--) {
294
- if (list[i] === listener || list[i].listener === listener) {
295
- originalListener = list[i].listener;
296
- position = i;
297
- break;
298
- }
299
- }
903
+ // src/utils/request/parseBody.ts
904
+ function parseBody(body2, headers) {
905
+ var _a;
906
+ if (!body2) {
907
+ return body2;
908
+ }
909
+ const contentType = ((_a = headers == null ? void 0 : headers.get("content-type")) == null ? void 0 : _a.toLowerCase()) || "";
910
+ const hasMultipartContent = contentType.startsWith("multipart/form-data");
911
+ if (hasMultipartContent && typeof body2 !== "object") {
912
+ return parseMultipartData(body2.toString(), headers) || body2;
913
+ }
914
+ const hasJsonContent = contentType.includes("json");
915
+ if (hasJsonContent && typeof body2 !== "object") {
916
+ return jsonParse(body2.toString()) || body2;
917
+ }
918
+ return body2;
919
+ }
300
920
 
301
- if (position < 0)
302
- return this;
921
+ // src/utils/request/pruneGetRequestBody.ts
922
+ init_esm_shims();
303
923
 
304
- if (position === 0)
305
- list.shift();
306
- else {
307
- spliceOne(list, position);
308
- }
924
+ // src/utils/internal/isStringEqual.ts
925
+ init_esm_shims();
926
+ function isStringEqual(actual, expected) {
927
+ return actual.toLowerCase() === expected.toLowerCase();
928
+ }
309
929
 
310
- if (list.length === 1)
311
- events[type] = list[0];
930
+ // src/utils/request/pruneGetRequestBody.ts
931
+ function pruneGetRequestBody(request) {
932
+ if (request.method && isStringEqual(request.method, "GET") && request.body === "") {
933
+ return void 0;
934
+ }
935
+ return request.body;
936
+ }
312
937
 
313
- if (events.removeListener !== undefined)
314
- this.emit('removeListener', type, originalListener || listener);
315
- }
938
+ // src/utils/request/parseWorkerRequest.ts
939
+ function parseWorkerRequest(rawRequest) {
940
+ const request = {
941
+ id: rawRequest.id,
942
+ cache: rawRequest.cache,
943
+ credentials: rawRequest.credentials,
944
+ method: rawRequest.method,
945
+ url: new URL(rawRequest.url),
946
+ referrer: rawRequest.referrer,
947
+ referrerPolicy: rawRequest.referrerPolicy,
948
+ redirect: rawRequest.redirect,
949
+ mode: rawRequest.mode,
950
+ params: {},
951
+ cookies: {},
952
+ integrity: rawRequest.integrity,
953
+ keepalive: rawRequest.keepalive,
954
+ destination: rawRequest.destination,
955
+ body: pruneGetRequestBody(rawRequest),
956
+ bodyUsed: rawRequest.bodyUsed,
957
+ headers: new Headers4(rawRequest.headers),
958
+ passthrough
959
+ };
960
+ setRequestCookies(request);
961
+ request.body = parseBody(request.body, request.headers);
962
+ return request;
963
+ }
316
964
 
317
- return this;
965
+ // src/utils/handleRequest.ts
966
+ init_esm_shims();
967
+ import { until as until2 } from "@open-draft/until";
968
+
969
+ // src/utils/getResponse.ts
970
+ init_esm_shims();
971
+ var getResponse = async (request, handlers, resolutionContext) => {
972
+ const relevantHandlers = handlers.filter((handler) => {
973
+ return handler.test(request, resolutionContext);
974
+ });
975
+ if (relevantHandlers.length === 0) {
976
+ return {
977
+ handler: void 0,
978
+ response: void 0
979
+ };
980
+ }
981
+ const result = await relevantHandlers.reduce(async (executionResult, handler) => {
982
+ const previousResults = await executionResult;
983
+ if (!!(previousResults == null ? void 0 : previousResults.response)) {
984
+ return executionResult;
985
+ }
986
+ const result2 = await handler.run(request, resolutionContext);
987
+ if (result2 === null || result2.handler.shouldSkip) {
988
+ return null;
989
+ }
990
+ if (!result2.response) {
991
+ return {
992
+ request: result2.request,
993
+ handler: result2.handler,
994
+ response: void 0,
995
+ parsedResult: result2.parsedResult
996
+ };
997
+ }
998
+ if (result2.response.once) {
999
+ handler.markAsSkipped(true);
1000
+ }
1001
+ return result2;
1002
+ }, Promise.resolve(null));
1003
+ if (!result) {
1004
+ return {
1005
+ handler: void 0,
1006
+ response: void 0
318
1007
  };
1008
+ }
1009
+ return {
1010
+ handler: result.handler,
1011
+ publicRequest: result.request,
1012
+ parsedRequest: result.parsedResult,
1013
+ response: result.response
1014
+ };
1015
+ };
1016
+
1017
+ // src/utils/request/onUnhandledRequest.ts
1018
+ init_esm_shims();
1019
+ import getStringMatchScore from "js-levenshtein";
1020
+
1021
+ // src/utils/internal/parseGraphQLRequest.ts
1022
+ init_esm_shims();
1023
+ import {
1024
+ parse as parse3
1025
+ } from "graphql";
1026
+
1027
+ // src/utils/request/getPublicUrlFromRequest.ts
1028
+ init_esm_shims();
1029
+ var getPublicUrlFromRequest = (request) => {
1030
+ return request.referrer.startsWith(request.url.origin) ? request.url.pathname : new URL(request.url.pathname, `${request.url.protocol}//${request.url.host}`).href;
1031
+ };
319
1032
 
320
- EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
321
-
322
- EventEmitter.prototype.removeAllListeners =
323
- function removeAllListeners(type) {
324
- var listeners, events, i;
325
-
326
- events = this._events;
327
- if (events === undefined)
328
- return this;
329
-
330
- // not listening for removeListener, no need to emit
331
- if (events.removeListener === undefined) {
332
- if (arguments.length === 0) {
333
- this._events = Object.create(null);
334
- this._eventsCount = 0;
335
- } else if (events[type] !== undefined) {
336
- if (--this._eventsCount === 0)
337
- this._events = Object.create(null);
338
- else
339
- delete events[type];
1033
+ // src/utils/internal/parseGraphQLRequest.ts
1034
+ function parseDocumentNode(node) {
1035
+ var _a;
1036
+ const operationDef = node.definitions.find((def) => {
1037
+ return def.kind === "OperationDefinition";
1038
+ });
1039
+ return {
1040
+ operationType: operationDef == null ? void 0 : operationDef.operation,
1041
+ operationName: (_a = operationDef == null ? void 0 : operationDef.name) == null ? void 0 : _a.value
1042
+ };
1043
+ }
1044
+ function parseQuery(query) {
1045
+ try {
1046
+ const ast = parse3(query);
1047
+ return parseDocumentNode(ast);
1048
+ } catch (error2) {
1049
+ return error2;
1050
+ }
1051
+ }
1052
+ function extractMultipartVariables(variables, map, files) {
1053
+ const operations = { variables };
1054
+ for (const [key, pathArray] of Object.entries(map)) {
1055
+ if (!(key in files)) {
1056
+ throw new Error(`Given files do not have a key '${key}' .`);
1057
+ }
1058
+ for (const dotPath of pathArray) {
1059
+ const [lastPath, ...reversedPaths] = dotPath.split(".").reverse();
1060
+ const paths = reversedPaths.reverse();
1061
+ let target = operations;
1062
+ for (const path of paths) {
1063
+ if (!(path in target)) {
1064
+ throw new Error(`Property '${paths}' is not in operations.`);
340
1065
  }
341
- return this;
1066
+ target = target[path];
342
1067
  }
343
-
344
- // emit removeListener for all listeners on all events
345
- if (arguments.length === 0) {
346
- var keys = Object.keys(events);
347
- var key;
348
- for (i = 0; i < keys.length; ++i) {
349
- key = keys[i];
350
- if (key === 'removeListener') continue;
351
- this.removeAllListeners(key);
1068
+ target[lastPath] = files[key];
1069
+ }
1070
+ }
1071
+ return operations.variables;
1072
+ }
1073
+ function getGraphQLInput(request) {
1074
+ var _a, _b;
1075
+ switch (request.method) {
1076
+ case "GET": {
1077
+ const query = request.url.searchParams.get("query");
1078
+ const variables = request.url.searchParams.get("variables") || "";
1079
+ return {
1080
+ query,
1081
+ variables: jsonParse(variables)
1082
+ };
1083
+ }
1084
+ case "POST": {
1085
+ if ((_a = request.body) == null ? void 0 : _a.query) {
1086
+ const { query, variables } = request.body;
1087
+ return {
1088
+ query,
1089
+ variables
1090
+ };
1091
+ }
1092
+ if ((_b = request.body) == null ? void 0 : _b.operations) {
1093
+ const _c = request.body, { operations, map } = _c, files = __objRest(_c, ["operations", "map"]);
1094
+ const parsedOperations = jsonParse(operations) || {};
1095
+ if (!parsedOperations.query) {
1096
+ return null;
352
1097
  }
353
- this.removeAllListeners('removeListener');
354
- this._events = Object.create(null);
355
- this._eventsCount = 0;
356
- return this;
1098
+ const parsedMap = jsonParse(map || "") || {};
1099
+ const variables = parsedOperations.variables ? extractMultipartVariables(parsedOperations.variables, parsedMap, files) : {};
1100
+ return {
1101
+ query: parsedOperations.query,
1102
+ variables
1103
+ };
357
1104
  }
1105
+ }
1106
+ default:
1107
+ return null;
1108
+ }
1109
+ }
1110
+ function parseGraphQLRequest(request) {
1111
+ const input = getGraphQLInput(request);
1112
+ if (!input || !input.query) {
1113
+ return void 0;
1114
+ }
1115
+ const { query, variables } = input;
1116
+ const parsedResult = parseQuery(query);
1117
+ if (parsedResult instanceof Error) {
1118
+ const requestPublicUrl = getPublicUrlFromRequest(request);
1119
+ 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));
1120
+ }
1121
+ return {
1122
+ operationType: parsedResult.operationType,
1123
+ operationName: parsedResult.operationName,
1124
+ variables
1125
+ };
1126
+ }
358
1127
 
359
- listeners = events[type];
1128
+ // src/handlers/RestHandler.ts
1129
+ init_esm_shims();
360
1130
 
361
- if (typeof listeners === 'function') {
362
- this.removeListener(type, listeners);
363
- } else if (listeners !== undefined) {
364
- // LIFO order
365
- for (i = listeners.length - 1; i >= 0; i--) {
366
- this.removeListener(type, listeners[i]);
367
- }
368
- }
1131
+ // src/utils/logging/getStatusCodeColor.ts
1132
+ init_esm_shims();
1133
+ function getStatusCodeColor(status2) {
1134
+ if (status2 < 300) {
1135
+ return "#69AB32" /* Success */;
1136
+ }
1137
+ if (status2 < 400) {
1138
+ return "#F0BB4B" /* Warning */;
1139
+ }
1140
+ return "#E95F5D" /* Danger */;
1141
+ }
369
1142
 
370
- return this;
371
- };
1143
+ // src/utils/logging/getTimestamp.ts
1144
+ init_esm_shims();
1145
+ function getTimestamp() {
1146
+ const now = new Date();
1147
+ return [now.getHours(), now.getMinutes(), now.getSeconds()].map(String).map((chunk) => chunk.slice(0, 2)).map((chunk) => chunk.padStart(2, "0")).join(":");
1148
+ }
372
1149
 
373
- function _listeners(target, type, unwrap) {
374
- var events = target._events;
1150
+ // src/utils/logging/prepareRequest.ts
1151
+ init_esm_shims();
1152
+ function prepareRequest(request) {
1153
+ return __spreadProps(__spreadValues({}, request), {
1154
+ headers: request.headers.all()
1155
+ });
1156
+ }
375
1157
 
376
- if (events === undefined)
377
- return [];
1158
+ // src/utils/logging/prepareResponse.ts
1159
+ init_esm_shims();
1160
+ import { objectToHeaders as objectToHeaders2 } from "headers-polyfill";
1161
+ function prepareResponse(res) {
1162
+ const responseHeaders = objectToHeaders2(res.headers);
1163
+ return __spreadProps(__spreadValues({}, res), {
1164
+ body: parseBody(res.body, responseHeaders)
1165
+ });
1166
+ }
378
1167
 
379
- var evlistener = events[type];
380
- if (evlistener === undefined)
381
- return [];
1168
+ // src/utils/matching/matchRequestUrl.ts
1169
+ init_esm_shims();
1170
+ import { match } from "path-to-regexp";
1171
+ import { getCleanUrl } from "@mswjs/interceptors/lib/utils/getCleanUrl";
382
1172
 
383
- if (typeof evlistener === 'function')
384
- return unwrap ? [evlistener.listener || evlistener] : [evlistener];
1173
+ // src/utils/matching/normalizePath.ts
1174
+ init_esm_shims();
385
1175
 
386
- return unwrap ?
387
- unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
1176
+ // src/utils/url/cleanUrl.ts
1177
+ init_esm_shims();
1178
+ var REDUNDANT_CHARACTERS_EXP = /[\?|#].*$/g;
1179
+ function getSearchParams(path) {
1180
+ return new URL(`/${path}`, "http://localhost").searchParams;
1181
+ }
1182
+ function cleanUrl(path) {
1183
+ return path.replace(REDUNDANT_CHARACTERS_EXP, "");
388
1184
  }
389
1185
 
390
- EventEmitter.prototype.listeners = function listeners(type) {
391
- return _listeners(this, type, true);
392
- };
1186
+ // src/utils/url/getAbsoluteUrl.ts
1187
+ init_esm_shims();
393
1188
 
394
- EventEmitter.prototype.rawListeners = function rawListeners(type) {
395
- return _listeners(this, type, false);
396
- };
1189
+ // src/utils/url/isAbsoluteUrl.ts
1190
+ init_esm_shims();
1191
+ function isAbsoluteUrl(url) {
1192
+ return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
1193
+ }
397
1194
 
398
- EventEmitter.listenerCount = function(emitter, type) {
399
- if (typeof emitter.listenerCount === 'function') {
400
- return emitter.listenerCount(type);
401
- } else {
402
- return listenerCount.call(emitter, type);
1195
+ // src/utils/url/getAbsoluteUrl.ts
1196
+ function getAbsoluteUrl(path, baseUrl) {
1197
+ if (isAbsoluteUrl(path)) {
1198
+ return path;
403
1199
  }
404
- };
405
-
406
- EventEmitter.prototype.listenerCount = listenerCount;
407
- function listenerCount(type) {
408
- var events = this._events;
409
-
410
- if (events !== undefined) {
411
- var evlistener = events[type];
1200
+ if (path.startsWith("*")) {
1201
+ return path;
1202
+ }
1203
+ const origin = baseUrl || typeof document !== "undefined" && document.baseURI;
1204
+ return origin ? decodeURI(new URL(encodeURI(path), origin).href) : path;
1205
+ }
412
1206
 
413
- if (typeof evlistener === 'function') {
414
- return 1;
415
- } else if (evlistener !== undefined) {
416
- return evlistener.length;
417
- }
1207
+ // src/utils/matching/normalizePath.ts
1208
+ function normalizePath(path, baseUrl) {
1209
+ if (path instanceof RegExp) {
1210
+ return path;
418
1211
  }
1212
+ const maybeAbsoluteUrl = getAbsoluteUrl(path, baseUrl);
1213
+ return cleanUrl(maybeAbsoluteUrl);
1214
+ }
419
1215
 
420
- return 0;
1216
+ // src/utils/matching/matchRequestUrl.ts
1217
+ function coercePath(path) {
1218
+ return path.replace(/([:a-zA-Z_-]*)(\*{1,2})+/g, (_, parameterName, wildcard) => {
1219
+ const expression = "(.*)";
1220
+ if (!parameterName) {
1221
+ return expression;
1222
+ }
1223
+ return parameterName.startsWith(":") ? `${parameterName}${wildcard}` : `${parameterName}${expression}`;
1224
+ }).replace(/([^\/])(:)(?=\d+)/, "$1\\$2").replace(/^([^\/]+)(:)(?=\/\/)/, "$1\\$2");
1225
+ }
1226
+ function matchRequestUrl(url, path, baseUrl) {
1227
+ const normalizedPath = normalizePath(path, baseUrl);
1228
+ const cleanPath = typeof normalizedPath === "string" ? coercePath(normalizedPath) : normalizedPath;
1229
+ const cleanUrl2 = getCleanUrl(url);
1230
+ const result = match(cleanPath, { decode: decodeURIComponent })(cleanUrl2);
1231
+ const params = result && result.params || {};
1232
+ return {
1233
+ matches: result !== false,
1234
+ params
1235
+ };
421
1236
  }
422
1237
 
423
- EventEmitter.prototype.eventNames = function eventNames() {
424
- return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
1238
+ // src/handlers/RestHandler.ts
1239
+ var RESTMethods = /* @__PURE__ */ ((RESTMethods2) => {
1240
+ RESTMethods2["HEAD"] = "HEAD";
1241
+ RESTMethods2["GET"] = "GET";
1242
+ RESTMethods2["POST"] = "POST";
1243
+ RESTMethods2["PUT"] = "PUT";
1244
+ RESTMethods2["PATCH"] = "PATCH";
1245
+ RESTMethods2["OPTIONS"] = "OPTIONS";
1246
+ RESTMethods2["DELETE"] = "DELETE";
1247
+ return RESTMethods2;
1248
+ })(RESTMethods || {});
1249
+ var restContext = __spreadProps(__spreadValues({}, defaultContext), {
1250
+ cookie,
1251
+ body,
1252
+ text,
1253
+ json,
1254
+ xml
1255
+ });
1256
+ var RestHandler = class extends RequestHandler {
1257
+ constructor(method, path, resolver) {
1258
+ super({
1259
+ info: {
1260
+ header: `${method} ${path}`,
1261
+ path,
1262
+ method
1263
+ },
1264
+ ctx: restContext,
1265
+ resolver
1266
+ });
1267
+ this.checkRedundantQueryParameters();
1268
+ }
1269
+ checkRedundantQueryParameters() {
1270
+ const { method, path } = this.info;
1271
+ if (path instanceof RegExp) {
1272
+ return;
1273
+ }
1274
+ const url = cleanUrl(path);
1275
+ if (url === path) {
1276
+ return;
1277
+ }
1278
+ const searchParams = getSearchParams(path);
1279
+ const queryParams = [];
1280
+ searchParams.forEach((_, paramName) => {
1281
+ queryParams.push(paramName);
1282
+ });
1283
+ devUtils.warn(`Found a redundant usage of query parameters in the request handler URL for "${method} ${path}". Please match against a path instead and access query parameters in the response resolver function using "req.url.searchParams".`);
1284
+ }
1285
+ parse(request, resolutionContext) {
1286
+ return matchRequestUrl(request.url, this.info.path, resolutionContext == null ? void 0 : resolutionContext.baseUrl);
1287
+ }
1288
+ getPublicRequest(request, parsedResult) {
1289
+ return __spreadProps(__spreadValues({}, request), {
1290
+ params: parsedResult.params || {}
1291
+ });
1292
+ }
1293
+ predicate(request, parsedResult) {
1294
+ const matchesMethod = this.info.method instanceof RegExp ? this.info.method.test(request.method) : isStringEqual(this.info.method, request.method);
1295
+ return matchesMethod && parsedResult.matches;
1296
+ }
1297
+ log(request, response2) {
1298
+ const publicUrl = getPublicUrlFromRequest(request);
1299
+ const loggedRequest = prepareRequest(request);
1300
+ const loggedResponse = prepareResponse(response2);
1301
+ const statusColor = getStatusCodeColor(response2.status);
1302
+ console.groupCollapsed(devUtils.formatMessage("%s %s %s (%c%s%c)"), getTimestamp(), request.method, publicUrl, `color:${statusColor}`, `${response2.status} ${response2.statusText}`, "color:inherit");
1303
+ console.log("Request", loggedRequest);
1304
+ console.log("Handler:", {
1305
+ mask: this.info.path,
1306
+ resolver: this.resolver
1307
+ });
1308
+ console.log("Response", loggedResponse);
1309
+ console.groupEnd();
1310
+ }
425
1311
  };
426
1312
 
427
- function arrayClone(arr, n) {
428
- var copy = new Array(n);
429
- for (var i = 0; i < n; ++i)
430
- copy[i] = arr[i];
431
- return copy;
432
- }
433
-
434
- function spliceOne(list, index) {
435
- for (; index + 1 < list.length; index++)
436
- list[index] = list[index + 1];
437
- list.pop();
1313
+ // src/handlers/GraphQLHandler.ts
1314
+ init_esm_shims();
1315
+
1316
+ // src/utils/internal/tryCatch.ts
1317
+ init_esm_shims();
1318
+ function tryCatch(fn, onException) {
1319
+ try {
1320
+ const result = fn();
1321
+ return result;
1322
+ } catch (error2) {
1323
+ onException == null ? void 0 : onException(error2);
1324
+ }
438
1325
  }
439
1326
 
440
- function unwrapListeners(arr) {
441
- var ret = new Array(arr.length);
442
- for (var i = 0; i < ret.length; ++i) {
443
- ret[i] = arr[i].listener || arr[i];
1327
+ // src/handlers/GraphQLHandler.ts
1328
+ var graphqlContext = __spreadProps(__spreadValues({}, defaultContext), {
1329
+ data,
1330
+ extensions,
1331
+ errors,
1332
+ cookie
1333
+ });
1334
+ function isDocumentNode(value) {
1335
+ if (value == null) {
1336
+ return false;
444
1337
  }
445
- return ret;
1338
+ return typeof value === "object" && "kind" in value && "definitions" in value;
446
1339
  }
1340
+ var GraphQLHandler = class extends RequestHandler {
1341
+ constructor(operationType, operationName, endpoint, resolver) {
1342
+ let resolvedOperationName = operationName;
1343
+ if (isDocumentNode(operationName)) {
1344
+ const parsedNode = parseDocumentNode(operationName);
1345
+ if (parsedNode.operationType !== operationType) {
1346
+ throw new Error(`Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "${operationType}", but got "${parsedNode.operationType}").`);
1347
+ }
1348
+ if (!parsedNode.operationName) {
1349
+ throw new Error(`Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`);
1350
+ }
1351
+ resolvedOperationName = parsedNode.operationName;
1352
+ }
1353
+ const header = operationType === "all" ? `${operationType} (origin: ${endpoint.toString()})` : `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`;
1354
+ super({
1355
+ info: {
1356
+ header,
1357
+ operationType,
1358
+ operationName: resolvedOperationName
1359
+ },
1360
+ ctx: graphqlContext,
1361
+ resolver
1362
+ });
1363
+ this.endpoint = endpoint;
1364
+ }
1365
+ parse(request) {
1366
+ return tryCatch(() => parseGraphQLRequest(request), (error2) => console.error(error2.message));
1367
+ }
1368
+ getPublicRequest(request, parsedResult) {
1369
+ return __spreadProps(__spreadValues({}, request), {
1370
+ variables: (parsedResult == null ? void 0 : parsedResult.variables) || {}
1371
+ });
1372
+ }
1373
+ predicate(request, parsedResult) {
1374
+ if (!parsedResult) {
1375
+ return false;
1376
+ }
1377
+ if (!parsedResult.operationName && this.info.operationType !== "all") {
1378
+ const publicUrl = getPublicUrlFromRequest(request);
1379
+ devUtils.warn(`Failed to intercept a GraphQL request at "${request.method} ${publicUrl}": anonymous GraphQL operations are not supported.
447
1380
 
448
- function once(emitter, name) {
449
- return new Promise(function (resolve, reject) {
450
- function errorListener(err) {
451
- emitter.removeListener(name, resolver);
452
- reject(err);
1381
+ Consider naming this operation or using "graphql.operation" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/operation `);
1382
+ return false;
453
1383
  }
1384
+ const hasMatchingUrl = matchRequestUrl(request.url, this.endpoint);
1385
+ const hasMatchingOperationType = this.info.operationType === "all" || parsedResult.operationType === this.info.operationType;
1386
+ const hasMatchingOperationName = this.info.operationName instanceof RegExp ? this.info.operationName.test(parsedResult.operationName || "") : parsedResult.operationName === this.info.operationName;
1387
+ return hasMatchingUrl.matches && hasMatchingOperationType && hasMatchingOperationName;
1388
+ }
1389
+ log(request, response2, handler, parsedRequest) {
1390
+ const loggedRequest = prepareRequest(request);
1391
+ const loggedResponse = prepareResponse(response2);
1392
+ const statusColor = getStatusCodeColor(response2.status);
1393
+ const requestInfo = (parsedRequest == null ? void 0 : parsedRequest.operationName) ? `${parsedRequest == null ? void 0 : parsedRequest.operationType} ${parsedRequest == null ? void 0 : parsedRequest.operationName}` : `anonymous ${parsedRequest == null ? void 0 : parsedRequest.operationType}`;
1394
+ console.groupCollapsed(devUtils.formatMessage("%s %s (%c%s%c)"), getTimestamp(), `${requestInfo}`, `color:${statusColor}`, `${response2.status} ${response2.statusText}`, "color:inherit");
1395
+ console.log("Request:", loggedRequest);
1396
+ console.log("Handler:", this);
1397
+ console.log("Response:", loggedResponse);
1398
+ console.groupEnd();
1399
+ }
1400
+ };
454
1401
 
455
- function resolver() {
456
- if (typeof emitter.removeListener === 'function') {
457
- emitter.removeListener('error', errorListener);
458
- }
459
- resolve([].slice.call(arguments));
1402
+ // src/utils/request/onUnhandledRequest.ts
1403
+ var MAX_MATCH_SCORE = 3;
1404
+ var MAX_SUGGESTION_COUNT = 4;
1405
+ var TYPE_MATCH_DELTA = 0.5;
1406
+ function groupHandlersByType(handlers) {
1407
+ return handlers.reduce((groups, handler) => {
1408
+ if (handler instanceof RestHandler) {
1409
+ groups.rest.push(handler);
460
1410
  }
461
- eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
462
- if (name !== 'error') {
463
- addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
1411
+ if (handler instanceof GraphQLHandler) {
1412
+ groups.graphql.push(handler);
464
1413
  }
1414
+ return groups;
1415
+ }, {
1416
+ rest: [],
1417
+ graphql: []
465
1418
  });
466
1419
  }
1420
+ function getRestHandlerScore() {
1421
+ return (request, handler) => {
1422
+ const { path, method } = handler.info;
1423
+ if (path instanceof RegExp || method instanceof RegExp) {
1424
+ return Infinity;
1425
+ }
1426
+ const hasSameMethod = isStringEqual(request.method, method);
1427
+ const methodScoreDelta = hasSameMethod ? TYPE_MATCH_DELTA : 0;
1428
+ const requestPublicUrl = getPublicUrlFromRequest(request);
1429
+ const score = getStringMatchScore(requestPublicUrl, path);
1430
+ return score - methodScoreDelta;
1431
+ };
1432
+ }
1433
+ function getGraphQLHandlerScore(parsedQuery) {
1434
+ return (_, handler) => {
1435
+ if (typeof parsedQuery.operationName === "undefined") {
1436
+ return Infinity;
1437
+ }
1438
+ const { operationType, operationName } = handler.info;
1439
+ if (typeof operationName !== "string") {
1440
+ return Infinity;
1441
+ }
1442
+ const hasSameOperationType = parsedQuery.operationType === operationType;
1443
+ const operationTypeScoreDelta = hasSameOperationType ? TYPE_MATCH_DELTA : 0;
1444
+ const score = getStringMatchScore(parsedQuery.operationName, operationName);
1445
+ return score - operationTypeScoreDelta;
1446
+ };
1447
+ }
1448
+ function getSuggestedHandler(request, handlers, getScore) {
1449
+ const suggestedHandlers = handlers.reduce((suggestions, handler) => {
1450
+ const score = getScore(request, handler);
1451
+ return suggestions.concat([[score, handler]]);
1452
+ }, []).sort(([leftScore], [rightScore]) => leftScore - rightScore).filter(([score]) => score <= MAX_MATCH_SCORE).slice(0, MAX_SUGGESTION_COUNT).map(([, handler]) => handler);
1453
+ return suggestedHandlers;
1454
+ }
1455
+ function getSuggestedHandlersMessage(handlers) {
1456
+ if (handlers.length > 1) {
1457
+ return `Did you mean to request one of the following resources instead?
467
1458
 
468
- function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
469
- if (typeof emitter.on === 'function') {
470
- eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
1459
+ ${handlers.map((handler) => ` \u2022 ${handler.info.header}`).join("\n")}`;
471
1460
  }
1461
+ return `Did you mean to request "${handlers[0].info.header}" instead?`;
472
1462
  }
473
-
474
- function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
475
- if (typeof emitter.on === 'function') {
476
- if (flags.once) {
477
- emitter.once(name, listener);
478
- } else {
479
- emitter.on(name, listener);
480
- }
481
- } else if (typeof emitter.addEventListener === 'function') {
482
- // EventTarget does not have `error` event semantics like Node
483
- // EventEmitters, we do not listen for `error` events here.
484
- emitter.addEventListener(name, function wrapListener(arg) {
485
- // IE does not have builtin `{ once: true }` support so we
486
- // have to do it manually.
487
- if (flags.once) {
488
- emitter.removeEventListener(name, wrapListener);
1463
+ function onUnhandledRequest(request, handlers, strategy = "warn") {
1464
+ const parsedGraphQLQuery = tryCatch(() => parseGraphQLRequest(request));
1465
+ function generateHandlerSuggestion() {
1466
+ const handlerGroups = groupHandlersByType(handlers);
1467
+ const relevantHandlers = parsedGraphQLQuery ? handlerGroups.graphql : handlerGroups.rest;
1468
+ const suggestedHandlers = getSuggestedHandler(request, relevantHandlers, parsedGraphQLQuery ? getGraphQLHandlerScore(parsedGraphQLQuery) : getRestHandlerScore());
1469
+ return suggestedHandlers.length > 0 ? getSuggestedHandlersMessage(suggestedHandlers) : "";
1470
+ }
1471
+ function generateUnhandledRequestMessage() {
1472
+ const publicUrl = getPublicUrlFromRequest(request);
1473
+ const requestHeader = parsedGraphQLQuery ? `${parsedGraphQLQuery.operationType} ${parsedGraphQLQuery.operationName} (${request.method} ${publicUrl})` : `${request.method} ${publicUrl}`;
1474
+ const handlerSuggestion = generateHandlerSuggestion();
1475
+ const messageTemplate = [
1476
+ `captured a request without a matching request handler:`,
1477
+ ` \u2022 ${requestHeader}`,
1478
+ handlerSuggestion,
1479
+ `If you still wish to intercept this unhandled request, please create a request handler for it.
1480
+ Read more: https://mswjs.io/docs/getting-started/mocks`
1481
+ ].filter(Boolean);
1482
+ return messageTemplate.join("\n\n");
1483
+ }
1484
+ function applyStrategy(strategy2) {
1485
+ const message = generateUnhandledRequestMessage();
1486
+ switch (strategy2) {
1487
+ case "error": {
1488
+ devUtils.error("Error: %s", message);
1489
+ throw new Error(devUtils.formatMessage('Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.'));
1490
+ }
1491
+ case "warn": {
1492
+ devUtils.warn("Warning: %s", message);
1493
+ break;
489
1494
  }
490
- listener(arg);
1495
+ case "bypass":
1496
+ break;
1497
+ default:
1498
+ throw new Error(devUtils.formatMessage('Failed to react to an unhandled request: unknown strategy "%s". Please provide one of the supported strategies ("bypass", "warn", "error") or a custom callback function as the value of the "onUnhandledRequest" option.', strategy2));
1499
+ }
1500
+ }
1501
+ if (typeof strategy === "function") {
1502
+ strategy(request, {
1503
+ warning: applyStrategy.bind(null, "warn"),
1504
+ error: applyStrategy.bind(null, "error")
491
1505
  });
492
- } else {
493
- throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
1506
+ return;
494
1507
  }
1508
+ applyStrategy(strategy);
495
1509
  }
496
1510
 
497
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
498
- var extendStatics = function (d, b) {
499
- extendStatics = Object.setPrototypeOf ||
500
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
501
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
502
- return extendStatics(d, b);
503
- };
504
- return function (d, b) {
505
- extendStatics(d, b);
506
- function __() { this.constructor = d; }
507
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
508
- };
509
- })();
510
- var __spreadArrays = (commonjsGlobal && commonjsGlobal.__spreadArrays) || function () {
511
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
512
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
513
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
514
- r[k] = a[j];
515
- return r;
516
- };
517
- StrictEventEmitter$1.__esModule = true;
518
- StrictEventEmitter$1.StrictEventEmitter = void 0;
519
- var events_1 = events.exports;
520
- var StrictEventEmitter = /** @class */ (function (_super) {
521
- __extends(StrictEventEmitter, _super);
522
- function StrictEventEmitter() {
523
- return _super.call(this) || this;
524
- }
525
- StrictEventEmitter.prototype.on = function (event, listener) {
526
- return _super.prototype.on.call(this, event.toString(), listener);
527
- };
528
- StrictEventEmitter.prototype.once = function (event, listener) {
529
- return _super.prototype.on.call(this, event.toString(), listener);
530
- };
531
- StrictEventEmitter.prototype.off = function (event, listener) {
532
- return _super.prototype.off.call(this, event.toString(), listener);
533
- };
534
- StrictEventEmitter.prototype.emit = function (event) {
535
- var data = [];
536
- for (var _i = 1; _i < arguments.length; _i++) {
537
- data[_i - 1] = arguments[_i];
538
- }
539
- return _super.prototype.emit.apply(this, __spreadArrays([event.toString()], data));
540
- };
541
- StrictEventEmitter.prototype.addListener = function (event, listener) {
542
- return _super.prototype.addListener.call(this, event.toString(), listener);
543
- };
544
- StrictEventEmitter.prototype.removeListener = function (event, listener) {
545
- return _super.prototype.removeListener.call(this, event.toString(), listener);
546
- };
547
- return StrictEventEmitter;
548
- }(events_1.EventEmitter));
549
- StrictEventEmitter$1.StrictEventEmitter = StrictEventEmitter;
550
-
551
- (function (exports) {
552
- var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
553
- if (k2 === undefined) k2 = k;
554
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
555
- }) : (function(o, m, k, k2) {
556
- if (k2 === undefined) k2 = k;
557
- o[k2] = m[k];
558
- }));
559
- exports.__esModule = true;
560
- exports.StrictEventEmitter = void 0;
561
- var StrictEventEmitter_1 = StrictEventEmitter$1;
562
- __createBinding(exports, StrictEventEmitter_1, "StrictEventEmitter");
563
- }(lib$1));
564
-
565
- var lib = {};
566
-
567
- var until$1 = {};
568
-
569
- Object.defineProperty(until$1, "__esModule", { value: true });
570
- /**
571
- * Gracefully handles a given Promise factory.
572
- * @example
573
- * cosnt [error, data] = await until(() => asyncAction())
574
- */
575
- until$1.until = async (promise) => {
1511
+ // src/utils/request/readResponseCookies.ts
1512
+ init_esm_shims();
1513
+ import { store as store2 } from "@mswjs/cookies";
1514
+ function readResponseCookies(request, response2) {
1515
+ store2.add(__spreadProps(__spreadValues({}, request), { url: request.url.toString() }), response2);
1516
+ store2.persist();
1517
+ }
1518
+
1519
+ // src/utils/handleRequest.ts
1520
+ async function handleRequest(request, handlers, options, emitter, handleRequestOptions) {
1521
+ var _a, _b, _c, _d;
1522
+ emitter.emit("request:start", request);
1523
+ if (request.headers.get("x-msw-bypass") === "true") {
1524
+ emitter.emit("request:end", request);
1525
+ (_a = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _a.call(handleRequestOptions, request);
1526
+ return;
1527
+ }
1528
+ const [lookupError, lookupResult] = await until2(() => {
1529
+ return getResponse(request, handlers, handleRequestOptions == null ? void 0 : handleRequestOptions.resolutionContext);
1530
+ });
1531
+ if (lookupError) {
1532
+ emitter.emit("unhandledException", lookupError, request);
1533
+ throw lookupError;
1534
+ }
1535
+ const { handler, response: response2 } = lookupResult;
1536
+ if (!handler) {
1537
+ onUnhandledRequest(request, handlers, options.onUnhandledRequest);
1538
+ emitter.emit("request:unhandled", request);
1539
+ emitter.emit("request:end", request);
1540
+ (_b = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _b.call(handleRequestOptions, request);
1541
+ return;
1542
+ }
1543
+ if (!response2) {
1544
+ devUtils.warn(`Expected response resolver to return a mocked response Object, but got %s. The original response is going to be used instead.
1545
+
1546
+ \u2022 %s
1547
+ %s`, response2, handler.info.header, handler.info.callFrame);
1548
+ emitter.emit("request:end", request);
1549
+ (_c = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _c.call(handleRequestOptions, request);
1550
+ return;
1551
+ }
1552
+ if (response2.passthrough) {
1553
+ emitter.emit("request:end", request);
1554
+ (_d = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _d.call(handleRequestOptions, request);
1555
+ return;
1556
+ }
1557
+ readResponseCookies(request, response2);
1558
+ emitter.emit("request:match", request);
1559
+ return new Promise((resolve) => {
1560
+ var _a2, _b2, _c2;
1561
+ const requiredLookupResult = lookupResult;
1562
+ const transformedResponse = ((_a2 = handleRequestOptions == null ? void 0 : handleRequestOptions.transformResponse) == null ? void 0 : _a2.call(handleRequestOptions, response2)) || response2;
1563
+ (_b2 = handleRequestOptions == null ? void 0 : handleRequestOptions.onMockedResponse) == null ? void 0 : _b2.call(handleRequestOptions, transformedResponse, requiredLookupResult);
1564
+ setTimeout(() => {
1565
+ var _a3;
1566
+ (_a3 = handleRequestOptions == null ? void 0 : handleRequestOptions.onMockedResponseSent) == null ? void 0 : _a3.call(handleRequestOptions, transformedResponse, requiredLookupResult);
1567
+ emitter.emit("request:end", request);
1568
+ resolve(transformedResponse);
1569
+ }, (_c2 = response2.delay) != null ? _c2 : 0);
1570
+ });
1571
+ }
1572
+
1573
+ // src/utils/worker/createRequestListener.ts
1574
+ var createRequestListener = (context, options) => {
1575
+ return async (event, message) => {
1576
+ const channel = createBroadcastChannel(event);
576
1577
  try {
577
- const data = await promise().catch((error) => {
578
- throw error;
1578
+ const request = parseWorkerRequest(message.payload);
1579
+ await handleRequest(request, context.requestHandlers, options, context.emitter, {
1580
+ transformResponse(response2) {
1581
+ return __spreadProps(__spreadValues({}, response2), {
1582
+ headers: response2.headers.all()
1583
+ });
1584
+ },
1585
+ onPassthroughResponse() {
1586
+ return channel.send({
1587
+ type: "MOCK_NOT_FOUND"
1588
+ });
1589
+ },
1590
+ onMockedResponse(response2) {
1591
+ channel.send({
1592
+ type: "MOCK_SUCCESS",
1593
+ payload: response2
1594
+ });
1595
+ },
1596
+ onMockedResponseSent(response2, { handler, publicRequest, parsedRequest }) {
1597
+ if (!options.quiet) {
1598
+ handler.log(publicRequest, response2, handler, parsedRequest);
1599
+ }
1600
+ }
1601
+ });
1602
+ } catch (error2) {
1603
+ if (error2 instanceof NetworkError) {
1604
+ return channel.send({
1605
+ type: "NETWORK_ERROR",
1606
+ payload: {
1607
+ name: error2.name,
1608
+ message: error2.message
1609
+ }
579
1610
  });
580
- return [null, data];
581
- }
582
- catch (error) {
583
- return [error, null];
1611
+ }
1612
+ if (error2 instanceof Error) {
1613
+ channel.send({
1614
+ type: "INTERNAL_ERROR",
1615
+ payload: {
1616
+ status: 500,
1617
+ body: JSON.stringify({
1618
+ errorType: error2.constructor.name,
1619
+ message: error2.message,
1620
+ location: error2.stack
1621
+ })
1622
+ }
1623
+ });
1624
+ }
584
1625
  }
1626
+ };
585
1627
  };
586
1628
 
587
- Object.defineProperty(lib, "__esModule", { value: true });
588
- var until_1 = until$1;
589
- var until = lib.until = until_1.until;
590
-
591
- /**
592
- * Attempts to resolve a Service Worker instance from a given registration,
593
- * regardless of its state (active, installing, waiting).
594
- */
595
- const getWorkerByRegistration = (registration, absoluteWorkerUrl, findWorker) => {
596
- const allStates = [
597
- registration.active,
598
- registration.installing,
599
- registration.waiting,
600
- ];
601
- const existingStates = allStates.filter(Boolean);
602
- const mockWorker = existingStates.find((worker) => {
603
- return findWorker(worker.scriptURL, absoluteWorkerUrl);
604
- });
605
- return mockWorker || null;
606
- };
607
-
608
- /**
609
- * Returns an absolute Service Worker URL based on the given
610
- * relative URL (known during the registration).
611
- */
612
- function getAbsoluteWorkerUrl(relativeUrl) {
613
- return new URL(relativeUrl, location.origin).href;
614
- }
615
-
616
- /**
617
- * Returns an active Service Worker instance.
618
- * When not found, registers a new Service Worker.
619
- */
620
- const getWorkerInstance = (url, options = {}, findWorker) => __awaiter(void 0, void 0, void 0, function* () {
621
- // Resolve the absolute Service Worker URL.
622
- const absoluteWorkerUrl = getAbsoluteWorkerUrl(url);
623
- const mockRegistrations = yield navigator.serviceWorker
624
- .getRegistrations()
625
- .then((registrations) => registrations.filter((registration) => getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker)));
626
- if (!navigator.serviceWorker.controller && mockRegistrations.length > 0) {
627
- // Reload the page when it has associated workers, but no active controller.
628
- // The absence of a controller can mean either:
629
- // - page has no Service Worker associated with it
630
- // - page has been hard-reloaded and its workers won't be used until the next reload.
631
- // Since we've checked that there are registrations associated with this page,
632
- // at this point we are sure it's hard reload that falls into this clause.
633
- location.reload();
634
- }
635
- const [existingRegistration] = mockRegistrations;
636
- if (existingRegistration) {
637
- // When the Service Worker is registered, update it and return the reference.
638
- return existingRegistration.update().then(() => {
639
- return [
640
- getWorkerByRegistration(existingRegistration, absoluteWorkerUrl, findWorker),
641
- existingRegistration,
642
- ];
643
- });
644
- }
645
- // When the Service Worker wasn't found, register it anew and return the reference.
646
- const [error, instance] = yield until(() => __awaiter(void 0, void 0, void 0, function* () {
647
- const registration = yield navigator.serviceWorker.register(url, options);
648
- return [
649
- // Compare existing worker registration by its worker URL,
650
- // to prevent irrelevant workers to resolve here (such as Codesandbox worker).
651
- getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),
652
- registration,
653
- ];
654
- }));
655
- // Handle Service Worker registration errors.
656
- if (error) {
657
- const isWorkerMissing = error.message.includes('(404)');
658
- // Produce a custom error message when given a non-existing Service Worker url.
659
- // Suggest developers to check their setup.
660
- if (isWorkerMissing) {
661
- const scopeUrl = new URL((options === null || options === void 0 ? void 0 : options.scope) || '/', location.href);
662
- throw new Error(devUtils.formatMessage(`\
663
- Failed to register a Service Worker for scope ('${scopeUrl.href}') with script ('${absoluteWorkerUrl}'): Service Worker script does not exist at the given path.
664
-
665
- Did you forget to run "npx msw init <PUBLIC_DIR>"?
666
-
667
- Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/init`));
668
- }
669
- // Fallback error message for any other registration errors.
670
- throw new Error(devUtils.formatMessage('Failed to register the Service Worker:\n\n%s', error.message));
671
- }
672
- return instance;
673
- });
674
-
675
- /**
676
- * Prints a worker activation message in the browser's console.
677
- */
678
- function printStartMessage(args = {}) {
679
- if (args.quiet) {
680
- return;
681
- }
682
- const message = args.message || 'Mocking enabled.';
683
- console.groupCollapsed(`%c${devUtils.formatMessage(message)}`, 'color:orangered;font-weight:bold;');
684
- console.log('%cDocumentation: %chttps://mswjs.io/docs', 'font-weight:bold', 'font-weight:normal');
685
- console.log('Found an issue? https://github.com/mswjs/msw/issues');
686
- if (args.workerUrl) {
687
- console.log('Worker script URL:', args.workerUrl);
688
- }
689
- if (args.workerScope) {
690
- console.log('Worker scope:', args.workerScope);
691
- }
692
- console.groupEnd();
693
- }
694
-
695
- /**
696
- * Signals the worker to enable the interception of requests.
697
- */
698
- function enableMocking(context, options) {
699
- var _a, _b;
700
- return __awaiter(this, void 0, void 0, function* () {
701
- context.workerChannel.send('MOCK_ACTIVATE');
702
- yield context.events.once('MOCKING_ENABLED');
703
- // Warn the developer on multiple "worker.start()" calls.
704
- // While this will not affect the worker in any way,
705
- // it likely indicates an issue with the developer's code.
706
- if (context.isMockingEnabled) {
707
- devUtils.warn(`Found a redundant "worker.start()" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this "worker.start()" call.`);
708
- return;
709
- }
710
- context.isMockingEnabled = true;
711
- printStartMessage({
712
- quiet: options.quiet,
713
- workerScope: (_a = context.registration) === null || _a === void 0 ? void 0 : _a.scope,
714
- workerUrl: (_b = context.worker) === null || _b === void 0 ? void 0 : _b.scriptURL,
715
- });
716
- });
717
- }
718
-
719
- /**
720
- * Creates a communication channel between the client
721
- * and the Service Worker associated with the given event.
722
- */
723
- const createBroadcastChannel = (event) => {
724
- const port = event.ports[0];
725
- return {
726
- /**
727
- * Sends a text message to the connected Service Worker.
728
- */
729
- send(message) {
730
- if (port) {
731
- port.postMessage(message);
732
- }
733
- },
734
- };
735
- };
1629
+ // src/utils/internal/requestIntegrityCheck.ts
1630
+ init_esm_shims();
1631
+ async function requestIntegrityCheck(context, serviceWorker) {
1632
+ context.workerChannel.send("INTEGRITY_CHECK_REQUEST");
1633
+ const { payload: actualChecksum } = await context.events.once("INTEGRITY_CHECK_RESPONSE");
1634
+ if (actualChecksum !== "02f4ad4a2797f85668baf196e553d929") {
1635
+ throw new Error(`Currently active Service Worker (${actualChecksum}) is behind the latest published one (${"02f4ad4a2797f85668baf196e553d929"}).`);
1636
+ }
1637
+ return serviceWorker;
1638
+ }
736
1639
 
737
- function getAllCookies() {
738
- return parse_1(document.cookie);
739
- }
740
- /**
741
- * Returns relevant document cookies based on the request `credentials` option.
742
- */
743
- function getRequestCookies(request) {
744
- /**
745
- * @note No cookies persist on the document in Node.js: no document.
746
- */
747
- if (typeof document === 'undefined' || typeof location === 'undefined') {
748
- return {};
749
- }
750
- switch (request.credentials) {
751
- case 'same-origin': {
752
- // Return document cookies only when requested a resource
753
- // from the same origin as the current document.
754
- return location.origin === request.url.origin ? getAllCookies() : {};
755
- }
756
- case 'include': {
757
- // Return all document cookies.
758
- return getAllCookies();
759
- }
760
- default: {
761
- return {};
762
- }
763
- }
764
- }
765
-
766
- /**
767
- * Sets relevant cookies on the request.
768
- * Request cookies are taken from the following sources:
769
- * - Immediate (own) request cookies (those in the "Cookie" request header);
770
- * - From the `document.cookie` based on the request's `credentials` value;
771
- * - From the internal cookie store that persists/hydrates cookies in Node.js
772
- */
773
- function setRequestCookies(request) {
774
- var _a;
775
- // Set mocked request cookies from the `cookie` header of the original request.
776
- // No need to take `credentials` into account, because in Node.js requests are intercepted
777
- // _after_ they happen. Request issuer should have already taken care of sending relevant cookies.
778
- // Unlike browser, where interception is on the worker level, _before_ the request happens.
779
- const requestCookiesString = request.headers.get('cookie');
780
- store.hydrate();
781
- const cookiesFromStore = Array.from((_a = store.get(Object.assign(Object.assign({}, request), { url: request.url.toString() }))) === null || _a === void 0 ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => {
782
- return Object.assign(cookies, { [name.trim()]: value });
783
- }, {});
784
- const cookiesFromDocument = getRequestCookies(request);
785
- const forwardedCookies = Object.assign(Object.assign({}, cookiesFromDocument), cookiesFromStore);
786
- // Ensure the persisted (document) cookies are propagated to the request.
787
- // Propagated the cookies persisted in the Cookuie Store to the request headers.
788
- // This forwards relevant request cookies based on the request's credentials.
789
- for (const [name, value] of Object.entries(forwardedCookies)) {
790
- request.headers.append('cookie', `${name}=${value}`);
791
- }
792
- const ownCookies = requestCookiesString
793
- ? parse_1(requestCookiesString)
794
- : {};
795
- request.cookies = Object.assign(Object.assign(Object.assign({}, request.cookies), forwardedCookies), ownCookies);
796
- }
797
-
798
- /**
799
- * Ensures that an empty GET request body is always represented as `undefined`.
800
- */
801
- function pruneGetRequestBody(request) {
802
- if (request.method &&
803
- isStringEqual(request.method, 'GET') &&
804
- request.body === '') {
805
- return undefined;
806
- }
807
- return request.body;
808
- }
809
-
810
- /**
811
- * Converts a given request received from the Service Worker
812
- * into a `MockedRequest` instance.
813
- */
814
- function parseWorkerRequest(rawRequest) {
815
- const request = {
816
- id: rawRequest.id,
817
- cache: rawRequest.cache,
818
- credentials: rawRequest.credentials,
819
- method: rawRequest.method,
820
- url: new URL(rawRequest.url),
821
- referrer: rawRequest.referrer,
822
- referrerPolicy: rawRequest.referrerPolicy,
823
- redirect: rawRequest.redirect,
824
- mode: rawRequest.mode,
825
- params: {},
826
- cookies: {},
827
- integrity: rawRequest.integrity,
828
- keepalive: rawRequest.keepalive,
829
- destination: rawRequest.destination,
830
- body: pruneGetRequestBody(rawRequest),
831
- bodyUsed: rawRequest.bodyUsed,
832
- headers: new lib$2.Headers(rawRequest.headers),
833
- passthrough,
834
- };
835
- // Set document cookies on the request.
836
- setRequestCookies(request);
837
- // Parse the request's body based on the "Content-Type" header.
838
- request.body = parseBody(request.body, request.headers);
839
- return request;
840
- }
841
-
842
- /**
843
- * Returns a mocked response for a given request using following request handlers.
844
- */
845
- const getResponse = (request, handlers, resolutionContext) => __awaiter(void 0, void 0, void 0, function* () {
846
- const relevantHandlers = handlers.filter((handler) => {
847
- return handler.test(request, resolutionContext);
848
- });
849
- if (relevantHandlers.length === 0) {
850
- return {
851
- handler: undefined,
852
- response: undefined,
853
- };
854
- }
855
- const result = yield relevantHandlers.reduce((executionResult, handler) => __awaiter(void 0, void 0, void 0, function* () {
856
- const previousResults = yield executionResult;
857
- if (!!(previousResults === null || previousResults === void 0 ? void 0 : previousResults.response)) {
858
- return executionResult;
859
- }
860
- const result = yield handler.run(request, resolutionContext);
861
- if (result === null || result.handler.shouldSkip) {
862
- return null;
863
- }
864
- if (!result.response) {
865
- return {
866
- request: result.request,
867
- handler: result.handler,
868
- response: undefined,
869
- parsedResult: result.parsedResult,
870
- };
871
- }
872
- if (result.response.once) {
873
- handler.markAsSkipped(true);
874
- }
875
- return result;
876
- }), Promise.resolve(null));
877
- // Although reducing a list of relevant request handlers, it's possible
878
- // that in the end there will be no handler associted with the request
879
- // (i.e. if relevant handlers are fall-through).
880
- if (!result) {
881
- return {
882
- handler: undefined,
883
- response: undefined,
884
- };
885
- }
886
- return {
887
- handler: result.handler,
888
- publicRequest: result.request,
889
- parsedRequest: result.parsedResult,
890
- response: result.response,
891
- };
892
- });
1640
+ // src/utils/deferNetworkRequestsUntil.ts
1641
+ init_esm_shims();
1642
+ import { until as until3 } from "@open-draft/until";
1643
+ function deferNetworkRequestsUntil(predicatePromise) {
1644
+ const originalXhrSend = window.XMLHttpRequest.prototype.send;
1645
+ window.XMLHttpRequest.prototype.send = function(...args) {
1646
+ until3(() => predicatePromise).then(() => {
1647
+ window.XMLHttpRequest.prototype.send = originalXhrSend;
1648
+ this.send(...args);
1649
+ });
1650
+ };
1651
+ const originalFetch = window.fetch;
1652
+ window.fetch = async (...args) => {
1653
+ await until3(() => predicatePromise);
1654
+ window.fetch = originalFetch;
1655
+ return window.fetch(...args);
1656
+ };
1657
+ }
893
1658
 
894
- var jsLevenshtein = (function()
895
- {
896
- function _min(d0, d1, d2, bx, ay)
897
- {
898
- return d0 < d1 || d2 < d1
899
- ? d0 > d2
900
- ? d2 + 1
901
- : d0 + 1
902
- : bx === ay
903
- ? d1
904
- : d1 + 1;
905
- }
906
-
907
- return function(a, b)
908
- {
909
- if (a === b) {
910
- return 0;
1659
+ // src/utils/worker/createResponseListener.ts
1660
+ init_esm_shims();
1661
+ function createResponseListener(context) {
1662
+ return (_, message) => {
1663
+ var _a;
1664
+ const { payload: responseJson } = message;
1665
+ if ((_a = responseJson.type) == null ? void 0 : _a.includes("opaque")) {
1666
+ return;
911
1667
  }
912
-
913
- if (a.length > b.length) {
914
- var tmp = a;
915
- a = b;
916
- b = tmp;
1668
+ const response2 = new Response(responseJson.body || null, responseJson);
1669
+ const isMockedResponse = response2.headers.get("x-powered-by") === "msw";
1670
+ if (isMockedResponse) {
1671
+ context.emitter.emit("response:mocked", response2, responseJson.requestId);
1672
+ } else {
1673
+ context.emitter.emit("response:bypass", response2, responseJson.requestId);
917
1674
  }
1675
+ };
1676
+ }
918
1677
 
919
- var la = a.length;
920
- var lb = b.length;
1678
+ // src/setupWorker/start/utils/validateWorkerScope.ts
1679
+ init_esm_shims();
1680
+ function validateWorkerScope(registration, options) {
1681
+ if (!(options == null ? void 0 : options.quiet) && !location.href.startsWith(registration.scope)) {
1682
+ devUtils.warn(`Cannot intercept requests on this page because it's outside of the worker's scope ("${registration.scope}"). If you wish to mock API requests on this page, you must resolve this scope issue.
921
1683
 
922
- while (la > 0 && (a.charCodeAt(la - 1) === b.charCodeAt(lb - 1))) {
923
- la--;
924
- lb--;
925
- }
1684
+ - (Recommended) Register the worker at the root level ("/") of your application.
1685
+ - Set the "Service-Worker-Allowed" response header to allow out-of-scope workers.`);
1686
+ }
1687
+ }
926
1688
 
927
- var offset = 0;
1689
+ // src/setupWorker/start/createStartHandler.ts
1690
+ var createStartHandler = (context) => {
1691
+ return function start(options, customOptions) {
1692
+ const startWorkerInstance = async () => {
1693
+ context.events.removeAllListeners();
1694
+ context.workerChannel.on("REQUEST", createRequestListener(context, options));
1695
+ context.workerChannel.on("RESPONSE", createResponseListener(context));
1696
+ const instance = await getWorkerInstance(options.serviceWorker.url, options.serviceWorker.options, options.findWorker);
1697
+ const [worker, registration] = instance;
1698
+ if (!worker) {
1699
+ const missingWorkerMessage = (customOptions == null ? void 0 : customOptions.findWorker) ? devUtils.formatMessage(`Failed to locate the Service Worker registration using a custom "findWorker" predicate.
928
1700
 
929
- while (offset < la && (a.charCodeAt(offset) === b.charCodeAt(offset))) {
930
- offset++;
931
- }
1701
+ Please ensure that the custom predicate properly locates the Service Worker registration at "%s".
1702
+ More details: https://mswjs.io/docs/api/setup-worker/start#findworker
1703
+ `, options.serviceWorker.url) : devUtils.formatMessage(`Failed to locate the Service Worker registration.
932
1704
 
933
- la -= offset;
934
- lb -= offset;
1705
+ This most likely means that the worker script URL "%s" cannot resolve against the actual public hostname (%s). This may happen if your application runs behind a proxy, or has a dynamic hostname.
935
1706
 
936
- if (la === 0 || lb < 3) {
937
- return lb;
938
- }
1707
+ Please consider using a custom "serviceWorker.url" option to point to the actual worker script location, or a custom "findWorker" option to resolve the Service Worker registration manually. More details: https://mswjs.io/docs/api/setup-worker/start`, options.serviceWorker.url, location.host);
1708
+ throw new Error(missingWorkerMessage);
1709
+ }
1710
+ context.worker = worker;
1711
+ context.registration = registration;
1712
+ context.events.addListener(window, "beforeunload", () => {
1713
+ if (worker.state !== "redundant") {
1714
+ context.workerChannel.send("CLIENT_CLOSED");
1715
+ }
1716
+ window.clearInterval(context.keepAliveInterval);
1717
+ });
1718
+ const [integrityError] = await until4(() => requestIntegrityCheck(context, worker));
1719
+ if (integrityError) {
1720
+ devUtils.error(`Detected outdated Service Worker: ${integrityError.message}
939
1721
 
940
- var x = 0;
941
- var y;
942
- var d0;
943
- var d1;
944
- var d2;
945
- var d3;
946
- var dd;
947
- var dy;
948
- var ay;
949
- var bx0;
950
- var bx1;
951
- var bx2;
952
- var bx3;
953
-
954
- var vector = [];
955
-
956
- for (y = 0; y < la; y++) {
957
- vector.push(y + 1);
958
- vector.push(a.charCodeAt(offset + y));
959
- }
1722
+ The mocking is still enabled, but it's highly recommended that you update your Service Worker by running:
960
1723
 
961
- var len = vector.length - 1;
962
-
963
- for (; x < lb - 3;) {
964
- bx0 = b.charCodeAt(offset + (d0 = x));
965
- bx1 = b.charCodeAt(offset + (d1 = x + 1));
966
- bx2 = b.charCodeAt(offset + (d2 = x + 2));
967
- bx3 = b.charCodeAt(offset + (d3 = x + 3));
968
- dd = (x += 4);
969
- for (y = 0; y < len; y += 2) {
970
- dy = vector[y];
971
- ay = vector[y + 1];
972
- d0 = _min(dy, d0, d1, bx0, ay);
973
- d1 = _min(d0, d1, d2, bx1, ay);
974
- d2 = _min(d1, d2, d3, bx2, ay);
975
- dd = _min(d2, d3, dd, bx3, ay);
976
- vector[y] = dd;
977
- d3 = d2;
978
- d2 = d1;
979
- d1 = d0;
980
- d0 = dy;
981
- }
982
- }
1724
+ $ npx msw init <PUBLIC_DIR>
983
1725
 
984
- for (; x < lb;) {
985
- bx0 = b.charCodeAt(offset + (d0 = x));
986
- dd = ++x;
987
- for (y = 0; y < len; y += 2) {
988
- dy = vector[y];
989
- vector[y] = dd = _min(dy, d0, dd, bx0, vector[y + 1]);
990
- d0 = dy;
1726
+ This is necessary to ensure that the Service Worker is in sync with the library to guarantee its stability.
1727
+ If this message still persists after updating, please report an issue: https://github.com/open-draft/msw/issues `);
1728
+ }
1729
+ context.keepAliveInterval = window.setInterval(() => context.workerChannel.send("KEEPALIVE_REQUEST"), 5e3);
1730
+ validateWorkerScope(registration, context.startOptions);
1731
+ return registration;
1732
+ };
1733
+ const workerRegistration = startWorkerInstance().then(async (registration) => {
1734
+ const pendingInstance = registration.installing || registration.waiting;
1735
+ if (pendingInstance) {
1736
+ await new Promise((resolve) => {
1737
+ pendingInstance.addEventListener("statechange", () => {
1738
+ if (pendingInstance.state === "activated") {
1739
+ return resolve();
1740
+ }
1741
+ });
1742
+ });
991
1743
  }
1744
+ await enableMocking(context, options).catch((error2) => {
1745
+ throw new Error(`Failed to enable mocking: ${error2 == null ? void 0 : error2.message}`);
1746
+ });
1747
+ return registration;
1748
+ });
1749
+ if (options.waitUntilReady) {
1750
+ deferNetworkRequestsUntil(workerRegistration);
992
1751
  }
1752
+ return workerRegistration;
1753
+ };
1754
+ };
1755
+
1756
+ // src/setupWorker/stop/createStop.ts
1757
+ init_esm_shims();
1758
+
1759
+ // src/setupWorker/stop/utils/printStopMessage.ts
1760
+ init_esm_shims();
1761
+ function printStopMessage(args = {}) {
1762
+ if (args.quiet) {
1763
+ return;
1764
+ }
1765
+ console.log(`%c${devUtils.formatMessage("Mocking disabled.")}`, "color:orangered;font-weight:bold;");
1766
+ }
993
1767
 
994
- return dd;
1768
+ // src/setupWorker/stop/createStop.ts
1769
+ var createStop = (context) => {
1770
+ return function stop() {
1771
+ var _a;
1772
+ if (!context.isMockingEnabled) {
1773
+ devUtils.warn('Found a redundant "worker.stop()" call. Note that stopping the worker while mocking already stopped has no effect. Consider removing this "worker.stop()" call.');
1774
+ return;
1775
+ }
1776
+ context.workerChannel.send("MOCK_DEACTIVATE");
1777
+ context.isMockingEnabled = false;
1778
+ window.clearInterval(context.keepAliveInterval);
1779
+ printStopMessage({ quiet: (_a = context.startOptions) == null ? void 0 : _a.quiet });
995
1780
  };
996
- })();
997
-
998
- const MAX_MATCH_SCORE = 3;
999
- const MAX_SUGGESTION_COUNT = 4;
1000
- const TYPE_MATCH_DELTA = 0.5;
1001
- function groupHandlersByType(handlers) {
1002
- return handlers.reduce((groups, handler) => {
1003
- if (handler instanceof RestHandler) {
1004
- groups.rest.push(handler);
1005
- }
1006
- if (handler instanceof GraphQLHandler) {
1007
- groups.graphql.push(handler);
1008
- }
1009
- return groups;
1010
- }, {
1011
- rest: [],
1012
- graphql: [],
1013
- });
1014
- }
1015
- function getRestHandlerScore() {
1016
- return (request, handler) => {
1017
- const { path, method } = handler.info;
1018
- if (path instanceof RegExp || method instanceof RegExp) {
1019
- return Infinity;
1020
- }
1021
- const hasSameMethod = isStringEqual(request.method, method);
1022
- // Always treat a handler with the same method as a more similar one.
1023
- const methodScoreDelta = hasSameMethod ? TYPE_MATCH_DELTA : 0;
1024
- const requestPublicUrl = getPublicUrlFromRequest(request);
1025
- const score = jsLevenshtein(requestPublicUrl, path);
1026
- return score - methodScoreDelta;
1027
- };
1028
- }
1029
- function getGraphQLHandlerScore(parsedQuery) {
1030
- return (_, handler) => {
1031
- if (typeof parsedQuery.operationName === 'undefined') {
1032
- return Infinity;
1033
- }
1034
- const { operationType, operationName } = handler.info;
1035
- if (typeof operationName !== 'string') {
1036
- return Infinity;
1037
- }
1038
- const hasSameOperationType = parsedQuery.operationType === operationType;
1039
- // Always treat a handler with the same operation type as a more similar one.
1040
- const operationTypeScoreDelta = hasSameOperationType ? TYPE_MATCH_DELTA : 0;
1041
- const score = jsLevenshtein(parsedQuery.operationName, operationName);
1042
- return score - operationTypeScoreDelta;
1043
- };
1044
- }
1045
- function getSuggestedHandler(request, handlers, getScore) {
1046
- const suggestedHandlers = handlers
1047
- .reduce((suggestions, handler) => {
1048
- const score = getScore(request, handler);
1049
- return suggestions.concat([[score, handler]]);
1050
- }, [])
1051
- .sort(([leftScore], [rightScore]) => leftScore - rightScore)
1052
- .filter(([score]) => score <= MAX_MATCH_SCORE)
1053
- .slice(0, MAX_SUGGESTION_COUNT)
1054
- .map(([, handler]) => handler);
1055
- return suggestedHandlers;
1056
- }
1057
- function getSuggestedHandlersMessage(handlers) {
1058
- if (handlers.length > 1) {
1059
- return `\
1060
- Did you mean to request one of the following resources instead?
1061
-
1062
- ${handlers.map((handler) => ` • ${handler.info.header}`).join('\n')}`;
1063
- }
1064
- return `Did you mean to request "${handlers[0].info.header}" instead?`;
1065
- }
1066
- function onUnhandledRequest(request, handlers, strategy = 'warn') {
1067
- const parsedGraphQLQuery = tryCatch(() => parseGraphQLRequest(request));
1068
- function generateHandlerSuggestion() {
1069
- /**
1070
- * @note Ignore exceptions during GraphQL request parsing because at this point
1071
- * we cannot assume the unhandled request is a valid GraphQL request.
1072
- * If the GraphQL parsing fails, just don't treat it as a GraphQL request.
1073
- */
1074
- const handlerGroups = groupHandlersByType(handlers);
1075
- const relevantHandlers = parsedGraphQLQuery
1076
- ? handlerGroups.graphql
1077
- : handlerGroups.rest;
1078
- const suggestedHandlers = getSuggestedHandler(request, relevantHandlers, parsedGraphQLQuery
1079
- ? getGraphQLHandlerScore(parsedGraphQLQuery)
1080
- : getRestHandlerScore());
1081
- return suggestedHandlers.length > 0
1082
- ? getSuggestedHandlersMessage(suggestedHandlers)
1083
- : '';
1084
- }
1085
- function generateUnhandledRequestMessage() {
1086
- const publicUrl = getPublicUrlFromRequest(request);
1087
- const requestHeader = parsedGraphQLQuery
1088
- ? `${parsedGraphQLQuery.operationType} ${parsedGraphQLQuery.operationName} (${request.method} ${publicUrl})`
1089
- : `${request.method} ${publicUrl}`;
1090
- const handlerSuggestion = generateHandlerSuggestion();
1091
- const messageTemplate = [
1092
- `captured a request without a matching request handler:`,
1093
- ` \u2022 ${requestHeader}`,
1094
- handlerSuggestion,
1095
- `\
1096
- If you still wish to intercept this unhandled request, please create a request handler for it.
1097
- Read more: https://mswjs.io/docs/getting-started/mocks\
1098
- `,
1099
- ].filter(Boolean);
1100
- return messageTemplate.join('\n\n');
1101
- }
1102
- function applyStrategy(strategy) {
1103
- // Generate handler suggestions only when applying the strategy.
1104
- // This saves bandwidth for scenarios when developers opt-out
1105
- // from the default unhandled request handling strategy.
1106
- const message = generateUnhandledRequestMessage();
1107
- switch (strategy) {
1108
- case 'error': {
1109
- // Print a developer-friendly error.
1110
- devUtils.error('Error: %s', message);
1111
- // Throw an exception to halt request processing and not perform the original request.
1112
- throw new Error(devUtils.formatMessage('Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.'));
1113
- }
1114
- case 'warn': {
1115
- devUtils.warn('Warning: %s', message);
1116
- break;
1117
- }
1118
- case 'bypass':
1119
- break;
1120
- default:
1121
- throw new Error(devUtils.formatMessage('Failed to react to an unhandled request: unknown strategy "%s". Please provide one of the supported strategies ("bypass", "warn", "error") or a custom callback function as the value of the "onUnhandledRequest" option.', strategy));
1122
- }
1123
- }
1124
- if (typeof strategy === 'function') {
1125
- strategy(request, {
1126
- warning: applyStrategy.bind(null, 'warn'),
1127
- error: applyStrategy.bind(null, 'error'),
1128
- });
1129
- return;
1130
- }
1131
- applyStrategy(strategy);
1132
- }
1133
-
1134
- function readResponseCookies(request, response) {
1135
- store.add(Object.assign(Object.assign({}, request), { url: request.url.toString() }), response);
1136
- store.persist();
1137
- }
1138
-
1139
- function handleRequest(request, handlers, options, emitter, handleRequestOptions) {
1140
- var _a, _b, _c, _d;
1141
- return __awaiter(this, void 0, void 0, function* () {
1142
- emitter.emit('request:start', request);
1143
- // Perform bypassed requests (i.e. issued via "ctx.fetch") as-is.
1144
- if (request.headers.get('x-msw-bypass') === 'true') {
1145
- emitter.emit('request:end', request);
1146
- (_a = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.onPassthroughResponse) === null || _a === void 0 ? void 0 : _a.call(handleRequestOptions, request);
1147
- return;
1148
- }
1149
- // Resolve a mocked response from the list of request handlers.
1150
- const [lookupError, lookupResult] = yield until(() => {
1151
- return getResponse(request, handlers, handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.resolutionContext);
1152
- });
1153
- if (lookupError) {
1154
- // Allow developers to react to unhandled exceptions in request handlers.
1155
- emitter.emit('unhandledException', lookupError, request);
1156
- throw lookupError;
1157
- }
1158
- const { handler, response } = lookupResult;
1159
- // When there's no handler for the request, consider it unhandled.
1160
- // Allow the developer to react to such cases.
1161
- if (!handler) {
1162
- onUnhandledRequest(request, handlers, options.onUnhandledRequest);
1163
- emitter.emit('request:unhandled', request);
1164
- emitter.emit('request:end', request);
1165
- (_b = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.onPassthroughResponse) === null || _b === void 0 ? void 0 : _b.call(handleRequestOptions, request);
1166
- return;
1167
- }
1168
- // When the handled request returned no mocked response, warn the developer,
1169
- // as it may be an oversight on their part. Perform the request as-is.
1170
- if (!response) {
1171
- devUtils.warn(`\
1172
- Expected response resolver to return a mocked response Object, but got %s. The original response is going to be used instead.\
1173
- \n
1174
- \u2022 %s
1175
- %s\
1176
- `, response, handler.info.header, handler.info.callFrame);
1177
- emitter.emit('request:end', request);
1178
- (_c = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.onPassthroughResponse) === null || _c === void 0 ? void 0 : _c.call(handleRequestOptions, request);
1179
- return;
1180
- }
1181
- // When the developer explicitly returned "req.passthrough()" do not warn them.
1182
- // Perform the request as-is.
1183
- if (response.passthrough) {
1184
- emitter.emit('request:end', request);
1185
- (_d = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.onPassthroughResponse) === null || _d === void 0 ? void 0 : _d.call(handleRequestOptions, request);
1186
- return;
1187
- }
1188
- // Store all the received response cookies in the virtual cookie store.
1189
- readResponseCookies(request, response);
1190
- emitter.emit('request:match', request);
1191
- return new Promise((resolve) => {
1192
- var _a, _b, _c;
1193
- const requiredLookupResult = lookupResult;
1194
- const transformedResponse = ((_a = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.transformResponse) === null || _a === void 0 ? void 0 : _a.call(handleRequestOptions, response)) ||
1195
- response;
1196
- (_b = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.onMockedResponse) === null || _b === void 0 ? void 0 : _b.call(handleRequestOptions, transformedResponse, requiredLookupResult);
1197
- setTimeout(() => {
1198
- var _a;
1199
- (_a = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.onMockedResponseSent) === null || _a === void 0 ? void 0 : _a.call(handleRequestOptions, transformedResponse, requiredLookupResult);
1200
- emitter.emit('request:end', request);
1201
- resolve(transformedResponse);
1202
- }, (_c = response.delay) !== null && _c !== void 0 ? _c : 0);
1203
- });
1204
- });
1205
- }
1206
-
1207
- const createRequestListener = (context, options) => {
1208
- return (event, message) => __awaiter(void 0, void 0, void 0, function* () {
1209
- const channel = createBroadcastChannel(event);
1210
- try {
1211
- const request = parseWorkerRequest(message.payload);
1212
- yield handleRequest(request, context.requestHandlers, options, context.emitter, {
1213
- transformResponse(response) {
1214
- return Object.assign(Object.assign({}, response), { headers: response.headers.all() });
1215
- },
1216
- onPassthroughResponse() {
1217
- return channel.send({
1218
- type: 'MOCK_NOT_FOUND',
1219
- });
1220
- },
1221
- onMockedResponse(response) {
1222
- channel.send({
1223
- type: 'MOCK_SUCCESS',
1224
- payload: response,
1225
- });
1226
- },
1227
- onMockedResponseSent(response, { handler, publicRequest, parsedRequest }) {
1228
- if (!options.quiet) {
1229
- handler.log(publicRequest, response, handler, parsedRequest);
1230
- }
1231
- },
1232
- });
1233
- }
1234
- catch (error) {
1235
- if (error instanceof NetworkError) {
1236
- // Treat emulated network error differently,
1237
- // as it is an intended exception in a request handler.
1238
- return channel.send({
1239
- type: 'NETWORK_ERROR',
1240
- payload: {
1241
- name: error.name,
1242
- message: error.message,
1243
- },
1244
- });
1245
- }
1246
- if (error instanceof Error) {
1247
- // Treat all the other exceptions in a request handler
1248
- // as unintended, alerting that there is a problem needs fixing.
1249
- channel.send({
1250
- type: 'INTERNAL_ERROR',
1251
- payload: {
1252
- status: 500,
1253
- body: JSON.stringify({
1254
- errorType: error.constructor.name,
1255
- message: error.message,
1256
- location: error.stack,
1257
- }),
1258
- },
1259
- });
1260
- }
1261
- }
1262
- });
1263
1781
  };
1264
1782
 
1265
- function requestIntegrityCheck(context, serviceWorker) {
1266
- return __awaiter(this, void 0, void 0, function* () {
1267
- // Signal Service Worker to report back its integrity
1268
- context.workerChannel.send('INTEGRITY_CHECK_REQUEST');
1269
- const { payload: actualChecksum } = yield context.events.once('INTEGRITY_CHECK_RESPONSE');
1270
- // Compare the response from the Service Worker and the
1271
- // global variable set by Rollup during the build.
1272
- if (actualChecksum !== "02f4ad4a2797f85668baf196e553d929") {
1273
- throw new Error(`Currently active Service Worker (${actualChecksum}) is behind the latest published one (${"02f4ad4a2797f85668baf196e553d929"}).`);
1274
- }
1275
- return serviceWorker;
1276
- });
1277
- }
1278
-
1279
- /**
1280
- * Intercepts and defers any requests on the page
1281
- * until the Service Worker instance is ready.
1282
- * Must only be used in a browser.
1283
- */
1284
- function deferNetworkRequestsUntil(predicatePromise) {
1285
- // Defer any `XMLHttpRequest` requests until the Service Worker is ready.
1286
- const originalXhrSend = window.XMLHttpRequest.prototype.send;
1287
- window.XMLHttpRequest.prototype.send = function (...args) {
1288
- // Keep this function synchronous to comply with `XMLHttpRequest.prototype.send`,
1289
- // because that method is always synchronous.
1290
- until(() => predicatePromise).then(() => {
1291
- window.XMLHttpRequest.prototype.send = originalXhrSend;
1292
- this.send(...args);
1293
- });
1294
- };
1295
- // Defer any `fetch` requests until the Service Worker is ready.
1296
- const originalFetch = window.fetch;
1297
- window.fetch = (...args) => __awaiter(this, void 0, void 0, function* () {
1298
- yield until(() => predicatePromise);
1299
- window.fetch = originalFetch;
1300
- return window.fetch(...args);
1301
- });
1302
- }
1303
-
1304
- function createResponseListener(context) {
1305
- return (_, message) => {
1306
- var _a;
1307
- const { payload: responseJson } = message;
1308
- /**
1309
- * CORS requests with `mode: "no-cors"` result in "opaque" responses.
1310
- * That kind of responses cannot be manipulated in JavaScript due
1311
- * to the security considerations.
1312
- * @see https://fetch.spec.whatwg.org/#concept-filtered-response-opaque
1313
- * @see https://github.com/mswjs/msw/issues/529
1314
- */
1315
- if ((_a = responseJson.type) === null || _a === void 0 ? void 0 : _a.includes('opaque')) {
1316
- return;
1317
- }
1318
- const response = new Response(responseJson.body || null, responseJson);
1319
- const isMockedResponse = response.headers.get('x-powered-by') === 'msw';
1320
- if (isMockedResponse) {
1321
- context.emitter.emit('response:mocked', response, responseJson.requestId);
1322
- }
1323
- else {
1324
- context.emitter.emit('response:bypass', response, responseJson.requestId);
1325
- }
1326
- };
1327
- }
1328
-
1329
- function validateWorkerScope(registration, options) {
1330
- if (!(options === null || options === void 0 ? void 0 : options.quiet) && !location.href.startsWith(registration.scope)) {
1331
- devUtils.warn(`\
1332
- Cannot intercept requests on this page because it's outside of the worker's scope ("${registration.scope}"). If you wish to mock API requests on this page, you must resolve this scope issue.
1783
+ // src/utils/internal/requestHandlerUtils.ts
1784
+ init_esm_shims();
1785
+ function use(currentHandlers, ...handlers) {
1786
+ currentHandlers.unshift(...handlers);
1787
+ }
1788
+ function restoreHandlers(handlers) {
1789
+ handlers.forEach((handler) => {
1790
+ handler.markAsSkipped(false);
1791
+ });
1792
+ }
1793
+ function resetHandlers(initialHandlers, ...nextHandlers) {
1794
+ return nextHandlers.length > 0 ? [...nextHandlers] : [...initialHandlers];
1795
+ }
1333
1796
 
1334
- - (Recommended) Register the worker at the root level ("/") of your application.
1335
- - Set the "Service-Worker-Allowed" response header to allow out-of-scope workers.\
1336
- `);
1337
- }
1338
- }
1339
-
1340
- const createStartHandler = (context) => {
1341
- return function start(options, customOptions) {
1342
- const startWorkerInstance = () => __awaiter(this, void 0, void 0, function* () {
1343
- // Remove all previously existing event listeners.
1344
- // This way none of the listeners persists between Fast refresh
1345
- // of the application's code.
1346
- context.events.removeAllListeners();
1347
- // Handle requests signaled by the worker.
1348
- context.workerChannel.on('REQUEST', createRequestListener(context, options));
1349
- context.workerChannel.on('RESPONSE', createResponseListener(context));
1350
- const instance = yield getWorkerInstance(options.serviceWorker.url, options.serviceWorker.options, options.findWorker);
1351
- const [worker, registration] = instance;
1352
- if (!worker) {
1353
- const missingWorkerMessage = (customOptions === null || customOptions === void 0 ? void 0 : customOptions.findWorker)
1354
- ? devUtils.formatMessage(`Failed to locate the Service Worker registration using a custom "findWorker" predicate.
1797
+ // src/setupWorker/start/utils/prepareStartHandler.ts
1798
+ init_esm_shims();
1799
+ var DEFAULT_START_OPTIONS = {
1800
+ serviceWorker: {
1801
+ url: "/mockServiceWorker.js",
1802
+ options: null
1803
+ },
1804
+ quiet: false,
1805
+ waitUntilReady: true,
1806
+ onUnhandledRequest: "warn",
1807
+ findWorker(scriptURL, mockServiceWorkerUrl) {
1808
+ return scriptURL === mockServiceWorkerUrl;
1809
+ }
1810
+ };
1811
+ function resolveStartOptions(initialOptions) {
1812
+ return mergeRight(DEFAULT_START_OPTIONS, initialOptions || {});
1813
+ }
1814
+ function prepareStartHandler(handler, context) {
1815
+ return (initialOptions) => {
1816
+ context.startOptions = resolveStartOptions(initialOptions);
1817
+ return handler(context.startOptions, initialOptions || {});
1818
+ };
1819
+ }
1355
1820
 
1356
- Please ensure that the custom predicate properly locates the Service Worker registration at "%s".
1357
- More details: https://mswjs.io/docs/api/setup-worker/start#findworker
1358
- `, options.serviceWorker.url)
1359
- : devUtils.formatMessage(`Failed to locate the Service Worker registration.
1821
+ // src/setupWorker/start/createFallbackStart.ts
1822
+ init_esm_shims();
1823
+
1824
+ // src/utils/worker/createFallbackRequestListener.ts
1825
+ init_esm_shims();
1826
+ import { createInterceptor } from "@mswjs/interceptors";
1827
+ import { interceptFetch } from "@mswjs/interceptors/lib/interceptors/fetch";
1828
+ import { interceptXMLHttpRequest } from "@mswjs/interceptors/lib/interceptors/XMLHttpRequest";
1829
+
1830
+ // src/utils/request/parseIsomorphicRequest.ts
1831
+ init_esm_shims();
1832
+ function parseIsomorphicRequest(request) {
1833
+ const mockedRequest = {
1834
+ id: request.id,
1835
+ url: request.url,
1836
+ method: request.method,
1837
+ body: parseBody(request.body, request.headers),
1838
+ credentials: request.credentials || "same-origin",
1839
+ headers: request.headers,
1840
+ cookies: {},
1841
+ redirect: "manual",
1842
+ referrer: "",
1843
+ keepalive: false,
1844
+ cache: "default",
1845
+ mode: "cors",
1846
+ referrerPolicy: "no-referrer",
1847
+ integrity: "",
1848
+ destination: "document",
1849
+ bodyUsed: false,
1850
+ passthrough
1851
+ };
1852
+ setRequestCookies(mockedRequest);
1853
+ return mockedRequest;
1854
+ }
1360
1855
 
1361
- This most likely means that the worker script URL "%s" cannot resolve against the actual public hostname (%s). This may happen if your application runs behind a proxy, or has a dynamic hostname.
1856
+ // src/utils/worker/createFallbackRequestListener.ts
1857
+ function createFallbackRequestListener(context, options) {
1858
+ const interceptor = createInterceptor({
1859
+ modules: [interceptFetch, interceptXMLHttpRequest],
1860
+ async resolver(request) {
1861
+ const mockedRequest = parseIsomorphicRequest(request);
1862
+ return handleRequest(mockedRequest, context.requestHandlers, options, context.emitter, {
1863
+ transformResponse(response2) {
1864
+ return {
1865
+ status: response2.status,
1866
+ statusText: response2.statusText,
1867
+ headers: response2.headers.all(),
1868
+ body: response2.body
1869
+ };
1870
+ },
1871
+ onMockedResponseSent(response2, { handler, publicRequest, parsedRequest }) {
1872
+ if (!options.quiet) {
1873
+ handler.log(publicRequest, response2, handler, parsedRequest);
1874
+ }
1875
+ }
1876
+ });
1877
+ }
1878
+ });
1879
+ interceptor.apply();
1880
+ return interceptor;
1881
+ }
1362
1882
 
1363
- Please consider using a custom "serviceWorker.url" option to point to the actual worker script location, or a custom "findWorker" option to resolve the Service Worker registration manually. More details: https://mswjs.io/docs/api/setup-worker/start`, options.serviceWorker.url, location.host);
1364
- throw new Error(missingWorkerMessage);
1365
- }
1366
- context.worker = worker;
1367
- context.registration = registration;
1368
- context.events.addListener(window, 'beforeunload', () => {
1369
- if (worker.state !== 'redundant') {
1370
- // Notify the Service Worker that this client has closed.
1371
- // Internally, it's similar to disabling the mocking, only
1372
- // client close event has a handler that self-terminates
1373
- // the Service Worker when there are no open clients.
1374
- context.workerChannel.send('CLIENT_CLOSED');
1375
- }
1376
- // Make sure we're always clearing the interval - there are reports that not doing this can
1377
- // cause memory leaks in headless browser environments.
1378
- window.clearInterval(context.keepAliveInterval);
1379
- });
1380
- // Check if the active Service Worker is the latest published one
1381
- const [integrityError] = yield until(() => requestIntegrityCheck(context, worker));
1382
- if (integrityError) {
1383
- devUtils.error(`\
1384
- Detected outdated Service Worker: ${integrityError.message}
1883
+ // src/setupWorker/start/createFallbackStart.ts
1884
+ function createFallbackStart(context) {
1885
+ return async function start(options) {
1886
+ context.fallbackInterceptor = createFallbackRequestListener(context, options);
1887
+ printStartMessage({
1888
+ message: "Mocking enabled (fallback mode).",
1889
+ quiet: options.quiet
1890
+ });
1891
+ return void 0;
1892
+ };
1893
+ }
1385
1894
 
1386
- The mocking is still enabled, but it's highly recommended that you update your Service Worker by running:
1895
+ // src/setupWorker/stop/createFallbackStop.ts
1896
+ init_esm_shims();
1897
+ function createFallbackStop(context) {
1898
+ return function stop() {
1899
+ var _a, _b;
1900
+ (_a = context.fallbackInterceptor) == null ? void 0 : _a.restore();
1901
+ printStopMessage({ quiet: (_b = context.startOptions) == null ? void 0 : _b.quiet });
1902
+ };
1903
+ }
1387
1904
 
1388
- $ npx msw init <PUBLIC_DIR>
1905
+ // src/utils/internal/pipeEvents.ts
1906
+ init_esm_shims();
1907
+ function pipeEvents(source, destination) {
1908
+ const rawEmit = source.emit;
1909
+ if (rawEmit._isPiped) {
1910
+ return;
1911
+ }
1912
+ source.emit = function(event, ...data2) {
1913
+ destination.emit(event, ...data2);
1914
+ return rawEmit.call(this, event, ...data2);
1915
+ };
1916
+ source.emit._isPiped = true;
1917
+ }
1389
1918
 
1390
- This is necessary to ensure that the Service Worker is in sync with the library to guarantee its stability.
1391
- If this message still persists after updating, please report an issue: https://github.com/open-draft/msw/issues\
1392
- `);
1393
- }
1394
- context.keepAliveInterval = window.setInterval(() => context.workerChannel.send('KEEPALIVE_REQUEST'), 5000);
1395
- // Warn the user when loading the page that lies outside
1396
- // of the worker's scope.
1397
- validateWorkerScope(registration, context.startOptions);
1398
- return registration;
1399
- });
1400
- const workerRegistration = startWorkerInstance().then((registration) => __awaiter(this, void 0, void 0, function* () {
1401
- const pendingInstance = registration.installing || registration.waiting;
1402
- // Wait until the worker is activated.
1403
- // Assume the worker is already activated if there's no pending registration
1404
- // (i.e. when reloading the page after a successful activation).
1405
- if (pendingInstance) {
1406
- yield new Promise((resolve) => {
1407
- pendingInstance.addEventListener('statechange', () => {
1408
- if (pendingInstance.state === 'activated') {
1409
- return resolve();
1410
- }
1411
- });
1412
- });
1413
- }
1414
- // Print the activation message only after the worker has been activated.
1415
- yield enableMocking(context, options).catch((error) => {
1416
- throw new Error(`Failed to enable mocking: ${error === null || error === void 0 ? void 0 : error.message}`);
1417
- });
1418
- return registration;
1419
- }));
1420
- // Defer any network requests until the Service Worker instance is ready.
1421
- // This prevents a race condition between the Service Worker registration
1422
- // and application's runtime requests (i.e. requests on mount).
1423
- if (options.waitUntilReady) {
1424
- deferNetworkRequestsUntil(workerRegistration);
1425
- }
1426
- return workerRegistration;
1427
- };
1428
- };
1919
+ // src/setupWorker/setupWorker.ts
1920
+ var listeners = [];
1921
+ function setupWorker(...requestHandlers) {
1922
+ requestHandlers.forEach((handler) => {
1923
+ if (Array.isArray(handler))
1924
+ throw new Error(devUtils.formatMessage('Failed to call "setupWorker" given an Array of request handlers (setupWorker([a, b])), expected to receive each handler individually: setupWorker(a, b).'));
1925
+ });
1926
+ if (isNodeProcess3()) {
1927
+ throw new Error(devUtils.formatMessage("Failed to execute `setupWorker` in a non-browser environment. Consider using `setupServer` for Node.js environment instead."));
1928
+ }
1929
+ const emitter = new StrictEventEmitter();
1930
+ const publicEmitter = new StrictEventEmitter();
1931
+ pipeEvents(emitter, publicEmitter);
1932
+ const context = {
1933
+ isMockingEnabled: false,
1934
+ startOptions: void 0,
1935
+ worker: null,
1936
+ registration: null,
1937
+ requestHandlers: [...requestHandlers],
1938
+ emitter,
1939
+ workerChannel: {
1940
+ on(eventType, callback) {
1941
+ context.events.addListener(navigator.serviceWorker, "message", (event) => {
1942
+ if (event.source !== context.worker) {
1943
+ return;
1944
+ }
1945
+ const message = jsonParse(event.data);
1946
+ if (!message) {
1947
+ return;
1948
+ }
1949
+ if (message.type === eventType) {
1950
+ callback(event, message);
1951
+ }
1952
+ });
1953
+ },
1954
+ send(type) {
1955
+ var _a;
1956
+ (_a = context.worker) == null ? void 0 : _a.postMessage(type);
1957
+ }
1958
+ },
1959
+ events: {
1960
+ addListener(target, eventType, callback) {
1961
+ target.addEventListener(eventType, callback);
1962
+ listeners.push({ eventType, target, callback });
1963
+ return () => {
1964
+ target.removeEventListener(eventType, callback);
1965
+ };
1966
+ },
1967
+ removeAllListeners() {
1968
+ for (const { target, eventType, callback } of listeners) {
1969
+ target.removeEventListener(eventType, callback);
1970
+ }
1971
+ listeners = [];
1972
+ },
1973
+ once(eventType) {
1974
+ const bindings = [];
1975
+ return new Promise((resolve, reject) => {
1976
+ const handleIncomingMessage = (event) => {
1977
+ try {
1978
+ const message = JSON.parse(event.data);
1979
+ if (message.type === eventType) {
1980
+ resolve(message);
1981
+ }
1982
+ } catch (error2) {
1983
+ reject(error2);
1984
+ }
1985
+ };
1986
+ bindings.push(context.events.addListener(navigator.serviceWorker, "message", handleIncomingMessage), context.events.addListener(navigator.serviceWorker, "messageerror", reject));
1987
+ }).finally(() => {
1988
+ bindings.forEach((unbind) => unbind());
1989
+ });
1990
+ }
1991
+ },
1992
+ useFallbackMode: !("serviceWorker" in navigator) || location.protocol === "file:"
1993
+ };
1994
+ const startHandler = context.useFallbackMode ? createFallbackStart(context) : createStartHandler(context);
1995
+ const stopHandler = context.useFallbackMode ? createFallbackStop(context) : createStop(context);
1996
+ return {
1997
+ start: prepareStartHandler(startHandler, context),
1998
+ stop() {
1999
+ context.events.removeAllListeners();
2000
+ context.emitter.removeAllListeners();
2001
+ publicEmitter.removeAllListeners();
2002
+ stopHandler();
2003
+ },
2004
+ use(...handlers) {
2005
+ use(context.requestHandlers, ...handlers);
2006
+ },
2007
+ restoreHandlers() {
2008
+ restoreHandlers(context.requestHandlers);
2009
+ },
2010
+ resetHandlers(...nextHandlers) {
2011
+ context.requestHandlers = resetHandlers(requestHandlers, ...nextHandlers);
2012
+ },
2013
+ printHandlers() {
2014
+ context.requestHandlers.forEach((handler) => {
2015
+ const { header, callFrame } = handler.info;
2016
+ const pragma = handler.info.hasOwnProperty("operationType") ? "[graphql]" : "[rest]";
2017
+ console.groupCollapsed(`${pragma} ${header}`);
2018
+ if (callFrame) {
2019
+ console.log(`Declaration: ${callFrame}`);
2020
+ }
2021
+ console.log("Handler:", handler);
2022
+ if (handler instanceof RestHandler) {
2023
+ console.log("Match:", `https://mswjs.io/repl?path=${handler.info.path}`);
2024
+ }
2025
+ console.groupEnd();
2026
+ });
2027
+ },
2028
+ events: {
2029
+ on(...args) {
2030
+ return publicEmitter.on(...args);
2031
+ },
2032
+ removeListener(...args) {
2033
+ return publicEmitter.removeListener(...args);
2034
+ },
2035
+ removeAllListeners(...args) {
2036
+ return publicEmitter.removeAllListeners(...args);
2037
+ }
2038
+ }
2039
+ };
2040
+ }
1429
2041
 
1430
- function printStopMessage(args = {}) {
1431
- if (args.quiet) {
1432
- return;
1433
- }
1434
- console.log(`%c${devUtils.formatMessage('Mocking disabled.')}`, 'color:orangered;font-weight:bold;');
1435
- }
1436
-
1437
- const createStop = (context) => {
1438
- return function stop() {
1439
- var _a;
1440
- // Warn developers calling "worker.stop()" more times than necessary.
1441
- // This likely indicates a mistake in their code.
1442
- if (!context.isMockingEnabled) {
1443
- devUtils.warn('Found a redundant "worker.stop()" call. Note that stopping the worker while mocking already stopped has no effect. Consider removing this "worker.stop()" call.');
1444
- return;
1445
- }
1446
- /**
1447
- * Signal the Service Worker to disable mocking for this client.
1448
- * Use this an an explicit way to stop the mocking, while preserving
1449
- * the worker-client relation. Does not affect the worker's lifecycle.
1450
- */
1451
- context.workerChannel.send('MOCK_DEACTIVATE');
1452
- context.isMockingEnabled = false;
1453
- window.clearInterval(context.keepAliveInterval);
1454
- printStopMessage({ quiet: (_a = context.startOptions) === null || _a === void 0 ? void 0 : _a.quiet });
1455
- };
2042
+ // src/rest.ts
2043
+ init_esm_shims();
2044
+ function createRestHandler(method) {
2045
+ return (path, resolver) => {
2046
+ return new RestHandler(method, path, resolver);
2047
+ };
2048
+ }
2049
+ var rest = {
2050
+ all: createRestHandler(/.+/),
2051
+ head: createRestHandler("HEAD" /* HEAD */),
2052
+ get: createRestHandler("GET" /* GET */),
2053
+ post: createRestHandler("POST" /* POST */),
2054
+ put: createRestHandler("PUT" /* PUT */),
2055
+ delete: createRestHandler("DELETE" /* DELETE */),
2056
+ patch: createRestHandler("PATCH" /* PATCH */),
2057
+ options: createRestHandler("OPTIONS" /* OPTIONS */)
1456
2058
  };
1457
2059
 
1458
- function use(currentHandlers, ...handlers) {
1459
- currentHandlers.unshift(...handlers);
1460
- }
1461
- function restoreHandlers(handlers) {
1462
- handlers.forEach((handler) => {
1463
- handler.markAsSkipped(false);
1464
- });
1465
- }
1466
- function resetHandlers(initialHandlers, ...nextHandlers) {
1467
- return nextHandlers.length > 0 ? [...nextHandlers] : [...initialHandlers];
1468
- }
1469
-
1470
- const DEFAULT_START_OPTIONS = {
1471
- serviceWorker: {
1472
- url: '/mockServiceWorker.js',
1473
- options: null,
1474
- },
1475
- quiet: false,
1476
- waitUntilReady: true,
1477
- onUnhandledRequest: 'warn',
1478
- findWorker(scriptURL, mockServiceWorkerUrl) {
1479
- return scriptURL === mockServiceWorkerUrl;
1480
- },
1481
- };
1482
- /**
1483
- * Returns resolved worker start options, merging the default options
1484
- * with the given custom options.
1485
- */
1486
- function resolveStartOptions(initialOptions) {
1487
- return mergeRight(DEFAULT_START_OPTIONS, initialOptions || {});
1488
- }
1489
- function prepareStartHandler(handler, context) {
1490
- return (initialOptions) => {
1491
- context.startOptions = resolveStartOptions(initialOptions);
1492
- return handler(context.startOptions, initialOptions || {});
1493
- };
1494
- }
1495
-
1496
- /**
1497
- * Converts a given isomorphic request to a `MockedRequest` instance.
1498
- */
1499
- function parseIsomorphicRequest(request) {
1500
- const mockedRequest = {
1501
- id: request.id,
1502
- url: request.url,
1503
- method: request.method,
1504
- body: parseBody(request.body, request.headers),
1505
- credentials: request.credentials || 'same-origin',
1506
- headers: request.headers,
1507
- cookies: {},
1508
- redirect: 'manual',
1509
- referrer: '',
1510
- keepalive: false,
1511
- cache: 'default',
1512
- mode: 'cors',
1513
- referrerPolicy: 'no-referrer',
1514
- integrity: '',
1515
- destination: 'document',
1516
- bodyUsed: false,
1517
- passthrough,
1518
- };
1519
- // Attach all the cookies from the virtual cookie store.
1520
- setRequestCookies(mockedRequest);
1521
- return mockedRequest;
1522
- }
1523
-
1524
- function createFallbackRequestListener(context, options) {
1525
- const interceptor = createInterceptor({
1526
- modules: [interceptFetch, interceptXMLHttpRequest],
1527
- resolver(request) {
1528
- return __awaiter(this, void 0, void 0, function* () {
1529
- const mockedRequest = parseIsomorphicRequest(request);
1530
- return handleRequest(mockedRequest, context.requestHandlers, options, context.emitter, {
1531
- transformResponse(response) {
1532
- return {
1533
- status: response.status,
1534
- statusText: response.statusText,
1535
- headers: response.headers.all(),
1536
- body: response.body,
1537
- };
1538
- },
1539
- onMockedResponseSent(response, { handler, publicRequest, parsedRequest }) {
1540
- if (!options.quiet) {
1541
- handler.log(publicRequest, response, handler, parsedRequest);
1542
- }
1543
- },
1544
- });
1545
- });
1546
- },
1547
- });
1548
- interceptor.apply();
1549
- return interceptor;
1550
- }
1551
-
1552
- function createFallbackStart(context) {
1553
- return function start(options) {
1554
- return __awaiter(this, void 0, void 0, function* () {
1555
- context.fallbackInterceptor = createFallbackRequestListener(context, options);
1556
- printStartMessage({
1557
- message: 'Mocking enabled (fallback mode).',
1558
- quiet: options.quiet,
1559
- });
1560
- return undefined;
1561
- });
1562
- };
1563
- }
1564
-
1565
- function createFallbackStop(context) {
1566
- return function stop() {
1567
- var _a, _b;
1568
- (_a = context.fallbackInterceptor) === null || _a === void 0 ? void 0 : _a.restore();
1569
- printStopMessage({ quiet: (_b = context.startOptions) === null || _b === void 0 ? void 0 : _b.quiet });
1570
- };
1571
- }
1572
-
1573
- /**
1574
- * Pipes all emitted events from one emitter to another.
1575
- */
1576
- function pipeEvents(source, destination) {
1577
- const rawEmit = source.emit;
1578
- // @ts-ignore
1579
- if (rawEmit._isPiped) {
1580
- return;
1581
- }
1582
- source.emit = function (event, ...data) {
1583
- destination.emit(event, ...data);
1584
- return rawEmit.call(this, event, ...data);
1585
- };
1586
- // @ts-ignore
1587
- source.emit._isPiped = true;
1588
- }
1589
-
1590
- // Declare the list of event handlers on the module's scope
1591
- // so it persists between Fash refreshes of the application's code.
1592
- let listeners = [];
1593
- /**
1594
- * Creates a new mock Service Worker registration
1595
- * with the given request handlers.
1596
- * @param {RequestHandler[]} requestHandlers List of request handlers
1597
- * @see {@link https://mswjs.io/docs/api/setup-worker `setupWorker`}
1598
- */
1599
- function setupWorker(...requestHandlers) {
1600
- requestHandlers.forEach((handler) => {
1601
- if (Array.isArray(handler))
1602
- throw new Error(devUtils.formatMessage('Failed to call "setupWorker" given an Array of request handlers (setupWorker([a, b])), expected to receive each handler individually: setupWorker(a, b).'));
1603
- });
1604
- // Error when attempting to run this function in a Node.js environment.
1605
- if (lib$3.exports.isNodeProcess()) {
1606
- throw new Error(devUtils.formatMessage('Failed to execute `setupWorker` in a non-browser environment. Consider using `setupServer` for Node.js environment instead.'));
1607
- }
1608
- const emitter = new lib$1.StrictEventEmitter();
1609
- const publicEmitter = new lib$1.StrictEventEmitter();
1610
- pipeEvents(emitter, publicEmitter);
1611
- const context = {
1612
- // Mocking is not considered enabled until the worker
1613
- // signals back the successful activation event.
1614
- isMockingEnabled: false,
1615
- startOptions: undefined,
1616
- worker: null,
1617
- registration: null,
1618
- requestHandlers: [...requestHandlers],
1619
- emitter,
1620
- workerChannel: {
1621
- on(eventType, callback) {
1622
- context.events.addListener(navigator.serviceWorker, 'message', (event) => {
1623
- // Avoid messages broadcasted from unrelated workers.
1624
- if (event.source !== context.worker) {
1625
- return;
1626
- }
1627
- const message = jsonParse(event.data);
1628
- if (!message) {
1629
- return;
1630
- }
1631
- if (message.type === eventType) {
1632
- callback(event, message);
1633
- }
1634
- });
1635
- },
1636
- send(type) {
1637
- var _a;
1638
- (_a = context.worker) === null || _a === void 0 ? void 0 : _a.postMessage(type);
1639
- },
1640
- },
1641
- events: {
1642
- addListener(target, eventType, callback) {
1643
- target.addEventListener(eventType, callback);
1644
- listeners.push({ eventType, target, callback });
1645
- return () => {
1646
- target.removeEventListener(eventType, callback);
1647
- };
1648
- },
1649
- removeAllListeners() {
1650
- for (const { target, eventType, callback } of listeners) {
1651
- target.removeEventListener(eventType, callback);
1652
- }
1653
- listeners = [];
1654
- },
1655
- once(eventType) {
1656
- const bindings = [];
1657
- return new Promise((resolve, reject) => {
1658
- const handleIncomingMessage = (event) => {
1659
- try {
1660
- const message = JSON.parse(event.data);
1661
- if (message.type === eventType) {
1662
- resolve(message);
1663
- }
1664
- }
1665
- catch (error) {
1666
- reject(error);
1667
- }
1668
- };
1669
- bindings.push(context.events.addListener(navigator.serviceWorker, 'message', handleIncomingMessage), context.events.addListener(navigator.serviceWorker, 'messageerror', reject));
1670
- }).finally(() => {
1671
- bindings.forEach((unbind) => unbind());
1672
- });
1673
- },
1674
- },
1675
- useFallbackMode: !('serviceWorker' in navigator) || location.protocol === 'file:',
1676
- };
1677
- const startHandler = context.useFallbackMode
1678
- ? createFallbackStart(context)
1679
- : createStartHandler(context);
1680
- const stopHandler = context.useFallbackMode
1681
- ? createFallbackStop(context)
1682
- : createStop(context);
1683
- return {
1684
- start: prepareStartHandler(startHandler, context),
1685
- stop() {
1686
- context.events.removeAllListeners();
1687
- context.emitter.removeAllListeners();
1688
- publicEmitter.removeAllListeners();
1689
- stopHandler();
1690
- },
1691
- use(...handlers) {
1692
- use(context.requestHandlers, ...handlers);
1693
- },
1694
- restoreHandlers() {
1695
- restoreHandlers(context.requestHandlers);
1696
- },
1697
- resetHandlers(...nextHandlers) {
1698
- context.requestHandlers = resetHandlers(requestHandlers, ...nextHandlers);
1699
- },
1700
- printHandlers() {
1701
- context.requestHandlers.forEach((handler) => {
1702
- const { header, callFrame } = handler.info;
1703
- const pragma = handler.info.hasOwnProperty('operationType')
1704
- ? '[graphql]'
1705
- : '[rest]';
1706
- console.groupCollapsed(`${pragma} ${header}`);
1707
- if (callFrame) {
1708
- console.log(`Declaration: ${callFrame}`);
1709
- }
1710
- console.log('Handler:', handler);
1711
- if (handler instanceof RestHandler) {
1712
- console.log('Match:', `https://mswjs.io/repl?path=${handler.info.path}`);
1713
- }
1714
- console.groupEnd();
1715
- });
1716
- },
1717
- events: {
1718
- on(...args) {
1719
- return publicEmitter.on(...args);
1720
- },
1721
- removeListener(...args) {
1722
- return publicEmitter.removeListener(...args);
1723
- },
1724
- removeAllListeners(...args) {
1725
- return publicEmitter.removeAllListeners(...args);
1726
- },
1727
- },
1728
- };
1729
- }
1730
-
1731
- export { handleRequest, parseIsomorphicRequest, setupWorker };
2060
+ // src/graphql.ts
2061
+ init_esm_shims();
2062
+ import { OperationTypeNode as OperationTypeNode2 } from "graphql";
2063
+ function createScopedGraphQLHandler(operationType, url) {
2064
+ return (operationName, resolver) => {
2065
+ return new GraphQLHandler(operationType, operationName, url, resolver);
2066
+ };
2067
+ }
2068
+ function createGraphQLOperationHandler(url) {
2069
+ return (resolver) => {
2070
+ return new GraphQLHandler("all", new RegExp(".*"), url, resolver);
2071
+ };
2072
+ }
2073
+ var standardGraphQLHandlers = {
2074
+ operation: createGraphQLOperationHandler("*"),
2075
+ query: createScopedGraphQLHandler(OperationTypeNode2.QUERY, "*"),
2076
+ mutation: createScopedGraphQLHandler(OperationTypeNode2.MUTATION, "*")
2077
+ };
2078
+ function createGraphQLLink(url) {
2079
+ return {
2080
+ operation: createGraphQLOperationHandler(url),
2081
+ query: createScopedGraphQLHandler(OperationTypeNode2.QUERY, url),
2082
+ mutation: createScopedGraphQLHandler(OperationTypeNode2.MUTATION, url)
2083
+ };
2084
+ }
2085
+ var graphql = __spreadProps(__spreadValues({}, standardGraphQLHandlers), {
2086
+ link: createGraphQLLink
2087
+ });
2088
+ export {
2089
+ GraphQLHandler,
2090
+ RESTMethods,
2091
+ RequestHandler,
2092
+ RestHandler,
2093
+ cleanUrl,
2094
+ compose,
2095
+ context_exports as context,
2096
+ createResponseComposition,
2097
+ defaultContext,
2098
+ defaultResponse,
2099
+ graphql,
2100
+ graphqlContext,
2101
+ handleRequest,
2102
+ matchRequestUrl,
2103
+ parseIsomorphicRequest,
2104
+ response,
2105
+ rest,
2106
+ restContext,
2107
+ setupWorker
2108
+ };
2109
+ //# sourceMappingURL=index.js.map