msw 2.6.3 → 2.6.5

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.
@@ -8,8 +8,8 @@
8
8
  * - Please do NOT serve this file on production.
9
9
  */
10
10
 
11
- const PACKAGE_VERSION = '2.6.3'
12
- const INTEGRITY_CHECKSUM = '07a8241b182f8a246a7cd39894799a9e'
11
+ const PACKAGE_VERSION = '2.6.5'
12
+ const INTEGRITY_CHECKSUM = 'ca7800994cc8bfb5eb961e037c877074'
13
13
  const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
14
14
  const activeClientIds = new Set()
15
15
 
@@ -192,12 +192,14 @@ async function getResponse(event, client, requestId) {
192
192
  const requestClone = request.clone()
193
193
 
194
194
  function passthrough() {
195
- const headers = Object.fromEntries(requestClone.headers.entries())
196
-
197
- // Remove internal MSW request header so the passthrough request
198
- // complies with any potential CORS preflight checks on the server.
199
- // Some servers forbid unknown request headers.
200
- delete headers['x-msw-intention']
195
+ // Cast the request headers to a new Headers instance
196
+ // so the headers can be manipulated with.
197
+ const headers = new Headers(requestClone.headers)
198
+
199
+ // Remove the "accept" header value that marked this request as passthrough.
200
+ // This prevents request alteration and also keeps it compliant with the
201
+ // user-defined CORS policies.
202
+ headers.delete('accept', 'msw/passthrough')
201
203
 
202
204
  return fetch(requestClone, { headers })
203
205
  }
@@ -63,7 +63,23 @@ var SetupServerCommonApi = class extends import_SetupApi.SetupApi {
63
63
  requestId,
64
64
  this.handlersController.currentHandlers().filter((0, import_isHandlerKind.isHandlerKind)("RequestHandler")),
65
65
  this.resolvedOptions,
66
- this.emitter
66
+ this.emitter,
67
+ {
68
+ onPassthroughResponse(request2) {
69
+ const acceptHeader = request2.headers.get("accept");
70
+ if (acceptHeader) {
71
+ const nextAcceptHeader = acceptHeader.replace(
72
+ /(,\s+)?msw\/passthrough/,
73
+ ""
74
+ );
75
+ if (nextAcceptHeader) {
76
+ request2.headers.set("accept", nextAcceptHeader);
77
+ } else {
78
+ request2.headers.delete("accept");
79
+ }
80
+ }
81
+ }
82
+ }
67
83
  );
68
84
  if (response) {
69
85
  controller.respondWith(response);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/native/index.ts","../../src/node/SetupServerCommonApi.ts"],"sourcesContent":["import { FetchInterceptor } from '@mswjs/interceptors/fetch'\nimport { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport { SetupServerCommonApi } from '../node/SetupServerCommonApi'\n\n/**\n * Sets up a requests interception in React Native with the given request handlers.\n * @param {RequestHandler[]} handlers List of request handlers.\n *\n * @see {@link https://mswjs.io/docs/api/setup-server `setupServer()` API reference}\n */\nexport function setupServer(\n ...handlers: Array<RequestHandler>\n): SetupServerCommonApi {\n // Provision request interception via patching the `XMLHttpRequest` class only\n // in React Native. There is no `http`/`https` modules in that environment.\n return new SetupServerCommonApi(\n [FetchInterceptor, XMLHttpRequestInterceptor],\n handlers,\n )\n}\n","/**\n * @note This API is extended by both \"msw/node\" and \"msw/native\"\n * so be minding about the things you import!\n */\nimport type { RequiredDeep } from 'type-fest'\nimport { invariant } from 'outvariant'\nimport {\n BatchInterceptor,\n InterceptorReadyState,\n type HttpRequestEventMap,\n type Interceptor,\n} from '@mswjs/interceptors'\nimport type { LifeCycleEventsMap, SharedOptions } from '~/core/sharedOptions'\nimport { SetupApi } from '~/core/SetupApi'\nimport { handleRequest } from '~/core/utils/handleRequest'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport { mergeRight } from '~/core/utils/internal/mergeRight'\nimport { InternalError, devUtils } from '~/core/utils/internal/devUtils'\nimport type { SetupServerCommon } from './glossary'\nimport { handleWebSocketEvent } from '~/core/ws/handleWebSocketEvent'\nimport { webSocketInterceptor } from '~/core/ws/webSocketInterceptor'\nimport { isHandlerKind } from '~/core/utils/internal/isHandlerKind'\n\nexport const DEFAULT_LISTEN_OPTIONS: RequiredDeep<SharedOptions> = {\n onUnhandledRequest: 'warn',\n}\n\nexport class SetupServerCommonApi\n extends SetupApi<LifeCycleEventsMap>\n implements SetupServerCommon\n{\n protected readonly interceptor: BatchInterceptor<\n Array<Interceptor<HttpRequestEventMap>>,\n HttpRequestEventMap\n >\n private resolvedOptions: RequiredDeep<SharedOptions>\n\n constructor(\n interceptors: Array<{ new (): Interceptor<HttpRequestEventMap> }>,\n handlers: Array<RequestHandler | WebSocketHandler>,\n ) {\n super(...handlers)\n\n this.interceptor = new BatchInterceptor({\n name: 'setup-server',\n interceptors: interceptors.map((Interceptor) => new Interceptor()),\n })\n\n this.resolvedOptions = {} as RequiredDeep<SharedOptions>\n\n this.init()\n }\n\n /**\n * Subscribe to all requests that are using the interceptor object\n */\n private init(): void {\n this.interceptor.on(\n 'request',\n async ({ request, requestId, controller }) => {\n const response = await handleRequest(\n request,\n requestId,\n this.handlersController\n .currentHandlers()\n .filter(isHandlerKind('RequestHandler')),\n this.resolvedOptions,\n this.emitter,\n )\n\n if (response) {\n controller.respondWith(response)\n }\n\n return\n },\n )\n\n this.interceptor.on('unhandledException', ({ error }) => {\n if (error instanceof InternalError) {\n throw error\n }\n })\n\n this.interceptor.on(\n 'response',\n ({ response, isMockedResponse, request, requestId }) => {\n this.emitter.emit(\n isMockedResponse ? 'response:mocked' : 'response:bypass',\n {\n response,\n request,\n requestId,\n },\n )\n },\n )\n\n // Preconfigure the WebSocket interception but don't enable it just yet.\n // It will be enabled when the server starts.\n handleWebSocketEvent({\n getUnhandledRequestStrategy: () => {\n return this.resolvedOptions.onUnhandledRequest\n },\n getHandlers: () => {\n return this.handlersController.currentHandlers()\n },\n onMockedConnection: () => {},\n onPassthroughConnection: () => {},\n })\n }\n\n public listen(options: Partial<SharedOptions> = {}): void {\n this.resolvedOptions = mergeRight(\n DEFAULT_LISTEN_OPTIONS,\n options,\n ) as RequiredDeep<SharedOptions>\n\n // Apply the interceptor when starting the server.\n this.interceptor.apply()\n this.subscriptions.push(() => this.interceptor.dispose())\n\n // Apply the WebSocket interception.\n webSocketInterceptor.apply()\n this.subscriptions.push(() => webSocketInterceptor.dispose())\n\n // Assert that the interceptor has been applied successfully.\n // Also guards us from forgetting to call \"interceptor.apply()\"\n // as a part of the \"listen\" method.\n invariant(\n [InterceptorReadyState.APPLYING, InterceptorReadyState.APPLIED].includes(\n this.interceptor.readyState,\n ),\n devUtils.formatMessage(\n 'Failed to start \"setupServer\": the interceptor failed to apply. This is likely an issue with the library and you should report it at \"%s\".',\n ),\n 'https://github.com/mswjs/msw/issues/new/choose',\n )\n }\n\n public close(): void {\n this.dispose()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAiC;AACjC,4BAA0C;;;ACI1C,wBAA0B;AAC1B,0BAKO;AAEP,sBAAyB;AACzB,2BAA8B;AAG9B,wBAA2B;AAC3B,sBAAwC;AAExC,kCAAqC;AACrC,kCAAqC;AACrC,2BAA8B;AAEvB,IAAM,yBAAsD;AAAA,EACjE,oBAAoB;AACtB;AAEO,IAAM,uBAAN,cACG,yBAEV;AAAA,EACqB;AAAA,EAIX;AAAA,EAER,YACE,cACA,UACA;AACA,UAAM,GAAG,QAAQ;AAEjB,SAAK,cAAc,IAAI,qCAAiB;AAAA,MACtC,MAAM;AAAA,MACN,cAAc,aAAa,IAAI,CAAC,gBAAgB,IAAI,YAAY,CAAC;AAAA,IACnE,CAAC;AAED,SAAK,kBAAkB,CAAC;AAExB,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA,EAKQ,OAAa;AACnB,SAAK,YAAY;AAAA,MACf;AAAA,MACA,OAAO,EAAE,SAAS,WAAW,WAAW,MAAM;AAC5C,cAAM,WAAW,UAAM;AAAA,UACrB;AAAA,UACA;AAAA,UACA,KAAK,mBACF,gBAAgB,EAChB,WAAO,oCAAc,gBAAgB,CAAC;AAAA,UACzC,KAAK;AAAA,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,+BAAkB,+CAAyB;AAAA,IAC5C;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/native/index.ts","../../src/node/SetupServerCommonApi.ts"],"sourcesContent":["import { FetchInterceptor } from '@mswjs/interceptors/fetch'\nimport { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport { SetupServerCommonApi } from '../node/SetupServerCommonApi'\n\n/**\n * Sets up a requests interception in React Native with the given request handlers.\n * @param {RequestHandler[]} handlers List of request handlers.\n *\n * @see {@link https://mswjs.io/docs/api/setup-server `setupServer()` API reference}\n */\nexport function setupServer(\n ...handlers: Array<RequestHandler>\n): SetupServerCommonApi {\n // Provision request interception via patching the `XMLHttpRequest` class only\n // in React Native. There is no `http`/`https` modules in that environment.\n return new SetupServerCommonApi(\n [FetchInterceptor, XMLHttpRequestInterceptor],\n handlers,\n )\n}\n","/**\n * @note This API is extended by both \"msw/node\" and \"msw/native\"\n * so be minding about the things you import!\n */\nimport type { RequiredDeep } from 'type-fest'\nimport { invariant } from 'outvariant'\nimport {\n BatchInterceptor,\n InterceptorReadyState,\n type HttpRequestEventMap,\n type Interceptor,\n} from '@mswjs/interceptors'\nimport type { LifeCycleEventsMap, SharedOptions } from '~/core/sharedOptions'\nimport { SetupApi } from '~/core/SetupApi'\nimport { handleRequest } from '~/core/utils/handleRequest'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport { mergeRight } from '~/core/utils/internal/mergeRight'\nimport { InternalError, devUtils } from '~/core/utils/internal/devUtils'\nimport type { SetupServerCommon } from './glossary'\nimport { handleWebSocketEvent } from '~/core/ws/handleWebSocketEvent'\nimport { webSocketInterceptor } from '~/core/ws/webSocketInterceptor'\nimport { isHandlerKind } from '~/core/utils/internal/isHandlerKind'\n\nexport const DEFAULT_LISTEN_OPTIONS: RequiredDeep<SharedOptions> = {\n onUnhandledRequest: 'warn',\n}\n\nexport class SetupServerCommonApi\n extends SetupApi<LifeCycleEventsMap>\n implements SetupServerCommon\n{\n protected readonly interceptor: BatchInterceptor<\n Array<Interceptor<HttpRequestEventMap>>,\n HttpRequestEventMap\n >\n private resolvedOptions: RequiredDeep<SharedOptions>\n\n constructor(\n interceptors: Array<{ new (): Interceptor<HttpRequestEventMap> }>,\n handlers: Array<RequestHandler | WebSocketHandler>,\n ) {\n super(...handlers)\n\n this.interceptor = new BatchInterceptor({\n name: 'setup-server',\n interceptors: interceptors.map((Interceptor) => new Interceptor()),\n })\n\n this.resolvedOptions = {} as RequiredDeep<SharedOptions>\n\n this.init()\n }\n\n /**\n * Subscribe to all requests that are using the interceptor object\n */\n private init(): void {\n this.interceptor.on(\n 'request',\n async ({ request, requestId, controller }) => {\n const response = await handleRequest(\n request,\n requestId,\n this.handlersController\n .currentHandlers()\n .filter(isHandlerKind('RequestHandler')),\n this.resolvedOptions,\n this.emitter,\n {\n onPassthroughResponse(request) {\n const acceptHeader = request.headers.get('accept')\n\n /**\n * @note Remove the internal bypass request header.\n * In the browser, this is done by the worker script.\n * In Node.js, it has to be done here.\n */\n if (acceptHeader) {\n const nextAcceptHeader = acceptHeader.replace(\n /(,\\s+)?msw\\/passthrough/,\n '',\n )\n\n if (nextAcceptHeader) {\n request.headers.set('accept', nextAcceptHeader)\n } else {\n request.headers.delete('accept')\n }\n }\n },\n },\n )\n\n if (response) {\n controller.respondWith(response)\n }\n\n return\n },\n )\n\n this.interceptor.on('unhandledException', ({ error }) => {\n if (error instanceof InternalError) {\n throw error\n }\n })\n\n this.interceptor.on(\n 'response',\n ({ response, isMockedResponse, request, requestId }) => {\n this.emitter.emit(\n isMockedResponse ? 'response:mocked' : 'response:bypass',\n {\n response,\n request,\n requestId,\n },\n )\n },\n )\n\n // Preconfigure the WebSocket interception but don't enable it just yet.\n // It will be enabled when the server starts.\n handleWebSocketEvent({\n getUnhandledRequestStrategy: () => {\n return this.resolvedOptions.onUnhandledRequest\n },\n getHandlers: () => {\n return this.handlersController.currentHandlers()\n },\n onMockedConnection: () => {},\n onPassthroughConnection: () => {},\n })\n }\n\n public listen(options: Partial<SharedOptions> = {}): void {\n this.resolvedOptions = mergeRight(\n DEFAULT_LISTEN_OPTIONS,\n options,\n ) as RequiredDeep<SharedOptions>\n\n // Apply the interceptor when starting the server.\n this.interceptor.apply()\n this.subscriptions.push(() => this.interceptor.dispose())\n\n // Apply the WebSocket interception.\n webSocketInterceptor.apply()\n this.subscriptions.push(() => webSocketInterceptor.dispose())\n\n // Assert that the interceptor has been applied successfully.\n // Also guards us from forgetting to call \"interceptor.apply()\"\n // as a part of the \"listen\" method.\n invariant(\n [InterceptorReadyState.APPLYING, InterceptorReadyState.APPLIED].includes(\n this.interceptor.readyState,\n ),\n devUtils.formatMessage(\n 'Failed to start \"setupServer\": the interceptor failed to apply. This is likely an issue with the library and you should report it at \"%s\".',\n ),\n 'https://github.com/mswjs/msw/issues/new/choose',\n )\n }\n\n public close(): void {\n this.dispose()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAiC;AACjC,4BAA0C;;;ACI1C,wBAA0B;AAC1B,0BAKO;AAEP,sBAAyB;AACzB,2BAA8B;AAG9B,wBAA2B;AAC3B,sBAAwC;AAExC,kCAAqC;AACrC,kCAAqC;AACrC,2BAA8B;AAEvB,IAAM,yBAAsD;AAAA,EACjE,oBAAoB;AACtB;AAEO,IAAM,uBAAN,cACG,yBAEV;AAAA,EACqB;AAAA,EAIX;AAAA,EAER,YACE,cACA,UACA;AACA,UAAM,GAAG,QAAQ;AAEjB,SAAK,cAAc,IAAI,qCAAiB;AAAA,MACtC,MAAM;AAAA,MACN,cAAc,aAAa,IAAI,CAAC,gBAAgB,IAAI,YAAY,CAAC;AAAA,IACnE,CAAC;AAED,SAAK,kBAAkB,CAAC;AAExB,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA,E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AAM;AAAA,MAAC;AAAA,IAClC,CAAC;AAAA,EACH;AAAA,EAEO,OAAO,UAAkC,CAAC,GAAS;AACxD,SAAK,sBAAkB;AAAA,MACrB;AAAA,MACA;AAAA,IACF;AAGA,SAAK,YAAY,MAAM;AACvB,SAAK,cAAc,KAAK,MAAM,KAAK,YAAY,QAAQ,CAAC;AAGxD,qDAAqB,MAAM;AAC3B,SAAK,cAAc,KAAK,MAAM,iDAAqB,QAAQ,CAAC;AAK5D;AAAA,MACE,CAAC,0CAAsB,UAAU,0CAAsB,OAAO,EAAE;AAAA,QAC9D,KAAK,YAAY;AAAA,MACnB;AAAA,MACA,yBAAS;AAAA,QACP;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEO,QAAc;AACnB,SAAK,QAAQ;AAAA,EACf;AACF;;;AD5JO,SAAS,eACX,UACmB;AAGtB,SAAO,IAAI;AAAA,IACT,CAAC,+BAAkB,+CAAyB;AAAA,IAC5C;AAAA,EACF;AACF;","names":["request"]}
@@ -42,7 +42,23 @@ var SetupServerCommonApi = class extends SetupApi {
42
42
  requestId,
43
43
  this.handlersController.currentHandlers().filter(isHandlerKind("RequestHandler")),
44
44
  this.resolvedOptions,
45
- this.emitter
45
+ this.emitter,
46
+ {
47
+ onPassthroughResponse(request2) {
48
+ const acceptHeader = request2.headers.get("accept");
49
+ if (acceptHeader) {
50
+ const nextAcceptHeader = acceptHeader.replace(
51
+ /(,\s+)?msw\/passthrough/,
52
+ ""
53
+ );
54
+ if (nextAcceptHeader) {
55
+ request2.headers.set("accept", nextAcceptHeader);
56
+ } else {
57
+ request2.headers.delete("accept");
58
+ }
59
+ }
60
+ }
61
+ }
46
62
  );
47
63
  if (response) {
48
64
  controller.respondWith(response);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/native/index.ts","../../src/node/SetupServerCommonApi.ts"],"sourcesContent":["import { FetchInterceptor } from '@mswjs/interceptors/fetch'\nimport { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport { SetupServerCommonApi } from '../node/SetupServerCommonApi'\n\n/**\n * Sets up a requests interception in React Native with the given request handlers.\n * @param {RequestHandler[]} handlers List of request handlers.\n *\n * @see {@link https://mswjs.io/docs/api/setup-server `setupServer()` API reference}\n */\nexport function setupServer(\n ...handlers: Array<RequestHandler>\n): SetupServerCommonApi {\n // Provision request interception via patching the `XMLHttpRequest` class only\n // in React Native. There is no `http`/`https` modules in that environment.\n return new SetupServerCommonApi(\n [FetchInterceptor, XMLHttpRequestInterceptor],\n handlers,\n )\n}\n","/**\n * @note This API is extended by both \"msw/node\" and \"msw/native\"\n * so be minding about the things you import!\n */\nimport type { RequiredDeep } from 'type-fest'\nimport { invariant } from 'outvariant'\nimport {\n BatchInterceptor,\n InterceptorReadyState,\n type HttpRequestEventMap,\n type Interceptor,\n} from '@mswjs/interceptors'\nimport type { LifeCycleEventsMap, SharedOptions } from '~/core/sharedOptions'\nimport { SetupApi } from '~/core/SetupApi'\nimport { handleRequest } from '~/core/utils/handleRequest'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport { mergeRight } from '~/core/utils/internal/mergeRight'\nimport { InternalError, devUtils } from '~/core/utils/internal/devUtils'\nimport type { SetupServerCommon } from './glossary'\nimport { handleWebSocketEvent } from '~/core/ws/handleWebSocketEvent'\nimport { webSocketInterceptor } from '~/core/ws/webSocketInterceptor'\nimport { isHandlerKind } from '~/core/utils/internal/isHandlerKind'\n\nexport const DEFAULT_LISTEN_OPTIONS: RequiredDeep<SharedOptions> = {\n onUnhandledRequest: 'warn',\n}\n\nexport class SetupServerCommonApi\n extends SetupApi<LifeCycleEventsMap>\n implements SetupServerCommon\n{\n protected readonly interceptor: BatchInterceptor<\n Array<Interceptor<HttpRequestEventMap>>,\n HttpRequestEventMap\n >\n private resolvedOptions: RequiredDeep<SharedOptions>\n\n constructor(\n interceptors: Array<{ new (): Interceptor<HttpRequestEventMap> }>,\n handlers: Array<RequestHandler | WebSocketHandler>,\n ) {\n super(...handlers)\n\n this.interceptor = new BatchInterceptor({\n name: 'setup-server',\n interceptors: interceptors.map((Interceptor) => new Interceptor()),\n })\n\n this.resolvedOptions = {} as RequiredDeep<SharedOptions>\n\n this.init()\n }\n\n /**\n * Subscribe to all requests that are using the interceptor object\n */\n private init(): void {\n this.interceptor.on(\n 'request',\n async ({ request, requestId, controller }) => {\n const response = await handleRequest(\n request,\n requestId,\n this.handlersController\n .currentHandlers()\n .filter(isHandlerKind('RequestHandler')),\n this.resolvedOptions,\n this.emitter,\n )\n\n if (response) {\n controller.respondWith(response)\n }\n\n return\n },\n )\n\n this.interceptor.on('unhandledException', ({ error }) => {\n if (error instanceof InternalError) {\n throw error\n }\n })\n\n this.interceptor.on(\n 'response',\n ({ response, isMockedResponse, request, requestId }) => {\n this.emitter.emit(\n isMockedResponse ? 'response:mocked' : 'response:bypass',\n {\n response,\n request,\n requestId,\n },\n )\n },\n )\n\n // Preconfigure the WebSocket interception but don't enable it just yet.\n // It will be enabled when the server starts.\n handleWebSocketEvent({\n getUnhandledRequestStrategy: () => {\n return this.resolvedOptions.onUnhandledRequest\n },\n getHandlers: () => {\n return this.handlersController.currentHandlers()\n },\n onMockedConnection: () => {},\n onPassthroughConnection: () => {},\n })\n }\n\n public listen(options: Partial<SharedOptions> = {}): void {\n this.resolvedOptions = mergeRight(\n DEFAULT_LISTEN_OPTIONS,\n options,\n ) as RequiredDeep<SharedOptions>\n\n // Apply the interceptor when starting the server.\n this.interceptor.apply()\n this.subscriptions.push(() => this.interceptor.dispose())\n\n // Apply the WebSocket interception.\n webSocketInterceptor.apply()\n this.subscriptions.push(() => webSocketInterceptor.dispose())\n\n // Assert that the interceptor has been applied successfully.\n // Also guards us from forgetting to call \"interceptor.apply()\"\n // as a part of the \"listen\" method.\n invariant(\n [InterceptorReadyState.APPLYING, InterceptorReadyState.APPLIED].includes(\n this.interceptor.readyState,\n ),\n devUtils.formatMessage(\n 'Failed to start \"setupServer\": the interceptor failed to apply. This is likely an issue with the library and you should report it at \"%s\".',\n ),\n 'https://github.com/mswjs/msw/issues/new/choose',\n )\n }\n\n public close(): void {\n this.dispose()\n }\n}\n"],"mappings":";AAAA,SAAS,wBAAwB;AACjC,SAAS,iCAAiC;;;ACI1C,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAEP,SAAS,gBAAgB;AACzB,SAAS,qBAAqB;AAG9B,SAAS,kBAAkB;AAC3B,SAAS,eAAe,gBAAgB;AAExC,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,qBAAqB;AAEvB,IAAM,yBAAsD;AAAA,EACjE,oBAAoB;AACtB;AAEO,IAAM,uBAAN,cACG,SAEV;AAAA,EACqB;AAAA,EAIX;AAAA,EAER,YACE,cACA,UACA;AACA,UAAM,GAAG,QAAQ;AAEjB,SAAK,cAAc,IAAI,iBAAiB;AAAA,MACtC,MAAM;AAAA,MACN,cAAc,aAAa,IAAI,CAAC,gBAAgB,IAAI,YAAY,CAAC;AAAA,IACnE,CAAC;AAED,SAAK,kBAAkB,CAAC;AAExB,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA,EAKQ,OAAa;AACnB,SAAK,YAAY;AAAA,MACf;AAAA,MACA,OAAO,EAAE,SAAS,WAAW,WAAW,MAAM;AAC5C,cAAM,WAAW,MAAM;AAAA,UACrB;AAAA,UACA;AAAA,UACA,KAAK,mBACF,gBAAgB,EAChB,OAAO,cAAc,gBAAgB,CAAC;AAAA,UACzC,KAAK;AAAA,UACL,KAAK;AAAA,QACP;AAEA,YAAI,UAAU;AACZ,qBAAW,YAAY,QAAQ;AAAA,QACjC;AAEA;AAAA,MACF;AAAA,IACF;AAEA,SAAK,YAAY,GAAG,sBAAsB,CAAC,EAAE,MAAM,MAAM;AACvD,UAAI,iBAAiB,eAAe;AAClC,cAAM;AAAA,MACR;AAAA,IACF,CAAC;AAED,SAAK,YAAY;AAAA,MACf;AAAA,MACA,CAAC,EAAE,UAAU,kBAAkB,SAAS,UAAU,MAAM;AACtD,aAAK,QAAQ;AAAA,UACX,mBAAmB,oBAAoB;AAAA,UACvC;AAAA,YACE;AAAA,YACA;AAAA,YACA;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAIA,yBAAqB;AAAA,MACnB,6BAA6B,MAAM;AACjC,eAAO,KAAK,gBAAgB;AAAA,MAC9B;AAAA,MACA,aAAa,MAAM;AACjB,eAAO,KAAK,mBAAmB,gBAAgB;AAAA,MACjD;AAAA,MACA,oBAAoB,MAAM;AAAA,MAAC;AAAA,MAC3B,yBAAyB,MAAM;AAAA,MAAC;AAAA,IAClC,CAAC;AAAA,EACH;AAAA,EAEO,OAAO,UAAkC,CAAC,GAAS;AACxD,SAAK,kBAAkB;AAAA,MACrB;AAAA,MACA;AAAA,IACF;AAGA,SAAK,YAAY,MAAM;AACvB,SAAK,cAAc,KAAK,MAAM,KAAK,YAAY,QAAQ,CAAC;AAGxD,yBAAqB,MAAM;AAC3B,SAAK,cAAc,KAAK,MAAM,qBAAqB,QAAQ,CAAC;AAK5D;AAAA,MACE,CAAC,sBAAsB,UAAU,sBAAsB,OAAO,EAAE;AAAA,QAC9D,KAAK,YAAY;AAAA,MACnB;AAAA,MACA,SAAS;AAAA,QACP;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEO,QAAc;AACnB,SAAK,QAAQ;AAAA,EACf;AACF;;;ADrIO,SAAS,eACX,UACmB;AAGtB,SAAO,IAAI;AAAA,IACT,CAAC,kBAAkB,yBAAyB;AAAA,IAC5C;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/native/index.ts","../../src/node/SetupServerCommonApi.ts"],"sourcesContent":["import { FetchInterceptor } from '@mswjs/interceptors/fetch'\nimport { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport { SetupServerCommonApi } from '../node/SetupServerCommonApi'\n\n/**\n * Sets up a requests interception in React Native with the given request handlers.\n * @param {RequestHandler[]} handlers List of request handlers.\n *\n * @see {@link https://mswjs.io/docs/api/setup-server `setupServer()` API reference}\n */\nexport function setupServer(\n ...handlers: Array<RequestHandler>\n): SetupServerCommonApi {\n // Provision request interception via patching the `XMLHttpRequest` class only\n // in React Native. There is no `http`/`https` modules in that environment.\n return new SetupServerCommonApi(\n [FetchInterceptor, XMLHttpRequestInterceptor],\n handlers,\n )\n}\n","/**\n * @note This API is extended by both \"msw/node\" and \"msw/native\"\n * so be minding about the things you import!\n */\nimport type { RequiredDeep } from 'type-fest'\nimport { invariant } from 'outvariant'\nimport {\n BatchInterceptor,\n InterceptorReadyState,\n type HttpRequestEventMap,\n type Interceptor,\n} from '@mswjs/interceptors'\nimport type { LifeCycleEventsMap, SharedOptions } from '~/core/sharedOptions'\nimport { SetupApi } from '~/core/SetupApi'\nimport { handleRequest } from '~/core/utils/handleRequest'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport { mergeRight } from '~/core/utils/internal/mergeRight'\nimport { InternalError, devUtils } from '~/core/utils/internal/devUtils'\nimport type { SetupServerCommon } from './glossary'\nimport { handleWebSocketEvent } from '~/core/ws/handleWebSocketEvent'\nimport { webSocketInterceptor } from '~/core/ws/webSocketInterceptor'\nimport { isHandlerKind } from '~/core/utils/internal/isHandlerKind'\n\nexport const DEFAULT_LISTEN_OPTIONS: RequiredDeep<SharedOptions> = {\n onUnhandledRequest: 'warn',\n}\n\nexport class SetupServerCommonApi\n extends SetupApi<LifeCycleEventsMap>\n implements SetupServerCommon\n{\n protected readonly interceptor: BatchInterceptor<\n Array<Interceptor<HttpRequestEventMap>>,\n HttpRequestEventMap\n >\n private resolvedOptions: RequiredDeep<SharedOptions>\n\n constructor(\n interceptors: Array<{ new (): Interceptor<HttpRequestEventMap> }>,\n handlers: Array<RequestHandler | WebSocketHandler>,\n ) {\n super(...handlers)\n\n this.interceptor = new BatchInterceptor({\n name: 'setup-server',\n interceptors: interceptors.map((Interceptor) => new Interceptor()),\n })\n\n this.resolvedOptions = {} as RequiredDeep<SharedOptions>\n\n this.init()\n }\n\n /**\n * Subscribe to all requests that are using the interceptor object\n */\n private init(): void {\n this.interceptor.on(\n 'request',\n async ({ request, requestId, controller }) => {\n const response = await handleRequest(\n request,\n requestId,\n this.handlersController\n .currentHandlers()\n .filter(isHandlerKind('RequestHandler')),\n this.resolvedOptions,\n this.emitter,\n {\n onPassthroughResponse(request) {\n const acceptHeader = request.headers.get('accept')\n\n /**\n * @note Remove the internal bypass request header.\n * In the browser, this is done by the worker script.\n * In Node.js, it has to be done here.\n */\n if (acceptHeader) {\n const nextAcceptHeader = acceptHeader.replace(\n /(,\\s+)?msw\\/passthrough/,\n '',\n )\n\n if (nextAcceptHeader) {\n request.headers.set('accept', nextAcceptHeader)\n } else {\n request.headers.delete('accept')\n }\n }\n },\n },\n )\n\n if (response) {\n controller.respondWith(response)\n }\n\n return\n },\n )\n\n this.interceptor.on('unhandledException', ({ error }) => {\n if (error instanceof InternalError) {\n throw error\n }\n })\n\n this.interceptor.on(\n 'response',\n ({ response, isMockedResponse, request, requestId }) => {\n this.emitter.emit(\n isMockedResponse ? 'response:mocked' : 'response:bypass',\n {\n response,\n request,\n requestId,\n },\n )\n },\n )\n\n // Preconfigure the WebSocket interception but don't enable it just yet.\n // It will be enabled when the server starts.\n handleWebSocketEvent({\n getUnhandledRequestStrategy: () => {\n return this.resolvedOptions.onUnhandledRequest\n },\n getHandlers: () => {\n return this.handlersController.currentHandlers()\n },\n onMockedConnection: () => {},\n onPassthroughConnection: () => {},\n })\n }\n\n public listen(options: Partial<SharedOptions> = {}): void {\n this.resolvedOptions = mergeRight(\n DEFAULT_LISTEN_OPTIONS,\n options,\n ) as RequiredDeep<SharedOptions>\n\n // Apply the interceptor when starting the server.\n this.interceptor.apply()\n this.subscriptions.push(() => this.interceptor.dispose())\n\n // Apply the WebSocket interception.\n webSocketInterceptor.apply()\n this.subscriptions.push(() => webSocketInterceptor.dispose())\n\n // Assert that the interceptor has been applied successfully.\n // Also guards us from forgetting to call \"interceptor.apply()\"\n // as a part of the \"listen\" method.\n invariant(\n [InterceptorReadyState.APPLYING, InterceptorReadyState.APPLIED].includes(\n this.interceptor.readyState,\n ),\n devUtils.formatMessage(\n 'Failed to start \"setupServer\": the interceptor failed to apply. This is likely an issue with the library and you should report it at \"%s\".',\n ),\n 'https://github.com/mswjs/msw/issues/new/choose',\n )\n }\n\n public close(): void {\n this.dispose()\n }\n}\n"],"mappings":";AAAA,SAAS,wBAAwB;AACjC,SAAS,iCAAiC;;;ACI1C,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAEP,SAAS,gBAAgB;AACzB,SAAS,qBAAqB;AAG9B,SAAS,kBAAkB;AAC3B,SAAS,eAAe,gBAAgB;AAExC,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,qBAAqB;AAEvB,IAAM,yBAAsD;AAAA,EACjE,oBAAoB;AACtB;AAEO,IAAM,uBAAN,cACG,SAEV;AAAA,EACqB;AAAA,EAIX;AAAA,EAER,YACE,cACA,UACA;AACA,UAAM,GAAG,QAAQ;AAEjB,SAAK,cAAc,IAAI,iBAAiB;AAAA,MACtC,MAAM;AAAA,MACN,cAAc,aAAa,IAAI,CAAC,gBAAgB,IAAI,YAAY,CAAC;AAAA,IACnE,CAAC;AAED,SAAK,kBAAkB,CAAC;AAExB,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA,EAKQ,OAAa;AACnB,SAAK,YAAY;AAAA,MACf;AAAA,MACA,OAAO,EAAE,SAAS,WAAW,WAAW,MAAM;AAC5C,cAAM,WAAW,MAAM;AAAA,UACrB;AAAA,UACA;AAAA,UACA,KAAK,mBACF,gBAAgB,E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K,cAAc,KAAK,MAAM,KAAK,YAAY,QAAQ,CAAC;AAGxD,yBAAqB,MAAM;AAC3B,SAAK,cAAc,KAAK,MAAM,qBAAqB,QAAQ,CAAC;AAK5D;AAAA,MACE,CAAC,sBAAsB,UAAU,sBAAsB,OAAO,EAAE;AAAA,QAC9D,KAAK,YAAY;AAAA,MACnB;AAAA,MACA,SAAS;AAAA,QACP;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEO,QAAc;AACnB,SAAK,QAAQ;AAAA,EACf;AACF;;;AD5JO,SAAS,eACX,UACmB;AAGtB,SAAO,IAAI;AAAA,IACT,CAAC,kBAAkB,yBAAyB;AAAA,IAC5C;AAAA,EACF;AACF;","names":["request"]}
package/lib/node/index.js CHANGED
@@ -68,7 +68,23 @@ var SetupServerCommonApi = class extends import_SetupApi.SetupApi {
68
68
  requestId,
69
69
  this.handlersController.currentHandlers().filter((0, import_isHandlerKind.isHandlerKind)("RequestHandler")),
70
70
  this.resolvedOptions,
71
- this.emitter
71
+ this.emitter,
72
+ {
73
+ onPassthroughResponse(request2) {
74
+ const acceptHeader = request2.headers.get("accept");
75
+ if (acceptHeader) {
76
+ const nextAcceptHeader = acceptHeader.replace(
77
+ /(,\s+)?msw\/passthrough/,
78
+ ""
79
+ );
80
+ if (nextAcceptHeader) {
81
+ request2.headers.set("accept", nextAcceptHeader);
82
+ } else {
83
+ request2.headers.delete("accept");
84
+ }
85
+ }
86
+ }
87
+ }
72
88
  );
73
89
  if (response) {
74
90
  controller.respondWith(response);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/node/index.ts","../../src/node/SetupServerApi.ts","../../src/node/SetupServerCommonApi.ts","../../src/node/setupServer.ts"],"sourcesContent":["export type { SetupServer } from './glossary'\nexport { SetupServerApi } from './SetupServerApi'\nexport { setupServer } from './setupServer'\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest'\nimport { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest'\nimport { FetchInterceptor } from '@mswjs/interceptors/fetch'\nimport { HandlersController } from '~/core/SetupApi'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport type { SetupServer } from './glossary'\nimport { SetupServerCommonApi } from './SetupServerCommonApi'\n\nconst store = new AsyncLocalStorage<RequestHandlersContext>()\n\ntype RequestHandlersContext = {\n initialHandlers: Array<RequestHandler | WebSocketHandler>\n handlers: Array<RequestHandler | WebSocketHandler>\n}\n\n/**\n * A handlers controller that utilizes `AsyncLocalStorage` in Node.js\n * to prevent the request handlers list from being a shared state\n * across mutliple tests.\n */\nclass AsyncHandlersController implements HandlersController {\n private rootContext: RequestHandlersContext\n\n constructor(initialHandlers: Array<RequestHandler | WebSocketHandler>) {\n this.rootContext = { initialHandlers, handlers: [] }\n }\n\n get context(): RequestHandlersContext {\n return store.getStore() || this.rootContext\n }\n\n public prepend(runtimeHandlers: Array<RequestHandler | WebSocketHandler>) {\n this.context.handlers.unshift(...runtimeHandlers)\n }\n\n public reset(nextHandlers: Array<RequestHandler | WebSocketHandler>) {\n const context = this.context\n context.handlers = []\n context.initialHandlers =\n nextHandlers.length > 0 ? nextHandlers : context.initialHandlers\n }\n\n public currentHandlers(): Array<RequestHandler | WebSocketHandler> {\n const { initialHandlers, handlers } = this.context\n return handlers.concat(initialHandlers)\n }\n}\n\nexport class SetupServerApi\n extends SetupServerCommonApi\n implements SetupServer\n{\n constructor(handlers: Array<RequestHandler | WebSocketHandler>) {\n super(\n [ClientRequestInterceptor, XMLHttpRequestInterceptor, FetchInterceptor],\n handlers,\n )\n\n this.handlersController = new AsyncHandlersController(handlers)\n }\n\n public boundary<Args extends Array<any>, R>(\n callback: (...args: Args) => R,\n ): (...args: Args) => R {\n return (...args: Args): R => {\n return store.run<any, any>(\n {\n initialHandlers: this.handlersController.currentHandlers(),\n handlers: [],\n },\n callback,\n ...args,\n )\n }\n }\n\n public close(): void {\n super.close()\n store.disable()\n }\n}\n","/**\n * @note This API is extended by both \"msw/node\" and \"msw/native\"\n * so be minding about the things you import!\n */\nimport type { RequiredDeep } from 'type-fest'\nimport { invariant } from 'outvariant'\nimport {\n BatchInterceptor,\n InterceptorReadyState,\n type HttpRequestEventMap,\n type Interceptor,\n} from '@mswjs/interceptors'\nimport type { LifeCycleEventsMap, SharedOptions } from '~/core/sharedOptions'\nimport { SetupApi } from '~/core/SetupApi'\nimport { handleRequest } from '~/core/utils/handleRequest'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport { mergeRight } from '~/core/utils/internal/mergeRight'\nimport { InternalError, devUtils } from '~/core/utils/internal/devUtils'\nimport type { SetupServerCommon } from './glossary'\nimport { handleWebSocketEvent } from '~/core/ws/handleWebSocketEvent'\nimport { webSocketInterceptor } from '~/core/ws/webSocketInterceptor'\nimport { isHandlerKind } from '~/core/utils/internal/isHandlerKind'\n\nexport const DEFAULT_LISTEN_OPTIONS: RequiredDeep<SharedOptions> = {\n onUnhandledRequest: 'warn',\n}\n\nexport class SetupServerCommonApi\n extends SetupApi<LifeCycleEventsMap>\n implements SetupServerCommon\n{\n protected readonly interceptor: BatchInterceptor<\n Array<Interceptor<HttpRequestEventMap>>,\n HttpRequestEventMap\n >\n private resolvedOptions: RequiredDeep<SharedOptions>\n\n constructor(\n interceptors: Array<{ new (): Interceptor<HttpRequestEventMap> }>,\n handlers: Array<RequestHandler | WebSocketHandler>,\n ) {\n super(...handlers)\n\n this.interceptor = new BatchInterceptor({\n name: 'setup-server',\n interceptors: interceptors.map((Interceptor) => new Interceptor()),\n })\n\n this.resolvedOptions = {} as RequiredDeep<SharedOptions>\n\n this.init()\n }\n\n /**\n * Subscribe to all requests that are using the interceptor object\n */\n private init(): void {\n this.interceptor.on(\n 'request',\n async ({ request, requestId, controller }) => {\n const response = await handleRequest(\n request,\n requestId,\n this.handlersController\n .currentHandlers()\n .filter(isHandlerKind('RequestHandler')),\n this.resolvedOptions,\n this.emitter,\n )\n\n if (response) {\n controller.respondWith(response)\n }\n\n return\n },\n )\n\n this.interceptor.on('unhandledException', ({ error }) => {\n if (error instanceof InternalError) {\n throw error\n }\n })\n\n this.interceptor.on(\n 'response',\n ({ response, isMockedResponse, request, requestId }) => {\n this.emitter.emit(\n isMockedResponse ? 'response:mocked' : 'response:bypass',\n {\n response,\n request,\n requestId,\n },\n )\n },\n )\n\n // Preconfigure the WebSocket interception but don't enable it just yet.\n // It will be enabled when the server starts.\n handleWebSocketEvent({\n getUnhandledRequestStrategy: () => {\n return this.resolvedOptions.onUnhandledRequest\n },\n getHandlers: () => {\n return this.handlersController.currentHandlers()\n },\n onMockedConnection: () => {},\n onPassthroughConnection: () => {},\n })\n }\n\n public listen(options: Partial<SharedOptions> = {}): void {\n this.resolvedOptions = mergeRight(\n DEFAULT_LISTEN_OPTIONS,\n options,\n ) as RequiredDeep<SharedOptions>\n\n // Apply the interceptor when starting the server.\n this.interceptor.apply()\n this.subscriptions.push(() => this.interceptor.dispose())\n\n // Apply the WebSocket interception.\n webSocketInterceptor.apply()\n this.subscriptions.push(() => webSocketInterceptor.dispose())\n\n // Assert that the interceptor has been applied successfully.\n // Also guards us from forgetting to call \"interceptor.apply()\"\n // as a part of the \"listen\" method.\n invariant(\n [InterceptorReadyState.APPLYING, InterceptorReadyState.APPLIED].includes(\n this.interceptor.readyState,\n ),\n devUtils.formatMessage(\n 'Failed to start \"setupServer\": the interceptor failed to apply. This is likely an issue with the library and you should report it at \"%s\".',\n ),\n 'https://github.com/mswjs/msw/issues/new/choose',\n )\n }\n\n public close(): void {\n this.dispose()\n }\n}\n","import type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport { SetupServerApi } from './SetupServerApi'\n\n/**\n * Sets up a requests interception in Node.js with the given request handlers.\n * @param {RequestHandler[]} handlers List of request handlers.\n *\n * @see {@link https://mswjs.io/docs/api/setup-server `setupServer()` API reference}\n */\nexport const setupServer = (\n ...handlers: Array<RequestHandler | WebSocketHandler>\n): SetupServerApi => {\n return new SetupServerApi(handlers)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,8BAAkC;AAClC,2BAAyC;AACzC,4BAA0C;AAC1C,mBAAiC;;;ACEjC,wBAA0B;AAC1B,0BAKO;AAEP,sBAAyB;AACzB,2BAA8B;AAG9B,wBAA2B;AAC3B,sBAAwC;AAExC,kCAAqC;AACrC,kCAAqC;AACrC,2BAA8B;AAEvB,IAAM,yBAAsD;AAAA,EACjE,oBAAoB;AACtB;AAEO,IAAM,uBAAN,cACG,yBAEV;AAAA,EACqB;AAAA,EAIX;AAAA,EAER,YACE,cACA,UACA;AACA,UAAM,GAAG,QAAQ;AAEjB,SAAK,cAAc,IAAI,qCAAiB;AAAA,MACtC,MAAM;AAAA,MACN,cAAc,aAAa,IAAI,CAAC,gBAAgB,IAAI,YAAY,CAAC;AAAA,IACnE,CAAC;AAED,SAAK,kBAAkB,CAAC;AAExB,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA,EAKQ,OAAa;AACnB,SAAK,YAAY;AAAA,MACf;AAAA,MACA,OAAO,EAAE,SAAS,WAAW,WAAW,MAAM;AAC5C,cAAM,WAAW,UAAM;AAAA,UACrB;AAAA,UACA;AAAA,UACA,KAAK,mBACF,gBAAgB,EAChB,WAAO,oCAAc,gBAAgB,CAAC;AAAA,UACzC,KAAK;AAAA,UACL,KAAK;AAAA,QACP;AAEA,YAAI,UAAU;AACZ,qBAAW,YAAY,QAAQ;AAAA,QACjC;AAEA;AAAA,MACF;AAAA,IACF;AAEA,SAAK,YAAY,GAAG,sBAAsB,CAAC,EAAE,MAAM,MAAM;AACvD,UAAI,iBAAiB,+BAAe;AAClC,cAAM;AAAA,MACR;AAAA,IACF,CAAC;AAED,SAA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AAG,eAAe;AAAA,EAClD;AAAA,EAEO,MAAM,cAAwD;AACnE,UAAM,UAAU,KAAK;AACrB,YAAQ,WAAW,CAAC;AACpB,YAAQ,kBACN,aAAa,SAAS,IAAI,eAAe,QAAQ;AAAA,EACrD;AAAA,EAEO,kBAA4D;AACjE,UAAM,EAAE,iBAAiB,SAAS,IAAI,KAAK;AAC3C,WAAO,SAAS,OAAO,eAAe;AAAA,EACxC;AACF;AAEO,IAAM,iBAAN,cACG,qBAEV;AAAA,EACE,YAAY,UAAoD;AAC9D;AAAA,MACE,CAAC,+CAA0B,iDAA2B,6BAAgB;AAAA,MACtE;AAAA,IACF;AAEA,SAAK,qBAAqB,IAAI,wBAAwB,QAAQ;AAAA,EAChE;AAAA,EAEO,SACL,UACsB;AACtB,WAAO,IAAI,SAAkB;AAC3B,aAAO,MAAM;AAAA,QACX;AAAA,UACE,iBAAiB,KAAK,mBAAmB,gBAAgB;AAAA,UACzD,UAAU,CAAC;AAAA,QACb;AAAA,QACA;AAAA,QACA,GAAG;AAAA,MACL;AAAA,IACF;AAAA,EACF;AAAA,EAEO,QAAc;AACnB,UAAM,MAAM;AACZ,UAAM,QAAQ;AAAA,EAChB;AACF;;;AExEO,IAAM,cAAc,IACtB,aACgB;AACnB,SAAO,IAAI,eAAe,QAAQ;AACpC;","names":[]}
1
+ {"version":3,"sources":["../../src/node/index.ts","../../src/node/SetupServerApi.ts","../../src/node/SetupServerCommonApi.ts","../../src/node/setupServer.ts"],"sourcesContent":["export type { SetupServer } from './glossary'\nexport { SetupServerApi } from './SetupServerApi'\nexport { setupServer } from './setupServer'\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest'\nimport { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest'\nimport { FetchInterceptor } from '@mswjs/interceptors/fetch'\nimport { HandlersController } from '~/core/SetupApi'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport type { SetupServer } from './glossary'\nimport { SetupServerCommonApi } from './SetupServerCommonApi'\n\nconst store = new AsyncLocalStorage<RequestHandlersContext>()\n\ntype RequestHandlersContext = {\n initialHandlers: Array<RequestHandler | WebSocketHandler>\n handlers: Array<RequestHandler | WebSocketHandler>\n}\n\n/**\n * A handlers controller that utilizes `AsyncLocalStorage` in Node.js\n * to prevent the request handlers list from being a shared state\n * across mutliple tests.\n */\nclass AsyncHandlersController implements HandlersController {\n private rootContext: RequestHandlersContext\n\n constructor(initialHandlers: Array<RequestHandler | WebSocketHandler>) {\n this.rootContext = { initialHandlers, handlers: [] }\n }\n\n get context(): RequestHandlersContext {\n return store.getStore() || this.rootContext\n }\n\n public prepend(runtimeHandlers: Array<RequestHandler | WebSocketHandler>) {\n this.context.handlers.unshift(...runtimeHandlers)\n }\n\n public reset(nextHandlers: Array<RequestHandler | WebSocketHandler>) {\n const context = this.context\n context.handlers = []\n context.initialHandlers =\n nextHandlers.length > 0 ? nextHandlers : context.initialHandlers\n }\n\n public currentHandlers(): Array<RequestHandler | WebSocketHandler> {\n const { initialHandlers, handlers } = this.context\n return handlers.concat(initialHandlers)\n }\n}\n\nexport class SetupServerApi\n extends SetupServerCommonApi\n implements SetupServer\n{\n constructor(handlers: Array<RequestHandler | WebSocketHandler>) {\n super(\n [ClientRequestInterceptor, XMLHttpRequestInterceptor, FetchInterceptor],\n handlers,\n )\n\n this.handlersController = new AsyncHandlersController(handlers)\n }\n\n public boundary<Args extends Array<any>, R>(\n callback: (...args: Args) => R,\n ): (...args: Args) => R {\n return (...args: Args): R => {\n return store.run<any, any>(\n {\n initialHandlers: this.handlersController.currentHandlers(),\n handlers: [],\n },\n callback,\n ...args,\n )\n }\n }\n\n public close(): void {\n super.close()\n store.disable()\n }\n}\n","/**\n * @note This API is extended by both \"msw/node\" and \"msw/native\"\n * so be minding about the things you import!\n */\nimport type { RequiredDeep } from 'type-fest'\nimport { invariant } from 'outvariant'\nimport {\n BatchInterceptor,\n InterceptorReadyState,\n type HttpRequestEventMap,\n type Interceptor,\n} from '@mswjs/interceptors'\nimport type { LifeCycleEventsMap, SharedOptions } from '~/core/sharedOptions'\nimport { SetupApi } from '~/core/SetupApi'\nimport { handleRequest } from '~/core/utils/handleRequest'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport { mergeRight } from '~/core/utils/internal/mergeRight'\nimport { InternalError, devUtils } from '~/core/utils/internal/devUtils'\nimport type { SetupServerCommon } from './glossary'\nimport { handleWebSocketEvent } from '~/core/ws/handleWebSocketEvent'\nimport { webSocketInterceptor } from '~/core/ws/webSocketInterceptor'\nimport { isHandlerKind } from '~/core/utils/internal/isHandlerKind'\n\nexport const DEFAULT_LISTEN_OPTIONS: RequiredDeep<SharedOptions> = {\n onUnhandledRequest: 'warn',\n}\n\nexport class SetupServerCommonApi\n extends SetupApi<LifeCycleEventsMap>\n implements SetupServerCommon\n{\n protected readonly interceptor: BatchInterceptor<\n Array<Interceptor<HttpRequestEventMap>>,\n HttpRequestEventMap\n >\n private resolvedOptions: RequiredDeep<SharedOptions>\n\n constructor(\n interceptors: Array<{ new (): Interceptor<HttpRequestEventMap> }>,\n handlers: Array<RequestHandler | WebSocketHandler>,\n ) {\n super(...handlers)\n\n this.interceptor = new BatchInterceptor({\n name: 'setup-server',\n interceptors: interceptors.map((Interceptor) => new Interceptor()),\n })\n\n this.resolvedOptions = {} as RequiredDeep<SharedOptions>\n\n this.init()\n }\n\n /**\n * Subscribe to all requests that are using the interceptor object\n */\n private init(): void {\n this.interceptor.on(\n 'request',\n async ({ request, requestId, controller }) => {\n const response = await handleRequest(\n request,\n requestId,\n this.handlersController\n .currentHandlers()\n .filter(isHandlerKind('RequestHandler')),\n this.resolvedOptions,\n this.emitter,\n {\n onPassthroughResponse(request) {\n const acceptHeader = request.headers.get('accept')\n\n /**\n * @note Remove the internal bypass request header.\n * In the browser, this is done by the worker script.\n * In Node.js, it has to be done here.\n */\n if (acceptHeader) {\n const nextAcceptHeader = acceptHeader.replace(\n /(,\\s+)?msw\\/passthrough/,\n '',\n )\n\n if (nextAcceptHeader) {\n request.headers.set('accept', nextAcceptHeader)\n } else {\n request.headers.delete('accept')\n }\n }\n },\n },\n )\n\n if (response) {\n controller.respondWith(response)\n }\n\n return\n },\n )\n\n this.interceptor.on('unhandledException', ({ error }) => {\n if (error instanceof InternalError) {\n throw error\n }\n })\n\n this.interceptor.on(\n 'response',\n ({ response, isMockedResponse, request, requestId }) => {\n this.emitter.emit(\n isMockedResponse ? 'response:mocked' : 'response:bypass',\n {\n response,\n request,\n requestId,\n },\n )\n },\n )\n\n // Preconfigure the WebSocket interception but don't enable it just yet.\n // It will be enabled when the server starts.\n handleWebSocketEvent({\n getUnhandledRequestStrategy: () => {\n return this.resolvedOptions.onUnhandledRequest\n },\n getHandlers: () => {\n return this.handlersController.currentHandlers()\n },\n onMockedConnection: () => {},\n onPassthroughConnection: () => {},\n })\n }\n\n public listen(options: Partial<SharedOptions> = {}): void {\n this.resolvedOptions = mergeRight(\n DEFAULT_LISTEN_OPTIONS,\n options,\n ) as RequiredDeep<SharedOptions>\n\n // Apply the interceptor when starting the server.\n this.interceptor.apply()\n this.subscriptions.push(() => this.interceptor.dispose())\n\n // Apply the WebSocket interception.\n webSocketInterceptor.apply()\n this.subscriptions.push(() => webSocketInterceptor.dispose())\n\n // Assert that the interceptor has been applied successfully.\n // Also guards us from forgetting to call \"interceptor.apply()\"\n // as a part of the \"listen\" method.\n invariant(\n [InterceptorReadyState.APPLYING, InterceptorReadyState.APPLIED].includes(\n this.interceptor.readyState,\n ),\n devUtils.formatMessage(\n 'Failed to start \"setupServer\": the interceptor failed to apply. This is likely an issue with the library and you should report it at \"%s\".',\n ),\n 'https://github.com/mswjs/msw/issues/new/choose',\n )\n }\n\n public close(): void {\n this.dispose()\n }\n}\n","import type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport { SetupServerApi } from './SetupServerApi'\n\n/**\n * Sets up a requests interception in Node.js with the given request handlers.\n * @param {RequestHandler[]} handlers List of request handlers.\n *\n * @see {@link https://mswjs.io/docs/api/setup-server `setupServer()` API reference}\n */\nexport const setupServer = (\n ...handlers: Array<RequestHandler | WebSocketHandler>\n): SetupServerApi => {\n return new SetupServerApi(handlers)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,8BAAkC;AAClC,2BAAyC;AACzC,4BAA0C;AAC1C,mBAAiC;;;ACEjC,wBAA0B;AAC1B,0BAKO;AAEP,sBAAyB;AACzB,2BAA8B;AAG9B,wBAA2B;AAC3B,sBAAwC;AAExC,kCAAqC;AACrC,kCAAqC;AACrC,2BAA8B;AAEvB,IAAM,yBAAsD;AAAA,EACjE,oBAAoB;AACtB;AAEO,IAAM,uBAAN,cACG,yBAEV;AAAA,EACqB;AAAA,EAIX;AAAA,EAER,YACE,cACA,UACA;AACA,UAAM,GAAG,QAAQ;AAEjB,SAAK,cAAc,IAAI,qCAAiB;AAAA,MACtC,MAAM;AAAA,MACN,cAAc,aAAa,IAAI,CAAC,gBAAgB,IAAI,YAAY,CAAC;AAAA,IACnE,CAAC;AAED,SAAK,kBAAkB,CAAC;AAExB,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA,EAKQ,OAAa;AACnB,SAAK,YAAY;AAAA,MACf;AAAA,MACA,OAAO,EAAE,SAAS,WAAW,WAAW,MAAM;AAC5C,cAAM,WAAW,UAAM;AAAA,UACrB;AAAA,UACA;AAAA,UACA,KAAK,mBACF,gBAAgB,EAChB,WAAO,oCAAc,gBAAgB,CAAC;AAAA,UACzC,KAAK;AAAA,UACL,KAAK;AAAA,UACL;AAAA,YACE,sBAAsBA,UAAS;AAC7B,oBAAM,eAAeA,SAAQ,QAAQ,IAAI,QAAQ;AAOjD,kBAAI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,cAAc,IACtB,aACgB;AACnB,SAAO,IAAI,eAAe,QAAQ;AACpC;","names":["request"]}
@@ -44,7 +44,23 @@ var SetupServerCommonApi = class extends SetupApi {
44
44
  requestId,
45
45
  this.handlersController.currentHandlers().filter(isHandlerKind("RequestHandler")),
46
46
  this.resolvedOptions,
47
- this.emitter
47
+ this.emitter,
48
+ {
49
+ onPassthroughResponse(request2) {
50
+ const acceptHeader = request2.headers.get("accept");
51
+ if (acceptHeader) {
52
+ const nextAcceptHeader = acceptHeader.replace(
53
+ /(,\s+)?msw\/passthrough/,
54
+ ""
55
+ );
56
+ if (nextAcceptHeader) {
57
+ request2.headers.set("accept", nextAcceptHeader);
58
+ } else {
59
+ request2.headers.delete("accept");
60
+ }
61
+ }
62
+ }
63
+ }
48
64
  );
49
65
  if (response) {
50
66
  controller.respondWith(response);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/node/SetupServerApi.ts","../../src/node/SetupServerCommonApi.ts","../../src/node/setupServer.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest'\nimport { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest'\nimport { FetchInterceptor } from '@mswjs/interceptors/fetch'\nimport { HandlersController } from '~/core/SetupApi'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport type { SetupServer } from './glossary'\nimport { SetupServerCommonApi } from './SetupServerCommonApi'\n\nconst store = new AsyncLocalStorage<RequestHandlersContext>()\n\ntype RequestHandlersContext = {\n initialHandlers: Array<RequestHandler | WebSocketHandler>\n handlers: Array<RequestHandler | WebSocketHandler>\n}\n\n/**\n * A handlers controller that utilizes `AsyncLocalStorage` in Node.js\n * to prevent the request handlers list from being a shared state\n * across mutliple tests.\n */\nclass AsyncHandlersController implements HandlersController {\n private rootContext: RequestHandlersContext\n\n constructor(initialHandlers: Array<RequestHandler | WebSocketHandler>) {\n this.rootContext = { initialHandlers, handlers: [] }\n }\n\n get context(): RequestHandlersContext {\n return store.getStore() || this.rootContext\n }\n\n public prepend(runtimeHandlers: Array<RequestHandler | WebSocketHandler>) {\n this.context.handlers.unshift(...runtimeHandlers)\n }\n\n public reset(nextHandlers: Array<RequestHandler | WebSocketHandler>) {\n const context = this.context\n context.handlers = []\n context.initialHandlers =\n nextHandlers.length > 0 ? nextHandlers : context.initialHandlers\n }\n\n public currentHandlers(): Array<RequestHandler | WebSocketHandler> {\n const { initialHandlers, handlers } = this.context\n return handlers.concat(initialHandlers)\n }\n}\n\nexport class SetupServerApi\n extends SetupServerCommonApi\n implements SetupServer\n{\n constructor(handlers: Array<RequestHandler | WebSocketHandler>) {\n super(\n [ClientRequestInterceptor, XMLHttpRequestInterceptor, FetchInterceptor],\n handlers,\n )\n\n this.handlersController = new AsyncHandlersController(handlers)\n }\n\n public boundary<Args extends Array<any>, R>(\n callback: (...args: Args) => R,\n ): (...args: Args) => R {\n return (...args: Args): R => {\n return store.run<any, any>(\n {\n initialHandlers: this.handlersController.currentHandlers(),\n handlers: [],\n },\n callback,\n ...args,\n )\n }\n }\n\n public close(): void {\n super.close()\n store.disable()\n }\n}\n","/**\n * @note This API is extended by both \"msw/node\" and \"msw/native\"\n * so be minding about the things you import!\n */\nimport type { RequiredDeep } from 'type-fest'\nimport { invariant } from 'outvariant'\nimport {\n BatchInterceptor,\n InterceptorReadyState,\n type HttpRequestEventMap,\n type Interceptor,\n} from '@mswjs/interceptors'\nimport type { LifeCycleEventsMap, SharedOptions } from '~/core/sharedOptions'\nimport { SetupApi } from '~/core/SetupApi'\nimport { handleRequest } from '~/core/utils/handleRequest'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport { mergeRight } from '~/core/utils/internal/mergeRight'\nimport { InternalError, devUtils } from '~/core/utils/internal/devUtils'\nimport type { SetupServerCommon } from './glossary'\nimport { handleWebSocketEvent } from '~/core/ws/handleWebSocketEvent'\nimport { webSocketInterceptor } from '~/core/ws/webSocketInterceptor'\nimport { isHandlerKind } from '~/core/utils/internal/isHandlerKind'\n\nexport const DEFAULT_LISTEN_OPTIONS: RequiredDeep<SharedOptions> = {\n onUnhandledRequest: 'warn',\n}\n\nexport class SetupServerCommonApi\n extends SetupApi<LifeCycleEventsMap>\n implements SetupServerCommon\n{\n protected readonly interceptor: BatchInterceptor<\n Array<Interceptor<HttpRequestEventMap>>,\n HttpRequestEventMap\n >\n private resolvedOptions: RequiredDeep<SharedOptions>\n\n constructor(\n interceptors: Array<{ new (): Interceptor<HttpRequestEventMap> }>,\n handlers: Array<RequestHandler | WebSocketHandler>,\n ) {\n super(...handlers)\n\n this.interceptor = new BatchInterceptor({\n name: 'setup-server',\n interceptors: interceptors.map((Interceptor) => new Interceptor()),\n })\n\n this.resolvedOptions = {} as RequiredDeep<SharedOptions>\n\n this.init()\n }\n\n /**\n * Subscribe to all requests that are using the interceptor object\n */\n private init(): void {\n this.interceptor.on(\n 'request',\n async ({ request, requestId, controller }) => {\n const response = await handleRequest(\n request,\n requestId,\n this.handlersController\n .currentHandlers()\n .filter(isHandlerKind('RequestHandler')),\n this.resolvedOptions,\n this.emitter,\n )\n\n if (response) {\n controller.respondWith(response)\n }\n\n return\n },\n )\n\n this.interceptor.on('unhandledException', ({ error }) => {\n if (error instanceof InternalError) {\n throw error\n }\n })\n\n this.interceptor.on(\n 'response',\n ({ response, isMockedResponse, request, requestId }) => {\n this.emitter.emit(\n isMockedResponse ? 'response:mocked' : 'response:bypass',\n {\n response,\n request,\n requestId,\n },\n )\n },\n )\n\n // Preconfigure the WebSocket interception but don't enable it just yet.\n // It will be enabled when the server starts.\n handleWebSocketEvent({\n getUnhandledRequestStrategy: () => {\n return this.resolvedOptions.onUnhandledRequest\n },\n getHandlers: () => {\n return this.handlersController.currentHandlers()\n },\n onMockedConnection: () => {},\n onPassthroughConnection: () => {},\n })\n }\n\n public listen(options: Partial<SharedOptions> = {}): void {\n this.resolvedOptions = mergeRight(\n DEFAULT_LISTEN_OPTIONS,\n options,\n ) as RequiredDeep<SharedOptions>\n\n // Apply the interceptor when starting the server.\n this.interceptor.apply()\n this.subscriptions.push(() => this.interceptor.dispose())\n\n // Apply the WebSocket interception.\n webSocketInterceptor.apply()\n this.subscriptions.push(() => webSocketInterceptor.dispose())\n\n // Assert that the interceptor has been applied successfully.\n // Also guards us from forgetting to call \"interceptor.apply()\"\n // as a part of the \"listen\" method.\n invariant(\n [InterceptorReadyState.APPLYING, InterceptorReadyState.APPLIED].includes(\n this.interceptor.readyState,\n ),\n devUtils.formatMessage(\n 'Failed to start \"setupServer\": the interceptor failed to apply. This is likely an issue with the library and you should report it at \"%s\".',\n ),\n 'https://github.com/mswjs/msw/issues/new/choose',\n )\n }\n\n public close(): void {\n this.dispose()\n }\n}\n","import type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport { SetupServerApi } from './SetupServerApi'\n\n/**\n * Sets up a requests interception in Node.js with the given request handlers.\n * @param {RequestHandler[]} handlers List of request handlers.\n *\n * @see {@link https://mswjs.io/docs/api/setup-server `setupServer()` API reference}\n */\nexport const setupServer = (\n ...handlers: Array<RequestHandler | WebSocketHandler>\n): SetupServerApi => {\n return new SetupServerApi(handlers)\n}\n"],"mappings":";AAAA,SAAS,yBAAyB;AAClC,SAAS,gCAAgC;AACzC,SAAS,iCAAiC;AAC1C,SAAS,wBAAwB;;;ACEjC,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAEP,SAAS,gBAAgB;AACzB,SAAS,qBAAqB;AAG9B,SAAS,kBAAkB;AAC3B,SAAS,eAAe,gBAAgB;AAExC,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,qBAAqB;AAEvB,IAAM,yBAAsD;AAAA,EACjE,oBAAoB;AACtB;AAEO,IAAM,uBAAN,cACG,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B,WAAO,IAAI,SAAkB;AAC3B,aAAO,MAAM;AAAA,QACX;AAAA,UACE,iBAAiB,KAAK,mBAAmB,gBAAgB;AAAA,UACzD,UAAU,CAAC;AAAA,QACb;AAAA,QACA;AAAA,QACA,GAAG;AAAA,MACL;AAAA,IACF;AAAA,EACF;AAAA,EAEO,QAAc;AACnB,UAAM,MAAM;AACZ,UAAM,QAAQ;AAAA,EAChB;AACF;;;AExEO,IAAM,cAAc,IACtB,aACgB;AACnB,SAAO,IAAI,eAAe,QAAQ;AACpC;","names":[]}
1
+ {"version":3,"sources":["../../src/node/SetupServerApi.ts","../../src/node/SetupServerCommonApi.ts","../../src/node/setupServer.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest'\nimport { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest'\nimport { FetchInterceptor } from '@mswjs/interceptors/fetch'\nimport { HandlersController } from '~/core/SetupApi'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport type { SetupServer } from './glossary'\nimport { SetupServerCommonApi } from './SetupServerCommonApi'\n\nconst store = new AsyncLocalStorage<RequestHandlersContext>()\n\ntype RequestHandlersContext = {\n initialHandlers: Array<RequestHandler | WebSocketHandler>\n handlers: Array<RequestHandler | WebSocketHandler>\n}\n\n/**\n * A handlers controller that utilizes `AsyncLocalStorage` in Node.js\n * to prevent the request handlers list from being a shared state\n * across mutliple tests.\n */\nclass AsyncHandlersController implements HandlersController {\n private rootContext: RequestHandlersContext\n\n constructor(initialHandlers: Array<RequestHandler | WebSocketHandler>) {\n this.rootContext = { initialHandlers, handlers: [] }\n }\n\n get context(): RequestHandlersContext {\n return store.getStore() || this.rootContext\n }\n\n public prepend(runtimeHandlers: Array<RequestHandler | WebSocketHandler>) {\n this.context.handlers.unshift(...runtimeHandlers)\n }\n\n public reset(nextHandlers: Array<RequestHandler | WebSocketHandler>) {\n const context = this.context\n context.handlers = []\n context.initialHandlers =\n nextHandlers.length > 0 ? nextHandlers : context.initialHandlers\n }\n\n public currentHandlers(): Array<RequestHandler | WebSocketHandler> {\n const { initialHandlers, handlers } = this.context\n return handlers.concat(initialHandlers)\n }\n}\n\nexport class SetupServerApi\n extends SetupServerCommonApi\n implements SetupServer\n{\n constructor(handlers: Array<RequestHandler | WebSocketHandler>) {\n super(\n [ClientRequestInterceptor, XMLHttpRequestInterceptor, FetchInterceptor],\n handlers,\n )\n\n this.handlersController = new AsyncHandlersController(handlers)\n }\n\n public boundary<Args extends Array<any>, R>(\n callback: (...args: Args) => R,\n ): (...args: Args) => R {\n return (...args: Args): R => {\n return store.run<any, any>(\n {\n initialHandlers: this.handlersController.currentHandlers(),\n handlers: [],\n },\n callback,\n ...args,\n )\n }\n }\n\n public close(): void {\n super.close()\n store.disable()\n }\n}\n","/**\n * @note This API is extended by both \"msw/node\" and \"msw/native\"\n * so be minding about the things you import!\n */\nimport type { RequiredDeep } from 'type-fest'\nimport { invariant } from 'outvariant'\nimport {\n BatchInterceptor,\n InterceptorReadyState,\n type HttpRequestEventMap,\n type Interceptor,\n} from '@mswjs/interceptors'\nimport type { LifeCycleEventsMap, SharedOptions } from '~/core/sharedOptions'\nimport { SetupApi } from '~/core/SetupApi'\nimport { handleRequest } from '~/core/utils/handleRequest'\nimport type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport { mergeRight } from '~/core/utils/internal/mergeRight'\nimport { InternalError, devUtils } from '~/core/utils/internal/devUtils'\nimport type { SetupServerCommon } from './glossary'\nimport { handleWebSocketEvent } from '~/core/ws/handleWebSocketEvent'\nimport { webSocketInterceptor } from '~/core/ws/webSocketInterceptor'\nimport { isHandlerKind } from '~/core/utils/internal/isHandlerKind'\n\nexport const DEFAULT_LISTEN_OPTIONS: RequiredDeep<SharedOptions> = {\n onUnhandledRequest: 'warn',\n}\n\nexport class SetupServerCommonApi\n extends SetupApi<LifeCycleEventsMap>\n implements SetupServerCommon\n{\n protected readonly interceptor: BatchInterceptor<\n Array<Interceptor<HttpRequestEventMap>>,\n HttpRequestEventMap\n >\n private resolvedOptions: RequiredDeep<SharedOptions>\n\n constructor(\n interceptors: Array<{ new (): Interceptor<HttpRequestEventMap> }>,\n handlers: Array<RequestHandler | WebSocketHandler>,\n ) {\n super(...handlers)\n\n this.interceptor = new BatchInterceptor({\n name: 'setup-server',\n interceptors: interceptors.map((Interceptor) => new Interceptor()),\n })\n\n this.resolvedOptions = {} as RequiredDeep<SharedOptions>\n\n this.init()\n }\n\n /**\n * Subscribe to all requests that are using the interceptor object\n */\n private init(): void {\n this.interceptor.on(\n 'request',\n async ({ request, requestId, controller }) => {\n const response = await handleRequest(\n request,\n requestId,\n this.handlersController\n .currentHandlers()\n .filter(isHandlerKind('RequestHandler')),\n this.resolvedOptions,\n this.emitter,\n {\n onPassthroughResponse(request) {\n const acceptHeader = request.headers.get('accept')\n\n /**\n * @note Remove the internal bypass request header.\n * In the browser, this is done by the worker script.\n * In Node.js, it has to be done here.\n */\n if (acceptHeader) {\n const nextAcceptHeader = acceptHeader.replace(\n /(,\\s+)?msw\\/passthrough/,\n '',\n )\n\n if (nextAcceptHeader) {\n request.headers.set('accept', nextAcceptHeader)\n } else {\n request.headers.delete('accept')\n }\n }\n },\n },\n )\n\n if (response) {\n controller.respondWith(response)\n }\n\n return\n },\n )\n\n this.interceptor.on('unhandledException', ({ error }) => {\n if (error instanceof InternalError) {\n throw error\n }\n })\n\n this.interceptor.on(\n 'response',\n ({ response, isMockedResponse, request, requestId }) => {\n this.emitter.emit(\n isMockedResponse ? 'response:mocked' : 'response:bypass',\n {\n response,\n request,\n requestId,\n },\n )\n },\n )\n\n // Preconfigure the WebSocket interception but don't enable it just yet.\n // It will be enabled when the server starts.\n handleWebSocketEvent({\n getUnhandledRequestStrategy: () => {\n return this.resolvedOptions.onUnhandledRequest\n },\n getHandlers: () => {\n return this.handlersController.currentHandlers()\n },\n onMockedConnection: () => {},\n onPassthroughConnection: () => {},\n })\n }\n\n public listen(options: Partial<SharedOptions> = {}): void {\n this.resolvedOptions = mergeRight(\n DEFAULT_LISTEN_OPTIONS,\n options,\n ) as RequiredDeep<SharedOptions>\n\n // Apply the interceptor when starting the server.\n this.interceptor.apply()\n this.subscriptions.push(() => this.interceptor.dispose())\n\n // Apply the WebSocket interception.\n webSocketInterceptor.apply()\n this.subscriptions.push(() => webSocketInterceptor.dispose())\n\n // Assert that the interceptor has been applied successfully.\n // Also guards us from forgetting to call \"interceptor.apply()\"\n // as a part of the \"listen\" method.\n invariant(\n [InterceptorReadyState.APPLYING, InterceptorReadyState.APPLIED].includes(\n this.interceptor.readyState,\n ),\n devUtils.formatMessage(\n 'Failed to start \"setupServer\": the interceptor failed to apply. This is likely an issue with the library and you should report it at \"%s\".',\n ),\n 'https://github.com/mswjs/msw/issues/new/choose',\n )\n }\n\n public close(): void {\n this.dispose()\n }\n}\n","import type { RequestHandler } from '~/core/handlers/RequestHandler'\nimport type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'\nimport { SetupServerApi } from './SetupServerApi'\n\n/**\n * Sets up a requests interception in Node.js with the given request handlers.\n * @param {RequestHandler[]} handlers List of request handlers.\n *\n * @see {@link https://mswjs.io/docs/api/setup-server `setupServer()` API reference}\n */\nexport const setupServer = (\n ...handlers: Array<RequestHandler | WebSocketHandler>\n): SetupServerApi => {\n return new SetupServerApi(handlers)\n}\n"],"mappings":";AAAA,SAAS,yBAAyB;AAClC,SAAS,gCAAgC;AACzC,SAAS,iCAAiC;AAC1C,SAAS,wBAAwB;;;ACEjC,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAEP,SAAS,gBAAgB;AACzB,SAAS,qBAAqB;AAG9B,SAAS,kBAAkB;AAC3B,SAAS,eAAe,gBAAgB;AAExC,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAA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ACnE,UAAM,UAAU,KAAK;AACrB,YAAQ,WAAW,CAAC;AACpB,YAAQ,kBACN,aAAa,SAAS,IAAI,eAAe,QAAQ;AAAA,EACrD;AAAA,EAEO,kBAA4D;AACjE,UAAM,EAAE,iBAAiB,SAAS,IAAI,KAAK;AAC3C,WAAO,SAAS,OAAO,eAAe;AAAA,EACxC;AACF;AAEO,IAAM,iBAAN,cACG,qBAEV;AAAA,EACE,YAAY,UAAoD;AAC9D;AAAA,MACE,CAAC,0BAA0B,2BAA2B,gBAAgB;AAAA,MACtE;AAAA,IACF;AAEA,SAAK,qBAAqB,IAAI,wBAAwB,QAAQ;AAAA,EAChE;AAAA,EAEO,SACL,UACsB;AACtB,WAAO,IAAI,SAAkB;AAC3B,aAAO,MAAM;AAAA,QACX;AAAA,UACE,iBAAiB,KAAK,mBAAmB,gBAAgB;AAAA,UACzD,UAAU,CAAC;AAAA,QACb;AAAA,QACA;AAAA,QACA,GAAG;AAAA,MACL;AAAA,IACF;AAAA,EACF;AAAA,EAEO,QAAc;AACnB,UAAM,MAAM;AACZ,UAAM,QAAQ;AAAA,EAChB;AACF;;;AExEO,IAAM,cAAc,IACtB,aACgB;AACnB,SAAO,IAAI,eAAe,QAAQ;AACpC;","names":["request"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "msw",
3
- "version": "2.6.3",
3
+ "version": "2.6.5",
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",
@@ -123,7 +123,7 @@
123
123
  "@bundled-es-modules/statuses": "^1.0.1",
124
124
  "@bundled-es-modules/tough-cookie": "^0.1.6",
125
125
  "@inquirer/confirm": "^5.0.0",
126
- "@mswjs/interceptors": "^0.36.5",
126
+ "@mswjs/interceptors": "^0.37.0",
127
127
  "@open-draft/deferred-promise": "^2.2.0",
128
128
  "@open-draft/until": "^2.1.0",
129
129
  "@types/cookie": "^0.6.0",
@@ -1,9 +1,9 @@
1
+ import { FetchResponse } from '@mswjs/interceptors'
1
2
  import type {
2
3
  ServiceWorkerIncomingEventsMap,
3
4
  SetupWorkerInternalContext,
4
5
  } from '../glossary'
5
6
  import type { ServiceWorkerMessage } from './utils/createMessageChannel'
6
- import { isResponseWithoutBody } from '@mswjs/interceptors'
7
7
 
8
8
  export function createResponseListener(context: SetupWorkerInternalContext) {
9
9
  return (
@@ -35,32 +35,27 @@ export function createResponseListener(context: SetupWorkerInternalContext) {
35
35
  const response =
36
36
  responseJson.status === 0
37
37
  ? Response.error()
38
- : new Response(
38
+ : new FetchResponse(
39
39
  /**
40
40
  * Responses may be streams here, but when we create a response object
41
41
  * with null-body status codes, like 204, 205, 304 Response will
42
42
  * throw when passed a non-null body, so ensure it's null here
43
43
  * for those codes
44
44
  */
45
- isResponseWithoutBody(responseJson.status)
46
- ? null
47
- : responseJson.body,
48
- responseJson,
45
+ FetchResponse.isResponseWithBody(responseJson.status)
46
+ ? responseJson.body
47
+ : null,
48
+ {
49
+ ...responseJson,
50
+ /**
51
+ * Set response URL if it's not set already.
52
+ * @see https://github.com/mswjs/msw/issues/2030
53
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/url
54
+ */
55
+ url: request.url,
56
+ },
49
57
  )
50
58
 
51
- /**
52
- * Set response URL if it's not set already.
53
- * @see https://github.com/mswjs/msw/issues/2030
54
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/url
55
- */
56
- if (!response.url) {
57
- Object.defineProperty(response, 'url', {
58
- value: request.url,
59
- enumerable: true,
60
- writable: false,
61
- })
62
- }
63
-
64
59
  context.emitter.emit(
65
60
  responseJson.isMockedResponse ? 'response:mocked' : 'response:bypass',
66
61
  {
@@ -9,24 +9,21 @@ it('returns bypassed request given a request url string', async () => {
9
9
  // Relative URLs are rebased against the current location.
10
10
  expect(request.method).toBe('GET')
11
11
  expect(request.url).toBe('https://api.example.com/resource')
12
- expect(Object.fromEntries(request.headers.entries())).toEqual({
13
- 'x-msw-intention': 'bypass',
14
- })
12
+ expect(Array.from(request.headers)).toEqual([['accept', 'msw/passthrough']])
15
13
  })
16
14
 
17
15
  it('returns bypassed request given a request url', async () => {
18
16
  const request = bypass(new URL('/resource', 'https://api.example.com'))
19
17
 
20
18
  expect(request.url).toBe('https://api.example.com/resource')
21
- expect(Object.fromEntries(request.headers)).toEqual({
22
- 'x-msw-intention': 'bypass',
23
- })
19
+ expect(Array.from(request.headers)).toEqual([['accept', 'msw/passthrough']])
24
20
  })
25
21
 
26
22
  it('returns bypassed request given request instance', async () => {
27
23
  const original = new Request('http://localhost/resource', {
28
24
  method: 'POST',
29
25
  headers: {
26
+ accept: '*/*',
30
27
  'X-My-Header': 'value',
31
28
  },
32
29
  body: 'hello world',
@@ -40,10 +37,11 @@ it('returns bypassed request given request instance', async () => {
40
37
  expect(original.bodyUsed).toBe(false)
41
38
 
42
39
  expect(bypassedRequestBody).toEqual(await original.text())
43
- expect(Object.fromEntries(request.headers.entries())).toEqual({
44
- ...Object.fromEntries(original.headers.entries()),
45
- 'x-msw-intention': 'bypass',
46
- })
40
+ expect(Array.from(request.headers)).toEqual([
41
+ ['accept', '*/*, msw/passthrough'],
42
+ ['content-type', 'text/plain;charset=UTF-8'],
43
+ ['x-my-header', 'value'],
44
+ ])
47
45
  })
48
46
 
49
47
  it('allows modifying the bypassed request instance', async () => {
@@ -57,13 +55,26 @@ it('allows modifying the bypassed request instance', async () => {
57
55
  })
58
56
 
59
57
  expect(request.method).toBe('PUT')
60
- expect(Object.fromEntries(request.headers.entries())).toEqual({
61
- 'x-msw-intention': 'bypass',
62
- 'x-modified-header': 'yes',
63
- })
58
+ expect(Array.from(request.headers)).toEqual([
59
+ ['accept', 'msw/passthrough'],
60
+ ['x-modified-header', 'yes'],
61
+ ])
64
62
  expect(original.bodyUsed).toBe(false)
65
63
  expect(request.bodyUsed).toBe(false)
66
64
 
67
65
  expect(await request.text()).toBe('hello world')
68
66
  expect(original.bodyUsed).toBe(false)
69
67
  })
68
+
69
+ it('supports bypassing "keepalive: true" requests', async () => {
70
+ const original = new Request('http://localhost/resource', {
71
+ method: 'POST',
72
+ keepalive: true,
73
+ })
74
+ const request = bypass(original)
75
+
76
+ expect(request.method).toBe('POST')
77
+ expect(request.url).toBe('http://localhost/resource')
78
+ expect(request.body).toBeNull()
79
+ expect(Array.from(request.headers)).toEqual([['accept', 'msw/passthrough']])
80
+ })
@@ -34,11 +34,13 @@ export function bypass(input: BypassRequestInput, init?: RequestInit): Request {
34
34
 
35
35
  const requestClone = request.clone()
36
36
 
37
- // Set the internal header that would instruct MSW
38
- // to bypass this request from any further request matching.
39
- // Unlike "passthrough()", bypass is meant for performing
40
- // additional requests within pending request resolution.
41
- requestClone.headers.set('x-msw-intention', 'bypass')
37
+ /**
38
+ * Send the internal request header that would instruct MSW
39
+ * to perform this request as-is, ignoring any matching handlers.
40
+ * @note Use the `accept` header to support scenarios when the
41
+ * request cannot have headers (e.g. `sendBeacon` requests).
42
+ */
43
+ requestClone.headers.append('accept', 'msw/passthrough')
42
44
 
43
45
  return requestClone
44
46
  }
@@ -1,6 +1,4 @@
1
- /**
2
- * @vitest-environment node
3
- */
1
+ // @vitest-environment node
4
2
  import { passthrough } from './passthrough'
5
3
 
6
4
  it('creates a 302 response with the intention header', () => {
@@ -46,13 +46,13 @@ afterEach(() => {
46
46
  vi.resetAllMocks()
47
47
  })
48
48
 
49
- test('returns undefined for a request with the "x-msw-intention" header equal to "bypass"', async () => {
49
+ test('returns undefined for a request with the "accept: msw/passthrough" header equal to "bypass"', async () => {
50
50
  const { emitter, events } = setup()
51
51
 
52
52
  const requestId = createRequestId()
53
53
  const request = new Request(new URL('http://localhost/user'), {
54
54
  headers: new Headers({
55
- 'x-msw-intention': 'bypass',
55
+ accept: 'msw/passthrough',
56
56
  }),
57
57
  })
58
58
  const handlers: Array<RequestHandler> = []
@@ -79,12 +79,12 @@ test('returns undefined for a request with the "x-msw-intention" header equal to
79
79
  expect(handleRequestOptions.onMockedResponse).not.toHaveBeenCalled()
80
80
  })
81
81
 
82
- test('does not bypass a request with "x-msw-intention" header set to arbitrary value', async () => {
82
+ test('does not bypass a request with "accept: msw/*" header set to arbitrary value', async () => {
83
83
  const { emitter } = setup()
84
84
 
85
85
  const request = new Request(new URL('http://localhost/user'), {
86
86
  headers: new Headers({
87
- 'x-msw-intention': 'invalid',
87
+ acceot: 'msw/invalid',
88
88
  }),
89
89
  })
90
90
  const handlers: Array<RequestHandler> = [
@@ -46,8 +46,8 @@ export async function handleRequest(
46
46
  ): Promise<Response | undefined> {
47
47
  emitter.emit('request:start', { request, requestId })
48
48
 
49
- // Perform bypassed requests (i.e. wrapped in "bypass()") as-is.
50
- if (request.headers.get('x-msw-intention') === 'bypass') {
49
+ // Perform requests wrapped in "bypass()" as-is.
50
+ if (request.headers.get('accept')?.includes('msw/passthrough')) {
51
51
  emitter.emit('request:end', { request, requestId })
52
52
  handleRequestOptions?.onPassthroughResponse?.(request)
53
53
  return
@@ -192,12 +192,14 @@ async function getResponse(event, client, requestId) {
192
192
  const requestClone = request.clone()
193
193
 
194
194
  function passthrough() {
195
- const headers = Object.fromEntries(requestClone.headers.entries())
196
-
197
- // Remove internal MSW request header so the passthrough request
198
- // complies with any potential CORS preflight checks on the server.
199
- // Some servers forbid unknown request headers.
200
- delete headers['x-msw-intention']
195
+ // Cast the request headers to a new Headers instance
196
+ // so the headers can be manipulated with.
197
+ const headers = new Headers(requestClone.headers)
198
+
199
+ // Remove the "accept" header value that marked this request as passthrough.
200
+ // This prevents request alteration and also keeps it compliant with the
201
+ // user-defined CORS policies.
202
+ headers.delete('accept', 'msw/passthrough')
201
203
 
202
204
  return fetch(requestClone, { headers })
203
205
  }
@@ -67,6 +67,29 @@ export class SetupServerCommonApi
67
67
  .filter(isHandlerKind('RequestHandler')),
68
68
  this.resolvedOptions,
69
69
  this.emitter,
70
+ {
71
+ onPassthroughResponse(request) {
72
+ const acceptHeader = request.headers.get('accept')
73
+
74
+ /**
75
+ * @note Remove the internal bypass request header.
76
+ * In the browser, this is done by the worker script.
77
+ * In Node.js, it has to be done here.
78
+ */
79
+ if (acceptHeader) {
80
+ const nextAcceptHeader = acceptHeader.replace(
81
+ /(,\s+)?msw\/passthrough/,
82
+ '',
83
+ )
84
+
85
+ if (nextAcceptHeader) {
86
+ request.headers.set('accept', nextAcceptHeader)
87
+ } else {
88
+ request.headers.delete('accept')
89
+ }
90
+ }
91
+ },
92
+ },
70
93
  )
71
94
 
72
95
  if (response) {