@mswjs/interceptors 0.42.3 → 0.42.5
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/interceptors/WebSocket/index.js +14 -1
- package/lib/browser/interceptors/WebSocket/index.js.map +1 -1
- package/lib/browser/interceptors/fetch/web.js +1 -1
- package/lib/browser/presets/browser.js +1 -1
- package/lib/browser/{web-CdcYFjgm.js → web-DUlFZEtz.js} +58 -3
- package/lib/browser/web-DUlFZEtz.js.map +1 -0
- package/lib/node/{batch-interceptor-ByEZVih3.js → batch-interceptor-DMOfd-9x.js} +2 -2
- package/lib/node/{batch-interceptor-ByEZVih3.js.map → batch-interceptor-DMOfd-9x.js.map} +1 -1
- package/lib/node/buffer-utils-B4FUq-l2.js +17 -0
- package/lib/node/buffer-utils-B4FUq-l2.js.map +1 -0
- package/lib/node/create-request-id-DHo-fRTV.js +14 -0
- package/lib/node/create-request-id-DHo-fRTV.js.map +1 -0
- package/lib/node/{fetch-utils-Dw1PsmtX.js → fetch-utils-D-_xeRlK.js} +3 -14
- package/lib/node/{fetch-utils-Dw1PsmtX.js.map → fetch-utils-D-_xeRlK.js.map} +1 -1
- package/lib/node/{has-configurable-global-BU1sT1u4.js → has-configurable-global-CT6-QYdg.js} +2 -2
- package/lib/node/{has-configurable-global-BU1sT1u4.js.map → has-configurable-global-CT6-QYdg.js.map} +1 -1
- package/lib/node/index.d.ts +2 -243
- package/lib/node/index.js +6 -25
- package/lib/node/index.js.map +1 -1
- package/lib/node/{buffer-utils-BvPY1Tc-.js → interceptor-C8qRPjxG.js} +2 -16
- package/lib/node/interceptor-C8qRPjxG.js.map +1 -0
- package/lib/node/interceptors/ClientRequest/index.js +3 -3
- package/lib/node/interceptors/WebSocket/index.d.ts +2 -0
- package/lib/node/interceptors/WebSocket/index.js +635 -0
- package/lib/node/interceptors/WebSocket/index.js.map +1 -0
- package/lib/node/interceptors/XMLHttpRequest/node.js +5 -5
- package/lib/node/interceptors/fetch/node.js +5 -5
- package/lib/node/interceptors/http/index.js +2 -2
- package/lib/node/interceptors/net/index.d.ts +16 -0
- package/lib/node/interceptors/net/index.js +1 -1
- package/lib/node/{net-Ca8p1rIe.js → net-Bh16MP4u.js} +82 -92
- package/lib/node/net-Bh16MP4u.js.map +1 -0
- package/lib/node/patches-registry-DxR5TEc-.js +76 -0
- package/lib/node/patches-registry-DxR5TEc-.js.map +1 -0
- package/lib/node/remote-http-interceptor.js +4 -4
- package/lib/node/resolve-web-socket-url-CSvNPLGi.js +25 -0
- package/lib/node/resolve-web-socket-url-CSvNPLGi.js.map +1 -0
- package/lib/node/{source-CIgPng7r.js → source-DHVO1vzq.js} +327 -213
- package/lib/node/source-DHVO1vzq.js.map +1 -0
- package/lib/node/websocket-CC0nB0md.d.ts +285 -0
- package/package.json +5 -2
- package/src/interceptors/WebSocket/index.ts +4 -1
- package/src/interceptors/fetch/web.ts +11 -2
- package/src/interceptors/http/http-parser/index.ts +9 -1
- package/src/interceptors/http/http-parser.ts +21 -4
- package/src/interceptors/http/source.ts +368 -283
- package/src/interceptors/net/index.ts +39 -12
- package/src/interceptors/net/socket-controller.ts +126 -66
- package/src/utils/clone-response.ts +72 -0
- package/src/utils/internal-connection.ts +22 -0
- package/lib/browser/web-CdcYFjgm.js.map +0 -1
- package/lib/node/buffer-utils-BvPY1Tc-.js.map +0 -1
- package/lib/node/net-Ca8p1rIe.js.map +0 -1
- package/lib/node/source-CIgPng7r.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["kEmitter","kBoundListener"],"sources":["../../../../src/utils/internal-connection.ts","../../../../src/events/websocket.ts","../../../../src/interceptors/WebSocket/utils/bind-event.ts","../../../../src/interceptors/WebSocket/utils/events.ts","../../../../src/interceptors/WebSocket/web-socket-client-connection.ts","../../../../src/interceptors/WebSocket/web-socket-override.ts","../../../../src/interceptors/WebSocket/web-socket-server-connection.ts","../../../../src/interceptors/WebSocket/web-socket-class-transport.ts","../../../../src/interceptors/WebSocket/index.ts"],"sourcesContent":["interface InternalConnectionContext {\n run<T>(callback: () => T): T\n consume(): boolean\n}\n\ndeclare global {\n var __MSW_INTERNAL_CONNECTION_CONTEXT: InternalConnectionContext | undefined\n}\n\n/**\n * Share the Node-provided async context with the browser-built WebSocket\n * entry point without importing Node modules into the browser bundle.\n */\nexport function runAsInternalConnection<T>(callback: () => T): T {\n const context = globalThis.__MSW_INTERNAL_CONNECTION_CONTEXT\n\n if (context) {\n return context.run(callback)\n }\n\n return callback()\n}\n","import { TypedEvent } from 'rettime'\nimport type {\n WebSocketClientConnection,\n WebSocketServerConnection,\n} from '../interceptors/WebSocket'\n\n/**\n * The connection information.\n */\ninterface WebSocketConnectionInfo {\n /**\n * The protocols supported by the WebSocket client.\n */\n protocols: string | Array<string> | undefined\n}\n\ninterface WebSocketConnectionEventData {\n /**\n * The incoming WebSocket client connection.\n */\n client: WebSocketClientConnection\n /**\n * The original WebSocket server connection.\n */\n server: WebSocketServerConnection\n info: WebSocketConnectionInfo\n}\n\nexport class WebSocketConnectionEvent<\n DataType extends WebSocketConnectionEventData = WebSocketConnectionEventData,\n> extends TypedEvent<DataType, void, 'connection'> {\n public client: WebSocketClientConnection\n public server: WebSocketServerConnection\n public info: WebSocketConnectionInfo\n\n constructor(data: DataType) {\n super(...(['connection', {}] as any))\n\n this.client = data.client\n this.server = data.server\n this.info = data.info\n }\n}\n\nexport type WebSocketEventMap = {\n connection: WebSocketConnectionEvent\n}\n","type EventWithTarget<E extends Event, T> = E & { target: T }\n\nexport function bindEvent<E extends Event, T>(\n target: T,\n event: E\n): EventWithTarget<E, T> {\n Object.defineProperties(event, {\n target: {\n value: target,\n enumerable: true,\n writable: true,\n },\n currentTarget: {\n value: target,\n enumerable: true,\n writable: true,\n },\n })\n\n return event as EventWithTarget<E, T>\n}\n","const kCancelable = Symbol('kCancelable')\nconst kDefaultPrevented = Symbol('kDefaultPrevented')\n\n/**\n * A `MessageEvent` superset that supports event cancellation\n * in Node.js. It's rather non-intrusive so it can be safely\n * used in the browser as well.\n *\n * @see https://github.com/nodejs/node/issues/51767\n */\nexport class CancelableMessageEvent<T = any> extends MessageEvent<T> {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: MessageEventInit<T>) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n\ninterface CloseEventInit extends EventInit {\n code?: number\n reason?: string\n wasClean?: boolean\n}\n\nexport class CloseEvent extends Event {\n public code: number\n public reason: string\n public wasClean: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this.code = init.code === undefined ? 0 : init.code\n this.reason = init.reason === undefined ? '' : init.reason\n this.wasClean = init.wasClean === undefined ? false : init.wasClean\n }\n}\n\nexport class CancelableCloseEvent extends CloseEvent {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n","import type { WebSocketData, WebSocketTransport } from './web-socket-transport'\nimport type { WebSocketEventListener } from './web-socket-override'\nimport { bindEvent } from './utils/bind-event'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\nimport { createRequestId } from '../../create-request-id'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\n\nexport interface WebSocketClientEventMap {\n message: MessageEvent<WebSocketData>\n close: CloseEvent\n}\n\nexport abstract class WebSocketClientConnectionProtocol {\n abstract id: string\n abstract url: URL\n public abstract send(data: WebSocketData): void\n public abstract close(code?: number, reason?: string): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketClientEventMap,\n >(\n type: EventType,\n listener: WebSocketEventListener<WebSocketClientEventMap[EventType]>,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketClientEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener<WebSocketClientEventMap[EventType]>,\n options?: EventListenerOptions | boolean\n ): void\n}\n\n/**\n * The WebSocket client instance represents an incoming\n * client connection. The user can control the connection,\n * send and receive events.\n */\nexport class WebSocketClientConnection implements WebSocketClientConnectionProtocol {\n public readonly id: string\n public readonly url: URL\n\n private [kEmitter]: EventTarget\n\n constructor(\n public readonly socket: WebSocket,\n private readonly transport: WebSocketTransport\n ) {\n this.id = createRequestId()\n this.url = new URL(socket.url)\n this[kEmitter] = new EventTarget()\n\n // Emit outgoing client data (\"ws.send()\") as \"message\"\n // events on the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n const message = bindEvent(\n this.socket,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(message)\n\n // This is a bit silly but forward the cancellation state\n // of the \"client\" message event to the \"outgoing\" transport event.\n // This way, other agens (like \"server\" connection) can know\n // whether the client listener has pervented the default.\n if (message.defaultPrevented) {\n event.preventDefault()\n }\n })\n\n /**\n * Emit the \"close\" event on the \"client\" connection\n * whenever the underlying transport is closed.\n * @note \"client.close()\" does NOT dispatch the \"close\"\n * event on the WebSocket because it uses non-configurable\n * close status code. Thus, we listen to the transport\n * instead of the WebSocket's \"close\" event.\n */\n this.transport.addEventListener('close', (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.socket, new CloseEvent('close', event))\n )\n })\n }\n\n /**\n * Listen for the outgoing events from the connected WebSocket client.\n */\n public addEventListener<EventType extends keyof WebSocketClientEventMap>(\n type: EventType,\n listener: WebSocketEventListener<WebSocketClientEventMap[EventType]>,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (!Reflect.has(listener, kBoundListener)) {\n const boundListener = listener.bind(this.socket)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n configurable: false,\n })\n }\n\n this[kEmitter].addEventListener(\n type,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Removes the listener for the given event.\n */\n public removeEventListener<EventType extends keyof WebSocketClientEventMap>(\n event: EventType,\n listener: WebSocketEventListener<WebSocketClientEventMap[EventType]>,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the connected client.\n */\n public send(data: WebSocketData): void {\n this.transport.send(data)\n }\n\n /**\n * Close the WebSocket connection.\n * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1).\n * @param {string} reason A custom connection close reason.\n */\n public close(code?: number, reason?: string): void {\n this.transport.close(code, reason)\n }\n}\n","import { invariant } from 'outvariant'\nimport type { WebSocketData } from './web-socket-transport'\nimport { bindEvent } from './utils/bind-event'\nimport { CloseEvent } from './utils/events'\nimport { resolveWebSocketUrl } from '../../utils/resolve-web-socket-url'\n\nexport type WebSocketEventListener<\n EventType extends WebSocketEventMap[keyof WebSocketEventMap] = Event,\n> = (this: WebSocket, event: EventType) => void\n\nconst WEBSOCKET_CLOSE_CODE_RANGE_ERROR =\n 'InvalidAccessError: close code out of user configurable range'\n\nexport const kPassthroughPromise = Symbol('kPassthroughPromise')\nexport const kOnSend = Symbol('kOnSend')\nexport const kClose = Symbol('kClose')\n\nexport class WebSocketOverride extends EventTarget implements WebSocket {\n static readonly CONNECTING = 0\n static readonly OPEN = 1\n static readonly CLOSING = 2\n static readonly CLOSED = 3\n readonly CONNECTING = 0\n readonly OPEN = 1\n readonly CLOSING = 2\n readonly CLOSED = 3\n\n public url: string\n public protocol: string\n public extensions: string\n public binaryType: BinaryType\n public readyState: WebSocket['readyState']\n public bufferedAmount: number\n\n private _onopen: WebSocketEventListener | null = null\n private _onmessage: WebSocketEventListener<\n MessageEvent<WebSocketData>\n > | null = null\n private _onerror: WebSocketEventListener | null = null\n private _onclose: WebSocketEventListener<CloseEvent> | null = null\n\n private [kPassthroughPromise]: PromiseWithResolvers<boolean>\n private [kOnSend]?: (data: WebSocketData) => void\n\n constructor(url: string | URL, protocols?: string | Array<string>) {\n super()\n this.url = resolveWebSocketUrl(url)\n this.protocol = ''\n this.extensions = ''\n this.binaryType = 'blob'\n this.readyState = this.CONNECTING\n this.bufferedAmount = 0\n\n this[kPassthroughPromise] = Promise.withResolvers<boolean>()\n\n queueMicrotask(async () => {\n if (await this[kPassthroughPromise].promise) {\n return\n }\n\n this.protocol =\n typeof protocols === 'string'\n ? protocols\n : Array.isArray(protocols) && protocols.length > 0\n ? protocols[0]\n : ''\n\n /**\n * @note Check that nothing has prevented this connection\n * (e.g. called `client.close()` in the connection listener).\n * If the connection has been prevented, never dispatch the open event,.\n */\n if (this.readyState === this.CONNECTING) {\n this.readyState = this.OPEN\n this.dispatchEvent(bindEvent(this, new Event('open')))\n }\n })\n }\n\n set onopen(listener: WebSocketEventListener | null) {\n this.removeEventListener('open', this._onopen)\n this._onopen = listener\n if (listener !== null) {\n this.addEventListener('open', listener)\n }\n }\n get onopen(): WebSocketEventListener | null {\n return this._onopen\n }\n\n set onmessage(\n listener: WebSocketEventListener<MessageEvent<WebSocketData>> | null\n ) {\n this.removeEventListener(\n 'message',\n this._onmessage as WebSocketEventListener\n )\n this._onmessage = listener\n if (listener !== null) {\n this.addEventListener('message', listener)\n }\n }\n get onmessage(): WebSocketEventListener<MessageEvent<WebSocketData>> | null {\n return this._onmessage\n }\n\n set onerror(listener: WebSocketEventListener | null) {\n this.removeEventListener('error', this._onerror)\n this._onerror = listener\n if (listener !== null) {\n this.addEventListener('error', listener)\n }\n }\n get onerror(): WebSocketEventListener | null {\n return this._onerror\n }\n\n set onclose(listener: WebSocketEventListener<CloseEvent> | null) {\n this.removeEventListener('close', this._onclose as WebSocketEventListener)\n this._onclose = listener\n if (listener !== null) {\n this.addEventListener('close', listener)\n }\n }\n get onclose(): WebSocketEventListener<CloseEvent> | null {\n return this._onclose\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0\n */\n public send(data: WebSocketData): void {\n if (this.readyState === this.CONNECTING) {\n this.close()\n throw new DOMException('InvalidStateError')\n }\n\n // Sending when the socket is about to close\n // discards the sent data.\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n // Buffer the data to send in this even loop\n // but send it in the next.\n this.bufferedAmount += getDataSize(data)\n\n queueMicrotask(() => {\n // This is a bit optimistic but since no actual data transfer\n // is involved, all the data will be \"sent\" on the next tick.\n this.bufferedAmount = 0\n\n /**\n * @note Notify the parent about outgoing data.\n * This notifies the transport and the connection\n * listens to the outgoing data to emit the \"message\" event.\n */\n this[kOnSend]?.(data)\n })\n }\n\n public close(code: number = 1000, reason?: string): void {\n invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR)\n invariant(\n code === 1000 || (code >= 3000 && code <= 4999),\n WEBSOCKET_CLOSE_CODE_RANGE_ERROR\n )\n\n this[kClose](code, reason)\n }\n\n private [kClose](\n code: number = 1000,\n reason?: string,\n wasClean = true\n ): void {\n /**\n * @note Move this check here so that even internal closures,\n * like those triggered by the `server` connection, are not\n * performed twice.\n */\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n this.readyState = this.CLOSING\n\n queueMicrotask(() => {\n this.readyState = this.CLOSED\n\n this.dispatchEvent(\n bindEvent(\n this,\n new CloseEvent('close', {\n code,\n reason,\n wasClean,\n })\n )\n )\n\n // Remove all event listeners once the socket is closed.\n this._onopen = null\n this._onmessage = null\n this._onerror = null\n this._onclose = null\n })\n }\n\n public addEventListener<K extends keyof WebSocketEventMap>(\n type: K,\n listener: (this: WebSocket, event: WebSocketEventMap[K]) => void,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: unknown,\n listener: unknown,\n options?: unknown\n ): void {\n return super.addEventListener(\n type as string,\n listener as EventListener,\n options as AddEventListenerOptions\n )\n }\n\n removeEventListener<K extends keyof WebSocketEventMap>(\n type: K,\n callback: EventListenerOrEventListenerObject | null,\n options?: boolean | EventListenerOptions\n ): void {\n return super.removeEventListener(type, callback, options)\n }\n}\n\nfunction getDataSize(data: WebSocketData): number {\n if (typeof data === 'string') {\n return data.length\n }\n\n if (data instanceof Blob) {\n return data.size\n }\n\n return data.byteLength\n}\n","import { invariant } from 'outvariant'\nimport {\n kClose,\n WebSocketEventListener,\n WebSocketOverride,\n} from './web-socket-override'\nimport type { WebSocketData } from './web-socket-transport'\nimport type { WebSocketClassTransport } from './web-socket-class-transport'\nimport { bindEvent } from './utils/bind-event'\nimport {\n CancelableMessageEvent,\n CancelableCloseEvent,\n CloseEvent,\n} from './utils/events'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\nconst kSend = Symbol('kSend')\n\nexport interface WebSocketServerEventMap {\n open: Event\n message: MessageEvent<WebSocketData>\n error: Event\n close: CloseEvent\n}\n\nexport abstract class WebSocketServerConnectionProtocol {\n public abstract connect(): void\n public abstract send(data: WebSocketData): void\n public abstract close(): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketServerEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener<WebSocketServerEventMap[EventType]>,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketServerEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener<WebSocketServerEventMap[EventType]>,\n options?: EventListenerOptions | boolean\n ): void\n}\n\n/**\n * The WebSocket server instance represents the actual production\n * WebSocket server connection. It's idle by default but you can\n * establish it by calling `server.connect()`.\n */\nexport class WebSocketServerConnection implements WebSocketServerConnectionProtocol {\n /**\n * A WebSocket instance connected to the original server.\n */\n private realWebSocket?: WebSocket\n private mockCloseController: AbortController\n private realCloseController: AbortController\n private [kEmitter]: EventTarget\n\n constructor(\n private readonly client: WebSocketOverride,\n private readonly transport: WebSocketClassTransport,\n private readonly createConnection: () => WebSocket\n ) {\n this[kEmitter] = new EventTarget()\n this.mockCloseController = new AbortController()\n this.realCloseController = new AbortController()\n\n // Automatically forward outgoing client events\n // to the actual server unless the outgoing message event\n // has been prevented. The \"outgoing\" transport event it\n // dispatched by the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n // Ignore client messages if the server connection\n // hasn't been established yet. Nowhere to forward.\n if (typeof this.realWebSocket === 'undefined') {\n return\n }\n\n // Every outgoing client message can prevent this forwarding\n // by preventing the default of the outgoing message event.\n // This listener will be added before user-defined listeners,\n // so execute the logic on the next tick.\n queueMicrotask(() => {\n if (!event.defaultPrevented) {\n /**\n * @note Use the internal send mechanism so consumers can tell\n * apart direct user calls to `server.send()` and internal calls.\n * E.g. MSW has to ignore this internal call to log out messages correctly.\n */\n this[kSend](event.data)\n }\n })\n })\n\n this.transport.addEventListener(\n 'incoming',\n this.handleIncomingMessage.bind(this)\n )\n }\n\n /**\n * The `WebSocket` instance connected to the original server.\n * Accessing this before calling `server.connect()` will throw.\n */\n public get socket(): WebSocket {\n invariant(\n this.realWebSocket,\n 'Cannot access \"socket\" on the original WebSocket server object: the connection is not open. Did you forget to call `server.connect()`?'\n )\n\n return this.realWebSocket\n }\n\n /**\n * Open connection to the original WebSocket server.\n */\n public connect(): void {\n invariant(\n !this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN,\n 'Failed to call \"connect()\" on the original WebSocket instance: the connection already open'\n )\n\n const realWebSocket = this.createConnection()\n\n // Inherit the binary type from the mock WebSocket client.\n realWebSocket.binaryType = this.client.binaryType\n\n // Allow the interceptor to listen to when the server connection\n // has been established. This isn't necessary to operate with the connection\n // but may be beneficial in some cases (like conditionally adding logging).\n realWebSocket.addEventListener(\n 'open',\n (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.realWebSocket!, new Event('open', event))\n )\n },\n { once: true }\n )\n\n realWebSocket.addEventListener('message', (event) => {\n // Dispatch the \"incoming\" transport event instead of\n // invoking the internal handler directly. This way,\n // anyone can listen to the \"incoming\" event but this\n // class is the one resulting in it.\n this.transport.dispatchEvent(\n bindEvent(\n this.realWebSocket!,\n new MessageEvent('incoming', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n })\n\n // Close the original connection when the mock client closes.\n // E.g. \"client.close()\" was called. This is never forwarded anywhere.\n this.client.addEventListener(\n 'close',\n (event) => {\n this.handleMockClose(event)\n },\n {\n signal: this.mockCloseController.signal,\n }\n )\n\n // Forward the \"close\" event to let the interceptor handle\n // closures initiated by the original server.\n realWebSocket.addEventListener(\n 'close',\n (event) => {\n this.handleRealClose(event)\n },\n {\n signal: this.realCloseController.signal,\n }\n )\n\n realWebSocket.addEventListener('error', () => {\n const errorEvent = bindEvent(\n realWebSocket,\n new Event('error', { cancelable: true })\n )\n\n // Emit the \"error\" event on the `server` connection\n // to let the interceptor react to original server errors.\n this[kEmitter].dispatchEvent(errorEvent)\n\n // If the error event from the original server hasn't been prevented,\n // forward it to the underlying client.\n if (!errorEvent.defaultPrevented) {\n this.client.dispatchEvent(bindEvent(this.client, new Event('error')))\n }\n })\n\n this.realWebSocket = realWebSocket\n }\n\n /**\n * Listen for the incoming events from the original WebSocket server.\n */\n public addEventListener<EventType extends keyof WebSocketServerEventMap>(\n event: EventType,\n listener: WebSocketEventListener<WebSocketServerEventMap[EventType]>,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (!Reflect.has(listener, kBoundListener)) {\n const boundListener = listener.bind(this.client)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n })\n }\n\n this[kEmitter].addEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Remove the listener for the given event.\n */\n public removeEventListener<EventType extends keyof WebSocketServerEventMap>(\n event: EventType,\n listener: WebSocketEventListener<WebSocketServerEventMap[EventType]>,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the original WebSocket server.\n * @example\n * server.send('hello')\n * server.send(new Blob(['hello']))\n * server.send(new TextEncoder().encode('hello'))\n */\n public send(data: WebSocketData): void {\n this[kSend](data)\n }\n\n private [kSend](data: WebSocketData): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to call \"server.send()\" for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.client.url\n )\n\n // Silently ignore writes on the closed original WebSocket.\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Delegate the send to when the original connection is open.\n // Unlike the mock, connecting to the original server may take time\n // so we cannot call this on the next tick.\n if (realWebSocket.readyState === WebSocket.CONNECTING) {\n realWebSocket.addEventListener(\n 'open',\n () => {\n realWebSocket.send(data)\n },\n { once: true }\n )\n return\n }\n\n // Send the data to the original WebSocket server.\n realWebSocket.send(data)\n }\n\n /**\n * Close the actual server connection.\n */\n public close(): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to close server connection for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.client.url\n )\n\n // Remove the \"close\" event listener from the server\n // so it doesn't close the underlying WebSocket client\n // when you call \"server.close()\". This also prevents the\n // `close` event on the `server` connection from being dispatched twice.\n this.realCloseController.abort()\n\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Close the actual client connection.\n realWebSocket.close()\n\n // Dispatch the \"close\" event on the `server` connection.\n queueMicrotask(() => {\n this[kEmitter].dispatchEvent(\n bindEvent(\n this.realWebSocket,\n new CancelableCloseEvent('close', {\n /**\n * @note `server.close()` in the interceptor\n * always results in clean closures.\n */\n code: 1000,\n cancelable: true,\n })\n )\n )\n })\n }\n\n private handleIncomingMessage(event: MessageEvent<WebSocketData>): void {\n // Clone the event to dispatch it on this class\n // once again and prevent the \"already being dispatched\"\n // exception. Clone it here so we can observe this event\n // being prevented in the \"server.on()\" listeners.\n const messageEvent = bindEvent(\n event.target,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n /**\n * @note Emit \"message\" event on the server connection\n * instance to let the interceptor know about these\n * incoming events from the original server. In that listener,\n * the interceptor can modify or skip the event forwarding\n * to the mock WebSocket instance.\n */\n this[kEmitter].dispatchEvent(messageEvent)\n\n /**\n * @note Forward the incoming server events to the client.\n * Preventing the default on the message event stops this.\n */\n if (!messageEvent.defaultPrevented) {\n this.client.dispatchEvent(\n bindEvent(\n /**\n * @note Bind the forwarded original server events\n * to the mock WebSocket instance so it would\n * dispatch them straight away.\n */\n this.client,\n // Clone the message event again to prevent\n // the \"already being dispatched\" exception.\n new MessageEvent('message', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n }\n }\n\n private handleMockClose(_event: Event): void {\n // Close the original connection if the mock client closes.\n if (this.realWebSocket) {\n this.realWebSocket.close()\n }\n }\n\n private handleRealClose(event: CloseEvent): void {\n // For closures originating from the original server,\n // remove the \"close\" listener from the mock client.\n // original close -> (?) client[kClose]() --X--> \"close\" (again).\n this.mockCloseController.abort()\n\n const closeEvent = bindEvent(\n this.realWebSocket,\n new CancelableCloseEvent('close', {\n code: event.code,\n reason: event.reason,\n wasClean: event.wasClean,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(closeEvent)\n\n // If the close event from the server hasn't been prevented,\n // forward the closure to the mock client.\n if (!closeEvent.defaultPrevented) {\n // Close the intercepted client forcefully to\n // allow non-configurable status codes from the server.\n // If the socket has been closed by now, no harm calling\n // this again—it will have no effect.\n this.client[kClose](event.code, event.reason)\n }\n }\n}\n","import { bindEvent } from './utils/bind-event'\nimport {\n StrictEventListenerOrEventListenerObject,\n WebSocketData,\n WebSocketTransport,\n WebSocketTransportEventMap,\n} from './web-socket-transport'\nimport { kOnSend, kClose, WebSocketOverride } from './web-socket-override'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\n\n/**\n * Abstraction over the given mock `WebSocket` instance that allows\n * for controlling that instance (e.g. sending and receiving messages).\n */\nexport class WebSocketClassTransport\n extends EventTarget\n implements WebSocketTransport\n{\n constructor(protected readonly socket: WebSocketOverride) {\n super()\n\n // Emit the \"close\" event on the transport if the close\n // originates from the WebSocket client. E.g. the application\n // calls \"ws.close()\", not the interceptor.\n this.socket.addEventListener('close', (event) => {\n this.dispatchEvent(bindEvent(this.socket, new CloseEvent('close', event)))\n })\n\n /**\n * Emit the \"outgoing\" event on the transport\n * whenever the WebSocket client sends data (\"ws.send()\").\n */\n this.socket[kOnSend] = (data) => {\n this.dispatchEvent(\n bindEvent(\n this.socket,\n // Dispatch this as cancelable because \"client\" connection\n // re-creates this message event (cannot dispatch the same event).\n new CancelableMessageEvent('outgoing', {\n data,\n origin: this.socket.url,\n cancelable: true,\n })\n )\n )\n }\n }\n\n public addEventListener<EventType extends keyof WebSocketTransportEventMap>(\n type: EventType,\n callback: StrictEventListenerOrEventListenerObject<\n WebSocketTransportEventMap[EventType]\n > | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n return super.addEventListener(type, callback as EventListener, options)\n }\n\n public dispatchEvent<EventType extends keyof WebSocketTransportEventMap>(\n event: WebSocketTransportEventMap[EventType]\n ): boolean {\n return super.dispatchEvent(event)\n }\n\n public send(data: WebSocketData): void {\n queueMicrotask(() => {\n if (\n this.socket.readyState === this.socket.CLOSING ||\n this.socket.readyState === this.socket.CLOSED\n ) {\n return\n }\n\n const dispatchEvent = () => {\n this.socket.dispatchEvent(\n bindEvent(\n /**\n * @note Setting this event's \"target\" to the\n * WebSocket override instance is important.\n * This way it can tell apart original incoming events\n * (must be forwarded to the transport) from the\n * mocked message events like the one below\n * (must be dispatched on the client instance).\n */\n this.socket,\n new MessageEvent('message', {\n data,\n origin: this.socket.url,\n })\n )\n )\n }\n\n if (this.socket.readyState === this.socket.CONNECTING) {\n this.socket.addEventListener(\n 'open',\n () => {\n dispatchEvent()\n },\n { once: true }\n )\n } else {\n dispatchEvent()\n }\n })\n }\n\n public close(code: number, reason?: string): void {\n /**\n * @note Call the internal close method directly\n * to allow closing the connection with the status codes\n * that are non-configurable by the user (> 1000 <= 1015).\n */\n this.socket[kClose](code, reason)\n }\n}\n","import { Interceptor } from '../../interceptor'\nimport {\n WebSocketConnectionEvent,\n type WebSocketEventMap,\n} from '../../events/websocket'\nimport {\n WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n type WebSocketClientEventMap,\n} from './web-socket-client-connection'\nimport {\n WebSocketServerConnectionProtocol,\n WebSocketServerConnection,\n type WebSocketServerEventMap,\n} from './web-socket-server-connection'\nimport { WebSocketClassTransport } from './web-socket-class-transport'\nimport {\n kClose,\n kPassthroughPromise,\n WebSocketOverride,\n} from './web-socket-override'\nimport { bindEvent } from './utils/bind-event'\nimport { hasConfigurableGlobal } from '../../utils/has-configurable-global'\nimport { patchesRegistry } from '../../utils/patches-registry'\nimport { createLogger } from '../../utils/logger'\nimport { runAsInternalConnection } from '../../utils/internal-connection'\n\nexport {\n type WebSocketData,\n type WebSocketTransport,\n} from './web-socket-transport'\nexport {\n WebSocketClientEventMap,\n WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n WebSocketServerEventMap,\n WebSocketServerConnectionProtocol,\n WebSocketServerConnection,\n}\n\nexport {\n CloseEvent,\n CancelableCloseEvent,\n CancelableMessageEvent,\n} from './utils/events'\n\nconst logger = createLogger('websocket')\n\n/**\n * Intercept the outgoing WebSocket connections created using\n * the global `WebSocket` class.\n */\nexport class WebSocketInterceptor extends Interceptor<WebSocketEventMap> {\n static symbol = Symbol.for('websocket-interceptor')\n\n protected predicate(): boolean {\n return hasConfigurableGlobal('WebSocket')\n }\n\n protected setup(): void {\n logger.verbose('setup')\n\n const WebSocketProxy = new Proxy(globalThis.WebSocket, {\n construct: (\n target,\n args: ConstructorParameters<typeof globalThis.WebSocket>,\n newTarget\n ) => {\n const [url, protocols] = args\n\n logger.info('connection intercepted %o', {\n url: url.toString(),\n protocols,\n })\n\n const createConnection = (): WebSocket => {\n return runAsInternalConnection(() => {\n return Reflect.construct(target, args, newTarget)\n })\n }\n\n // All WebSocket instances are mocked and don't forward\n // any events to the original server (no connection established).\n // To forward the events, the user must use the \"server.send()\" API.\n const socket = new WebSocketOverride(url, protocols)\n const transport = new WebSocketClassTransport(socket)\n\n // Emit the \"connection\" event to the interceptor on the next tick\n // so the client can modify WebSocket options, like \"binaryType\"\n // while the connection is already pending.\n queueMicrotask(async () => {\n try {\n const server = new WebSocketServerConnection(\n socket,\n transport,\n createConnection\n )\n\n const hasConnectionListeners =\n this.emitter.listenerCount('connection') > 0\n\n // The \"globalThis.WebSocket\" class stands for\n // the client-side connection. Assume it's established\n // as soon as the WebSocket instance is constructed.\n await this.emitter.emitAsPromise(\n new WebSocketConnectionEvent({\n client: new WebSocketClientConnection(socket, transport),\n server,\n info: {\n protocols,\n },\n })\n )\n\n if (hasConnectionListeners) {\n socket[kPassthroughPromise].resolve(false)\n } else {\n socket[kPassthroughPromise].resolve(true)\n\n server.connect()\n\n // Forward the \"open\" event from the original server\n // to the mock WebSocket client in the case of a passthrough connection.\n server.addEventListener('open', () => {\n socket.dispatchEvent(bindEvent(socket, new Event('open')))\n\n // Forward the original connection protocol to the\n // mock WebSocket client.\n if (server['realWebSocket']) {\n socket.protocol = server['realWebSocket'].protocol\n }\n })\n }\n } catch (error) {\n /**\n * @note Translate unhandled exceptions during the connection\n * handling (i.e. interceptor exceptions) as WebSocket connection\n * closures with error. This prevents from the exceptions occurring\n * in `queueMicrotask` from being process-wide and uncatchable.\n */\n if (error instanceof Error) {\n socket.dispatchEvent(new Event('error'))\n\n // No need to close the connection if it's already being closed.\n // E.g. the interceptor called `client.close()` and then threw an error.\n if (\n socket.readyState !== WebSocket.CLOSING &&\n socket.readyState !== WebSocket.CLOSED\n ) {\n socket[kClose](1011, error.message, false)\n }\n\n console.error(error)\n }\n }\n })\n\n return socket\n },\n })\n\n logger.verbose('patching global WebSocket...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'WebSocket', () => WebSocketProxy)\n )\n\n logger.verbose('global WebSocket patched: %s', globalThis.WebSocket.name)\n }\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAgB,wBAA2B,UAAsB;CAC/D,MAAM,UAAU,WAAW;CAE3B,IAAI,SACF,OAAO,QAAQ,IAAI,QAAQ;CAG7B,OAAO,SAAS;AAClB;;;ACOA,IAAa,2BAAb,cAEU,WAAyC;CAKjD,YAAY,MAAgB;EAC1B,MAAM,GAAI,CAAC,cAAc,CAAC,CAAC,CAAS;EAEpC,KAAK,SAAS,KAAK;EACnB,KAAK,SAAS,KAAK;EACnB,KAAK,OAAO,KAAK;CACnB;AACF;;;ACxCA,SAAgB,UACd,QACA,OACuB;CACvB,OAAO,iBAAiB,OAAO;EAC7B,QAAQ;GACN,OAAO;GACP,YAAY;GACZ,UAAU;EACZ;EACA,eAAe;GACb,OAAO;GACP,YAAY;GACZ,UAAU;EACZ;CACF,CAAC;CAED,OAAO;AACT;;;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AU,IAAI;CAC1E;AACF"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { a as requestContext, i as forwardHttpEvents, t as NodeHttpRequestSource } from "../../source-
|
|
2
|
-
import {
|
|
3
|
-
import { t as FetchRequest } from "../../fetch-utils-
|
|
4
|
-
import {
|
|
5
|
-
import { t as hasConfigurableGlobal } from "../../has-configurable-global-
|
|
1
|
+
import { a as requestContext, i as forwardHttpEvents, t as NodeHttpRequestSource } from "../../source-DHVO1vzq.js";
|
|
2
|
+
import { n as createLogger, t as Interceptor } from "../../interceptor-C8qRPjxG.js";
|
|
3
|
+
import { t as FetchRequest } from "../../fetch-utils-D-_xeRlK.js";
|
|
4
|
+
import { n as patchesRegistry } from "../../patches-registry-DxR5TEc-.js";
|
|
5
|
+
import { t as hasConfigurableGlobal } from "../../has-configurable-global-CT6-QYdg.js";
|
|
6
6
|
//#region src/interceptors/XMLHttpRequest/node.ts
|
|
7
7
|
const logger = createLogger("xhr");
|
|
8
8
|
var XMLHttpRequestInterceptor = class extends Interceptor {
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { a as requestContext, i as forwardHttpEvents, t as NodeHttpRequestSource } from "../../source-
|
|
2
|
-
import {
|
|
3
|
-
import { i as getErrorResponse } from "../../fetch-utils-
|
|
4
|
-
import {
|
|
5
|
-
import { t as hasConfigurableGlobal } from "../../has-configurable-global-
|
|
1
|
+
import { a as requestContext, i as forwardHttpEvents, t as NodeHttpRequestSource } from "../../source-DHVO1vzq.js";
|
|
2
|
+
import { t as Interceptor } from "../../interceptor-C8qRPjxG.js";
|
|
3
|
+
import { i as getErrorResponse } from "../../fetch-utils-D-_xeRlK.js";
|
|
4
|
+
import { n as patchesRegistry } from "../../patches-registry-DxR5TEc-.js";
|
|
5
|
+
import { t as hasConfigurableGlobal } from "../../has-configurable-global-CT6-QYdg.js";
|
|
6
6
|
//#region src/interceptors/fetch/node.ts
|
|
7
7
|
/**
|
|
8
8
|
* Interceptor for `fetch` requests in Node.js.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { i as forwardHttpEvents, t as NodeHttpRequestSource } from "../../source-
|
|
2
|
-
import {
|
|
1
|
+
import { i as forwardHttpEvents, t as NodeHttpRequestSource } from "../../source-DHVO1vzq.js";
|
|
2
|
+
import { t as Interceptor } from "../../interceptor-C8qRPjxG.js";
|
|
3
3
|
//#region src/interceptors/http/index.ts
|
|
4
4
|
/**
|
|
5
5
|
* Interceptor for all HTTP requests in Node.js.
|
|
@@ -144,6 +144,7 @@ declare class TcpSocketController extends SocketController {
|
|
|
144
144
|
protected readonly createConnection: () => net.Socket;
|
|
145
145
|
serverSocket: net.Socket;
|
|
146
146
|
protected pendingConnection: PromiseWithResolvers<[TcpWrap, TcpHandle]>;
|
|
147
|
+
private removePassthroughSocketListeners?;
|
|
147
148
|
constructor(socket: net.Socket, createConnection: () => net.Socket, connectionOptions?: NetworkConnectionOptions);
|
|
148
149
|
/**
|
|
149
150
|
* Reset this controller to the pending state so the next exchange
|
|
@@ -192,6 +193,11 @@ declare class TcpSocketController extends SocketController {
|
|
|
192
193
|
uncorkReads(): void;
|
|
193
194
|
claim(): void;
|
|
194
195
|
passthrough(flushPendingData?: FlushPendingDataFunction): net.Socket;
|
|
196
|
+
/**
|
|
197
|
+
* Forward events for the lifetime of the connection, including while
|
|
198
|
+
* it is idle in an agent pool. Reusing it must not add more listeners.
|
|
199
|
+
*/
|
|
200
|
+
protected addPassthroughSocketListeners(realSocket: net.Socket): () => void;
|
|
195
201
|
}
|
|
196
202
|
declare class TlsSocketController extends TcpSocketController {
|
|
197
203
|
#private;
|
|
@@ -201,6 +207,16 @@ declare class TlsSocketController extends TcpSocketController {
|
|
|
201
207
|
protected emulateConnect(): void;
|
|
202
208
|
claim(): void;
|
|
203
209
|
passthrough(flushPendingData?: FlushPendingDataFunction): tls.TLSSocket;
|
|
210
|
+
protected addPassthroughSocketListeners(realSocket: net.Socket): () => void;
|
|
211
|
+
}
|
|
212
|
+
//#endregion
|
|
213
|
+
//#region src/utils/internal-connection.d.ts
|
|
214
|
+
interface InternalConnectionContext {
|
|
215
|
+
run<T>(callback: () => T): T;
|
|
216
|
+
consume(): boolean;
|
|
217
|
+
}
|
|
218
|
+
declare global {
|
|
219
|
+
var __MSW_INTERNAL_CONNECTION_CONTEXT: InternalConnectionContext | undefined;
|
|
204
220
|
}
|
|
205
221
|
//#endregion
|
|
206
222
|
//#region src/interceptors/net/index.d.ts
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as SocketInterceptor } from "../../net-
|
|
1
|
+
import { t as SocketInterceptor } from "../../net-Bh16MP4u.js";
|
|
2
2
|
export { SocketInterceptor };
|
|
@@ -1,81 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as createLogger, t as Interceptor } from "./interceptor-C8qRPjxG.js";
|
|
2
|
+
import { r as toBuffer } from "./buffer-utils-B4FUq-l2.js";
|
|
3
|
+
import { n as patchesRegistry } from "./patches-registry-DxR5TEc-.js";
|
|
2
4
|
import { TypedEvent } from "rettime";
|
|
3
5
|
import { invariant } from "outvariant";
|
|
4
6
|
import http from "node:http";
|
|
7
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
5
8
|
import net from "node:net";
|
|
6
9
|
import tls from "node:tls";
|
|
7
|
-
//#region src/utils/patches-registry.ts
|
|
8
|
-
var PatchesRegistry = class {
|
|
9
|
-
#replacements = /* @__PURE__ */ new Map();
|
|
10
|
-
applyPatch(owner, key, getNextValue) {
|
|
11
|
-
const ownerReplacements = this.#replacements.get(owner);
|
|
12
|
-
invariant(!ownerReplacements?.has(key), `Failed to replace a global value at "${String(key)}": already replaced.`);
|
|
13
|
-
const match = getDeepPropertyDescriptor(owner, key);
|
|
14
|
-
if (typeof match === "undefined") {
|
|
15
|
-
console.warn(`Failed to replace a global value at "${String(key)}": not a global value.`);
|
|
16
|
-
return () => {};
|
|
17
|
-
}
|
|
18
|
-
if (match.descriptor.configurable) Object.defineProperty(owner, key, {
|
|
19
|
-
value: getNextValue(owner[key]),
|
|
20
|
-
enumerable: true,
|
|
21
|
-
configurable: true
|
|
22
|
-
});
|
|
23
|
-
else if (match.descriptor.writable) owner[key] = getNextValue(owner[key]);
|
|
24
|
-
else throw new Error(`Failed to patch a non-configurable non-writable property "${key.toString()}"`);
|
|
25
|
-
const restorePatch = () => {
|
|
26
|
-
const currentReplacements = this.#replacements.get(owner);
|
|
27
|
-
if (!currentReplacements?.has(key)) return;
|
|
28
|
-
if (match.owner === owner)
|
|
29
|
-
/**
|
|
30
|
-
* @note Restoring non-configurable properties works as long as "writable: true"
|
|
31
|
-
* and none of the other descriptor properties except for "value" have changed.
|
|
32
|
-
*/
|
|
33
|
-
Object.defineProperty(match.owner, key, match.descriptor);
|
|
34
|
-
else
|
|
35
|
-
/**
|
|
36
|
-
* @todo Delete the proxy property set by the registry.
|
|
37
|
-
* If the match's owner isn't the original owner, the property is likely nested in the prototype.
|
|
38
|
-
* The registry does not meddle with those, they are left intact.
|
|
39
|
-
*/
|
|
40
|
-
Reflect.deleteProperty(owner, key);
|
|
41
|
-
currentReplacements.delete(key);
|
|
42
|
-
if (currentReplacements.size === 0) this.#replacements.delete(owner);
|
|
43
|
-
};
|
|
44
|
-
if (ownerReplacements) ownerReplacements.set(key, restorePatch);
|
|
45
|
-
else this.#replacements.set(owner, /* @__PURE__ */ new Map([[key, restorePatch]]));
|
|
46
|
-
return restorePatch;
|
|
47
|
-
}
|
|
48
|
-
restoreAllPatches() {
|
|
49
|
-
const errors = [];
|
|
50
|
-
for (const [, ownerReplacements] of this.#replacements) for (const [, restorePatch] of ownerReplacements) try {
|
|
51
|
-
restorePatch();
|
|
52
|
-
} catch (error) {
|
|
53
|
-
if (error instanceof Error) errors.push(error);
|
|
54
|
-
else throw error;
|
|
55
|
-
}
|
|
56
|
-
if (errors.length > 0) throw new AggregateError(errors, "FOO!");
|
|
57
|
-
}
|
|
58
|
-
};
|
|
59
|
-
const patchesRegistry = new PatchesRegistry();
|
|
60
|
-
/**
|
|
61
|
-
* Returns a property descriptor for the given property on the owner.
|
|
62
|
-
* Walks down the prototype chain if the property does not exist on the owner.
|
|
63
|
-
* Handy for getting a global property descriptor where `globalThis` is
|
|
64
|
-
* replaced with a controlled class (e.g. ServiceWorkerGlobalScope).
|
|
65
|
-
*/
|
|
66
|
-
function getDeepPropertyDescriptor(owner, key) {
|
|
67
|
-
let currentOwner = owner;
|
|
68
|
-
let descriptor;
|
|
69
|
-
while (currentOwner) {
|
|
70
|
-
descriptor = Object.getOwnPropertyDescriptor(currentOwner, key);
|
|
71
|
-
if (descriptor) return {
|
|
72
|
-
owner: currentOwner,
|
|
73
|
-
descriptor
|
|
74
|
-
};
|
|
75
|
-
currentOwner = Object.getPrototypeOf(currentOwner);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
//#endregion
|
|
79
10
|
//#region src/interceptors/net/utils/normalize-net-connect-args.ts
|
|
80
11
|
/**
|
|
81
12
|
* Normalizes the arguments passed to `net.connect()`.
|
|
@@ -551,7 +482,8 @@ var TcpSocketController = class extends SocketController {
|
|
|
551
482
|
* must not close the client socket).
|
|
552
483
|
*/
|
|
553
484
|
if (this.#passthroughSocket) {
|
|
554
|
-
this
|
|
485
|
+
this.removePassthroughSocketListeners?.();
|
|
486
|
+
this.#passthroughSocket.destroy();
|
|
555
487
|
this.#passthroughSocket = null;
|
|
556
488
|
/**
|
|
557
489
|
* @note The handle swapped in from the destroyed connection,
|
|
@@ -890,13 +822,14 @@ var TcpSocketController = class extends SocketController {
|
|
|
890
822
|
* the consumer reads the buffered data.
|
|
891
823
|
*/
|
|
892
824
|
#emitClientClose(hadError) {
|
|
825
|
+
if (this.#clientCloseEmitted) return;
|
|
893
826
|
if (this.#clientEndPushed && !this.socket.readableEnded && !this.socket.destroyed) {
|
|
894
827
|
let closeDelivered = false;
|
|
895
828
|
const deliverClose = (hadErrorOverride) => {
|
|
896
829
|
if (closeDelivered) return;
|
|
897
830
|
closeDelivered = true;
|
|
898
831
|
process.nextTick(() => {
|
|
899
|
-
|
|
832
|
+
this.#emitClientClose(hadErrorOverride ?? hadError);
|
|
900
833
|
});
|
|
901
834
|
};
|
|
902
835
|
this.socket.once("end", () => {
|
|
@@ -915,7 +848,8 @@ var TcpSocketController = class extends SocketController {
|
|
|
915
848
|
};
|
|
916
849
|
return;
|
|
917
850
|
}
|
|
918
|
-
this.socket.
|
|
851
|
+
this.socket.destroy();
|
|
852
|
+
if (this.#realHandleSwapped) this.socket.emit("close", hadError);
|
|
919
853
|
}
|
|
920
854
|
#onMockSocketDrain = () => {
|
|
921
855
|
logger$1.verbose("client socket drained!");
|
|
@@ -1033,11 +967,13 @@ var TcpSocketController = class extends SocketController {
|
|
|
1033
967
|
const createRealSocket = () => {
|
|
1034
968
|
const realSocket = this.#retargetedConnectionOptions ? this.#createRetargetedConnection(this.#retargetedConnectionOptions) : this.createConnection();
|
|
1035
969
|
realSocket[kPatched] = true;
|
|
970
|
+
realSocket.allowHalfOpen = true;
|
|
1036
971
|
if (this.socket.timeout != null) realSocket.setTimeout(this.socket.timeout);
|
|
1037
972
|
return realSocket;
|
|
1038
973
|
};
|
|
1039
974
|
const realSocket = this.#passthroughSocket && !this.#passthroughSocket.destroyed ? this.#passthroughSocket : createRealSocket();
|
|
1040
|
-
|
|
975
|
+
const isNewConnection = realSocket !== this.#passthroughSocket;
|
|
976
|
+
this.#passthroughSocket = realSocket;
|
|
1041
977
|
if (this.#bufferedWrites.length === 0) logger$1.verbose("passthrough with empty writes buffer (state: %d)", this.readyState);
|
|
1042
978
|
/**
|
|
1043
979
|
* Flush any writes during the pending phase to the passthrough socket.
|
|
@@ -1062,8 +998,10 @@ var TcpSocketController = class extends SocketController {
|
|
|
1062
998
|
this.socket.address = realSocket.address.bind(realSocket);
|
|
1063
999
|
this.socket.removeListener("drain", this.#onMockSocketDrain);
|
|
1064
1000
|
this.socket.on("drain", this.#onMockSocketDrain);
|
|
1065
|
-
|
|
1066
|
-
|
|
1001
|
+
if (isNewConnection) {
|
|
1002
|
+
this.removePassthroughSocketListeners = this.addPassthroughSocketListeners(realSocket);
|
|
1003
|
+
realSocket.once("close", this.removePassthroughSocketListeners);
|
|
1004
|
+
}
|
|
1067
1005
|
/**
|
|
1068
1006
|
* @note Forward the client's half-close, unless the real handle
|
|
1069
1007
|
* is already swapped in — the client's own shutdown then reaches
|
|
@@ -1077,6 +1015,16 @@ var TcpSocketController = class extends SocketController {
|
|
|
1077
1015
|
return realSocket;
|
|
1078
1016
|
}
|
|
1079
1017
|
/**
|
|
1018
|
+
* Forward events for the lifetime of the connection, including while
|
|
1019
|
+
* it is idle in an agent pool. Reusing it must not add more listeners.
|
|
1020
|
+
*/
|
|
1021
|
+
addPassthroughSocketListeners(realSocket) {
|
|
1022
|
+
realSocket.once("connect", this.#onRealSocketConnect).on("connectionAttemptFailed", this.#onRealSocketConnectionAttemptFailed).on("connectionAttemptTimeout", this.#onRealSocketConnectionAttemptTimeout).on("data", this.#onRealSocketData).on("error", this.#onRealSocketError).on("end", this.#onRealSocketEnd).on("close", this.#onRealSocketClose);
|
|
1023
|
+
return () => {
|
|
1024
|
+
realSocket.removeListener("connect", this.#onRealSocketConnect).removeListener("connectionAttemptFailed", this.#onRealSocketConnectionAttemptFailed).removeListener("connectionAttemptTimeout", this.#onRealSocketConnectionAttemptTimeout).removeListener("data", this.#onRealSocketData).removeListener("error", this.#onRealSocketError).removeListener("end", this.#onRealSocketEnd).removeListener("close", this.#onRealSocketClose);
|
|
1025
|
+
};
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1080
1028
|
* Create the passthrough connection to the target this controller
|
|
1081
1029
|
* was retargeted to (see `reset()`). The original `createConnection`
|
|
1082
1030
|
* dials the originally requested target and cannot serve retargeted
|
|
@@ -1118,6 +1066,15 @@ var TlsSocketController = class extends TcpSocketController {
|
|
|
1118
1066
|
});
|
|
1119
1067
|
}
|
|
1120
1068
|
emulateConnect() {
|
|
1069
|
+
/**
|
|
1070
|
+
* @note The client chooses its wire protocol when we emulate the
|
|
1071
|
+
* handshake. A later passthrough handshake must preserve that choice
|
|
1072
|
+
* instead of negotiating a different protocol for buffered writes.
|
|
1073
|
+
*/
|
|
1074
|
+
if (this.#tlsConnectionOptions) {
|
|
1075
|
+
const alpnProtocol = this.socket._handle.getALPNNegotiatedProtocol();
|
|
1076
|
+
this.#tlsConnectionOptions.ALPNProtocols = alpnProtocol ? [alpnProtocol] : [];
|
|
1077
|
+
}
|
|
1121
1078
|
super.emulateConnect();
|
|
1122
1079
|
for (const listener of this.socket.rawListeners("secureConnect")) listener.apply(this.socket);
|
|
1123
1080
|
}
|
|
@@ -1239,17 +1196,28 @@ var TlsSocketController = class extends TcpSocketController {
|
|
|
1239
1196
|
# Assertion failed: !wrap->started_
|
|
1240
1197
|
*/
|
|
1241
1198
|
for (const connectListener of this.socket.listeners("connect")) if (connectListener === this.socket._start || "listener" in connectListener && connectListener.listener === this.socket._start) this.socket.removeListener("connect", connectListener);
|
|
1242
|
-
realSocket.on("secure", () => {
|
|
1243
|
-
this.socket.emit("secure");
|
|
1244
|
-
}).on("session", (...args) => {
|
|
1245
|
-
this.socket.emit("session", ...args);
|
|
1246
|
-
}).on("keylog", (...args) => {
|
|
1247
|
-
this.socket.emit("keylog", ...args);
|
|
1248
|
-
}).on("OCSPResponse", (...args) => {
|
|
1249
|
-
this.socket.emit("OCSPResponse", ...args);
|
|
1250
|
-
});
|
|
1251
1199
|
return realSocket;
|
|
1252
1200
|
}
|
|
1201
|
+
#onRealSocketSecure = () => {
|
|
1202
|
+
this.socket.emit("secure");
|
|
1203
|
+
};
|
|
1204
|
+
#onRealSocketSession = (session) => {
|
|
1205
|
+
this.socket.emit("session", session);
|
|
1206
|
+
};
|
|
1207
|
+
#onRealSocketKeylog = (line) => {
|
|
1208
|
+
this.socket.emit("keylog", line);
|
|
1209
|
+
};
|
|
1210
|
+
#onRealSocketOCSPResponse = (response) => {
|
|
1211
|
+
this.socket.emit("OCSPResponse", response);
|
|
1212
|
+
};
|
|
1213
|
+
addPassthroughSocketListeners(realSocket) {
|
|
1214
|
+
const removeTcpSocketListeners = super.addPassthroughSocketListeners(realSocket);
|
|
1215
|
+
realSocket.on("secure", this.#onRealSocketSecure).on("session", this.#onRealSocketSession).on("keylog", this.#onRealSocketKeylog).on("OCSPResponse", this.#onRealSocketOCSPResponse);
|
|
1216
|
+
return () => {
|
|
1217
|
+
removeTcpSocketListeners();
|
|
1218
|
+
realSocket.removeListener("secure", this.#onRealSocketSecure).removeListener("session", this.#onRealSocketSession).removeListener("keylog", this.#onRealSocketKeylog).removeListener("OCSPResponse", this.#onRealSocketOCSPResponse);
|
|
1219
|
+
};
|
|
1220
|
+
}
|
|
1253
1221
|
};
|
|
1254
1222
|
//#endregion
|
|
1255
1223
|
//#region src/interceptors/net/utils/normalize-tls-connect-args.ts
|
|
@@ -1270,6 +1238,24 @@ function normalizeTlsConnectArgs(args) {
|
|
|
1270
1238
|
}
|
|
1271
1239
|
//#endregion
|
|
1272
1240
|
//#region src/interceptors/net/index.ts
|
|
1241
|
+
/**
|
|
1242
|
+
* @note Initialize once across entry points and package copies. The runner
|
|
1243
|
+
* is inert without the socket patch, so it needs no disposal lifecycle.
|
|
1244
|
+
*/
|
|
1245
|
+
globalThis.__MSW_INTERNAL_CONNECTION_CONTEXT ??= (() => {
|
|
1246
|
+
const context = new AsyncLocalStorage();
|
|
1247
|
+
return {
|
|
1248
|
+
run(callback) {
|
|
1249
|
+
return context.run({ consumed: false }, callback);
|
|
1250
|
+
},
|
|
1251
|
+
consume() {
|
|
1252
|
+
const connection = context.getStore();
|
|
1253
|
+
if (!connection || connection.consumed) return false;
|
|
1254
|
+
connection.consumed = true;
|
|
1255
|
+
return true;
|
|
1256
|
+
}
|
|
1257
|
+
};
|
|
1258
|
+
})();
|
|
1273
1259
|
var SocketConnectionEvent = class extends TypedEvent {
|
|
1274
1260
|
constructor(data) {
|
|
1275
1261
|
super(...["connection", {}]);
|
|
@@ -1355,6 +1341,10 @@ var SocketInterceptor = class extends Interceptor {
|
|
|
1355
1341
|
* reach Node.js as-is.
|
|
1356
1342
|
*/
|
|
1357
1343
|
if (socket[kPatched] || isCreatingPassthroughConnection) return realSocketConnect.apply(socket, args);
|
|
1344
|
+
if (globalThis.__MSW_INTERNAL_CONNECTION_CONTEXT?.consume()) {
|
|
1345
|
+
socket[kPatched] = true;
|
|
1346
|
+
return realSocketConnect.apply(socket, args);
|
|
1347
|
+
}
|
|
1358
1348
|
logger.verbose("socket.connect() %o", args);
|
|
1359
1349
|
/**
|
|
1360
1350
|
* @note The original "net.connect()"/"tls.connect()" normalize
|
|
@@ -1387,14 +1377,14 @@ var SocketInterceptor = class extends Interceptor {
|
|
|
1387
1377
|
controller = new TlsSocketController(socket, () => {
|
|
1388
1378
|
/**
|
|
1389
1379
|
* @note Create the passthrough connection via the original
|
|
1390
|
-
* "tls.connect()" with the
|
|
1380
|
+
* "tls.connect()" with the effective connection options
|
|
1391
1381
|
* (the real DNS lookup and the caller's certificate
|
|
1392
1382
|
* validation included). The latch exempts the transport
|
|
1393
1383
|
* connect of that connection from interception.
|
|
1394
1384
|
*/
|
|
1395
1385
|
isCreatingPassthroughConnection = true;
|
|
1396
1386
|
try {
|
|
1397
|
-
return tls.connect(
|
|
1387
|
+
return tls.connect(tlsConnectionOptions);
|
|
1398
1388
|
} finally {
|
|
1399
1389
|
isCreatingPassthroughConnection = false;
|
|
1400
1390
|
}
|
|
@@ -1512,6 +1502,6 @@ var SocketInterceptor = class extends Interceptor {
|
|
|
1512
1502
|
}
|
|
1513
1503
|
};
|
|
1514
1504
|
//#endregion
|
|
1515
|
-
export {
|
|
1505
|
+
export { unwrapPendingData as i, SocketController as n, kRawSocket as r, SocketInterceptor as t };
|
|
1516
1506
|
|
|
1517
|
-
//# sourceMappingURL=net-
|
|
1507
|
+
//# sourceMappingURL=net-Bh16MP4u.js.map
|