@mswjs/interceptors 0.42.2 → 0.42.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/lib/browser/interceptors/WebSocket/index.js +14 -1
  2. package/lib/browser/interceptors/WebSocket/index.js.map +1 -1
  3. package/lib/node/{batch-interceptor-ByEZVih3.js → batch-interceptor-DMOfd-9x.js} +2 -2
  4. package/lib/node/{batch-interceptor-ByEZVih3.js.map → batch-interceptor-DMOfd-9x.js.map} +1 -1
  5. package/lib/node/buffer-utils-B4FUq-l2.js +17 -0
  6. package/lib/node/buffer-utils-B4FUq-l2.js.map +1 -0
  7. package/lib/node/create-request-id-DHo-fRTV.js +14 -0
  8. package/lib/node/create-request-id-DHo-fRTV.js.map +1 -0
  9. package/lib/node/{fetch-utils-Dw1PsmtX.js → fetch-utils-Tm5LbwBe.js} +3 -14
  10. package/lib/node/{fetch-utils-Dw1PsmtX.js.map → fetch-utils-Tm5LbwBe.js.map} +1 -1
  11. package/lib/node/{has-configurable-global-IskkJJOL.js → has-configurable-global-CT6-QYdg.js} +2 -2
  12. package/lib/node/{has-configurable-global-IskkJJOL.js.map → has-configurable-global-CT6-QYdg.js.map} +1 -1
  13. package/lib/node/index.d.ts +2 -243
  14. package/lib/node/index.js +6 -25
  15. package/lib/node/index.js.map +1 -1
  16. package/lib/node/{buffer-utils-BvPY1Tc-.js → interceptor-C8qRPjxG.js} +2 -16
  17. package/lib/node/interceptor-C8qRPjxG.js.map +1 -0
  18. package/lib/node/interceptors/ClientRequest/index.js +3 -3
  19. package/lib/node/interceptors/WebSocket/index.d.ts +2 -0
  20. package/lib/node/interceptors/WebSocket/index.js +635 -0
  21. package/lib/node/interceptors/WebSocket/index.js.map +1 -0
  22. package/lib/node/interceptors/XMLHttpRequest/node.js +5 -5
  23. package/lib/node/interceptors/fetch/node.js +5 -5
  24. package/lib/node/interceptors/http/index.js +2 -2
  25. package/lib/node/interceptors/net/index.d.ts +21 -0
  26. package/lib/node/interceptors/net/index.js +1 -1
  27. package/lib/node/{net-9sRKnjIG.js → net-DkiHxhQF.js} +66 -79
  28. package/lib/node/net-DkiHxhQF.js.map +1 -0
  29. package/lib/node/patches-registry-DxR5TEc-.js +76 -0
  30. package/lib/node/patches-registry-DxR5TEc-.js.map +1 -0
  31. package/lib/node/remote-http-interceptor.js +4 -4
  32. package/lib/node/resolve-web-socket-url-CSvNPLGi.js +25 -0
  33. package/lib/node/resolve-web-socket-url-CSvNPLGi.js.map +1 -0
  34. package/lib/node/{source-BUVce4Q1.js → source-BFZ6wg4P.js} +115 -39
  35. package/lib/node/source-BFZ6wg4P.js.map +1 -0
  36. package/lib/node/websocket-CC0nB0md.d.ts +285 -0
  37. package/package.json +5 -2
  38. package/src/interceptors/WebSocket/index.ts +4 -1
  39. package/src/interceptors/http/http-parser/index.ts +9 -1
  40. package/src/interceptors/http/http-parser.ts +34 -5
  41. package/src/interceptors/http/source.ts +82 -3
  42. package/src/interceptors/net/index.ts +39 -12
  43. package/src/interceptors/net/socket-controller.ts +61 -9
  44. package/src/utils/internal-connection.ts +22 -0
  45. package/lib/node/buffer-utils-BvPY1Tc-.js.map +0 -1
  46. package/lib/node/net-9sRKnjIG.js.map +0 -1
  47. package/lib/node/source-BUVce4Q1.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;;;ACpBA,MAAM,cAAc,OAAO,aAAa;AACxC,MAAM,oBAAoB,OAAO,mBAAmB;;;;;;;;AASpD,IAAa,yBAAb,cAAqD,aAAgB;CAInE,YAA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a as createLogger, i as Interceptor } from "../../buffer-utils-BvPY1Tc-.js";
3
- import { t as FetchRequest } from "../../fetch-utils-Dw1PsmtX.js";
4
- import { o as patchesRegistry } from "../../net-9sRKnjIG.js";
5
- import { t as hasConfigurableGlobal } from "../../has-configurable-global-IskkJJOL.js";
1
+ import { a as requestContext, i as forwardHttpEvents, t as NodeHttpRequestSource } from "../../source-BFZ6wg4P.js";
2
+ import { n as createLogger, t as Interceptor } from "../../interceptor-C8qRPjxG.js";
3
+ import { t as FetchRequest } from "../../fetch-utils-Tm5LbwBe.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-BUVce4Q1.js";
2
- import { i as Interceptor } from "../../buffer-utils-BvPY1Tc-.js";
3
- import { i as getErrorResponse } from "../../fetch-utils-Dw1PsmtX.js";
4
- import { o as patchesRegistry } from "../../net-9sRKnjIG.js";
5
- import { t as hasConfigurableGlobal } from "../../has-configurable-global-IskkJJOL.js";
1
+ import { a as requestContext, i as forwardHttpEvents, t as NodeHttpRequestSource } from "../../source-BFZ6wg4P.js";
2
+ import { t as Interceptor } from "../../interceptor-C8qRPjxG.js";
3
+ import { i as getErrorResponse } from "../../fetch-utils-Tm5LbwBe.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-BUVce4Q1.js";
2
- import { i as Interceptor } from "../../buffer-utils-BvPY1Tc-.js";
1
+ import { i as forwardHttpEvents, t as NodeHttpRequestSource } from "../../source-BFZ6wg4P.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.
@@ -161,6 +161,18 @@ declare class TcpSocketController extends SocketController {
161
161
  * the exchanges, retargeted or not.
162
162
  */
163
163
  reset(connectionOptions?: NetworkConnectionOptions & net.SocketConnectOpts): void;
164
+ /**
165
+ * Schedule a reset of this controller to happen right before the
166
+ * next client write. The consumer signals the boundary of the
167
+ * current exchange (e.g. an HTTP message boundary) the moment it is
168
+ * parsed — mid-delivery of the exchange's final chunk — when an
169
+ * immediate reset would discard that chunk. Deferring the reset to
170
+ * the next write lets the current exchange settle as-is while the
171
+ * next exchange's first write already buffers for a new verdict
172
+ * (instead of following the previous one, e.g. leaking to the
173
+ * passthrough connection).
174
+ */
175
+ scheduleReset(): void;
164
176
  protected emulateConnect(): void;
165
177
  /**
166
178
  * Suspend forwarding of the passthrough socket events ("data", "end", "close")
@@ -191,6 +203,15 @@ declare class TlsSocketController extends TcpSocketController {
191
203
  passthrough(flushPendingData?: FlushPendingDataFunction): tls.TLSSocket;
192
204
  }
193
205
  //#endregion
206
+ //#region src/utils/internal-connection.d.ts
207
+ interface InternalConnectionContext {
208
+ run<T>(callback: () => T): T;
209
+ consume(): boolean;
210
+ }
211
+ declare global {
212
+ var __MSW_INTERNAL_CONNECTION_CONTEXT: InternalConnectionContext | undefined;
213
+ }
214
+ //#endregion
194
215
  //#region src/interceptors/net/index.d.ts
195
216
  declare module 'node:http' {
196
217
  interface Agent {
@@ -1,2 +1,2 @@
1
- import { t as SocketInterceptor } from "../../net-9sRKnjIG.js";
1
+ import { t as SocketInterceptor } from "../../net-DkiHxhQF.js";
2
2
  export { SocketInterceptor };
@@ -1,81 +1,12 @@
1
- import { a as createLogger, i as Interceptor, r as toBuffer } from "./buffer-utils-BvPY1Tc-.js";
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()`.
@@ -447,6 +378,7 @@ var TcpSocketController = class extends SocketController {
447
378
  #readsCorked = false;
448
379
  #corkedReads = [];
449
380
  #realHandleSwapped = false;
381
+ #resetScheduled = false;
450
382
  #clientCloseEmitted = false;
451
383
  #clientEndPushed = false;
452
384
  #connectEmulated = false;
@@ -570,8 +502,23 @@ var TcpSocketController = class extends SocketController {
570
502
  if (this.readyState === SocketController.PENDING) return;
571
503
  this.#reset();
572
504
  }
505
+ /**
506
+ * Schedule a reset of this controller to happen right before the
507
+ * next client write. The consumer signals the boundary of the
508
+ * current exchange (e.g. an HTTP message boundary) the moment it is
509
+ * parsed — mid-delivery of the exchange's final chunk — when an
510
+ * immediate reset would discard that chunk. Deferring the reset to
511
+ * the next write lets the current exchange settle as-is while the
512
+ * next exchange's first write already buffers for a new verdict
513
+ * (instead of following the previous one, e.g. leaking to the
514
+ * passthrough connection).
515
+ */
516
+ scheduleReset() {
517
+ this.#resetScheduled = true;
518
+ }
573
519
  #reset() {
574
520
  logger$1.verbose("resetting the socket...");
521
+ this.#resetScheduled = false;
575
522
  this.readyState = SocketController.PENDING;
576
523
  this.pendingConnection = Promise.withResolvers();
577
524
  this.#bufferedWrites = [];
@@ -622,6 +569,13 @@ var TcpSocketController = class extends SocketController {
622
569
  const data = args[1];
623
570
  logger$1.verbose("socket write (state: %d) %o", this.readyState, args);
624
571
  /**
572
+ * @note A scheduled reset marks the boundary of the previous
573
+ * exchange (see "scheduleReset"). This write is the first one past
574
+ * the boundary; reset before dispatching so it opens the next
575
+ * exchange instead of following the previous exchange's verdict.
576
+ */
577
+ if (this.#resetScheduled) this.reset();
578
+ /**
625
579
  * @note Buffer the write BEFORE pushing the data to the server socket.
626
580
  * Handling the pushed data may transition this controller within the
627
581
  * same call stack, and each transition settles the buffered entry:
@@ -867,13 +821,14 @@ var TcpSocketController = class extends SocketController {
867
821
  * the consumer reads the buffered data.
868
822
  */
869
823
  #emitClientClose(hadError) {
824
+ if (this.#clientCloseEmitted) return;
870
825
  if (this.#clientEndPushed && !this.socket.readableEnded && !this.socket.destroyed) {
871
826
  let closeDelivered = false;
872
827
  const deliverClose = (hadErrorOverride) => {
873
828
  if (closeDelivered) return;
874
829
  closeDelivered = true;
875
830
  process.nextTick(() => {
876
- if (!this.#clientCloseEmitted) this.socket.emit("close", hadErrorOverride ?? hadError);
831
+ this.#emitClientClose(hadErrorOverride ?? hadError);
877
832
  });
878
833
  };
879
834
  this.socket.once("end", () => {
@@ -892,7 +847,8 @@ var TcpSocketController = class extends SocketController {
892
847
  };
893
848
  return;
894
849
  }
895
- this.socket.emit("close", hadError);
850
+ this.socket.destroy();
851
+ if (this.#realHandleSwapped) this.socket.emit("close", hadError);
896
852
  }
897
853
  #onMockSocketDrain = () => {
898
854
  logger$1.verbose("client socket drained!");
@@ -1095,6 +1051,15 @@ var TlsSocketController = class extends TcpSocketController {
1095
1051
  });
1096
1052
  }
1097
1053
  emulateConnect() {
1054
+ /**
1055
+ * @note The client chooses its wire protocol when we emulate the
1056
+ * handshake. A later passthrough handshake must preserve that choice
1057
+ * instead of negotiating a different protocol for buffered writes.
1058
+ */
1059
+ if (this.#tlsConnectionOptions) {
1060
+ const alpnProtocol = this.socket._handle.getALPNNegotiatedProtocol();
1061
+ this.#tlsConnectionOptions.ALPNProtocols = alpnProtocol ? [alpnProtocol] : [];
1062
+ }
1098
1063
  super.emulateConnect();
1099
1064
  for (const listener of this.socket.rawListeners("secureConnect")) listener.apply(this.socket);
1100
1065
  }
@@ -1247,6 +1212,24 @@ function normalizeTlsConnectArgs(args) {
1247
1212
  }
1248
1213
  //#endregion
1249
1214
  //#region src/interceptors/net/index.ts
1215
+ /**
1216
+ * @note Initialize once across entry points and package copies. The runner
1217
+ * is inert without the socket patch, so it needs no disposal lifecycle.
1218
+ */
1219
+ globalThis.__MSW_INTERNAL_CONNECTION_CONTEXT ??= (() => {
1220
+ const context = new AsyncLocalStorage();
1221
+ return {
1222
+ run(callback) {
1223
+ return context.run({ consumed: false }, callback);
1224
+ },
1225
+ consume() {
1226
+ const connection = context.getStore();
1227
+ if (!connection || connection.consumed) return false;
1228
+ connection.consumed = true;
1229
+ return true;
1230
+ }
1231
+ };
1232
+ })();
1250
1233
  var SocketConnectionEvent = class extends TypedEvent {
1251
1234
  constructor(data) {
1252
1235
  super(...["connection", {}]);
@@ -1332,6 +1315,10 @@ var SocketInterceptor = class extends Interceptor {
1332
1315
  * reach Node.js as-is.
1333
1316
  */
1334
1317
  if (socket[kPatched] || isCreatingPassthroughConnection) return realSocketConnect.apply(socket, args);
1318
+ if (globalThis.__MSW_INTERNAL_CONNECTION_CONTEXT?.consume()) {
1319
+ socket[kPatched] = true;
1320
+ return realSocketConnect.apply(socket, args);
1321
+ }
1335
1322
  logger.verbose("socket.connect() %o", args);
1336
1323
  /**
1337
1324
  * @note The original "net.connect()"/"tls.connect()" normalize
@@ -1364,14 +1351,14 @@ var SocketInterceptor = class extends Interceptor {
1364
1351
  controller = new TlsSocketController(socket, () => {
1365
1352
  /**
1366
1353
  * @note Create the passthrough connection via the original
1367
- * "tls.connect()" with the original connection options
1354
+ * "tls.connect()" with the effective connection options
1368
1355
  * (the real DNS lookup and the caller's certificate
1369
1356
  * validation included). The latch exempts the transport
1370
1357
  * connect of that connection from interception.
1371
1358
  */
1372
1359
  isCreatingPassthroughConnection = true;
1373
1360
  try {
1374
- return tls.connect(realTlsConnectionOptions ?? tlsConnectionOptions);
1361
+ return tls.connect(tlsConnectionOptions);
1375
1362
  } finally {
1376
1363
  isCreatingPassthroughConnection = false;
1377
1364
  }
@@ -1489,6 +1476,6 @@ var SocketInterceptor = class extends Interceptor {
1489
1476
  }
1490
1477
  };
1491
1478
  //#endregion
1492
- export { getDeepPropertyDescriptor as a, unwrapPendingData as i, SocketController as n, patchesRegistry as o, kRawSocket as r, SocketInterceptor as t };
1479
+ export { unwrapPendingData as i, SocketController as n, kRawSocket as r, SocketInterceptor as t };
1493
1480
 
1494
- //# sourceMappingURL=net-9sRKnjIG.js.map
1481
+ //# sourceMappingURL=net-DkiHxhQF.js.map