@mswjs/interceptors 0.41.6 → 0.41.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/lib/browser/{XMLHttpRequest-DNly-bu0.cjs → XMLHttpRequest-B11I9TBx.cjs} +10 -8
  2. package/lib/browser/{XMLHttpRequest-DNly-bu0.cjs.map → XMLHttpRequest-B11I9TBx.cjs.map} +1 -1
  3. package/lib/browser/{XMLHttpRequest-DaQ73vVt.mjs → XMLHttpRequest-DHEkSoRN.mjs} +10 -8
  4. package/lib/{node/XMLHttpRequest-Cj07Pos7.mjs.map → browser/XMLHttpRequest-DHEkSoRN.mjs.map} +1 -1
  5. package/lib/browser/{fetch-BS6cxWzo.mjs → fetch-BJwfdses.mjs} +11 -8
  6. package/lib/browser/{fetch-BS6cxWzo.mjs.map → fetch-BJwfdses.mjs.map} +1 -1
  7. package/lib/browser/{fetch-BmrYPMQ0.cjs → fetch-M8iXkZ3L.cjs} +11 -8
  8. package/lib/browser/{fetch-BmrYPMQ0.cjs.map → fetch-M8iXkZ3L.cjs.map} +1 -1
  9. package/lib/browser/{getRawRequest-BP--nUwn.mjs → getRawRequest-B1BqgWG6.mjs} +39 -15
  10. package/lib/browser/getRawRequest-B1BqgWG6.mjs.map +1 -0
  11. package/lib/browser/{getRawRequest-B6GjFKAr.cjs → getRawRequest-DdfaiPVH.cjs} +39 -15
  12. package/lib/browser/getRawRequest-DdfaiPVH.cjs.map +1 -0
  13. package/lib/browser/{handleRequest-CnDA8MVO.mjs → handleRequest-1Yqu_ho_.mjs} +3 -3
  14. package/lib/browser/{handleRequest-CnDA8MVO.mjs.map → handleRequest-1Yqu_ho_.mjs.map} +1 -1
  15. package/lib/browser/{handleRequest-BIte-8l8.cjs → handleRequest-Cz4_wmQ9.cjs} +3 -3
  16. package/lib/browser/{handleRequest-BIte-8l8.cjs.map → handleRequest-Cz4_wmQ9.cjs.map} +1 -1
  17. package/lib/browser/{hasConfigurableGlobal-B39W0thh.mjs → hasConfigurableGlobal-C8zq1MCg.mjs} +34 -23
  18. package/lib/browser/hasConfigurableGlobal-C8zq1MCg.mjs.map +1 -0
  19. package/lib/browser/{hasConfigurableGlobal-B5o6PHq3.cjs → hasConfigurableGlobal-CS7adEvV.cjs} +37 -26
  20. package/lib/browser/hasConfigurableGlobal-CS7adEvV.cjs.map +1 -0
  21. package/lib/browser/index.cjs +1 -1
  22. package/lib/browser/index.d.cts +2 -0
  23. package/lib/browser/index.d.mts +2 -0
  24. package/lib/browser/index.mjs +1 -1
  25. package/lib/browser/interceptors/WebSocket/index.cjs +2 -2
  26. package/lib/browser/interceptors/WebSocket/index.cjs.map +1 -1
  27. package/lib/browser/interceptors/WebSocket/index.mjs +2 -2
  28. package/lib/browser/interceptors/WebSocket/index.mjs.map +1 -1
  29. package/lib/browser/interceptors/XMLHttpRequest/index.cjs +4 -4
  30. package/lib/browser/interceptors/XMLHttpRequest/index.mjs +4 -4
  31. package/lib/browser/interceptors/fetch/index.cjs +4 -4
  32. package/lib/browser/interceptors/fetch/index.mjs +4 -4
  33. package/lib/browser/presets/browser.cjs +5 -5
  34. package/lib/browser/presets/browser.mjs +5 -5
  35. package/lib/node/{BatchInterceptor-0prNZ0wK.mjs → BatchInterceptor-DdMNfSUY.mjs} +2 -2
  36. package/lib/node/{BatchInterceptor-0prNZ0wK.mjs.map → BatchInterceptor-DdMNfSUY.mjs.map} +1 -1
  37. package/lib/node/{BatchInterceptor-Bo8JunSK.cjs → BatchInterceptor-Z1lwK23r.cjs} +2 -2
  38. package/lib/node/{BatchInterceptor-Bo8JunSK.cjs.map → BatchInterceptor-Z1lwK23r.cjs.map} +1 -1
  39. package/lib/node/{ClientRequest-OY5NnrOh.cjs → ClientRequest-DFs7FPNi.cjs} +8 -7
  40. package/lib/node/ClientRequest-DFs7FPNi.cjs.map +1 -0
  41. package/lib/node/{ClientRequest-BquJl6T-.mjs → ClientRequest-dRpI9v1o.mjs} +8 -7
  42. package/lib/node/ClientRequest-dRpI9v1o.mjs.map +1 -0
  43. package/lib/node/RemoteHttpInterceptor.cjs +7 -7
  44. package/lib/node/RemoteHttpInterceptor.mjs +7 -7
  45. package/lib/node/{XMLHttpRequest-Cj07Pos7.mjs → XMLHttpRequest-DhupxLHX.mjs} +10 -8
  46. package/lib/{browser/XMLHttpRequest-DaQ73vVt.mjs.map → node/XMLHttpRequest-DhupxLHX.mjs.map} +1 -1
  47. package/lib/node/{XMLHttpRequest-C1KTngEF.cjs → XMLHttpRequest-Dyi6ahGz.cjs} +10 -8
  48. package/lib/node/{XMLHttpRequest-C1KTngEF.cjs.map → XMLHttpRequest-Dyi6ahGz.cjs.map} +1 -1
  49. package/lib/node/{fetch-UxWd1aQX.mjs → fetch-BqMcbuYR.mjs} +11 -8
  50. package/lib/node/{fetch-UxWd1aQX.mjs.map → fetch-BqMcbuYR.mjs.map} +1 -1
  51. package/lib/node/{fetch-B9UiBg-M.cjs → fetch-aQJu1Gf_.cjs} +11 -8
  52. package/lib/node/{fetch-B9UiBg-M.cjs.map → fetch-aQJu1Gf_.cjs.map} +1 -1
  53. package/lib/node/{fetchUtils-Bq0Mdmkv.mjs → fetchUtils-BKJ1XmiO.mjs} +39 -15
  54. package/lib/node/{fetchUtils-Bq0Mdmkv.mjs.map → fetchUtils-BKJ1XmiO.mjs.map} +1 -1
  55. package/lib/node/{fetchUtils-BAlG765A.cjs → fetchUtils-umV5xXBy.cjs} +39 -15
  56. package/lib/node/{fetchUtils-BAlG765A.cjs.map → fetchUtils-umV5xXBy.cjs.map} +1 -1
  57. package/lib/node/{handleRequest-u6jpjgrr.mjs → handleRequest-DCLzePtS.mjs} +2 -2
  58. package/lib/node/{handleRequest-u6jpjgrr.mjs.map → handleRequest-DCLzePtS.mjs.map} +1 -1
  59. package/lib/node/{handleRequest-DUPo40Df.cjs → handleRequest-DVOthWJo.cjs} +2 -2
  60. package/lib/node/{handleRequest-DUPo40Df.cjs.map → handleRequest-DVOthWJo.cjs.map} +1 -1
  61. package/lib/node/{hasConfigurableGlobal-jN_-v3gp.mjs → hasConfigurableGlobal-BiTmog1u.mjs} +34 -23
  62. package/lib/node/hasConfigurableGlobal-BiTmog1u.mjs.map +1 -0
  63. package/lib/node/{hasConfigurableGlobal-Befl_QJD.cjs → hasConfigurableGlobal-MjY06_Ok.cjs} +37 -26
  64. package/lib/node/hasConfigurableGlobal-MjY06_Ok.cjs.map +1 -0
  65. package/lib/node/index.cjs +2 -2
  66. package/lib/node/index.d.cts +2 -0
  67. package/lib/node/index.d.mts +2 -0
  68. package/lib/node/index.mjs +2 -2
  69. package/lib/node/interceptors/ClientRequest/index.cjs +3 -3
  70. package/lib/node/interceptors/ClientRequest/index.mjs +3 -3
  71. package/lib/node/interceptors/XMLHttpRequest/index.cjs +4 -4
  72. package/lib/node/interceptors/XMLHttpRequest/index.mjs +4 -4
  73. package/lib/node/interceptors/fetch/index.cjs +4 -4
  74. package/lib/node/interceptors/fetch/index.mjs +4 -4
  75. package/lib/node/presets/node.cjs +6 -6
  76. package/lib/node/presets/node.mjs +6 -6
  77. package/package.json +1 -1
  78. package/src/interceptors/ClientRequest/utils/recordRawHeaders.test.ts +33 -0
  79. package/src/interceptors/ClientRequest/utils/recordRawHeaders.ts +19 -4
  80. package/src/interceptors/WebSocket/index.ts +2 -2
  81. package/src/interceptors/XMLHttpRequest/index.ts +4 -5
  82. package/src/interceptors/fetch/index.ts +13 -8
  83. package/src/utils/fetchUtils.test.ts +22 -0
  84. package/src/utils/fetchUtils.ts +61 -16
  85. package/src/utils/hasConfigurableGlobal.ts +1 -1
  86. package/src/utils/patchesRegistry.test.ts +240 -0
  87. package/src/utils/patchesRegistry.ts +134 -0
  88. package/lib/browser/getRawRequest-B6GjFKAr.cjs.map +0 -1
  89. package/lib/browser/getRawRequest-BP--nUwn.mjs.map +0 -1
  90. package/lib/browser/hasConfigurableGlobal-B39W0thh.mjs.map +0 -1
  91. package/lib/browser/hasConfigurableGlobal-B5o6PHq3.cjs.map +0 -1
  92. package/lib/node/ClientRequest-BquJl6T-.mjs.map +0 -1
  93. package/lib/node/ClientRequest-OY5NnrOh.cjs.map +0 -1
  94. package/lib/node/hasConfigurableGlobal-Befl_QJD.cjs.map +0 -1
  95. package/lib/node/hasConfigurableGlobal-jN_-v3gp.mjs.map +0 -1
  96. package/src/utils/globalUtils.test.ts +0 -144
  97. package/src/utils/globalsRegistry.ts +0 -107
@@ -1,7 +1,7 @@
1
1
  import { r as Interceptor, t as createRequestId } from "./createRequestId-DYCsFHOi.mjs";
2
- import { a as canParseUrl, i as FetchResponse, n as setRawRequest, o as RequestController, r as FetchRequest } from "./getRawRequest-BP--nUwn.mjs";
3
- import { n as globalsRegistry, r as emitAsync, t as hasConfigurableGlobal } from "./hasConfigurableGlobal-B39W0thh.mjs";
4
- import { n as isResponseError, t as handleRequest } from "./handleRequest-CnDA8MVO.mjs";
2
+ import { a as canParseUrl, i as FetchResponse, n as setRawRequest, o as RequestController, r as FetchRequest } from "./getRawRequest-B1BqgWG6.mjs";
3
+ import { n as patchesRegistry, r as emitAsync, t as hasConfigurableGlobal } from "./hasConfigurableGlobal-C8zq1MCg.mjs";
4
+ import { n as isResponseError, t as handleRequest } from "./handleRequest-1Yqu_ho_.mjs";
5
5
  import { DeferredPromise } from "@open-draft/deferred-promise";
6
6
  import { until } from "@open-draft/until";
7
7
 
@@ -172,9 +172,12 @@ var FetchInterceptor = class FetchInterceptor extends Interceptor {
172
172
  return;
173
173
  }
174
174
  this.logger.info("received mocked response!", { rawResponse });
175
- const decompressedStream = decompressResponse(rawResponse);
176
- const response = decompressedStream === null ? rawResponse : new FetchResponse(decompressedStream, rawResponse);
177
- FetchResponse.setUrl(request.url, response);
175
+ const response = new FetchResponse(decompressResponse(rawResponse) || rawResponse.body, {
176
+ url: request.url,
177
+ status: rawResponse.status,
178
+ statusText: rawResponse.statusText,
179
+ headers: rawResponse.headers
180
+ });
178
181
  /**
179
182
  * Undici's handling of following redirect responses.
180
183
  * Treat the "manual" redirect mode as a regular mocked response.
@@ -223,11 +226,11 @@ var FetchInterceptor = class FetchInterceptor extends Interceptor {
223
226
  return responsePromise;
224
227
  };
225
228
  logger.info("patching global fetch...");
226
- this.subscriptions.push(globalsRegistry.replaceGlobal("fetch", fetchProxy));
229
+ this.subscriptions.push(patchesRegistry.applyPatch(globalThis, "fetch", () => fetchProxy));
227
230
  logger.info("global fetch patched!", globalThis.fetch.name);
228
231
  }
229
232
  };
230
233
 
231
234
  //#endregion
232
235
  export { FetchInterceptor as t };
233
- //# sourceMappingURL=fetch-BS6cxWzo.mjs.map
236
+ //# sourceMappingURL=fetch-BJwfdses.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-BS6cxWzo.mjs","names":["locationUrl: URL","requestInit: RequestInit","readable","fetchProxy: typeof fetch","response"],"sources":["../../src/interceptors/fetch/utils/createNetworkError.ts","../../src/interceptors/fetch/utils/followRedirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.browser.ts","../../src/interceptors/fetch/utils/decompression.ts","../../src/interceptors/fetch/index.ts"],"sourcesContent":["export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise<Response> {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","export class BrotliDecompressionStream extends TransformStream {\n constructor() {\n console.warn(\n '[Interceptors]: Brotli decompression of response streams is not supported in the browser'\n )\n\n super({\n transform(chunk, controller) {\n // Keep the stream as passthrough, it does nothing.\n controller.enqueue(chunk)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array<TransformStream>,\n ...strategies: Array<QueuingStrategy>\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array<string> {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight<Array<TransformStream>>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream<any> | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchRequest, FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\nimport { globalsRegistry } from '../../utils/globalsRegistry'\n\nexport class FetchInterceptor extends Interceptor<HttpRequestEventMap> {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const logger = this.logger.extend('setup')\n\n const pureFetch = globalThis.fetch\n\n const fetchProxy: typeof fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new FetchRequest(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise<Response>()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = FetchResponse.clone(originalResponse)\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response =\n decompressedStream === null\n ? rawResponse\n : new FetchResponse(decompressedStream, rawResponse)\n\n FetchResponse.setUrl(request.url, response)\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: FetchResponse.clone(response),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n logger.info('patching global fetch...')\n\n this.subscriptions.push(globalsRegistry.replaceGlobal('fetch', fetchProxy))\n\n logger.info('global fetch patched!', globalThis.fetch.name)\n }\n}\n"],"mappings":";;;;;;;;AAAA,SAAgB,mBAAmB,OAAiB;AAClD,QAAO,OAAO,uBAAO,IAAI,UAAU,kBAAkB,EAAE,EACrD,OACD,CAAC;;;;;ACDJ,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,iBAAiB,OAAO,iBAAiB;;;;AAK/C,eAAsB,oBACpB,SACA,UACmB;AACnB,KAAI,SAAS,WAAW,OAAO,QAAQ,QAAQ,KAC7C,QAAO,QAAQ,OAAO,oBAAoB,CAAC;CAG7C,MAAM,aAAa,IAAI,IAAI,QAAQ,IAAI;CAEvC,IAAIA;AACJ,KAAI;AAEF,gBAAc,IAAI,IAAI,SAAS,QAAQ,IAAI,WAAW,EAAG,QAAQ,IAAI;UAC9D,OAAO;AACd,SAAO,QAAQ,OAAO,mBAAmB,MAAM,CAAC;;AAGlD,KACE,EAAE,YAAY,aAAa,WAAW,YAAY,aAAa,UAE/D,QAAO,QAAQ,OACb,mBAAmB,sCAAsC,CAC1D;AAGH,KAAI,QAAQ,IAAI,SAAS,eAAe,GAAG,GACzC,QAAO,QAAQ,OAAO,mBAAmB,0BAA0B,CAAC;AAGtE,QAAO,eAAe,SAAS,gBAAgB,EAC7C,QAAQ,QAAQ,IAAI,SAAS,eAAe,IAAI,KAAK,GACtD,CAAC;AAEF,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B,OAAO,mBAAmB,sBAAsB,CAAC;AACjE;;AAGF,UAAI,QAAQ,aAAa,UAAU;AACjC,2BAAoB,SAAS,SAAS,CAAC,MACpC,eAAa;AACZ,wBAAgB,QAAQC,WAAS;WAElC,WAAW;AACV,wBAAgB,OAAO,OAAO;SAEjC;AACD;;;AAIJ,SAAI,KAAK,QAAQ,cAAc,WAAW,GAAG,GAAG;AAC9C,WAAK,OAAO,KAAK,qCAAmC;AAKpD,YAAM,UAAU,KAAK,SAAS,YAAY;OAIxC,UAAU,cAAc,MAAM,SAAS;OACvC,kBAAkB;OAClB;OACA;OACD,CAAC;;AAGJ,qBAAgB,QAAQ,SAAS;;IAEnC,YAAY,WAAW;AACrB,UAAK,OAAO,KAAK,6BAA6B,EAAE,QAAQ,CAAC;AACzD,qBAAgB,OAAO,OAAO;;IAEjC,CAAC;AAEF,QAAK,OAAO,KAAK,WAAW,QAAQ,QAAQ,QAAQ,IAAI;AACxD,QAAK,OAAO,KAAK,sCAAsC;AAEvD,QAAK,OAAO,KACV,wDACA,KAAK,QAAQ,cAAc,UAAU,CACtC;AAED,SAAM,cAAc;IAClB;IACA;IACA,SAAS,KAAK;IACd;IACD,CAAC;AAEF,UAAO;;AAGT,SAAO,KAAK,2BAA2B;AAEvC,OAAK,cAAc,KAAK,gBAAgB,cAAc,SAAS,WAAW,CAAC;AAE3E,SAAO,KAAK,yBAAyB,WAAW,MAAM,KAAK"}
1
+ {"version":3,"file":"fetch-BJwfdses.mjs","names":["locationUrl: URL","requestInit: RequestInit","readable","fetchProxy: typeof fetch","response"],"sources":["../../src/interceptors/fetch/utils/createNetworkError.ts","../../src/interceptors/fetch/utils/followRedirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.browser.ts","../../src/interceptors/fetch/utils/decompression.ts","../../src/interceptors/fetch/index.ts"],"sourcesContent":["export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise<Response> {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","export class BrotliDecompressionStream extends TransformStream {\n constructor() {\n console.warn(\n '[Interceptors]: Brotli decompression of response streams is not supported in the browser'\n )\n\n super({\n transform(chunk, controller) {\n // Keep the stream as passthrough, it does nothing.\n controller.enqueue(chunk)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array<TransformStream>,\n ...strategies: Array<QueuingStrategy>\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array<string> {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight<Array<TransformStream>>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream<any> | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchRequest, FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport class FetchInterceptor extends Interceptor<HttpRequestEventMap> {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const logger = this.logger.extend('setup')\n\n const pureFetch = globalThis.fetch\n\n const fetchProxy: typeof fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new FetchRequest(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise<Response>()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = FetchResponse.clone(originalResponse)\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response = new FetchResponse(\n decompressedStream || rawResponse.body,\n {\n url: request.url,\n status: rawResponse.status,\n statusText: rawResponse.statusText,\n headers: rawResponse.headers,\n }\n )\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: FetchResponse.clone(response),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n logger.info('patching global fetch...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'fetch', () => fetchProxy)\n )\n\n logger.info('global fetch patched!', globalThis.fetch.name)\n }\n}\n"],"mappings":";;;;;;;;AAAA,SAAgB,mBAAmB,OAAiB;AAClD,QAAO,OAAO,uBAAO,IAAI,UAAU,kBAAkB,EAAE,EACrD,OACD,CAAC;;;;;ACDJ,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,iBAAiB,OAAO,iBAAiB;;;;AAK/C,eAAsB,oBACpB,SACA,UACmB;AACnB,KAAI,SAAS,WAAW,OAAO,QAAQ,QAAQ,KAC7C,QAAO,QAAQ,OAAO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;IACd;IACD,CAAC;AAEF,UAAO;;AAGT,SAAO,KAAK,2BAA2B;AAEvC,OAAK,cAAc,KACjB,gBAAgB,WAAW,YAAY,eAAe,WAAW,CAClE;AAED,SAAO,KAAK,yBAAyB,WAAW,MAAM,KAAK"}
@@ -1,7 +1,7 @@
1
1
  const require_createRequestId = require('./createRequestId-DOf8Ktjs.cjs');
2
- const require_getRawRequest = require('./getRawRequest-B6GjFKAr.cjs');
3
- const require_hasConfigurableGlobal = require('./hasConfigurableGlobal-B5o6PHq3.cjs');
4
- const require_handleRequest = require('./handleRequest-BIte-8l8.cjs');
2
+ const require_getRawRequest = require('./getRawRequest-DdfaiPVH.cjs');
3
+ const require_hasConfigurableGlobal = require('./hasConfigurableGlobal-CS7adEvV.cjs');
4
+ const require_handleRequest = require('./handleRequest-Cz4_wmQ9.cjs');
5
5
  let _open_draft_deferred_promise = require("@open-draft/deferred-promise");
6
6
  let _open_draft_until = require("@open-draft/until");
7
7
 
@@ -172,9 +172,12 @@ var FetchInterceptor = class FetchInterceptor extends require_createRequestId.In
172
172
  return;
173
173
  }
174
174
  this.logger.info("received mocked response!", { rawResponse });
175
- const decompressedStream = decompressResponse(rawResponse);
176
- const response = decompressedStream === null ? rawResponse : new require_getRawRequest.FetchResponse(decompressedStream, rawResponse);
177
- require_getRawRequest.FetchResponse.setUrl(request.url, response);
175
+ const response = new require_getRawRequest.FetchResponse(decompressResponse(rawResponse) || rawResponse.body, {
176
+ url: request.url,
177
+ status: rawResponse.status,
178
+ statusText: rawResponse.statusText,
179
+ headers: rawResponse.headers
180
+ });
178
181
  /**
179
182
  * Undici's handling of following redirect responses.
180
183
  * Treat the "manual" redirect mode as a regular mocked response.
@@ -223,7 +226,7 @@ var FetchInterceptor = class FetchInterceptor extends require_createRequestId.In
223
226
  return responsePromise;
224
227
  };
225
228
  logger.info("patching global fetch...");
226
- this.subscriptions.push(require_hasConfigurableGlobal.globalsRegistry.replaceGlobal("fetch", fetchProxy));
229
+ this.subscriptions.push(require_hasConfigurableGlobal.patchesRegistry.applyPatch(globalThis, "fetch", () => fetchProxy));
227
230
  logger.info("global fetch patched!", globalThis.fetch.name);
228
231
  }
229
232
  };
@@ -235,4 +238,4 @@ Object.defineProperty(exports, 'FetchInterceptor', {
235
238
  return FetchInterceptor;
236
239
  }
237
240
  });
238
- //# sourceMappingURL=fetch-BmrYPMQ0.cjs.map
241
+ //# sourceMappingURL=fetch-M8iXkZ3L.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-BmrYPMQ0.cjs","names":["locationUrl: URL","requestInit: RequestInit","readable","Interceptor","hasConfigurableGlobal","fetchProxy: typeof fetch","createRequestId","FetchRequest","canParseUrl","DeferredPromise","RequestController","FetchResponse","emitAsync","isResponseError","response","handleRequest","globalsRegistry"],"sources":["../../src/interceptors/fetch/utils/createNetworkError.ts","../../src/interceptors/fetch/utils/followRedirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.browser.ts","../../src/interceptors/fetch/utils/decompression.ts","../../src/interceptors/fetch/index.ts"],"sourcesContent":["export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise<Response> {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","export class BrotliDecompressionStream extends TransformStream {\n constructor() {\n console.warn(\n '[Interceptors]: Brotli decompression of response streams is not supported in the browser'\n )\n\n super({\n transform(chunk, controller) {\n // Keep the stream as passthrough, it does nothing.\n controller.enqueue(chunk)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array<TransformStream>,\n ...strategies: Array<QueuingStrategy>\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array<string> {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight<Array<TransformStream>>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream<any> | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchRequest, FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\nimport { globalsRegistry } from '../../utils/globalsRegistry'\n\nexport class FetchInterceptor extends Interceptor<HttpRequestEventMap> {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const logger = this.logger.extend('setup')\n\n const pureFetch = globalThis.fetch\n\n const fetchProxy: typeof fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new FetchRequest(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise<Response>()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = FetchResponse.clone(originalResponse)\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response =\n decompressedStream === null\n ? rawResponse\n : new FetchResponse(decompressedStream, rawResponse)\n\n FetchResponse.setUrl(request.url, response)\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: FetchResponse.clone(response),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n logger.info('patching global fetch...')\n\n this.subscriptions.push(globalsRegistry.replaceGlobal('fetch', fetchProxy))\n\n logger.info('global fetch patched!', globalThis.fetch.name)\n }\n}\n"],"mappings":";;;;;;;;AAAA,SAAgB,mBAAmB,OAAiB;AAClD,QAAO,OAAO,uBAAO,IAAI,UAAU,kBAAkB,EAAE,EACrD,OACD,CAAC;;;;;ACDJ,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,iBAAiB,OAAO,iBAAiB;;;;AAK/C,eAAsB,oBACpB,SACA,UACmB;AACnB,KAAI,SAAS,WAAW,OAAO,QAAQ,QAAQ,KAC7C,QAAO,QAAQ,OAAO,oBAAoB,CAAC;CAG7C,MAAM,aAAa,IAAI,IAAI,QAAQ,IAAI;CAEvC,IAAIA;AACJ,KAAI;AAEF,gBAAc,IAAI,IAAI,SAAS,QAAQ,IAAI,WAAW,EAAG,QAAQ,IAAI;UAC9D,OAAO;AACd,SAAO,QAAQ,OAAO,mBAAmB,MAAM,CAAC;;AAGlD,KACE,EAAE,YAAY,aAAa,WAAW,YAAY,aAAa,UAE/D,QAAO,QAAQ,OACb,mBAAmB,sCAAsC,CAC1D;AAGH,KAAI,QAAQ,IAAI,SAAS,eAAe,GAAG,GACzC,QAAO,QAAQ,OAAO,mBAAmB,0BAA0B,CAAC;AAGtE,QAAO,eAAe,SAAS,gBAAgB,EAC7C,QAAQ,QAAQ,IAAI,SAAS,eAAe,IAAI,KAAK,GACtD,CAAC;AAEF,KACE,QAAQ,SA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AAgB,OAAO,mBAAmB,sBAAsB,CAAC;AACjE;;AAGF,UAAI,QAAQ,aAAa,UAAU;AACjC,2BAAoB,SAAS,SAAS,CAAC,MACpC,eAAa;AACZ,wBAAgB,QAAQG,WAAS;WAElC,WAAW;AACV,wBAAgB,OAAO,OAAO;SAEjC;AACD;;;AAIJ,SAAI,KAAK,QAAQ,cAAc,WAAW,GAAG,GAAG;AAC9C,WAAK,OAAO,KAAK,qCAAmC;AAKpD,YAAMF,wCAAU,KAAK,SAAS,YAAY;OAIxC,UAAUD,oCAAc,MAAM,SAAS;OACvC,kBAAkB;OAClB;OACA;OACD,CAAC;;AAGJ,qBAAgB,QAAQ,SAAS;;IAEnC,YAAY,WAAW;AACrB,UAAK,OAAO,KAAK,6BAA6B,EAAE,QAAQ,CAAC;AACzD,qBAAgB,OAAO,OAAO;;IAEjC,CAAC;AAEF,QAAK,OAAO,KAAK,WAAW,QAAQ,QAAQ,QAAQ,IAAI;AACxD,QAAK,OAAO,KAAK,sCAAsC;AAEvD,QAAK,OAAO,KACV,wDACA,KAAK,QAAQ,cAAc,UAAU,CACtC;AAED,SAAMI,oCAAc;IAClB;IACA;IACA,SAAS,KAAK;IACd;IACD,CAAC;AAEF,UAAO;;AAGT,SAAO,KAAK,2BAA2B;AAEvC,OAAK,cAAc,KAAKC,8CAAgB,cAAc,SAAS,WAAW,CAAC;AAE3E,SAAO,KAAK,yBAAyB,WAAW,MAAM,KAAK"}
1
+ {"version":3,"file":"fetch-M8iXkZ3L.cjs","names":["locationUrl: URL","requestInit: RequestInit","readable","Interceptor","hasConfigurableGlobal","fetchProxy: typeof fetch","createRequestId","FetchRequest","canParseUrl","DeferredPromise","RequestController","FetchResponse","emitAsync","isResponseError","response","handleRequest","patchesRegistry"],"sources":["../../src/interceptors/fetch/utils/createNetworkError.ts","../../src/interceptors/fetch/utils/followRedirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.browser.ts","../../src/interceptors/fetch/utils/decompression.ts","../../src/interceptors/fetch/index.ts"],"sourcesContent":["export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise<Response> {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","export class BrotliDecompressionStream extends TransformStream {\n constructor() {\n console.warn(\n '[Interceptors]: Brotli decompression of response streams is not supported in the browser'\n )\n\n super({\n transform(chunk, controller) {\n // Keep the stream as passthrough, it does nothing.\n controller.enqueue(chunk)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array<TransformStream>,\n ...strategies: Array<QueuingStrategy>\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array<string> {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight<Array<TransformStream>>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream<any> | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchRequest, FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport class FetchInterceptor extends Interceptor<HttpRequestEventMap> {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const logger = this.logger.extend('setup')\n\n const pureFetch = globalThis.fetch\n\n const fetchProxy: typeof fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new FetchRequest(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise<Response>()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = FetchResponse.clone(originalResponse)\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response = new FetchResponse(\n decompressedStream || rawResponse.body,\n {\n url: request.url,\n status: rawResponse.status,\n statusText: rawResponse.statusText,\n headers: rawResponse.headers,\n }\n )\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: FetchResponse.clone(response),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n logger.info('patching global fetch...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'fetch', () => fetchProxy)\n )\n\n logger.info('global fetch patched!', globalThis.fetch.name)\n }\n}\n"],"mappings":";;;;;;;;AAAA,SAAgB,mBAAmB,OAAiB;AAClD,QAAO,OAAO,uBAAO,IAAI,UAAU,kBAAkB,EAAE,EACrD,OACD,CAAC;;;;;ACDJ,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,iBAAiB,OAA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I;AACxD,QAAK,OAAO,KAAK,sCAAsC;AAEvD,QAAK,OAAO,KACV,wDACA,KAAK,QAAQ,cAAc,UAAU,CACtC;AAED,SAAMI,oCAAc;IAClB;IACA;IACA,SAAS,KAAK;IACd;IACD,CAAC;AAEF,UAAO;;AAGT,SAAO,KAAK,2BAA2B;AAEvC,OAAK,cAAc,KACjBC,8CAAgB,WAAW,YAAY,eAAe,WAAW,CAClE;AAED,SAAO,KAAK,yBAAyB,WAAW,MAAM,KAAK"}
@@ -185,6 +185,8 @@ var FetchRequest = class FetchRequest extends Request {
185
185
  });
186
186
  }
187
187
  };
188
+ const kStatus = Symbol("kStatus");
189
+ const kUrl = Symbol("kUrl");
188
190
  var FetchResponse = class FetchResponse extends Response {
189
191
  static {
190
192
  this.STATUS_CODES_WITHOUT_BODY = [
@@ -217,6 +219,24 @@ var FetchResponse = class FetchResponse extends Response {
217
219
  static isResponseWithBody(status) {
218
220
  return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status);
219
221
  }
222
+ static setStatus(status, response) {
223
+ /**
224
+ * @note Undici keeps an internal "Symbol(state)" that holds
225
+ * the actual value of response status. Update that in Node.js.
226
+ */
227
+ const internalState = getValueBySymbol("state", response);
228
+ if (internalState) internalState.status = status;
229
+ else Object.defineProperty(response, "status", {
230
+ value: status,
231
+ enumerable: true,
232
+ configurable: true,
233
+ writable: false
234
+ });
235
+ Object.defineProperty(response, kStatus, {
236
+ value: status,
237
+ enumerable: false
238
+ });
239
+ }
220
240
  static setUrl(url, response) {
221
241
  if (!url || url === "about:" || !canParseUrl(url)) return;
222
242
  const state = getValueBySymbol("state", response);
@@ -227,6 +247,10 @@ var FetchResponse = class FetchResponse extends Response {
227
247
  configurable: true,
228
248
  writable: false
229
249
  });
250
+ Object.defineProperty(response, kUrl, {
251
+ value: url,
252
+ enumerable: false
253
+ });
230
254
  }
231
255
  /**
232
256
  * Parses the given raw HTTP headers into a Fetch API `Headers` instance.
@@ -266,22 +290,22 @@ var FetchResponse = class FetchResponse extends Response {
266
290
  statusText: init.statusText,
267
291
  headers: init.headers
268
292
  });
269
- if (status !== safeStatus) {
270
- /**
271
- * @note Undici keeps an internal "Symbol(state)" that holds
272
- * the actual value of response status. Update that in Node.js.
273
- */
274
- const state = getValueBySymbol("state", this);
275
- if (state) state.status = status;
276
- else Object.defineProperty(this, "status", {
277
- value: status,
278
- enumerable: true,
279
- configurable: true,
280
- writable: false
281
- });
282
- }
293
+ /**
294
+ * Since Node.js v24, Undici stores the Response state in an inaccessible field "#state".
295
+ * Forward the modified status/URL to the cloned response manually.
296
+ * @see https://github.com/nodejs/undici/blob/f734c87280e626c75f59aad55b65eb6a89cef392/lib/web/fetch/response.js#L242
297
+ */
298
+ if (status !== safeStatus) FetchResponse.setStatus(status, this);
283
299
  FetchResponse.setUrl(init.url, this);
284
300
  }
301
+ clone() {
302
+ const clonedResponse = super.clone();
303
+ const customStatus = Reflect.get(this, kStatus);
304
+ if (customStatus) FetchResponse.setStatus(customStatus, clonedResponse);
305
+ const customUrl = Reflect.get(this, kUrl);
306
+ if (customUrl) FetchResponse.setUrl(customUrl, clonedResponse);
307
+ return clonedResponse;
308
+ }
285
309
  };
286
310
 
287
311
  //#endregion
@@ -308,4 +332,4 @@ function setRawRequest(request, rawRequest) {
308
332
 
309
333
  //#endregion
310
334
  export { canParseUrl as a, FetchResponse as i, setRawRequest as n, RequestController as o, FetchRequest as r, InterceptorError as s, getRawRequest as t };
311
- //# sourceMappingURL=getRawRequest-BP--nUwn.mjs.map
335
+ //# sourceMappingURL=getRawRequest-B1BqgWG6.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getRawRequest-B1BqgWG6.mjs","names":["request: Request","source: RequestControllerSource","#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;EAFmB;EACA;AAEnB,OAAK,aAAa,kBAAkB;AACpC,OAAK,UAAU,IAAI,iBAAuB;;CAG5C,KAAIC,UAAW;AACb,SAAO,KAAK;;;;;CAMd,MAAa,cAA6B;AACxC,YAAU,GACR,kBACA,KAAK,eAAe,kBAAkB,SACtC,qFACA,KAAK,QAAQ,QACb,KAAK,QAAQ,IACd;AAED,OAAK,aAAa,kBAAkB;AACpC,QAAM,KAAK,OAAO,aAAa;AAC/B,QAAKA,QAAS,SAAS;;;;;;;;;;CAWzB,AAAO,YAAY,UAA0B;AAC3C,YAAU,GACR,kBACA,KAAK,eAA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wB,OAA0B,EAAE,EAAE;EAChE,MAAM,SAAS,KAAK,UAAU;EAC9B,MAAM,aAAa,cAAc,yBAAyB,OAAO,GAC7D,SACA;EACJ,MAAM,YAAY,cAAc,mBAAmB,OAAO,GAAG,OAAO;AAEpE,QAAM,WAAW;GACf,QAAQ;GACR,YAAY,KAAK;GACjB,SAAS,KAAK;GACf,CAAC;;;;;;AAOF,MAAI,WAAW,WACb,eAAc,UAAU,QAAQ,KAAK;AAGvC,gBAAc,OAAO,KAAK,KAAK,KAAK;;CAGtC,AAAO,QAAQ;EACb,MAAM,iBAAiB,MAAM,OAAO;EAEpC,MAAM,eAAe,QAAQ,IAAI,MAAM,QAAQ;AAE/C,MAAI,aACF,eAAc,UAAU,cAAc,eAAe;EAGvD,MAAM,YAAY,QAAQ,IAAI,MAAM,KAAK;AAEzC,MAAI,UACF,eAAc,OAAO,WAAW,eAAe;AAGjD,SAAO;;;;;;ACrUX,MAAM,cAAc,OAAO,cAAc;;;;;;;;;;;;;AAczC,SAAgB,cAAc,SAAuC;AACnE,QAAO,QAAQ,IAAI,SAAS,YAAY;;AAG1C,SAAgB,cAAc,SAAkB,YAA2B;AACzE,SAAQ,IAAI,SAAS,aAAa,WAAW"}
@@ -185,6 +185,8 @@ var FetchRequest = class FetchRequest extends Request {
185
185
  });
186
186
  }
187
187
  };
188
+ const kStatus = Symbol("kStatus");
189
+ const kUrl = Symbol("kUrl");
188
190
  var FetchResponse = class FetchResponse extends Response {
189
191
  static {
190
192
  this.STATUS_CODES_WITHOUT_BODY = [
@@ -217,6 +219,24 @@ var FetchResponse = class FetchResponse extends Response {
217
219
  static isResponseWithBody(status) {
218
220
  return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status);
219
221
  }
222
+ static setStatus(status, response) {
223
+ /**
224
+ * @note Undici keeps an internal "Symbol(state)" that holds
225
+ * the actual value of response status. Update that in Node.js.
226
+ */
227
+ const internalState = getValueBySymbol("state", response);
228
+ if (internalState) internalState.status = status;
229
+ else Object.defineProperty(response, "status", {
230
+ value: status,
231
+ enumerable: true,
232
+ configurable: true,
233
+ writable: false
234
+ });
235
+ Object.defineProperty(response, kStatus, {
236
+ value: status,
237
+ enumerable: false
238
+ });
239
+ }
220
240
  static setUrl(url, response) {
221
241
  if (!url || url === "about:" || !canParseUrl(url)) return;
222
242
  const state = getValueBySymbol("state", response);
@@ -227,6 +247,10 @@ var FetchResponse = class FetchResponse extends Response {
227
247
  configurable: true,
228
248
  writable: false
229
249
  });
250
+ Object.defineProperty(response, kUrl, {
251
+ value: url,
252
+ enumerable: false
253
+ });
230
254
  }
231
255
  /**
232
256
  * Parses the given raw HTTP headers into a Fetch API `Headers` instance.
@@ -266,22 +290,22 @@ var FetchResponse = class FetchResponse extends Response {
266
290
  statusText: init.statusText,
267
291
  headers: init.headers
268
292
  });
269
- if (status !== safeStatus) {
270
- /**
271
- * @note Undici keeps an internal "Symbol(state)" that holds
272
- * the actual value of response status. Update that in Node.js.
273
- */
274
- const state = getValueBySymbol("state", this);
275
- if (state) state.status = status;
276
- else Object.defineProperty(this, "status", {
277
- value: status,
278
- enumerable: true,
279
- configurable: true,
280
- writable: false
281
- });
282
- }
293
+ /**
294
+ * Since Node.js v24, Undici stores the Response state in an inaccessible field "#state".
295
+ * Forward the modified status/URL to the cloned response manually.
296
+ * @see https://github.com/nodejs/undici/blob/f734c87280e626c75f59aad55b65eb6a89cef392/lib/web/fetch/response.js#L242
297
+ */
298
+ if (status !== safeStatus) FetchResponse.setStatus(status, this);
283
299
  FetchResponse.setUrl(init.url, this);
284
300
  }
301
+ clone() {
302
+ const clonedResponse = super.clone();
303
+ const customStatus = Reflect.get(this, kStatus);
304
+ if (customStatus) FetchResponse.setStatus(customStatus, clonedResponse);
305
+ const customUrl = Reflect.get(this, kUrl);
306
+ if (customUrl) FetchResponse.setUrl(customUrl, clonedResponse);
307
+ return clonedResponse;
308
+ }
285
309
  };
286
310
 
287
311
  //#endregion
@@ -349,4 +373,4 @@ Object.defineProperty(exports, 'setRawRequest', {
349
373
  return setRawRequest;
350
374
  }
351
375
  });
352
- //# sourceMappingURL=getRawRequest-B6GjFKAr.cjs.map
376
+ //# sourceMappingURL=getRawRequest-DdfaiPVH.cjs.map
@@ -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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import { r as emitAsync } from "./hasConfigurableGlobal-B39W0thh.mjs";
1
+ import { o as RequestController, s as InterceptorError } from "./getRawRequest-B1BqgWG6.mjs";
2
+ import { r as emitAsync } from "./hasConfigurableGlobal-C8zq1MCg.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-CnDA8MVO.mjs.map
178
+ //# sourceMappingURL=handleRequest-1Yqu_ho_.mjs.map