msw 0.47.4 → 0.48.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.
@@ -56,25 +56,299 @@ __export(native_exports, {
56
56
  module.exports = __toCommonJS(native_exports);
57
57
  var import_XMLHttpRequest = require("@mswjs/interceptors/lib/interceptors/XMLHttpRequest");
58
58
 
59
- // src/node/createSetupServer.ts
60
- var import_chalk = require("chalk");
61
- var import_is_node_process3 = require("is-node-process");
62
- var import_strict_event_emitter = require("strict-event-emitter");
59
+ // src/node/SetupServerApi.ts
60
+ var import_chalk = __toESM(require("chalk"));
61
+ var import_outvariant4 = require("outvariant");
63
62
  var import_interceptors2 = require("@mswjs/interceptors");
64
63
 
65
- // src/utils/internal/requestHandlerUtils.ts
66
- function use(currentHandlers, ...handlers) {
67
- currentHandlers.unshift(...handlers);
64
+ // src/SetupApi.ts
65
+ var import_outvariant2 = require("outvariant");
66
+ var import_strict_event_emitter = require("strict-event-emitter");
67
+
68
+ // src/utils/internal/devUtils.ts
69
+ var import_outvariant = require("outvariant");
70
+ var LIBRARY_PREFIX = "[MSW]";
71
+ function formatMessage(message, ...positionals) {
72
+ const interpolatedMessage = (0, import_outvariant.format)(message, ...positionals);
73
+ return `${LIBRARY_PREFIX} ${interpolatedMessage}`;
68
74
  }
69
- function restoreHandlers(handlers) {
70
- handlers.forEach((handler) => {
71
- handler.markAsSkipped(false);
72
- });
75
+ function warn(message, ...positionals) {
76
+ console.warn(formatMessage(message, ...positionals));
77
+ }
78
+ function error(message, ...positionals) {
79
+ console.error(formatMessage(message, ...positionals));
80
+ }
81
+ var devUtils = {
82
+ formatMessage,
83
+ warn,
84
+ error
85
+ };
86
+
87
+ // src/utils/internal/pipeEvents.ts
88
+ function pipeEvents(source, destination) {
89
+ const rawEmit = source.emit;
90
+ if (rawEmit._isPiped) {
91
+ return;
92
+ }
93
+ source.emit = function(event, ...data2) {
94
+ destination.emit(event, ...data2);
95
+ return rawEmit.call(this, event, ...data2);
96
+ };
97
+ source.emit._isPiped = true;
98
+ }
99
+
100
+ // src/utils/internal/toReadonlyArray.ts
101
+ function toReadonlyArray(source) {
102
+ const clone = [...source];
103
+ Object.freeze(clone);
104
+ return clone;
105
+ }
106
+
107
+ // src/SetupApi.ts
108
+ var SetupApi = class {
109
+ constructor(initialHandlers) {
110
+ this.validateHandlers(initialHandlers);
111
+ this.initialHandlers = toReadonlyArray(initialHandlers);
112
+ this.currentHandlers = [...initialHandlers];
113
+ this.emitter = new import_strict_event_emitter.StrictEventEmitter();
114
+ this.publicEmitter = new import_strict_event_emitter.StrictEventEmitter();
115
+ pipeEvents(this.emitter, this.publicEmitter);
116
+ this.events = this.createLifeCycleEvents();
117
+ }
118
+ validateHandlers(handlers) {
119
+ for (const handler of handlers) {
120
+ (0, import_outvariant2.invariant)(!Array.isArray(handler), devUtils.formatMessage('Failed to construct "%s" given an Array of request handlers. Make sure you spread the request handlers when calling the respective setup function.'), this.constructor.name);
121
+ }
122
+ }
123
+ dispose() {
124
+ this.emitter.removeAllListeners();
125
+ this.publicEmitter.removeAllListeners();
126
+ }
127
+ use(...runtimeHandlers) {
128
+ this.currentHandlers.unshift(...runtimeHandlers);
129
+ }
130
+ restoreHandlers() {
131
+ this.currentHandlers.forEach((handler) => {
132
+ handler.markAsSkipped(false);
133
+ });
134
+ }
135
+ resetHandlers(...nextHandlers) {
136
+ this.currentHandlers = nextHandlers.length > 0 ? [...nextHandlers] : [...this.initialHandlers];
137
+ }
138
+ listHandlers() {
139
+ return toReadonlyArray(this.currentHandlers);
140
+ }
141
+ createLifeCycleEvents() {
142
+ return {
143
+ on: (...args) => {
144
+ return this.publicEmitter.on(...args);
145
+ },
146
+ removeListener: (...args) => {
147
+ return this.publicEmitter.removeListener(...args);
148
+ },
149
+ removeAllListeners: (...args) => {
150
+ return this.publicEmitter.removeAllListeners(...args);
151
+ }
152
+ };
153
+ }
154
+ };
155
+
156
+ // src/utils/internal/isObject.ts
157
+ function isObject(value) {
158
+ return value != null && typeof value === "object" && !Array.isArray(value);
159
+ }
160
+
161
+ // src/utils/internal/mergeRight.ts
162
+ function mergeRight(left, right) {
163
+ return Object.entries(right).reduce((result, [key, rightValue]) => {
164
+ const leftValue = result[key];
165
+ if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
166
+ result[key] = leftValue.concat(rightValue);
167
+ return result;
168
+ }
169
+ if (isObject(leftValue) && isObject(rightValue)) {
170
+ result[key] = mergeRight(leftValue, rightValue);
171
+ return result;
172
+ }
173
+ result[key] = rightValue;
174
+ return result;
175
+ }, Object.assign({}, left));
176
+ }
177
+
178
+ // src/utils/request/MockedRequest.ts
179
+ var cookieUtils2 = __toESM(require("cookie"));
180
+ var import_cookies = require("@mswjs/cookies");
181
+ var import_interceptors = require("@mswjs/interceptors");
182
+ var import_bufferUtils = require("@mswjs/interceptors/lib/utils/bufferUtils");
183
+ var import_headers_polyfill2 = require("headers-polyfill");
184
+
185
+ // src/utils/request/getRequestCookies.ts
186
+ var cookieUtils = __toESM(require("cookie"));
187
+ function getAllCookies() {
188
+ return cookieUtils.parse(document.cookie);
189
+ }
190
+ function getRequestCookies(request) {
191
+ if (typeof document === "undefined" || typeof location === "undefined") {
192
+ return {};
193
+ }
194
+ switch (request.credentials) {
195
+ case "same-origin": {
196
+ return location.origin === request.url.origin ? getAllCookies() : {};
197
+ }
198
+ case "include": {
199
+ return getAllCookies();
200
+ }
201
+ default: {
202
+ return {};
203
+ }
204
+ }
205
+ }
206
+
207
+ // src/utils/internal/jsonParse.ts
208
+ function jsonParse(value) {
209
+ try {
210
+ return JSON.parse(value);
211
+ } catch (error2) {
212
+ return void 0;
213
+ }
214
+ }
215
+
216
+ // src/utils/internal/parseMultipartData.ts
217
+ var import_headers_polyfill = require("headers-polyfill");
218
+ function parseContentHeaders(headersString) {
219
+ var _a, _b;
220
+ const headers = (0, import_headers_polyfill.stringToHeaders)(headersString);
221
+ const contentType = headers.get("content-type") || "text/plain";
222
+ const disposition = headers.get("content-disposition");
223
+ if (!disposition) {
224
+ throw new Error('"Content-Disposition" header is required.');
225
+ }
226
+ const directives = disposition.split(";").reduce((acc, chunk) => {
227
+ const [name2, ...rest] = chunk.trim().split("=");
228
+ acc[name2] = rest.join("=");
229
+ return acc;
230
+ }, {});
231
+ const name = (_a = directives.name) == null ? void 0 : _a.slice(1, -1);
232
+ const filename = (_b = directives.filename) == null ? void 0 : _b.slice(1, -1);
233
+ return {
234
+ name,
235
+ filename,
236
+ contentType
237
+ };
238
+ }
239
+ function parseMultipartData(data2, headers) {
240
+ const contentType = headers == null ? void 0 : headers.get("content-type");
241
+ if (!contentType) {
242
+ return void 0;
243
+ }
244
+ const [, ...directives] = contentType.split(/; */);
245
+ const boundary = directives.filter((d) => d.startsWith("boundary=")).map((s) => s.replace(/^boundary=/, ""))[0];
246
+ if (!boundary) {
247
+ return void 0;
248
+ }
249
+ const boundaryRegExp = new RegExp(`--+${boundary}`);
250
+ const fields = data2.split(boundaryRegExp).filter((chunk) => chunk.startsWith("\r\n") && chunk.endsWith("\r\n")).map((chunk) => chunk.trimStart().replace(/\r\n$/, ""));
251
+ if (!fields.length) {
252
+ return void 0;
253
+ }
254
+ const parsedBody = {};
255
+ try {
256
+ for (const field2 of fields) {
257
+ const [contentHeaders, ...rest] = field2.split("\r\n\r\n");
258
+ const contentBody = rest.join("\r\n\r\n");
259
+ const { contentType: contentType2, filename, name } = parseContentHeaders(contentHeaders);
260
+ const value = filename === void 0 ? contentBody : new File([contentBody], filename, { type: contentType2 });
261
+ const parsedValue = parsedBody[name];
262
+ if (parsedValue === void 0) {
263
+ parsedBody[name] = value;
264
+ } else if (Array.isArray(parsedValue)) {
265
+ parsedBody[name] = [...parsedValue, value];
266
+ } else {
267
+ parsedBody[name] = [parsedValue, value];
268
+ }
269
+ }
270
+ return parsedBody;
271
+ } catch (error2) {
272
+ return void 0;
273
+ }
274
+ }
275
+
276
+ // src/utils/request/parseBody.ts
277
+ function parseBody(body2, headers) {
278
+ var _a;
279
+ if (!body2) {
280
+ return body2;
281
+ }
282
+ const contentType = ((_a = headers == null ? void 0 : headers.get("content-type")) == null ? void 0 : _a.toLowerCase()) || "";
283
+ const hasMultipartContent = contentType.startsWith("multipart/form-data");
284
+ if (hasMultipartContent && typeof body2 !== "object") {
285
+ return parseMultipartData(body2.toString(), headers) || body2;
286
+ }
287
+ const hasJsonContent = contentType.includes("json");
288
+ if (hasJsonContent && typeof body2 !== "object") {
289
+ return jsonParse(body2.toString()) || body2;
290
+ }
291
+ return body2;
73
292
  }
74
- function resetHandlers(initialHandlers, ...nextHandlers) {
75
- return nextHandlers.length > 0 ? [...nextHandlers] : [...initialHandlers];
293
+
294
+ // src/utils/internal/isStringEqual.ts
295
+ function isStringEqual(actual, expected) {
296
+ return actual.toLowerCase() === expected.toLowerCase();
76
297
  }
77
298
 
299
+ // src/utils/request/MockedRequest.ts
300
+ var MockedRequest = class extends import_interceptors.IsomorphicRequest {
301
+ constructor(url, init = {}) {
302
+ super(url, init);
303
+ if (init.id) {
304
+ this.id = init.id;
305
+ }
306
+ this.cache = init.cache || "default";
307
+ this.destination = init.destination || "";
308
+ this.integrity = init.integrity || "";
309
+ this.keepalive = init.keepalive || false;
310
+ this.mode = init.mode || "cors";
311
+ this.priority = init.priority || "auto";
312
+ this.redirect = init.redirect || "follow";
313
+ this.referrer = init.referrer || "";
314
+ this.referrerPolicy = init.referrerPolicy || "no-referrer";
315
+ this.cookies = init.cookies || this.getCookies();
316
+ }
317
+ get body() {
318
+ const text2 = (0, import_bufferUtils.decodeBuffer)(this["_body"]);
319
+ const body2 = parseBody(text2, this.headers);
320
+ if (isStringEqual(this.method, "GET") && body2 === "") {
321
+ return void 0;
322
+ }
323
+ return body2;
324
+ }
325
+ passthrough() {
326
+ return {
327
+ status: 101,
328
+ statusText: "Continue",
329
+ headers: new import_headers_polyfill2.Headers(),
330
+ body: null,
331
+ passthrough: true,
332
+ once: false
333
+ };
334
+ }
335
+ getCookies() {
336
+ var _a;
337
+ const requestCookiesString = this.headers.get("cookie");
338
+ const ownCookies = requestCookiesString ? cookieUtils2.parse(requestCookiesString) : {};
339
+ import_cookies.store.hydrate();
340
+ const cookiesFromStore = Array.from((_a = import_cookies.store.get(__spreadProps(__spreadValues({}, this), { url: this.url.href }))) == null ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => {
341
+ return Object.assign(cookies, { [name.trim()]: value });
342
+ }, {});
343
+ const cookiesFromDocument = getRequestCookies(this);
344
+ const forwardedCookies = __spreadValues(__spreadValues({}, cookiesFromDocument), cookiesFromStore);
345
+ for (const [name, value] of Object.entries(forwardedCookies)) {
346
+ this.headers.append("cookie", `${name}=${value}`);
347
+ }
348
+ return __spreadValues(__spreadValues({}, forwardedCookies), ownCookies);
349
+ }
350
+ };
351
+
78
352
  // src/utils/handleRequest.ts
79
353
  var import_until = require("@open-draft/until");
80
354
 
@@ -125,25 +399,6 @@ var getResponse = async (request, handlers, resolutionContext) => {
125
399
  };
126
400
  };
127
401
 
128
- // src/utils/internal/devUtils.ts
129
- var import_outvariant = require("outvariant");
130
- var LIBRARY_PREFIX = "[MSW]";
131
- function formatMessage(message, ...positionals) {
132
- const interpolatedMessage = (0, import_outvariant.format)(message, ...positionals);
133
- return `${LIBRARY_PREFIX} ${interpolatedMessage}`;
134
- }
135
- function warn(message, ...positionals) {
136
- console.warn(formatMessage(message, ...positionals));
137
- }
138
- function error(message, ...positionals) {
139
- console.error(formatMessage(message, ...positionals));
140
- }
141
- var devUtils = {
142
- formatMessage,
143
- warn,
144
- error
145
- };
146
-
147
402
  // src/utils/request/onUnhandledRequest.ts
148
403
  var import_js_levenshtein = __toESM(require("js-levenshtein"));
149
404
 
@@ -155,15 +410,6 @@ var getPublicUrlFromRequest = (request) => {
155
410
  return request.referrer.startsWith(request.url.origin) ? request.url.pathname : new URL(request.url.pathname, `${request.url.protocol}//${request.url.host}`).href;
156
411
  };
157
412
 
158
- // src/utils/internal/jsonParse.ts
159
- function jsonParse(value) {
160
- try {
161
- return JSON.parse(value);
162
- } catch (error2) {
163
- return void 0;
164
- }
165
- }
166
-
167
413
  // src/utils/internal/parseGraphQLRequest.ts
168
414
  function parseDocumentNode(node) {
169
415
  var _a;
@@ -259,11 +505,6 @@ function parseGraphQLRequest(request) {
259
505
  };
260
506
  }
261
507
 
262
- // src/utils/internal/isStringEqual.ts
263
- function isStringEqual(actual, expected) {
264
- return actual.toLowerCase() === expected.toLowerCase();
265
- }
266
-
267
508
  // src/context/status.ts
268
509
  var import_codes = __toESM(require("statuses/codes.json"));
269
510
  var status = (statusCode, statusText) => {
@@ -275,14 +516,14 @@ var status = (statusCode, statusText) => {
275
516
  };
276
517
 
277
518
  // src/context/set.ts
278
- var import_headers_polyfill = require("headers-polyfill");
519
+ var import_headers_polyfill3 = require("headers-polyfill");
279
520
  function set(...args) {
280
521
  return (res) => {
281
522
  const [name, value] = args;
282
523
  if (typeof name === "string") {
283
524
  res.headers.append(name, value);
284
525
  } else {
285
- const headers = (0, import_headers_polyfill.objectToHeaders)(name);
526
+ const headers = (0, import_headers_polyfill3.objectToHeaders)(name);
286
527
  headers.forEach((value2, name2) => {
287
528
  res.headers.append(name2, value2);
288
529
  });
@@ -292,10 +533,10 @@ function set(...args) {
292
533
  }
293
534
 
294
535
  // src/context/cookie.ts
295
- var cookieUtils = __toESM(require("cookie"));
536
+ var cookieUtils3 = __toESM(require("cookie"));
296
537
  var cookie = (name, value, options) => {
297
538
  return (res) => {
298
- const serializedCookie = cookieUtils.serialize(name, value, options);
539
+ const serializedCookie = cookieUtils3.serialize(name, value, options);
299
540
  res.headers.append("Set-Cookie", serializedCookie);
300
541
  if (typeof document !== "undefined") {
301
542
  document.cookie = serializedCookie;
@@ -312,28 +553,6 @@ var body = (value) => {
312
553
  };
313
554
  };
314
555
 
315
- // src/utils/internal/isObject.ts
316
- function isObject(value) {
317
- return value != null && typeof value === "object" && !Array.isArray(value);
318
- }
319
-
320
- // src/utils/internal/mergeRight.ts
321
- function mergeRight(left, right) {
322
- return Object.entries(right).reduce((result, [key, rightValue]) => {
323
- const leftValue = result[key];
324
- if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
325
- result[key] = leftValue.concat(rightValue);
326
- return result;
327
- }
328
- if (isObject(leftValue) && isObject(rightValue)) {
329
- result[key] = mergeRight(leftValue, rightValue);
330
- return result;
331
- }
332
- result[key] = rightValue;
333
- return result;
334
- }, Object.assign({}, left));
335
- }
336
-
337
556
  // src/context/json.ts
338
557
  var json = (body2) => {
339
558
  return (res) => {
@@ -417,10 +636,10 @@ var errors = (errorsList) => {
417
636
 
418
637
  // src/context/fetch.ts
419
638
  var import_is_node_process2 = require("is-node-process");
420
- var import_headers_polyfill2 = require("headers-polyfill");
421
- var useFetch = (0, import_is_node_process2.isNodeProcess)() ? require("node-fetch") : window.fetch;
639
+ var import_headers_polyfill4 = require("headers-polyfill");
640
+ var useFetch = (0, import_is_node_process2.isNodeProcess)() ? (input, init) => Promise.resolve().then(() => __toESM(require("node-fetch"))).then(({ default: nodeFetch }) => nodeFetch(input, init)) : window.fetch;
422
641
  var augmentRequestInit = (requestInit) => {
423
- const headers = new import_headers_polyfill2.Headers(requestInit.headers);
642
+ const headers = new import_headers_polyfill4.Headers(requestInit.headers);
424
643
  headers.set("x-msw-bypass", "true");
425
644
  return __spreadProps(__spreadValues({}, requestInit), {
426
645
  headers: headers.all()
@@ -494,89 +713,9 @@ function prepareRequest(request) {
494
713
  }
495
714
 
496
715
  // src/utils/logging/prepareResponse.ts
497
- var import_headers_polyfill4 = require("headers-polyfill");
498
-
499
- // src/utils/internal/parseMultipartData.ts
500
- var import_headers_polyfill3 = require("headers-polyfill");
501
- function parseContentHeaders(headersString) {
502
- var _a, _b;
503
- const headers = (0, import_headers_polyfill3.stringToHeaders)(headersString);
504
- const contentType = headers.get("content-type") || "text/plain";
505
- const disposition = headers.get("content-disposition");
506
- if (!disposition) {
507
- throw new Error('"Content-Disposition" header is required.');
508
- }
509
- const directives = disposition.split(";").reduce((acc, chunk) => {
510
- const [name2, ...rest] = chunk.trim().split("=");
511
- acc[name2] = rest.join("=");
512
- return acc;
513
- }, {});
514
- const name = (_a = directives.name) == null ? void 0 : _a.slice(1, -1);
515
- const filename = (_b = directives.filename) == null ? void 0 : _b.slice(1, -1);
516
- return {
517
- name,
518
- filename,
519
- contentType
520
- };
521
- }
522
- function parseMultipartData(data2, headers) {
523
- const contentType = headers == null ? void 0 : headers.get("content-type");
524
- if (!contentType) {
525
- return void 0;
526
- }
527
- const [, ...directives] = contentType.split(/; */);
528
- const boundary = directives.filter((d) => d.startsWith("boundary=")).map((s) => s.replace(/^boundary=/, ""))[0];
529
- if (!boundary) {
530
- return void 0;
531
- }
532
- const boundaryRegExp = new RegExp(`--+${boundary}`);
533
- const fields = data2.split(boundaryRegExp).filter((chunk) => chunk.startsWith("\r\n") && chunk.endsWith("\r\n")).map((chunk) => chunk.trimStart().replace(/\r\n$/, ""));
534
- if (!fields.length) {
535
- return void 0;
536
- }
537
- const parsedBody = {};
538
- try {
539
- for (const field2 of fields) {
540
- const [contentHeaders, ...rest] = field2.split("\r\n\r\n");
541
- const contentBody = rest.join("\r\n\r\n");
542
- const { contentType: contentType2, filename, name } = parseContentHeaders(contentHeaders);
543
- const value = filename === void 0 ? contentBody : new File([contentBody], filename, { type: contentType2 });
544
- const parsedValue = parsedBody[name];
545
- if (parsedValue === void 0) {
546
- parsedBody[name] = value;
547
- } else if (Array.isArray(parsedValue)) {
548
- parsedBody[name] = [...parsedValue, value];
549
- } else {
550
- parsedBody[name] = [parsedValue, value];
551
- }
552
- }
553
- return parsedBody;
554
- } catch (error2) {
555
- return void 0;
556
- }
557
- }
558
-
559
- // src/utils/request/parseBody.ts
560
- function parseBody(body2, headers) {
561
- var _a;
562
- if (!body2) {
563
- return body2;
564
- }
565
- const contentType = ((_a = headers == null ? void 0 : headers.get("content-type")) == null ? void 0 : _a.toLowerCase()) || "";
566
- const hasMultipartContent = contentType.startsWith("multipart/form-data");
567
- if (hasMultipartContent && typeof body2 !== "object") {
568
- return parseMultipartData(body2.toString(), headers) || body2;
569
- }
570
- const hasJsonContent = contentType.includes("json");
571
- if (hasJsonContent && typeof body2 !== "object") {
572
- return jsonParse(body2.toString()) || body2;
573
- }
574
- return body2;
575
- }
576
-
577
- // src/utils/logging/prepareResponse.ts
716
+ var import_headers_polyfill5 = require("headers-polyfill");
578
717
  function prepareResponse(res) {
579
- const responseHeaders = (0, import_headers_polyfill4.objectToHeaders)(res.headers);
718
+ const responseHeaders = (0, import_headers_polyfill5.objectToHeaders)(res.headers);
580
719
  return __spreadProps(__spreadValues({}, res), {
581
720
  body: parseBody(res.body, responseHeaders)
582
721
  });
@@ -584,7 +723,7 @@ function prepareResponse(res) {
584
723
 
585
724
  // src/utils/matching/matchRequestUrl.ts
586
725
  var import_path_to_regexp = require("path-to-regexp");
587
- var import_getCleanUrl = require("@mswjs/interceptors/lib/utils/getCleanUrl");
726
+ var import_getCleanUrl = require("@mswjs/interceptors/lib/utils/getCleanUrl.js");
588
727
 
589
728
  // src/utils/url/cleanUrl.ts
590
729
  var REDUNDANT_CHARACTERS_EXP = /[\?|#].*$/g;
@@ -643,88 +782,6 @@ function matchRequestUrl(url, path, baseUrl) {
643
782
  };
644
783
  }
645
784
 
646
- // src/utils/request/MockedRequest.ts
647
- var cookieUtils3 = __toESM(require("cookie"));
648
- var import_cookies = require("@mswjs/cookies");
649
- var import_interceptors = require("@mswjs/interceptors");
650
- var import_bufferUtils = require("@mswjs/interceptors/lib/utils/bufferUtils");
651
- var import_headers_polyfill5 = require("headers-polyfill");
652
-
653
- // src/utils/request/getRequestCookies.ts
654
- var cookieUtils2 = __toESM(require("cookie"));
655
- function getAllCookies() {
656
- return cookieUtils2.parse(document.cookie);
657
- }
658
- function getRequestCookies(request) {
659
- if (typeof document === "undefined" || typeof location === "undefined") {
660
- return {};
661
- }
662
- switch (request.credentials) {
663
- case "same-origin": {
664
- return location.origin === request.url.origin ? getAllCookies() : {};
665
- }
666
- case "include": {
667
- return getAllCookies();
668
- }
669
- default: {
670
- return {};
671
- }
672
- }
673
- }
674
-
675
- // src/utils/request/MockedRequest.ts
676
- var MockedRequest = class extends import_interceptors.IsomorphicRequest {
677
- constructor(url, init = {}) {
678
- super(url, init);
679
- if (init.id) {
680
- this.id = init.id;
681
- }
682
- this.cache = init.cache || "default";
683
- this.destination = init.destination || "";
684
- this.integrity = init.integrity || "";
685
- this.keepalive = init.keepalive || false;
686
- this.mode = init.mode || "cors";
687
- this.priority = init.priority || "auto";
688
- this.redirect = init.redirect || "follow";
689
- this.referrer = init.referrer || "";
690
- this.referrerPolicy = init.referrerPolicy || "no-referrer";
691
- this.cookies = init.cookies || this.getCookies();
692
- }
693
- get body() {
694
- const text2 = (0, import_bufferUtils.decodeBuffer)(this["_body"]);
695
- const body2 = parseBody(text2, this.headers);
696
- if (isStringEqual(this.method, "GET") && body2 === "") {
697
- return void 0;
698
- }
699
- return body2;
700
- }
701
- passthrough() {
702
- return {
703
- status: 101,
704
- statusText: "Continue",
705
- headers: new import_headers_polyfill5.Headers(),
706
- body: null,
707
- passthrough: true,
708
- once: false
709
- };
710
- }
711
- getCookies() {
712
- var _a;
713
- const requestCookiesString = this.headers.get("cookie");
714
- const ownCookies = requestCookiesString ? cookieUtils3.parse(requestCookiesString) : {};
715
- import_cookies.store.hydrate();
716
- const cookiesFromStore = Array.from((_a = import_cookies.store.get(__spreadProps(__spreadValues({}, this), { url: this.url.href }))) == null ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => {
717
- return Object.assign(cookies, { [name.trim()]: value });
718
- }, {});
719
- const cookiesFromDocument = getRequestCookies(this);
720
- const forwardedCookies = __spreadValues(__spreadValues({}, cookiesFromDocument), cookiesFromStore);
721
- for (const [name, value] of Object.entries(forwardedCookies)) {
722
- this.headers.append("cookie", `${name}=${value}`);
723
- }
724
- return __spreadValues(__spreadValues({}, forwardedCookies), ownCookies);
725
- }
726
- };
727
-
728
785
  // src/handlers/RequestHandler.ts
729
786
  var import_headers_polyfill7 = require("headers-polyfill");
730
787
 
@@ -948,7 +1005,7 @@ var RestHandler = class extends RequestHandler {
948
1005
  };
949
1006
 
950
1007
  // src/context/field.ts
951
- var import_outvariant2 = require("outvariant");
1008
+ var import_outvariant3 = require("outvariant");
952
1009
  var field = (fieldName, fieldValue) => {
953
1010
  return (res) => {
954
1011
  validateFieldName(fieldName);
@@ -958,10 +1015,10 @@ var field = (fieldName, fieldValue) => {
958
1015
  };
959
1016
  };
960
1017
  function validateFieldName(fieldName) {
961
- (0, import_outvariant2.invariant)(fieldName.trim() !== "", devUtils.formatMessage("Failed to set a custom field on a GraphQL response: field name cannot be empty."));
962
- (0, import_outvariant2.invariant)(fieldName !== "data", devUtils.formatMessage('Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.data()" instead?', fieldName));
963
- (0, import_outvariant2.invariant)(fieldName !== "errors", devUtils.formatMessage('Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.errors()" instead?', fieldName));
964
- (0, import_outvariant2.invariant)(fieldName !== "extensions", devUtils.formatMessage('Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.extensions()" instead?', fieldName));
1018
+ (0, import_outvariant3.invariant)(fieldName.trim() !== "", devUtils.formatMessage("Failed to set a custom field on a GraphQL response: field name cannot be empty."));
1019
+ (0, import_outvariant3.invariant)(fieldName !== "data", devUtils.formatMessage('Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.data()" instead?', fieldName));
1020
+ (0, import_outvariant3.invariant)(fieldName !== "errors", devUtils.formatMessage('Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.errors()" instead?', fieldName));
1021
+ (0, import_outvariant3.invariant)(fieldName !== "extensions", devUtils.formatMessage('Failed to set a custom "%s" field on a mocked GraphQL response: forbidden field name. Did you mean to call "ctx.extensions()" instead?', fieldName));
965
1022
  }
966
1023
 
967
1024
  // src/utils/internal/tryCatch.ts
@@ -1219,53 +1276,27 @@ async function handleRequest(request, handlers, options, emitter, handleRequestO
1219
1276
  return transformedResponse;
1220
1277
  }
1221
1278
 
1222
- // src/utils/internal/pipeEvents.ts
1223
- function pipeEvents(source, destination) {
1224
- const rawEmit = source.emit;
1225
- if (rawEmit._isPiped) {
1226
- return;
1227
- }
1228
- source.emit = function(event, ...data2) {
1229
- destination.emit(event, ...data2);
1230
- return rawEmit.call(this, event, ...data2);
1231
- };
1232
- source.emit._isPiped = true;
1233
- }
1234
-
1235
- // src/utils/internal/toReadonlyArray.ts
1236
- function toReadonlyArray(source) {
1237
- const clone = [...source];
1238
- Object.freeze(clone);
1239
- return clone;
1240
- }
1241
-
1242
- // src/node/createSetupServer.ts
1279
+ // src/node/SetupServerApi.ts
1280
+ var { bold } = import_chalk.default;
1243
1281
  var DEFAULT_LISTEN_OPTIONS = {
1244
1282
  onUnhandledRequest: "warn"
1245
1283
  };
1246
- function createSetupServer(...interceptors) {
1247
- const emitter = new import_strict_event_emitter.StrictEventEmitter();
1248
- const publicEmitter = new import_strict_event_emitter.StrictEventEmitter();
1249
- pipeEvents(emitter, publicEmitter);
1250
- return function setupServer2(...requestHandlers) {
1251
- requestHandlers.forEach((handler) => {
1252
- if (Array.isArray(handler))
1253
- throw new Error(devUtils.formatMessage('Failed to call "setupServer" given an Array of request handlers (setupServer([a, b])), expected to receive each handler individually: setupServer(a, b).'));
1254
- });
1255
- let currentHandlers = [...requestHandlers];
1256
- if (!(0, import_is_node_process3.isNodeProcess)()) {
1257
- throw new Error(devUtils.formatMessage("Failed to execute `setupServer` in the environment that is not Node.js (i.e. a browser). Consider using `setupWorker` instead."));
1258
- }
1259
- let resolvedOptions = {};
1260
- const interceptor = new import_interceptors2.BatchInterceptor({
1284
+ var SetupServerApi = class extends SetupApi {
1285
+ constructor(interceptors, handlers) {
1286
+ super(handlers);
1287
+ this.interceptor = new import_interceptors2.BatchInterceptor({
1261
1288
  name: "setup-server",
1262
1289
  interceptors: interceptors.map((Interceptor2) => new Interceptor2())
1263
1290
  });
1264
- interceptor.on("request", async function setupServerListener(request) {
1291
+ this.resolvedOptions = {};
1292
+ this.init();
1293
+ }
1294
+ init() {
1295
+ this.interceptor.on("request", async (request) => {
1265
1296
  const mockedRequest = new MockedRequest(request.url, __spreadProps(__spreadValues({}, request), {
1266
1297
  body: await request.arrayBuffer()
1267
1298
  }));
1268
- const response2 = await handleRequest(mockedRequest, currentHandlers, resolvedOptions, emitter, {
1299
+ const response2 = await handleRequest(mockedRequest, this.currentHandlers, this.resolvedOptions, this.emitter, {
1269
1300
  transformResponse(response3) {
1270
1301
  return {
1271
1302
  status: response3.status,
@@ -1286,65 +1317,42 @@ function createSetupServer(...interceptors) {
1286
1317
  }
1287
1318
  return;
1288
1319
  });
1289
- interceptor.on("response", (request, response2) => {
1320
+ this.interceptor.on("response", (request, response2) => {
1290
1321
  if (!request.id) {
1291
1322
  return;
1292
1323
  }
1293
1324
  if (response2.headers.get("x-powered-by") === "msw") {
1294
- emitter.emit("response:mocked", response2, request.id);
1325
+ this.emitter.emit("response:mocked", response2, request.id);
1295
1326
  } else {
1296
- emitter.emit("response:bypass", response2, request.id);
1327
+ this.emitter.emit("response:bypass", response2, request.id);
1297
1328
  }
1298
1329
  });
1299
- return {
1300
- listen(options) {
1301
- resolvedOptions = mergeRight(DEFAULT_LISTEN_OPTIONS, options || {});
1302
- interceptor.apply();
1303
- },
1304
- use(...handlers) {
1305
- use(currentHandlers, ...handlers);
1306
- },
1307
- restoreHandlers() {
1308
- restoreHandlers(currentHandlers);
1309
- },
1310
- resetHandlers(...nextHandlers) {
1311
- currentHandlers = resetHandlers(requestHandlers, ...nextHandlers);
1312
- },
1313
- listHandlers() {
1314
- return toReadonlyArray(currentHandlers);
1315
- },
1316
- printHandlers() {
1317
- const handlers = this.listHandlers();
1318
- handlers.forEach((handler) => {
1319
- const { header, callFrame } = handler.info;
1320
- const pragma = handler.info.hasOwnProperty("operationType") ? "[graphql]" : "[rest]";
1321
- console.log(`${(0, import_chalk.bold)(`${pragma} ${header}`)}
1330
+ }
1331
+ listen(options = {}) {
1332
+ this.resolvedOptions = mergeRight(DEFAULT_LISTEN_OPTIONS, options);
1333
+ this.interceptor.apply();
1334
+ (0, import_outvariant4.invariant)([import_interceptors2.InterceptorReadyState.APPLYING, import_interceptors2.InterceptorReadyState.APPLIED].includes(this.interceptor.readyState), devUtils.formatMessage('Failed to start "setupServer": the interceptor failed to apply. This is likely an issue with the library and you should report it at "%s".'), "https://github.com/mswjs/msw/issues/new/choose");
1335
+ }
1336
+ printHandlers() {
1337
+ const handlers = this.listHandlers();
1338
+ handlers.forEach((handler) => {
1339
+ const { header, callFrame } = handler.info;
1340
+ const pragma = handler.info.hasOwnProperty("operationType") ? "[graphql]" : "[rest]";
1341
+ console.log(`${bold(`${pragma} ${header}`)}
1322
1342
  Declaration: ${callFrame}
1323
1343
  `);
1324
- });
1325
- },
1326
- events: {
1327
- on(...args) {
1328
- return publicEmitter.on(...args);
1329
- },
1330
- removeListener(...args) {
1331
- return publicEmitter.removeListener(...args);
1332
- },
1333
- removeAllListeners(...args) {
1334
- return publicEmitter.removeAllListeners(...args);
1335
- }
1336
- },
1337
- close() {
1338
- emitter.removeAllListeners();
1339
- publicEmitter.removeAllListeners();
1340
- interceptor.dispose();
1341
- }
1342
- };
1343
- };
1344
- }
1344
+ });
1345
+ }
1346
+ close() {
1347
+ super.dispose();
1348
+ this.interceptor.dispose();
1349
+ }
1350
+ };
1345
1351
 
1346
1352
  // src/native/index.ts
1347
- var setupServer = createSetupServer(import_XMLHttpRequest.XMLHttpRequestInterceptor);
1353
+ function setupServer(...handlers) {
1354
+ return new SetupServerApi([import_XMLHttpRequest.XMLHttpRequestInterceptor], handlers);
1355
+ }
1348
1356
  // Annotate the CommonJS export names for ESM import in node:
1349
1357
  0 && (module.exports = {
1350
1358
  setupServer