@mswjs/interceptors 0.39.7 → 0.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/browser/{chunk-PFGO5BSM.js → chunk-2HUMWGRD.js} +15 -3
- package/lib/browser/chunk-2HUMWGRD.js.map +1 -0
- package/lib/browser/{chunk-ZXAL3FMU.js → chunk-2MCNQOY3.js} +56 -51
- package/lib/browser/chunk-2MCNQOY3.js.map +1 -0
- package/lib/browser/chunk-57RIRQUY.js +218 -0
- package/lib/browser/chunk-57RIRQUY.js.map +1 -0
- package/lib/browser/chunk-FW45TRCB.js +178 -0
- package/lib/browser/chunk-FW45TRCB.js.map +1 -0
- package/lib/browser/{chunk-TIPR373R.js → chunk-JQ2S7G56.js} +19 -3
- package/lib/browser/chunk-JQ2S7G56.js.map +1 -0
- package/lib/browser/{chunk-3RXCRGL2.mjs → chunk-LIKZF2VU.mjs} +102 -1
- package/lib/browser/chunk-LIKZF2VU.mjs.map +1 -0
- package/lib/browser/{chunk-F2NPA2FP.js → chunk-MNT2FUCH.js} +61 -56
- package/lib/browser/chunk-MNT2FUCH.js.map +1 -0
- package/lib/browser/chunk-VOUOVDAW.mjs +178 -0
- package/lib/browser/chunk-VOUOVDAW.mjs.map +1 -0
- package/lib/browser/{chunk-TX5GBTFY.mjs → chunk-VYSDLBSS.mjs} +13 -1
- package/lib/browser/chunk-VYSDLBSS.mjs.map +1 -0
- package/lib/browser/{chunk-ZDGZFWQH.mjs → chunk-WADP6VHN.mjs} +49 -44
- package/lib/browser/chunk-WADP6VHN.mjs.map +1 -0
- package/lib/browser/{chunk-MDMPOBGY.mjs → chunk-WOWPV4GR.mjs} +52 -47
- package/lib/browser/chunk-WOWPV4GR.mjs.map +1 -0
- package/lib/browser/{chunk-QED3Q6Z2.mjs → chunk-Z5TSB3T6.mjs} +17 -1
- package/lib/browser/{chunk-QED3Q6Z2.mjs.map → chunk-Z5TSB3T6.mjs.map} +1 -1
- package/lib/browser/{glossary-7152281e.d.ts → glossary-f7ee1c9d.d.ts} +22 -17
- package/lib/browser/index.d.ts +1 -2
- package/lib/browser/index.js +6 -4
- package/lib/browser/index.js.map +1 -1
- package/lib/browser/index.mjs +4 -2
- package/lib/browser/index.mjs.map +1 -1
- package/lib/browser/interceptors/WebSocket/index.js +9 -7
- package/lib/browser/interceptors/WebSocket/index.js.map +1 -1
- package/lib/browser/interceptors/WebSocket/index.mjs +6 -4
- package/lib/browser/interceptors/WebSocket/index.mjs.map +1 -1
- package/lib/browser/interceptors/XMLHttpRequest/index.d.ts +1 -2
- package/lib/browser/interceptors/XMLHttpRequest/index.js +6 -6
- package/lib/browser/interceptors/XMLHttpRequest/index.mjs +5 -5
- package/lib/browser/interceptors/fetch/index.d.ts +1 -2
- package/lib/browser/interceptors/fetch/index.js +6 -6
- package/lib/browser/interceptors/fetch/index.mjs +5 -5
- package/lib/browser/presets/browser.d.ts +1 -2
- package/lib/browser/presets/browser.js +8 -8
- package/lib/browser/presets/browser.mjs +6 -6
- package/lib/node/{BatchInterceptor-5b72232f.d.ts → BatchInterceptor-cb9a2eee.d.ts} +1 -1
- package/lib/node/{Interceptor-bc5a9d8e.d.ts → Interceptor-dc0a39b5.d.ts} +22 -16
- package/lib/node/RemoteHttpInterceptor.d.ts +2 -3
- package/lib/node/RemoteHttpInterceptor.js +31 -27
- package/lib/node/RemoteHttpInterceptor.js.map +1 -1
- package/lib/node/RemoteHttpInterceptor.mjs +28 -24
- package/lib/node/RemoteHttpInterceptor.mjs.map +1 -1
- package/lib/node/{chunk-EKNRB5ZS.mjs → chunk-5UGIB6OX.mjs} +40 -29
- package/lib/node/chunk-5UGIB6OX.mjs.map +1 -0
- package/lib/node/{chunk-4NEYTVWD.mjs → chunk-5V3SIIW2.mjs} +48 -43
- package/lib/node/chunk-5V3SIIW2.mjs.map +1 -0
- package/lib/node/{chunk-VV2LUF5K.js → chunk-6B3ZQOO2.js} +51 -46
- package/lib/node/chunk-6B3ZQOO2.js.map +1 -0
- package/lib/node/chunk-7Q53NNPV.js +189 -0
- package/lib/node/chunk-7Q53NNPV.js.map +1 -0
- package/lib/node/{chunk-A7U44ARP.js → chunk-DOWWQYXZ.js} +104 -3
- package/lib/node/chunk-DOWWQYXZ.js.map +1 -0
- package/lib/node/{chunk-Z5LWCBZS.js → chunk-FRZQJNBO.js} +56 -51
- package/lib/node/chunk-FRZQJNBO.js.map +1 -0
- package/lib/node/{chunk-TJDMZZXE.mjs → chunk-GKN5RBVR.mjs} +2 -2
- package/lib/node/{chunk-R6JVCM7X.js → chunk-J5MULIHT.js} +3 -3
- package/lib/node/{chunk-IHJSPMYM.mjs → chunk-JXGB54LE.mjs} +102 -1
- package/lib/node/chunk-JXGB54LE.mjs.map +1 -0
- package/lib/node/{chunk-3CNGDJFB.mjs → chunk-OFW5L5ET.mjs} +50 -45
- package/lib/node/chunk-OFW5L5ET.mjs.map +1 -0
- package/lib/node/{chunk-A7Q4RTDJ.mjs → chunk-R6T7CL5E.mjs} +55 -115
- package/lib/node/chunk-R6T7CL5E.mjs.map +1 -0
- package/lib/node/{chunk-RC2XPCC4.mjs → chunk-SQ6RHTJR.mjs} +2 -2
- package/lib/node/chunk-SRMAQGPM.js +30 -0
- package/lib/node/chunk-SRMAQGPM.js.map +1 -0
- package/lib/node/{chunk-4YBV77DG.js → chunk-T3TW4P64.js} +3 -3
- package/lib/node/{chunk-N4ZZFE24.js → chunk-VYO5XDY2.js} +56 -45
- package/lib/node/chunk-VYO5XDY2.js.map +1 -0
- package/lib/node/chunk-YWNGXXUQ.mjs +30 -0
- package/lib/node/{chunk-3GJB4JDF.mjs.map → chunk-YWNGXXUQ.mjs.map} +1 -1
- package/lib/node/index.d.ts +2 -3
- package/lib/node/index.js +6 -4
- package/lib/node/index.js.map +1 -1
- package/lib/node/index.mjs +5 -3
- package/lib/node/index.mjs.map +1 -1
- package/lib/node/interceptors/ClientRequest/index.d.ts +1 -2
- package/lib/node/interceptors/ClientRequest/index.js +6 -6
- package/lib/node/interceptors/ClientRequest/index.mjs +5 -5
- package/lib/node/interceptors/XMLHttpRequest/index.d.ts +1 -2
- package/lib/node/interceptors/XMLHttpRequest/index.js +5 -5
- package/lib/node/interceptors/XMLHttpRequest/index.mjs +4 -4
- package/lib/node/interceptors/fetch/index.d.ts +1 -2
- package/lib/node/interceptors/fetch/index.js +5 -5
- package/lib/node/interceptors/fetch/index.mjs +4 -4
- package/lib/node/presets/node.d.ts +1 -2
- package/lib/node/presets/node.js +10 -10
- package/lib/node/presets/node.mjs +7 -7
- package/lib/node/utils/node/index.js +3 -3
- package/lib/node/utils/node/index.mjs +2 -2
- package/package.json +2 -1
- package/src/RemoteHttpInterceptor.ts +18 -13
- package/src/RequestController.test.ts +78 -31
- package/src/RequestController.ts +63 -39
- package/src/index.ts +4 -0
- package/src/interceptors/ClientRequest/MockHttpSocket.ts +24 -3
- package/src/interceptors/ClientRequest/index.ts +14 -18
- package/src/interceptors/WebSocket/index.ts +6 -2
- package/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts +45 -35
- package/src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +24 -21
- package/src/interceptors/fetch/index.ts +61 -50
- package/src/utils/handleRequest.ts +65 -95
- package/lib/browser/chunk-3RXCRGL2.mjs.map +0 -1
- package/lib/browser/chunk-F2NPA2FP.js.map +0 -1
- package/lib/browser/chunk-MDMPOBGY.mjs.map +0 -1
- package/lib/browser/chunk-MMKGBEJO.mjs +0 -246
- package/lib/browser/chunk-MMKGBEJO.mjs.map +0 -1
- package/lib/browser/chunk-PFGO5BSM.js.map +0 -1
- package/lib/browser/chunk-T7TBRNJZ.js +0 -117
- package/lib/browser/chunk-T7TBRNJZ.js.map +0 -1
- package/lib/browser/chunk-TIPR373R.js.map +0 -1
- package/lib/browser/chunk-TX5GBTFY.mjs.map +0 -1
- package/lib/browser/chunk-XX6WKANU.js +0 -246
- package/lib/browser/chunk-XX6WKANU.js.map +0 -1
- package/lib/browser/chunk-ZDGZFWQH.mjs.map +0 -1
- package/lib/browser/chunk-ZXAL3FMU.js.map +0 -1
- package/lib/node/chunk-3CNGDJFB.mjs.map +0 -1
- package/lib/node/chunk-3GJB4JDF.mjs +0 -14
- package/lib/node/chunk-4NEYTVWD.mjs.map +0 -1
- package/lib/node/chunk-72ZIHMEB.js +0 -249
- package/lib/node/chunk-72ZIHMEB.js.map +0 -1
- package/lib/node/chunk-A7Q4RTDJ.mjs.map +0 -1
- package/lib/node/chunk-A7U44ARP.js.map +0 -1
- package/lib/node/chunk-EKNRB5ZS.mjs.map +0 -1
- package/lib/node/chunk-IHJSPMYM.mjs.map +0 -1
- package/lib/node/chunk-N4ZZFE24.js.map +0 -1
- package/lib/node/chunk-SMXZPJEA.js +0 -14
- package/lib/node/chunk-SMXZPJEA.js.map +0 -1
- package/lib/node/chunk-VV2LUF5K.js.map +0 -1
- package/lib/node/chunk-Z5LWCBZS.js.map +0 -1
- package/src/utils/RequestController.ts +0 -21
- /package/lib/node/{chunk-TJDMZZXE.mjs.map → chunk-GKN5RBVR.mjs.map} +0 -0
- /package/lib/node/{chunk-R6JVCM7X.js.map → chunk-J5MULIHT.js.map} +0 -0
- /package/lib/node/{chunk-RC2XPCC4.mjs.map → chunk-SQ6RHTJR.mjs.map} +0 -0
- /package/lib/node/{chunk-4YBV77DG.js.map → chunk-T3TW4P64.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/RequestController.ts","../../src/InterceptorError.ts","../../src/utils/emitAsync.ts","../../src/utils/handleRequest.ts","../../src/utils/isObject.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { InterceptorError } from './InterceptorError'\n\nconst kRequestHandled = Symbol('kRequestHandled')\nexport const kResponsePromise = Symbol('kResponsePromise')\n\nexport class RequestController {\n /**\n * Internal response promise.\n * Available only for the library internals to grab the\n * response instance provided by the developer.\n * @note This promise cannot be rejected. It's either infinitely\n * pending or resolved with whichever Response was passed to `respondWith()`.\n */\n [kResponsePromise]: DeferredPromise<\n Response | Record<string, any> | undefined\n >;\n\n /**\n * Internal flag indicating if this request has been handled.\n * @note The response promise becomes \"fulfilled\" on the next tick.\n */\n [kRequestHandled]: boolean\n\n constructor(private request: Request) {\n this[kRequestHandled] = false\n this[kResponsePromise] = new DeferredPromise()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n * @example\n * controller.respondWith(new Response())\n * controller.respondWith(Response.json({ id }))\n * controller.respondWith(Response.error())\n */\n public respondWith(response: Response): void {\n invariant.as(\n InterceptorError,\n !this[kRequestHandled],\n 'Failed to respond to the \"%s %s\" request: the \"request\" event has already been handled.',\n this.request.method,\n this.request.url\n )\n\n this[kRequestHandled] = true\n this[kResponsePromise].resolve(response)\n\n /**\n * @note The request controller doesn't do anything\n * apart from letting the interceptor await the response\n * provided by the developer through the response promise.\n * Each interceptor implements the actual respondWith/errorWith\n * logic based on that interceptor's needs.\n */\n }\n\n /**\n * Error this request with the given reason.\n *\n * @example\n * controller.errorWith()\n * controller.errorWith(new Error('Oops!'))\n * controller.errorWith({ message: 'Oops!'})\n */\n public errorWith(reason?: Error | Record<string, any>): void {\n invariant.as(\n InterceptorError,\n !this[kRequestHandled],\n 'Failed to error the \"%s %s\" request: the \"request\" event has already been handled.',\n this.request.method,\n this.request.url\n )\n\n this[kRequestHandled] = true\n\n /**\n * @note Resolve the response promise, not reject.\n * This helps us differentiate between unhandled exceptions\n * and intended errors (\"errorWith\") while waiting for the response.\n */\n this[kResponsePromise].resolve(reason)\n }\n}\n","export class InterceptorError extends Error {\n constructor(message?: string) {\n super(message)\n this.name = 'InterceptorError'\n Object.setPrototypeOf(this, InterceptorError.prototype)\n }\n}\n","import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter<Events>,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise<void> {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { kResponsePromise, RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\n ResponseError,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\nimport { isObject } from './isObject'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter<HttpRequestEventMap>\n controller: RequestController\n\n /**\n * Called when the request has been handled\n * with the given `Response` instance.\n */\n onResponse: (response: Response) => void | Promise<void>\n\n /**\n * Called when the request has been handled\n * with the given `Response.error()` instance.\n */\n onRequestError: (response: ResponseError) => void\n\n /**\n * Called when an unhandled error happens during the\n * request handling. This is never a thrown error/response.\n */\n onError: (error: unknown) => void\n}\n\n/**\n * @returns {Promise<boolean>} Indicates whether the request has been handled.\n */\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise<boolean> {\n const handleResponse = async (\n response: Response | Error | Record<string, any>\n ) => {\n if (response instanceof Error) {\n options.onError(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n options.onRequestError(response)\n return true\n }\n\n /**\n * Handle normal responses or response-like objects.\n * @note This must come before the arbitrary object check\n * since Response instances are, in fact, objects.\n */\n if (isResponseLike(response)) {\n await options.onResponse(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n options.onError(response)\n return true\n }\n\n return false\n }\n\n const handleResponseError = async (error: unknown): Promise<boolean> => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n options.onError(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n options.emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== options.requestId) {\n return\n }\n\n if (options.controller[kResponsePromise].state === 'pending') {\n options.controller[kResponsePromise].resolve(undefined)\n }\n })\n\n const requestAbortPromise = new DeferredPromise<void, unknown>()\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n requestAbortPromise.reject(options.request.signal.reason)\n } else {\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\n )\n }\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListenersPromise,\n options.controller[kResponsePromise],\n ])\n\n // The response promise will settle immediately once\n // the developer calls either \"respondWith\" or \"errorWith\".\n return await options.controller[kResponsePromise]\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n options.onError(requestAbortPromise.rejectionReason)\n return true\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return true\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n }).then(() => {\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the response in any way, preemptively\n // resolve the pending response promise from the new controller.\n // This prevents it from hanging forever.\n if (\n unhandledExceptionController[kResponsePromise].state === 'pending'\n ) {\n unhandledExceptionController[kResponsePromise].resolve(undefined)\n }\n })\n\n const nextResult = await until(\n () => unhandledExceptionController[kResponsePromise]\n )\n\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n if (nextResult.error) {\n return handleResponseError(nextResult.error)\n }\n\n if (nextResult.data) {\n return handleResponse(nextResult.data)\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n options.onResponse(createServerErrorResponse(result.error))\n return true\n }\n\n /**\n * Handle a mocked Response instance.\n * @note That this can also be an Error in case\n * the developer called \"errorWith\". This differentiates\n * unhandled exceptions from intended errors.\n */\n if (result.data) {\n return handleResponse(result.data)\n }\n\n // In all other cases, consider the request unhandled.\n return false\n}\n","/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject<T>(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible<Obj extends Record<string, any>>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isObject } from './isObject'\nimport { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: unknown): response is ResponseError {\n return (\n response != null &&\n response instanceof Response &&\n isPropertyAccessible(response, 'type') &&\n response.type === 'error'\n )\n}\n\n/**\n * Check if the given value is a `Response` or a Response-like object.\n * This is different from `value instanceof Response` because it supports\n * custom `Response` constructors, like the one when using Undici directly.\n */\nexport function isResponseLike(value: unknown): value is Response {\n return (\n isObject<Record<string, any>>(value, true) &&\n isPropertyAccessible(value, 'status') &&\n isPropertyAccessible(value, 'statusText') &&\n isPropertyAccessible(value, 'bodyUsed')\n )\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;;;ACDzB,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAkB;AAC5B,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,iBAAiB,SAAS;AAAA,EACxD;AACF;;;ADFA,IAAM,kBAAkB,OAAO,iBAAiB;AACzC,IAAM,mBAAmB,OAAO,kBAAkB;AAElD,IAAM,o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AI,OAAO,WAAW,QAAQ,eAAe,CAAC,WAAW,cAAc;AACrE,YAAQ;AAAA,MACN,mDAAmD;AAAA,IACrD;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AACT","sourcesContent":["/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(propertyName: string): boolean {\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof descriptor === 'undefined') {\n return false\n }\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n"]}
|
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/glossary.ts
|
|
2
|
-
var IS_PATCHED_MODULE = Symbol("isPatchedModule");
|
|
3
|
-
|
|
4
|
-
// src/utils/canParseUrl.ts
|
|
5
|
-
function canParseUrl(url) {
|
|
6
|
-
try {
|
|
7
|
-
new URL(url);
|
|
8
|
-
return true;
|
|
9
|
-
} catch (_error) {
|
|
10
|
-
return false;
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
// src/utils/getValueBySymbol.ts
|
|
15
|
-
function getValueBySymbol(symbolName, source) {
|
|
16
|
-
const ownSymbols = Object.getOwnPropertySymbols(source);
|
|
17
|
-
const symbol = ownSymbols.find((symbol2) => {
|
|
18
|
-
return symbol2.description === symbolName;
|
|
19
|
-
});
|
|
20
|
-
if (symbol) {
|
|
21
|
-
return Reflect.get(source, symbol);
|
|
22
|
-
}
|
|
23
|
-
return;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
// src/utils/fetchUtils.ts
|
|
27
|
-
var _FetchResponse = class extends Response {
|
|
28
|
-
static isConfigurableStatusCode(status) {
|
|
29
|
-
return status >= 200 && status <= 599;
|
|
30
|
-
}
|
|
31
|
-
static isRedirectResponse(status) {
|
|
32
|
-
return _FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status);
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Returns a boolean indicating whether the given response status
|
|
36
|
-
* code represents a response that can have a body.
|
|
37
|
-
*/
|
|
38
|
-
static isResponseWithBody(status) {
|
|
39
|
-
return !_FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status);
|
|
40
|
-
}
|
|
41
|
-
static setUrl(url, response) {
|
|
42
|
-
if (!url || url === "about:" || !canParseUrl(url)) {
|
|
43
|
-
return;
|
|
44
|
-
}
|
|
45
|
-
const state = getValueBySymbol("state", response);
|
|
46
|
-
if (state) {
|
|
47
|
-
state.urlList.push(new URL(url));
|
|
48
|
-
} else {
|
|
49
|
-
Object.defineProperty(response, "url", {
|
|
50
|
-
value: url,
|
|
51
|
-
enumerable: true,
|
|
52
|
-
configurable: true,
|
|
53
|
-
writable: false
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Parses the given raw HTTP headers into a Fetch API `Headers` instance.
|
|
59
|
-
*/
|
|
60
|
-
static parseRawHeaders(rawHeaders) {
|
|
61
|
-
const headers = new Headers();
|
|
62
|
-
for (let line = 0; line < rawHeaders.length; line += 2) {
|
|
63
|
-
headers.append(rawHeaders[line], rawHeaders[line + 1]);
|
|
64
|
-
}
|
|
65
|
-
return headers;
|
|
66
|
-
}
|
|
67
|
-
constructor(body, init = {}) {
|
|
68
|
-
var _a;
|
|
69
|
-
const status = (_a = init.status) != null ? _a : 200;
|
|
70
|
-
const safeStatus = _FetchResponse.isConfigurableStatusCode(status) ? status : 200;
|
|
71
|
-
const finalBody = _FetchResponse.isResponseWithBody(status) ? body : null;
|
|
72
|
-
super(finalBody, {
|
|
73
|
-
status: safeStatus,
|
|
74
|
-
statusText: init.statusText,
|
|
75
|
-
headers: init.headers
|
|
76
|
-
});
|
|
77
|
-
if (status !== safeStatus) {
|
|
78
|
-
const state = getValueBySymbol("state", this);
|
|
79
|
-
if (state) {
|
|
80
|
-
state.status = status;
|
|
81
|
-
} else {
|
|
82
|
-
Object.defineProperty(this, "status", {
|
|
83
|
-
value: status,
|
|
84
|
-
enumerable: true,
|
|
85
|
-
configurable: true,
|
|
86
|
-
writable: false
|
|
87
|
-
});
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
_FetchResponse.setUrl(init.url, this);
|
|
91
|
-
}
|
|
92
|
-
};
|
|
93
|
-
var FetchResponse = _FetchResponse;
|
|
94
|
-
/**
|
|
95
|
-
* Response status codes for responses that cannot have body.
|
|
96
|
-
* @see https://fetch.spec.whatwg.org/#statuses
|
|
97
|
-
*/
|
|
98
|
-
FetchResponse.STATUS_CODES_WITHOUT_BODY = [101, 103, 204, 205, 304];
|
|
99
|
-
FetchResponse.STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308];
|
|
100
|
-
|
|
101
|
-
// src/getRawRequest.ts
|
|
102
|
-
var kRawRequest = Symbol("kRawRequest");
|
|
103
|
-
function getRawRequest(request) {
|
|
104
|
-
return Reflect.get(request, kRawRequest);
|
|
105
|
-
}
|
|
106
|
-
function setRawRequest(request, rawRequest) {
|
|
107
|
-
Reflect.set(request, kRawRequest, rawRequest);
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
exports.IS_PATCHED_MODULE = IS_PATCHED_MODULE; exports.canParseUrl = canParseUrl; exports.FetchResponse = FetchResponse; exports.getRawRequest = getRawRequest; exports.setRawRequest = setRawRequest;
|
|
117
|
-
//# sourceMappingURL=chunk-T7TBRNJZ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/glossary.ts","../../src/utils/canParseUrl.ts","../../src/utils/getValueBySymbol.ts","../../src/utils/fetchUtils.ts","../../src/getRawRequest.ts"],"names":["symbol"],"mappings":";AAEO,IAAM,oBAAmC,OAAO,iBAAiB;;;ACGjE,SAAS,YAAY,KAAsB;AAChD,MAAI;AACF,QAAI,IAAI,GAAG;AACX,WAAO;AAAA,EACT,SAAS,QAAP;AACA,WAAO;AAAA,EACT;AACF;;;ACTO,SAAS,iBACd,YACA,QACe;AACf,QAAM,aAAa,OAAO,sBAAsB,MAAM;AAEtD,QAAM,SAAS,WAAW,KAAK,CAACA,YAAW;AACzC,WAAOA,QAAO,gBAAgB;AAAA,EAChC,CAAC;AAED,MAAI,QAAQ;AACV,WAAO,QAAQ,IAAI,QAAQ,MAAM;AAAA,EACnC;AAEA;AACF;;;ACQO,IAAM,iBAAN,cAA4B,SAAS;AAAA,EAS1C,OAAO,yBAAyB,QAAyB;AACvD,WAAO,UAAU,OAAO,UAAU;AAAA,EACpC;AAAA,EAEA,OAAO,mBAAmB,QAAyB;AACjD,WAAO,eAAc,2BAA2B,SAAS,MAAM;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OAAO,mBAAmB,QAAyB;AACjD,WAAO,CAAC,eAAc,0BAA0B,SAAS,MAAM;AAAA,EACjE;AAAA,EAEA,OAAO,OAAO,KAAyB,UAA0B;AAC/D,QAAI,CAAC,OAAO,QAAQ,YAAY,CAAC,YAAY,GAAG,GAAG;AACjD;AAAA,IACF;AAEA,UAAM,QAAQ,iBAA2C,SAAS,QAAQ;AAE1E,QAAI,OAAO;AAGT,YAAM,QAAQ,KAAK,IAAI,IAAI,GAAG,CAAC;AAAA,IACjC,OAAO;AAEL,aAAO,eAAe,UAAU,OAAO;AAAA,QACrC,OAAO;AAAA,QACP,YAAY;AAAA,QACZ,cAAc;AAAA,QACd,UAA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type { RequestController } from './RequestController'\n\nexport const IS_PATCHED_MODULE: unique symbol = Symbol('isPatchedModule')\n\n/**\n * @note Export `RequestController` as a type only.\n * It's never meant to be created in the userland.\n */\nexport type { RequestController }\n\nexport type RequestCredentials = 'omit' | 'include' | 'same-origin'\n\nexport type HttpRequestEventMap = {\n request: [\n args: {\n request: Request\n requestId: string\n controller: RequestController\n }\n ]\n response: [\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ]\n unhandledException: [\n args: {\n error: unknown\n request: Request\n requestId: string\n controller: RequestController\n }\n ]\n}\n","/**\n * Returns a boolean indicating whether the given URL string\n * can be parsed into a `URL` instance.\n * A substitute for `URL.canParse()` for Node.js 18.\n */\nexport function canParseUrl(url: string): boolean {\n try {\n new URL(url)\n return true\n } catch (_error) {\n return false\n }\n}\n","/**\n * Returns the value behind the symbol with the given name.\n */\nexport function getValueBySymbol<T>(\n symbolName: string,\n source: object\n): T | undefined {\n const ownSymbols = Object.getOwnPropertySymbols(source)\n\n const symbol = ownSymbols.find((symbol) => {\n return symbol.description === symbolName\n })\n\n if (symbol) {\n return Reflect.get(source, symbol)\n }\n\n return\n}\n","import { canParseUrl } from './canParseUrl'\nimport { getValueBySymbol } from './getValueBySymbol'\n\nexport interface FetchResponseInit extends ResponseInit {\n url?: string\n}\n\ninterface UndiciFetchInternalState {\n aborted: boolean\n rangeRequested: boolean\n timingAllowPassed: boolean\n requestIncludesCredentials: boolean\n type: ResponseType\n status: number\n statusText: string\n timingInfo: unknown\n cacheState: unknown\n headersList: Record<symbol, Map<string, unknown>>\n urlList: Array<URL>\n body?: {\n stream: ReadableStream\n source: unknown\n length: number\n }\n}\n\nexport class FetchResponse extends Response {\n /**\n * Response status codes for responses that cannot have body.\n * @see https://fetch.spec.whatwg.org/#statuses\n */\n static readonly STATUS_CODES_WITHOUT_BODY = [101, 103, 204, 205, 304]\n\n static readonly STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308]\n\n static isConfigurableStatusCode(status: number): boolean {\n return status >= 200 && status <= 599\n }\n\n static isRedirectResponse(status: number): boolean {\n return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status)\n }\n\n /**\n * Returns a boolean indicating whether the given response status\n * code represents a response that can have a body.\n */\n static isResponseWithBody(status: number): boolean {\n return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status)\n }\n\n static setUrl(url: string | undefined, response: Response): void {\n if (!url || url === 'about:' || !canParseUrl(url)) {\n return\n }\n\n const state = getValueBySymbol<UndiciFetchInternalState>('state', response)\n\n if (state) {\n // In Undici, push the URL to the internal list of URLs.\n // This will respect the `response.url` getter logic correctly.\n state.urlList.push(new URL(url))\n } else {\n // In other libraries, redefine the `url` property directly.\n Object.defineProperty(response, 'url', {\n value: url,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n }\n\n /**\n * Parses the given raw HTTP headers into a Fetch API `Headers` instance.\n */\n static parseRawHeaders(rawHeaders: Array<string>): Headers {\n const headers = new Headers()\n for (let line = 0; line < rawHeaders.length; line += 2) {\n headers.append(rawHeaders[line], rawHeaders[line + 1])\n }\n return headers\n }\n\n constructor(body?: BodyInit | null, init: FetchResponseInit = {}) {\n const status = init.status ?? 200\n const safeStatus = FetchResponse.isConfigurableStatusCode(status)\n ? status\n : 200\n const finalBody = FetchResponse.isResponseWithBody(status) ? body : null\n\n super(finalBody, {\n status: safeStatus,\n statusText: init.statusText,\n headers: init.headers,\n })\n\n if (status !== safeStatus) {\n /**\n * @note Undici keeps an internal \"Symbol(state)\" that holds\n * the actual value of response status. Update that in Node.js.\n */\n const state = getValueBySymbol<UndiciFetchInternalState>('state', this)\n\n if (state) {\n state.status = status\n } else {\n Object.defineProperty(this, 'status', {\n value: status,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n }\n\n FetchResponse.setUrl(init.url, this)\n }\n}\n","const kRawRequest = Symbol('kRawRequest')\n\n/**\n * Returns a raw request instance associated with this request.\n *\n * @example\n * interceptor.on('request', ({ request }) => {\n * const rawRequest = getRawRequest(request)\n *\n * if (rawRequest instanceof http.ClientRequest) {\n * console.log(rawRequest.rawHeaders)\n * }\n * })\n */\nexport function getRawRequest(request: Request): unknown | undefined {\n return Reflect.get(request, kRawRequest)\n}\n\nexport function setRawRequest(request: Request, rawRequest: unknown): void {\n Reflect.set(request, kRawRequest, rawRequest)\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Interceptor.ts","../../src/createRequestId.ts"],"names":["InterceptorReadyState"],"mappings":";AAAA,SAAS,cAAc;AACvB,SAAS,eAAyB;AAY3B,IAAM,kCACX;AAEK,SAAS,gBAAmB,QAA+B;AAChE;AAAA;AAAA,IAEE,WAAW,MAAM,KAAK;AAAA;AAE1B;AAEA,SAAS,gBAAgB,QAAgB,OAAkB;AAEzD,aAAW,MAAM,IAAI;AACvB;AAEO,SAAS,mBAAmB,QAAsB;AAEvD,SAAO,WAAW,MAAM;AAC1B;AAEO,IAAK,wBAAL,kBAAKA,2BAAL;AACL,EAAAA,uBAAA,cAAW;AACX,EAAAA,uBAAA,cAAW;AACX,EAAAA,uBAAA,aAAU;AACV,EAAAA,uBAAA,eAAY;AACZ,EAAAA,uBAAA,cAAW;AALD,SAAAA;AAAA,GAAA;AAWL,IAAM,cAAN,MAAsD;AAAA,EAO3D,YAA6B,QAAgB;AAAhB;AAC3B,SAAK,aAAa;AAElB,SAAK,UAAU,IAAI,QAAQ;AAC3B,SAAK,gBAAgB,CAAC;AACtB,SAAK,SAAS,IAAI,OAAO,OAAO,WAAY;AAI5C,SAAK,QAAQ,gBAAgB,CAAC;AAE9B,SAAK,OAAO,KAAK,iCAAiC;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMU,mBAA4B;AACpC,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA,EAMO,QAAc;AACnB,UAAM,SAAS,KAAK,OAAO,OAAO,OAAO;AACzC,WAAO,KAAK,6BAA6B;AA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-emitter'\n\nexport type InterceptorEventMap = Record<string, any>\nexport type InterceptorSubscription = () => void\n\n/**\n * Request header name to detect when a single request\n * is being handled by nested interceptors (XHR -> ClientRequest).\n * Obscure by design to prevent collisions with user-defined headers.\n * Ideally, come up with the Interceptor-level mechanism for this.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\nexport const INTERNAL_REQUEST_ID_HEADER_NAME =\n 'x-interceptors-internal-request-id'\n\nexport function getGlobalSymbol<V>(symbol: Symbol): V | undefined {\n return (\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587\n globalThis[symbol] || undefined\n )\n}\n\nfunction setGlobalSymbol(symbol: Symbol, value: any): void {\n // @ts-ignore\n globalThis[symbol] = value\n}\n\nexport function deleteGlobalSymbol(symbol: Symbol): void {\n // @ts-ignore\n delete globalThis[symbol]\n}\n\nexport enum InterceptorReadyState {\n INACTIVE = 'INACTIVE',\n APPLYING = 'APPLYING',\n APPLIED = 'APPLIED',\n DISPOSING = 'DISPOSING',\n DISPOSED = 'DISPOSED',\n}\n\nexport type ExtractEventNames<Events extends Record<string, any>> =\n Events extends Record<infer EventName, any> ? EventName : never\n\nexport class Interceptor<Events extends InterceptorEventMap> {\n protected emitter: Emitter<Events>\n protected subscriptions: Array<InterceptorSubscription>\n protected logger: Logger\n\n public readyState: InterceptorReadyState\n\n constructor(private readonly symbol: symbol) {\n this.readyState = InterceptorReadyState.INACTIVE\n\n this.emitter = new Emitter()\n this.subscriptions = []\n this.logger = new Logger(symbol.description!)\n\n // Do not limit the maximum number of listeners\n // so not to limit the maximum amount of parallel events emitted.\n this.emitter.setMaxListeners(0)\n\n this.logger.info('constructing the interceptor...')\n }\n\n /**\n * Determine if this interceptor can be applied\n * in the current environment.\n */\n protected checkEnvironment(): boolean {\n return true\n }\n\n /**\n * Apply this interceptor to the current process.\n * Returns an already running interceptor instance if it's present.\n */\n public apply(): void {\n const logger = this.logger.extend('apply')\n logger.info('applying the interceptor...')\n\n if (this.readyState === InterceptorReadyState.APPLIED) {\n logger.info('intercepted already applied!')\n return\n }\n\n const shouldApply = this.checkEnvironment()\n\n if (!shouldApply) {\n logger.info('the interceptor cannot be applied in this environment!')\n return\n }\n\n this.readyState = InterceptorReadyState.APPLYING\n\n // Whenever applying a new interceptor, check if it hasn't been applied already.\n // This enables to apply the same interceptor multiple times, for example from a different\n // interceptor, only proxying events but keeping the stubs in a single place.\n const runningInstance = this.getInstance()\n\n if (runningInstance) {\n logger.info('found a running instance, reusing...')\n\n // Proxy any listeners you set on this instance to the running instance.\n this.on = (event, listener) => {\n logger.info('proxying the \"%s\" listener', event)\n\n // Add listeners to the running instance so they appear\n // at the top of the event listeners list and are executed first.\n runningInstance.emitter.addListener(event, listener)\n\n // Ensure that once this interceptor instance is disposed,\n // it removes all listeners it has appended to the running interceptor instance.\n this.subscriptions.push(() => {\n runningInstance.emitter.removeListener(event, listener)\n logger.info('removed proxied \"%s\" listener!', event)\n })\n\n return this\n }\n\n this.readyState = InterceptorReadyState.APPLIED\n\n return\n }\n\n logger.info('no running instance found, setting up a new instance...')\n\n // Setup the interceptor.\n this.setup()\n\n // Store the newly applied interceptor instance globally.\n this.setInstance()\n\n this.readyState = InterceptorReadyState.APPLIED\n }\n\n /**\n * Setup the module augments and stubs necessary for this interceptor.\n * This method is not run if there's a running interceptor instance\n * to prevent instantiating an interceptor multiple times.\n */\n protected setup(): void {}\n\n /**\n * Listen to the interceptor's public events.\n */\n public on<EventName extends ExtractEventNames<Events>>(\n event: EventName,\n listener: Listener<Events[EventName]>\n ): this {\n const logger = this.logger.extend('on')\n\n if (\n this.readyState === InterceptorReadyState.DISPOSING ||\n this.readyState === InterceptorReadyState.DISPOSED\n ) {\n logger.info('cannot listen to events, already disposed!')\n return this\n }\n\n logger.info('adding \"%s\" event listener:', event, listener)\n\n this.emitter.on(event, listener)\n return this\n }\n\n public once<EventName extends ExtractEventNames<Events>>(\n event: EventName,\n listener: Listener<Events[EventName]>\n ): this {\n this.emitter.once(event, listener)\n return this\n }\n\n public off<EventName extends ExtractEventNames<Events>>(\n event: EventName,\n listener: Listener<Events[EventName]>\n ): this {\n this.emitter.off(event, listener)\n return this\n }\n\n public removeAllListeners<EventName extends ExtractEventNames<Events>>(\n event?: EventName\n ): this {\n this.emitter.removeAllListeners(event)\n return this\n }\n\n /**\n * Disposes of any side-effects this interceptor has introduced.\n */\n public dispose(): void {\n const logger = this.logger.extend('dispose')\n\n if (this.readyState === InterceptorReadyState.DISPOSED) {\n logger.info('cannot dispose, already disposed!')\n return\n }\n\n logger.info('disposing the interceptor...')\n this.readyState = InterceptorReadyState.DISPOSING\n\n if (!this.getInstance()) {\n logger.info('no interceptors running, skipping dispose...')\n return\n }\n\n // Delete the global symbol as soon as possible,\n // indicating that the interceptor is no longer running.\n this.clearInstance()\n\n logger.info('global symbol deleted:', getGlobalSymbol(this.symbol))\n\n if (this.subscriptions.length > 0) {\n logger.info('disposing of %d subscriptions...', this.subscriptions.length)\n\n for (const dispose of this.subscriptions) {\n dispose()\n }\n\n this.subscriptions = []\n\n logger.info('disposed of all subscriptions!', this.subscriptions.length)\n }\n\n this.emitter.removeAllListeners()\n logger.info('destroyed the listener!')\n\n this.readyState = InterceptorReadyState.DISPOSED\n }\n\n private getInstance(): this | undefined {\n const instance = getGlobalSymbol<this>(this.symbol)\n this.logger.info('retrieved global instance:', instance?.constructor?.name)\n return instance\n }\n\n private setInstance(): void {\n setGlobalSymbol(this.symbol, this)\n this.logger.info('set global instance!', this.symbol.description)\n }\n\n private clearInstance(): void {\n deleteGlobalSymbol(this.symbol)\n this.logger.info('cleared global instance!', this.symbol.description)\n }\n}\n","/**\n * Generate a random ID string to represent a request.\n * @example\n * createRequestId()\n * // \"f774b6c9c600f\"\n */\nexport function createRequestId(): string {\n return Math.random().toString(16).slice(2)\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/hasConfigurableGlobal.ts"],"sourcesContent":["/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(propertyName: string): boolean {\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof descriptor === 'undefined') {\n return false\n }\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n"],"mappings":";AAIO,SAAS,sBAAsB,cAA+B;AACnE,QAAM,aAAa,OAAO,yBAAyB,YAAY,YAAY;AAG3E,MAAI,OAAO,eAAe,aAAa;AACrC,WAAO;AAAA,EACT;AAGA,MACE,OAAO,WAAW,QAAQ,cAC1B,OAAO,WAAW,IAAI,MAAM,aAC5B;AACA,WAAO;AAAA,EACT;AAGA,MAAI,OAAO,WAAW,QAAQ,eAAe,WAAW,SAAS,MAAM;AACrE,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,WAAW,QAAQ,eAAe,CAAC,WAAW,cAAc;AACrE,YAAQ;AAAA,MACN,mDAAmD;AAAA,IACrD;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -1,246 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/RequestController.ts
|
|
2
|
-
var _outvariant = require('outvariant');
|
|
3
|
-
var _deferredpromise = require('@open-draft/deferred-promise');
|
|
4
|
-
|
|
5
|
-
// src/InterceptorError.ts
|
|
6
|
-
var InterceptorError = class extends Error {
|
|
7
|
-
constructor(message) {
|
|
8
|
-
super(message);
|
|
9
|
-
this.name = "InterceptorError";
|
|
10
|
-
Object.setPrototypeOf(this, InterceptorError.prototype);
|
|
11
|
-
}
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
// src/RequestController.ts
|
|
15
|
-
var kRequestHandled = Symbol("kRequestHandled");
|
|
16
|
-
var kResponsePromise = Symbol("kResponsePromise");
|
|
17
|
-
var RequestController = class {
|
|
18
|
-
constructor(request) {
|
|
19
|
-
this.request = request;
|
|
20
|
-
this[kRequestHandled] = false;
|
|
21
|
-
this[kResponsePromise] = new (0, _deferredpromise.DeferredPromise)();
|
|
22
|
-
}
|
|
23
|
-
/**
|
|
24
|
-
* Respond to this request with the given `Response` instance.
|
|
25
|
-
* @example
|
|
26
|
-
* controller.respondWith(new Response())
|
|
27
|
-
* controller.respondWith(Response.json({ id }))
|
|
28
|
-
* controller.respondWith(Response.error())
|
|
29
|
-
*/
|
|
30
|
-
respondWith(response) {
|
|
31
|
-
_outvariant.invariant.as(
|
|
32
|
-
InterceptorError,
|
|
33
|
-
!this[kRequestHandled],
|
|
34
|
-
'Failed to respond to the "%s %s" request: the "request" event has already been handled.',
|
|
35
|
-
this.request.method,
|
|
36
|
-
this.request.url
|
|
37
|
-
);
|
|
38
|
-
this[kRequestHandled] = true;
|
|
39
|
-
this[kResponsePromise].resolve(response);
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Error this request with the given reason.
|
|
43
|
-
*
|
|
44
|
-
* @example
|
|
45
|
-
* controller.errorWith()
|
|
46
|
-
* controller.errorWith(new Error('Oops!'))
|
|
47
|
-
* controller.errorWith({ message: 'Oops!'})
|
|
48
|
-
*/
|
|
49
|
-
errorWith(reason) {
|
|
50
|
-
_outvariant.invariant.as(
|
|
51
|
-
InterceptorError,
|
|
52
|
-
!this[kRequestHandled],
|
|
53
|
-
'Failed to error the "%s %s" request: the "request" event has already been handled.',
|
|
54
|
-
this.request.method,
|
|
55
|
-
this.request.url
|
|
56
|
-
);
|
|
57
|
-
this[kRequestHandled] = true;
|
|
58
|
-
this[kResponsePromise].resolve(reason);
|
|
59
|
-
}
|
|
60
|
-
};
|
|
61
|
-
kResponsePromise, kRequestHandled;
|
|
62
|
-
|
|
63
|
-
// src/utils/emitAsync.ts
|
|
64
|
-
async function emitAsync(emitter, eventName, ...data) {
|
|
65
|
-
const listeners = emitter.listeners(eventName);
|
|
66
|
-
if (listeners.length === 0) {
|
|
67
|
-
return;
|
|
68
|
-
}
|
|
69
|
-
for (const listener of listeners) {
|
|
70
|
-
await listener.apply(emitter, data);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// src/utils/handleRequest.ts
|
|
75
|
-
|
|
76
|
-
var _until = require('@open-draft/until');
|
|
77
|
-
|
|
78
|
-
// src/utils/isObject.ts
|
|
79
|
-
function isObject(value, loose = false) {
|
|
80
|
-
return loose ? Object.prototype.toString.call(value).startsWith("[object ") : Object.prototype.toString.call(value) === "[object Object]";
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
// src/utils/isPropertyAccessible.ts
|
|
84
|
-
function isPropertyAccessible(obj, key) {
|
|
85
|
-
try {
|
|
86
|
-
obj[key];
|
|
87
|
-
return true;
|
|
88
|
-
} catch (e) {
|
|
89
|
-
return false;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// src/utils/responseUtils.ts
|
|
94
|
-
function createServerErrorResponse(body) {
|
|
95
|
-
return new Response(
|
|
96
|
-
JSON.stringify(
|
|
97
|
-
body instanceof Error ? {
|
|
98
|
-
name: body.name,
|
|
99
|
-
message: body.message,
|
|
100
|
-
stack: body.stack
|
|
101
|
-
} : body
|
|
102
|
-
),
|
|
103
|
-
{
|
|
104
|
-
status: 500,
|
|
105
|
-
statusText: "Unhandled Exception",
|
|
106
|
-
headers: {
|
|
107
|
-
"Content-Type": "application/json"
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
);
|
|
111
|
-
}
|
|
112
|
-
function isResponseError(response) {
|
|
113
|
-
return response != null && response instanceof Response && isPropertyAccessible(response, "type") && response.type === "error";
|
|
114
|
-
}
|
|
115
|
-
function isResponseLike(value) {
|
|
116
|
-
return isObject(value, true) && isPropertyAccessible(value, "status") && isPropertyAccessible(value, "statusText") && isPropertyAccessible(value, "bodyUsed");
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// src/utils/isNodeLikeError.ts
|
|
120
|
-
function isNodeLikeError(error) {
|
|
121
|
-
if (error == null) {
|
|
122
|
-
return false;
|
|
123
|
-
}
|
|
124
|
-
if (!(error instanceof Error)) {
|
|
125
|
-
return false;
|
|
126
|
-
}
|
|
127
|
-
return "code" in error && "errno" in error;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
// src/utils/handleRequest.ts
|
|
131
|
-
async function handleRequest(options) {
|
|
132
|
-
const handleResponse = async (response) => {
|
|
133
|
-
if (response instanceof Error) {
|
|
134
|
-
options.onError(response);
|
|
135
|
-
return true;
|
|
136
|
-
}
|
|
137
|
-
if (isResponseError(response)) {
|
|
138
|
-
options.onRequestError(response);
|
|
139
|
-
return true;
|
|
140
|
-
}
|
|
141
|
-
if (isResponseLike(response)) {
|
|
142
|
-
await options.onResponse(response);
|
|
143
|
-
return true;
|
|
144
|
-
}
|
|
145
|
-
if (isObject(response)) {
|
|
146
|
-
options.onError(response);
|
|
147
|
-
return true;
|
|
148
|
-
}
|
|
149
|
-
return false;
|
|
150
|
-
};
|
|
151
|
-
const handleResponseError = async (error) => {
|
|
152
|
-
if (error instanceof InterceptorError) {
|
|
153
|
-
throw result.error;
|
|
154
|
-
}
|
|
155
|
-
if (isNodeLikeError(error)) {
|
|
156
|
-
options.onError(error);
|
|
157
|
-
return true;
|
|
158
|
-
}
|
|
159
|
-
if (error instanceof Response) {
|
|
160
|
-
return await handleResponse(error);
|
|
161
|
-
}
|
|
162
|
-
return false;
|
|
163
|
-
};
|
|
164
|
-
options.emitter.once("request", ({ requestId: pendingRequestId }) => {
|
|
165
|
-
if (pendingRequestId !== options.requestId) {
|
|
166
|
-
return;
|
|
167
|
-
}
|
|
168
|
-
if (options.controller[kResponsePromise].state === "pending") {
|
|
169
|
-
options.controller[kResponsePromise].resolve(void 0);
|
|
170
|
-
}
|
|
171
|
-
});
|
|
172
|
-
const requestAbortPromise = new (0, _deferredpromise.DeferredPromise)();
|
|
173
|
-
if (options.request.signal) {
|
|
174
|
-
if (options.request.signal.aborted) {
|
|
175
|
-
requestAbortPromise.reject(options.request.signal.reason);
|
|
176
|
-
} else {
|
|
177
|
-
options.request.signal.addEventListener(
|
|
178
|
-
"abort",
|
|
179
|
-
() => {
|
|
180
|
-
requestAbortPromise.reject(options.request.signal.reason);
|
|
181
|
-
},
|
|
182
|
-
{ once: true }
|
|
183
|
-
);
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
const result = await _until.until.call(void 0, async () => {
|
|
187
|
-
const requestListenersPromise = emitAsync(options.emitter, "request", {
|
|
188
|
-
requestId: options.requestId,
|
|
189
|
-
request: options.request,
|
|
190
|
-
controller: options.controller
|
|
191
|
-
});
|
|
192
|
-
await Promise.race([
|
|
193
|
-
// Short-circuit the request handling promise if the request gets aborted.
|
|
194
|
-
requestAbortPromise,
|
|
195
|
-
requestListenersPromise,
|
|
196
|
-
options.controller[kResponsePromise]
|
|
197
|
-
]);
|
|
198
|
-
return await options.controller[kResponsePromise];
|
|
199
|
-
});
|
|
200
|
-
if (requestAbortPromise.state === "rejected") {
|
|
201
|
-
options.onError(requestAbortPromise.rejectionReason);
|
|
202
|
-
return true;
|
|
203
|
-
}
|
|
204
|
-
if (result.error) {
|
|
205
|
-
if (await handleResponseError(result.error)) {
|
|
206
|
-
return true;
|
|
207
|
-
}
|
|
208
|
-
if (options.emitter.listenerCount("unhandledException") > 0) {
|
|
209
|
-
const unhandledExceptionController = new RequestController(
|
|
210
|
-
options.request
|
|
211
|
-
);
|
|
212
|
-
await emitAsync(options.emitter, "unhandledException", {
|
|
213
|
-
error: result.error,
|
|
214
|
-
request: options.request,
|
|
215
|
-
requestId: options.requestId,
|
|
216
|
-
controller: unhandledExceptionController
|
|
217
|
-
}).then(() => {
|
|
218
|
-
if (unhandledExceptionController[kResponsePromise].state === "pending") {
|
|
219
|
-
unhandledExceptionController[kResponsePromise].resolve(void 0);
|
|
220
|
-
}
|
|
221
|
-
});
|
|
222
|
-
const nextResult = await _until.until.call(void 0,
|
|
223
|
-
() => unhandledExceptionController[kResponsePromise]
|
|
224
|
-
);
|
|
225
|
-
if (nextResult.error) {
|
|
226
|
-
return handleResponseError(nextResult.error);
|
|
227
|
-
}
|
|
228
|
-
if (nextResult.data) {
|
|
229
|
-
return handleResponse(nextResult.data);
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
options.onResponse(createServerErrorResponse(result.error));
|
|
233
|
-
return true;
|
|
234
|
-
}
|
|
235
|
-
if (result.data) {
|
|
236
|
-
return handleResponse(result.data);
|
|
237
|
-
}
|
|
238
|
-
return false;
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
exports.RequestController = RequestController; exports.emitAsync = emitAsync; exports.handleRequest = handleRequest;
|
|
246
|
-
//# sourceMappingURL=chunk-XX6WKANU.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/RequestController.ts","../../src/InterceptorError.ts","../../src/utils/emitAsync.ts","../../src/utils/handleRequest.ts","../../src/utils/isObject.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts"],"names":["DeferredPromise"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;;;ACDzB,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAkB;AAC5B,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,iBAAiB,SAAS;AAAA,EACxD;AACF;;;ADFA,IAAM,kBAAkB,OAAO,iBAAiB;AACzC,IAAM,mBAAmB,OAAO,kBAAkB;AAElD,IAAM,oBAAN,MAAw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AO,KAAK,GAAG;AAC3C,aAAO;AAAA,IACT;AAKA,QAAI,QAAQ,QAAQ,cAAc,oBAAoB,IAAI,GAAG;AAI3D,YAAM,+BAA+B,IAAI;AAAA,QACvC,QAAQ;AAAA,MACV;AAEA,YAAM,UAAU,QAAQ,SAAS,sBAAsB;AAAA,QACrD,OAAO,OAAO;AAAA,QACd,SAAS,QAAQ;AAAA,QACjB,WAAW,QAAQ;AAAA,QACnB,YAAY;AAAA,MACd,CAAC,EAAE,KAAK,MAAM;AAKZ,YACE,6BAA6B,gBAAgB,EAAE,UAAU,WACzD;AACA,uCAA6B,gBAAgB,EAAE,QAAQ,MAAS;AAAA,QAClE;AAAA,MACF,CAAC;AAED,YAAM,aAAa,MAAM;AAAA,QACvB,MAAM,6BAA6B,gBAAgB;AAAA,MACrD;AASA,UAAI,WAAW,OAAO;AACpB,eAAO,oBAAoB,WAAW,KAAK;AAAA,MAC7C;AAEA,UAAI,WAAW,MAAM;AACnB,eAAO,eAAe,WAAW,IAAI;AAAA,MACvC;AAAA,IACF;AAGA,YAAQ,WAAW,0BAA0B,OAAO,KAAK,CAAC;AAC1D,WAAO;AAAA,EACT;AAQA,MAAI,OAAO,MAAM;AACf,WAAO,eAAe,OAAO,IAAI;AAAA,EACnC;AAGA,SAAO;AACT","sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { InterceptorError } from './InterceptorError'\n\nconst kRequestHandled = Symbol('kRequestHandled')\nexport const kResponsePromise = Symbol('kResponsePromise')\n\nexport class RequestController {\n /**\n * Internal response promise.\n * Available only for the library internals to grab the\n * response instance provided by the developer.\n * @note This promise cannot be rejected. It's either infinitely\n * pending or resolved with whichever Response was passed to `respondWith()`.\n */\n [kResponsePromise]: DeferredPromise<\n Response | Record<string, any> | undefined\n >;\n\n /**\n * Internal flag indicating if this request has been handled.\n * @note The response promise becomes \"fulfilled\" on the next tick.\n */\n [kRequestHandled]: boolean\n\n constructor(private request: Request) {\n this[kRequestHandled] = false\n this[kResponsePromise] = new DeferredPromise()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n * @example\n * controller.respondWith(new Response())\n * controller.respondWith(Response.json({ id }))\n * controller.respondWith(Response.error())\n */\n public respondWith(response: Response): void {\n invariant.as(\n InterceptorError,\n !this[kRequestHandled],\n 'Failed to respond to the \"%s %s\" request: the \"request\" event has already been handled.',\n this.request.method,\n this.request.url\n )\n\n this[kRequestHandled] = true\n this[kResponsePromise].resolve(response)\n\n /**\n * @note The request controller doesn't do anything\n * apart from letting the interceptor await the response\n * provided by the developer through the response promise.\n * Each interceptor implements the actual respondWith/errorWith\n * logic based on that interceptor's needs.\n */\n }\n\n /**\n * Error this request with the given reason.\n *\n * @example\n * controller.errorWith()\n * controller.errorWith(new Error('Oops!'))\n * controller.errorWith({ message: 'Oops!'})\n */\n public errorWith(reason?: Error | Record<string, any>): void {\n invariant.as(\n InterceptorError,\n !this[kRequestHandled],\n 'Failed to error the \"%s %s\" request: the \"request\" event has already been handled.',\n this.request.method,\n this.request.url\n )\n\n this[kRequestHandled] = true\n\n /**\n * @note Resolve the response promise, not reject.\n * This helps us differentiate between unhandled exceptions\n * and intended errors (\"errorWith\") while waiting for the response.\n */\n this[kResponsePromise].resolve(reason)\n }\n}\n","export class InterceptorError extends Error {\n constructor(message?: string) {\n super(message)\n this.name = 'InterceptorError'\n Object.setPrototypeOf(this, InterceptorError.prototype)\n }\n}\n","import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter<Events>,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise<void> {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { kResponsePromise, RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\n ResponseError,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\nimport { isObject } from './isObject'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter<HttpRequestEventMap>\n controller: RequestController\n\n /**\n * Called when the request has been handled\n * with the given `Response` instance.\n */\n onResponse: (response: Response) => void | Promise<void>\n\n /**\n * Called when the request has been handled\n * with the given `Response.error()` instance.\n */\n onRequestError: (response: ResponseError) => void\n\n /**\n * Called when an unhandled error happens during the\n * request handling. This is never a thrown error/response.\n */\n onError: (error: unknown) => void\n}\n\n/**\n * @returns {Promise<boolean>} Indicates whether the request has been handled.\n */\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise<boolean> {\n const handleResponse = async (\n response: Response | Error | Record<string, any>\n ) => {\n if (response instanceof Error) {\n options.onError(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n options.onRequestError(response)\n return true\n }\n\n /**\n * Handle normal responses or response-like objects.\n * @note This must come before the arbitrary object check\n * since Response instances are, in fact, objects.\n */\n if (isResponseLike(response)) {\n await options.onResponse(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n options.onError(response)\n return true\n }\n\n return false\n }\n\n const handleResponseError = async (error: unknown): Promise<boolean> => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n options.onError(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n options.emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== options.requestId) {\n return\n }\n\n if (options.controller[kResponsePromise].state === 'pending') {\n options.controller[kResponsePromise].resolve(undefined)\n }\n })\n\n const requestAbortPromise = new DeferredPromise<void, unknown>()\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n requestAbortPromise.reject(options.request.signal.reason)\n } else {\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\n )\n }\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListenersPromise,\n options.controller[kResponsePromise],\n ])\n\n // The response promise will settle immediately once\n // the developer calls either \"respondWith\" or \"errorWith\".\n return await options.controller[kResponsePromise]\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n options.onError(requestAbortPromise.rejectionReason)\n return true\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return true\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n }).then(() => {\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the response in any way, preemptively\n // resolve the pending response promise from the new controller.\n // This prevents it from hanging forever.\n if (\n unhandledExceptionController[kResponsePromise].state === 'pending'\n ) {\n unhandledExceptionController[kResponsePromise].resolve(undefined)\n }\n })\n\n const nextResult = await until(\n () => unhandledExceptionController[kResponsePromise]\n )\n\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n if (nextResult.error) {\n return handleResponseError(nextResult.error)\n }\n\n if (nextResult.data) {\n return handleResponse(nextResult.data)\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n options.onResponse(createServerErrorResponse(result.error))\n return true\n }\n\n /**\n * Handle a mocked Response instance.\n * @note That this can also be an Error in case\n * the developer called \"errorWith\". This differentiates\n * unhandled exceptions from intended errors.\n */\n if (result.data) {\n return handleResponse(result.data)\n }\n\n // In all other cases, consider the request unhandled.\n return false\n}\n","/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject<T>(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible<Obj extends Record<string, any>>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isObject } from './isObject'\nimport { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: unknown): response is ResponseError {\n return (\n response != null &&\n response instanceof Response &&\n isPropertyAccessible(response, 'type') &&\n response.type === 'error'\n )\n}\n\n/**\n * Check if the given value is a `Response` or a Response-like object.\n * This is different from `value instanceof Response` because it supports\n * custom `Response` constructors, like the one when using Undici directly.\n */\nexport function isResponseLike(value: unknown): value is Response {\n return (\n isObject<Record<string, any>>(value, true) &&\n isPropertyAccessible(value, 'status') &&\n isPropertyAccessible(value, 'statusText') &&\n isPropertyAccessible(value, 'bodyUsed')\n )\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n"]}
|