msw 2.0.5 → 2.0.7

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.
@@ -35,6 +35,7 @@ type GraphQLResolverExtras<Variables extends GraphQLVariables> = {
35
35
  query: string;
36
36
  operationName: string;
37
37
  variables: Variables;
38
+ cookies: Record<string, string>;
38
39
  };
39
40
  type GraphQLRequestBody<VariablesType extends GraphQLVariables> = GraphQLJsonRequestBody<VariablesType> | GraphQLMultipartRequestBody | Record<string, any> | undefined;
40
41
  interface GraphQLJsonRequestBody<Variables extends GraphQLVariables> {
@@ -54,7 +55,7 @@ declare class GraphQLHandler extends RequestHandler<GraphQLHandlerInfo, ParsedGr
54
55
  }): Promise<ParsedGraphQLRequest<GraphQLVariables>>;
55
56
  predicate(args: {
56
57
  request: Request;
57
- parsedResult: ParsedGraphQLRequest;
58
+ parsedResult: ParsedGraphQLRequest<GraphQLVariables>;
58
59
  }): boolean;
59
60
  protected extendResolverArgs(args: {
60
61
  request: Request;
@@ -63,6 +64,7 @@ declare class GraphQLHandler extends RequestHandler<GraphQLHandlerInfo, ParsedGr
63
64
  query: string;
64
65
  operationName: string;
65
66
  variables: GraphQLVariables;
67
+ cookies: Record<string, string>;
66
68
  };
67
69
  log(args: {
68
70
  request: Request;
@@ -1,6 +1,6 @@
1
1
  import { DocumentNode } from 'graphql';
2
2
  import { a as ResponseResolver, c as RequestHandlerOptions } from './RequestHandler-bb5cbb8f.js';
3
- import { a as GraphQLVariables, d as GraphQLHandlerNameSelector, e as GraphQLResolverExtras, f as GraphQLResponseBody, G as GraphQLHandler } from './GraphQLHandler-d46c4f60.js';
3
+ import { a as GraphQLVariables, d as GraphQLHandlerNameSelector, e as GraphQLResolverExtras, f as GraphQLResponseBody, G as GraphQLHandler } from './GraphQLHandler-97ee3314.js';
4
4
  import { Path } from './utils/matching/matchRequestUrl.js';
5
5
  import './typeUtils.js';
6
6
 
@@ -1,5 +1,5 @@
1
1
  import 'graphql';
2
2
  import '../RequestHandler-bb5cbb8f.js';
3
3
  import '../utils/matching/matchRequestUrl.js';
4
- export { E as ExpectedOperationTypeNode, G as GraphQLHandler, k as GraphQLHandlerInfo, d as GraphQLHandlerNameSelector, c as GraphQLJsonRequestBody, b as GraphQLRequestBody, e as GraphQLResolverExtras, f as GraphQLResponseBody, a as GraphQLVariables, l as isDocumentNode } from '../GraphQLHandler-d46c4f60.js';
4
+ export { E as ExpectedOperationTypeNode, G as GraphQLHandler, k as GraphQLHandlerInfo, d as GraphQLHandlerNameSelector, c as GraphQLJsonRequestBody, b as GraphQLRequestBody, e as GraphQLResolverExtras, f as GraphQLResponseBody, a as GraphQLVariables, l as isDocumentNode } from '../GraphQLHandler-97ee3314.js';
5
5
  import '../typeUtils.js';
@@ -51,6 +51,7 @@ var import_matchRequestUrl = require("../utils/matching/matchRequestUrl.js");
51
51
  var import_parseGraphQLRequest = require("../utils/internal/parseGraphQLRequest.js");
52
52
  var import_getPublicUrlFromRequest = require("../utils/request/getPublicUrlFromRequest.js");
53
53
  var import_devUtils = require("../utils/internal/devUtils.js");
54
+ var import_getRequestCookies = require("../utils/request/getRequestCookies.js");
54
55
  function isDocumentNode(value) {
55
56
  if (value == null) {
56
57
  return false;
@@ -88,10 +89,21 @@ class GraphQLHandler extends import_RequestHandler.RequestHandler {
88
89
  }
89
90
  parse(args) {
90
91
  return __async(this, null, function* () {
91
- return (0, import_parseGraphQLRequest.parseGraphQLRequest)(args.request).catch((error) => {
92
- console.error(error);
92
+ const parsedResult = yield (0, import_parseGraphQLRequest.parseGraphQLRequest)(args.request).catch(
93
+ (error) => {
94
+ console.error(error);
95
+ return void 0;
96
+ }
97
+ );
98
+ if (typeof parsedResult === "undefined") {
93
99
  return void 0;
94
- });
100
+ }
101
+ return {
102
+ query: parsedResult.query,
103
+ operationType: parsedResult.operationType,
104
+ operationName: parsedResult.operationName,
105
+ variables: parsedResult.variables
106
+ };
95
107
  });
96
108
  }
97
109
  predicate(args) {
@@ -102,7 +114,7 @@ class GraphQLHandler extends import_RequestHandler.RequestHandler {
102
114
  const publicUrl = (0, import_getPublicUrlFromRequest.getPublicUrlFromRequest)(args.request);
103
115
  import_devUtils.devUtils.warn(`Failed to intercept a GraphQL request at "${args.request.method} ${publicUrl}": anonymous GraphQL operations are not supported.
104
116
 
105
- 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`);
117
+ 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/#graphqloperationresolver`);
106
118
  return false;
107
119
  }
108
120
  const hasMatchingUrl = (0, import_matchRequestUrl.matchRequestUrl)(
@@ -115,10 +127,12 @@ Consider naming this operation or using "graphql.operation()" request handler to
115
127
  }
116
128
  extendResolverArgs(args) {
117
129
  var _a, _b, _c;
130
+ const cookies = (0, import_getRequestCookies.getAllRequestCookies)(args.request);
118
131
  return {
119
132
  query: ((_a = args.parsedResult) == null ? void 0 : _a.query) || "",
120
133
  operationName: ((_b = args.parsedResult) == null ? void 0 : _b.operationName) || "",
121
- variables: ((_c = args.parsedResult) == null ? void 0 : _c.variables) || {}
134
+ variables: ((_c = args.parsedResult) == null ? void 0 : _c.variables) || {},
135
+ cookies
122
136
  };
123
137
  }
124
138
  log(args) {
@@ -32,6 +32,7 @@ import {
32
32
  } from '../utils/internal/parseGraphQLRequest.mjs';
33
33
  import { getPublicUrlFromRequest } from '../utils/request/getPublicUrlFromRequest.mjs';
34
34
  import { devUtils } from '../utils/internal/devUtils.mjs';
35
+ import { getAllRequestCookies } from '../utils/request/getRequestCookies.mjs';
35
36
  function isDocumentNode(value) {
36
37
  if (value == null) {
37
38
  return false;
@@ -69,10 +70,21 @@ class GraphQLHandler extends RequestHandler {
69
70
  }
70
71
  parse(args) {
71
72
  return __async(this, null, function* () {
72
- return parseGraphQLRequest(args.request).catch((error) => {
73
- console.error(error);
73
+ const parsedResult = yield parseGraphQLRequest(args.request).catch(
74
+ (error) => {
75
+ console.error(error);
76
+ return void 0;
77
+ }
78
+ );
79
+ if (typeof parsedResult === "undefined") {
74
80
  return void 0;
75
- });
81
+ }
82
+ return {
83
+ query: parsedResult.query,
84
+ operationType: parsedResult.operationType,
85
+ operationName: parsedResult.operationName,
86
+ variables: parsedResult.variables
87
+ };
76
88
  });
77
89
  }
78
90
  predicate(args) {
@@ -83,7 +95,7 @@ class GraphQLHandler extends RequestHandler {
83
95
  const publicUrl = getPublicUrlFromRequest(args.request);
84
96
  devUtils.warn(`Failed to intercept a GraphQL request at "${args.request.method} ${publicUrl}": anonymous GraphQL operations are not supported.
85
97
 
86
- 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`);
98
+ 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/#graphqloperationresolver`);
87
99
  return false;
88
100
  }
89
101
  const hasMatchingUrl = matchRequestUrl(
@@ -96,10 +108,12 @@ Consider naming this operation or using "graphql.operation()" request handler to
96
108
  }
97
109
  extendResolverArgs(args) {
98
110
  var _a, _b, _c;
111
+ const cookies = getAllRequestCookies(args.request);
99
112
  return {
100
113
  query: ((_a = args.parsedResult) == null ? void 0 : _a.query) || "",
101
114
  operationName: ((_b = args.parsedResult) == null ? void 0 : _b.operationName) || "",
102
- variables: ((_c = args.parsedResult) == null ? void 0 : _c.variables) || {}
115
+ variables: ((_c = args.parsedResult) == null ? void 0 : _c.variables) || {},
116
+ cookies
103
117
  };
104
118
  }
105
119
  log(args) {
@@ -25,7 +25,7 @@ type HttpRequestParsedResult = {
25
25
  };
26
26
  type HttpRequestResolverExtras<Params extends PathParams> = {
27
27
  params: Params;
28
- cookies: Record<string, string | Array<string>>;
28
+ cookies: Record<string, string>;
29
29
  };
30
30
  /**
31
31
  * Request handler for HTTP requests.
@@ -3,7 +3,7 @@ export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as Defaul
3
3
  export { http } from './http.js';
4
4
  export { HttpHandler, HttpMethods, HttpRequestParsedResult, RequestQuery } from './handlers/HttpHandler.js';
5
5
  export { graphql } from './graphql.js';
6
- export { G as GraphQLHandler, c as GraphQLJsonRequestBody, b as GraphQLRequestBody, a as GraphQLVariables, P as ParsedGraphQLRequest } from './GraphQLHandler-d46c4f60.js';
6
+ export { G as GraphQLHandler, c as GraphQLJsonRequestBody, b as GraphQLRequestBody, a as GraphQLVariables, P as ParsedGraphQLRequest } from './GraphQLHandler-97ee3314.js';
7
7
  export { Match, Path, PathParams, matchRequestUrl } from './utils/matching/matchRequestUrl.js';
8
8
  export { HandleRequestOptions, handleRequest } from './utils/handleRequest.js';
9
9
  export { cleanUrl } from './utils/url/cleanUrl.js';
@@ -1,5 +1,5 @@
1
1
  import 'graphql';
2
- export { i as GraphQLMultipartRequestBody, h as GraphQLParsedOperationsMap, g as ParsedGraphQLQuery, P as ParsedGraphQLRequest, p as parseDocumentNode, j as parseGraphQLRequest } from '../../GraphQLHandler-d46c4f60.js';
2
+ export { i as GraphQLMultipartRequestBody, h as GraphQLParsedOperationsMap, g as ParsedGraphQLQuery, P as ParsedGraphQLRequest, p as parseDocumentNode, j as parseGraphQLRequest } from '../../GraphQLHandler-97ee3314.js';
3
3
  import '../../RequestHandler-bb5cbb8f.js';
4
4
  import '../../typeUtils.js';
5
5
  import '../matching/matchRequestUrl.js';
@@ -73,16 +73,13 @@ function getAllRequestCookies(request) {
73
73
  const requestCookiesString = request.headers.get("cookie");
74
74
  const cookiesFromHeaders = requestCookiesString ? import_cookie.default.parse(requestCookiesString) : {};
75
75
  import_cookies.store.hydrate();
76
- const cookiesFromStore = Array.from((_a = import_cookies.store.get(request)) == null ? void 0 : _a.entries()).reduce(
77
- (cookies, [name, { value }]) => {
78
- return Object.assign(cookies, { [name.trim()]: value });
79
- },
80
- {}
81
- );
76
+ const cookiesFromStore = Array.from((_a = import_cookies.store.get(request)) == null ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => {
77
+ return Object.assign(cookies, { [name.trim()]: value });
78
+ }, {});
82
79
  const cookiesFromDocument = getRequestCookies(request);
83
80
  const forwardedCookies = __spreadValues(__spreadValues({}, cookiesFromDocument), cookiesFromStore);
84
81
  for (const [name, value] of Object.entries(forwardedCookies)) {
85
- request.headers.append("cookie", `${name}=${value}`);
82
+ request.headers.append("cookie", import_cookie.default.serialize(name, value));
86
83
  }
87
84
  return __spreadValues(__spreadValues({}, forwardedCookies), cookiesFromHeaders);
88
85
  }
@@ -41,16 +41,13 @@ function getAllRequestCookies(request) {
41
41
  const requestCookiesString = request.headers.get("cookie");
42
42
  const cookiesFromHeaders = requestCookiesString ? cookieUtils.parse(requestCookiesString) : {};
43
43
  store.hydrate();
44
- const cookiesFromStore = Array.from((_a = store.get(request)) == null ? void 0 : _a.entries()).reduce(
45
- (cookies, [name, { value }]) => {
46
- return Object.assign(cookies, { [name.trim()]: value });
47
- },
48
- {}
49
- );
44
+ const cookiesFromStore = Array.from((_a = store.get(request)) == null ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => {
45
+ return Object.assign(cookies, { [name.trim()]: value });
46
+ }, {});
50
47
  const cookiesFromDocument = getRequestCookies(request);
51
48
  const forwardedCookies = __spreadValues(__spreadValues({}, cookiesFromDocument), cookiesFromStore);
52
49
  for (const [name, value] of Object.entries(forwardedCookies)) {
53
- request.headers.append("cookie", `${name}=${value}`);
50
+ request.headers.append("cookie", cookieUtils.serialize(name, value));
54
51
  }
55
52
  return __spreadValues(__spreadValues({}, forwardedCookies), cookiesFromHeaders);
56
53
  }
package/lib/iife/index.js CHANGED
@@ -2402,16 +2402,13 @@ Invalid value has been removed from localStorage to prevent subsequent failed pa
2402
2402
  const requestCookiesString = request.headers.get("cookie");
2403
2403
  const cookiesFromHeaders = requestCookiesString ? source_default2.parse(requestCookiesString) : {};
2404
2404
  store.hydrate();
2405
- const cookiesFromStore = Array.from((_a3 = store.get(request)) == null ? void 0 : _a3.entries()).reduce(
2406
- (cookies, [name, { value }]) => {
2407
- return Object.assign(cookies, { [name.trim()]: value });
2408
- },
2409
- {}
2410
- );
2405
+ const cookiesFromStore = Array.from((_a3 = store.get(request)) == null ? void 0 : _a3.entries()).reduce((cookies, [name, { value }]) => {
2406
+ return Object.assign(cookies, { [name.trim()]: value });
2407
+ }, {});
2411
2408
  const cookiesFromDocument = getRequestCookies(request);
2412
2409
  const forwardedCookies = __spreadValues(__spreadValues({}, cookiesFromDocument), cookiesFromStore);
2413
2410
  for (const [name, value] of Object.entries(forwardedCookies)) {
2414
- request.headers.append("cookie", `${name}=${value}`);
2411
+ request.headers.append("cookie", source_default2.serialize(name, value));
2415
2412
  }
2416
2413
  return __spreadValues(__spreadValues({}, forwardedCookies), cookiesFromHeaders);
2417
2414
  }
@@ -5639,10 +5636,21 @@ spurious results.`);
5639
5636
  }
5640
5637
  parse(args) {
5641
5638
  return __async(this, null, function* () {
5642
- return parseGraphQLRequest(args.request).catch((error3) => {
5643
- console.error(error3);
5639
+ const parsedResult = yield parseGraphQLRequest(args.request).catch(
5640
+ (error3) => {
5641
+ console.error(error3);
5642
+ return void 0;
5643
+ }
5644
+ );
5645
+ if (typeof parsedResult === "undefined") {
5644
5646
  return void 0;
5645
- });
5647
+ }
5648
+ return {
5649
+ query: parsedResult.query,
5650
+ operationType: parsedResult.operationType,
5651
+ operationName: parsedResult.operationName,
5652
+ variables: parsedResult.variables
5653
+ };
5646
5654
  });
5647
5655
  }
5648
5656
  predicate(args) {
@@ -5653,7 +5661,7 @@ spurious results.`);
5653
5661
  const publicUrl = getPublicUrlFromRequest(args.request);
5654
5662
  devUtils.warn(`Failed to intercept a GraphQL request at "${args.request.method} ${publicUrl}": anonymous GraphQL operations are not supported.
5655
5663
 
5656
- 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`);
5664
+ 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/#graphqloperationresolver`);
5657
5665
  return false;
5658
5666
  }
5659
5667
  const hasMatchingUrl = matchRequestUrl(
@@ -5666,10 +5674,12 @@ Consider naming this operation or using "graphql.operation()" request handler to
5666
5674
  }
5667
5675
  extendResolverArgs(args) {
5668
5676
  var _a3, _b2, _c;
5677
+ const cookies = getAllRequestCookies(args.request);
5669
5678
  return {
5670
5679
  query: ((_a3 = args.parsedResult) == null ? void 0 : _a3.query) || "",
5671
5680
  operationName: ((_b2 = args.parsedResult) == null ? void 0 : _b2.operationName) || "",
5672
- variables: ((_c = args.parsedResult) == null ? void 0 : _c.variables) || {}
5681
+ variables: ((_c = args.parsedResult) == null ? void 0 : _c.variables) || {},
5682
+ cookies
5673
5683
  };
5674
5684
  }
5675
5685
  log(args) {
@@ -2,7 +2,7 @@
2
2
  /* tslint:disable */
3
3
 
4
4
  /**
5
- * Mock Service Worker (2.0.5).
5
+ * Mock Service Worker (2.0.7).
6
6
  * @see https://github.com/mswjs/msw
7
7
  * - Please do NOT modify this file.
8
8
  * - Please do NOT serve this file on production.
@@ -51,17 +51,29 @@ interface SetupServer {
51
51
  }
52
52
 
53
53
  declare class SetupServerApi extends SetupApi<LifeCycleEventsMap> implements SetupServer {
54
+ private context;
54
55
  protected readonly interceptor: BatchInterceptor<Array<Interceptor<HttpRequestEventMap>>, HttpRequestEventMap>;
55
56
  private resolvedOptions;
56
57
  constructor(interceptors: Array<{
57
58
  new (): Interceptor<HttpRequestEventMap>;
58
59
  }>, ...handlers: Array<RequestHandler>);
60
+ private createContext;
59
61
  /**
60
62
  * Subscribe to all requests that are using the interceptor object
61
63
  */
62
64
  private init;
63
65
  listen(options?: Partial<SharedOptions>): void;
64
66
  close(): void;
67
+ /**
68
+ * Bump the maximum number of event listeners on the
69
+ * request's "AbortSignal". This prepares the request
70
+ * for each request handler cloning it at least once.
71
+ * Note that cloning a request automatically appends a
72
+ * new "abort" event listener to the parent request's
73
+ * "AbortController" so if the parent aborts, all the
74
+ * clones are automatically aborted.
75
+ */
76
+ private setRequestAbortSignalMaxListeners;
65
77
  }
66
78
 
67
79
  /**
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
  var __async = (__this, __arguments, generator) => {
20
30
  return new Promise((resolve, reject) => {
@@ -46,7 +56,6 @@ module.exports = __toCommonJS(native_exports);
46
56
  var import_XMLHttpRequest = require("@mswjs/interceptors/XMLHttpRequest");
47
57
 
48
58
  // src/node/SetupServerApi.ts
49
- var import_node_events = require("events");
50
59
  var import_outvariant = require("outvariant");
51
60
  var import_interceptors = require("@mswjs/interceptors");
52
61
  var import_SetupApi = require("../core/SetupApi.js");
@@ -66,6 +75,7 @@ var DEFAULT_LISTEN_OPTIONS = {
66
75
  var SetupServerApi = class extends import_SetupApi.SetupApi {
67
76
  constructor(interceptors, ...handlers) {
68
77
  super(...handlers);
78
+ this.context = this.createContext();
69
79
  this.interceptor = new import_interceptors.BatchInterceptor({
70
80
  name: "setup-server",
71
81
  interceptors: interceptors.map((Interceptor2) => new Interceptor2())
@@ -73,23 +83,19 @@ var SetupServerApi = class extends import_SetupApi.SetupApi {
73
83
  this.resolvedOptions = {};
74
84
  this.init();
75
85
  }
86
+ createContext() {
87
+ return {
88
+ get nodeEvents() {
89
+ return import("events").then((events) => events).catch(() => void 0);
90
+ }
91
+ };
92
+ }
76
93
  /**
77
94
  * Subscribe to all requests that are using the interceptor object
78
95
  */
79
96
  init() {
80
97
  this.interceptor.on("request", (_0) => __async(this, [_0], function* ({ request, requestId }) {
81
- if (typeof import_node_events.setMaxListeners === "function") {
82
- try {
83
- (0, import_node_events.setMaxListeners)(
84
- Math.max(import_node_events.defaultMaxListeners, this.currentHandlers.length),
85
- request.signal
86
- );
87
- } catch (error) {
88
- if (!(isNodeExceptionLike(error) && error.code === "ERR_INVALID_ARG_TYPE")) {
89
- throw error;
90
- }
91
- }
92
- }
98
+ yield this.setRequestAbortSignalMaxListeners(request);
93
99
  const response = yield (0, import_handleRequest.handleRequest)(
94
100
  request,
95
101
  requestId,
@@ -138,6 +144,37 @@ var SetupServerApi = class extends import_SetupApi.SetupApi {
138
144
  close() {
139
145
  this.dispose();
140
146
  }
147
+ /**
148
+ * Bump the maximum number of event listeners on the
149
+ * request's "AbortSignal". This prepares the request
150
+ * for each request handler cloning it at least once.
151
+ * Note that cloning a request automatically appends a
152
+ * new "abort" event listener to the parent request's
153
+ * "AbortController" so if the parent aborts, all the
154
+ * clones are automatically aborted.
155
+ */
156
+ setRequestAbortSignalMaxListeners(request) {
157
+ return __async(this, null, function* () {
158
+ const events = yield this.context.nodeEvents;
159
+ if (typeof events === "undefined") {
160
+ return;
161
+ }
162
+ const { setMaxListeners, defaultMaxListeners } = events;
163
+ if (typeof setMaxListeners !== "function") {
164
+ return;
165
+ }
166
+ try {
167
+ setMaxListeners(
168
+ Math.max(defaultMaxListeners, this.currentHandlers.length),
169
+ request.signal
170
+ );
171
+ } catch (error) {
172
+ if (!(isNodeExceptionLike(error) && error.code === "ERR_INVALID_ARG_TYPE")) {
173
+ throw error;
174
+ }
175
+ }
176
+ });
177
+ }
141
178
  };
142
179
 
143
180
  // src/native/index.ts
@@ -23,7 +23,6 @@ var __async = (__this, __arguments, generator) => {
23
23
  import { XMLHttpRequestInterceptor } from "@mswjs/interceptors/XMLHttpRequest";
24
24
 
25
25
  // src/node/SetupServerApi.ts
26
- import { setMaxListeners, defaultMaxListeners } from "events";
27
26
  import { invariant } from "outvariant";
28
27
  import {
29
28
  BatchInterceptor,
@@ -46,6 +45,7 @@ var DEFAULT_LISTEN_OPTIONS = {
46
45
  var SetupServerApi = class extends SetupApi {
47
46
  constructor(interceptors, ...handlers) {
48
47
  super(...handlers);
48
+ this.context = this.createContext();
49
49
  this.interceptor = new BatchInterceptor({
50
50
  name: "setup-server",
51
51
  interceptors: interceptors.map((Interceptor2) => new Interceptor2())
@@ -53,23 +53,19 @@ var SetupServerApi = class extends SetupApi {
53
53
  this.resolvedOptions = {};
54
54
  this.init();
55
55
  }
56
+ createContext() {
57
+ return {
58
+ get nodeEvents() {
59
+ return import("events").then((events) => events).catch(() => void 0);
60
+ }
61
+ };
62
+ }
56
63
  /**
57
64
  * Subscribe to all requests that are using the interceptor object
58
65
  */
59
66
  init() {
60
67
  this.interceptor.on("request", (_0) => __async(this, [_0], function* ({ request, requestId }) {
61
- if (typeof setMaxListeners === "function") {
62
- try {
63
- setMaxListeners(
64
- Math.max(defaultMaxListeners, this.currentHandlers.length),
65
- request.signal
66
- );
67
- } catch (error) {
68
- if (!(isNodeExceptionLike(error) && error.code === "ERR_INVALID_ARG_TYPE")) {
69
- throw error;
70
- }
71
- }
72
- }
68
+ yield this.setRequestAbortSignalMaxListeners(request);
73
69
  const response = yield handleRequest(
74
70
  request,
75
71
  requestId,
@@ -118,6 +114,37 @@ var SetupServerApi = class extends SetupApi {
118
114
  close() {
119
115
  this.dispose();
120
116
  }
117
+ /**
118
+ * Bump the maximum number of event listeners on the
119
+ * request's "AbortSignal". This prepares the request
120
+ * for each request handler cloning it at least once.
121
+ * Note that cloning a request automatically appends a
122
+ * new "abort" event listener to the parent request's
123
+ * "AbortController" so if the parent aborts, all the
124
+ * clones are automatically aborted.
125
+ */
126
+ setRequestAbortSignalMaxListeners(request) {
127
+ return __async(this, null, function* () {
128
+ const events = yield this.context.nodeEvents;
129
+ if (typeof events === "undefined") {
130
+ return;
131
+ }
132
+ const { setMaxListeners, defaultMaxListeners } = events;
133
+ if (typeof setMaxListeners !== "function") {
134
+ return;
135
+ }
136
+ try {
137
+ setMaxListeners(
138
+ Math.max(defaultMaxListeners, this.currentHandlers.length),
139
+ request.signal
140
+ );
141
+ } catch (error) {
142
+ if (!(isNodeExceptionLike(error) && error.code === "ERR_INVALID_ARG_TYPE")) {
143
+ throw error;
144
+ }
145
+ }
146
+ });
147
+ }
121
148
  };
122
149
 
123
150
  // src/native/index.ts
@@ -51,17 +51,29 @@ interface SetupServer {
51
51
  }
52
52
 
53
53
  declare class SetupServerApi extends SetupApi<LifeCycleEventsMap> implements SetupServer {
54
+ private context;
54
55
  protected readonly interceptor: BatchInterceptor<Array<Interceptor<HttpRequestEventMap>>, HttpRequestEventMap>;
55
56
  private resolvedOptions;
56
57
  constructor(interceptors: Array<{
57
58
  new (): Interceptor<HttpRequestEventMap>;
58
59
  }>, ...handlers: Array<RequestHandler>);
60
+ private createContext;
59
61
  /**
60
62
  * Subscribe to all requests that are using the interceptor object
61
63
  */
62
64
  private init;
63
65
  listen(options?: Partial<SharedOptions>): void;
64
66
  close(): void;
67
+ /**
68
+ * Bump the maximum number of event listeners on the
69
+ * request's "AbortSignal". This prepares the request
70
+ * for each request handler cloning it at least once.
71
+ * Note that cloning a request automatically appends a
72
+ * new "abort" event listener to the parent request's
73
+ * "AbortController" so if the parent aborts, all the
74
+ * clones are automatically aborted.
75
+ */
76
+ private setRequestAbortSignalMaxListeners;
65
77
  }
66
78
 
67
79
  /**
package/lib/node/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
  var __async = (__this, __arguments, generator) => {
20
30
  return new Promise((resolve, reject) => {
@@ -46,7 +56,6 @@ __export(node_exports, {
46
56
  module.exports = __toCommonJS(node_exports);
47
57
 
48
58
  // src/node/SetupServerApi.ts
49
- var import_node_events = require("events");
50
59
  var import_outvariant = require("outvariant");
51
60
  var import_interceptors = require("@mswjs/interceptors");
52
61
  var import_SetupApi = require("../core/SetupApi.js");
@@ -66,6 +75,7 @@ var DEFAULT_LISTEN_OPTIONS = {
66
75
  var SetupServerApi = class extends import_SetupApi.SetupApi {
67
76
  constructor(interceptors, ...handlers) {
68
77
  super(...handlers);
78
+ this.context = this.createContext();
69
79
  this.interceptor = new import_interceptors.BatchInterceptor({
70
80
  name: "setup-server",
71
81
  interceptors: interceptors.map((Interceptor2) => new Interceptor2())
@@ -73,23 +83,19 @@ var SetupServerApi = class extends import_SetupApi.SetupApi {
73
83
  this.resolvedOptions = {};
74
84
  this.init();
75
85
  }
86
+ createContext() {
87
+ return {
88
+ get nodeEvents() {
89
+ return import("events").then((events) => events).catch(() => void 0);
90
+ }
91
+ };
92
+ }
76
93
  /**
77
94
  * Subscribe to all requests that are using the interceptor object
78
95
  */
79
96
  init() {
80
97
  this.interceptor.on("request", (_0) => __async(this, [_0], function* ({ request, requestId }) {
81
- if (typeof import_node_events.setMaxListeners === "function") {
82
- try {
83
- (0, import_node_events.setMaxListeners)(
84
- Math.max(import_node_events.defaultMaxListeners, this.currentHandlers.length),
85
- request.signal
86
- );
87
- } catch (error) {
88
- if (!(isNodeExceptionLike(error) && error.code === "ERR_INVALID_ARG_TYPE")) {
89
- throw error;
90
- }
91
- }
92
- }
98
+ yield this.setRequestAbortSignalMaxListeners(request);
93
99
  const response = yield (0, import_handleRequest.handleRequest)(
94
100
  request,
95
101
  requestId,
@@ -138,6 +144,37 @@ var SetupServerApi = class extends import_SetupApi.SetupApi {
138
144
  close() {
139
145
  this.dispose();
140
146
  }
147
+ /**
148
+ * Bump the maximum number of event listeners on the
149
+ * request's "AbortSignal". This prepares the request
150
+ * for each request handler cloning it at least once.
151
+ * Note that cloning a request automatically appends a
152
+ * new "abort" event listener to the parent request's
153
+ * "AbortController" so if the parent aborts, all the
154
+ * clones are automatically aborted.
155
+ */
156
+ setRequestAbortSignalMaxListeners(request) {
157
+ return __async(this, null, function* () {
158
+ const events = yield this.context.nodeEvents;
159
+ if (typeof events === "undefined") {
160
+ return;
161
+ }
162
+ const { setMaxListeners, defaultMaxListeners } = events;
163
+ if (typeof setMaxListeners !== "function") {
164
+ return;
165
+ }
166
+ try {
167
+ setMaxListeners(
168
+ Math.max(defaultMaxListeners, this.currentHandlers.length),
169
+ request.signal
170
+ );
171
+ } catch (error) {
172
+ if (!(isNodeExceptionLike(error) && error.code === "ERR_INVALID_ARG_TYPE")) {
173
+ throw error;
174
+ }
175
+ }
176
+ });
177
+ }
141
178
  };
142
179
 
143
180
  // src/node/setupServer.ts
@@ -20,7 +20,6 @@ var __async = (__this, __arguments, generator) => {
20
20
  };
21
21
 
22
22
  // src/node/SetupServerApi.ts
23
- import { setMaxListeners, defaultMaxListeners } from "events";
24
23
  import { invariant } from "outvariant";
25
24
  import {
26
25
  BatchInterceptor,
@@ -43,6 +42,7 @@ var DEFAULT_LISTEN_OPTIONS = {
43
42
  var SetupServerApi = class extends SetupApi {
44
43
  constructor(interceptors, ...handlers) {
45
44
  super(...handlers);
45
+ this.context = this.createContext();
46
46
  this.interceptor = new BatchInterceptor({
47
47
  name: "setup-server",
48
48
  interceptors: interceptors.map((Interceptor2) => new Interceptor2())
@@ -50,23 +50,19 @@ var SetupServerApi = class extends SetupApi {
50
50
  this.resolvedOptions = {};
51
51
  this.init();
52
52
  }
53
+ createContext() {
54
+ return {
55
+ get nodeEvents() {
56
+ return import("events").then((events) => events).catch(() => void 0);
57
+ }
58
+ };
59
+ }
53
60
  /**
54
61
  * Subscribe to all requests that are using the interceptor object
55
62
  */
56
63
  init() {
57
64
  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 (!(isNodeExceptionLike(error) && error.code === "ERR_INVALID_ARG_TYPE")) {
66
- throw error;
67
- }
68
- }
69
- }
65
+ yield this.setRequestAbortSignalMaxListeners(request);
70
66
  const response = yield handleRequest(
71
67
  request,
72
68
  requestId,
@@ -115,6 +111,37 @@ var SetupServerApi = class extends SetupApi {
115
111
  close() {
116
112
  this.dispose();
117
113
  }
114
+ /**
115
+ * Bump the maximum number of event listeners on the
116
+ * request's "AbortSignal". This prepares the request
117
+ * for each request handler cloning it at least once.
118
+ * Note that cloning a request automatically appends a
119
+ * new "abort" event listener to the parent request's
120
+ * "AbortController" so if the parent aborts, all the
121
+ * clones are automatically aborted.
122
+ */
123
+ setRequestAbortSignalMaxListeners(request) {
124
+ return __async(this, null, function* () {
125
+ const events = yield this.context.nodeEvents;
126
+ if (typeof events === "undefined") {
127
+ return;
128
+ }
129
+ const { setMaxListeners, defaultMaxListeners } = events;
130
+ if (typeof setMaxListeners !== "function") {
131
+ return;
132
+ }
133
+ try {
134
+ setMaxListeners(
135
+ Math.max(defaultMaxListeners, this.currentHandlers.length),
136
+ request.signal
137
+ );
138
+ } catch (error) {
139
+ if (!(isNodeExceptionLike(error) && error.code === "ERR_INVALID_ARG_TYPE")) {
140
+ throw error;
141
+ }
142
+ }
143
+ });
144
+ }
118
145
  };
119
146
 
120
147
  // src/node/setupServer.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "msw",
3
- "version": "2.0.5",
3
+ "version": "2.0.7",
4
4
  "description": "Seamless REST/GraphQL API mocking library for browser and Node.js.",
5
5
  "main": "./lib/core/index.js",
6
6
  "module": "./lib/core/index.mjs",
@@ -132,6 +132,7 @@
132
132
  "@typescript-eslint/eslint-plugin": "^5.11.0",
133
133
  "@typescript-eslint/parser": "^5.11.0",
134
134
  "@web/dev-server": "^0.1.38",
135
+ "axios": "^1.6.1",
135
136
  "babel-loader": "^8.2.3",
136
137
  "babel-minify": "^0.5.1",
137
138
  "commitizen": "^4.2.4",