@mswjs/interceptors 0.41.5 → 0.41.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/browser/{XMLHttpRequest-DSAhl6_a.cjs → XMLHttpRequest-CHqOQWxg.cjs} +10 -8
- package/lib/browser/{XMLHttpRequest-DSAhl6_a.cjs.map → XMLHttpRequest-CHqOQWxg.cjs.map} +1 -1
- package/lib/browser/{XMLHttpRequest-DYyDAIJh.mjs → XMLHttpRequest-DP9ps_69.mjs} +10 -8
- package/lib/{node/XMLHttpRequest-DmsdUGmj.mjs.map → browser/XMLHttpRequest-DP9ps_69.mjs.map} +1 -1
- package/lib/browser/{fetch-BMC2en2x.cjs → fetch-CtkfZi4Z.cjs} +13 -10
- package/lib/browser/{fetch-BMC2en2x.cjs.map → fetch-CtkfZi4Z.cjs.map} +1 -1
- package/lib/browser/{fetch-D5LGhx5i.mjs → fetch-Ddj5TV04.mjs} +13 -10
- package/lib/browser/{fetch-D5LGhx5i.mjs.map → fetch-Ddj5TV04.mjs.map} +1 -1
- package/lib/browser/{getRawRequest-BEw5hEOW.mjs → getRawRequest-B1BqgWG6.mjs} +60 -15
- package/lib/browser/getRawRequest-B1BqgWG6.mjs.map +1 -0
- package/lib/browser/{getRawRequest-B9kRTvjs.cjs → getRawRequest-DdfaiPVH.cjs} +60 -15
- package/lib/browser/getRawRequest-DdfaiPVH.cjs.map +1 -0
- package/lib/browser/{handleRequest-DuUoGpfA.mjs → handleRequest-BHrC8Flw.mjs} +3 -3
- package/lib/browser/{handleRequest-DuUoGpfA.mjs.map → handleRequest-BHrC8Flw.mjs.map} +1 -1
- package/lib/browser/{handleRequest-BCtqvFSS.cjs → handleRequest-tUNU616J.cjs} +3 -3
- package/lib/browser/{handleRequest-BCtqvFSS.cjs.map → handleRequest-tUNU616J.cjs.map} +1 -1
- package/lib/browser/{hasConfigurableGlobal-B5o6PHq3.cjs → hasConfigurableGlobal-BS75Oulv.cjs} +30 -26
- package/lib/browser/hasConfigurableGlobal-BS75Oulv.cjs.map +1 -0
- package/lib/browser/{hasConfigurableGlobal-B39W0thh.mjs → hasConfigurableGlobal-FTYwno1G.mjs} +27 -23
- package/lib/browser/hasConfigurableGlobal-FTYwno1G.mjs.map +1 -0
- package/lib/browser/index.cjs +1 -1
- package/lib/browser/index.d.cts +10 -0
- package/lib/browser/index.d.mts +10 -0
- package/lib/browser/index.mjs +1 -1
- package/lib/browser/interceptors/WebSocket/index.cjs +2 -2
- package/lib/browser/interceptors/WebSocket/index.cjs.map +1 -1
- package/lib/browser/interceptors/WebSocket/index.mjs +2 -2
- package/lib/browser/interceptors/WebSocket/index.mjs.map +1 -1
- package/lib/browser/interceptors/XMLHttpRequest/index.cjs +4 -4
- package/lib/browser/interceptors/XMLHttpRequest/index.mjs +4 -4
- package/lib/browser/interceptors/fetch/index.cjs +4 -4
- package/lib/browser/interceptors/fetch/index.mjs +4 -4
- package/lib/browser/presets/browser.cjs +5 -5
- package/lib/browser/presets/browser.mjs +5 -5
- package/lib/node/{BatchInterceptor-B2YAn5m9.mjs → BatchInterceptor-DdMNfSUY.mjs} +2 -2
- package/lib/node/{BatchInterceptor-B2YAn5m9.mjs.map → BatchInterceptor-DdMNfSUY.mjs.map} +1 -1
- package/lib/node/{BatchInterceptor-AZr7q8p_.cjs → BatchInterceptor-Z1lwK23r.cjs} +2 -2
- package/lib/node/{BatchInterceptor-AZr7q8p_.cjs.map → BatchInterceptor-Z1lwK23r.cjs.map} +1 -1
- package/lib/node/{ClientRequest-BgwQG-9G.cjs → ClientRequest-DFs7FPNi.cjs} +8 -7
- package/lib/node/ClientRequest-DFs7FPNi.cjs.map +1 -0
- package/lib/node/{ClientRequest-5WjHvs9Y.mjs → ClientRequest-dRpI9v1o.mjs} +8 -7
- package/lib/node/ClientRequest-dRpI9v1o.mjs.map +1 -0
- package/lib/node/RemoteHttpInterceptor.cjs +8 -8
- package/lib/node/RemoteHttpInterceptor.cjs.map +1 -1
- package/lib/node/RemoteHttpInterceptor.mjs +8 -8
- package/lib/node/RemoteHttpInterceptor.mjs.map +1 -1
- package/lib/node/{XMLHttpRequest-DmsdUGmj.mjs → XMLHttpRequest-BgkpwNOu.mjs} +10 -8
- package/lib/{browser/XMLHttpRequest-DYyDAIJh.mjs.map → node/XMLHttpRequest-BgkpwNOu.mjs.map} +1 -1
- package/lib/node/{XMLHttpRequest-B7sloBex.cjs → XMLHttpRequest-CUbLHiq6.cjs} +10 -8
- package/lib/node/{XMLHttpRequest-B7sloBex.cjs.map → XMLHttpRequest-CUbLHiq6.cjs.map} +1 -1
- package/lib/node/{fetch-DDAGTtZi.mjs → fetch-BciBtVqm.mjs} +13 -10
- package/lib/node/{fetch-DDAGTtZi.mjs.map → fetch-BciBtVqm.mjs.map} +1 -1
- package/lib/node/{fetch-uc7pNtPg.cjs → fetch-znfXVEPe.cjs} +13 -10
- package/lib/node/{fetch-uc7pNtPg.cjs.map → fetch-znfXVEPe.cjs.map} +1 -1
- package/lib/node/{fetchUtils-BJxD7wvl.mjs → fetchUtils-BKJ1XmiO.mjs} +60 -15
- package/lib/node/{fetchUtils-BJxD7wvl.mjs.map → fetchUtils-BKJ1XmiO.mjs.map} +1 -1
- package/lib/node/{fetchUtils-Dw6kQghF.cjs → fetchUtils-umV5xXBy.cjs} +60 -15
- package/lib/node/{fetchUtils-Dw6kQghF.cjs.map → fetchUtils-umV5xXBy.cjs.map} +1 -1
- package/lib/node/{handleRequest-DGfUg9bm.mjs → handleRequest-DCLzePtS.mjs} +2 -2
- package/lib/node/{handleRequest-DGfUg9bm.mjs.map → handleRequest-DCLzePtS.mjs.map} +1 -1
- package/lib/node/{handleRequest-Dzg1d3e5.cjs → handleRequest-DVOthWJo.cjs} +2 -2
- package/lib/node/{handleRequest-Dzg1d3e5.cjs.map → handleRequest-DVOthWJo.cjs.map} +1 -1
- package/lib/node/{hasConfigurableGlobal-Befl_QJD.cjs → hasConfigurableGlobal-BtHi5OlL.cjs} +30 -26
- package/lib/node/hasConfigurableGlobal-BtHi5OlL.cjs.map +1 -0
- package/lib/node/{hasConfigurableGlobal-jN_-v3gp.mjs → hasConfigurableGlobal-Cwrs35Xo.mjs} +27 -23
- package/lib/node/hasConfigurableGlobal-Cwrs35Xo.mjs.map +1 -0
- package/lib/node/index.cjs +2 -2
- package/lib/node/index.d.cts +10 -0
- package/lib/node/index.d.mts +10 -0
- package/lib/node/index.mjs +2 -2
- package/lib/node/interceptors/ClientRequest/index.cjs +3 -3
- package/lib/node/interceptors/ClientRequest/index.mjs +3 -3
- package/lib/node/interceptors/XMLHttpRequest/index.cjs +4 -4
- package/lib/node/interceptors/XMLHttpRequest/index.mjs +4 -4
- package/lib/node/interceptors/fetch/index.cjs +4 -4
- package/lib/node/interceptors/fetch/index.mjs +4 -4
- package/lib/node/presets/node.cjs +6 -6
- package/lib/node/presets/node.mjs +6 -6
- package/package.json +1 -1
- package/src/RemoteHttpInterceptor.ts +1 -1
- package/src/interceptors/ClientRequest/utils/recordRawHeaders.test.ts +33 -0
- package/src/interceptors/ClientRequest/utils/recordRawHeaders.ts +19 -4
- package/src/interceptors/WebSocket/index.ts +2 -2
- package/src/interceptors/XMLHttpRequest/index.ts +4 -5
- package/src/interceptors/fetch/index.ts +15 -10
- package/src/utils/fetchUtils.test.ts +47 -1
- package/src/utils/fetchUtils.ts +89 -16
- package/src/utils/hasConfigurableGlobal.ts +1 -1
- package/src/utils/{globalUtils.test.ts → patchesRegistry.test.ts} +59 -19
- package/src/utils/patchesRegistry.ts +122 -0
- package/lib/browser/getRawRequest-B9kRTvjs.cjs.map +0 -1
- package/lib/browser/getRawRequest-BEw5hEOW.mjs.map +0 -1
- package/lib/browser/hasConfigurableGlobal-B39W0thh.mjs.map +0 -1
- package/lib/browser/hasConfigurableGlobal-B5o6PHq3.cjs.map +0 -1
- package/lib/node/ClientRequest-5WjHvs9Y.mjs.map +0 -1
- package/lib/node/ClientRequest-BgwQG-9G.cjs.map +0 -1
- package/lib/node/hasConfigurableGlobal-Befl_QJD.cjs.map +0 -1
- package/lib/node/hasConfigurableGlobal-jN_-v3gp.mjs.map +0 -1
- package/src/utils/globalsRegistry.ts +0 -107
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getRawRequest-DdfaiPVH.cjs","names":["request: Request","source: RequestControllerSource","DeferredPromise","#handled","symbol","#resolveProperty","bodyInit: { body?: BodyInit | null }","#setInternalProperty","authority: string"],"sources":["../../src/InterceptorError.ts","../../src/RequestController.ts","../../src/utils/canParseUrl.ts","../../src/utils/getValueBySymbol.ts","../../src/utils/fetchUtils.ts","../../src/getRawRequest.ts"],"sourcesContent":["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 { DeferredPromise } from '@open-draft/deferred-promise'\nimport { invariant } from 'outvariant'\nimport { InterceptorError } from './InterceptorError'\n\nexport interface RequestControllerSource {\n passthrough(): void\n respondWith(response: Response): void\n errorWith(reason?: unknown): void\n}\n\nexport class RequestController {\n static PENDING = 0 as const\n static PASSTHROUGH = 1 as const\n static RESPONSE = 2 as const\n static ERROR = 3 as const\n\n public readyState: number\n\n /**\n * A Promise that resolves when this controller handles a request.\n * See `controller.readyState` for more information on the handling result.\n */\n public handled: Promise<void>\n\n constructor(\n protected readonly request: Request,\n protected readonly source: RequestControllerSource\n ) {\n this.readyState = RequestController.PENDING\n this.handled = new DeferredPromise<void>()\n }\n\n get #handled() {\n return this.handled as DeferredPromise<void>\n }\n\n /**\n * Perform this request as-is.\n */\n public async passthrough(): Promise<void> {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to passthrough the \"%s %s\" request: the request has already been handled',\n this.request.method,\n this.request.url\n )\n\n this.readyState = RequestController.PASSTHROUGH\n await this.source.passthrough()\n this.#handled.resolve()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n *\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.readyState === RequestController.PENDING,\n 'Failed to respond to the \"%s %s\" request with \"%d %s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n response.status,\n response.statusText || 'OK',\n this.readyState\n )\n\n this.readyState = RequestController.RESPONSE\n this.#handled.resolve()\n\n /**\n * @note Although `source.respondWith()` is potentially asynchronous,\n * do NOT await it for backward-compatibility. Awaiting it will short-circuit\n * the request listener invocation as soon as a listener responds to a request.\n * Ideally, that's what we want, but that's not what we promise the user.\n */\n this.source.respondWith(response)\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?: unknown): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to error the \"%s %s\" request with \"%s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n reason?.toString(),\n this.readyState\n )\n\n this.readyState = RequestController.ERROR\n this.source.errorWith(reason)\n this.#handled.resolve()\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\ninterface UndiciRequestState extends RequestInit {}\n\ninterface FetchRequestInit extends Omit<RequestInit, 'mode'> {\n mode?: RequestMode | 'websocket' | 'webtransport'\n duplex?: 'half' | 'full'\n}\n\nexport class FetchRequest extends Request {\n static #resolveProperty<T extends keyof FetchRequestInit & keyof Request>(\n input: RequestInfo | URL,\n init: FetchRequestInit = {},\n key: T\n ): FetchRequestInit[T] {\n return init[key] ?? (input instanceof Request ? input[key] : undefined)\n }\n\n /**\n * Check if the given request method is configurable.\n * @see https://fetch.spec.whatwg.org/#methods\n */\n static isConfigurableMethod(method: string): boolean {\n return method !== 'CONNECT' && method !== 'TRACE' && method !== 'TRACK'\n }\n\n static isMethodWithBody(method: string): boolean {\n return (\n method !== 'HEAD' &&\n method !== 'GET' &&\n FetchRequest.isConfigurableMethod(method)\n )\n }\n\n /**\n * Check if the given request `mode` is configurable.\n * @see https://fetch.spec.whatwg.org/#concept-request-mode\n */\n static isConfigurableMode(mode: string): boolean {\n return (\n mode !== 'navigate' && mode !== 'websocket' && mode !== 'webtransport'\n )\n }\n\n constructor(input: URL | RequestInfo, init?: FetchRequestInit) {\n const method = FetchRequest.#resolveProperty(input, init, 'method') || 'GET'\n const safeMethod = FetchRequest.isConfigurableMethod(method)\n ? method\n : 'GET'\n\n const hasExplicitBody = init != null && 'body' in init\n\n /**\n * Only include `body` in the super init when it needs to be overridden.\n * When `input` is a Request and no explicit body is in `init`, let the\n * Request constructor handle body transfer naturally so it properly\n * marks the original request's body as consumed (bodyUsed = true).\n */\n const bodyInit: { body?: BodyInit | null } = !FetchRequest.isMethodWithBody(\n method\n )\n ? { body: undefined }\n : hasExplicitBody\n ? { body: init.body }\n : {}\n\n const mode =\n (FetchRequest.#resolveProperty(input, init, 'mode') as RequestMode) ??\n undefined\n const safeMode = FetchRequest.isConfigurableMode(mode) ? mode : undefined\n\n super(input, {\n ...(init || {}),\n method: safeMethod,\n mode: safeMode,\n // @ts-expect-error Untyped Node.js property.\n duplex:\n init?.duplex ??\n (FetchRequest.isMethodWithBody(method) ? 'half' : undefined),\n ...bodyInit,\n })\n\n if (method !== safeMethod) {\n this.#setInternalProperty('method', method)\n }\n\n if (method === 'CONNECT') {\n const url = new URL(input instanceof Request ? input.url : input)\n\n let authority: string\n\n /**\n * @note Node.js has a bug parsing raw CONNECT requests URLs like\n * \"http://127.0.0.1:1337/localhost:80\". It would treat \"localhost:\" as a protocol.\n */\n if (url.protocol === 'localhost:') {\n authority = url.href\n } else {\n authority = url.pathname.replace(/^\\/+/, '')\n }\n\n /**\n * @note Define \"url\" as a getter because Undici uses their own\n * logic to resolve the \"request.url\" property. Simply reassigning\n * its value doesn't do anything. This is a destructive action\n * but it's safe because \"CONNECT\" requests are forbidden per fetch.\n */\n Object.defineProperty(this, 'url', {\n get: () => authority,\n enumerable: true,\n configurable: true,\n })\n }\n\n if (mode != null && mode !== safeMode) {\n this.#setInternalProperty('mode', mode)\n }\n }\n\n #setInternalProperty<T extends keyof Request>(\n key: T,\n value: Request[T]\n ): void {\n const internalState = getValueBySymbol<UndiciRequestState>('state', this)\n\n if (internalState) {\n Reflect.set(internalState, key, value)\n } else {\n Object.defineProperty(this, key, {\n value,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n }\n}\n\nexport interface FetchResponseInit extends ResponseInit {\n url?: string\n}\n\ninterface UndiciResponseState {\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\nconst kStatus = Symbol('kStatus')\nconst kUrl = Symbol('kUrl')\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 setStatus(status: number, response: Response): void {\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 internalState = getValueBySymbol<UndiciResponseState>(\n 'state',\n response\n )\n\n if (internalState) {\n internalState.status = status\n } else {\n Object.defineProperty(response, 'status', {\n value: status,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n\n Object.defineProperty(response, kStatus, {\n value: status,\n enumerable: false,\n })\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<UndiciResponseState>('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 Object.defineProperty(response, kUrl, {\n value: url,\n enumerable: false,\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\n for (let line = 0; line < rawHeaders.length; line += 2) {\n headers.append(rawHeaders[line], rawHeaders[line + 1])\n }\n\n return headers\n }\n\n /**\n * Safely clones the given `Response`.\n * Coerces response clone exceptions into 500 mocked responses.\n * Handy in the environments that introduce arbitrary response\n * cloning restrictions, like \"101 Switching Protocols\" cloning\n * in \"miniflare\".\n */\n static clone(response: Response): Response {\n try {\n const clone = response.clone()\n return clone\n } catch (error) {\n return Response.json(\n error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : {},\n {\n status: 500,\n statusText: 'Unclonable Response',\n }\n )\n }\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 /**\n * Since Node.js v24, Undici stores the Response state in an inaccessible field \"#state\".\n * Forward the modified status/URL to the cloned response manually.\n * @see https://github.com/nodejs/undici/blob/f734c87280e626c75f59aad55b65eb6a89cef392/lib/web/fetch/response.js#L242\n */\n if (status !== safeStatus) {\n FetchResponse.setStatus(status, this)\n }\n\n FetchResponse.setUrl(init.url, this)\n }\n\n public clone() {\n const clonedResponse = super.clone()\n\n const customStatus = Reflect.get(this, kStatus) as number | undefined\n\n if (customStatus) {\n FetchResponse.setStatus(customStatus, clonedResponse)\n }\n\n const customUrl = Reflect.get(this, kUrl) as string | undefined\n\n if (customUrl) {\n FetchResponse.setUrl(customUrl, clonedResponse)\n }\n\n return clonedResponse\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"],"mappings":";;;;AAAA,IAAa,mBAAb,MAAa,yBAAyB,MAAM;CAC1C,YAAY,SAAkB;AAC5B,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,SAAO,eAAe,MAAM,iBAAiB,UAAU;;;;;;ACM3D,IAAa,oBAAb,MAAa,kBAAkB;;iBACZ;;;qBACI;;;kBACH;;;eACH;;CAUf,YACE,AAAmBA,SACnB,AAAmBC,QACnB;EAFm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} from "./hasConfigurableGlobal-
|
|
1
|
+
import { o as RequestController, s as InterceptorError } from "./getRawRequest-B1BqgWG6.mjs";
|
|
2
|
+
import { r as emitAsync } from "./hasConfigurableGlobal-FTYwno1G.mjs";
|
|
3
3
|
import { DeferredPromise } from "@open-draft/deferred-promise";
|
|
4
4
|
import { until } from "@open-draft/until";
|
|
5
5
|
|
|
@@ -175,4 +175,4 @@ async function handleRequest(options) {
|
|
|
175
175
|
|
|
176
176
|
//#endregion
|
|
177
177
|
export { isResponseError as n, handleRequest as t };
|
|
178
|
-
//# sourceMappingURL=handleRequest-
|
|
178
|
+
//# sourceMappingURL=handleRequest-BHrC8Flw.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handleRequest-DuUoGpfA.mjs","names":[],"sources":["../../src/utils/isObject.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts","../../src/utils/handleRequest.ts"],"sourcesContent":["/**\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","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 { RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\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\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise<void> {\n const handleResponse = async (\n response: Response | Error | Record<string, any>\n ) => {\n if (response instanceof Error) {\n await options.controller.errorWith(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n await options.controller.respondWith(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.controller.respondWith(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n await options.controller.errorWith(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 await options.controller.errorWith(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', async ({ requestId: pendingRequestId }) => {\n // if (\n // pendingRequestId === options.requestId &&\n // options.controller.readyState === RequestController.PENDING\n // ) {\n // await options.controller.passthrough()\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 await options.controller.errorWith(options.request.signal.reason)\n return\n }\n\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\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.handled,\n ])\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n await options.controller.errorWith(requestAbortPromise.rejectionReason)\n return\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\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 * @note Intentionally empty passthrough handle.\n * This controller is created within another controller and we only need\n * to know if `unhandledException` listeners handled the request.\n */\n passthrough() {},\n async respondWith(response) {\n await handleResponse(response)\n },\n async errorWith(reason) {\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 await options.controller.errorWith(reason)\n },\n }\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n })\n\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the request in any way, passthrough.\n if (\n unhandledExceptionController.readyState !== RequestController.PENDING\n ) {\n return\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n await options.controller.respondWith(\n createServerErrorResponse(result.error)\n )\n return\n }\n\n // If the request hasn't been handled by this point, passthrough.\n if (options.controller.readyState === RequestController.PENDING) {\n return await options.controller.passthrough()\n }\n\n return options.controller.handled\n}\n"],"mappings":";;;;;;;;;AAGA,SAAgB,SAAY,OAAY,QAAQ,OAAmB;AACjE,QAAO,QACH,OAAO,UAAU,SAAS,KAAK,MAAM,CAAC,WAAW,WAAW,GAC5D,OAAO,UAAU,SAAS,KAAK,MAAM,KAAK;;;;;;;;;;;;;ACEhD,SAAgB,qBACd,KACA,KACA;AACA,KAAI;AACF,MAAI;AACJ,SAAO;SACD;AACN,SAAO;;;;;;;;;ACVX,SAAgB,0BAA0B,MAAyB;AACjE,QAAO,IA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,"file":"handleRequest-BHrC8Flw.mjs","names":[],"sources":["../../src/utils/isObject.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts","../../src/utils/handleRequest.ts"],"sourcesContent":["/**\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","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 { RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\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\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise<void> {\n const handleResponse = async (\n response: Response | Error | Record<string, any>\n ) => {\n if (response instanceof Error) {\n await options.controller.errorWith(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n await options.controller.respondWith(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.controller.respondWith(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n await options.controller.errorWith(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 await options.controller.errorWith(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', async ({ requestId: pendingRequestId }) => {\n // if (\n // pendingRequestId === options.requestId &&\n // options.controller.readyState === RequestController.PENDING\n // ) {\n // await options.controller.passthrough()\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 await options.controller.errorWith(options.request.signal.reason)\n return\n }\n\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\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.handled,\n ])\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n await options.controller.errorWith(requestAbortPromise.rejectionReason)\n return\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\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 * @note Intentionally empty passthrough handle.\n * This controller is created within another controller and we only need\n * to know if `unhandledException` listeners handled the request.\n */\n passthrough() {},\n async respondWith(response) {\n await handleResponse(response)\n },\n async errorWith(reason) {\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 await options.controller.errorWith(reason)\n },\n }\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n })\n\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the request in any way, passthrough.\n if (\n unhandledExceptionController.readyState !== RequestController.PENDING\n ) {\n return\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n await options.controller.respondWith(\n createServerErrorResponse(result.error)\n )\n return\n }\n\n // If the request hasn't been handled by this point, passthrough.\n if (options.controller.readyState === RequestController.PENDING) {\n return await options.controller.passthrough()\n }\n\n return options.controller.handled\n}\n"],"mappings":";;;;;;;;;AAGA,SAAgB,SAAY,OAAY,QAAQ,OAAmB;AACjE,QAAO,QACH,OAAO,UAAU,SAAS,KAAK,MAAM,CAAC,WAAW,WAAW,GAC5D,OAAO,UAAU,SAAS,KAAK,MAAM,KAAK;;;;;;;;;;;;;ACEhD,SAAgB,qBACd,KACA,KACA;AACA,KAAI;AACF,MAAI;AACJ,SAAO;SACD;AACN,SAAO;;;;;;;;;ACVX,SAAgB,0BAA0B,MAAyB;AACjE,QAAO,IAAI,SACT,KAAK,UACH,gBAAgB,QACZ;EACE,MAAM,KAAK;EACX,SAAS,KAAK;EACd,OAAO,KAAK;EACb,GACD,KACL,EACD;EACE,QAAQ;EACR,YAAY;EACZ,SAAS,EACP,gBAAgB,oBACjB;EACF,CACF;;;;;;;;;;AAaH,SAAgB,gBAAgB,UAA8C;AAC5E,QACE,YAAY,QACZ,oBAAoB,YACpB,qBAAqB,UAAU,OAAO,IACtC,SAAS,SAAS;;;;;;;AAStB,SAAgB,eAAe,OAAmC;AAChE,QACE,SAA8B,OAAO,KAAK,IAC1C,qBAAqB,OAAO,SAAS,IACrC,qBAAqB,OAAO,aAAa,IACzC,qBAAqB,OAAO,WAAW;;;;;ACxD3C,SAAgB,gBACd,O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AAW;GACpB,CAAC;GACF;AAGF,KAAI,oBAAoB,UAAU,YAAY;AAC5C,QAAM,QAAQ,WAAW,UAAU,oBAAoB,gBAAgB;AACvE;;AAGF,KAAI,OAAO,OAAO;AAGhB,MAAI,MAAM,oBAAoB,OAAO,MAAM,CACzC;AAMF,MAAI,QAAQ,QAAQ,cAAc,qBAAqB,GAAG,GAAG;GAI3D,MAAM,+BAA+B,IAAI,kBACvC,QAAQ,SACR;IAME,cAAc;IACd,MAAM,YAAY,UAAU;AAC1B,WAAM,eAAe,SAAS;;IAEhC,MAAM,UAAU,QAAQ;;;;;;;;AAQtB,WAAM,QAAQ,WAAW,UAAU,OAAO;;IAE7C,CACF;AAED,SAAM,UAAU,QAAQ,SAAS,sBAAsB;IACrD,OAAO,OAAO;IACd,SAAS,QAAQ;IACjB,WAAW,QAAQ;IACnB,YAAY;IACb,CAAC;AAIF,OACE,6BAA6B,eAAe,kBAAkB,QAE9D;;AAKJ,QAAM,QAAQ,WAAW,YACvB,0BAA0B,OAAO,MAAM,CACxC;AACD;;AAIF,KAAI,QAAQ,WAAW,eAAe,kBAAkB,QACtD,QAAO,MAAM,QAAQ,WAAW,aAAa;AAG/C,QAAO,QAAQ,WAAW"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const require_getRawRequest = require('./getRawRequest-
|
|
2
|
-
const require_hasConfigurableGlobal = require('./hasConfigurableGlobal-
|
|
1
|
+
const require_getRawRequest = require('./getRawRequest-DdfaiPVH.cjs');
|
|
2
|
+
const require_hasConfigurableGlobal = require('./hasConfigurableGlobal-BS75Oulv.cjs');
|
|
3
3
|
let _open_draft_deferred_promise = require("@open-draft/deferred-promise");
|
|
4
4
|
let _open_draft_until = require("@open-draft/until");
|
|
5
5
|
|
|
@@ -186,4 +186,4 @@ Object.defineProperty(exports, 'isResponseError', {
|
|
|
186
186
|
return isResponseError;
|
|
187
187
|
}
|
|
188
188
|
});
|
|
189
|
-
//# sourceMappingURL=handleRequest-
|
|
189
|
+
//# sourceMappingURL=handleRequest-tUNU616J.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handleRequest-BCtqvFSS.cjs","names":["InterceptorError","DeferredPromise","emitAsync","RequestController"],"sources":["../../src/utils/isObject.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts","../../src/utils/handleRequest.ts"],"sourcesContent":["/**\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","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 { RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\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\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise<void> {\n const handleResponse = async (\n response: Response | Error | Record<string, any>\n ) => {\n if (response instanceof Error) {\n await options.controller.errorWith(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n await options.controller.respondWith(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.controller.respondWith(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n await options.controller.errorWith(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 await options.controller.errorWith(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', async ({ requestId: pendingRequestId }) => {\n // if (\n // pendingRequestId === options.requestId &&\n // options.controller.readyState === RequestController.PENDING\n // ) {\n // await options.controller.passthrough()\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 await options.controller.errorWith(options.request.signal.reason)\n return\n }\n\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\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.handled,\n ])\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n await options.controller.errorWith(requestAbortPromise.rejectionReason)\n return\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\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 * @note Intentionally empty passthrough handle.\n * This controller is created within another controller and we only need\n * to know if `unhandledException` listeners handled the request.\n */\n passthrough() {},\n async respondWith(response) {\n await handleResponse(response)\n },\n async errorWith(reason) {\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 await options.controller.errorWith(reason)\n },\n }\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n })\n\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the request in any way, passthrough.\n if (\n unhandledExceptionController.readyState !== RequestController.PENDING\n ) {\n return\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n await options.controller.respondWith(\n createServerErrorResponse(result.error)\n )\n return\n }\n\n // If the request hasn't been handled by this point, passthrough.\n if (options.controller.readyState === RequestController.PENDING) {\n return await options.controller.passthrough()\n }\n\n return options.controller.handled\n}\n"],"mappings":";;;;;;;;;AAGA,SAAgB,SAAY,OAAY,QAAQ,OAAmB;AACjE,QAAO,QACH,OAAO,UAAU,SAAS,KAAK,MAAM,CAAC,WAAW,WAAW,GAC5D,OAAO,UAAU,SAAS,KAAK,MAAM,KAAK;;;;;;;;;;;;;ACEhD,SAAgB,qBACd,KACA,KACA;AACA,KAAI;AACF,MAAI;AACJ,SAAO;SACD;AACN,SAAO;;;;;;;;;ACVX,SAAgB,0BAA0B,MAAyB;AACjE,QAAO,IAAI,SACT,KAAK,UACH,gBAAgB,QACZ;EACE,MAAM,KAAK;EACX,SAAS,KAAK;EACd,OAAO,KAAK;EACb,GACD,KACL,EACD;EACE,QAAQ;EACR,YAAY;EACZ,SAAS,EACP,gBAAgB,oBACjB;EACF,CACF;;;;;;;;;;AAaH,SAAgB,gBAAgB,UAA8C;AAC5E,QACE,YAAY,QACZ,oBAAoB,YACpB,qBAAqB,UAAU,OAAO,IACtC,SAAS,SAAS;;;;;;;AAStB,SAAgB,eAAe,OAAmC;AAChE,QACE,SAA8B,OAAO,KAAK,I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AAQ;GACnB,SAAS,QAAQ;GACjB,YAAY,QAAQ;GACrB,CAAC;AAEF,QAAM,QAAQ,KAAK;GAEjB;GACA;GACA,QAAQ,WAAW;GACpB,CAAC;GACF;AAGF,KAAI,oBAAoB,UAAU,YAAY;AAC5C,QAAM,QAAQ,WAAW,UAAU,oBAAoB,gBAAgB;AACvE;;AAGF,KAAI,OAAO,OAAO;AAGhB,MAAI,MAAM,oBAAoB,OAAO,MAAM,CACzC;AAMF,MAAI,QAAQ,QAAQ,cAAc,qBAAqB,GAAG,GAAG;GAI3D,MAAM,+BAA+B,IAAIC,wCACvC,QAAQ,SACR;IAME,cAAc;IACd,MAAM,YAAY,UAAU;AAC1B,WAAM,eAAe,SAAS;;IAEhC,MAAM,UAAU,QAAQ;;;;;;;;AAQtB,WAAM,QAAQ,WAAW,UAAU,OAAO;;IAE7C,CACF;AAED,SAAMD,wCAAU,QAAQ,SAAS,sBAAsB;IACrD,OAAO,OAAO;IACd,SAAS,QAAQ;IACjB,WAAW,QAAQ;IACnB,YAAY;IACb,CAAC;AAIF,OACE,6BAA6B,eAAeC,wCAAkB,QAE9D;;AAKJ,QAAM,QAAQ,WAAW,YACvB,0BAA0B,OAAO,MAAM,CACxC;AACD;;AAIF,KAAI,QAAQ,WAAW,eAAeA,wCAAkB,QACtD,QAAO,MAAM,QAAQ,WAAW,aAAa;AAG/C,QAAO,QAAQ,WAAW"}
|
|
1
|
+
{"version":3,"file":"handleRequest-tUNU616J.cjs","names":["InterceptorError","DeferredPromise","emitAsync","RequestController"],"sources":["../../src/utils/isObject.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts","../../src/utils/handleRequest.ts"],"sourcesContent":["/**\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","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 { RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\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\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise<void> {\n const handleResponse = async (\n response: Response | Error | Record<string, any>\n ) => {\n if (response instanceof Error) {\n await options.controller.errorWith(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n await options.controller.respondWith(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.controller.respondWith(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n await options.controller.errorWith(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 await options.controller.errorWith(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', async ({ requestId: pendingRequestId }) => {\n // if (\n // pendingRequestId === options.requestId &&\n // options.controller.readyState === RequestController.PENDING\n // ) {\n // await options.controller.passthrough()\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 await options.controller.errorWith(options.request.signal.reason)\n return\n }\n\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\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.handled,\n ])\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n await options.controller.errorWith(requestAbortPromise.rejectionReason)\n return\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\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 * @note Intentionally empty passthrough handle.\n * This controller is created within another controller and we only need\n * to know if `unhandledException` listeners handled the request.\n */\n passthrough() {},\n async respondWith(response) {\n await handleResponse(response)\n },\n async errorWith(reason) {\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 await options.controller.errorWith(reason)\n },\n }\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n })\n\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the request in any way, passthrough.\n if (\n unhandledExceptionController.readyState !== RequestController.PENDING\n ) {\n return\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n await options.controller.respondWith(\n createServerErrorResponse(result.error)\n )\n return\n }\n\n // If the request hasn't been handled by this point, passthrough.\n if (options.controller.readyState === RequestController.PENDING) {\n return await options.controller.passthrough()\n }\n\n return options.controller.handled\n}\n"],"mappings":";;;;;;;;;AAGA,SAAgB,SAAY,OAAY,QAAQ,OAAmB;AACjE,QAAO,QACH,OAAO,UAAU,SAAS,KAAK,MAAM,CAAC,WAAW,WAAW,GAC5D,OAAO,UAAU,SAAS,KAAK,MAAM,KAAK;;;;;;;;;;;;;ACEhD,SAAgB,qBACd,KACA,KACA;AACA,KAAI;AACF,MAAI;AACJ,SAAO;SACD;AACN,SAAO;;;;;;;;;ACVX,SAAgB,0BAA0B,MAAyB;AACjE,QAAO,IAAI,SACT,KAAK,UACH,gBAAgB,QACZ;EACE,MAAM,KAAK;EACX,SAAS,KAAK;EACd,OAAO,KAAK;EACb,GACD,KACL,EACD;EACE,QAAQ;EACR,YAAY;EACZ,SAAS,EACP,gBAAgB,oBACjB;EACF,CACF;;;;;;;;;;AAaH,SAAgB,gBAAgB,UAA8C;AAC5E,QACE,YAAY,QACZ,oBAAoB,YACpB,qBAAqB,UAAU,OAAO,IACtC,SAAS,SAAS;;;;;;;AAStB,SAAgB,eAAe,OAAmC;AAChE,QACE,SAA8B,OAAO,KAAK,IAC1C,qBAAqB,OAAO,SAAS,IACrC,qBAAqB,OAAO,aAAa,IACzC,qBAAqB,OAAO,WAAW;;;;;ACxD3C,SAAgB,gBACd,OACgC;AAChC,KAAI,SAAS,KACX,QAAO;AAGT,KAAI,EAAE,iBAAiB,OACrB,QAAO;AAGT,QAAO,UAAU,SAAS,WAAW;;;;;ACWvC,eAAsB,cACpB,SACe;CACf,MAAM,iBAAiB,OACrB,aACG;AACH,MAAI,oBAAoB,OAAO;AAC7B,SAAM,QAAQ,WAAW,UAAU,SAAS;AAC5C,UAAO;;AAIT,MAAI,gBAAgB,SAAS,EAAE;AAC7B,SAAM,QAAQ,WAAW,YAAY,SAAS;AAC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AAC1B,WAAM,eAAe,SAAS;;IAEhC,MAAM,UAAU,QAAQ;;;;;;;;AAQtB,WAAM,QAAQ,WAAW,UAAU,OAAO;;IAE7C,CACF;AAED,SAAMD,wCAAU,QAAQ,SAAS,sBAAsB;IACrD,OAAO,OAAO;IACd,SAAS,QAAQ;IACjB,WAAW,QAAQ;IACnB,YAAY;IACb,CAAC;AAIF,OACE,6BAA6B,eAAeC,wCAAkB,QAE9D;;AAKJ,QAAM,QAAQ,WAAW,YACvB,0BAA0B,OAAO,MAAM,CACxC;AACD;;AAIF,KAAI,QAAQ,WAAW,eAAeA,wCAAkB,QACtD,QAAO,MAAM,QAAQ,WAAW,aAAa;AAG/C,QAAO,QAAQ,WAAW"}
|
package/lib/browser/{hasConfigurableGlobal-B5o6PHq3.cjs → hasConfigurableGlobal-BS75Oulv.cjs}
RENAMED
|
@@ -13,40 +13,44 @@ async function emitAsync(emitter, eventName, ...data) {
|
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
//#endregion
|
|
16
|
-
//#region src/utils/
|
|
17
|
-
var
|
|
18
|
-
#
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
16
|
+
//#region src/utils/patchesRegistry.ts
|
|
17
|
+
var PatchesRegistry = class {
|
|
18
|
+
#replacements = /* @__PURE__ */ new Map();
|
|
19
|
+
applyPatch(owner, key, getNextValue) {
|
|
20
|
+
const ownerReplacements = this.#replacements.get(owner);
|
|
21
|
+
(0, outvariant.invariant)(!ownerReplacements?.has(key), `Failed to replace a global value at "${String(key)}": already replaced.`);
|
|
22
|
+
const match = getDeepPropertyDescriptor(owner, key);
|
|
22
23
|
if (typeof match === "undefined") {
|
|
23
|
-
console.warn(`Failed to replace a global value at "${key}": not a global value.`);
|
|
24
|
+
console.warn(`Failed to replace a global value at "${String(key)}": not a global value.`);
|
|
24
25
|
return () => {};
|
|
25
26
|
}
|
|
26
|
-
Object.defineProperty(
|
|
27
|
-
value:
|
|
27
|
+
Object.defineProperty(owner, key, {
|
|
28
|
+
value: getNextValue(owner[key]),
|
|
28
29
|
enumerable: true,
|
|
29
30
|
configurable: true
|
|
30
31
|
});
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
if (
|
|
32
|
+
const restorePatch = () => {
|
|
33
|
+
const currentReplacements = this.#replacements.get(owner);
|
|
34
|
+
if (!currentReplacements?.has(key)) return;
|
|
35
|
+
if (match.owner === owner) Object.defineProperty(match.owner, key, match.descriptor);
|
|
34
36
|
else
|
|
35
37
|
/**
|
|
36
38
|
* @todo Delete the proxy property set by the registry.
|
|
37
|
-
* If the owner isn't
|
|
39
|
+
* If the match's owner isn't the original owner, the property is likely nested in the prototype.
|
|
38
40
|
* The registry does not meddle with those, they are left intact.
|
|
39
41
|
*/
|
|
40
|
-
Reflect.deleteProperty(
|
|
41
|
-
|
|
42
|
+
Reflect.deleteProperty(owner, key);
|
|
43
|
+
currentReplacements.delete(key);
|
|
44
|
+
if (currentReplacements.size === 0) this.#replacements.delete(owner);
|
|
42
45
|
};
|
|
43
|
-
|
|
44
|
-
|
|
46
|
+
if (ownerReplacements) ownerReplacements.set(key, restorePatch);
|
|
47
|
+
else this.#replacements.set(owner, new Map([[key, restorePatch]]));
|
|
48
|
+
return restorePatch;
|
|
45
49
|
}
|
|
46
|
-
|
|
50
|
+
restoreAllPatches() {
|
|
47
51
|
const errors = [];
|
|
48
|
-
for (const [,
|
|
49
|
-
|
|
52
|
+
for (const [, ownerReplacements] of this.#replacements) for (const [, restorePatch] of ownerReplacements) try {
|
|
53
|
+
restorePatch();
|
|
50
54
|
} catch (error) {
|
|
51
55
|
if (error instanceof Error) errors.push(error);
|
|
52
56
|
else throw error;
|
|
@@ -54,7 +58,7 @@ var GlobalsRegistry = class {
|
|
|
54
58
|
if (errors.length > 0) throw new AggregateError(errors, "FOO!");
|
|
55
59
|
}
|
|
56
60
|
};
|
|
57
|
-
const
|
|
61
|
+
const patchesRegistry = new PatchesRegistry();
|
|
58
62
|
/**
|
|
59
63
|
* Returns a property descriptor for the given property on the owner.
|
|
60
64
|
* Walks down the prototype chain if the property does not exist on the owner.
|
|
@@ -100,16 +104,16 @@ Object.defineProperty(exports, 'emitAsync', {
|
|
|
100
104
|
return emitAsync;
|
|
101
105
|
}
|
|
102
106
|
});
|
|
103
|
-
Object.defineProperty(exports, '
|
|
107
|
+
Object.defineProperty(exports, 'hasConfigurableGlobal', {
|
|
104
108
|
enumerable: true,
|
|
105
109
|
get: function () {
|
|
106
|
-
return
|
|
110
|
+
return hasConfigurableGlobal;
|
|
107
111
|
}
|
|
108
112
|
});
|
|
109
|
-
Object.defineProperty(exports, '
|
|
113
|
+
Object.defineProperty(exports, 'patchesRegistry', {
|
|
110
114
|
enumerable: true,
|
|
111
115
|
get: function () {
|
|
112
|
-
return
|
|
116
|
+
return patchesRegistry;
|
|
113
117
|
}
|
|
114
118
|
});
|
|
115
|
-
//# sourceMappingURL=hasConfigurableGlobal-
|
|
119
|
+
//# sourceMappingURL=hasConfigurableGlobal-BS75Oulv.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hasConfigurableGlobal-BS75Oulv.cjs","names":["#replacements","errors: Array<Error>","currentOwner: Owner | null","descriptor: PropertyDescriptor | undefined"],"sources":["../../src/utils/emitAsync.ts","../../src/utils/patchesRegistry.ts","../../src/utils/hasConfigurableGlobal.ts"],"sourcesContent":["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 { invariant } from 'outvariant'\n\nclass PatchesRegistry {\n #replacements = new Map<object, Map<PropertyKey, () => void>>()\n\n public applyPatch<Owner extends object, K extends keyof Owner>(\n owner: Owner,\n key: K,\n getNextValue: (realValue: Owner[K]) => Owner[K]\n ): () => void {\n const ownerReplacements = this.#replacements.get(owner)\n\n invariant(\n !ownerReplacements?.has(key),\n `Failed to replace a global value at \"${String(key)}\": already replaced.`\n )\n\n const match = getDeepPropertyDescriptor(owner, key)\n\n if (typeof match === 'undefined') {\n console.warn(\n `Failed to replace a global value at \"${String(key)}\": not a global value.`\n )\n return () => {}\n }\n\n Object.defineProperty(owner, key, {\n value: getNextValue(owner[key]),\n enumerable: true,\n configurable: true,\n })\n\n const restorePatch = () => {\n const currentReplacements = this.#replacements.get(owner)\n\n if (!currentReplacements?.has(key)) {\n return\n }\n\n if (match.owner === owner) {\n Object.defineProperty(match.owner, key, match.descriptor)\n } else {\n /**\n * @todo Delete the proxy property set by the registry.\n * If the match's owner isn't the original owner, the property is likely nested in the prototype.\n * The registry does not meddle with those, they are left intact.\n */\n Reflect.deleteProperty(owner, key)\n }\n\n currentReplacements.delete(key)\n\n if (currentReplacements.size === 0) {\n this.#replacements.delete(owner)\n }\n }\n\n if (ownerReplacements) {\n ownerReplacements.set(key, restorePatch)\n } else {\n this.#replacements.set(owner, new Map([[key, restorePatch]]))\n }\n\n return restorePatch\n }\n\n public restoreAllPatches(): void {\n const errors: Array<Error> = []\n\n for (const [, ownerReplacements] of this.#replacements) {\n for (const [, restorePatch] of ownerReplacements) {\n try {\n restorePatch()\n } catch (error) {\n if (error instanceof Error) {\n errors.push(error)\n } else {\n throw error\n }\n }\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'FOO!')\n }\n }\n}\n\nexport const patchesRegistry = new PatchesRegistry()\n\ninterface DeepDescriptorMatch {\n owner: object\n descriptor: PropertyDescriptor\n}\n\n/**\n * Returns a property descriptor for the given property on the owner.\n * Walks down the prototype chain if the property does not exist on the owner.\n * Handy for getting a global property descriptor where `globalThis` is\n * replaced with a controlled class (e.g. ServiceWorkerGlobalScope).\n */\nexport function getDeepPropertyDescriptor<Owner extends object>(\n owner: Owner,\n key: keyof Owner\n): DeepDescriptorMatch | undefined {\n let currentOwner: Owner | null = owner\n let descriptor: PropertyDescriptor | undefined\n\n while (currentOwner) {\n descriptor = Object.getOwnPropertyDescriptor(currentOwner, key)\n\n if (descriptor) {\n return {\n owner: currentOwner,\n descriptor,\n }\n }\n\n currentOwner = Object.getPrototypeOf(currentOwner)\n }\n}\n","import { getDeepPropertyDescriptor } from './patchesRegistry'\n\n/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(\n propertyName: keyof typeof globalThis\n): boolean {\n const match = getDeepPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof match === 'undefined') {\n return false\n }\n\n const { descriptor } = match\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":";;;;;;;;AAOA,eAAsB,UAIpB,SACA,WACA,GAAG,MACY;CACf,MAAM,YAAY,QAAQ,UAAU,UAAU;AAE9C,KAAI,UAAU,WAAW,EACvB;AAGF,MAAK,MAAM,YAAY,UACrB,OAAM,SAAS,MAAM,SAAS,KAAK;;;;;ACpBvC,IAAM,kBAAN,MAAsB;CACpB,gCAAgB,IAAI,KAA2C;CAE/D,AAAO,WACL,OACA,KACA,cACY;EACZ,MAAM,oBAAoB,MAAKA,aAAc,IAAI,MAAM;AAEvD,4BACE,CAAC,mBAAmB,IAAI,IAAI,EAC5B,wCAAwC,OAAO,IAAI,CAAC,sBACrD;EAED,MAA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,cACS;CACT,MAAM,QAAQ,0BAA0B,YAAY,aAAa;AAGjE,KAAI,OAAO,UAAU,YACnB,QAAO;CAGT,MAAM,EAAE,eAAe;AAGvB,KACE,OAAO,WAAW,QAAQ,cAC1B,OAAO,WAAW,KAAK,KAAK,YAE5B,QAAO;AAIT,KAAI,OAAO,WAAW,QAAQ,eAAe,WAAW,SAAS,KAC/D,QAAO;AAGT,KAAI,OAAO,WAAW,QAAQ,eAAe,CAAC,WAAW,cAAc;AACrE,UAAQ,MACN,mDAAmD,aAAa,oKACjE;AACD,SAAO;;AAGT,QAAO"}
|
package/lib/browser/{hasConfigurableGlobal-B39W0thh.mjs → hasConfigurableGlobal-FTYwno1G.mjs}
RENAMED
|
@@ -13,40 +13,44 @@ async function emitAsync(emitter, eventName, ...data) {
|
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
//#endregion
|
|
16
|
-
//#region src/utils/
|
|
17
|
-
var
|
|
18
|
-
#
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
16
|
+
//#region src/utils/patchesRegistry.ts
|
|
17
|
+
var PatchesRegistry = class {
|
|
18
|
+
#replacements = /* @__PURE__ */ new Map();
|
|
19
|
+
applyPatch(owner, key, getNextValue) {
|
|
20
|
+
const ownerReplacements = this.#replacements.get(owner);
|
|
21
|
+
invariant(!ownerReplacements?.has(key), `Failed to replace a global value at "${String(key)}": already replaced.`);
|
|
22
|
+
const match = getDeepPropertyDescriptor(owner, key);
|
|
22
23
|
if (typeof match === "undefined") {
|
|
23
|
-
console.warn(`Failed to replace a global value at "${key}": not a global value.`);
|
|
24
|
+
console.warn(`Failed to replace a global value at "${String(key)}": not a global value.`);
|
|
24
25
|
return () => {};
|
|
25
26
|
}
|
|
26
|
-
Object.defineProperty(
|
|
27
|
-
value:
|
|
27
|
+
Object.defineProperty(owner, key, {
|
|
28
|
+
value: getNextValue(owner[key]),
|
|
28
29
|
enumerable: true,
|
|
29
30
|
configurable: true
|
|
30
31
|
});
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
if (
|
|
32
|
+
const restorePatch = () => {
|
|
33
|
+
const currentReplacements = this.#replacements.get(owner);
|
|
34
|
+
if (!currentReplacements?.has(key)) return;
|
|
35
|
+
if (match.owner === owner) Object.defineProperty(match.owner, key, match.descriptor);
|
|
34
36
|
else
|
|
35
37
|
/**
|
|
36
38
|
* @todo Delete the proxy property set by the registry.
|
|
37
|
-
* If the owner isn't
|
|
39
|
+
* If the match's owner isn't the original owner, the property is likely nested in the prototype.
|
|
38
40
|
* The registry does not meddle with those, they are left intact.
|
|
39
41
|
*/
|
|
40
|
-
Reflect.deleteProperty(
|
|
41
|
-
|
|
42
|
+
Reflect.deleteProperty(owner, key);
|
|
43
|
+
currentReplacements.delete(key);
|
|
44
|
+
if (currentReplacements.size === 0) this.#replacements.delete(owner);
|
|
42
45
|
};
|
|
43
|
-
|
|
44
|
-
|
|
46
|
+
if (ownerReplacements) ownerReplacements.set(key, restorePatch);
|
|
47
|
+
else this.#replacements.set(owner, new Map([[key, restorePatch]]));
|
|
48
|
+
return restorePatch;
|
|
45
49
|
}
|
|
46
|
-
|
|
50
|
+
restoreAllPatches() {
|
|
47
51
|
const errors = [];
|
|
48
|
-
for (const [,
|
|
49
|
-
|
|
52
|
+
for (const [, ownerReplacements] of this.#replacements) for (const [, restorePatch] of ownerReplacements) try {
|
|
53
|
+
restorePatch();
|
|
50
54
|
} catch (error) {
|
|
51
55
|
if (error instanceof Error) errors.push(error);
|
|
52
56
|
else throw error;
|
|
@@ -54,7 +58,7 @@ var GlobalsRegistry = class {
|
|
|
54
58
|
if (errors.length > 0) throw new AggregateError(errors, "FOO!");
|
|
55
59
|
}
|
|
56
60
|
};
|
|
57
|
-
const
|
|
61
|
+
const patchesRegistry = new PatchesRegistry();
|
|
58
62
|
/**
|
|
59
63
|
* Returns a property descriptor for the given property on the owner.
|
|
60
64
|
* Walks down the prototype chain if the property does not exist on the owner.
|
|
@@ -94,5 +98,5 @@ function hasConfigurableGlobal(propertyName) {
|
|
|
94
98
|
}
|
|
95
99
|
|
|
96
100
|
//#endregion
|
|
97
|
-
export {
|
|
98
|
-
//# sourceMappingURL=hasConfigurableGlobal-
|
|
101
|
+
export { patchesRegistry as n, emitAsync as r, hasConfigurableGlobal as t };
|
|
102
|
+
//# sourceMappingURL=hasConfigurableGlobal-FTYwno1G.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hasConfigurableGlobal-FTYwno1G.mjs","names":["#replacements","errors: Array<Error>","currentOwner: Owner | null","descriptor: PropertyDescriptor | undefined"],"sources":["../../src/utils/emitAsync.ts","../../src/utils/patchesRegistry.ts","../../src/utils/hasConfigurableGlobal.ts"],"sourcesContent":["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 { invariant } from 'outvariant'\n\nclass PatchesRegistry {\n #replacements = new Map<object, Map<PropertyKey, () => void>>()\n\n public applyPatch<Owner extends object, K extends keyof Owner>(\n owner: Owner,\n key: K,\n getNextValue: (realValue: Owner[K]) => Owner[K]\n ): () => void {\n const ownerReplacements = this.#replacements.get(owner)\n\n invariant(\n !ownerReplacements?.has(key),\n `Failed to replace a global value at \"${String(key)}\": already replaced.`\n )\n\n const match = getDeepPropertyDescriptor(owner, key)\n\n if (typeof match === 'undefined') {\n console.warn(\n `Failed to replace a global value at \"${String(key)}\": not a global value.`\n )\n return () => {}\n }\n\n Object.defineProperty(owner, key, {\n value: getNextValue(owner[key]),\n enumerable: true,\n configurable: true,\n })\n\n const restorePatch = () => {\n const currentReplacements = this.#replacements.get(owner)\n\n if (!currentReplacements?.has(key)) {\n return\n }\n\n if (match.owner === owner) {\n Object.defineProperty(match.owner, key, match.descriptor)\n } else {\n /**\n * @todo Delete the proxy property set by the registry.\n * If the match's owner isn't the original owner, the property is likely nested in the prototype.\n * The registry does not meddle with those, they are left intact.\n */\n Reflect.deleteProperty(owner, key)\n }\n\n currentReplacements.delete(key)\n\n if (currentReplacements.size === 0) {\n this.#replacements.delete(owner)\n }\n }\n\n if (ownerReplacements) {\n ownerReplacements.set(key, restorePatch)\n } else {\n this.#replacements.set(owner, new Map([[key, restorePatch]]))\n }\n\n return restorePatch\n }\n\n public restoreAllPatches(): void {\n const errors: Array<Error> = []\n\n for (const [, ownerReplacements] of this.#replacements) {\n for (const [, restorePatch] of ownerReplacements) {\n try {\n restorePatch()\n } catch (error) {\n if (error instanceof Error) {\n errors.push(error)\n } else {\n throw error\n }\n }\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'FOO!')\n }\n }\n}\n\nexport const patchesRegistry = new PatchesRegistry()\n\ninterface DeepDescriptorMatch {\n owner: object\n descriptor: PropertyDescriptor\n}\n\n/**\n * Returns a property descriptor for the given property on the owner.\n * Walks down the prototype chain if the property does not exist on the owner.\n * Handy for getting a global property descriptor where `globalThis` is\n * replaced with a controlled class (e.g. ServiceWorkerGlobalScope).\n */\nexport function getDeepPropertyDescriptor<Owner extends object>(\n owner: Owner,\n key: keyof Owner\n): DeepDescriptorMatch | undefined {\n let currentOwner: Owner | null = owner\n let descriptor: PropertyDescriptor | undefined\n\n while (currentOwner) {\n descriptor = Object.getOwnPropertyDescriptor(currentOwner, key)\n\n if (descriptor) {\n return {\n owner: currentOwner,\n descriptor,\n }\n }\n\n currentOwner = Object.getPrototypeOf(currentOwner)\n }\n}\n","import { getDeepPropertyDescriptor } from './patchesRegistry'\n\n/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(\n propertyName: keyof typeof globalThis\n): boolean {\n const match = getDeepPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof match === 'undefined') {\n return false\n }\n\n const { descriptor } = match\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":";;;;;;;;AAOA,eAAsB,UAIpB,SACA,WACA,GAAG,MACY;CACf,MAAM,YAAY,QAAQ,UAAU,UAAU;AAE9C,KAAI,UAAU,WAAW,EACvB;AAGF,MAAK,MAAM,YAAY,UACrB,OAAM,SAAS,MAAM,SAAS,KAAK;;;;;ACpBvC,IAAM,kBAAN,MAAsB;CACpB,gCAAgB,IAAI,KAA2C;CAE/D,AAAO,WACL,OACA,KACA,cACY;EACZ,MAAM,oBAAoB,MAAKA,aAAc,IAAI,MAAM;AAEvD,YACE,CAAC,mBAAmB,IAAI,IAAI,EAC5B,wCAAwC,OAAO,IAAI,CAAC,sBACrD;EAED,MAAM,QAAQ,0BAA0B,OAAO,IAAI;AAEnD,MAAI,OAAO,UAAU,aAAa;AAChC,WAAQ,KACN,wCAAwC,OAAO,IAAI,CAAC,wBACrD;AACD,gBAAa;;AAGf,SAAO,eAAe,OAAO,KAAK;GAChC,OAAO,aAAa,MAAM,KAAK;GAC/B,YAAY;GACZ,cAAc;GACf,CAAC;EAEF,MAAM,qBAAqB;GACzB,MAAM,sBAAsB,MAAKA,aAAc,IAAI,MAAM;AAEzD,OAAI,CAAC,qBAAqB,IAAI,IAAI,CAChC;AAGF,OAAI,MAAM,UAAU,MAClB,QAAO,eAAe,MAAM,OAAO,KAAK,MAAM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1,5 +1,5 @@
|
|
|
1
1
|
const require_createRequestId = require('./createRequestId-DOf8Ktjs.cjs');
|
|
2
|
-
const require_getRawRequest = require('./getRawRequest-
|
|
2
|
+
const require_getRawRequest = require('./getRawRequest-DdfaiPVH.cjs');
|
|
3
3
|
const require_bufferUtils = require('./bufferUtils-Uc0eRItL.cjs');
|
|
4
4
|
const require_resolveWebSocketUrl = require('./resolveWebSocketUrl-6K6EgqsA.cjs');
|
|
5
5
|
|
package/lib/browser/index.d.cts
CHANGED
|
@@ -79,12 +79,22 @@ declare class FetchResponse extends Response {
|
|
|
79
79
|
* code represents a response that can have a body.
|
|
80
80
|
*/
|
|
81
81
|
static isResponseWithBody(status: number): boolean;
|
|
82
|
+
static setStatus(status: number, response: Response): void;
|
|
82
83
|
static setUrl(url: string | undefined, response: Response): void;
|
|
83
84
|
/**
|
|
84
85
|
* Parses the given raw HTTP headers into a Fetch API `Headers` instance.
|
|
85
86
|
*/
|
|
86
87
|
static parseRawHeaders(rawHeaders: Array<string>): Headers;
|
|
88
|
+
/**
|
|
89
|
+
* Safely clones the given `Response`.
|
|
90
|
+
* Coerces response clone exceptions into 500 mocked responses.
|
|
91
|
+
* Handy in the environments that introduce arbitrary response
|
|
92
|
+
* cloning restrictions, like "101 Switching Protocols" cloning
|
|
93
|
+
* in "miniflare".
|
|
94
|
+
*/
|
|
95
|
+
static clone(response: Response): Response;
|
|
87
96
|
constructor(body?: BodyInit | null, init?: FetchResponseInit);
|
|
97
|
+
clone(): Response;
|
|
88
98
|
}
|
|
89
99
|
//#endregion
|
|
90
100
|
//#region src/getRawRequest.d.ts
|
package/lib/browser/index.d.mts
CHANGED
|
@@ -79,12 +79,22 @@ declare class FetchResponse extends Response {
|
|
|
79
79
|
* code represents a response that can have a body.
|
|
80
80
|
*/
|
|
81
81
|
static isResponseWithBody(status: number): boolean;
|
|
82
|
+
static setStatus(status: number, response: Response): void;
|
|
82
83
|
static setUrl(url: string | undefined, response: Response): void;
|
|
83
84
|
/**
|
|
84
85
|
* Parses the given raw HTTP headers into a Fetch API `Headers` instance.
|
|
85
86
|
*/
|
|
86
87
|
static parseRawHeaders(rawHeaders: Array<string>): Headers;
|
|
88
|
+
/**
|
|
89
|
+
* Safely clones the given `Response`.
|
|
90
|
+
* Coerces response clone exceptions into 500 mocked responses.
|
|
91
|
+
* Handy in the environments that introduce arbitrary response
|
|
92
|
+
* cloning restrictions, like "101 Switching Protocols" cloning
|
|
93
|
+
* in "miniflare".
|
|
94
|
+
*/
|
|
95
|
+
static clone(response: Response): Response;
|
|
87
96
|
constructor(body?: BodyInit | null, init?: FetchResponseInit);
|
|
97
|
+
clone(): Response;
|
|
88
98
|
}
|
|
89
99
|
//#endregion
|
|
90
100
|
//#region src/getRawRequest.d.ts
|
package/lib/browser/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as deleteGlobalSymbol, i as InterceptorReadyState, n as INTERNAL_REQUEST_ID_HEADER_NAME, o as getGlobalSymbol, r as Interceptor, t as createRequestId } from "./createRequestId-DYCsFHOi.mjs";
|
|
2
|
-
import { i as FetchResponse, o as RequestController, r as FetchRequest, t as getRawRequest } from "./getRawRequest-
|
|
2
|
+
import { i as FetchResponse, o as RequestController, r as FetchRequest, t as getRawRequest } from "./getRawRequest-B1BqgWG6.mjs";
|
|
3
3
|
import { n as encodeBuffer, t as decodeBuffer } from "./bufferUtils-BiiO6HZv.mjs";
|
|
4
4
|
import { t as resolveWebSocketUrl } from "./resolveWebSocketUrl-C83-x9iE.mjs";
|
|
5
5
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const require_createRequestId = require('../../createRequestId-DOf8Ktjs.cjs');
|
|
2
2
|
const require_resolveWebSocketUrl = require('../../resolveWebSocketUrl-6K6EgqsA.cjs');
|
|
3
|
-
const require_hasConfigurableGlobal = require('../../hasConfigurableGlobal-
|
|
3
|
+
const require_hasConfigurableGlobal = require('../../hasConfigurableGlobal-BS75Oulv.cjs');
|
|
4
4
|
let _open_draft_deferred_promise = require("@open-draft/deferred-promise");
|
|
5
5
|
let outvariant = require("outvariant");
|
|
6
6
|
|
|
@@ -601,7 +601,7 @@ var WebSocketInterceptor = class WebSocketInterceptor extends require_createRequ
|
|
|
601
601
|
return socket;
|
|
602
602
|
} });
|
|
603
603
|
logger.info("patching global WebSocket...");
|
|
604
|
-
this.subscriptions.push(require_hasConfigurableGlobal.
|
|
604
|
+
this.subscriptions.push(require_hasConfigurableGlobal.patchesRegistry.applyPatch(globalThis, "WebSocket", () => WebSocketProxy));
|
|
605
605
|
logger.info("global WebSocket patched!", globalThis.WebSocket.name);
|
|
606
606
|
}
|
|
607
607
|
};
|