msw 2.10.5 → 2.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/lib/browser/index.js.map +1 -1
  2. package/lib/browser/index.mjs.map +1 -1
  3. package/lib/core/{HttpResponse-CC5tPhLa.d.mts → HttpResponse-B4YmE-GJ.d.mts} +22 -8
  4. package/lib/core/{HttpResponse-CKZrrwKE.d.ts → HttpResponse-BbwAqLE_.d.ts} +22 -8
  5. package/lib/core/HttpResponse.d.mts +1 -1
  6. package/lib/core/HttpResponse.d.ts +1 -1
  7. package/lib/core/HttpResponse.js.map +1 -1
  8. package/lib/core/HttpResponse.mjs.map +1 -1
  9. package/lib/core/SetupApi.d.mts +1 -1
  10. package/lib/core/SetupApi.d.ts +1 -1
  11. package/lib/core/getResponse.d.mts +1 -1
  12. package/lib/core/getResponse.d.ts +1 -1
  13. package/lib/core/graphql.d.mts +2 -2
  14. package/lib/core/graphql.d.ts +2 -2
  15. package/lib/core/graphql.js +2 -8
  16. package/lib/core/graphql.js.map +1 -1
  17. package/lib/core/graphql.mjs +2 -8
  18. package/lib/core/graphql.mjs.map +1 -1
  19. package/lib/core/handlers/GraphQLHandler.d.mts +1 -1
  20. package/lib/core/handlers/GraphQLHandler.d.ts +1 -1
  21. package/lib/core/handlers/GraphQLHandler.js +36 -9
  22. package/lib/core/handlers/GraphQLHandler.js.map +1 -1
  23. package/lib/core/handlers/GraphQLHandler.mjs +36 -9
  24. package/lib/core/handlers/GraphQLHandler.mjs.map +1 -1
  25. package/lib/core/handlers/HttpHandler.d.mts +15 -5
  26. package/lib/core/handlers/HttpHandler.d.ts +15 -5
  27. package/lib/core/handlers/HttpHandler.js +21 -10
  28. package/lib/core/handlers/HttpHandler.js.map +1 -1
  29. package/lib/core/handlers/HttpHandler.mjs +21 -10
  30. package/lib/core/handlers/HttpHandler.mjs.map +1 -1
  31. package/lib/core/handlers/RequestHandler.d.mts +1 -1
  32. package/lib/core/handlers/RequestHandler.d.ts +1 -1
  33. package/lib/core/handlers/RequestHandler.js +1 -1
  34. package/lib/core/handlers/RequestHandler.js.map +1 -1
  35. package/lib/core/handlers/RequestHandler.mjs +1 -1
  36. package/lib/core/handlers/RequestHandler.mjs.map +1 -1
  37. package/lib/core/http.d.mts +4 -4
  38. package/lib/core/http.d.ts +4 -4
  39. package/lib/core/http.js +2 -2
  40. package/lib/core/http.js.map +1 -1
  41. package/lib/core/http.mjs +2 -2
  42. package/lib/core/http.mjs.map +1 -1
  43. package/lib/core/index.d.mts +2 -2
  44. package/lib/core/index.d.ts +2 -2
  45. package/lib/core/index.js.map +1 -1
  46. package/lib/core/index.mjs.map +1 -1
  47. package/lib/core/passthrough.d.mts +1 -1
  48. package/lib/core/passthrough.d.ts +1 -1
  49. package/lib/core/utils/HttpResponse/decorators.d.mts +1 -1
  50. package/lib/core/utils/HttpResponse/decorators.d.ts +1 -1
  51. package/lib/core/utils/cookieStore.d.mts +10 -2
  52. package/lib/core/utils/cookieStore.d.ts +10 -2
  53. package/lib/core/utils/cookieStore.js +49 -146
  54. package/lib/core/utils/cookieStore.js.map +1 -1
  55. package/lib/core/utils/cookieStore.mjs +53 -136
  56. package/lib/core/utils/cookieStore.mjs.map +1 -1
  57. package/lib/core/utils/executeHandlers.d.mts +1 -1
  58. package/lib/core/utils/executeHandlers.d.ts +1 -1
  59. package/lib/core/utils/handleRequest.d.mts +1 -1
  60. package/lib/core/utils/handleRequest.d.ts +1 -1
  61. package/lib/core/utils/handleRequest.js +1 -1
  62. package/lib/core/utils/handleRequest.js.map +1 -1
  63. package/lib/core/utils/handleRequest.mjs +1 -1
  64. package/lib/core/utils/handleRequest.mjs.map +1 -1
  65. package/lib/core/utils/internal/isHandlerKind.d.mts +1 -1
  66. package/lib/core/utils/internal/isHandlerKind.d.ts +1 -1
  67. package/lib/core/utils/internal/parseGraphQLRequest.d.mts +1 -1
  68. package/lib/core/utils/internal/parseGraphQLRequest.d.ts +1 -1
  69. package/lib/core/utils/internal/parseMultipartData.d.mts +1 -1
  70. package/lib/core/utils/internal/parseMultipartData.d.ts +1 -1
  71. package/lib/core/utils/internal/requestHandlerUtils.d.mts +1 -1
  72. package/lib/core/utils/internal/requestHandlerUtils.d.ts +1 -1
  73. package/lib/core/utils/request/getRequestCookies.js +1 -1
  74. package/lib/core/utils/request/getRequestCookies.js.map +1 -1
  75. package/lib/core/utils/request/getRequestCookies.mjs +1 -1
  76. package/lib/core/utils/request/getRequestCookies.mjs.map +1 -1
  77. package/lib/core/utils/request/storeResponseCookies.d.mts +1 -1
  78. package/lib/core/utils/request/storeResponseCookies.d.ts +1 -1
  79. package/lib/core/utils/request/storeResponseCookies.js +2 -2
  80. package/lib/core/utils/request/storeResponseCookies.js.map +1 -1
  81. package/lib/core/utils/request/storeResponseCookies.mjs +2 -2
  82. package/lib/core/utils/request/storeResponseCookies.mjs.map +1 -1
  83. package/lib/core/ws/handleWebSocketEvent.d.mts +1 -1
  84. package/lib/core/ws/handleWebSocketEvent.d.ts +1 -1
  85. package/lib/iife/index.js +2661 -12110
  86. package/lib/iife/index.js.map +1 -1
  87. package/lib/mockServiceWorker.js +1 -1
  88. package/lib/node/index.js.map +1 -1
  89. package/lib/node/index.mjs.map +1 -1
  90. package/package.json +4 -4
  91. package/src/browser/setupWorker/setupWorker.ts +1 -1
  92. package/src/core/HttpResponse.ts +3 -3
  93. package/src/core/graphql.ts +8 -12
  94. package/src/core/handlers/GraphQLHandler.test.ts +86 -51
  95. package/src/core/handlers/GraphQLHandler.ts +81 -17
  96. package/src/core/handlers/HttpHandler.test.ts +60 -30
  97. package/src/core/handlers/HttpHandler.ts +61 -12
  98. package/src/core/handlers/RequestHandler.ts +2 -2
  99. package/src/core/http.ts +5 -5
  100. package/src/core/index.ts +3 -0
  101. package/src/core/utils/cookieStore.ts +56 -198
  102. package/src/core/utils/handleRequest.test.ts +84 -0
  103. package/src/core/utils/handleRequest.ts +1 -1
  104. package/src/core/utils/request/getRequestCookies.ts +1 -1
  105. package/src/core/utils/request/storeResponseCookies.ts +3 -3
  106. package/src/core/utils/request/toPublicUrl.test.ts +1 -1
  107. package/src/core/ws/WebSocketClientManager.test.ts +1 -1
  108. package/src/node/SetupServerApi.ts +1 -1
@@ -7,7 +7,7 @@
7
7
  * - Please do NOT modify this file.
8
8
  */
9
9
 
10
- const PACKAGE_VERSION = '2.10.5'
10
+ const PACKAGE_VERSION = '2.11.1'
11
11
  const INTEGRITY_CHECKSUM = 'f5825c521429caf22a4dd13b66e243af'
12
12
  const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
13
13
  const activeClientIds = new Set()
@@ -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 type { HttpRequestEventMap, Interceptor } from '@mswjs/interceptors'\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}\nexport class SetupServerApi\n extends SetupServerCommonApi\n implements SetupServer\n{\n constructor(\n handlers: Array<RequestHandler | WebSocketHandler>,\n interceptors: Array<Interceptor<HttpRequestEventMap>> = [\n new ClientRequestInterceptor(),\n new XMLHttpRequestInterceptor(),\n new FetchInterceptor(),\n ],\n ) {\n super(interceptors, handlers)\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\nconst 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<Interceptor<HttpRequestEventMap>>,\n handlers: Array<RequestHandler | WebSocketHandler>,\n ) {\n super(...handlers)\n\n this.interceptor = new BatchInterceptor({\n name: 'setup-server',\n interceptors,\n })\n\n this.resolvedOptions = {} as RequiredDeep<SharedOptions>\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 // Attach the event listeners to the interceptor here\n // so they get re-attached whenever `.listen()` is called.\n this.interceptor.apply()\n this.init()\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;AAA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,UAAkC;AACpC,WAAO,MAAM,SAAS,KAAK,KAAK;AAAA,EAClC;AAAA,EAEO,QAAQ,iBAA2D;AACxE,SAAK,QAAQ,SAAS,QAAQ,GAAG,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;AACO,IAAM,iBAAN,cACG,qBAEV;AAAA,EACE,YACE,UACA,eAAwD;AAAA,IACtD,IAAI,8CAAyB;AAAA,IAC7B,IAAI,gDAA0B;AAAA,IAC9B,IAAI,8BAAiB;AAAA,EACvB,GACA;AACA,UAAM,cAAc,QAAQ;AAE5B,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;;;AE5EO,IAAM,cAAc,IACtB,aACgB;AACnB,SAAO,IAAI,eAAe,QAAQ;AACpC;","names":["request"]}
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 type { HttpRequestEventMap, Interceptor } from '@mswjs/interceptors'\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 multiple 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}\nexport class SetupServerApi\n extends SetupServerCommonApi\n implements SetupServer\n{\n constructor(\n handlers: Array<RequestHandler | WebSocketHandler>,\n interceptors: Array<Interceptor<HttpRequestEventMap>> = [\n new ClientRequestInterceptor(),\n new XMLHttpRequestInterceptor(),\n new FetchInterceptor(),\n ],\n ) {\n super(interceptors, handlers)\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\nconst 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<Interceptor<HttpRequestEventMap>>,\n handlers: Array<RequestHandler | WebSocketHandler>,\n ) {\n super(...handlers)\n\n this.interceptor = new BatchInterceptor({\n name: 'setup-server',\n interceptors,\n })\n\n this.resolvedOptions = {} as RequiredDeep<SharedOptions>\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 // Attach the event listeners to the interceptor here\n // so they get re-attached whenever `.listen()` is called.\n this.interceptor.apply()\n this.init()\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;AAElC,2BAAyC;AACzC,4BAA0C;AAC1C,mBAAiC;;;ACCjC,wBAA0B;AAC1B,0BAKO;AAEP,sBAAyB;AACzB,2BAA8B;AAG9B,wBAA2B;AAC3B,sBAAwC;AAExC,kCAAqC;AACrC,kCAAqC;AACrC,2BAA8B;AAE9B,IAAM,yBAAsD;AAAA,EAC1D,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;AAAA,IACF,CAAC;AAED,SAAK,kBAAkB,CAAC;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA,EAKQ,OAAa;AACnB,SAAK,YAAY;AAAA,MACf;AAAA,MACA,OAAO,EAAE,SAAS,WAAW,WAAW,MAAM;AAC5C,cAAM,WAAW,UAAM;AAAA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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;;;AE5EO,IAAM,cAAc,IACtB,aACgB;AACnB,SAAO,IAAI,eAAe,QAAQ;AACpC;","names":["request"]}
@@ -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 type { HttpRequestEventMap, Interceptor } from '@mswjs/interceptors'\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}\nexport class SetupServerApi\n extends SetupServerCommonApi\n implements SetupServer\n{\n constructor(\n handlers: Array<RequestHandler | WebSocketHandler>,\n interceptors: Array<Interceptor<HttpRequestEventMap>> = [\n new ClientRequestInterceptor(),\n new XMLHttpRequestInterceptor(),\n new FetchInterceptor(),\n ],\n ) {\n super(interceptors, handlers)\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\nconst 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<Interceptor<HttpRequestEventMap>>,\n handlers: Array<RequestHandler | WebSocketHandler>,\n ) {\n super(...handlers)\n\n this.interceptor = new BatchInterceptor({\n name: 'setup-server',\n interceptors,\n })\n\n this.resolvedOptions = {} as RequiredDeep<SharedOptions>\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 // Attach the event listeners to the interceptor here\n // so they get re-attached whenever `.listen()` is called.\n this.interceptor.apply()\n this.init()\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;AAElC,SAAS,gCAAgC;AACzC,SAAS,iCAAiC;AAC1C,SAAS,wBAAwB;;;ACCjC,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,OAGK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iBAA2D;AACxE,SAAK,QAAQ,SAAS,QAAQ,GAAG,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;AACO,IAAM,iBAAN,cACG,qBAEV;AAAA,EACE,YACE,UACA,eAAwD;AAAA,IACtD,IAAI,yBAAyB;AAAA,IAC7B,IAAI,0BAA0B;AAAA,IAC9B,IAAI,iBAAiB;AAAA,EACvB,GACA;AACA,UAAM,cAAc,QAAQ;AAE5B,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;;;AE5EO,IAAM,cAAc,IACtB,aACgB;AACnB,SAAO,IAAI,eAAe,QAAQ;AACpC;","names":["request"]}
1
+ {"version":3,"sources":["../../src/node/SetupServerApi.ts","../../src/node/SetupServerCommonApi.ts","../../src/node/setupServer.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { HttpRequestEventMap, Interceptor } from '@mswjs/interceptors'\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 multiple 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}\nexport class SetupServerApi\n extends SetupServerCommonApi\n implements SetupServer\n{\n constructor(\n handlers: Array<RequestHandler | WebSocketHandler>,\n interceptors: Array<Interceptor<HttpRequestEventMap>> = [\n new ClientRequestInterceptor(),\n new XMLHttpRequestInterceptor(),\n new FetchInterceptor(),\n ],\n ) {\n super(interceptors, handlers)\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\nconst 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<Interceptor<HttpRequestEventMap>>,\n handlers: Array<RequestHandler | WebSocketHandler>,\n ) {\n super(...handlers)\n\n this.interceptor = new BatchInterceptor({\n name: 'setup-server',\n interceptors,\n })\n\n this.resolvedOptions = {} as RequiredDeep<SharedOptions>\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 // Attach the event listeners to the interceptor here\n // so they get re-attached whenever `.listen()` is called.\n this.interceptor.apply()\n this.init()\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;AAElC,SAAS,gCAAgC;AACzC,SAAS,iCAAiC;AAC1C,SAAS,wBAAwB;;;ACCjC,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;AAE9B,IAAM,yBAAsD;AAAA,EAC1D,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;AAAA,IACF,CAAC;AAED,SAAK,kBAAkB,CAAC;AAAA,EAC1B;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;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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;;;AE5EO,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.10.5",
3
+ "version": "2.11.1",
4
4
  "description": "Seamless REST/GraphQL API mocking library for browser and Node.js.",
5
5
  "type": "commonjs",
6
6
  "main": "./lib/core/index.js",
@@ -216,7 +216,6 @@
216
216
  "dependencies": {
217
217
  "@bundled-es-modules/cookie": "^2.0.1",
218
218
  "@bundled-es-modules/statuses": "^1.0.1",
219
- "@bundled-es-modules/tough-cookie": "^0.1.6",
220
219
  "@inquirer/confirm": "^5.0.0",
221
220
  "@mswjs/interceptors": "^0.39.1",
222
221
  "@open-draft/deferred-promise": "^2.2.0",
@@ -230,6 +229,7 @@
230
229
  "path-to-regexp": "^6.3.0",
231
230
  "picocolors": "^1.1.1",
232
231
  "strict-event-emitter": "^0.5.1",
232
+ "tough-cookie": "^6.0.0",
233
233
  "type-fest": "^4.26.1",
234
234
  "yargs": "^17.7.2"
235
235
  },
@@ -273,14 +273,14 @@
273
273
  "rimraf": "^6.0.1",
274
274
  "simple-git-hooks": "^2.9.0",
275
275
  "tsup": "^8.4.0",
276
- "typescript": "^5.5.2",
276
+ "typescript": "^5.9.2",
277
277
  "undici": "^6.20.0",
278
278
  "url-loader": "^4.1.1",
279
279
  "vitest": "^3.1.4",
280
280
  "vitest-environment-miniflare": "^2.14.4",
281
281
  "webpack": "^5.95.0",
282
282
  "webpack-http-server": "^0.5.0",
283
- "msw": "2.10.5"
283
+ "msw": "2.11.1"
284
284
  },
285
285
  "peerDependencies": {
286
286
  "typescript": ">= 4.8.x"
@@ -7,6 +7,7 @@ import {
7
7
  StopHandler,
8
8
  StartHandler,
9
9
  StartOptions,
10
+ SetupWorker,
10
11
  } from './glossary'
11
12
  import { createStartHandler } from './start/createStartHandler'
12
13
  import { createStop } from './stop/createStop'
@@ -20,7 +21,6 @@ import { SetupApi } from '~/core/SetupApi'
20
21
  import { mergeRight } from '~/core/utils/internal/mergeRight'
21
22
  import type { LifeCycleEventsMap } from '~/core/sharedOptions'
22
23
  import type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'
23
- import { SetupWorker } from './glossary'
24
24
  import { supportsReadableStreamTransfer } from '../utils/supportsReadableStreamTransfer'
25
25
  import { webSocketInterceptor } from '~/core/ws/webSocketInterceptor'
26
26
  import { handleWebSocketEvent } from '~/core/ws/handleWebSocketEvent'
@@ -161,10 +161,10 @@ export class HttpResponse<
161
161
  *
162
162
  * HttpResponse.arrayBuffer(buffer)
163
163
  */
164
- static arrayBuffer(
165
- body?: ArrayBuffer | SharedArrayBuffer,
164
+ static arrayBuffer<BodyType extends ArrayBuffer | SharedArrayBuffer>(
165
+ body?: BodyType,
166
166
  init?: HttpResponseInit,
167
- ): HttpResponse<ArrayBuffer | SharedArrayBuffer> {
167
+ ): HttpResponse<BodyType> {
168
168
  const responseInit = normalizeResponseInit(init)
169
169
 
170
170
  if (!responseInit.headers.has('Content-Type')) {
@@ -6,11 +6,12 @@ import {
6
6
  import {
7
7
  GraphQLHandler,
8
8
  GraphQLVariables,
9
- ExpectedOperationTypeNode,
9
+ GraphQLOperationType,
10
10
  GraphQLHandlerNameSelector,
11
11
  GraphQLResolverExtras,
12
12
  GraphQLResponseBody,
13
13
  GraphQLQuery,
14
+ GraphQLCustomPredicate,
14
15
  } from './handlers/GraphQLHandler'
15
16
  import type { Path } from './utils/matching/matchRequestUrl'
16
17
 
@@ -27,10 +28,11 @@ export type GraphQLRequestHandler = <
27
28
  Query extends GraphQLQuery = GraphQLQuery,
28
29
  Variables extends GraphQLVariables = GraphQLVariables,
29
30
  >(
30
- operationName:
31
+ predicate:
31
32
  | GraphQLHandlerNameSelector
32
33
  | DocumentNode
33
- | TypedDocumentNode<Query, Variables>,
34
+ | TypedDocumentNode<Query, Variables>
35
+ | GraphQLCustomPredicate,
34
36
  resolver: GraphQLResponseResolver<
35
37
  [Query] extends [never] ? GraphQLQuery : Query,
36
38
  Variables
@@ -48,17 +50,11 @@ export type GraphQLResponseResolver<
48
50
  >
49
51
 
50
52
  function createScopedGraphQLHandler(
51
- operationType: ExpectedOperationTypeNode,
53
+ operationType: GraphQLOperationType,
52
54
  url: Path,
53
55
  ): GraphQLRequestHandler {
54
- return (operationName, resolver, options = {}) => {
55
- return new GraphQLHandler(
56
- operationType,
57
- operationName,
58
- url,
59
- resolver,
60
- options,
61
- )
56
+ return (predicate, resolver, options = {}) => {
57
+ return new GraphQLHandler(operationType, predicate, url, resolver, options)
62
58
  }
63
59
  }
64
60
 
@@ -1,6 +1,4 @@
1
- /**
2
- * @vitest-environment jsdom
3
- */
1
+ // @vitest-environment jsdom
4
2
  import { createRequestId, encodeBuffer } from '@mswjs/interceptors'
5
3
  import { OperationTypeNode, parse } from 'graphql'
6
4
  import {
@@ -62,7 +60,7 @@ const LOGIN = `
62
60
  `
63
61
 
64
62
  describe('info', () => {
65
- test('exposes request handler information for query', () => {
63
+ it('exposes request handler information for query', () => {
66
64
  const handler = new GraphQLHandler(
67
65
  OperationTypeNode.QUERY,
68
66
  'GetUser',
@@ -75,7 +73,7 @@ describe('info', () => {
75
73
  expect(handler.info.operationName).toEqual('GetUser')
76
74
  })
77
75
 
78
- test('exposes request handler information for mutation', () => {
76
+ it('exposes request handler information for mutation', () => {
79
77
  const handler = new GraphQLHandler(
80
78
  OperationTypeNode.MUTATION,
81
79
  'Login',
@@ -88,7 +86,7 @@ describe('info', () => {
88
86
  expect(handler.info.operationName).toEqual('Login')
89
87
  })
90
88
 
91
- test('parses a query operation name from a given DocumentNode', () => {
89
+ it('parses a query operation name from a given DocumentNode', () => {
92
90
  const node = parse(`
93
91
  query GetUser {
94
92
  user {
@@ -109,7 +107,7 @@ describe('info', () => {
109
107
  expect(handler.info).toHaveProperty('operationName', 'GetUser')
110
108
  })
111
109
 
112
- test('parses a mutation operation name from a given DocumentNode', () => {
110
+ it('parses a mutation operation name from a given DocumentNode', () => {
113
111
  const node = parse(`
114
112
  mutation Login {
115
113
  user {
@@ -129,7 +127,7 @@ describe('info', () => {
129
127
  expect(handler.info).toHaveProperty('operationName', 'Login')
130
128
  })
131
129
 
132
- test('throws an exception given a DocumentNode with a mismatched operation type', () => {
130
+ it('throws an exception given a DocumentNode with a mismatched operation type', () => {
133
131
  const node = parse(`
134
132
  mutation CreateUser {
135
133
  user {
@@ -148,7 +146,7 @@ describe('info', () => {
148
146
 
149
147
  describe('parse', () => {
150
148
  describe('query', () => {
151
- test('parses a query without variables (GET)', async () => {
149
+ it('parses a query without variables (GET)', async () => {
152
150
  const handler = new GraphQLHandler(
153
151
  OperationTypeNode.QUERY,
154
152
  'GetUser',
@@ -174,7 +172,7 @@ describe('parse', () => {
174
172
  })
175
173
  })
176
174
 
177
- test('parses a query with variables (GET)', async () => {
175
+ it('parses a query with variables (GET)', async () => {
178
176
  const handler = new GraphQLHandler(
179
177
  OperationTypeNode.QUERY,
180
178
  'GetUser',
@@ -205,7 +203,7 @@ describe('parse', () => {
205
203
  })
206
204
  })
207
205
 
208
- test('parses a query without variables (POST)', async () => {
206
+ it('parses a query without variables (POST)', async () => {
209
207
  const handler = new GraphQLHandler(
210
208
  OperationTypeNode.QUERY,
211
209
  'GetUser',
@@ -231,7 +229,7 @@ describe('parse', () => {
231
229
  })
232
230
  })
233
231
 
234
- test('parses a query with variables (POST)', async () => {
232
+ it('parses a query with variables (POST)', async () => {
235
233
  const handler = new GraphQLHandler(
236
234
  OperationTypeNode.QUERY,
237
235
  'GetUser',
@@ -264,7 +262,7 @@ describe('parse', () => {
264
262
  })
265
263
 
266
264
  describe('mutation', () => {
267
- test('parses a mutation without variables (GET)', async () => {
265
+ it('parses a mutation without variables (GET)', async () => {
268
266
  const handler = new GraphQLHandler(
269
267
  OperationTypeNode.MUTATION,
270
268
  'GetUser',
@@ -290,7 +288,7 @@ describe('parse', () => {
290
288
  })
291
289
  })
292
290
 
293
- test('parses a mutation with variables (GET)', async () => {
291
+ it('parses a mutation with variables (GET)', async () => {
294
292
  const handler = new GraphQLHandler(
295
293
  OperationTypeNode.MUTATION,
296
294
  'GetUser',
@@ -321,7 +319,7 @@ describe('parse', () => {
321
319
  })
322
320
  })
323
321
 
324
- test('parses a mutation without variables (POST)', async () => {
322
+ it('parses a mutation without variables (POST)', async () => {
325
323
  const handler = new GraphQLHandler(
326
324
  OperationTypeNode.MUTATION,
327
325
  'GetUser',
@@ -347,7 +345,7 @@ describe('parse', () => {
347
345
  })
348
346
  })
349
347
 
350
- test('parses a mutation with variables (POST)', async () => {
348
+ it('parses a mutation with variables (POST)', async () => {
351
349
  const handler = new GraphQLHandler(
352
350
  OperationTypeNode.MUTATION,
353
351
  'GetUser',
@@ -380,7 +378,7 @@ describe('parse', () => {
380
378
  })
381
379
 
382
380
  describe('with endpoint configuration', () => {
383
- test('parses the request and parses grapqhl properties from it when the graphql.link endpoint matches', async () => {
381
+ it('parses the request and parses grapqhl properties from it when the graphql.link endpoint matches', async () => {
384
382
  const handler = new GraphQLHandler(
385
383
  OperationTypeNode.QUERY,
386
384
  'GetUser',
@@ -441,7 +439,7 @@ describe('parse', () => {
441
439
  })
442
440
  })
443
441
 
444
- test('parses a request but does not parse graphql properties from it graphql.link hostname does not match', async () => {
442
+ it('parses a request but does not parse graphql properties from it graphql.link hostname does not match', async () => {
445
443
  const handler = new GraphQLHandler(
446
444
  OperationTypeNode.QUERY,
447
445
  'GetUser',
@@ -490,7 +488,7 @@ describe('parse', () => {
490
488
  })
491
489
  })
492
490
 
493
- test('parses a request but does not parse graphql properties from it graphql.link pathname does not match', async () => {
491
+ it('parses a request but does not parse graphql properties from it graphql.link pathname does not match', async () => {
494
492
  const handler = new GraphQLHandler(
495
493
  OperationTypeNode.QUERY,
496
494
  'GetUser',
@@ -542,7 +540,7 @@ describe('parse', () => {
542
540
  })
543
541
 
544
542
  describe('predicate', () => {
545
- test('respects operation type', async () => {
543
+ it('respects operation type', async () => {
546
544
  const handler = new GraphQLHandler(
547
545
  OperationTypeNode.QUERY,
548
546
  'GetUser',
@@ -557,20 +555,20 @@ describe('predicate', () => {
557
555
  })
558
556
 
559
557
  expect(
560
- handler.predicate({
558
+ await handler.predicate({
561
559
  request,
562
560
  parsedResult: await handler.parse({ request }),
563
561
  }),
564
562
  ).toBe(true)
565
563
  expect(
566
- handler.predicate({
564
+ await handler.predicate({
567
565
  request: alienRequest,
568
566
  parsedResult: await handler.parse({ request: alienRequest }),
569
567
  }),
570
568
  ).toBe(false)
571
569
  })
572
570
 
573
- test('respects operation name', async () => {
571
+ it('respects operation name', async () => {
574
572
  const handler = new GraphQLHandler(
575
573
  OperationTypeNode.QUERY,
576
574
  'GetUser',
@@ -590,21 +588,21 @@ describe('predicate', () => {
590
588
  `,
591
589
  })
592
590
 
593
- expect(
591
+ await expect(
594
592
  handler.predicate({
595
593
  request,
596
594
  parsedResult: await handler.parse({ request }),
597
595
  }),
598
- ).toBe(true)
599
- expect(
596
+ ).resolves.toBe(true)
597
+ await expect(
600
598
  handler.predicate({
601
599
  request: alienRequest,
602
600
  parsedResult: await handler.parse({ request: alienRequest }),
603
601
  }),
604
- ).toBe(false)
602
+ ).resolves.toBe(false)
605
603
  })
606
604
 
607
- test('allows anonymous GraphQL opertaions when using "all" expected operation type', async () => {
605
+ it('allows anonymous GraphQL operations when using "all" expected operation type', async () => {
608
606
  const handler = new GraphQLHandler('all', new RegExp('.*'), '*', resolver)
609
607
  const request = createPostGraphQLRequest({
610
608
  query: `
@@ -617,15 +615,15 @@ describe('predicate', () => {
617
615
  `,
618
616
  })
619
617
 
620
- expect(
618
+ await expect(
621
619
  handler.predicate({
622
620
  request,
623
621
  parsedResult: await handler.parse({ request }),
624
622
  }),
625
- ).toBe(true)
623
+ ).resolves.toBe(true)
626
624
  })
627
625
 
628
- test('respects custom endpoint', async () => {
626
+ it('respects custom endpoint', async () => {
629
627
  const handler = new GraphQLHandler(
630
628
  OperationTypeNode.QUERY,
631
629
  'GetUser',
@@ -642,23 +640,60 @@ describe('predicate', () => {
642
640
  query: GET_USER,
643
641
  })
644
642
 
645
- expect(
643
+ await expect(
646
644
  handler.predicate({
647
645
  request,
648
646
  parsedResult: await handler.parse({ request }),
649
647
  }),
650
- ).toBe(true)
651
- expect(
648
+ ).resolves.toBe(true)
649
+ await expect(
652
650
  handler.predicate({
653
651
  request: alienRequest,
654
652
  parsedResult: await handler.parse({ request: alienRequest }),
655
653
  }),
656
- ).toBe(false)
654
+ ).resolves.toBe(false)
655
+ })
656
+
657
+ it('supports custom predicate function', async () => {
658
+ const handler = new GraphQLHandler(
659
+ OperationTypeNode.QUERY,
660
+ ({ query }) => {
661
+ return query.includes('password')
662
+ },
663
+ /.+/,
664
+ resolver,
665
+ )
666
+
667
+ {
668
+ const request = createPostGraphQLRequest({
669
+ query: `query GetUser { user { password } }`,
670
+ })
671
+
672
+ await expect(
673
+ handler.predicate({
674
+ request,
675
+ parsedResult: await handler.parse({ request }),
676
+ }),
677
+ ).resolves.toBe(true)
678
+ }
679
+
680
+ {
681
+ const request = createPostGraphQLRequest({
682
+ query: `query GetUser { user { nonMatching } }`,
683
+ })
684
+
685
+ await expect(
686
+ handler.predicate({
687
+ request,
688
+ parsedResult: await handler.parse({ request }),
689
+ }),
690
+ ).resolves.toBe(false)
691
+ }
657
692
  })
658
693
  })
659
694
 
660
695
  describe('test', () => {
661
- test('respects operation type', async () => {
696
+ it('respects operation type', async () => {
662
697
  const handler = new GraphQLHandler(
663
698
  OperationTypeNode.QUERY,
664
699
  'GetUser',
@@ -676,7 +711,7 @@ describe('test', () => {
676
711
  expect(await handler.test({ request: alienRequest })).toBe(false)
677
712
  })
678
713
 
679
- test('respects operation name', async () => {
714
+ it('respects operation name', async () => {
680
715
  const handler = new GraphQLHandler(
681
716
  OperationTypeNode.QUERY,
682
717
  'GetUser',
@@ -696,11 +731,11 @@ describe('test', () => {
696
731
  `,
697
732
  })
698
733
 
699
- expect(await handler.test({ request })).toBe(true)
700
- expect(await handler.test({ request: alienRequest })).toBe(false)
734
+ await expect(handler.test({ request })).resolves.toBe(true)
735
+ await expect(handler.test({ request: alienRequest })).resolves.toBe(false)
701
736
  })
702
737
 
703
- test('respects custom endpoint', async () => {
738
+ it('respects custom endpoint', async () => {
704
739
  const handler = new GraphQLHandler(
705
740
  OperationTypeNode.QUERY,
706
741
  'GetUser',
@@ -717,13 +752,13 @@ describe('test', () => {
717
752
  query: GET_USER,
718
753
  })
719
754
 
720
- expect(await handler.test({ request })).toBe(true)
721
- expect(await handler.test({ request: alienRequest })).toBe(false)
755
+ await expect(handler.test({ request })).resolves.toBe(true)
756
+ await expect(handler.test({ request: alienRequest })).resolves.toBe(false)
722
757
  })
723
758
  })
724
759
 
725
760
  describe('run', () => {
726
- test('returns a mocked response given a matching query', async () => {
761
+ it('returns a mocked response given a matching query', async () => {
727
762
  const handler = new GraphQLHandler(
728
763
  OperationTypeNode.QUERY,
729
764
  'GetUser',
@@ -757,18 +792,18 @@ describe('run', () => {
757
792
  })
758
793
  expect(result!.request.method).toBe('POST')
759
794
  expect(result!.request.url).toBe('https://example.com/')
760
- expect(await result!.request.json()).toEqual({
795
+ await expect(result!.request.json()).resolves.toEqual({
761
796
  query: GET_USER,
762
797
  variables: { userId: 'abc-123' },
763
798
  })
764
799
  expect(result!.response?.status).toBe(200)
765
800
  expect(result!.response?.statusText).toBe('OK')
766
- expect(await result!.response?.json()).toEqual({
801
+ await expect(result!.response?.json()).resolves.toEqual({
767
802
  data: { user: { id: 'abc-123' } },
768
803
  })
769
804
  })
770
805
 
771
- test('returns null given a non-matching query', async () => {
806
+ it('returns null given a non-matching query', async () => {
772
807
  const handler = new GraphQLHandler(
773
808
  OperationTypeNode.QUERY,
774
809
  'GetUser',
@@ -818,12 +853,12 @@ describe('request', () => {
818
853
  )
819
854
  const request = createPostGraphQLRequest({
820
855
  query: `
821
- query GetAllUsers {
822
- user {
823
- id
824
- }
856
+ query GetAllUsers {
857
+ user {
858
+ id
825
859
  }
826
- `,
860
+ }
861
+ `,
827
862
  })
828
863
 
829
864
  const requestId = createRequestId()