@mswjs/interceptors 0.28.1 → 0.28.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/browser/{chunk-UJZOJSMP.mjs → chunk-6HYIRFX2.mjs} +2 -15
- package/lib/browser/chunk-6HYIRFX2.mjs.map +1 -0
- package/lib/browser/chunk-F2F5QHHJ.js +39 -0
- package/lib/browser/chunk-F2F5QHHJ.js.map +1 -0
- package/lib/browser/{chunk-BUK5B6JV.js → chunk-LAEV5ZGV.js} +17 -25
- package/lib/browser/chunk-LAEV5ZGV.js.map +1 -0
- package/lib/browser/{chunk-OJ2CN4LS.js → chunk-LK6DILFK.js} +2 -15
- package/lib/browser/chunk-LK6DILFK.js.map +1 -0
- package/lib/browser/{chunk-LRLSJWIP.mjs → chunk-NIWUC7GF.mjs} +42 -46
- package/lib/browser/chunk-NIWUC7GF.mjs.map +1 -0
- package/lib/browser/{chunk-DJQVIQNN.mjs → chunk-PXSYFJ7G.mjs} +11 -19
- package/lib/browser/chunk-PXSYFJ7G.mjs.map +1 -0
- package/lib/browser/{chunk-4RNZUHJE.js → chunk-RLGVQZ5O.js} +44 -48
- package/lib/browser/chunk-RLGVQZ5O.js.map +1 -0
- package/lib/browser/chunk-VISYSKLR.mjs +39 -0
- package/lib/browser/chunk-VISYSKLR.mjs.map +1 -0
- package/lib/browser/index.js +3 -3
- package/lib/browser/index.mjs +5 -5
- package/lib/browser/interceptors/XMLHttpRequest/index.js +4 -4
- package/lib/browser/interceptors/XMLHttpRequest/index.mjs +3 -3
- package/lib/browser/interceptors/fetch/index.js +3 -3
- package/lib/browser/interceptors/fetch/index.mjs +2 -2
- package/lib/browser/presets/browser.js +6 -6
- package/lib/browser/presets/browser.mjs +4 -4
- package/lib/node/RemoteHttpInterceptor.js +8 -9
- package/lib/node/RemoteHttpInterceptor.js.map +1 -1
- package/lib/node/RemoteHttpInterceptor.mjs +4 -5
- package/lib/node/RemoteHttpInterceptor.mjs.map +1 -1
- package/lib/node/{chunk-GUY7XK43.mjs → chunk-2SC4AD6S.mjs} +2 -2
- package/lib/node/{chunk-QED3Q6Z2.mjs → chunk-DQ5DO3KN.mjs} +34 -2
- package/lib/node/chunk-DQ5DO3KN.mjs.map +1 -0
- package/lib/node/{chunk-GXADOCKV.mjs → chunk-KGNKRQ7B.mjs} +10 -20
- package/lib/node/chunk-KGNKRQ7B.mjs.map +1 -0
- package/lib/node/{chunk-TIPR373R.js → chunk-KRDNUBDZ.js} +34 -2
- package/lib/node/chunk-KRDNUBDZ.js.map +1 -0
- package/lib/node/{chunk-MMDNOPXM.mjs → chunk-L576JLIX.mjs} +13 -25
- package/lib/node/chunk-L576JLIX.mjs.map +1 -0
- package/lib/node/{chunk-SUPZUWTB.js → chunk-M4JXH4RP.js} +13 -23
- package/lib/node/chunk-M4JXH4RP.js.map +1 -0
- package/lib/node/{chunk-PVWK3YQT.js → chunk-UXEUSYDY.js} +16 -28
- package/lib/node/chunk-UXEUSYDY.js.map +1 -0
- package/lib/node/{chunk-LMCO6WE2.js → chunk-Z2DPXZWN.js} +3 -3
- package/lib/node/index.js +4 -6
- package/lib/node/index.js.map +1 -1
- package/lib/node/index.mjs +4 -6
- package/lib/node/index.mjs.map +1 -1
- package/lib/node/interceptors/ClientRequest/index.js +3 -4
- package/lib/node/interceptors/ClientRequest/index.mjs +2 -3
- package/lib/node/interceptors/XMLHttpRequest/index.js +3 -4
- package/lib/node/interceptors/XMLHttpRequest/index.mjs +2 -3
- package/lib/node/interceptors/fetch/index.js +42 -46
- package/lib/node/interceptors/fetch/index.js.map +1 -1
- package/lib/node/interceptors/fetch/index.mjs +41 -45
- package/lib/node/interceptors/fetch/index.mjs.map +1 -1
- package/lib/node/presets/node.js +5 -6
- package/lib/node/presets/node.js.map +1 -1
- package/lib/node/presets/node.mjs +3 -4
- package/lib/node/presets/node.mjs.map +1 -1
- package/package.json +1 -1
- package/src/interceptors/ClientRequest/NodeClientRequest.ts +16 -22
- package/src/interceptors/ClientRequest/index.test.ts +1 -1
- package/src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +10 -22
- package/src/interceptors/fetch/index.ts +53 -54
- package/src/utils/responseUtils.ts +24 -0
- package/lib/browser/chunk-4RNZUHJE.js.map +0 -1
- package/lib/browser/chunk-BUK5B6JV.js.map +0 -1
- package/lib/browser/chunk-DJQVIQNN.mjs.map +0 -1
- package/lib/browser/chunk-FZJKKO5H.js +0 -7
- package/lib/browser/chunk-FZJKKO5H.js.map +0 -1
- package/lib/browser/chunk-HAGW22AN.mjs +0 -7
- package/lib/browser/chunk-HAGW22AN.mjs.map +0 -1
- package/lib/browser/chunk-LRLSJWIP.mjs.map +0 -1
- package/lib/browser/chunk-OJ2CN4LS.js.map +0 -1
- package/lib/browser/chunk-UJZOJSMP.mjs.map +0 -1
- package/lib/node/chunk-GXADOCKV.mjs.map +0 -1
- package/lib/node/chunk-IBYBTTYK.mjs +0 -16
- package/lib/node/chunk-IBYBTTYK.mjs.map +0 -1
- package/lib/node/chunk-JSSEHRRB.js +0 -16
- package/lib/node/chunk-JSSEHRRB.js.map +0 -1
- package/lib/node/chunk-MMDNOPXM.mjs.map +0 -1
- package/lib/node/chunk-PVWK3YQT.js.map +0 -1
- package/lib/node/chunk-QED3Q6Z2.mjs.map +0 -1
- package/lib/node/chunk-SUPZUWTB.js.map +0 -1
- package/lib/node/chunk-TIPR373R.js.map +0 -1
- /package/lib/node/{chunk-GUY7XK43.mjs.map → chunk-2SC4AD6S.mjs.map} +0 -0
- /package/lib/node/{chunk-LMCO6WE2.js.map → chunk-Z2DPXZWN.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/interceptors/ClientRequest/index.ts","../../src/interceptors/ClientRequest/NodeClientRequest.ts","../../src/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.ts","../../src/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.ts","../../src/interceptors/ClientRequest/utils/cloneIncomingMessage.ts","../../src/interceptors/ClientRequest/utils/createResponse.ts","../../src/interceptors/ClientRequest/utils/createRequest.ts","../../src/utils/getValueBySymbol.ts","../../src/utils/isObject.ts","../../src/utils/getRawFetchHeaders.ts","../../src/utils/isNodeLikeError.ts","../../src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts","../../src/utils/getRequestOptionsByUrl.ts","../../src/utils/getUrlByRequestOptions.ts","../../src/utils/cloneObject.ts","../../src/interceptors/ClientRequest/http.get.ts","../../src/interceptors/ClientRequest/http.request.ts"],"sourcesContent":["import http from 'http'\nimport https from 'https'\nimport type { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { get } from './http.get'\nimport { request } from './http.request'\nimport { NodeClientOptions, Protocol } from './NodeClientRequest'\n\nexport type ClientRequestEmitter = Emitter<HttpRequestEventMap>\n\nexport type ClientRequestModules = Map<Protocol, typeof http | typeof https>\n\n/**\n * Intercept requests made via the `ClientRequest` class.\n * Such requests include `http.get`, `https.request`, etc.\n */\nexport class ClientRequestInterceptor extends Interceptor<HttpRequestEventMap> {\n static interceptorSymbol = Symbol('http')\n private modules: ClientRequestModules\n\n constructor() {\n super(ClientRequestInterceptor.interceptorSymbol)\n\n this.modules = new Map()\n this.modules.set('http', http)\n this.modules.set('https', https)\n }\n\n protected setup(): void {\n const logger = this.logger.extend('setup')\n\n for (const [protocol, requestModule] of this.modules) {\n const { request: pureRequest, get: pureGet } = requestModule\n\n this.subscriptions.push(() => {\n requestModule.request = pureRequest\n requestModule.get = pureGet\n\n logger.info('native \"%s\" module restored!', protocol)\n })\n\n const options: NodeClientOptions = {\n emitter: this.emitter,\n logger: this.logger,\n }\n\n // @ts-ignore\n requestModule.request =\n // Force a line break.\n request(protocol, options)\n\n // @ts-ignore\n requestModule.get =\n // Force a line break.\n get(protocol, options)\n\n logger.info('native \"%s\" module patched!', protocol)\n }\n }\n}\n","import { ClientRequest, IncomingMessage, STATUS_CODES } from 'node:http'\nimport type { Logger } from '@open-draft/logger'\nimport { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport type { ClientRequestEmitter } from '.'\nimport {\n ClientRequestEndCallback,\n ClientRequestEndChunk,\n normalizeClientRequestEndArgs,\n} from './utils/normalizeClientRequestEndArgs'\nimport { NormalizedClientRequestArgs } from './utils/normalizeClientRequestArgs'\nimport {\n ClientRequestWriteArgs,\n normalizeClientRequestWriteArgs,\n} from './utils/normalizeClientRequestWriteArgs'\nimport { cloneIncomingMessage } from './utils/cloneIncomingMessage'\nimport { createResponse } from './utils/createResponse'\nimport { createRequest } from './utils/createRequest'\nimport { toInteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { getRawFetchHeaders } from '../../utils/getRawFetchHeaders'\nimport { isPropertyAccessible } from '../../utils/isPropertyAccessible'\nimport { isNodeLikeError } from '../../utils/isNodeLikeError'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\nimport { createServerErrorResponse } from '../../utils/responseUtils'\n\nexport type Protocol = 'http' | 'https'\n\nenum HttpClientInternalState {\n // Have the concept of an idle request because different\n // request methods can kick off request sending\n // (e.g. \".end()\" or \".flushHeaders()\").\n Idle,\n Sending,\n Sent,\n MockLookupStart,\n MockLookupEnd,\n ResponseReceived,\n}\n\nexport interface NodeClientOptions {\n emitter: ClientRequestEmitter\n logger: Logger\n}\n\nexport class NodeClientRequest extends ClientRequest {\n /**\n * The list of internal Node.js errors to suppress while\n * using the \"mock\" response source.\n */\n static suppressErrorCodes = [\n 'ENOTFOUND',\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EAI_AGAIN',\n 'ENETUNREACH',\n 'EHOSTUNREACH',\n ]\n\n /**\n * Internal state of the request.\n */\n private state: HttpClientInternalState\n private responseType?: 'mock' | 'passthrough'\n private response: IncomingMessage\n private emitter: ClientRequestEmitter\n private logger: Logger\n private chunks: Array<{\n chunk?: string | Buffer\n encoding?: BufferEncoding\n }> = []\n private capturedError?: NodeJS.ErrnoException\n\n public url: URL\n public requestBuffer: Buffer | null\n\n constructor(\n [url, requestOptions, callback]: NormalizedClientRequestArgs,\n options: NodeClientOptions\n ) {\n super(requestOptions, callback)\n\n this.logger = options.logger.extend(\n `request ${requestOptions.method} ${url.href}`\n )\n\n this.logger.info('constructing ClientRequest using options:', {\n url,\n requestOptions,\n callback,\n })\n\n this.state = HttpClientInternalState.Idle\n this.url = url\n this.emitter = options.emitter\n\n // Set request buffer to null by default so that GET/HEAD requests\n // without a body wouldn't suddenly get one.\n this.requestBuffer = null\n\n // Construct a mocked response message.\n this.response = new IncomingMessage(this.socket!)\n }\n\n private writeRequestBodyChunk(\n chunk: string | Buffer | null,\n encoding?: BufferEncoding\n ): void {\n if (chunk == null) {\n return\n }\n\n if (this.requestBuffer == null) {\n this.requestBuffer = Buffer.from([])\n }\n\n const resolvedChunk = Buffer.isBuffer(chunk)\n ? chunk\n : Buffer.from(chunk, encoding)\n\n this.requestBuffer = Buffer.concat([this.requestBuffer, resolvedChunk])\n }\n\n write(...args: ClientRequestWriteArgs): boolean {\n const [chunk, encoding, callback] = normalizeClientRequestWriteArgs(args)\n this.logger.info('write:', { chunk, encoding, callback })\n this.chunks.push({ chunk, encoding })\n\n // Write each request body chunk to the internal buffer.\n this.writeRequestBodyChunk(chunk, encoding)\n\n this.logger.info(\n 'chunk successfully stored!',\n this.requestBuffer?.byteLength\n )\n\n /**\n * Prevent invoking the callback if the written chunk is empty.\n * @see https://nodejs.org/api/http.html#requestwritechunk-encoding-callback\n */\n if (!chunk || chunk.length === 0) {\n this.logger.info('written chunk is empty, skipping callback...')\n } else {\n callback?.()\n }\n\n // Do not write the request body chunks to prevent\n // the Socket from sending data to a potentially existing\n // server when there is a mocked response defined.\n return true\n }\n\n end(...args: any): this {\n this.logger.info('end', args)\n\n const requestId = createRequestId()\n\n const [chunk, encoding, callback] = normalizeClientRequestEndArgs(...args)\n this.logger.info('normalized arguments:', { chunk, encoding, callback })\n\n // Write the last request body chunk passed to the \"end()\" method.\n this.writeRequestBodyChunk(chunk, encoding || undefined)\n\n /**\n * @note Mark the request as sent immediately when invoking \".end()\".\n * In Node.js, calling \".end()\" will flush the remaining request body\n * and mark the request as \"finished\" immediately (\"end\" is synchronous)\n * but we delegate that property update to:\n *\n * - respondWith(), in the case of mocked responses;\n * - super.end(), in the case of bypassed responses.\n *\n * For that reason, we have to keep an internal flag for a finished request.\n */\n this.state = HttpClientInternalState.Sent\n\n const capturedRequest = createRequest(this)\n const { interactiveRequest, requestController } =\n toInteractiveRequest(capturedRequest)\n\n /**\n * @todo Remove this modification of the original request\n * and expose the controller alongside it in the \"request\"\n * listener argument.\n */\n Object.defineProperty(capturedRequest, 'respondWith', {\n value: requestController.respondWith.bind(requestController),\n })\n\n // Prevent handling this request if it has already been handled\n // in another (parent) interceptor (like XMLHttpRequest -> ClientRequest).\n // That means some interceptor up the chain has concluded that\n // this request must be performed as-is.\n if (this.hasHeader(INTERNAL_REQUEST_ID_HEADER_NAME)) {\n this.removeHeader(INTERNAL_REQUEST_ID_HEADER_NAME)\n return this.passthrough(chunk, encoding, callback)\n }\n\n // Add the last \"request\" listener that always resolves\n // the pending response Promise. This way if the consumer\n // hasn't handled the request themselves, we will prevent\n // the response Promise from pending indefinitely.\n this.emitter.once('request', ({ requestId: pendingRequestId }) => {\n /**\n * @note Ignore request events emitted by irrelevant\n * requests. This happens when response patching.\n */\n if (pendingRequestId !== requestId) {\n return\n }\n\n if (requestController.responsePromise.state === 'pending') {\n this.logger.info(\n 'request has not been handled in listeners, executing fail-safe listener...'\n )\n\n requestController.responsePromise.resolve(undefined)\n }\n })\n\n // Execute the resolver Promise like a side-effect.\n // Node.js 16 forces \"ClientRequest.end\" to be synchronous and return \"this\".\n until<unknown, Response | undefined>(async () => {\n // Notify the interceptor about the request.\n // This will call any \"request\" listeners the users have.\n this.logger.info(\n 'emitting the \"request\" event for %d listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n this.state = HttpClientInternalState.MockLookupStart\n\n await emitAsync(this.emitter, 'request', {\n request: interactiveRequest,\n requestId,\n })\n\n this.logger.info('all \"request\" listeners done!')\n\n const mockedResponse = await requestController.responsePromise\n this.logger.info('event.respondWith called with:', mockedResponse)\n\n return mockedResponse\n }).then((resolverResult) => {\n this.logger.info('the listeners promise awaited!')\n\n this.state = HttpClientInternalState.MockLookupEnd\n\n /**\n * @fixme We are in the \"end()\" method that still executes in parallel\n * to our mocking logic here. This can be solved by migrating to the\n * Proxy-based approach and deferring the passthrough \"end()\" properly.\n * @see https://github.com/mswjs/interceptors/issues/346\n */\n if (!this.headersSent) {\n // Forward any request headers that the \"request\" listener\n // may have modified before proceeding with this request.\n for (const [headerName, headerValue] of capturedRequest.headers) {\n this.setHeader(headerName, headerValue)\n }\n }\n\n if (resolverResult.error) {\n this.logger.info(\n 'unhandled resolver exception, coercing to an error response...',\n resolverResult.error\n )\n\n // Treat thrown Responses as mocked responses.\n if (resolverResult.error instanceof Response) {\n this.respondWith(resolverResult.error)\n return\n }\n\n // Allow throwing Node.js-like errors, like connection rejection errors.\n // Treat them as request errors.\n if (isNodeLikeError(resolverResult.error)) {\n this.errorWith(resolverResult.error)\n return this\n }\n\n // Unhandled exceptions in the request listeners are\n // synonymous to unhandled exceptions on the server.\n // Those are represented as 500 error responses.\n this.respondWith(createServerErrorResponse(resolverResult.error))\n\n return this\n }\n\n const mockedResponse = resolverResult.data\n\n if (mockedResponse) {\n this.logger.info(\n 'received mocked response:',\n mockedResponse.status,\n mockedResponse.statusText\n )\n\n /**\n * @note Ignore this request being destroyed by TLS in Node.js\n * due to connection errors.\n */\n this.destroyed = false\n\n // Handle mocked \"Response.error\" network error responses.\n if (\n /**\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\n isPropertyAccessible(mockedResponse, 'type') &&\n mockedResponse.type === 'error'\n ) {\n this.logger.info(\n 'received network error response, erroring request...'\n )\n\n /**\n * There is no standardized error format for network errors\n * in Node.js. Instead, emit a generic TypeError.\n */\n this.errorWith(new TypeError('Network error'))\n\n return this\n }\n\n const responseClone = mockedResponse.clone()\n\n this.respondWith(mockedResponse)\n this.logger.info(\n mockedResponse.status,\n mockedResponse.statusText,\n '(MOCKED)'\n )\n\n callback?.()\n\n this.logger.info('emitting the custom \"response\" event...')\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: true,\n request: capturedRequest,\n requestId,\n })\n\n this.logger.info('request (mock) is completed')\n\n return this\n }\n\n this.logger.info('no mocked response received!')\n\n this.once('response-internal', (message: IncomingMessage) => {\n this.logger.info(message.statusCode, message.statusMessage)\n this.logger.info('original response headers:', message.headers)\n\n this.logger.info('emitting the custom \"response\" event...')\n this.emitter.emit('response', {\n response: createResponse(message),\n isMockedResponse: false,\n request: capturedRequest,\n requestId,\n })\n })\n\n return this.passthrough(chunk, encoding, callback)\n })\n\n return this\n }\n\n emit(event: string, ...data: any[]) {\n this.logger.info('emit: %s', event)\n\n if (event === 'response') {\n this.logger.info('found \"response\" event, cloning the response...')\n\n try {\n /**\n * Clone the response object when emitting the \"response\" event.\n * This prevents the response body stream from locking\n * and allows reading it twice:\n * 1. Internal \"response\" event from the observer.\n * 2. Any external response body listeners.\n * @see https://github.com/mswjs/interceptors/issues/161\n */\n const response = data[0] as IncomingMessage\n const firstClone = cloneIncomingMessage(response)\n const secondClone = cloneIncomingMessage(response)\n\n this.emit('response-internal', secondClone)\n\n this.logger.info(\n 'response successfully cloned, emitting \"response\" event...'\n )\n return super.emit(event, firstClone, ...data.slice(1))\n } catch (error) {\n this.logger.info('error when cloning response:', error)\n return super.emit(event, ...data)\n }\n }\n\n if (event === 'error') {\n const error = data[0] as NodeJS.ErrnoException\n const errorCode = error.code || ''\n\n this.logger.info('error:\\n', error)\n\n // Suppress only specific Node.js connection errors.\n if (NodeClientRequest.suppressErrorCodes.includes(errorCode)) {\n // Until we aren't sure whether the request will be\n // passthrough, capture the first emitted connection\n // error in case we have to replay it for this request.\n if (this.state < HttpClientInternalState.MockLookupEnd) {\n if (!this.capturedError) {\n this.capturedError = error\n this.logger.info('captured the first error:', this.capturedError)\n }\n return false\n }\n\n // Ignore any connection errors once we know the request\n // has been resolved with a mocked response. Don't capture\n // them as they won't ever be replayed.\n if (\n this.state === HttpClientInternalState.ResponseReceived &&\n this.responseType === 'mock'\n ) {\n return false\n }\n }\n }\n\n return super.emit(event, ...data)\n }\n\n /**\n * Performs the intercepted request as-is.\n * Replays the captured request body chunks,\n * still emits the internal events, and wraps\n * up the request with `super.end()`.\n */\n private passthrough(\n chunk: ClientRequestEndChunk | null,\n encoding?: BufferEncoding | null,\n callback?: ClientRequestEndCallback | null\n ): this {\n this.state = HttpClientInternalState.ResponseReceived\n this.responseType = 'passthrough'\n\n // Propagate previously captured errors.\n // For example, a ECONNREFUSED error when connecting to a non-existing host.\n if (this.capturedError) {\n this.emit('error', this.capturedError)\n return this\n }\n\n this.logger.info('writing request chunks...', this.chunks)\n\n // Write the request body chunks in the order of \".write()\" calls.\n // Note that no request body has been written prior to this point\n // in order to prevent the Socket to communicate with a potentially\n // existing server.\n for (const { chunk, encoding } of this.chunks) {\n if (encoding) {\n super.write(chunk, encoding)\n } else {\n super.write(chunk)\n }\n }\n\n this.once('error', (error) => {\n this.logger.info('original request error:', error)\n })\n\n this.once('abort', () => {\n this.logger.info('original request aborted!')\n })\n\n this.once('response-internal', (message: IncomingMessage) => {\n this.logger.info(message.statusCode, message.statusMessage)\n this.logger.info('original response headers:', message.headers)\n })\n\n this.logger.info('performing original request...')\n\n // This call signature is way too dynamic.\n return super.end(...[chunk, encoding as any, callback].filter(Boolean))\n }\n\n /**\n * Responds to this request instance using a mocked response.\n */\n private respondWith(mockedResponse: Response): void {\n this.logger.info('responding with a mocked response...', mockedResponse)\n\n this.state = HttpClientInternalState.ResponseReceived\n this.responseType = 'mock'\n\n /**\n * Mark the request as finished right before streaming back the response.\n * This is not entirely conventional but this will allow the consumer to\n * modify the outoging request in the interceptor.\n *\n * The request is finished when its headers and bodies have been sent.\n * @see https://nodejs.org/api/http.html#event-finish\n */\n Object.defineProperties(this, {\n writableFinished: { value: true },\n writableEnded: { value: true },\n })\n this.emit('finish')\n\n const { status, statusText, headers, body } = mockedResponse\n this.response.statusCode = status\n this.response.statusMessage = statusText || STATUS_CODES[status]\n\n // Try extracting the raw headers from the headers instance.\n // If not possible, fallback to the headers instance as-is.\n const rawHeaders = getRawFetchHeaders(headers) || headers\n\n if (rawHeaders) {\n this.response.headers = {}\n\n rawHeaders.forEach((headerValue, headerName) => {\n /**\n * @note Make sure that multi-value headers are appended correctly.\n */\n this.response.rawHeaders.push(headerName, headerValue)\n\n const insensitiveHeaderName = headerName.toLowerCase()\n const prevHeaders = this.response.headers[insensitiveHeaderName]\n this.response.headers[insensitiveHeaderName] = prevHeaders\n ? Array.prototype.concat([], prevHeaders, headerValue)\n : headerValue\n })\n }\n this.logger.info('mocked response headers ready:', headers)\n\n /**\n * Set the internal \"res\" property to the mocked \"OutgoingMessage\"\n * to make the \"ClientRequest\" instance think there's data received\n * from the socket.\n * @see https://github.com/nodejs/node/blob/9c405f2591f5833d0247ed0fafdcd68c5b14ce7a/lib/_http_client.js#L501\n *\n * Set the response immediately so the interceptor could stream data\n * chunks to the request client as they come in.\n */\n // @ts-ignore\n this.res = this.response\n this.emit('response', this.response)\n\n const isResponseStreamFinished = new DeferredPromise<void>()\n\n const finishResponseStream = () => {\n this.logger.info('finished response stream!')\n\n // Push \"null\" to indicate that the response body is complete\n // and shouldn't be written to anymore.\n this.response.push(null)\n this.response.complete = true\n\n isResponseStreamFinished.resolve()\n }\n\n if (body) {\n const bodyReader = body.getReader()\n const readNextChunk = async (): Promise<void> => {\n const { done, value } = await bodyReader.read()\n\n if (done) {\n finishResponseStream()\n return\n }\n\n this.response.emit('data', value)\n\n return readNextChunk()\n }\n\n readNextChunk()\n } else {\n finishResponseStream()\n }\n\n isResponseStreamFinished.then(() => {\n this.logger.info('finalizing response...')\n this.response.emit('end')\n this.terminate()\n\n this.logger.info('request complete!')\n })\n }\n\n private errorWith(error: Error): void {\n this.destroyed = true\n this.emit('error', error)\n this.terminate()\n }\n\n /**\n * Terminates a pending request.\n */\n private terminate(): void {\n /**\n * @note Some request clients (e.g. Octokit) create a ClientRequest\n * in a way that it has no Agent set. Now, whether that's correct is\n * debatable, but we should still handle this case gracefully.\n * @see https://github.com/mswjs/interceptors/issues/304\n */\n // @ts-ignore\n this.agent?.destroy()\n }\n}\n","import { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('utils getUrlByRequestOptions')\n\nexport type ClientRequestEndChunk = string | Buffer\nexport type ClientRequestEndCallback = () => void\n\ntype HttpRequestEndArgs =\n | []\n | [ClientRequestEndCallback]\n | [ClientRequestEndChunk, ClientRequestEndCallback?]\n | [ClientRequestEndChunk, BufferEncoding, ClientRequestEndCallback?]\n\ntype NormalizedHttpRequestEndParams = [\n ClientRequestEndChunk | null,\n BufferEncoding | null,\n ClientRequestEndCallback | null\n]\n\n/**\n * Normalizes a list of arguments given to the `ClientRequest.end()`\n * method to always include `chunk`, `encoding`, and `callback`.\n */\nexport function normalizeClientRequestEndArgs(\n ...args: HttpRequestEndArgs\n): NormalizedHttpRequestEndParams {\n logger.info('arguments', args)\n const normalizedArgs = new Array(3)\n .fill(null)\n .map((value, index) => args[index] || value)\n\n normalizedArgs.sort((a, b) => {\n // If first element is a function, move it rightwards.\n if (typeof a === 'function') {\n return 1\n }\n\n // If second element is a function, move the first leftwards.\n if (typeof b === 'function') {\n return -1\n }\n\n // If both elements are strings, preserve their original index.\n if (typeof a === 'string' && typeof b === 'string') {\n return normalizedArgs.indexOf(a) - normalizedArgs.indexOf(b)\n }\n\n return 0\n })\n\n logger.info('normalized args', normalizedArgs)\n return normalizedArgs as NormalizedHttpRequestEndParams\n}\n","import { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('http normalizeWriteArgs')\n\nexport type ClientRequestWriteCallback = (error?: Error | null) => void\nexport type ClientRequestWriteArgs = [\n chunk: string | Buffer,\n encoding?: BufferEncoding | ClientRequestWriteCallback,\n callback?: ClientRequestWriteCallback\n]\n\nexport type NormalizedClientRequestWriteArgs = [\n chunk: string | Buffer,\n encoding?: BufferEncoding,\n callback?: ClientRequestWriteCallback\n]\n\nexport function normalizeClientRequestWriteArgs(\n args: ClientRequestWriteArgs\n): NormalizedClientRequestWriteArgs {\n logger.info('normalizing ClientRequest.write arguments...', args)\n\n const chunk = args[0]\n const encoding =\n typeof args[1] === 'string' ? (args[1] as BufferEncoding) : undefined\n const callback = typeof args[1] === 'function' ? args[1] : args[2]\n\n const writeArgs: NormalizedClientRequestWriteArgs = [\n chunk,\n encoding,\n callback,\n ]\n logger.info(\n 'successfully normalized ClientRequest.write arguments:',\n writeArgs\n )\n\n return writeArgs\n}\n","import { IncomingMessage } from 'http'\nimport { PassThrough } from 'stream'\n\nexport const IS_CLONE = Symbol('isClone')\n\nexport interface ClonedIncomingMessage extends IncomingMessage {\n [IS_CLONE]: boolean\n}\n\n/**\n * Clones a given `http.IncomingMessage` instance.\n */\nexport function cloneIncomingMessage(\n message: IncomingMessage\n): ClonedIncomingMessage {\n const clone = message.pipe(new PassThrough())\n\n // Inherit all direct \"IncomingMessage\" properties.\n inheritProperties(message, clone)\n\n // Deeply inherit the message prototypes (Readable, Stream, EventEmitter, etc.).\n const clonedPrototype = Object.create(IncomingMessage.prototype)\n getPrototypes(clone).forEach((prototype) => {\n inheritProperties(prototype, clonedPrototype)\n })\n Object.setPrototypeOf(clone, clonedPrototype)\n\n Object.defineProperty(clone, IS_CLONE, {\n enumerable: true,\n value: true,\n })\n\n return clone as unknown as ClonedIncomingMessage\n}\n\n/**\n * Returns a list of all prototypes the given object extends.\n */\nfunction getPrototypes(source: object): object[] {\n const prototypes: object[] = []\n let current = source\n\n while ((current = Object.getPrototypeOf(current))) {\n prototypes.push(current)\n }\n\n return prototypes\n}\n\n/**\n * Inherits a given target object properties and symbols\n * onto the given source object.\n * @param source Object which should acquire properties.\n * @param target Object to inherit the properties from.\n */\nfunction inheritProperties(source: object, target: object): void {\n const properties = [\n ...Object.getOwnPropertyNames(source),\n ...Object.getOwnPropertySymbols(source),\n ]\n\n for (const property of properties) {\n if (target.hasOwnProperty(property)) {\n continue\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(source, property)\n if (!descriptor) {\n continue\n }\n\n Object.defineProperty(target, property, descriptor)\n }\n}\n","import type { IncomingHttpHeaders, IncomingMessage } from 'http'\nimport { isResponseWithoutBody } from '../../../utils/responseUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `http.IncomingMessage` instance.\n */\nexport function createResponse(message: IncomingMessage): Response {\n const responseBodyOrNull = isResponseWithoutBody(message.statusCode || 200)\n ? null\n : new ReadableStream({\n start(controller) {\n message.on('data', (chunk) => controller.enqueue(chunk))\n message.on('end', () => controller.close())\n\n /**\n * @todo Should also listen to the \"error\" on the message\n * and forward it to the controller. Otherwise the stream\n * will pend indefinitely.\n */\n },\n })\n\n return new Response(responseBodyOrNull, {\n status: message.statusCode,\n statusText: message.statusMessage,\n headers: createHeadersFromIncomingHttpHeaders(message.headers),\n })\n}\n\nfunction createHeadersFromIncomingHttpHeaders(\n httpHeaders: IncomingHttpHeaders\n): Headers {\n const headers = new Headers()\n\n for (const headerName in httpHeaders) {\n const headerValues = httpHeaders[headerName]\n\n if (typeof headerValues === 'undefined') {\n continue\n }\n\n if (Array.isArray(headerValues)) {\n headerValues.forEach((headerValue) => {\n headers.append(headerName, headerValue)\n })\n\n continue\n }\n\n headers.set(headerName, headerValues)\n }\n\n return headers\n}\n","import type { NodeClientRequest } from '../NodeClientRequest'\n\n/**\n * Creates a Fetch API `Request` instance from the given `http.ClientRequest`.\n */\nexport function createRequest(clientRequest: NodeClientRequest): Request {\n const headers = new Headers()\n\n const outgoingHeaders = clientRequest.getHeaders()\n for (const headerName in outgoingHeaders) {\n const headerValue = outgoingHeaders[headerName]\n\n if (typeof headerValue === 'undefined') {\n continue\n }\n\n const valuesList = Array.prototype.concat([], headerValue)\n for (const value of valuesList) {\n headers.append(headerName, value.toString())\n }\n }\n\n /**\n * Translate the authentication from the request URL to\n * the request \"Authorization\" header.\n * @see https://github.com/mswjs/interceptors/issues/438\n */\n if (clientRequest.url.username || clientRequest.url.password) {\n const auth = `${clientRequest.url.username || ''}:${clientRequest.url.password || ''}`\n headers.set('Authorization', `Basic ${btoa(auth)}`)\n\n // Remove the credentials from the URL since you cannot\n // construct a Request instance with such a URL.\n clientRequest.url.username = ''\n clientRequest.url.password = ''\n }\n\n const method = clientRequest.method || 'GET'\n\n return new Request(clientRequest.url, {\n method,\n headers,\n credentials: 'same-origin',\n body:\n method === 'HEAD' || method === 'GET'\n ? null\n : clientRequest.requestBuffer,\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","/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject<T>(value: any): value is T {\n return Object.prototype.toString.call(value) === '[object Object]'\n}\n","import { getValueBySymbol } from './getValueBySymbol'\nimport { isObject } from './isObject'\n\ntype RawHeadersMap = Map<string, string>\ntype HeadersMapHeader = { name: string; value: string }\n\n/**\n * Returns raw headers from the given `Headers` instance.\n * @example\n * const headers = new Headers([\n * ['X-HeadeR-NamE', 'Value']\n * ])\n * getRawFetchHeaders(headers)\n * // { 'X-HeadeR-NamE': 'Value' }\n */\nexport function getRawFetchHeaders(\n headers: Headers\n): RawHeadersMap | undefined {\n const headersList = getValueBySymbol<object>('headers list', headers)\n\n if (!headersList) {\n return\n }\n\n const headersMap = getValueBySymbol<\n Map<string, string> | Map<string, HeadersMapHeader>\n >('headers map', headersList)\n\n /**\n * @note Older versions of Node.js (e.g. 18.8.0) keep headers map\n * as Map<normalizedHeaderName, value> without any means to tap\n * into raw header values. Detect that and return undefined.\n */\n if (!headersMap || !isHeadersMapWithRawHeaderNames(headersMap)) {\n return\n }\n\n // Raw headers is a map of { rawHeaderName: rawHeaderValue }\n const rawHeaders: RawHeadersMap = new Map<string, string>()\n\n headersMap.forEach(({ name, value }) => {\n rawHeaders.set(name, value)\n })\n\n return rawHeaders\n}\n\nfunction isHeadersMapWithRawHeaderNames(\n headersMap: Map<string, string> | Map<string, HeadersMapHeader>\n): headersMap is Map<string, HeadersMapHeader> {\n return Array.from(\n headersMap.values() as Iterable<string | HeadersMapHeader>\n ).every((value) => {\n return isObject<HeadersMapHeader>(value) && 'name' in value\n })\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n","import {\n Agent as HttpAgent,\n globalAgent as httpGlobalAgent,\n IncomingMessage,\n} from 'http'\nimport {\n RequestOptions,\n Agent as HttpsAgent,\n globalAgent as httpsGlobalAgent,\n} from 'https'\nimport { Url as LegacyURL, parse as parseUrl } from 'url'\nimport { Logger } from '@open-draft/logger'\nimport { getRequestOptionsByUrl } from '../../../utils/getRequestOptionsByUrl'\nimport {\n ResolvedRequestOptions,\n getUrlByRequestOptions,\n} from '../../../utils/getUrlByRequestOptions'\nimport { cloneObject } from '../../../utils/cloneObject'\nimport { isObject } from '../../../utils/isObject'\n\nconst logger = new Logger('http normalizeClientRequestArgs')\n\nexport type HttpRequestCallback = (response: IncomingMessage) => void\n\nexport type ClientRequestArgs =\n // Request without any arguments is also possible.\n | []\n | [string | URL | LegacyURL, HttpRequestCallback?]\n | [string | URL | LegacyURL, RequestOptions, HttpRequestCallback?]\n | [RequestOptions, HttpRequestCallback?]\n\nfunction resolveRequestOptions(\n args: ClientRequestArgs,\n url: URL\n): RequestOptions {\n // Calling `fetch` provides only URL to `ClientRequest`\n // without any `RequestOptions` or callback.\n if (typeof args[1] === 'undefined' || typeof args[1] === 'function') {\n logger.info('request options not provided, deriving from the url', url)\n return getRequestOptionsByUrl(url)\n }\n\n if (args[1]) {\n logger.info('has custom RequestOptions!', args[1])\n const requestOptionsFromUrl = getRequestOptionsByUrl(url)\n\n logger.info('derived RequestOptions from the URL:', requestOptionsFromUrl)\n\n /**\n * Clone the request options to lock their state\n * at the moment they are provided to `ClientRequest`.\n * @see https://github.com/mswjs/interceptors/issues/86\n */\n logger.info('cloning RequestOptions...')\n const clonedRequestOptions = cloneObject(args[1])\n logger.info('successfully cloned RequestOptions!', clonedRequestOptions)\n\n return {\n ...requestOptionsFromUrl,\n ...clonedRequestOptions,\n }\n }\n\n logger.info('using an empty object as request options')\n return {} as RequestOptions\n}\n\n/**\n * Overrides the given `URL` instance with the explicit properties provided\n * on the `RequestOptions` object. The options object takes precedence,\n * and will replace URL properties like \"host\", \"path\", and \"port\", if specified.\n */\nfunction overrideUrlByRequestOptions(url: URL, options: RequestOptions): URL {\n url.host = options.host || url.host\n url.hostname = options.hostname || url.hostname\n url.port = options.port ? options.port.toString() : url.port\n\n if (options.path) {\n const parsedOptionsPath = parseUrl(options.path, false)\n url.pathname = parsedOptionsPath.pathname || ''\n url.search = parsedOptionsPath.search || ''\n }\n\n return url\n}\n\nfunction resolveCallback(\n args: ClientRequestArgs\n): HttpRequestCallback | undefined {\n return typeof args[1] === 'function' ? args[1] : args[2]\n}\n\nexport type NormalizedClientRequestArgs = [\n url: URL,\n options: ResolvedRequestOptions,\n callback?: HttpRequestCallback\n]\n\n/**\n * Normalizes parameters given to a `http.request` call\n * so it always has a `URL` and `RequestOptions`.\n */\nexport function normalizeClientRequestArgs(\n defaultProtocol: string,\n ...args: ClientRequestArgs\n): NormalizedClientRequestArgs {\n let url: URL\n let options: ResolvedRequestOptions\n let callback: HttpRequestCallback | undefined\n\n logger.info('arguments', args)\n logger.info('using default protocol:', defaultProtocol)\n\n // Support \"http.request()\" calls without any arguments.\n // That call results in a \"GET http://localhost\" request.\n if (args.length === 0) {\n const url = new URL('http://localhost')\n const options = resolveRequestOptions(args, url)\n return [url, options]\n }\n\n // Convert a url string into a URL instance\n // and derive request options from it.\n if (typeof args[0] === 'string') {\n logger.info('first argument is a location string:', args[0])\n\n url = new URL(args[0])\n logger.info('created a url:', url)\n\n const requestOptionsFromUrl = getRequestOptionsByUrl(url)\n logger.info('request options from url:', requestOptionsFromUrl)\n\n options = resolveRequestOptions(args, url)\n logger.info('resolved request options:', options)\n\n callback = resolveCallback(args)\n }\n // Handle a given URL instance as-is\n // and derive request options from it.\n else if (args[0] instanceof URL) {\n url = args[0]\n logger.info('first argument is a URL:', url)\n\n // Check if the second provided argument is RequestOptions.\n // If it is, check if \"options.path\" was set and rewrite it\n // on the input URL.\n // Do this before resolving options from the URL below\n // to prevent query string from being duplicated in the path.\n if (typeof args[1] !== 'undefined' && isObject<RequestOptions>(args[1])) {\n url = overrideUrlByRequestOptions(url, args[1])\n }\n\n options = resolveRequestOptions(args, url)\n logger.info('derived request options:', options)\n\n callback = resolveCallback(args)\n }\n // Handle a legacy URL instance and re-normalize from either a RequestOptions object\n // or a WHATWG URL.\n else if ('hash' in args[0] && !('method' in args[0])) {\n const [legacyUrl] = args\n logger.info('first argument is a legacy URL:', legacyUrl)\n\n if (legacyUrl.hostname === null) {\n /**\n * We are dealing with a relative url, so use the path as an \"option\" and\n * merge in any existing options, giving priority to exising options -- i.e. a path in any\n * existing options will take precedence over the one contained in the url. This is consistent\n * with the behaviour in ClientRequest.\n * @see https://github.com/nodejs/node/blob/d84f1312915fe45fe0febe888db692c74894c382/lib/_http_client.js#L122\n */\n logger.info('given legacy URL is relative (no hostname)')\n\n return isObject(args[1])\n ? normalizeClientRequestArgs(\n defaultProtocol,\n { path: legacyUrl.path, ...args[1] },\n args[2]\n )\n : normalizeClientRequestArgs(\n defaultProtocol,\n { path: legacyUrl.path },\n args[1] as HttpRequestCallback\n )\n }\n\n logger.info('given legacy url is absolute')\n\n // We are dealing with an absolute URL, so convert to WHATWG and try again.\n const resolvedUrl = new URL(legacyUrl.href)\n\n return args[1] === undefined\n ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl)\n : typeof args[1] === 'function'\n ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl, args[1])\n : normalizeClientRequestArgs(\n defaultProtocol,\n resolvedUrl,\n args[1],\n args[2]\n )\n }\n // Handle a given \"RequestOptions\" object as-is\n // and derive the URL instance from it.\n else if (isObject(args[0])) {\n options = args[0] as any\n logger.info('first argument is RequestOptions:', options)\n\n // When handling a \"RequestOptions\" object without an explicit \"protocol\",\n // infer the protocol from the request issuing module (http/https).\n options.protocol = options.protocol || defaultProtocol\n logger.info('normalized request options:', options)\n\n url = getUrlByRequestOptions(options)\n logger.info('created a URL from RequestOptions:', url.href)\n\n callback = resolveCallback(args)\n } else {\n throw new Error(\n `Failed to construct ClientRequest with these parameters: ${args}`\n )\n }\n\n options.protocol = options.protocol || url.protocol\n options.method = options.method || 'GET'\n\n /**\n * Infer a fallback agent from the URL protocol.\n * The interception is done on the \"ClientRequest\" level (\"NodeClientRequest\")\n * and it may miss the correct agent. Always align the agent\n * with the URL protocol, if not provided.\n *\n * @note Respect the \"agent: false\" value.\n */\n if (typeof options.agent === 'undefined') {\n const agent =\n options.protocol === 'https:'\n ? new HttpsAgent({\n rejectUnauthorized: options.rejectUnauthorized,\n })\n : new HttpAgent()\n\n options.agent = agent\n logger.info('resolved fallback agent:', agent)\n }\n\n /**\n * Ensure that the default Agent is always set.\n * This prevents the protocol mismatch for requests with { agent: false },\n * where the global Agent is inferred.\n * @see https://github.com/mswjs/msw/issues/1150\n * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L130\n * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L157-L159\n */\n if (!options._defaultAgent) {\n logger.info(\n 'has no default agent, setting the default agent for \"%s\"',\n options.protocol\n )\n\n options._defaultAgent =\n options.protocol === 'https:' ? httpsGlobalAgent : httpGlobalAgent\n }\n\n logger.info('successfully resolved url:', url.href)\n logger.info('successfully resolved options:', options)\n logger.info('successfully resolved callback:', callback)\n\n return [url, options, callback]\n}\n","import { RequestOptions } from 'http'\n\n/**\n * Converts a URL instance into the RequestOptions object expected by\n * the `ClientRequest` class.\n * @see https://github.com/nodejs/node/blob/908292cf1f551c614a733d858528ffb13fb3a524/lib/internal/url.js#L1257\n */\nexport function getRequestOptionsByUrl(url: URL): RequestOptions {\n const options: RequestOptions = {\n method: 'GET',\n protocol: url.protocol,\n hostname:\n typeof url.hostname === 'string' && url.hostname.startsWith('[')\n ? url.hostname.slice(1, -1)\n : url.hostname,\n host: url.host,\n path: `${url.pathname}${url.search || ''}`,\n }\n\n if (!!url.port) {\n options.port = Number(url.port)\n }\n\n if (url.username || url.password) {\n options.auth = `${url.username}:${url.password}`\n }\n\n return options\n}\n","import { Agent } from 'http'\nimport { RequestOptions, Agent as HttpsAgent } from 'https'\nimport { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('utils getUrlByRequestOptions')\n\n// Request instance constructed by the \"request\" library\n// has a \"self\" property that has a \"uri\" field. This is\n// reproducible by performing a \"XMLHttpRequest\" request in JSDOM.\nexport interface RequestSelf {\n uri?: URL\n}\n\nexport type ResolvedRequestOptions = RequestOptions & RequestSelf\n\nexport const DEFAULT_PATH = '/'\nconst DEFAULT_PROTOCOL = 'http:'\nconst DEFAULT_HOST = 'localhost'\nconst SSL_PORT = 443\n\nfunction getAgent(\n options: ResolvedRequestOptions\n): Agent | HttpsAgent | undefined {\n return options.agent instanceof Agent ? options.agent : undefined\n}\n\nfunction getProtocolByRequestOptions(options: ResolvedRequestOptions): string {\n if (options.protocol) {\n return options.protocol\n }\n\n const agent = getAgent(options)\n const agentProtocol = (agent as RequestOptions)?.protocol\n\n if (agentProtocol) {\n return agentProtocol\n }\n\n const port = getPortByRequestOptions(options)\n const isSecureRequest = options.cert || port === SSL_PORT\n\n return isSecureRequest ? 'https:' : options.uri?.protocol || DEFAULT_PROTOCOL\n}\n\nfunction getPortByRequestOptions(\n options: ResolvedRequestOptions\n): number | undefined {\n // Use the explicitly provided port.\n if (options.port) {\n return Number(options.port)\n }\n\n // Extract the port from the hostname.\n if (options.hostname != null) {\n const [, extractedPort] = options.hostname.match(/:(\\d+)$/) || []\n\n if (extractedPort != null) {\n return Number(extractedPort)\n }\n }\n\n // Otherwise, try to resolve port from the agent.\n const agent = getAgent(options)\n\n if ((agent as HttpsAgent)?.options.port) {\n return Number((agent as HttpsAgent).options.port)\n }\n\n if ((agent as RequestOptions)?.defaultPort) {\n return Number((agent as RequestOptions).defaultPort)\n }\n\n // Lastly, return undefined indicating that the port\n // must inferred from the protocol. Do not infer it here.\n return undefined\n}\n\nfunction getHostByRequestOptions(options: ResolvedRequestOptions): string {\n const { hostname, host } = options\n\n // If the hostname is specified, resolve the host from the \"host:port\" string.\n if (hostname != null) {\n return hostname.replace(/:\\d+$/, '')\n }\n\n return host || DEFAULT_HOST\n}\n\ninterface RequestAuth {\n username: string\n password: string\n}\n\nfunction getAuthByRequestOptions(\n options: ResolvedRequestOptions\n): RequestAuth | undefined {\n if (options.auth) {\n const [username, password] = options.auth.split(':')\n return { username, password }\n }\n}\n\n/**\n * Returns true if host looks like an IPv6 address without surrounding brackets\n * It assumes any host containing `:` is definitely not IPv4 and probably IPv6,\n * but note that this could include invalid IPv6 addresses as well.\n */\nfunction isRawIPv6Address(host: string): boolean {\n return host.includes(':') && !host.startsWith('[') && !host.endsWith(']')\n}\n\nfunction getHostname(host: string, port?: number): string {\n const portString = typeof port !== 'undefined' ? `:${port}` : ''\n\n /**\n * @note As of Node >= 17, hosts (including \"localhost\") can resolve to IPv6\n * addresses, so construct valid URL by surrounding the IPv6 host with brackets.\n */\n if (isRawIPv6Address(host)) {\n return `[${host}]${portString}`\n }\n\n if (typeof port === 'undefined') {\n return host\n }\n\n return `${host}${portString}`\n}\n\n/**\n * Creates a `URL` instance from a given `RequestOptions` object.\n */\nexport function getUrlByRequestOptions(options: ResolvedRequestOptions): URL {\n logger.info('request options', options)\n\n if (options.uri) {\n logger.info(\n 'constructing url from explicitly provided \"options.uri\": %s',\n options.uri\n )\n return new URL(options.uri.href)\n }\n\n logger.info('figuring out url from request options...')\n\n const protocol = getProtocolByRequestOptions(options)\n logger.info('protocol', protocol)\n\n const host = getHostByRequestOptions(options)\n logger.info('host', host)\n\n const port = getPortByRequestOptions(options)\n logger.info('port', port)\n\n const hostname = getHostname(host, port)\n logger.info('hostname', hostname)\n\n const path = options.path || DEFAULT_PATH\n logger.info('path', path)\n\n const credentials = getAuthByRequestOptions(options)\n logger.info('credentials', credentials)\n\n const authString = credentials\n ? `${credentials.username}:${credentials.password}@`\n : ''\n logger.info('auth string:', authString)\n\n const url = new URL(`${protocol}//${hostname}${path}`)\n url.username = credentials?.username || ''\n url.password = credentials?.password || ''\n\n logger.info('created url:', url)\n\n return url\n}\n","import { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('cloneObject')\n\nfunction isPlainObject(obj?: Record<string, any>): boolean {\n logger.info('is plain object?', obj)\n\n if (obj == null || !obj.constructor?.name) {\n logger.info('given object is undefined, not a plain object...')\n return false\n }\n\n logger.info('checking the object constructor:', obj.constructor.name)\n return obj.constructor.name === 'Object'\n}\n\nexport function cloneObject<ObjectType extends Record<string, any>>(\n obj: ObjectType\n): ObjectType {\n logger.info('cloning object:', obj)\n\n const enumerableProperties = Object.entries(obj).reduce<Record<string, any>>(\n (acc, [key, value]) => {\n logger.info('analyzing key-value pair:', key, value)\n\n // Recursively clone only plain objects, omitting class instances.\n acc[key] = isPlainObject(value) ? cloneObject(value) : value\n return acc\n },\n {}\n )\n\n return isPlainObject(obj)\n ? enumerableProperties\n : Object.assign(Object.getPrototypeOf(obj), enumerableProperties)\n}\n","import { ClientRequest } from 'node:http'\nimport {\n NodeClientOptions,\n NodeClientRequest,\n Protocol,\n} from './NodeClientRequest'\nimport {\n ClientRequestArgs,\n normalizeClientRequestArgs,\n} from './utils/normalizeClientRequestArgs'\n\nexport function get(protocol: Protocol, options: NodeClientOptions) {\n return function interceptorsHttpGet(\n ...args: ClientRequestArgs\n ): ClientRequest {\n const clientRequestArgs = normalizeClientRequestArgs(\n `${protocol}:`,\n ...args\n )\n const request = new NodeClientRequest(clientRequestArgs, options)\n\n /**\n * @note https://nodejs.org/api/http.html#httpgetoptions-callback\n * \"http.get\" sets the method to \"GET\" and calls \"req.end()\" automatically.\n */\n request.end()\n\n return request\n }\n}\n","import { ClientRequest } from 'http'\nimport { Logger } from '@open-draft/logger'\nimport {\n NodeClientOptions,\n NodeClientRequest,\n Protocol,\n} from './NodeClientRequest'\nimport {\n normalizeClientRequestArgs,\n ClientRequestArgs,\n} from './utils/normalizeClientRequestArgs'\n\nconst logger = new Logger('http request')\n\nexport function request(protocol: Protocol, options: NodeClientOptions) {\n return function interceptorsHttpRequest(\n ...args: ClientRequestArgs\n ): ClientRequest {\n logger.info('request call (protocol \"%s\"):', protocol, args)\n\n const clientRequestArgs = normalizeClientRequestArgs(\n `${protocol}:`,\n ...args\n )\n return new NodeClientRequest(clientRequestArgs, options)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,OAAO,UAAU;AACjB,OAAO,WAAW;;;ACDlB,SAAS,eAAe,mBAAAA,kBAAiB,oBAAoB;AAE7D,SAAS,aAAa;AACtB,SAAS,uBAAuB;;;ACHhC,SAAS,cAAc;AAEvB,IAAM,SAAS,IAAI,OAAO,8BAA8B;AAqBjD,SAAS,iCACX,MAC6B;AAChC,SAAO,KAAK,aAAa,IAAI;AAC7B,QAAM,iBAAiB,IAAI,MAAM,CAAC,EAC/B,KAAK,IAAI,EACT,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,KAAK,KAAK;AAE7C,iBAAe,KAAK,CAAC,GAAG,MAAM;AAE5B,QAAI,O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MACtD,CAAC;AAED,YAAM,UAA6B;AAAA,QACjC,SAAS,KAAK;AAAA,QACd,QAAQ,KAAK;AAAA,MACf;AAGA,oBAAc;AAAA,MAEZ,QAAQ,UAAU,OAAO;AAG3B,oBAAc;AAAA,MAEZ,IAAI,UAAU,OAAO;AAEvB,MAAAA,QAAO,KAAK,+BAA+B,QAAQ;AAAA,IACrD;AAAA,EACF;AACF;AA3CO,IAAM,2BAAN;AAAM,yBACJ,oBAAoB,OAAO,MAAM;","names":["IncomingMessage","Logger","logger","symbol","IncomingMessage","chunk","encoding","Logger","Logger","logger","Logger","logger","logger","Logger","url","options","request","Logger","logger","Logger","logger"]}
|
|
@@ -5,9 +5,6 @@
|
|
|
5
5
|
var _chunkLK6DILFKjs = require('./chunk-LK6DILFK.js');
|
|
6
6
|
|
|
7
7
|
|
|
8
|
-
var _chunkJSSEHRRBjs = require('./chunk-JSSEHRRB.js');
|
|
9
|
-
|
|
10
|
-
|
|
11
8
|
var _chunkFZJKKO5Hjs = require('./chunk-FZJKKO5H.js');
|
|
12
9
|
|
|
13
10
|
|
|
@@ -17,7 +14,9 @@ var _chunkMQJ3JOOKjs = require('./chunk-MQJ3JOOK.js');
|
|
|
17
14
|
|
|
18
15
|
|
|
19
16
|
|
|
20
|
-
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
var _chunkKRDNUBDZjs = require('./chunk-KRDNUBDZ.js');
|
|
21
20
|
|
|
22
21
|
// src/interceptors/XMLHttpRequest/index.ts
|
|
23
22
|
var _outvariant = require('outvariant');
|
|
@@ -208,7 +207,7 @@ function parseJson(data) {
|
|
|
208
207
|
|
|
209
208
|
// src/interceptors/XMLHttpRequest/utils/createResponse.ts
|
|
210
209
|
function createResponse(request, body) {
|
|
211
|
-
const responseBodyOrNull =
|
|
210
|
+
const responseBodyOrNull = _chunkKRDNUBDZjs.isResponseWithoutBody.call(void 0, request.status) ? null : body;
|
|
212
211
|
return new Response(responseBodyOrNull, {
|
|
213
212
|
status: request.status,
|
|
214
213
|
statusText: request.statusText,
|
|
@@ -241,7 +240,7 @@ var XMLHttpRequestController = class {
|
|
|
241
240
|
this.method = "GET";
|
|
242
241
|
this.url = null;
|
|
243
242
|
this.events = /* @__PURE__ */ new Map();
|
|
244
|
-
this.requestId =
|
|
243
|
+
this.requestId = _chunkKRDNUBDZjs.createRequestId.call(void 0, );
|
|
245
244
|
this.requestHeaders = new Headers();
|
|
246
245
|
this.responseBuffer = new Uint8Array();
|
|
247
246
|
this.request = createProxy(initialRequest, {
|
|
@@ -324,7 +323,7 @@ var XMLHttpRequestController = class {
|
|
|
324
323
|
);
|
|
325
324
|
if (IS_NODE) {
|
|
326
325
|
this.request.setRequestHeader(
|
|
327
|
-
|
|
326
|
+
_chunkKRDNUBDZjs.INTERNAL_REQUEST_ID_HEADER_NAME,
|
|
328
327
|
this.requestId
|
|
329
328
|
);
|
|
330
329
|
}
|
|
@@ -700,21 +699,12 @@ function createXMLHttpRequestProxy({
|
|
|
700
699
|
"request listener threw an exception, aborting request...",
|
|
701
700
|
resolverResult.error
|
|
702
701
|
);
|
|
702
|
+
if (resolverResult.error instanceof Response) {
|
|
703
|
+
this.respondWith(resolverResult.error);
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
703
706
|
xhrRequestController.respondWith(
|
|
704
|
-
|
|
705
|
-
JSON.stringify({
|
|
706
|
-
name: resolverResult.error.name,
|
|
707
|
-
message: resolverResult.error.message,
|
|
708
|
-
stack: resolverResult.error.stack
|
|
709
|
-
}),
|
|
710
|
-
{
|
|
711
|
-
status: 500,
|
|
712
|
-
statusText: "Unhandled Exception",
|
|
713
|
-
headers: {
|
|
714
|
-
"Content-Type": "application/json"
|
|
715
|
-
}
|
|
716
|
-
}
|
|
717
|
-
)
|
|
707
|
+
_chunkKRDNUBDZjs.createServerErrorResponse.call(void 0, resolverResult.error)
|
|
718
708
|
);
|
|
719
709
|
return;
|
|
720
710
|
}
|
|
@@ -762,7 +752,7 @@ function createXMLHttpRequestProxy({
|
|
|
762
752
|
}
|
|
763
753
|
|
|
764
754
|
// src/interceptors/XMLHttpRequest/index.ts
|
|
765
|
-
var _XMLHttpRequestInterceptor = class extends
|
|
755
|
+
var _XMLHttpRequestInterceptor = class extends _chunkKRDNUBDZjs.Interceptor {
|
|
766
756
|
constructor() {
|
|
767
757
|
super(_XMLHttpRequestInterceptor.interceptorSymbol);
|
|
768
758
|
}
|
|
@@ -808,4 +798,4 @@ XMLHttpRequestInterceptor.interceptorSymbol = Symbol("xhr");
|
|
|
808
798
|
|
|
809
799
|
|
|
810
800
|
exports.XMLHttpRequestInterceptor = XMLHttpRequestInterceptor;
|
|
811
|
-
//# sourceMappingURL=chunk-
|
|
801
|
+
//# sourceMappingURL=chunk-M4JXH4RP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/interceptors/XMLHttpRequest/index.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts","../../src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts","../../src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts","../../src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts","../../src/interceptors/XMLHttpRequest/utils/createEvent.ts","../../src/utils/findPropertySource.ts","../../src/utils/createProxy.ts","../../src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts","../../src/utils/parseJson.ts","../../src/interceptors/XMLHttpRequest/utils/createResponse.ts"],"names":["invariant","next","mockedResponse"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAAA,kBAAiB;;;ACA1B,SAAS,aAAa;;;ACAtB,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;;;ACEvB,SAAS,kBACd,MACA,OACY;AACZ,QAAM,SAAS,IAAI,WAAW,KAAK,aAAa,MAAM,UAAU;AAChE,SAAO,IAAI,MAAM,CAAC;AAClB,SAAO,IAAI,OAAO,KAAK,UAAU;AACjC,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U,QAAQ;AAChB,UAAM,SAAS,KAAK,OAAO,OAAO,OAAO;AAEzC,WAAO,KAAK,qCAAqC;AAEjD,UAAM,qBAAqB,WAAW;AAEtC,IAAAF;AAAA,MACE,CAAE,mBAA2B,iBAAiB;AAAA,MAC9C;AAAA,IACF;AAEA,eAAW,iBAAiB,0BAA0B;AAAA,MACpD,SAAS,KAAK;AAAA,MACd,QAAQ,KAAK;AAAA,IACf,CAAC;AAED,WAAO;AAAA,MACL;AAAA,MACA,WAAW,eAAe;AAAA,IAC5B;AAEA,WAAO,eAAe,WAAW,gBAAgB,mBAAmB;AAAA,MAClE,YAAY;AAAA,MACZ,cAAc;AAAA,MACd,OAAO;AAAA,IACT,CAAC;AAED,SAAK,cAAc,KAAK,MAAM;AAC5B,aAAO,eAAe,WAAW,gBAAgB,mBAAmB;AAAA,QAClE,OAAO;AAAA,MACT,CAAC;AAED,iBAAW,iBAAiB;AAC5B,aAAO;AAAA,QACL;AAAA,QACA,WAAW,eAAe;AAAA,MAC5B;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAnDO,IAAM,4BAAN;AAAM,0BACJ,oBAAoB,OAAO,KAAK","sourcesContent":["import { invariant } from 'outvariant'\nimport { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { InteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { Interceptor } from '../../Interceptor'\nimport { createXMLHttpRequestProxy } from './XMLHttpRequestProxy'\n\nexport type XMLHttpRequestEventListener = (args: {\n request: InteractiveRequest\n requestId: string\n}) => Promise<void> | void\n\nexport type XMLHttpRequestEmitter = Emitter<HttpRequestEventMap>\n\nexport class XMLHttpRequestInterceptor extends Interceptor<HttpRequestEventMap> {\n static interceptorSymbol = Symbol('xhr')\n\n constructor() {\n super(XMLHttpRequestInterceptor.interceptorSymbol)\n }\n\n protected checkEnvironment() {\n return typeof globalThis.XMLHttpRequest !== 'undefined'\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('patching \"XMLHttpRequest\" module...')\n\n const PureXMLHttpRequest = globalThis.XMLHttpRequest\n\n invariant(\n !(PureXMLHttpRequest as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"XMLHttpRequest\" module: already patched.'\n )\n\n globalThis.XMLHttpRequest = createXMLHttpRequestProxy({\n emitter: this.emitter,\n logger: this.logger,\n })\n\n logger.info(\n 'native \"XMLHttpRequest\" module patched!',\n globalThis.XMLHttpRequest.name\n )\n\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.XMLHttpRequest = PureXMLHttpRequest\n logger.info(\n 'native \"XMLHttpRequest\" module restored!',\n globalThis.XMLHttpRequest.name\n )\n })\n }\n}\n","import { until } from '@open-draft/until'\nimport type { Logger } from '@open-draft/logger'\nimport { XMLHttpRequestEmitter } from '.'\nimport { toInteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { XMLHttpRequestController } from './XMLHttpRequestController'\nimport { createServerErrorResponse } from '../../utils/responseUtils'\n\nexport interface XMLHttpRequestProxyOptions {\n emitter: XMLHttpRequestEmitter\n logger: Logger\n}\n\n/**\n * Create a proxied `XMLHttpRequest` class.\n * The proxied class establishes spies on certain methods,\n * allowing us to intercept requests and respond to them.\n */\nexport function createXMLHttpRequestProxy({\n emitter,\n logger,\n}: XMLHttpRequestProxyOptions) {\n const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, {\n construct(target, args, newTarget) {\n logger.info('constructed new XMLHttpRequest')\n\n const originalRequest = Reflect.construct(\n target,\n args,\n newTarget\n ) as XMLHttpRequest\n\n /**\n * @note Forward prototype descriptors onto the proxied object.\n * XMLHttpRequest is implemented in JSDOM in a way that assigns\n * a bunch of descriptors, like \"set responseType()\" on the prototype.\n * With this propagation, we make sure that those descriptors trigger\n * when the user operates with the proxied request instance.\n */\n const prototypeDescriptors = Object.getOwnPropertyDescriptors(\n target.prototype\n )\n for (const propertyName in prototypeDescriptors) {\n Reflect.defineProperty(\n originalRequest,\n propertyName,\n prototypeDescriptors[propertyName]\n )\n }\n\n const xhrRequestController = new XMLHttpRequestController(\n originalRequest,\n logger\n )\n\n xhrRequestController.onRequest = async function ({ request, requestId }) {\n const { interactiveRequest, requestController } =\n toInteractiveRequest(request)\n\n this.logger.info('awaiting mocked response...')\n\n emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== requestId) {\n return\n }\n\n if (requestController.responsePromise.state === 'pending') {\n requestController.respondWith(undefined)\n }\n })\n\n const resolverResult = await until(async () => {\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n emitter.listenerCount('request')\n )\n\n await emitAsync(emitter, 'request', {\n request: interactiveRequest,\n requestId,\n })\n\n this.logger.info('all \"request\" listeners settled!')\n\n const mockedResponse = await requestController.responsePromise\n\n this.logger.info('event.respondWith called with:', mockedResponse)\n\n return mockedResponse\n })\n\n if (resolverResult.error) {\n this.logger.info(\n 'request listener threw an exception, aborting request...',\n resolverResult.error\n )\n\n // Treat thrown Responses as mocked responses.\n if (resolverResult.error instanceof Response) {\n this.respondWith(resolverResult.error)\n return\n }\n // Unhandled exceptions in the request listeners are\n // synonymous to unhandled exceptions on the server.\n // Those are represented as 500 error responses.\n xhrRequestController.respondWith(\n createServerErrorResponse(resolverResult.error)\n )\n\n return\n }\n\n const mockedResponse = resolverResult.data\n\n if (typeof mockedResponse !== 'undefined') {\n this.logger.info(\n 'received mocked response: %d %s',\n mockedResponse.status,\n mockedResponse.statusText\n )\n\n if (mockedResponse.type === 'error') {\n this.logger.info(\n 'received a network error response, rejecting the request promise...'\n )\n\n xhrRequestController.errorWith(new TypeError('Network error'))\n return\n }\n\n return xhrRequestController.respondWith(mockedResponse)\n }\n\n this.logger.info(\n 'no mocked response received, performing request as-is...'\n )\n }\n\n xhrRequestController.onResponse = async function ({\n response,\n isMockedResponse,\n request,\n requestId,\n }) {\n this.logger.info(\n 'emitting the \"response\" event for %s listener(s)...',\n emitter.listenerCount('response')\n )\n\n emitter.emit('response', {\n response,\n isMockedResponse,\n request,\n requestId,\n })\n }\n\n // Return the proxied request from the controller\n // so that the controller can react to the consumer's interactions\n // with this request (opening/sending/etc).\n return xhrRequestController.request\n },\n })\n\n return XMLHttpRequestProxy\n}\n","import { invariant } from 'outvariant'\nimport { isNodeProcess } from 'is-node-process'\nimport type { Logger } from '@open-draft/logger'\nimport { concatArrayBuffer } from './utils/concatArrayBuffer'\nimport { createEvent } from './utils/createEvent'\nimport {\n decodeBuffer,\n encodeBuffer,\n toArrayBuffer,\n} from '../../utils/bufferUtils'\nimport { createProxy } from '../../utils/createProxy'\nimport { isDomParserSupportedType } from './utils/isDomParserSupportedType'\nimport { parseJson } from '../../utils/parseJson'\nimport { createResponse } from './utils/createResponse'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\n\nconst IS_MOCKED_RESPONSE = Symbol('isMockedResponse')\nconst IS_NODE = isNodeProcess()\n\n/**\n * An `XMLHttpRequest` instance controller that allows us\n * to handle any given request instance (e.g. responding to it).\n */\nexport class XMLHttpRequestController {\n public request: XMLHttpRequest\n public requestId: string\n public onRequest?: (\n this: XMLHttpRequestController,\n args: {\n request: Request\n requestId: string\n }\n ) => Promise<void>\n public onResponse?: (\n this: XMLHttpRequestController,\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ) => void\n\n private method: string = 'GET'\n private url: URL = null as any\n private requestHeaders: Headers\n private requestBody?: XMLHttpRequestBodyInit | Document | null\n private responseBuffer: Uint8Array\n private events: Map<keyof XMLHttpRequestEventTargetEventMap, Array<Function>>\n\n constructor(\n readonly initialRequest: XMLHttpRequest,\n public logger: Logger\n ) {\n this.events = new Map()\n this.requestId = createRequestId()\n this.requestHeaders = new Headers()\n this.responseBuffer = new Uint8Array()\n\n this.request = createProxy(initialRequest, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'ontimeout': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n /**\n * @note Proxy callbacks to event listeners because JSDOM has trouble\n * translating these properties to callbacks. It seemed to be operating\n * on events exclusively.\n */\n this.request.addEventListener(eventName, nextValue as any)\n\n return invoke()\n }\n\n default: {\n return invoke()\n }\n }\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'open': {\n const [method, url] = args as [string, string | undefined]\n\n if (typeof url === 'undefined') {\n this.method = 'GET'\n this.url = toAbsoluteUrl(method)\n } else {\n this.method = method\n this.url = toAbsoluteUrl(url)\n }\n\n this.logger = this.logger.extend(`${this.method} ${this.url.href}`)\n this.logger.info('open', this.method, this.url.href)\n\n return invoke()\n }\n\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function,\n ]\n\n this.registerEvent(eventName, listener)\n this.logger.info('addEventListener', eventName, listener)\n\n return invoke()\n }\n\n case 'setRequestHeader': {\n const [name, value] = args as [string, string]\n this.requestHeaders.set(name, value)\n\n this.logger.info('setRequestHeader', name, value)\n\n return invoke()\n }\n\n case 'send': {\n const [body] = args as [\n body?: XMLHttpRequestBodyInit | Document | null,\n ]\n\n if (body != null) {\n this.requestBody =\n typeof body === 'string' ? encodeBuffer(body) : body\n }\n\n this.request.addEventListener('load', () => {\n if (typeof this.onResponse !== 'undefined') {\n // Create a Fetch API Response representation of whichever\n // response this XMLHttpRequest received. Note those may\n // be either a mocked and the original response.\n const fetchResponse = createResponse(\n this.request,\n /**\n * The `response` property is the right way to read\n * the ambiguous response body, as the request's \"responseType\" may differ.\n * @see https://xhr.spec.whatwg.org/#the-response-attribute\n */\n this.request.response\n )\n\n // Notify the consumer about the response.\n this.onResponse.call(this, {\n response: fetchResponse,\n isMockedResponse: IS_MOCKED_RESPONSE in this.request,\n request: fetchRequest,\n requestId: this.requestId!,\n })\n }\n })\n\n // Delegate request handling to the consumer.\n const fetchRequest = this.toFetchApiRequest()\n const onceRequestSettled =\n this.onRequest?.call(this, {\n request: fetchRequest,\n requestId: this.requestId!,\n }) || Promise.resolve()\n\n onceRequestSettled.finally(() => {\n // If the consumer didn't handle the request perform it as-is.\n // Note that the request may not yet be DONE and may, in fact,\n // be LOADING while the \"respondWith\" method does its magic.\n if (this.request.readyState < this.request.LOADING) {\n this.logger.info(\n 'request callback settled but request has not been handled (readystate %d), performing as-is...',\n this.request.readyState\n )\n\n /**\n * @note Set the intercepted request ID on the original request in Node.js\n * so that if it triggers any other interceptors, they don't attempt\n * to process it once again.\n *\n * For instance, XMLHttpRequest is often implemented via \"http.ClientRequest\"\n * and we don't want for both XHR and ClientRequest interceptors to\n * handle the same request at the same time (e.g. emit the \"response\" event twice).\n */\n if (IS_NODE) {\n this.request.setRequestHeader(\n INTERNAL_REQUEST_ID_HEADER_NAME,\n this.requestId!\n )\n }\n\n return invoke()\n }\n })\n\n break\n }\n\n default: {\n return invoke()\n }\n }\n },\n })\n }\n\n private registerEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.events.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.events.set(eventName, nextEvents)\n\n this.logger.info('registered event \"%s\"', eventName, listener)\n }\n\n /**\n * Responds to the current request with the given\n * Fetch API `Response` instance.\n */\n public respondWith(response: Response): void {\n this.logger.info(\n 'responding with a mocked response: %d %s',\n response.status,\n response.statusText\n )\n\n /**\n * @note Since `XMLHttpRequestController` delegates the handling of the responses\n * to the \"load\" event listener that doesn't distinguish between the mocked and original\n * responses, mark the request that had a mocked response with a corresponding symbol.\n */\n define(this.request, IS_MOCKED_RESPONSE, true)\n\n define(this.request, 'status', response.status)\n define(this.request, 'statusText', response.statusText)\n define(this.request, 'responseURL', this.url.href)\n\n this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, {\n apply: (_, __, args: [name: string]) => {\n this.logger.info('getResponseHeader', args[0])\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning null')\n\n // Headers not received yet, nothing to return.\n return null\n }\n\n const headerValue = response.headers.get(args[0])\n this.logger.info(\n 'resolved response header \"%s\" to',\n args[0],\n headerValue\n )\n\n return headerValue\n },\n })\n\n this.request.getAllResponseHeaders = new Proxy(\n this.request.getAllResponseHeaders,\n {\n apply: () => {\n this.logger.info('getAllResponseHeaders')\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning empty string')\n\n // Headers not received yet, nothing to return.\n return ''\n }\n\n const headersList = Array.from(response.headers.entries())\n const allHeaders = headersList\n .map(([headerName, headerValue]) => {\n return `${headerName}: ${headerValue}`\n })\n .join('\\r\\n')\n\n this.logger.info('resolved all response headers to', allHeaders)\n\n return allHeaders\n },\n }\n )\n\n // Update the response getters to resolve against the mocked response.\n Object.defineProperties(this.request, {\n response: {\n enumerable: true,\n configurable: false,\n get: () => this.response,\n },\n responseText: {\n enumerable: true,\n configurable: false,\n get: () => this.responseText,\n },\n responseXML: {\n enumerable: true,\n configurable: false,\n get: () => this.responseXML,\n },\n })\n\n const totalResponseBodyLength = response.headers.has('Content-Length')\n ? Number(response.headers.get('Content-Length'))\n : /**\n * @todo Infer the response body length from the response body.\n */\n undefined\n\n this.logger.info('calculated response body length', totalResponseBodyLength)\n\n this.trigger('loadstart', {\n loaded: 0,\n total: totalResponseBodyLength,\n })\n\n this.setReadyState(this.request.HEADERS_RECEIVED)\n this.setReadyState(this.request.LOADING)\n\n const finalizeResponse = () => {\n this.logger.info('finalizing the mocked response...')\n\n this.setReadyState(this.request.DONE)\n\n this.trigger('load', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n\n this.trigger('loadend', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n if (response.body) {\n this.logger.info('mocked response has body, streaming...')\n\n const reader = response.body.getReader()\n\n const readNextResponseBodyChunk = async () => {\n const { value, done } = await reader.read()\n\n if (done) {\n this.logger.info('response body stream done!')\n finalizeResponse()\n return\n }\n\n if (value) {\n this.logger.info('read response body chunk:', value)\n this.responseBuffer = concatArrayBuffer(this.responseBuffer, value)\n\n this.trigger('progress', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n readNextResponseBodyChunk()\n }\n\n readNextResponseBodyChunk()\n } else {\n finalizeResponse()\n }\n }\n\n private responseBufferToText(): string {\n return decodeBuffer(this.responseBuffer)\n }\n\n get response(): unknown {\n this.logger.info(\n 'getResponse (responseType: %s)',\n this.request.responseType\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n switch (this.request.responseType) {\n case 'json': {\n const responseJson = parseJson(this.responseBufferToText())\n this.logger.info('resolved response JSON', responseJson)\n\n return responseJson\n }\n\n case 'arraybuffer': {\n const arrayBuffer = toArrayBuffer(this.responseBuffer)\n this.logger.info('resolved response ArrayBuffer', arrayBuffer)\n\n return arrayBuffer\n }\n\n case 'blob': {\n const mimeType =\n this.request.getResponseHeader('Content-Type') || 'text/plain'\n const responseBlob = new Blob([this.responseBufferToText()], {\n type: mimeType,\n })\n\n this.logger.info(\n 'resolved response Blob (mime type: %s)',\n responseBlob,\n mimeType\n )\n\n return responseBlob\n }\n\n default: {\n const responseText = this.responseBufferToText()\n this.logger.info(\n 'resolving \"%s\" response type as text',\n this.request.responseType,\n responseText\n )\n\n return responseText\n }\n }\n }\n\n get responseText(): string {\n /**\n * Throw when trying to read the response body as text when the\n * \"responseType\" doesn't expect text. This just respects the spec better.\n * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute\n */\n invariant(\n this.request.responseType === '' || this.request.responseType === 'text',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (\n this.request.readyState !== this.request.LOADING &&\n this.request.readyState !== this.request.DONE\n ) {\n return ''\n }\n\n const responseText = this.responseBufferToText()\n this.logger.info('getResponseText: \"%s\"', responseText)\n\n return responseText\n }\n\n get responseXML(): Document | null {\n invariant(\n this.request.responseType === '' ||\n this.request.responseType === 'document',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n const contentType = this.request.getResponseHeader('Content-Type') || ''\n\n if (typeof DOMParser === 'undefined') {\n console.warn(\n 'Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.'\n )\n return null\n }\n\n if (isDomParserSupportedType(contentType)) {\n return new DOMParser().parseFromString(\n this.responseBufferToText(),\n contentType\n )\n }\n\n return null\n }\n\n public errorWith(error: Error): void {\n this.logger.info('responding with an error')\n\n this.setReadyState(this.request.DONE)\n this.trigger('error')\n this.trigger('loadend')\n }\n\n /**\n * Transitions this request's `readyState` to the given one.\n */\n private setReadyState(nextReadyState: number): void {\n this.logger.info(\n 'setReadyState: %d -> %d',\n this.request.readyState,\n nextReadyState\n )\n\n if (this.request.readyState === nextReadyState) {\n this.logger.info('ready state identical, skipping transition...')\n return\n }\n\n define(this.request, 'readyState', nextReadyState)\n\n this.logger.info('set readyState to: %d', nextReadyState)\n\n if (nextReadyState !== this.request.UNSENT) {\n this.logger.info('triggerring \"readystatechange\" event...')\n\n this.trigger('readystatechange')\n }\n }\n\n /**\n * Triggers given event on the `XMLHttpRequest` instance.\n */\n private trigger<\n EventName extends keyof (XMLHttpRequestEventTargetEventMap & {\n readystatechange: ProgressEvent<XMLHttpRequestEventTarget>\n }),\n >(eventName: EventName, options?: ProgressEventInit): void {\n const callback = this.request[`on${eventName}`]\n const event = createEvent(this.request, eventName, options)\n\n this.logger.info('trigger \"%s\"', eventName, options || '')\n\n // Invoke direct callbacks.\n if (typeof callback === 'function') {\n this.logger.info('found a direct \"%s\" callback, calling...', eventName)\n callback.call(this.request, event)\n }\n\n // Invoke event listeners.\n for (const [registeredEventName, listeners] of this.events) {\n if (registeredEventName === eventName) {\n this.logger.info(\n 'found %d listener(s) for \"%s\" event, calling...',\n listeners.length,\n eventName\n )\n\n listeners.forEach((listener) => listener.call(this.request, event))\n }\n }\n }\n\n /**\n * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.\n */\n public toFetchApiRequest(): Request {\n this.logger.info('converting request to a Fetch API Request...')\n\n const fetchRequest = new Request(this.url.href, {\n method: this.method,\n headers: this.requestHeaders,\n /**\n * @see https://xhr.spec.whatwg.org/#cross-origin-credentials\n */\n credentials: this.request.withCredentials ? 'include' : 'same-origin',\n body: ['GET', 'HEAD'].includes(this.method)\n ? null\n : (this.requestBody as BodyInit),\n })\n\n const proxyHeaders = createProxy(fetchRequest.headers, {\n methodCall: ([methodName, args], invoke) => {\n // Forward the latest state of the internal request headers\n // because the interceptor might have modified them\n // without responding to the request.\n switch (methodName) {\n case 'append':\n case 'set': {\n const [headerName, headerValue] = args as [string, string]\n this.request.setRequestHeader(headerName, headerValue)\n break\n }\n\n case 'delete': {\n const [headerName] = args as [string]\n console.warn(\n `XMLHttpRequest: Cannot remove a \"${headerName}\" header from the Fetch API representation of the \"${fetchRequest.method} ${fetchRequest.url}\" request. XMLHttpRequest headers cannot be removed.`\n )\n break\n }\n }\n\n return invoke()\n },\n })\n define(fetchRequest, 'headers', proxyHeaders)\n\n this.logger.info('converted request to a Fetch API Request!', fetchRequest)\n\n return fetchRequest\n }\n}\n\nfunction toAbsoluteUrl(url: string | URL): URL {\n /**\n * @note XMLHttpRequest interceptor may run in environments\n * that implement XMLHttpRequest but don't implement \"location\"\n * (for example, React Native). If that's the case, return the\n * input URL as-is (nothing to be relative to).\n * @see https://github.com/mswjs/msw/issues/1777\n */\n if (typeof location === 'undefined') {\n return new URL(url)\n }\n\n return new URL(url.toString(), location.href)\n}\n\nfunction define(\n target: object,\n property: string | symbol,\n value: unknown\n): void {\n Reflect.defineProperty(target, property, {\n // Ensure writable properties to allow redefining readonly properties.\n writable: true,\n enumerable: true,\n value,\n })\n}\n","/**\n * Concatenate two `Uint8Array` buffers.\n */\nexport function concatArrayBuffer(\n left: Uint8Array,\n right: Uint8Array\n): Uint8Array {\n const result = new Uint8Array(left.byteLength + right.byteLength)\n result.set(left, 0)\n result.set(right, left.byteLength)\n return result\n}\n","export class EventPolyfill implements Event {\n readonly AT_TARGET: number = 0\n readonly BUBBLING_PHASE: number = 0\n readonly CAPTURING_PHASE: number = 0\n readonly NONE: number = 0\n\n public type: string = ''\n public srcElement: EventTarget | null = null\n public target: EventTarget | null\n public currentTarget: EventTarget | null = null\n public eventPhase: number = 0\n public timeStamp: number\n public isTrusted: boolean = true\n public composed: boolean = false\n public cancelable: boolean = true\n public defaultPrevented: boolean = false\n public bubbles: boolean = true\n public lengthComputable: boolean = true\n public loaded: number = 0\n public total: number = 0\n\n cancelBubble: boolean = false\n returnValue: boolean = true\n\n constructor(\n type: string,\n options?: { target: EventTarget; currentTarget: EventTarget }\n ) {\n this.type = type\n this.target = options?.target || null\n this.currentTarget = options?.currentTarget || null\n this.timeStamp = Date.now()\n }\n\n public composedPath(): EventTarget[] {\n return []\n }\n\n public initEvent(type: string, bubbles?: boolean, cancelable?: boolean) {\n this.type = type\n this.bubbles = !!bubbles\n this.cancelable = !!cancelable\n }\n\n public preventDefault() {\n this.defaultPrevented = true\n }\n\n public stopPropagation() {}\n public stopImmediatePropagation() {}\n}\n","import { EventPolyfill } from './EventPolyfill'\n\nexport class ProgressEventPolyfill extends EventPolyfill {\n readonly lengthComputable: boolean\n readonly composed: boolean\n readonly loaded: number\n readonly total: number\n\n constructor(type: string, init?: ProgressEventInit) {\n super(type)\n\n this.lengthComputable = init?.lengthComputable || false\n this.composed = init?.composed || false\n this.loaded = init?.loaded || 0\n this.total = init?.total || 0\n }\n}\n","import { EventPolyfill } from '../polyfills/EventPolyfill'\nimport { ProgressEventPolyfill } from '../polyfills/ProgressEventPolyfill'\n\nconst SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined'\n\nexport function createEvent(\n target: XMLHttpRequest,\n type: string,\n init?: ProgressEventInit\n): EventPolyfill {\n const progressEvents = [\n 'error',\n 'progress',\n 'loadstart',\n 'loadend',\n 'load',\n 'timeout',\n 'abort',\n ]\n\n /**\n * `ProgressEvent` is not supported in React Native.\n * @see https://github.com/mswjs/interceptors/issues/40\n */\n const ProgressEventClass = SUPPORTS_PROGRESS_EVENT\n ? ProgressEvent\n : ProgressEventPolyfill\n\n const event = progressEvents.includes(type)\n ? new ProgressEventClass(type, {\n lengthComputable: true,\n loaded: init?.loaded || 0,\n total: init?.total || 0,\n })\n : new EventPolyfill(type, {\n target,\n currentTarget: target,\n })\n\n return event\n}\n","/**\n * Returns the source object of the given property on the target object\n * (the target itself, any parent in its prototype, or null).\n */\nexport function findPropertySource(\n target: object,\n propertyName: string | symbol\n): object | null {\n if (!(propertyName in target)) {\n return null\n }\n\n const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName)\n if (hasProperty) {\n return target\n }\n\n const prototype = Reflect.getPrototypeOf(target)\n return prototype ? findPropertySource(prototype, propertyName) : null\n}\n","import { findPropertySource } from './findPropertySource'\n\nexport interface ProxyOptions<Target extends Record<string, any>> {\n constructorCall?(args: Array<unknown>, next: NextFunction<Target>): Target\n\n methodCall?<F extends keyof Target>(\n this: Target,\n data: [methodName: F, args: Array<unknown>],\n next: NextFunction<void>\n ): void\n\n setProperty?(\n data: [propertyName: string | symbol, nextValue: unknown],\n next: NextFunction<boolean>\n ): boolean\n\n getProperty?(\n data: [propertyName: string | symbol, receiver: Target],\n next: NextFunction<void>\n ): void\n}\n\nexport type NextFunction<ReturnType> = () => ReturnType\n\nexport function createProxy<Target extends object>(\n target: Target,\n options: ProxyOptions<Target>\n): Target {\n const proxy = new Proxy(target, optionsToProxyHandler(options))\n\n return proxy\n}\n\nfunction optionsToProxyHandler<T extends Record<string, any>>(\n options: ProxyOptions<T>\n): ProxyHandler<T> {\n const { constructorCall, methodCall, getProperty, setProperty } = options\n const handler: ProxyHandler<T> = {}\n\n if (typeof constructorCall !== 'undefined') {\n handler.construct = function (target, args, newTarget) {\n const next = Reflect.construct.bind(null, target as any, args, newTarget)\n return constructorCall.call(newTarget, args, next)\n }\n }\n\n handler.set = function (target, propertyName, nextValue) {\n const next = () => {\n const propertySource = findPropertySource(target, propertyName) || target\n const ownDescriptors = Reflect.getOwnPropertyDescriptor(\n propertySource,\n propertyName\n )\n\n // Respect any custom setters present for this property.\n if (typeof ownDescriptors?.set !== 'undefined') {\n ownDescriptors.set.apply(target, [nextValue])\n return true\n }\n\n // Otherwise, set the property on the source.\n return Reflect.defineProperty(propertySource, propertyName, {\n writable: true,\n enumerable: true,\n configurable: true,\n value: nextValue,\n })\n }\n\n if (typeof setProperty !== 'undefined') {\n return setProperty.call(target, [propertyName, nextValue], next)\n }\n\n return next()\n }\n\n handler.get = function (target, propertyName, receiver) {\n /**\n * @note Using `Reflect.get()` here causes \"TypeError: Illegal invocation\".\n */\n const next = () => target[propertyName as any]\n\n const value =\n typeof getProperty !== 'undefined'\n ? getProperty.call(target, [propertyName, receiver], next)\n : next()\n\n if (typeof value === 'function') {\n return (...args: Array<any>) => {\n const next = value.bind(target, ...args)\n\n if (typeof methodCall !== 'undefined') {\n return methodCall.call(target, [propertyName as any, args], next)\n }\n\n return next()\n }\n }\n\n return value\n }\n\n return handler\n}\n","export function isDomParserSupportedType(\n type: string\n): type is DOMParserSupportedType {\n const supportedTypes: Array<DOMParserSupportedType> = [\n 'application/xhtml+xml',\n 'application/xml',\n 'image/svg+xml',\n 'text/html',\n 'text/xml',\n ]\n return supportedTypes.some((supportedType) => {\n return type.startsWith(supportedType)\n })\n}\n","/**\n * Parses a given string into JSON.\n * Gracefully handles invalid JSON by returning `null`.\n */\nexport function parseJson(data: string): Record<string, unknown> | null {\n try {\n const json = JSON.parse(data)\n return json\n } catch (_) {\n return null\n }\n}\n","import { isResponseWithoutBody } from '../../../utils/responseUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `XMLHttpRequest` instance and a response body.\n */\nexport function createResponse(\n request: XMLHttpRequest,\n body: BodyInit | null\n): Response {\n /**\n * Handle XMLHttpRequest responses that must have null as the\n * response body when represented using Fetch API Response.\n * XMLHttpRequest response will always have an empty string\n * as the \"request.response\" in those cases, resulting in an error\n * when constructing a Response instance.\n * @see https://github.com/mswjs/interceptors/issues/379\n */\n const responseBodyOrNull = isResponseWithoutBody(request.status) ? null : body\n\n return new Response(responseBodyOrNull, {\n status: request.status,\n statusText: request.statusText,\n headers: createHeadersFromXMLHttpReqestHeaders(\n request.getAllResponseHeaders()\n ),\n })\n}\n\nfunction createHeadersFromXMLHttpReqestHeaders(headersString: string): Headers {\n const headers = new Headers()\n\n const lines = headersString.split(/[\\r\\n]+/)\n for (const line of lines) {\n if (line.trim() === '') {\n continue\n }\n\n const [name, ...parts] = line.split(': ')\n const value = parts.join(': ')\n\n headers.append(name, value)\n }\n\n return headers\n}\n"]}
|
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
2
2
|
|
|
3
|
-
var _chunkJSSEHRRBjs = require('./chunk-JSSEHRRB.js');
|
|
4
|
-
|
|
5
|
-
|
|
6
3
|
var _chunkY6GRL6UDjs = require('./chunk-Y6GRL6UD.js');
|
|
7
4
|
|
|
8
5
|
|
|
@@ -12,7 +9,9 @@ var _chunkMQJ3JOOKjs = require('./chunk-MQJ3JOOK.js');
|
|
|
12
9
|
|
|
13
10
|
|
|
14
11
|
|
|
15
|
-
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
var _chunkKRDNUBDZjs = require('./chunk-KRDNUBDZ.js');
|
|
16
15
|
|
|
17
16
|
// src/interceptors/ClientRequest/index.ts
|
|
18
17
|
var _http = require('http'); var _http2 = _interopRequireDefault(_http);
|
|
@@ -110,7 +109,7 @@ function inheritProperties(source, target) {
|
|
|
110
109
|
|
|
111
110
|
// src/interceptors/ClientRequest/utils/createResponse.ts
|
|
112
111
|
function createResponse(message) {
|
|
113
|
-
const responseBodyOrNull =
|
|
112
|
+
const responseBodyOrNull = _chunkKRDNUBDZjs.isResponseWithoutBody.call(void 0, message.statusCode || 200) ? null : new ReadableStream({
|
|
114
113
|
start(controller) {
|
|
115
114
|
message.on("data", (chunk) => controller.enqueue(chunk));
|
|
116
115
|
message.on("end", () => controller.close());
|
|
@@ -269,7 +268,7 @@ var _NodeClientRequest = class extends _http.ClientRequest {
|
|
|
269
268
|
}
|
|
270
269
|
end(...args) {
|
|
271
270
|
this.logger.info("end", args);
|
|
272
|
-
const requestId =
|
|
271
|
+
const requestId = _chunkKRDNUBDZjs.createRequestId.call(void 0, );
|
|
273
272
|
const [chunk, encoding, callback] = normalizeClientRequestEndArgs(...args);
|
|
274
273
|
this.logger.info("normalized arguments:", { chunk, encoding, callback });
|
|
275
274
|
this.writeRequestBodyChunk(chunk, encoding || void 0);
|
|
@@ -279,8 +278,8 @@ var _NodeClientRequest = class extends _http.ClientRequest {
|
|
|
279
278
|
Object.defineProperty(capturedRequest, "respondWith", {
|
|
280
279
|
value: requestController.respondWith.bind(requestController)
|
|
281
280
|
});
|
|
282
|
-
if (this.hasHeader(
|
|
283
|
-
this.removeHeader(
|
|
281
|
+
if (this.hasHeader(_chunkKRDNUBDZjs.INTERNAL_REQUEST_ID_HEADER_NAME)) {
|
|
282
|
+
this.removeHeader(_chunkKRDNUBDZjs.INTERNAL_REQUEST_ID_HEADER_NAME);
|
|
284
283
|
return this.passthrough(chunk, encoding, callback);
|
|
285
284
|
}
|
|
286
285
|
this.emitter.once("request", ({ requestId: pendingRequestId }) => {
|
|
@@ -321,26 +320,15 @@ var _NodeClientRequest = class extends _http.ClientRequest {
|
|
|
321
320
|
"unhandled resolver exception, coercing to an error response...",
|
|
322
321
|
resolverResult.error
|
|
323
322
|
);
|
|
323
|
+
if (resolverResult.error instanceof Response) {
|
|
324
|
+
this.respondWith(resolverResult.error);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
324
327
|
if (isNodeLikeError(resolverResult.error)) {
|
|
325
328
|
this.errorWith(resolverResult.error);
|
|
326
|
-
|
|
327
|
-
this.respondWith(
|
|
328
|
-
new Response(
|
|
329
|
-
JSON.stringify({
|
|
330
|
-
name: resolverResult.error.name,
|
|
331
|
-
message: resolverResult.error.message,
|
|
332
|
-
stack: resolverResult.error.stack
|
|
333
|
-
}),
|
|
334
|
-
{
|
|
335
|
-
status: 500,
|
|
336
|
-
statusText: "Unhandled Exception",
|
|
337
|
-
headers: {
|
|
338
|
-
"Content-Type": "application/json"
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
)
|
|
342
|
-
);
|
|
329
|
+
return this;
|
|
343
330
|
}
|
|
331
|
+
this.respondWith(_chunkKRDNUBDZjs.createServerErrorResponse.call(void 0, resolverResult.error));
|
|
344
332
|
return this;
|
|
345
333
|
}
|
|
346
334
|
const mockedResponse = resolverResult.data;
|
|
@@ -485,7 +473,7 @@ var _NodeClientRequest = class extends _http.ClientRequest {
|
|
|
485
473
|
this.emit("finish");
|
|
486
474
|
const { status, statusText, headers, body } = mockedResponse;
|
|
487
475
|
this.response.statusCode = status;
|
|
488
|
-
this.response.statusMessage = statusText;
|
|
476
|
+
this.response.statusMessage = statusText || _http.STATUS_CODES[status];
|
|
489
477
|
const rawHeaders = getRawFetchHeaders(headers) || headers;
|
|
490
478
|
if (rawHeaders) {
|
|
491
479
|
this.response.headers = {};
|
|
@@ -863,7 +851,7 @@ function request(protocol, options) {
|
|
|
863
851
|
}
|
|
864
852
|
|
|
865
853
|
// src/interceptors/ClientRequest/index.ts
|
|
866
|
-
var _ClientRequestInterceptor = class extends
|
|
854
|
+
var _ClientRequestInterceptor = class extends _chunkKRDNUBDZjs.Interceptor {
|
|
867
855
|
constructor() {
|
|
868
856
|
super(_ClientRequestInterceptor.interceptorSymbol);
|
|
869
857
|
this.modules = /* @__PURE__ */ new Map();
|
|
@@ -897,4 +885,4 @@ ClientRequestInterceptor.interceptorSymbol = Symbol("http");
|
|
|
897
885
|
|
|
898
886
|
|
|
899
887
|
exports.ClientRequestInterceptor = ClientRequestInterceptor;
|
|
900
|
-
//# sourceMappingURL=chunk-
|
|
888
|
+
//# sourceMappingURL=chunk-UXEUSYDY.js.map
|