msw 1.3.2 → 2.0.1

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 (169) hide show
  1. package/README.md +45 -29
  2. package/browser/package.json +5 -0
  3. package/cli/init.js +3 -3
  4. package/config/constants.js +1 -2
  5. package/lib/browser/index.d.ts +104 -0
  6. package/lib/browser/index.js +752 -0
  7. package/lib/browser/index.mjs +734 -0
  8. package/lib/core/GraphQLHandler-b42ca96f.d.ts +74 -0
  9. package/lib/core/HttpResponse.d.ts +2 -0
  10. package/lib/core/HttpResponse.js +94 -0
  11. package/lib/core/HttpResponse.mjs +77 -0
  12. package/lib/core/RequestHandler-1a5dbdc7.d.ts +172 -0
  13. package/lib/core/SetupApi.d.ts +26 -0
  14. package/lib/core/SetupApi.js +83 -0
  15. package/lib/core/SetupApi.mjs +63 -0
  16. package/lib/core/bypass.d.ts +16 -0
  17. package/lib/core/bypass.js +36 -0
  18. package/lib/core/bypass.mjs +16 -0
  19. package/lib/core/delay.d.ts +18 -0
  20. package/lib/core/delay.js +92 -0
  21. package/lib/core/delay.mjs +72 -0
  22. package/lib/core/graphql.d.ts +109 -0
  23. package/lib/core/graphql.js +112 -0
  24. package/lib/core/graphql.mjs +96 -0
  25. package/lib/core/handlers/GraphQLHandler.d.ts +5 -0
  26. package/lib/core/handlers/GraphQLHandler.js +145 -0
  27. package/lib/core/handlers/GraphQLHandler.mjs +130 -0
  28. package/lib/core/handlers/HttpHandler.d.ts +62 -0
  29. package/lib/core/handlers/HttpHandler.js +149 -0
  30. package/lib/core/handlers/HttpHandler.mjs +133 -0
  31. package/lib/core/handlers/RequestHandler.d.ts +2 -0
  32. package/lib/core/handlers/RequestHandler.js +180 -0
  33. package/lib/core/handlers/RequestHandler.mjs +162 -0
  34. package/lib/core/http.d.ts +26 -0
  35. package/lib/core/http.js +39 -0
  36. package/lib/core/http.mjs +22 -0
  37. package/lib/core/http.spec.d.ts +2 -0
  38. package/lib/core/http.spec.js +15 -0
  39. package/lib/core/http.spec.mjs +14 -0
  40. package/lib/core/index.d.ts +18 -0
  41. package/lib/core/index.js +49 -0
  42. package/lib/core/index.mjs +28 -0
  43. package/lib/core/passthrough.d.ts +17 -0
  44. package/lib/core/passthrough.js +32 -0
  45. package/lib/core/passthrough.mjs +12 -0
  46. package/lib/core/sharedOptions.d.ts +66 -0
  47. package/lib/core/sharedOptions.js +16 -0
  48. package/lib/core/sharedOptions.mjs +0 -0
  49. package/lib/core/typeUtils.d.ts +7 -0
  50. package/lib/core/typeUtils.js +16 -0
  51. package/lib/core/typeUtils.mjs +0 -0
  52. package/lib/core/utils/HttpResponse/decorators.d.ts +12 -0
  53. package/lib/core/utils/HttpResponse/decorators.js +80 -0
  54. package/lib/core/utils/HttpResponse/decorators.mjs +52 -0
  55. package/lib/core/utils/getResponse.d.ts +2 -0
  56. package/lib/core/utils/getResponse.js +64 -0
  57. package/lib/core/utils/getResponse.mjs +44 -0
  58. package/lib/core/utils/handleRequest.d.ts +30 -0
  59. package/lib/core/utils/handleRequest.js +102 -0
  60. package/lib/core/utils/handleRequest.mjs +82 -0
  61. package/lib/core/utils/internal/Disposable.d.ts +7 -0
  62. package/lib/core/utils/internal/Disposable.js +53 -0
  63. package/lib/core/utils/internal/Disposable.mjs +33 -0
  64. package/lib/core/utils/internal/checkGlobals.d.ts +3 -0
  65. package/lib/core/utils/internal/checkGlobals.js +33 -0
  66. package/lib/core/utils/internal/checkGlobals.mjs +13 -0
  67. package/lib/core/utils/internal/devUtils.d.ts +19 -0
  68. package/lib/core/utils/internal/devUtils.js +40 -0
  69. package/lib/core/utils/internal/devUtils.mjs +20 -0
  70. package/lib/core/utils/internal/getCallFrame.d.ts +6 -0
  71. package/lib/core/utils/internal/getCallFrame.js +40 -0
  72. package/lib/core/utils/internal/getCallFrame.mjs +20 -0
  73. package/lib/core/utils/internal/isIterable.d.ts +6 -0
  74. package/lib/core/utils/internal/isIterable.js +29 -0
  75. package/lib/core/utils/internal/isIterable.mjs +9 -0
  76. package/lib/core/utils/internal/isObject.d.ts +6 -0
  77. package/lib/core/utils/internal/isObject.js +26 -0
  78. package/lib/core/utils/internal/isObject.mjs +6 -0
  79. package/lib/core/utils/internal/isStringEqual.d.ts +6 -0
  80. package/lib/core/utils/internal/isStringEqual.js +26 -0
  81. package/lib/core/utils/internal/isStringEqual.mjs +6 -0
  82. package/lib/core/utils/internal/jsonParse.d.ts +7 -0
  83. package/lib/core/utils/internal/jsonParse.js +30 -0
  84. package/lib/core/utils/internal/jsonParse.mjs +10 -0
  85. package/lib/core/utils/internal/mergeRight.d.ts +7 -0
  86. package/lib/core/utils/internal/mergeRight.js +39 -0
  87. package/lib/core/utils/internal/mergeRight.mjs +19 -0
  88. package/lib/core/utils/internal/parseGraphQLRequest.d.ts +5 -0
  89. package/lib/core/utils/internal/parseGraphQLRequest.js +184 -0
  90. package/lib/core/utils/internal/parseGraphQLRequest.mjs +165 -0
  91. package/lib/core/utils/internal/parseMultipartData.d.ts +10 -0
  92. package/lib/core/utils/internal/parseMultipartData.js +81 -0
  93. package/lib/core/utils/internal/parseMultipartData.mjs +61 -0
  94. package/lib/core/utils/internal/pipeEvents.d.ts +8 -0
  95. package/lib/core/utils/internal/pipeEvents.js +34 -0
  96. package/lib/core/utils/internal/pipeEvents.mjs +14 -0
  97. package/lib/core/utils/internal/requestHandlerUtils.d.ts +8 -0
  98. package/lib/core/utils/internal/requestHandlerUtils.js +36 -0
  99. package/lib/core/utils/internal/requestHandlerUtils.mjs +16 -0
  100. package/lib/core/utils/internal/toReadonlyArray.d.ts +6 -0
  101. package/lib/core/utils/internal/toReadonlyArray.js +28 -0
  102. package/lib/core/utils/internal/toReadonlyArray.mjs +8 -0
  103. package/lib/core/utils/internal/tryCatch.d.ts +3 -0
  104. package/lib/core/utils/internal/tryCatch.js +31 -0
  105. package/lib/core/utils/internal/tryCatch.mjs +11 -0
  106. package/lib/core/utils/internal/uuidv4.d.ts +3 -0
  107. package/lib/core/utils/internal/uuidv4.js +26 -0
  108. package/lib/core/utils/internal/uuidv4.mjs +6 -0
  109. package/lib/core/utils/logging/getStatusCodeColor.d.ts +11 -0
  110. package/lib/core/utils/logging/getStatusCodeColor.js +39 -0
  111. package/lib/core/utils/logging/getStatusCodeColor.mjs +19 -0
  112. package/lib/core/utils/logging/getTimestamp.d.ts +6 -0
  113. package/lib/core/utils/logging/getTimestamp.js +27 -0
  114. package/lib/core/utils/logging/getTimestamp.mjs +7 -0
  115. package/lib/core/utils/logging/serializeRequest.d.ts +12 -0
  116. package/lib/core/utils/logging/serializeRequest.js +55 -0
  117. package/lib/core/utils/logging/serializeRequest.mjs +35 -0
  118. package/lib/core/utils/logging/serializeResponse.d.ts +9 -0
  119. package/lib/core/utils/logging/serializeResponse.js +69 -0
  120. package/lib/core/utils/logging/serializeResponse.mjs +39 -0
  121. package/lib/core/utils/matching/matchRequestUrl.d.ts +19 -0
  122. package/lib/core/utils/matching/matchRequestUrl.js +50 -0
  123. package/lib/core/utils/matching/matchRequestUrl.mjs +30 -0
  124. package/lib/core/utils/matching/normalizePath.d.ts +12 -0
  125. package/lib/core/utils/matching/normalizePath.js +32 -0
  126. package/lib/core/utils/matching/normalizePath.mjs +12 -0
  127. package/lib/core/utils/request/getPublicUrlFromRequest.d.ts +7 -0
  128. package/lib/core/utils/request/getPublicUrlFromRequest.js +30 -0
  129. package/lib/core/utils/request/getPublicUrlFromRequest.mjs +10 -0
  130. package/lib/core/utils/request/getRequestCookies.d.ts +8 -0
  131. package/lib/core/utils/request/getRequestCookies.js +88 -0
  132. package/lib/core/utils/request/getRequestCookies.mjs +60 -0
  133. package/lib/core/utils/request/onUnhandledRequest.d.ts +12 -0
  134. package/lib/core/utils/request/onUnhandledRequest.js +193 -0
  135. package/lib/core/utils/request/onUnhandledRequest.mjs +165 -0
  136. package/lib/core/utils/request/readResponseCookies.d.ts +3 -0
  137. package/lib/core/utils/request/readResponseCookies.js +45 -0
  138. package/lib/core/utils/request/readResponseCookies.mjs +27 -0
  139. package/lib/core/utils/toResponseInit.d.ts +3 -0
  140. package/lib/core/utils/toResponseInit.js +30 -0
  141. package/lib/core/utils/toResponseInit.mjs +10 -0
  142. package/lib/core/utils/url/cleanUrl.d.ts +7 -0
  143. package/lib/core/utils/url/cleanUrl.js +31 -0
  144. package/lib/core/utils/url/cleanUrl.mjs +11 -0
  145. package/lib/core/utils/url/getAbsoluteUrl.d.ts +6 -0
  146. package/lib/core/utils/url/getAbsoluteUrl.js +37 -0
  147. package/lib/core/utils/url/getAbsoluteUrl.mjs +17 -0
  148. package/lib/core/utils/url/isAbsoluteUrl.d.ts +6 -0
  149. package/lib/core/utils/url/isAbsoluteUrl.js +26 -0
  150. package/lib/core/utils/url/isAbsoluteUrl.mjs +6 -0
  151. package/lib/iife/index.js +6204 -12360
  152. package/lib/mockServiceWorker.js +82 -93
  153. package/lib/native/index.d.ts +67 -7
  154. package/lib/native/index.js +74 -1500
  155. package/lib/native/index.mjs +69 -1514
  156. package/lib/node/index.d.ts +68 -9
  157. package/lib/node/index.js +77 -1508
  158. package/lib/node/index.mjs +71 -1521
  159. package/native/package.json +2 -1
  160. package/node/package.json +2 -1
  161. package/package.json +53 -23
  162. package/lib/SetupServerApi-1855d9c6.d.ts +0 -20
  163. package/lib/glossary-de6278a9.d.ts +0 -385
  164. package/lib/iife/index.js.map +0 -1
  165. package/lib/index.d.ts +0 -365
  166. package/lib/index.js +0 -2295
  167. package/lib/index.js.map +0 -1
  168. package/lib/node/index.js.map +0 -1
  169. package/lib/node/index.mjs.map +0 -1
@@ -1,1482 +1,42 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
- }) : x)(function(x) {
10
- if (typeof require !== "undefined")
11
- return require.apply(this, arguments);
12
- throw new Error('Dynamic require of "' + x + '" is not supported');
13
- });
14
- var __copyProps = (to, from, except, desc) => {
15
- if (from && typeof from === "object" || typeof from === "function") {
16
- for (let key of __getOwnPropNames(from))
17
- if (!__hasOwnProp.call(to, key) && key !== except)
18
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
- mod
25
- ));
26
-
27
- // config/polyfills-node.ts
28
- import { setTimeout as nodeSetTimeout } from "timers";
29
- var setTimeout = nodeSetTimeout;
30
-
31
- // src/node/SetupServerApi.ts
32
- import chalk from "chalk";
33
- import { invariant as invariant3 } from "outvariant";
34
- import {
35
- BatchInterceptor,
36
- InterceptorReadyState
37
- } from "@mswjs/interceptors";
38
-
39
- // src/SetupApi.ts
40
- import { invariant } from "outvariant";
41
- import { Emitter } from "strict-event-emitter";
42
-
43
- // src/utils/internal/devUtils.ts
44
- import { format } from "outvariant";
45
- var LIBRARY_PREFIX = "[MSW]";
46
- function formatMessage(message, ...positionals) {
47
- const interpolatedMessage = format(message, ...positionals);
48
- return `${LIBRARY_PREFIX} ${interpolatedMessage}`;
49
- }
50
- function warn(message, ...positionals) {
51
- console.warn(formatMessage(message, ...positionals));
52
- }
53
- function error(message, ...positionals) {
54
- console.error(formatMessage(message, ...positionals));
55
- }
56
- var devUtils = {
57
- formatMessage,
58
- warn,
59
- error
60
- };
61
-
62
- // src/utils/internal/pipeEvents.ts
63
- function pipeEvents(source, destination) {
64
- const rawEmit = source.emit;
65
- if (rawEmit._isPiped) {
66
- return;
67
- }
68
- source.emit = function(event, ...data2) {
69
- destination.emit(event, ...data2);
70
- return rawEmit.call(this, event, ...data2);
71
- };
72
- source.emit._isPiped = true;
73
- }
74
-
75
- // src/utils/internal/toReadonlyArray.ts
76
- function toReadonlyArray(source) {
77
- const clone = [...source];
78
- Object.freeze(clone);
79
- return clone;
80
- }
81
-
82
- // src/SetupApi.ts
83
- var SetupApi = class {
84
- constructor(...initialHandlers) {
85
- this.validateHandlers(...initialHandlers);
86
- this.initialHandlers = toReadonlyArray(initialHandlers);
87
- this.currentHandlers = [...initialHandlers];
88
- this.emitter = new Emitter();
89
- this.publicEmitter = new Emitter();
90
- pipeEvents(this.emitter, this.publicEmitter);
91
- this.events = this.createLifeCycleEvents();
92
- }
93
- validateHandlers(...handlers) {
94
- for (const handler of handlers) {
95
- invariant(
96
- !Array.isArray(handler),
97
- devUtils.formatMessage(
98
- 'Failed to construct "%s" given an Array of request handlers. Make sure you spread the request handlers when calling the respective setup function.'
99
- ),
100
- this.constructor.name
101
- );
102
- }
103
- }
104
- dispose() {
105
- this.emitter.removeAllListeners();
106
- this.publicEmitter.removeAllListeners();
107
- }
108
- use(...runtimeHandlers) {
109
- this.currentHandlers.unshift(...runtimeHandlers);
110
- }
111
- restoreHandlers() {
112
- this.currentHandlers.forEach((handler) => {
113
- handler.markAsSkipped(false);
114
- });
115
- }
116
- resetHandlers(...nextHandlers) {
117
- this.currentHandlers = nextHandlers.length > 0 ? [...nextHandlers] : [...this.initialHandlers];
118
- }
119
- listHandlers() {
120
- return toReadonlyArray(this.currentHandlers);
121
- }
122
- createLifeCycleEvents() {
123
- return {
124
- on: (...args) => {
125
- return this.publicEmitter.on(...args);
126
- },
127
- removeListener: (...args) => {
128
- return this.publicEmitter.removeListener(...args);
129
- },
130
- removeAllListeners: (...args) => {
131
- return this.publicEmitter.removeAllListeners(...args);
1
+ var __async = (__this, __arguments, generator) => {
2
+ return new Promise((resolve, reject) => {
3
+ var fulfilled = (value) => {
4
+ try {
5
+ step(generator.next(value));
6
+ } catch (e) {
7
+ reject(e);
132
8
  }
133
9
  };
134
- }
135
- };
136
-
137
- // src/utils/internal/isObject.ts
138
- function isObject(value) {
139
- return value != null && typeof value === "object" && !Array.isArray(value);
140
- }
141
-
142
- // src/utils/internal/mergeRight.ts
143
- function mergeRight(left, right) {
144
- return Object.entries(right).reduce((result, [key, rightValue]) => {
145
- const leftValue = result[key];
146
- if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
147
- result[key] = leftValue.concat(rightValue);
148
- return result;
149
- }
150
- if (isObject(leftValue) && isObject(rightValue)) {
151
- result[key] = mergeRight(leftValue, rightValue);
152
- return result;
153
- }
154
- result[key] = rightValue;
155
- return result;
156
- }, Object.assign({}, left));
157
- }
158
-
159
- // src/utils/request/MockedRequest.ts
160
- import * as cookieUtils2 from "cookie";
161
- import { store } from "@mswjs/cookies";
162
- import { IsomorphicRequest } from "@mswjs/interceptors";
163
- import { decodeBuffer } from "@mswjs/interceptors/lib/utils/bufferUtils.js";
164
- import { Headers } from "headers-polyfill";
165
-
166
- // src/utils/request/getRequestCookies.ts
167
- import * as cookieUtils from "cookie";
168
- function getAllCookies() {
169
- return cookieUtils.parse(document.cookie);
170
- }
171
- function getRequestCookies(request) {
172
- if (typeof document === "undefined" || typeof location === "undefined") {
173
- return {};
174
- }
175
- switch (request.credentials) {
176
- case "same-origin": {
177
- return location.origin === request.url.origin ? getAllCookies() : {};
178
- }
179
- case "include": {
180
- return getAllCookies();
181
- }
182
- default: {
183
- return {};
184
- }
185
- }
186
- }
187
-
188
- // src/utils/internal/jsonParse.ts
189
- function jsonParse(value) {
190
- try {
191
- return JSON.parse(value);
192
- } catch (error2) {
193
- return void 0;
194
- }
195
- }
196
-
197
- // src/utils/internal/parseMultipartData.ts
198
- import { stringToHeaders } from "headers-polyfill";
199
- function parseContentHeaders(headersString) {
200
- var _a, _b;
201
- const headers = stringToHeaders(headersString);
202
- const contentType = headers.get("content-type") || "text/plain";
203
- const disposition = headers.get("content-disposition");
204
- if (!disposition) {
205
- throw new Error('"Content-Disposition" header is required.');
206
- }
207
- const directives = disposition.split(";").reduce((acc, chunk) => {
208
- const [name2, ...rest] = chunk.trim().split("=");
209
- acc[name2] = rest.join("=");
210
- return acc;
211
- }, {});
212
- const name = (_a = directives.name) == null ? void 0 : _a.slice(1, -1);
213
- const filename = (_b = directives.filename) == null ? void 0 : _b.slice(1, -1);
214
- return {
215
- name,
216
- filename,
217
- contentType
218
- };
219
- }
220
- function parseMultipartData(data2, headers) {
221
- const contentType = headers == null ? void 0 : headers.get("content-type");
222
- if (!contentType) {
223
- return void 0;
224
- }
225
- const [, ...directives] = contentType.split(/; */);
226
- const boundary = directives.filter((d) => d.startsWith("boundary=")).map((s) => s.replace(/^boundary=/, ""))[0];
227
- if (!boundary) {
228
- return void 0;
229
- }
230
- const boundaryRegExp = new RegExp(`--+${boundary}`);
231
- const fields = data2.split(boundaryRegExp).filter((chunk) => chunk.startsWith("\r\n") && chunk.endsWith("\r\n")).map((chunk) => chunk.trimStart().replace(/\r\n$/, ""));
232
- if (!fields.length) {
233
- return void 0;
234
- }
235
- const parsedBody = {};
236
- try {
237
- for (const field2 of fields) {
238
- const [contentHeaders, ...rest] = field2.split("\r\n\r\n");
239
- const contentBody = rest.join("\r\n\r\n");
240
- const { contentType: contentType2, filename, name } = parseContentHeaders(contentHeaders);
241
- const value = filename === void 0 ? contentBody : new File([contentBody], filename, { type: contentType2 });
242
- const parsedValue = parsedBody[name];
243
- if (parsedValue === void 0) {
244
- parsedBody[name] = value;
245
- } else if (Array.isArray(parsedValue)) {
246
- parsedBody[name] = [...parsedValue, value];
247
- } else {
248
- parsedBody[name] = [parsedValue, value];
10
+ var rejected = (value) => {
11
+ try {
12
+ step(generator.throw(value));
13
+ } catch (e) {
14
+ reject(e);
249
15
  }
250
- }
251
- return parsedBody;
252
- } catch (error2) {
253
- return void 0;
254
- }
255
- }
256
-
257
- // src/utils/request/parseBody.ts
258
- function parseBody(body2, headers) {
259
- var _a;
260
- if (!body2) {
261
- return body2;
262
- }
263
- const contentType = ((_a = headers == null ? void 0 : headers.get("content-type")) == null ? void 0 : _a.toLowerCase()) || "";
264
- const hasMultipartContent = contentType.startsWith("multipart/form-data");
265
- if (hasMultipartContent && typeof body2 !== "object") {
266
- return parseMultipartData(body2.toString(), headers) || body2;
267
- }
268
- const hasJsonContent = contentType.includes("json");
269
- if (hasJsonContent && typeof body2 !== "object") {
270
- return jsonParse(body2.toString()) || body2;
271
- }
272
- return body2;
273
- }
274
-
275
- // src/utils/internal/isStringEqual.ts
276
- function isStringEqual(actual, expected) {
277
- return actual.toLowerCase() === expected.toLowerCase();
278
- }
279
-
280
- // src/utils/request/MockedRequest.ts
281
- var MockedRequest = class extends IsomorphicRequest {
282
- constructor(url, init = {}) {
283
- super(url, init);
284
- if (init.id) {
285
- this.id = init.id;
286
- }
287
- this.cache = init.cache || "default";
288
- this.destination = init.destination || "";
289
- this.integrity = init.integrity || "";
290
- this.keepalive = init.keepalive || false;
291
- this.mode = init.mode || "cors";
292
- this.priority = init.priority || "auto";
293
- this.redirect = init.redirect || "follow";
294
- this.referrer = init.referrer || "";
295
- this.referrerPolicy = init.referrerPolicy || "no-referrer";
296
- this.cookies = init.cookies || this.getCookies();
297
- }
298
- get body() {
299
- const text2 = decodeBuffer(this["_body"]);
300
- const body2 = parseBody(text2, this.headers);
301
- if (isStringEqual(this.method, "GET") && body2 === "") {
302
- return void 0;
303
- }
304
- return body2;
305
- }
306
- passthrough() {
307
- return {
308
- status: 101,
309
- statusText: "Continue",
310
- headers: new Headers(),
311
- body: null,
312
- passthrough: true,
313
- once: false
314
- };
315
- }
316
- getCookies() {
317
- var _a;
318
- const requestCookiesString = this.headers.get("cookie");
319
- const ownCookies = requestCookiesString ? cookieUtils2.parse(requestCookiesString) : {};
320
- store.hydrate();
321
- const cookiesFromStore = Array.from(
322
- (_a = store.get({ ...this, url: this.url.href })) == null ? void 0 : _a.entries()
323
- ).reduce((cookies, [name, { value }]) => {
324
- return Object.assign(cookies, { [name.trim()]: value });
325
- }, {});
326
- const cookiesFromDocument = getRequestCookies(this);
327
- const forwardedCookies = {
328
- ...cookiesFromDocument,
329
- ...cookiesFromStore
330
- };
331
- for (const [name, value] of Object.entries(forwardedCookies)) {
332
- this.headers.append("cookie", `${name}=${value}`);
333
- }
334
- return {
335
- ...forwardedCookies,
336
- ...ownCookies
337
16
  };
338
- }
339
- };
340
-
341
- // src/utils/handleRequest.ts
342
- import { until } from "@open-draft/until";
343
-
344
- // src/utils/getResponse.ts
345
- var getResponse = async (request, handlers, resolutionContext) => {
346
- const relevantHandlers = handlers.filter((handler) => {
347
- return handler.test(request, resolutionContext);
17
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
+ step((generator = generator.apply(__this, __arguments)).next());
348
19
  });
349
- if (relevantHandlers.length === 0) {
350
- return {
351
- handler: void 0,
352
- response: void 0
353
- };
354
- }
355
- const result = await relevantHandlers.reduce(async (executionResult, handler) => {
356
- const previousResults = await executionResult;
357
- if (!!(previousResults == null ? void 0 : previousResults.response)) {
358
- return executionResult;
359
- }
360
- const result2 = await handler.run(request, resolutionContext);
361
- if (result2 === null || result2.handler.shouldSkip) {
362
- return null;
363
- }
364
- if (!result2.response) {
365
- return {
366
- request: result2.request,
367
- handler: result2.handler,
368
- response: void 0,
369
- parsedResult: result2.parsedResult
370
- };
371
- }
372
- if (result2.response.once) {
373
- handler.markAsSkipped(true);
374
- }
375
- return result2;
376
- }, Promise.resolve(null));
377
- if (!result) {
378
- return {
379
- handler: void 0,
380
- response: void 0
381
- };
382
- }
383
- return {
384
- handler: result.handler,
385
- publicRequest: result.request,
386
- parsedRequest: result.parsedResult,
387
- response: result.response
388
- };
389
- };
390
-
391
- // src/utils/request/onUnhandledRequest.ts
392
- import getStringMatchScore from "js-levenshtein";
393
-
394
- // src/utils/internal/parseGraphQLRequest.ts
395
- import { parse as parse3 } from "graphql";
396
-
397
- // src/utils/request/getPublicUrlFromRequest.ts
398
- var getPublicUrlFromRequest = (request) => {
399
- return request.referrer.startsWith(request.url.origin) ? request.url.pathname : new URL(
400
- request.url.pathname,
401
- `${request.url.protocol}//${request.url.host}`
402
- ).href;
403
20
  };
404
21
 
405
- // src/utils/internal/parseGraphQLRequest.ts
406
- function parseDocumentNode(node) {
407
- var _a;
408
- const operationDef = node.definitions.find((def) => {
409
- return def.kind === "OperationDefinition";
410
- });
411
- return {
412
- operationType: operationDef == null ? void 0 : operationDef.operation,
413
- operationName: (_a = operationDef == null ? void 0 : operationDef.name) == null ? void 0 : _a.value
414
- };
415
- }
416
- function parseQuery(query) {
417
- try {
418
- const ast = parse3(query);
419
- return parseDocumentNode(ast);
420
- } catch (error2) {
421
- return error2;
422
- }
423
- }
424
- function extractMultipartVariables(variables, map, files) {
425
- const operations = { variables };
426
- for (const [key, pathArray] of Object.entries(map)) {
427
- if (!(key in files)) {
428
- throw new Error(`Given files do not have a key '${key}' .`);
429
- }
430
- for (const dotPath of pathArray) {
431
- const [lastPath, ...reversedPaths] = dotPath.split(".").reverse();
432
- const paths = reversedPaths.reverse();
433
- let target = operations;
434
- for (const path of paths) {
435
- if (!(path in target)) {
436
- throw new Error(`Property '${paths}' is not in operations.`);
437
- }
438
- target = target[path];
439
- }
440
- target[lastPath] = files[key];
441
- }
442
- }
443
- return operations.variables;
444
- }
445
- function getGraphQLInput(request) {
446
- var _a, _b;
447
- switch (request.method) {
448
- case "GET": {
449
- const query = request.url.searchParams.get("query");
450
- const variables = request.url.searchParams.get("variables") || "";
451
- return {
452
- query,
453
- variables: jsonParse(variables)
454
- };
455
- }
456
- case "POST": {
457
- if ((_a = request.body) == null ? void 0 : _a.query) {
458
- const { query, variables } = request.body;
459
- return {
460
- query,
461
- variables
462
- };
463
- }
464
- if ((_b = request.body) == null ? void 0 : _b.operations) {
465
- const { operations, map, ...files } = request.body;
466
- const parsedOperations = jsonParse(
467
- operations
468
- ) || {};
469
- if (!parsedOperations.query) {
470
- return null;
471
- }
472
- const parsedMap = jsonParse(map || "") || {};
473
- const variables = parsedOperations.variables ? extractMultipartVariables(
474
- parsedOperations.variables,
475
- parsedMap,
476
- files
477
- ) : {};
478
- return {
479
- query: parsedOperations.query,
480
- variables
481
- };
482
- }
483
- }
484
- default:
485
- return null;
486
- }
487
- }
488
- function parseGraphQLRequest(request) {
489
- const input = getGraphQLInput(request);
490
- if (!input || !input.query) {
491
- return void 0;
492
- }
493
- const { query, variables } = input;
494
- const parsedResult = parseQuery(query);
495
- if (parsedResult instanceof Error) {
496
- const requestPublicUrl = getPublicUrlFromRequest(request);
497
- throw new Error(
498
- devUtils.formatMessage(
499
- 'Failed to intercept a GraphQL request to "%s %s": cannot parse query. See the error message from the parser below.\n\n%s',
500
- request.method,
501
- requestPublicUrl,
502
- parsedResult.message
503
- )
504
- );
505
- }
506
- return {
507
- operationType: parsedResult.operationType,
508
- operationName: parsedResult.operationName,
509
- variables
510
- };
511
- }
512
-
513
- // node_modules/.pnpm/statuses@2.0.1/node_modules/statuses/codes.json
514
- var codes_default = {
515
- "100": "Continue",
516
- "101": "Switching Protocols",
517
- "102": "Processing",
518
- "103": "Early Hints",
519
- "200": "OK",
520
- "201": "Created",
521
- "202": "Accepted",
522
- "203": "Non-Authoritative Information",
523
- "204": "No Content",
524
- "205": "Reset Content",
525
- "206": "Partial Content",
526
- "207": "Multi-Status",
527
- "208": "Already Reported",
528
- "226": "IM Used",
529
- "300": "Multiple Choices",
530
- "301": "Moved Permanently",
531
- "302": "Found",
532
- "303": "See Other",
533
- "304": "Not Modified",
534
- "305": "Use Proxy",
535
- "307": "Temporary Redirect",
536
- "308": "Permanent Redirect",
537
- "400": "Bad Request",
538
- "401": "Unauthorized",
539
- "402": "Payment Required",
540
- "403": "Forbidden",
541
- "404": "Not Found",
542
- "405": "Method Not Allowed",
543
- "406": "Not Acceptable",
544
- "407": "Proxy Authentication Required",
545
- "408": "Request Timeout",
546
- "409": "Conflict",
547
- "410": "Gone",
548
- "411": "Length Required",
549
- "412": "Precondition Failed",
550
- "413": "Payload Too Large",
551
- "414": "URI Too Long",
552
- "415": "Unsupported Media Type",
553
- "416": "Range Not Satisfiable",
554
- "417": "Expectation Failed",
555
- "418": "I'm a Teapot",
556
- "421": "Misdirected Request",
557
- "422": "Unprocessable Entity",
558
- "423": "Locked",
559
- "424": "Failed Dependency",
560
- "425": "Too Early",
561
- "426": "Upgrade Required",
562
- "428": "Precondition Required",
563
- "429": "Too Many Requests",
564
- "431": "Request Header Fields Too Large",
565
- "451": "Unavailable For Legal Reasons",
566
- "500": "Internal Server Error",
567
- "501": "Not Implemented",
568
- "502": "Bad Gateway",
569
- "503": "Service Unavailable",
570
- "504": "Gateway Timeout",
571
- "505": "HTTP Version Not Supported",
572
- "506": "Variant Also Negotiates",
573
- "507": "Insufficient Storage",
574
- "508": "Loop Detected",
575
- "509": "Bandwidth Limit Exceeded",
576
- "510": "Not Extended",
577
- "511": "Network Authentication Required"
578
- };
579
-
580
- // src/context/status.ts
581
- var status = (statusCode, statusText) => {
582
- return (res) => {
583
- res.status = statusCode;
584
- res.statusText = statusText || codes_default[String(statusCode)];
585
- return res;
586
- };
587
- };
588
-
589
- // src/context/set.ts
590
- import { objectToHeaders } from "headers-polyfill";
591
- function set(...args) {
592
- return (res) => {
593
- const [name, value] = args;
594
- if (typeof name === "string") {
595
- res.headers.append(name, value);
596
- } else {
597
- const headers = objectToHeaders(name);
598
- headers.forEach((value2, name2) => {
599
- res.headers.append(name2, value2);
600
- });
601
- }
602
- return res;
603
- };
604
- }
605
-
606
- // src/context/cookie.ts
607
- import * as cookieUtils3 from "cookie";
608
- var cookie = (name, value, options) => {
609
- return (res) => {
610
- const serializedCookie = cookieUtils3.serialize(name, value, options);
611
- res.headers.append("Set-Cookie", serializedCookie);
612
- if (typeof document !== "undefined") {
613
- document.cookie = serializedCookie;
614
- }
615
- return res;
616
- };
617
- };
618
-
619
- // src/context/body.ts
620
- var body = (value) => {
621
- return (res) => {
622
- res.body = value;
623
- return res;
624
- };
625
- };
626
-
627
- // src/context/json.ts
628
- var json = (body2) => {
629
- return (res) => {
630
- res.headers.set("Content-Type", "application/json");
631
- res.body = JSON.stringify(body2);
632
- return res;
633
- };
634
- };
635
-
636
- // src/context/data.ts
637
- var data = (payload) => {
638
- return (res) => {
639
- const prevBody = jsonParse(res.body) || {};
640
- const nextBody = mergeRight(prevBody, { data: payload });
641
- return json(nextBody)(res);
642
- };
643
- };
644
-
645
- // src/context/extensions.ts
646
- var extensions = (payload) => {
647
- return (res) => {
648
- const prevBody = jsonParse(res.body) || {};
649
- const nextBody = mergeRight(prevBody, { extensions: payload });
650
- return json(nextBody)(res);
651
- };
652
- };
653
-
654
- // src/context/delay.ts
655
- import { isNodeProcess } from "is-node-process";
656
- var SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647;
657
- var MIN_SERVER_RESPONSE_TIME = 100;
658
- var MAX_SERVER_RESPONSE_TIME = 400;
659
- var NODE_SERVER_RESPONSE_TIME = 5;
660
- var getRandomServerResponseTime = () => {
661
- if (isNodeProcess()) {
662
- return NODE_SERVER_RESPONSE_TIME;
663
- }
664
- return Math.floor(
665
- Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) + MIN_SERVER_RESPONSE_TIME
666
- );
667
- };
668
- var delay = (durationOrMode) => {
669
- return (res) => {
670
- let delayTime;
671
- if (typeof durationOrMode === "string") {
672
- switch (durationOrMode) {
673
- case "infinite": {
674
- delayTime = SET_TIMEOUT_MAX_ALLOWED_INT;
675
- break;
676
- }
677
- case "real": {
678
- delayTime = getRandomServerResponseTime();
679
- break;
680
- }
681
- default: {
682
- throw new Error(
683
- `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".`
684
- );
685
- }
686
- }
687
- } else if (typeof durationOrMode === "undefined") {
688
- delayTime = getRandomServerResponseTime();
689
- } else {
690
- if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {
691
- throw new Error(
692
- `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.`
693
- );
694
- }
695
- delayTime = durationOrMode;
696
- }
697
- res.delay = delayTime;
698
- return res;
699
- };
700
- };
701
-
702
- // src/context/errors.ts
703
- var errors = (errorsList) => {
704
- return (res) => {
705
- if (errorsList == null) {
706
- return res;
707
- }
708
- const prevBody = jsonParse(res.body) || {};
709
- const nextBody = mergeRight(prevBody, { errors: errorsList });
710
- return json(nextBody)(res);
711
- };
712
- };
713
-
714
- // src/context/fetch.ts
715
- import { isNodeProcess as isNodeProcess2 } from "is-node-process";
716
- import { Headers as Headers2 } from "headers-polyfill";
717
- var useFetch = isNodeProcess2() ? (input, init) => Promise.resolve().then(() => __toESM(__require("node-fetch"))).then(
718
- ({ default: nodeFetch }) => nodeFetch(input, init)
719
- ) : globalThis.fetch;
720
- var augmentRequestInit = (requestInit) => {
721
- const headers = new Headers2(requestInit.headers);
722
- headers.set("x-msw-bypass", "true");
723
- return {
724
- ...requestInit,
725
- headers: headers.all()
726
- };
727
- };
728
- var createFetchRequestParameters = (input) => {
729
- const { body: body2, method } = input;
730
- const requestParameters = {
731
- ...input,
732
- body: void 0
733
- };
734
- if (["GET", "HEAD"].includes(method)) {
735
- return requestParameters;
736
- }
737
- if (typeof body2 === "object" || typeof body2 === "number" || typeof body2 === "boolean") {
738
- requestParameters.body = JSON.stringify(body2);
739
- } else {
740
- requestParameters.body = body2;
741
- }
742
- return requestParameters;
743
- };
744
- var fetch = (input, requestInit = {}) => {
745
- if (typeof input === "string") {
746
- return useFetch(input, augmentRequestInit(requestInit));
747
- }
748
- const requestParameters = createFetchRequestParameters(input);
749
- const derivedRequestInit = augmentRequestInit(requestParameters);
750
- return useFetch(input.url.href, derivedRequestInit);
751
- };
752
-
753
- // src/context/text.ts
754
- var text = (body2) => {
755
- return (res) => {
756
- res.headers.set("Content-Type", "text/plain");
757
- res.body = body2;
758
- return res;
759
- };
760
- };
761
-
762
- // src/context/xml.ts
763
- var xml = (body2) => {
764
- return (res) => {
765
- res.headers.set("Content-Type", "text/xml");
766
- res.body = body2;
767
- return res;
768
- };
769
- };
770
-
771
- // src/utils/logging/getStatusCodeColor.ts
772
- function getStatusCodeColor(status2) {
773
- if (status2 < 300) {
774
- return "#69AB32" /* Success */;
775
- }
776
- if (status2 < 400) {
777
- return "#F0BB4B" /* Warning */;
778
- }
779
- return "#E95F5D" /* Danger */;
780
- }
781
-
782
- // src/utils/logging/getTimestamp.ts
783
- function getTimestamp() {
784
- const now = new Date();
785
- return [now.getHours(), now.getMinutes(), now.getSeconds()].map(String).map((chunk) => chunk.slice(0, 2)).map((chunk) => chunk.padStart(2, "0")).join(":");
786
- }
787
-
788
- // src/utils/logging/prepareRequest.ts
789
- function prepareRequest(request) {
790
- return {
791
- ...request,
792
- body: request.body,
793
- headers: request.headers.all()
794
- };
795
- }
796
-
797
- // src/utils/logging/prepareResponse.ts
798
- import { objectToHeaders as objectToHeaders2 } from "headers-polyfill";
799
- function prepareResponse(res) {
800
- const responseHeaders = objectToHeaders2(res.headers);
801
- const parsedBody = parseBody(res.body, responseHeaders);
802
- return {
803
- ...res,
804
- body: parsedBody
805
- };
806
- }
807
-
808
- // src/utils/matching/matchRequestUrl.ts
809
- import { match } from "path-to-regexp";
810
- import { getCleanUrl } from "@mswjs/interceptors/lib/utils/getCleanUrl.js";
811
-
812
- // src/utils/url/cleanUrl.ts
813
- var REDUNDANT_CHARACTERS_EXP = /[\?|#].*$/g;
814
- function getSearchParams(path) {
815
- return new URL(`/${path}`, "http://localhost").searchParams;
816
- }
817
- function cleanUrl(path) {
818
- return path.replace(REDUNDANT_CHARACTERS_EXP, "");
819
- }
820
-
821
- // src/utils/url/isAbsoluteUrl.ts
822
- function isAbsoluteUrl(url) {
823
- return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
824
- }
825
-
826
- // src/utils/url/getAbsoluteUrl.ts
827
- function getAbsoluteUrl(path, baseUrl) {
828
- if (isAbsoluteUrl(path)) {
829
- return path;
830
- }
831
- if (path.startsWith("*")) {
832
- return path;
833
- }
834
- const origin = baseUrl || typeof document !== "undefined" && document.baseURI;
835
- return origin ? decodeURI(new URL(encodeURI(path), origin).href) : path;
836
- }
837
-
838
- // src/utils/matching/normalizePath.ts
839
- function normalizePath(path, baseUrl) {
840
- if (path instanceof RegExp) {
841
- return path;
842
- }
843
- const maybeAbsoluteUrl = getAbsoluteUrl(path, baseUrl);
844
- return cleanUrl(maybeAbsoluteUrl);
845
- }
846
-
847
- // src/utils/matching/matchRequestUrl.ts
848
- function coercePath(path) {
849
- return path.replace(
850
- /([:a-zA-Z_-]*)(\*{1,2})+/g,
851
- (_, parameterName, wildcard) => {
852
- const expression = "(.*)";
853
- if (!parameterName) {
854
- return expression;
855
- }
856
- return parameterName.startsWith(":") ? `${parameterName}${wildcard}` : `${parameterName}${expression}`;
857
- }
858
- ).replace(/([^\/])(:)(?=\d+)/, "$1\\$2").replace(/^([^\/]+)(:)(?=\/\/)/, "$1\\$2");
859
- }
860
- function matchRequestUrl(url, path, baseUrl) {
861
- const normalizedPath = normalizePath(path, baseUrl);
862
- const cleanPath = typeof normalizedPath === "string" ? coercePath(normalizedPath) : normalizedPath;
863
- const cleanUrl2 = getCleanUrl(url);
864
- const result = match(cleanPath, { decode: decodeURIComponent })(cleanUrl2);
865
- const params = result && result.params || {};
866
- return {
867
- matches: result !== false,
868
- params
869
- };
870
- }
871
-
872
- // src/handlers/RequestHandler.ts
873
- import { Headers as Headers4 } from "headers-polyfill";
874
-
875
- // src/response.ts
876
- import { Headers as Headers3 } from "headers-polyfill";
877
-
878
- // src/utils/internal/compose.ts
879
- function compose(...fns) {
880
- return (...args) => {
881
- return fns.reduceRight((leftFn, rightFn) => {
882
- return leftFn instanceof Promise ? Promise.resolve(leftFn).then(rightFn) : rightFn(leftFn);
883
- }, args[0]);
884
- };
885
- }
886
-
887
- // src/utils/NetworkError.ts
888
- var NetworkError = class extends Error {
889
- constructor(message) {
890
- super(message);
891
- this.name = "NetworkError";
892
- }
893
- };
894
-
895
- // src/response.ts
896
- var defaultResponse = {
897
- status: 200,
898
- statusText: "OK",
899
- body: null,
900
- delay: 0,
901
- once: false,
902
- passthrough: false
903
- };
904
- var defaultResponseTransformers = [];
905
- function createResponseComposition(responseOverrides, defaultTransformers = defaultResponseTransformers) {
906
- return async (...transformers) => {
907
- const initialResponse = Object.assign(
908
- {},
909
- defaultResponse,
910
- {
911
- headers: new Headers3({
912
- "x-powered-by": "msw"
913
- })
914
- },
915
- responseOverrides
916
- );
917
- const resolvedTransformers = [
918
- ...defaultTransformers,
919
- ...transformers
920
- ].filter(Boolean);
921
- const resolvedResponse = resolvedTransformers.length > 0 ? compose(...resolvedTransformers)(initialResponse) : initialResponse;
922
- return resolvedResponse;
923
- };
924
- }
925
- var response = Object.assign(createResponseComposition(), {
926
- once: createResponseComposition({ once: true }),
927
- networkError(message) {
928
- throw new NetworkError(message);
929
- }
930
- });
931
-
932
- // src/utils/internal/getCallFrame.ts
933
- var SOURCE_FRAME = /[\/\\]msw[\/\\]src[\/\\](.+)/;
934
- var BUILD_FRAME = /(node_modules)?[\/\\]lib[\/\\](umd|esm|iief|cjs)[\/\\]|^[^\/\\]*$/;
935
- function getCallFrame(error2) {
936
- const stack = error2.stack;
937
- if (!stack) {
938
- return;
939
- }
940
- const frames = stack.split("\n").slice(1);
941
- const declarationFrame = frames.find((frame) => {
942
- return !(SOURCE_FRAME.test(frame) || BUILD_FRAME.test(frame));
943
- });
944
- if (!declarationFrame) {
945
- return;
946
- }
947
- const declarationPath = declarationFrame.replace(/\s*at [^()]*\(([^)]+)\)/, "$1").replace(/^@/, "");
948
- return declarationPath;
949
- }
950
-
951
- // src/utils/internal/isIterable.ts
952
- function isIterable(fn) {
953
- if (!fn) {
954
- return false;
955
- }
956
- return typeof fn[Symbol.iterator] == "function";
957
- }
958
-
959
- // src/handlers/RequestHandler.ts
960
- var defaultContext = {
961
- status,
962
- set,
963
- delay,
964
- fetch
965
- };
966
- var RequestHandler = class {
967
- constructor(options) {
968
- this.shouldSkip = false;
969
- this.ctx = options.ctx || defaultContext;
970
- this.resolver = options.resolver;
971
- const callFrame = getCallFrame(new Error());
972
- this.info = {
973
- ...options.info,
974
- callFrame
975
- };
976
- }
977
- parse(_request, _resolutionContext) {
978
- return null;
979
- }
980
- test(request, resolutionContext) {
981
- return this.predicate(
982
- request,
983
- this.parse(request, resolutionContext),
984
- resolutionContext
985
- );
986
- }
987
- getPublicRequest(request, _parsedResult) {
988
- return request;
989
- }
990
- markAsSkipped(shouldSkip = true) {
991
- this.shouldSkip = shouldSkip;
992
- }
993
- async run(request, resolutionContext) {
994
- if (this.shouldSkip) {
995
- return null;
996
- }
997
- const parsedResult = this.parse(request, resolutionContext);
998
- const shouldIntercept = this.predicate(
999
- request,
1000
- parsedResult,
1001
- resolutionContext
1002
- );
1003
- if (!shouldIntercept) {
1004
- return null;
1005
- }
1006
- const publicRequest = this.getPublicRequest(request, parsedResult);
1007
- const executeResolver = this.wrapResolver(this.resolver);
1008
- const mockedResponse = await executeResolver(
1009
- publicRequest,
1010
- response,
1011
- this.ctx
1012
- );
1013
- return this.createExecutionResult(
1014
- parsedResult,
1015
- publicRequest,
1016
- mockedResponse
1017
- );
1018
- }
1019
- wrapResolver(resolver) {
1020
- return async (req, res, ctx) => {
1021
- const result = this.resolverGenerator || await resolver(req, res, ctx);
1022
- if (isIterable(result)) {
1023
- const { value, done } = result[Symbol.iterator]().next();
1024
- const nextResponse = await value;
1025
- if (!nextResponse && done) {
1026
- return this.resolverGeneratorResult;
1027
- }
1028
- if (!this.resolverGenerator) {
1029
- this.resolverGenerator = result;
1030
- }
1031
- this.resolverGeneratorResult = nextResponse;
1032
- return nextResponse;
1033
- }
1034
- return result;
1035
- };
1036
- }
1037
- createExecutionResult(parsedResult, request, response2) {
1038
- return {
1039
- handler: this,
1040
- parsedResult: parsedResult || null,
1041
- request,
1042
- response: response2 || null
1043
- };
1044
- }
1045
- };
1046
-
1047
- // src/handlers/RestHandler.ts
1048
- var restContext = {
1049
- ...defaultContext,
1050
- cookie,
1051
- body,
1052
- text,
1053
- json,
1054
- xml
1055
- };
1056
- var RestRequest = class extends MockedRequest {
1057
- constructor(request, params) {
1058
- super(request.url, {
1059
- ...request,
1060
- body: request["_body"]
1061
- });
1062
- this.params = params;
1063
- this.id = request.id;
1064
- }
1065
- };
1066
- var RestHandler = class extends RequestHandler {
1067
- constructor(method, path, resolver) {
1068
- super({
1069
- info: {
1070
- header: `${method} ${path}`,
1071
- path,
1072
- method
1073
- },
1074
- ctx: restContext,
1075
- resolver
1076
- });
1077
- this.checkRedundantQueryParameters();
1078
- }
1079
- checkRedundantQueryParameters() {
1080
- const { method, path } = this.info;
1081
- if (path instanceof RegExp) {
1082
- return;
1083
- }
1084
- const url = cleanUrl(path);
1085
- if (url === path) {
1086
- return;
1087
- }
1088
- const searchParams = getSearchParams(path);
1089
- const queryParams = [];
1090
- searchParams.forEach((_, paramName) => {
1091
- queryParams.push(paramName);
1092
- });
1093
- devUtils.warn(
1094
- `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".`
1095
- );
1096
- }
1097
- parse(request, resolutionContext) {
1098
- return matchRequestUrl(
1099
- request.url,
1100
- this.info.path,
1101
- resolutionContext == null ? void 0 : resolutionContext.baseUrl
1102
- );
1103
- }
1104
- getPublicRequest(request, parsedResult) {
1105
- return new RestRequest(request, parsedResult.params || {});
1106
- }
1107
- predicate(request, parsedResult) {
1108
- const matchesMethod = this.info.method instanceof RegExp ? this.info.method.test(request.method) : isStringEqual(this.info.method, request.method);
1109
- return matchesMethod && parsedResult.matches;
1110
- }
1111
- log(request, response2) {
1112
- const publicUrl = getPublicUrlFromRequest(request);
1113
- const loggedRequest = prepareRequest(request);
1114
- const loggedResponse = prepareResponse(response2);
1115
- const statusColor = getStatusCodeColor(response2.status);
1116
- console.groupCollapsed(
1117
- devUtils.formatMessage("%s %s %s (%c%s%c)"),
1118
- getTimestamp(),
1119
- request.method,
1120
- publicUrl,
1121
- `color:${statusColor}`,
1122
- `${response2.status} ${response2.statusText}`,
1123
- "color:inherit"
1124
- );
1125
- console.log("Request", loggedRequest);
1126
- console.log("Handler:", this);
1127
- console.log("Response", loggedResponse);
1128
- console.groupEnd();
1129
- }
1130
- };
1131
-
1132
- // src/context/field.ts
1133
- import { invariant as invariant2 } from "outvariant";
1134
- var field = (fieldName, fieldValue) => {
1135
- return (res) => {
1136
- validateFieldName(fieldName);
1137
- const prevBody = jsonParse(res.body) || {};
1138
- const nextBody = mergeRight(prevBody, { [fieldName]: fieldValue });
1139
- return json(nextBody)(res);
1140
- };
1141
- };
1142
- function validateFieldName(fieldName) {
1143
- invariant2(
1144
- fieldName.trim() !== "",
1145
- devUtils.formatMessage(
1146
- "Failed to set a custom field on a GraphQL response: field name cannot be empty."
1147
- )
1148
- );
1149
- invariant2(
1150
- fieldName !== "data",
1151
- devUtils.formatMessage(
1152
- 'Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.data()" instead?',
1153
- fieldName
1154
- )
1155
- );
1156
- invariant2(
1157
- fieldName !== "errors",
1158
- devUtils.formatMessage(
1159
- 'Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.errors()" instead?',
1160
- fieldName
1161
- )
1162
- );
1163
- invariant2(
1164
- fieldName !== "extensions",
1165
- devUtils.formatMessage(
1166
- 'Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.extensions()" instead?',
1167
- fieldName
1168
- )
1169
- );
1170
- }
1171
-
1172
- // src/utils/internal/tryCatch.ts
1173
- function tryCatch(fn, onException) {
1174
- try {
1175
- const result = fn();
1176
- return result;
1177
- } catch (error2) {
1178
- onException == null ? void 0 : onException(error2);
1179
- }
1180
- }
1181
-
1182
- // src/handlers/GraphQLHandler.ts
1183
- var graphqlContext = {
1184
- ...defaultContext,
1185
- data,
1186
- extensions,
1187
- errors,
1188
- cookie,
1189
- field
1190
- };
1191
- function isDocumentNode(value) {
1192
- if (value == null) {
1193
- return false;
1194
- }
1195
- return typeof value === "object" && "kind" in value && "definitions" in value;
1196
- }
1197
- var GraphQLRequest = class extends MockedRequest {
1198
- constructor(request, variables, operationName) {
1199
- super(request.url, {
1200
- ...request,
1201
- body: request["_body"]
1202
- });
1203
- this.variables = variables;
1204
- this.operationName = operationName;
1205
- }
1206
- };
1207
- var GraphQLHandler = class extends RequestHandler {
1208
- constructor(operationType, operationName, endpoint, resolver) {
1209
- let resolvedOperationName = operationName;
1210
- if (isDocumentNode(operationName)) {
1211
- const parsedNode = parseDocumentNode(operationName);
1212
- if (parsedNode.operationType !== operationType) {
1213
- throw new Error(
1214
- `Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "${operationType}", but got "${parsedNode.operationType}").`
1215
- );
1216
- }
1217
- if (!parsedNode.operationName) {
1218
- throw new Error(
1219
- `Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`
1220
- );
1221
- }
1222
- resolvedOperationName = parsedNode.operationName;
1223
- }
1224
- const header = operationType === "all" ? `${operationType} (origin: ${endpoint.toString()})` : `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`;
1225
- super({
1226
- info: {
1227
- header,
1228
- operationType,
1229
- operationName: resolvedOperationName
1230
- },
1231
- ctx: graphqlContext,
1232
- resolver
1233
- });
1234
- this.endpoint = endpoint;
1235
- }
1236
- parse(request) {
1237
- return tryCatch(
1238
- () => parseGraphQLRequest(request),
1239
- (error2) => console.error(error2.message)
1240
- );
1241
- }
1242
- getPublicRequest(request, parsedResult) {
1243
- var _a, _b;
1244
- return new GraphQLRequest(
1245
- request,
1246
- (_a = parsedResult == null ? void 0 : parsedResult.variables) != null ? _a : {},
1247
- (_b = parsedResult == null ? void 0 : parsedResult.operationName) != null ? _b : ""
1248
- );
1249
- }
1250
- predicate(request, parsedResult) {
1251
- if (!parsedResult) {
1252
- return false;
1253
- }
1254
- if (!parsedResult.operationName && this.info.operationType !== "all") {
1255
- const publicUrl = getPublicUrlFromRequest(request);
1256
- devUtils.warn(`Failed to intercept a GraphQL request at "${request.method} ${publicUrl}": anonymous GraphQL operations are not supported.
1257
-
1258
- 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 `);
1259
- return false;
1260
- }
1261
- const hasMatchingUrl = matchRequestUrl(request.url, this.endpoint);
1262
- const hasMatchingOperationType = this.info.operationType === "all" || parsedResult.operationType === this.info.operationType;
1263
- const hasMatchingOperationName = this.info.operationName instanceof RegExp ? this.info.operationName.test(parsedResult.operationName || "") : parsedResult.operationName === this.info.operationName;
1264
- return hasMatchingUrl.matches && hasMatchingOperationType && hasMatchingOperationName;
1265
- }
1266
- log(request, response2, parsedRequest) {
1267
- const loggedRequest = prepareRequest(request);
1268
- const loggedResponse = prepareResponse(response2);
1269
- const statusColor = getStatusCodeColor(response2.status);
1270
- 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}`;
1271
- console.groupCollapsed(
1272
- devUtils.formatMessage("%s %s (%c%s%c)"),
1273
- getTimestamp(),
1274
- `${requestInfo}`,
1275
- `color:${statusColor}`,
1276
- `${response2.status} ${response2.statusText}`,
1277
- "color:inherit"
1278
- );
1279
- console.log("Request:", loggedRequest);
1280
- console.log("Handler:", this);
1281
- console.log("Response:", loggedResponse);
1282
- console.groupEnd();
1283
- }
1284
- };
1285
-
1286
- // src/utils/request/onUnhandledRequest.ts
1287
- var MAX_MATCH_SCORE = 3;
1288
- var MAX_SUGGESTION_COUNT = 4;
1289
- var TYPE_MATCH_DELTA = 0.5;
1290
- function groupHandlersByType(handlers) {
1291
- return handlers.reduce(
1292
- (groups, handler) => {
1293
- if (handler instanceof RestHandler) {
1294
- groups.rest.push(handler);
1295
- }
1296
- if (handler instanceof GraphQLHandler) {
1297
- groups.graphql.push(handler);
1298
- }
1299
- return groups;
1300
- },
1301
- {
1302
- rest: [],
1303
- graphql: []
1304
- }
1305
- );
1306
- }
1307
- function getRestHandlerScore() {
1308
- return (request, handler) => {
1309
- const { path, method } = handler.info;
1310
- if (path instanceof RegExp || method instanceof RegExp) {
1311
- return Infinity;
1312
- }
1313
- const hasSameMethod = isStringEqual(request.method, method);
1314
- const methodScoreDelta = hasSameMethod ? TYPE_MATCH_DELTA : 0;
1315
- const requestPublicUrl = getPublicUrlFromRequest(request);
1316
- const score = getStringMatchScore(requestPublicUrl, path);
1317
- return score - methodScoreDelta;
1318
- };
1319
- }
1320
- function getGraphQLHandlerScore(parsedQuery) {
1321
- return (_, handler) => {
1322
- if (typeof parsedQuery.operationName === "undefined") {
1323
- return Infinity;
1324
- }
1325
- const { operationType, operationName } = handler.info;
1326
- if (typeof operationName !== "string") {
1327
- return Infinity;
1328
- }
1329
- const hasSameOperationType = parsedQuery.operationType === operationType;
1330
- const operationTypeScoreDelta = hasSameOperationType ? TYPE_MATCH_DELTA : 0;
1331
- const score = getStringMatchScore(parsedQuery.operationName, operationName);
1332
- return score - operationTypeScoreDelta;
1333
- };
1334
- }
1335
- function getSuggestedHandler(request, handlers, getScore) {
1336
- const suggestedHandlers = handlers.reduce((suggestions, handler) => {
1337
- const score = getScore(request, handler);
1338
- return suggestions.concat([[score, handler]]);
1339
- }, []).sort(([leftScore], [rightScore]) => leftScore - rightScore).filter(([score]) => score <= MAX_MATCH_SCORE).slice(0, MAX_SUGGESTION_COUNT).map(([, handler]) => handler);
1340
- return suggestedHandlers;
1341
- }
1342
- function getSuggestedHandlersMessage(handlers) {
1343
- if (handlers.length > 1) {
1344
- return `Did you mean to request one of the following resources instead?
1345
-
1346
- ${handlers.map((handler) => ` \u2022 ${handler.info.header}`).join("\n")}`;
1347
- }
1348
- return `Did you mean to request "${handlers[0].info.header}" instead?`;
1349
- }
1350
- function onUnhandledRequest(request, handlers, strategy = "warn") {
1351
- const parsedGraphQLQuery = tryCatch(() => parseGraphQLRequest(request));
1352
- function generateHandlerSuggestion() {
1353
- const handlerGroups = groupHandlersByType(handlers);
1354
- const relevantHandlers = parsedGraphQLQuery ? handlerGroups.graphql : handlerGroups.rest;
1355
- const suggestedHandlers = getSuggestedHandler(
1356
- request,
1357
- relevantHandlers,
1358
- parsedGraphQLQuery ? getGraphQLHandlerScore(parsedGraphQLQuery) : getRestHandlerScore()
1359
- );
1360
- return suggestedHandlers.length > 0 ? getSuggestedHandlersMessage(suggestedHandlers) : "";
1361
- }
1362
- function generateUnhandledRequestMessage() {
1363
- const publicUrl = getPublicUrlFromRequest(request);
1364
- const requestHeader = parsedGraphQLQuery ? `${parsedGraphQLQuery.operationType} ${parsedGraphQLQuery.operationName} (${request.method} ${publicUrl})` : `${request.method} ${publicUrl}`;
1365
- const handlerSuggestion = generateHandlerSuggestion();
1366
- const messageTemplate = [
1367
- `captured a request without a matching request handler:`,
1368
- ` \u2022 ${requestHeader}`,
1369
- handlerSuggestion,
1370
- `If you still wish to intercept this unhandled request, please create a request handler for it.
1371
- Read more: https://mswjs.io/docs/getting-started/mocks`
1372
- ].filter(Boolean);
1373
- return messageTemplate.join("\n\n");
1374
- }
1375
- function applyStrategy(strategy2) {
1376
- const message = generateUnhandledRequestMessage();
1377
- switch (strategy2) {
1378
- case "error": {
1379
- devUtils.error("Error: %s", message);
1380
- throw new Error(
1381
- devUtils.formatMessage(
1382
- 'Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.'
1383
- )
1384
- );
1385
- }
1386
- case "warn": {
1387
- devUtils.warn("Warning: %s", message);
1388
- break;
1389
- }
1390
- case "bypass":
1391
- break;
1392
- default:
1393
- throw new Error(
1394
- devUtils.formatMessage(
1395
- '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.',
1396
- strategy2
1397
- )
1398
- );
1399
- }
1400
- }
1401
- if (typeof strategy === "function") {
1402
- strategy(request, {
1403
- warning: applyStrategy.bind(null, "warn"),
1404
- error: applyStrategy.bind(null, "error")
1405
- });
1406
- return;
1407
- }
1408
- applyStrategy(strategy);
1409
- }
22
+ // src/node/SetupServerApi.ts
23
+ import { setMaxListeners, defaultMaxListeners } from "events";
24
+ import { invariant } from "outvariant";
25
+ import {
26
+ BatchInterceptor,
27
+ InterceptorReadyState
28
+ } from "@mswjs/interceptors";
29
+ import { SetupApi } from '../core/SetupApi.mjs';
30
+ import { mergeRight } from '../core/utils/internal/mergeRight.mjs';
31
+ import { handleRequest } from '../core/utils/handleRequest.mjs';
32
+ import { devUtils } from '../core/utils/internal/devUtils.mjs';
1410
33
 
1411
- // src/utils/request/readResponseCookies.ts
1412
- import { store as store2 } from "@mswjs/cookies";
1413
- function readResponseCookies(request, response2) {
1414
- store2.add({ ...request, url: request.url.toString() }, response2);
1415
- store2.persist();
1416
- }
1417
-
1418
- // src/utils/handleRequest.ts
1419
- async function handleRequest(request, handlers, options, emitter, handleRequestOptions) {
1420
- var _a, _b, _c, _d, _e, _f;
1421
- emitter.emit("request:start", request);
1422
- if (request.headers.get("x-msw-bypass") === "true") {
1423
- emitter.emit("request:end", request);
1424
- (_a = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _a.call(handleRequestOptions, request);
1425
- return;
1426
- }
1427
- const [lookupError, lookupResult] = await until(() => {
1428
- return getResponse(
1429
- request,
1430
- handlers,
1431
- handleRequestOptions == null ? void 0 : handleRequestOptions.resolutionContext
1432
- );
1433
- });
1434
- if (lookupError) {
1435
- emitter.emit("unhandledException", lookupError, request);
1436
- throw lookupError;
1437
- }
1438
- const { handler, response: response2 } = lookupResult;
1439
- if (!handler) {
1440
- onUnhandledRequest(request, handlers, options.onUnhandledRequest);
1441
- emitter.emit("request:unhandled", request);
1442
- emitter.emit("request:end", request);
1443
- (_b = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _b.call(handleRequestOptions, request);
1444
- return;
1445
- }
1446
- if (!response2) {
1447
- devUtils.warn(
1448
- `Expected response resolver to return a mocked response Object, but got %s. The original response is going to be used instead.
1449
-
1450
- \u2022 %s
1451
- %s`,
1452
- response2,
1453
- handler.info.header,
1454
- handler.info.callFrame
1455
- );
1456
- emitter.emit("request:end", request);
1457
- (_c = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _c.call(handleRequestOptions, request);
1458
- return;
1459
- }
1460
- if (response2.passthrough) {
1461
- emitter.emit("request:end", request);
1462
- (_d = handleRequestOptions == null ? void 0 : handleRequestOptions.onPassthroughResponse) == null ? void 0 : _d.call(handleRequestOptions, request);
1463
- return;
1464
- }
1465
- readResponseCookies(request, response2);
1466
- emitter.emit("request:match", request);
1467
- const requiredLookupResult = lookupResult;
1468
- const transformedResponse = ((_e = handleRequestOptions == null ? void 0 : handleRequestOptions.transformResponse) == null ? void 0 : _e.call(handleRequestOptions, response2)) || response2;
1469
- (_f = handleRequestOptions == null ? void 0 : handleRequestOptions.onMockedResponse) == null ? void 0 : _f.call(
1470
- handleRequestOptions,
1471
- transformedResponse,
1472
- requiredLookupResult
1473
- );
1474
- emitter.emit("request:end", request);
1475
- return transformedResponse;
34
+ // src/node/utils/isNodeException.ts
35
+ function isNodeException(error) {
36
+ return error instanceof Error && "code" in error;
1476
37
  }
1477
38
 
1478
39
  // src/node/SetupServerApi.ts
1479
- var { bold } = chalk;
1480
40
  var DEFAULT_LISTEN_OPTIONS = {
1481
41
  onUnhandledRequest: "warn"
1482
42
  };
@@ -1490,49 +50,48 @@ var SetupServerApi = class extends SetupApi {
1490
50
  this.resolvedOptions = {};
1491
51
  this.init();
1492
52
  }
53
+ /**
54
+ * Subscribe to all requests that are using the interceptor object
55
+ */
1493
56
  init() {
1494
- this.interceptor.on("request", async (request) => {
1495
- const mockedRequest = new MockedRequest(request.url, {
1496
- ...request,
1497
- body: await request.arrayBuffer()
1498
- });
1499
- const response2 = await handleRequest(
1500
- mockedRequest,
1501
- this.currentHandlers,
1502
- this.resolvedOptions,
1503
- this.emitter,
1504
- {
1505
- transformResponse(response3) {
1506
- return {
1507
- status: response3.status,
1508
- statusText: response3.statusText,
1509
- headers: response3.headers.all(),
1510
- body: response3.body,
1511
- delay: response3.delay
1512
- };
57
+ this.interceptor.on("request", (_0) => __async(this, [_0], function* ({ request, requestId }) {
58
+ if (typeof setMaxListeners === "function") {
59
+ try {
60
+ setMaxListeners(
61
+ Math.max(defaultMaxListeners, this.currentHandlers.length),
62
+ request.signal
63
+ );
64
+ } catch (error) {
65
+ if (!(isNodeException(error) && error.code === "ERR_INVALID_ARG_TYPE")) {
66
+ throw error;
1513
67
  }
1514
68
  }
69
+ }
70
+ const response = yield handleRequest(
71
+ request,
72
+ requestId,
73
+ this.currentHandlers,
74
+ this.resolvedOptions,
75
+ this.emitter
1515
76
  );
1516
- if (response2) {
1517
- if (response2.delay) {
1518
- await new Promise((resolve) => {
1519
- setTimeout(resolve, response2.delay);
1520
- });
1521
- }
1522
- request.respondWith(response2);
77
+ if (response) {
78
+ request.respondWith(response);
1523
79
  }
1524
80
  return;
1525
- });
1526
- this.interceptor.on("response", (request, response2) => {
1527
- if (!request.id) {
1528
- return;
1529
- }
1530
- if (response2.headers.get("x-powered-by") === "msw") {
1531
- this.emitter.emit("response:mocked", response2, request.id);
1532
- } else {
1533
- this.emitter.emit("response:bypass", response2, request.id);
81
+ }));
82
+ this.interceptor.on(
83
+ "response",
84
+ ({ response, isMockedResponse, request, requestId }) => {
85
+ this.emitter.emit(
86
+ isMockedResponse ? "response:mocked" : "response:bypass",
87
+ {
88
+ response,
89
+ request,
90
+ requestId
91
+ }
92
+ );
1534
93
  }
1535
- });
94
+ );
1536
95
  }
1537
96
  listen(options = {}) {
1538
97
  this.resolvedOptions = mergeRight(
@@ -1540,7 +99,10 @@ var SetupServerApi = class extends SetupApi {
1540
99
  options
1541
100
  );
1542
101
  this.interceptor.apply();
1543
- invariant3(
102
+ this.subscriptions.push(() => {
103
+ this.interceptor.dispose();
104
+ });
105
+ invariant(
1544
106
  [InterceptorReadyState.APPLYING, InterceptorReadyState.APPLIED].includes(
1545
107
  this.interceptor.readyState
1546
108
  ),
@@ -1550,26 +112,15 @@ var SetupServerApi = class extends SetupApi {
1550
112
  "https://github.com/mswjs/msw/issues/new/choose"
1551
113
  );
1552
114
  }
1553
- printHandlers() {
1554
- const handlers = this.listHandlers();
1555
- handlers.forEach((handler) => {
1556
- const { header, callFrame } = handler.info;
1557
- const pragma = handler.info.hasOwnProperty("operationType") ? "[graphql]" : "[rest]";
1558
- console.log(`${bold(`${pragma} ${header}`)}
1559
- Declaration: ${callFrame}
1560
- `);
1561
- });
1562
- }
1563
115
  close() {
1564
- super.dispose();
1565
- this.interceptor.dispose();
116
+ this.dispose();
1566
117
  }
1567
118
  };
1568
119
 
1569
120
  // src/node/setupServer.ts
1570
- import { ClientRequestInterceptor } from "@mswjs/interceptors/lib/interceptors/ClientRequest/index.js";
1571
- import { XMLHttpRequestInterceptor } from "@mswjs/interceptors/lib/interceptors/XMLHttpRequest/index.js";
1572
- import { FetchInterceptor } from "@mswjs/interceptors/lib/interceptors/fetch/index.js";
121
+ import { ClientRequestInterceptor } from "@mswjs/interceptors/ClientRequest";
122
+ import { XMLHttpRequestInterceptor } from "@mswjs/interceptors/XMLHttpRequest";
123
+ import { FetchInterceptor } from "@mswjs/interceptors/fetch";
1573
124
  var setupServer = (...handlers) => {
1574
125
  return new SetupServerApi(
1575
126
  [ClientRequestInterceptor, XMLHttpRequestInterceptor, FetchInterceptor],
@@ -1580,4 +131,3 @@ export {
1580
131
  SetupServerApi,
1581
132
  setupServer
1582
133
  };
1583
- //# sourceMappingURL=index.mjs.map