@mswjs/interceptors 0.41.8 → 0.42.0
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/README.md +274 -228
- package/lib/browser/{bufferUtils-BiiO6HZv.mjs → buffer-utils-DJj7YzLG.js} +3 -3
- package/lib/browser/buffer-utils-DJj7YzLG.js.map +1 -0
- package/lib/browser/create-request-id-DlEd4GOA.js +184 -0
- package/lib/browser/create-request-id-DlEd4GOA.js.map +1 -0
- package/lib/browser/{getRawRequest-B1BqgWG6.mjs → fetch-utils-zxA_SD66.js} +123 -52
- package/lib/browser/fetch-utils-zxA_SD66.js.map +1 -0
- package/lib/browser/handle-request-CIOa9O-N.js +167 -0
- package/lib/browser/handle-request-CIOa9O-N.js.map +1 -0
- package/lib/{node/hasConfigurableGlobal-BiTmog1u.mjs → browser/has-configurable-global-Cew-dYqk.js} +5 -7
- package/lib/browser/has-configurable-global-Cew-dYqk.js.map +1 -0
- package/lib/browser/http-CB9rQ7i_.d.ts +105 -0
- package/lib/browser/{index.d.cts → index.d.ts} +33 -38
- package/lib/browser/index.js +130 -0
- package/lib/browser/index.js.map +1 -0
- package/lib/browser/interceptor-dtJZ_9QT.d.ts +50 -0
- package/lib/browser/interceptors/WebSocket/index.d.ts +2 -0
- package/lib/browser/interceptors/WebSocket/{index.mjs → index.js} +40 -31
- package/lib/browser/interceptors/WebSocket/index.js.map +1 -0
- package/lib/browser/interceptors/XMLHttpRequest/web.d.ts +11 -0
- package/lib/browser/interceptors/XMLHttpRequest/web.js +2 -0
- package/lib/browser/interceptors/fetch/web.d.ts +14 -0
- package/lib/browser/interceptors/fetch/web.js +2 -0
- package/lib/browser/presets/browser.d.ts +11 -0
- package/lib/browser/presets/browser.js +12 -0
- package/lib/browser/presets/browser.js.map +1 -0
- package/lib/browser/{resolveWebSocketUrl-C83-x9iE.mjs → resolve-web-socket-url-CSvNPLGi.js} +3 -3
- package/lib/browser/resolve-web-socket-url-CSvNPLGi.js.map +1 -0
- package/lib/browser/web-BjVDkiX0.js +248 -0
- package/lib/browser/web-BjVDkiX0.js.map +1 -0
- package/lib/{node/XMLHttpRequest-DhupxLHX.mjs → browser/web-C2oKsT3Q.js} +328 -256
- package/lib/browser/web-C2oKsT3Q.js.map +1 -0
- package/lib/browser/{interceptors/WebSocket/index.d.cts → websocket-CC0nB0md.d.ts} +41 -33
- package/lib/node/batch-interceptor-ByEZVih3.js +119 -0
- package/lib/node/batch-interceptor-ByEZVih3.js.map +1 -0
- package/lib/node/batch-interceptor-CPjFK2td.d.ts +28 -0
- package/lib/node/buffer-utils-BvPY1Tc-.js +187 -0
- package/lib/node/buffer-utils-BvPY1Tc-.js.map +1 -0
- package/lib/node/fetch-utils-Dw1PsmtX.js +568 -0
- package/lib/node/fetch-utils-Dw1PsmtX.js.map +1 -0
- package/lib/node/has-configurable-global-CJCh_g1I.js +22 -0
- package/lib/node/has-configurable-global-CJCh_g1I.js.map +1 -0
- package/lib/node/http-CB9rQ7i_.d.ts +105 -0
- package/lib/{browser/interceptors/WebSocket/index.d.mts → node/index.d.ts} +120 -60
- package/lib/node/{index.mjs → index.js} +8 -11
- package/lib/node/index.js.map +1 -0
- package/lib/node/interceptor-dtJZ_9QT.d.ts +50 -0
- package/lib/node/interceptors/ClientRequest/index.d.ts +14 -0
- package/lib/node/interceptors/ClientRequest/index.js +67 -0
- package/lib/node/interceptors/ClientRequest/index.js.map +1 -0
- package/lib/node/interceptors/XMLHttpRequest/node.d.ts +12 -0
- package/lib/node/interceptors/XMLHttpRequest/node.js +74 -0
- package/lib/node/interceptors/XMLHttpRequest/node.js.map +1 -0
- package/lib/node/interceptors/fetch/node.d.ts +18 -0
- package/lib/node/interceptors/fetch/node.js +83 -0
- package/lib/node/interceptors/fetch/node.js.map +1 -0
- package/lib/node/interceptors/http/index.d.ts +14 -0
- package/lib/node/interceptors/http/index.js +32 -0
- package/lib/node/interceptors/http/index.js.map +1 -0
- package/lib/node/interceptors/net/index.d.ts +203 -0
- package/lib/node/interceptors/net/index.js +2 -0
- package/lib/node/llhttp/constants.cjs +485 -0
- package/lib/node/llhttp/constants.d.cts +957 -0
- package/lib/node/llhttp/llhttp.wasm +0 -0
- package/lib/node/net-DtMnyEeg.js +1388 -0
- package/lib/node/net-DtMnyEeg.js.map +1 -0
- package/lib/node/presets/node.d.ts +12 -0
- package/lib/node/presets/node.js +17 -0
- package/lib/node/presets/node.js.map +1 -0
- package/lib/node/{RemoteHttpInterceptor.d.cts → remote-http-interceptor.d.ts} +12 -11
- package/lib/node/{RemoteHttpInterceptor.mjs → remote-http-interceptor.js} +38 -33
- package/lib/node/remote-http-interceptor.js.map +1 -0
- package/lib/node/source-lP0yyEtA.js +1990 -0
- package/lib/node/source-lP0yyEtA.js.map +1 -0
- package/package.json +79 -118
- package/src/batch-interceptor.test.ts +475 -0
- package/src/batch-interceptor.ts +244 -0
- package/src/{createRequestId.test.ts → create-request-id.test.ts} +1 -2
- package/src/disposable.ts +13 -0
- package/src/events/http.ts +92 -0
- package/src/events/websocket.ts +47 -0
- package/src/glossary.ts +1 -27
- package/src/index.ts +18 -10
- package/src/interceptor.test.ts +279 -0
- package/src/interceptor.ts +139 -0
- package/src/interceptors/ClientRequest/index.test.ts +21 -39
- package/src/interceptors/ClientRequest/index.ts +65 -180
- package/src/interceptors/ClientRequest/utils/{recordRawHeaders.test.ts → record-raw-headers.test.ts} +1 -2
- package/src/interceptors/ClientRequest/utils/{recordRawHeaders.ts → record-raw-headers.ts} +29 -2
- package/src/interceptors/WebSocket/index.ts +34 -51
- package/src/interceptors/WebSocket/utils/{bindEvent.test.ts → bind-event.test.ts} +1 -2
- package/src/interceptors/WebSocket/utils/events.test.ts +0 -1
- package/src/interceptors/WebSocket/{WebSocketClassTransport.ts → web-socket-class-transport.ts} +3 -3
- package/src/interceptors/WebSocket/{WebSocketClientConnection.ts → web-socket-client-connection.ts} +4 -4
- package/src/interceptors/WebSocket/{WebSocketOverride.ts → web-socket-override.ts} +6 -7
- package/src/interceptors/WebSocket/{WebSocketServerConnection.ts → web-socket-server-connection.ts} +4 -4
- package/src/interceptors/WebSocket/{WebSocketTransport.ts → web-socket-transport.ts} +1 -1
- package/src/interceptors/XMLHttpRequest/node.ts +104 -0
- package/src/interceptors/XMLHttpRequest/polyfills/{ProgressEventPolyfill.ts → progress-event-polyfill.ts} +1 -1
- package/src/interceptors/XMLHttpRequest/utils/{concateArrayBuffer.test.ts → concat-array-buffer.test.ts} +1 -2
- package/src/interceptors/XMLHttpRequest/utils/{concatArrayBuffer.ts → concat-array-buffer.ts} +1 -1
- package/src/interceptors/XMLHttpRequest/utils/{createEvent.test.ts → create-event.test.ts} +3 -4
- package/src/interceptors/XMLHttpRequest/utils/{createEvent.ts → create-event.ts} +2 -2
- package/src/interceptors/XMLHttpRequest/utils/{createResponse.ts → create-response.ts} +1 -1
- package/src/interceptors/XMLHttpRequest/utils/{getBodyByteLength.test.ts → get-body-byte-length.test.ts} +1 -2
- package/src/interceptors/XMLHttpRequest/web.ts +34 -0
- package/src/interceptors/XMLHttpRequest/{XMLHttpRequestController.ts → xml-http-request-controller.ts} +363 -204
- package/src/interceptors/XMLHttpRequest/{XMLHttpRequestProxy.ts → xml-http-request-proxy.ts} +28 -25
- package/src/interceptors/fetch/node.ts +103 -0
- package/src/interceptors/fetch/utils/{followRedirect.ts → follow-redirect.ts} +1 -1
- package/src/interceptors/fetch/web.ts +217 -0
- package/src/interceptors/http/forward-events.test.ts +86 -0
- package/src/interceptors/http/forward-events.ts +139 -0
- package/src/interceptors/http/http-parser/index.ts +310 -0
- package/src/interceptors/http/http-parser/llhttp/constants.cjs +485 -0
- package/src/interceptors/http/http-parser/llhttp/constants.d.cts +957 -0
- package/src/interceptors/http/http-parser/llhttp/llhttp.wasm +0 -0
- package/src/interceptors/http/http-parser.ts +138 -0
- package/src/interceptors/http/index.ts +34 -0
- package/src/interceptors/http/source.ts +688 -0
- package/src/interceptors/net/index.ts +368 -0
- package/src/interceptors/net/socket-controller.ts +1476 -0
- package/src/interceptors/net/utils/address-info.ts +54 -0
- package/src/interceptors/net/utils/connection-options-to-url.ts +56 -0
- package/src/interceptors/net/utils/flush-writes.ts +57 -0
- package/src/interceptors/net/utils/get-tls-connect-options.ts +23 -0
- package/src/interceptors/net/utils/normalize-net-connect-args.test.ts +233 -0
- package/src/interceptors/net/utils/normalize-net-connect-args.ts +121 -0
- package/src/interceptors/net/utils/normalize-tls-connect-args.ts +50 -0
- package/src/presets/browser.ts +4 -4
- package/src/presets/node.ts +4 -4
- package/src/{RemoteHttpInterceptor.ts → remote-http-interceptor.ts} +55 -42
- package/src/request-context.ts +40 -0
- package/src/{RequestController.test.ts → request-controller.test.ts} +37 -3
- package/src/{RequestController.ts → request-controller.ts} +33 -11
- package/src/utils/{bufferUtils.test.ts → buffer-utils.test.ts} +1 -2
- package/src/utils/buffer-utils.ts +37 -0
- package/src/utils/{cloneObject.test.ts → clone-object.test.ts} +1 -2
- package/src/utils/{cloneObject.ts → clone-object.ts} +8 -8
- package/src/utils/{createProxy.test.ts → create-proxy.test.ts} +6 -4
- package/src/utils/{createProxy.ts → create-proxy.ts} +1 -1
- package/src/utils/{fetchUtils.test.ts → fetch-utils.test.ts} +1 -1
- package/src/utils/{fetchUtils.ts → fetch-utils.ts} +28 -3
- package/src/utils/{findPropertySource.test.ts → find-property-source.test.ts} +1 -2
- package/src/utils/{getCleanUrl.test.ts → get-clean-url.test.ts} +1 -2
- package/src/utils/{getUrlByRequestOptions.test.ts → get-url-by-request-options.test.ts} +4 -8
- package/src/utils/{getUrlByRequestOptions.ts → get-url-by-request-options.ts} +16 -16
- package/src/utils/{getValueBySymbol.test.ts → get-value-by-symbol.test.ts} +1 -2
- package/src/utils/{handleRequest.ts → handle-request.ts} +66 -47
- package/src/utils/{hasConfigurableGlobal.test.ts → has-configurable-global.test.ts} +1 -2
- package/src/utils/{hasConfigurableGlobal.ts → has-configurable-global.ts} +2 -4
- package/src/utils/{isObject.test.ts → is-object.test.ts} +1 -2
- package/src/utils/logger.test.ts +154 -0
- package/src/utils/logger.ts +154 -0
- package/src/utils/{parseJson.test.ts → parse-json.test.ts} +1 -2
- package/src/utils/{patchesRegistry.test.ts → patches-registry.test.ts} +1 -1
- package/src/utils/{patchesRegistry.ts → patches-registry.ts} +1 -1
- package/src/utils/{responseUtils.ts → response-utils.ts} +25 -2
- package/ClientRequest/package.json +0 -11
- package/RemoteHttpInterceptor/package.json +0 -11
- package/WebSocket/package.json +0 -12
- package/XMLHttpRequest/package.json +0 -12
- package/fetch/package.json +0 -12
- package/lib/browser/Interceptor-Deczogc8.d.cts +0 -65
- package/lib/browser/Interceptor-gqKgs-aF.d.mts +0 -65
- package/lib/browser/XMLHttpRequest-B11I9TBx.cjs +0 -751
- package/lib/browser/XMLHttpRequest-B11I9TBx.cjs.map +0 -1
- package/lib/browser/XMLHttpRequest-DHEkSoRN.mjs +0 -746
- package/lib/browser/XMLHttpRequest-DHEkSoRN.mjs.map +0 -1
- package/lib/browser/bufferUtils-BiiO6HZv.mjs.map +0 -1
- package/lib/browser/bufferUtils-Uc0eRItL.cjs +0 -38
- package/lib/browser/bufferUtils-Uc0eRItL.cjs.map +0 -1
- package/lib/browser/createRequestId-DOf8Ktjs.cjs +0 -205
- package/lib/browser/createRequestId-DOf8Ktjs.cjs.map +0 -1
- package/lib/browser/createRequestId-DYCsFHOi.mjs +0 -170
- package/lib/browser/createRequestId-DYCsFHOi.mjs.map +0 -1
- package/lib/browser/fetch-BJwfdses.mjs +0 -236
- package/lib/browser/fetch-BJwfdses.mjs.map +0 -1
- package/lib/browser/fetch-M8iXkZ3L.cjs +0 -241
- package/lib/browser/fetch-M8iXkZ3L.cjs.map +0 -1
- package/lib/browser/getRawRequest-B1BqgWG6.mjs.map +0 -1
- package/lib/browser/getRawRequest-DdfaiPVH.cjs +0 -376
- package/lib/browser/getRawRequest-DdfaiPVH.cjs.map +0 -1
- package/lib/browser/glossary-1lhZx6Aw.d.cts +0 -69
- package/lib/browser/glossary-nkHWcwvY.d.mts +0 -69
- package/lib/browser/handleRequest-1Yqu_ho_.mjs +0 -178
- package/lib/browser/handleRequest-1Yqu_ho_.mjs.map +0 -1
- package/lib/browser/handleRequest-Cz4_wmQ9.cjs +0 -189
- package/lib/browser/handleRequest-Cz4_wmQ9.cjs.map +0 -1
- package/lib/browser/hasConfigurableGlobal-C8zq1MCg.mjs +0 -109
- package/lib/browser/hasConfigurableGlobal-C8zq1MCg.mjs.map +0 -1
- package/lib/browser/hasConfigurableGlobal-CS7adEvV.cjs +0 -126
- package/lib/browser/hasConfigurableGlobal-CS7adEvV.cjs.map +0 -1
- package/lib/browser/index.cjs +0 -70
- package/lib/browser/index.cjs.map +0 -1
- package/lib/browser/index.d.mts +0 -125
- package/lib/browser/index.mjs +0 -56
- package/lib/browser/index.mjs.map +0 -1
- package/lib/browser/interceptors/WebSocket/index.cjs +0 -618
- package/lib/browser/interceptors/WebSocket/index.cjs.map +0 -1
- package/lib/browser/interceptors/WebSocket/index.mjs.map +0 -1
- package/lib/browser/interceptors/XMLHttpRequest/index.cjs +0 -8
- package/lib/browser/interceptors/XMLHttpRequest/index.d.cts +0 -15
- package/lib/browser/interceptors/XMLHttpRequest/index.d.mts +0 -15
- package/lib/browser/interceptors/XMLHttpRequest/index.mjs +0 -8
- package/lib/browser/interceptors/fetch/index.cjs +0 -7
- package/lib/browser/interceptors/fetch/index.d.cts +0 -13
- package/lib/browser/interceptors/fetch/index.d.mts +0 -13
- package/lib/browser/interceptors/fetch/index.mjs +0 -7
- package/lib/browser/presets/browser.cjs +0 -18
- package/lib/browser/presets/browser.cjs.map +0 -1
- package/lib/browser/presets/browser.d.cts +0 -12
- package/lib/browser/presets/browser.d.mts +0 -14
- package/lib/browser/presets/browser.mjs +0 -18
- package/lib/browser/presets/browser.mjs.map +0 -1
- package/lib/browser/resolveWebSocketUrl-6K6EgqsA.cjs +0 -31
- package/lib/browser/resolveWebSocketUrl-6K6EgqsA.cjs.map +0 -1
- package/lib/browser/resolveWebSocketUrl-C83-x9iE.mjs.map +0 -1
- package/lib/node/BatchInterceptor-DdMNfSUY.mjs +0 -44
- package/lib/node/BatchInterceptor-DdMNfSUY.mjs.map +0 -1
- package/lib/node/BatchInterceptor-KKF8Q47I.d.cts +0 -26
- package/lib/node/BatchInterceptor-Z1lwK23r.cjs +0 -49
- package/lib/node/BatchInterceptor-Z1lwK23r.cjs.map +0 -1
- package/lib/node/BatchInterceptor-rSr-NH_H.d.mts +0 -26
- package/lib/node/ClientRequest-DFs7FPNi.cjs +0 -1058
- package/lib/node/ClientRequest-DFs7FPNi.cjs.map +0 -1
- package/lib/node/ClientRequest-dRpI9v1o.mjs +0 -1049
- package/lib/node/ClientRequest-dRpI9v1o.mjs.map +0 -1
- package/lib/node/Interceptor-BsZ21ue0.d.cts +0 -132
- package/lib/node/Interceptor-soD-WpQO.d.mts +0 -132
- package/lib/node/RemoteHttpInterceptor.cjs +0 -155
- package/lib/node/RemoteHttpInterceptor.cjs.map +0 -1
- package/lib/node/RemoteHttpInterceptor.d.mts +0 -39
- package/lib/node/RemoteHttpInterceptor.mjs.map +0 -1
- package/lib/node/XMLHttpRequest-DhupxLHX.mjs.map +0 -1
- package/lib/node/XMLHttpRequest-Dyi6ahGz.cjs +0 -752
- package/lib/node/XMLHttpRequest-Dyi6ahGz.cjs.map +0 -1
- package/lib/node/bufferUtils-DxPxwff_.mjs +0 -20
- package/lib/node/bufferUtils-DxPxwff_.mjs.map +0 -1
- package/lib/node/bufferUtils-S5_-2eN4.cjs +0 -38
- package/lib/node/bufferUtils-S5_-2eN4.cjs.map +0 -1
- package/lib/node/chunk-CbDLau6x.cjs +0 -34
- package/lib/node/fetch-BqMcbuYR.mjs +0 -252
- package/lib/node/fetch-BqMcbuYR.mjs.map +0 -1
- package/lib/node/fetch-aQJu1Gf_.cjs +0 -259
- package/lib/node/fetch-aQJu1Gf_.cjs.map +0 -1
- package/lib/node/fetchUtils-BKJ1XmiO.mjs +0 -480
- package/lib/node/fetchUtils-BKJ1XmiO.mjs.map +0 -1
- package/lib/node/fetchUtils-umV5xXBy.cjs +0 -546
- package/lib/node/fetchUtils-umV5xXBy.cjs.map +0 -1
- package/lib/node/getRawRequest-B6znU6il.cjs +0 -36
- package/lib/node/getRawRequest-B6znU6il.cjs.map +0 -1
- package/lib/node/getRawRequest-C2-1urzA.mjs +0 -24
- package/lib/node/getRawRequest-C2-1urzA.mjs.map +0 -1
- package/lib/node/handleRequest-DCLzePtS.mjs +0 -190
- package/lib/node/handleRequest-DCLzePtS.mjs.map +0 -1
- package/lib/node/handleRequest-DVOthWJo.cjs +0 -220
- package/lib/node/handleRequest-DVOthWJo.cjs.map +0 -1
- package/lib/node/hasConfigurableGlobal-BiTmog1u.mjs.map +0 -1
- package/lib/node/hasConfigurableGlobal-MjY06_Ok.cjs +0 -108
- package/lib/node/hasConfigurableGlobal-MjY06_Ok.cjs.map +0 -1
- package/lib/node/index-BJ5E5aW-.d.cts +0 -113
- package/lib/node/index-DfoF45ih.d.mts +0 -113
- package/lib/node/index.cjs +0 -53
- package/lib/node/index.cjs.map +0 -1
- package/lib/node/index.d.cts +0 -104
- package/lib/node/index.d.mts +0 -104
- package/lib/node/index.mjs.map +0 -1
- package/lib/node/interceptors/ClientRequest/index.cjs +0 -6
- package/lib/node/interceptors/ClientRequest/index.d.cts +0 -2
- package/lib/node/interceptors/ClientRequest/index.d.mts +0 -3
- package/lib/node/interceptors/ClientRequest/index.mjs +0 -6
- package/lib/node/interceptors/XMLHttpRequest/index.cjs +0 -7
- package/lib/node/interceptors/XMLHttpRequest/index.d.cts +0 -14
- package/lib/node/interceptors/XMLHttpRequest/index.d.mts +0 -14
- package/lib/node/interceptors/XMLHttpRequest/index.mjs +0 -7
- package/lib/node/interceptors/fetch/index.cjs +0 -6
- package/lib/node/interceptors/fetch/index.d.cts +0 -12
- package/lib/node/interceptors/fetch/index.d.mts +0 -12
- package/lib/node/interceptors/fetch/index.mjs +0 -6
- package/lib/node/node-DIKcnzhK.cjs +0 -39
- package/lib/node/node-DIKcnzhK.cjs.map +0 -1
- package/lib/node/node-lsdNwZEW.mjs +0 -27
- package/lib/node/node-lsdNwZEW.mjs.map +0 -1
- package/lib/node/presets/node.cjs +0 -23
- package/lib/node/presets/node.cjs.map +0 -1
- package/lib/node/presets/node.d.cts +0 -13
- package/lib/node/presets/node.d.mts +0 -15
- package/lib/node/presets/node.mjs +0 -23
- package/lib/node/presets/node.mjs.map +0 -1
- package/lib/node/utils/node/index.cjs +0 -4
- package/lib/node/utils/node/index.d.cts +0 -16
- package/lib/node/utils/node/index.d.mts +0 -16
- package/lib/node/utils/node/index.mjs +0 -3
- package/presets/browser/package.json +0 -5
- package/presets/node/package.json +0 -11
- package/src/BatchInterceptor.test.ts +0 -255
- package/src/BatchInterceptor.ts +0 -95
- package/src/Interceptor.test.ts +0 -205
- package/src/Interceptor.ts +0 -249
- package/src/getRawRequest.ts +0 -21
- package/src/interceptors/ClientRequest/MockHttpSocket.ts +0 -724
- package/src/interceptors/ClientRequest/agents.ts +0 -110
- package/src/interceptors/ClientRequest/utils/getIncomingMessageBody.test.ts +0 -54
- package/src/interceptors/ClientRequest/utils/getIncomingMessageBody.ts +0 -45
- package/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.test.ts +0 -427
- package/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts +0 -268
- package/src/interceptors/ClientRequest/utils/parserUtils.ts +0 -48
- package/src/interceptors/Socket/MockSocket.test.ts +0 -264
- package/src/interceptors/Socket/MockSocket.ts +0 -58
- package/src/interceptors/Socket/utils/baseUrlFromConnectionOptions.ts +0 -26
- package/src/interceptors/Socket/utils/normalizeSocketWriteArgs.test.ts +0 -52
- package/src/interceptors/Socket/utils/normalizeSocketWriteArgs.ts +0 -33
- package/src/interceptors/XMLHttpRequest/index.ts +0 -40
- package/src/interceptors/fetch/index.ts +0 -203
- package/src/utils/bufferUtils.ts +0 -22
- package/src/utils/canParseUrl.ts +0 -13
- package/src/utils/emitAsync.ts +0 -25
- package/src/utils/nextTick.ts +0 -11
- package/src/utils/node/index.ts +0 -39
- /package/src/{createRequestId.ts → create-request-id.ts} +0 -0
- /package/src/{InterceptorError.ts → interceptor-error.ts} +0 -0
- /package/src/interceptors/WebSocket/utils/{bindEvent.ts → bind-event.ts} +0 -0
- /package/src/interceptors/XMLHttpRequest/polyfills/{EventPolyfill.ts → event-polyfill.ts} +0 -0
- /package/src/interceptors/XMLHttpRequest/utils/{getBodyByteLength.ts → get-body-byte-length.ts} +0 -0
- /package/src/interceptors/XMLHttpRequest/utils/{isDomParserSupportedType.ts → is-dom-parser-supported-type.ts} +0 -0
- /package/src/interceptors/fetch/utils/{createNetworkError.ts → create-network-error.ts} +0 -0
- /package/src/utils/{findPropertySource.ts → find-property-source.ts} +0 -0
- /package/src/utils/{getCleanUrl.ts → get-clean-url.ts} +0 -0
- /package/src/utils/{getValueBySymbol.ts → get-value-by-symbol.ts} +0 -0
- /package/src/utils/{isNodeLikeError.ts → is-node-like-error.ts} +0 -0
- /package/src/utils/{isObject.ts → is-object.ts} +0 -0
- /package/src/utils/{isPropertyAccessible.ts → is-property-accessible.ts} +0 -0
- /package/src/utils/{parseJson.ts → parse-json.ts} +0 -0
- /package/src/utils/{resolveWebSocketUrl.ts → resolve-web-socket-url.ts} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region src/utils/
|
|
1
|
+
//#region src/utils/buffer-utils.ts
|
|
2
2
|
const encoder = new TextEncoder();
|
|
3
3
|
function encodeBuffer(text) {
|
|
4
4
|
return encoder.encode(text);
|
|
@@ -14,7 +14,7 @@ function decodeBuffer(buffer, encoding) {
|
|
|
14
14
|
function toArrayBuffer(array) {
|
|
15
15
|
return array.buffer.slice(array.byteOffset, array.byteOffset + array.byteLength);
|
|
16
16
|
}
|
|
17
|
-
|
|
18
17
|
//#endregion
|
|
19
18
|
export { encodeBuffer as n, toArrayBuffer as r, decodeBuffer as t };
|
|
20
|
-
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=buffer-utils-DJj7YzLG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buffer-utils-DJj7YzLG.js","names":[],"sources":["../../src/utils/buffer-utils.ts"],"sourcesContent":["const encoder = new TextEncoder()\n\nexport function encodeBuffer(text: string) {\n return encoder.encode(text)\n}\n\nexport function decodeBuffer(buffer: AllowSharedBufferSource, encoding?: string): string {\n const decoder = new TextDecoder(encoding)\n return decoder.decode(buffer)\n}\n\n/**\n * Create an `ArrayBuffer` from the given `Uint8Array`.\n * Takes the byte offset into account to produce the right buffer\n * in the case when the buffer is bigger than the data view.\n */\nexport function toArrayBuffer(array: Uint8Array<ArrayBuffer>): ArrayBuffer {\n return array.buffer.slice(\n array.byteOffset,\n array.byteOffset + array.byteLength\n )\n}\n\nexport function toBuffer(\n data: string | Buffer | Uint8Array<ArrayBufferLike>,\n encoding?: BufferEncoding\n): Buffer {\n if (Buffer.isBuffer(data)) {\n return data\n }\n\n if (data instanceof Uint8Array) {\n return Buffer.from(data.buffer)\n }\n\n return Buffer.from(data, encoding)\n}\n"],"mappings":";AAAA,MAAM,UAAU,IAAI,YAAY;AAEhC,SAAgB,aAAa,MAAc;CACzC,OAAO,QAAQ,OAAO,IAAI;AAC5B;AAEA,SAAgB,aAAa,QAAiC,UAA2B;CAEvF,OAAO,IADa,YAAY,QACnB,CAAC,CAAC,OAAO,MAAM;AAC9B;;;;;;AAOA,SAAgB,cAAc,OAA6C;CACzE,OAAO,MAAM,OAAO,MAClB,MAAM,YACN,MAAM,aAAa,MAAM,UAC3B;AACF"}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { Emitter } from "rettime";
|
|
2
|
+
import debug from "debug";
|
|
3
|
+
//#region src/disposable.ts
|
|
4
|
+
var Disposable = class {
|
|
5
|
+
constructor() {
|
|
6
|
+
this.subscriptions = [];
|
|
7
|
+
}
|
|
8
|
+
dispose() {
|
|
9
|
+
let subscription;
|
|
10
|
+
while (subscription = this.subscriptions.pop()) subscription();
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/utils/logger.ts
|
|
15
|
+
const LOG_TIMESTAMP_REGEXP = /\d{2}:\d{2}:\d{2}\.\d{3}/;
|
|
16
|
+
function normalizeNamespace(namespace) {
|
|
17
|
+
return namespace.split(":").map((segment) => {
|
|
18
|
+
return segment.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-|-$/g, "").toLowerCase();
|
|
19
|
+
}).filter(Boolean).join(":");
|
|
20
|
+
}
|
|
21
|
+
function getTimestamp() {
|
|
22
|
+
return (/* @__PURE__ */ new Date()).toISOString().slice(11, 23);
|
|
23
|
+
}
|
|
24
|
+
async function readBody(message) {
|
|
25
|
+
if (message.body == null) return null;
|
|
26
|
+
try {
|
|
27
|
+
return await message.clone().text();
|
|
28
|
+
} catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function formatHeaders(headers) {
|
|
33
|
+
return Array.from(headers.entries()).map(([name, value]) => {
|
|
34
|
+
return `${name}: ${value}`;
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
async function formatHttpMessage(startLine, message) {
|
|
38
|
+
const lines = [startLine, ...formatHeaders(message.headers)];
|
|
39
|
+
const body = await readBody(message);
|
|
40
|
+
lines.push("", body ?? "");
|
|
41
|
+
return lines.join("\n");
|
|
42
|
+
}
|
|
43
|
+
async function formatRequest(request) {
|
|
44
|
+
return formatHttpMessage(`${request.method} ${request.url}`, request);
|
|
45
|
+
}
|
|
46
|
+
async function formatResponse(response) {
|
|
47
|
+
const statusText = response.statusText ? ` ${response.statusText}` : "";
|
|
48
|
+
return formatHttpMessage(`HTTP ${response.status}${statusText}`, response);
|
|
49
|
+
}
|
|
50
|
+
function formatLogArguments(arguments_) {
|
|
51
|
+
const message = arguments_[0];
|
|
52
|
+
if (typeof message === "string") {
|
|
53
|
+
const messageWithoutDebugTimestamp = message.replace(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z /, "");
|
|
54
|
+
const timestampMatch = messageWithoutDebugTimestamp.match(LOG_TIMESTAMP_REGEXP);
|
|
55
|
+
if (!timestampMatch || timestampMatch.index === void 0) {
|
|
56
|
+
arguments_[0] = messageWithoutDebugTimestamp;
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
const messagePrefix = messageWithoutDebugTimestamp.slice(0, timestampMatch.index).trim();
|
|
60
|
+
const messageBody = messageWithoutDebugTimestamp.slice(timestampMatch.index + timestampMatch[0].length).trimStart();
|
|
61
|
+
arguments_[0] = `${timestampMatch[0]} ${messagePrefix} ${messageBody}`;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function useConciseTimestamp(logger) {
|
|
65
|
+
logger.log = (...arguments_) => {
|
|
66
|
+
formatLogArguments(arguments_);
|
|
67
|
+
debug.log(...arguments_);
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function isVerboseLoggingEnabled() {
|
|
71
|
+
if (typeof process !== "undefined" && process.env.DEBUG_LEVEL === "verbose") return true;
|
|
72
|
+
/**
|
|
73
|
+
* @note Consult the localStorage only in browser-like environments.
|
|
74
|
+
* In Node.js 26+, reading "globalThis.localStorage" without the
|
|
75
|
+
* "--localstorage-file" flag set emits an experimental warning
|
|
76
|
+
* (a try/catch cannot suppress it). Node.js consumers control the
|
|
77
|
+
* log level via the "DEBUG_LEVEL" environment variable above.
|
|
78
|
+
*/
|
|
79
|
+
if (typeof document === "undefined") return false;
|
|
80
|
+
try {
|
|
81
|
+
return globalThis.localStorage?.getItem("debugLevel") === "verbose";
|
|
82
|
+
} catch {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function createLogger(namespace) {
|
|
87
|
+
const logger = debug(`interceptors:${normalizeNamespace(namespace)}`);
|
|
88
|
+
Reflect.set(logger, "useColors", true);
|
|
89
|
+
useConciseTimestamp(logger);
|
|
90
|
+
return {
|
|
91
|
+
info(message, ...positionals) {
|
|
92
|
+
logger(`${getTimestamp()} ${message}`, ...positionals);
|
|
93
|
+
},
|
|
94
|
+
verbose(message, ...positionals) {
|
|
95
|
+
if (!isVerboseLoggingEnabled()) return;
|
|
96
|
+
logger(`${getTimestamp()} ${message}`, ...positionals);
|
|
97
|
+
},
|
|
98
|
+
isEnabled(level) {
|
|
99
|
+
return logger.enabled && (level === "default" || isVerboseLoggingEnabled());
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region src/interceptor.ts
|
|
105
|
+
const interceptorsRegistry = globalThis.__MSW_INTERCEPTORS_REGISTRY ??= /* @__PURE__ */ new Map();
|
|
106
|
+
var Interceptor = class extends Disposable {
|
|
107
|
+
#owners;
|
|
108
|
+
static singleton(InterceptorClass) {
|
|
109
|
+
const symbol = InterceptorClass.symbol;
|
|
110
|
+
const existing = interceptorsRegistry.get(symbol);
|
|
111
|
+
if (existing instanceof InterceptorClass) return existing;
|
|
112
|
+
const newInstance = new InterceptorClass();
|
|
113
|
+
interceptorsRegistry.set(symbol, newInstance);
|
|
114
|
+
return newInstance;
|
|
115
|
+
}
|
|
116
|
+
constructor() {
|
|
117
|
+
super();
|
|
118
|
+
this.on = (type, listener, options) => {
|
|
119
|
+
return this.emitter.on(type, listener, options);
|
|
120
|
+
};
|
|
121
|
+
this.once = (type, listener, options) => {
|
|
122
|
+
return this.emitter.once(type, listener, options);
|
|
123
|
+
};
|
|
124
|
+
this.listeners = (type) => {
|
|
125
|
+
return this.emitter.listeners(type);
|
|
126
|
+
};
|
|
127
|
+
this.listenerCount = (type) => {
|
|
128
|
+
return this.emitter.listenerCount(type);
|
|
129
|
+
};
|
|
130
|
+
this.removeListener = (type, listener) => {
|
|
131
|
+
return this.emitter.removeListener(type, listener);
|
|
132
|
+
};
|
|
133
|
+
this.removeAllListeners = (type) => {
|
|
134
|
+
this.logger.info("removeAllListeners %o", { eventType: type ?? "*" });
|
|
135
|
+
return this.emitter.removeAllListeners(type);
|
|
136
|
+
};
|
|
137
|
+
this.#owners = /* @__PURE__ */ new Set();
|
|
138
|
+
this.readyState = "INACTIVE";
|
|
139
|
+
this.emitter = new Emitter();
|
|
140
|
+
this.logger = createLogger(this.#getLoggerNamespace());
|
|
141
|
+
}
|
|
142
|
+
apply(owner = this) {
|
|
143
|
+
if (this.#owners.has(owner)) return;
|
|
144
|
+
if (this.readyState !== "ACTIVE" && !this.predicate()) return;
|
|
145
|
+
this.#owners.add(owner);
|
|
146
|
+
if (this.readyState === "ACTIVE") return;
|
|
147
|
+
try {
|
|
148
|
+
this.setup();
|
|
149
|
+
this.readyState = "ACTIVE";
|
|
150
|
+
this.logger.info("apply");
|
|
151
|
+
} catch (error) {
|
|
152
|
+
this.dispose(owner);
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
dispose(owner = this) {
|
|
157
|
+
if (!this.#owners.delete(owner)) return;
|
|
158
|
+
if (this.#owners.size > 0) return;
|
|
159
|
+
super.dispose();
|
|
160
|
+
this.emitter.removeAllListeners();
|
|
161
|
+
this.readyState = "DISPOSED";
|
|
162
|
+
this.logger.info("disable");
|
|
163
|
+
}
|
|
164
|
+
#getLoggerNamespace() {
|
|
165
|
+
const symbolDescription = this.constructor.symbol?.description;
|
|
166
|
+
if (symbolDescription) return symbolDescription.replace(/-interceptor$/, "");
|
|
167
|
+
return this.constructor.name.replace(/Interceptor$/, "");
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
//#endregion
|
|
171
|
+
//#region src/create-request-id.ts
|
|
172
|
+
/**
|
|
173
|
+
* Generate a random ID string to represent a request.
|
|
174
|
+
* @example
|
|
175
|
+
* createRequestId()
|
|
176
|
+
* // "f774b6c9c600f"
|
|
177
|
+
*/
|
|
178
|
+
function createRequestId() {
|
|
179
|
+
return Math.random().toString(16).slice(2);
|
|
180
|
+
}
|
|
181
|
+
//#endregion
|
|
182
|
+
export { formatResponse as a, formatRequest as i, Interceptor as n, createLogger as r, createRequestId as t };
|
|
183
|
+
|
|
184
|
+
//# sourceMappingURL=create-request-id-DlEd4GOA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create-request-id-DlEd4GOA.js","names":["#owners","#getLoggerNamespace"],"sources":["../../src/disposable.ts","../../src/utils/logger.ts","../../src/interceptor.ts","../../src/create-request-id.ts"],"sourcesContent":["export type DisposableSubscription = () => void\n\nexport class Disposable {\n protected subscriptions: Array<DisposableSubscription> = []\n\n public dispose() {\n let subscription: DisposableSubscription | undefined\n\n while ((subscription = this.subscriptions.pop())) {\n subscription()\n }\n }\n}\n","import debug from 'debug'\n\nexport type LogLevel = 'default' | 'verbose'\n\nexport interface Logger {\n info(message: string, ...positionals: Array<unknown>): void\n verbose(message: string, ...positionals: Array<unknown>): void\n isEnabled(level: LogLevel): boolean\n}\n\nconst LOG_TIMESTAMP_REGEXP = /\\d{2}:\\d{2}:\\d{2}\\.\\d{3}/\n\nfunction normalizeNamespace(namespace: string): string {\n return namespace\n .split(':')\n .map((segment) => {\n return segment\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/[^a-zA-Z0-9]+/g, '-')\n .replace(/^-|-$/g, '')\n .toLowerCase()\n })\n .filter(Boolean)\n .join(':')\n}\n\nfunction getTimestamp(): string {\n return new Date().toISOString().slice(11, 23)\n}\n\nasync function readBody(message: Request | Response): Promise<string | null> {\n if (message.body == null) {\n return null\n }\n\n try {\n return await message.clone().text()\n } catch {\n return null\n }\n}\n\nfunction formatHeaders(headers: Headers): Array<string> {\n return Array.from(headers.entries()).map(([name, value]) => {\n return `${name}: ${value}`\n })\n}\n\nasync function formatHttpMessage(\n startLine: string,\n message: Request | Response\n): Promise<string> {\n const lines = [startLine, ...formatHeaders(message.headers)]\n const body = await readBody(message)\n\n lines.push('', body ?? '')\n\n return lines.join('\\n')\n}\n\nexport async function formatRequest(request: Request): Promise<string> {\n return formatHttpMessage(`${request.method} ${request.url}`, request)\n}\n\nexport async function formatResponse(response: Response): Promise<string> {\n const statusText = response.statusText ? ` ${response.statusText}` : ''\n return formatHttpMessage(\n `HTTP ${response.status}${statusText}`,\n response\n )\n}\n\nfunction formatLogArguments(arguments_: Array<unknown>): void {\n const message = arguments_[0]\n\n if (typeof message === 'string') {\n const messageWithoutDebugTimestamp = message.replace(\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z /,\n ''\n )\n const timestampMatch = messageWithoutDebugTimestamp.match(\n LOG_TIMESTAMP_REGEXP\n )\n\n if (!timestampMatch || timestampMatch.index === undefined) {\n arguments_[0] = messageWithoutDebugTimestamp\n return\n }\n\n const messagePrefix = messageWithoutDebugTimestamp\n .slice(0, timestampMatch.index)\n .trim()\n const messageBody = messageWithoutDebugTimestamp\n .slice(timestampMatch.index + timestampMatch[0].length)\n .trimStart()\n\n arguments_[0] = `${timestampMatch[0]} ${messagePrefix} ${messageBody}`\n }\n}\n\nfunction useConciseTimestamp(logger: debug.Debugger): void {\n logger.log = (...arguments_) => {\n formatLogArguments(arguments_)\n debug.log(...arguments_)\n }\n}\n\nfunction isVerboseLoggingEnabled(): boolean {\n if (typeof process !== 'undefined' && process.env.DEBUG_LEVEL === 'verbose') {\n return true\n }\n\n /**\n * @note Consult the localStorage only in browser-like environments.\n * In Node.js 26+, reading \"globalThis.localStorage\" without the\n * \"--localstorage-file\" flag set emits an experimental warning\n * (a try/catch cannot suppress it). Node.js consumers control the\n * log level via the \"DEBUG_LEVEL\" environment variable above.\n */\n if (typeof document === 'undefined') {\n return false\n }\n\n try {\n return globalThis.localStorage?.getItem('debugLevel') === 'verbose'\n } catch {\n return false\n }\n}\n\nexport function createLogger(namespace: string): Logger {\n const normalizedNamespace = normalizeNamespace(namespace)\n const logger = debug(`interceptors:${normalizedNamespace}`)\n Reflect.set(logger, 'useColors', true)\n useConciseTimestamp(logger)\n\n return {\n info(message, ...positionals) {\n logger(`${getTimestamp()} ${message}`, ...positionals)\n },\n verbose(message, ...positionals) {\n if (!isVerboseLoggingEnabled()) {\n return\n }\n\n logger(`${getTimestamp()} ${message}`, ...positionals)\n },\n isEnabled(level) {\n return (\n logger.enabled && (level === 'default' || isVerboseLoggingEnabled())\n )\n },\n }\n}\n","import { Emitter, type DefaultEventMap } from 'rettime'\nimport { Disposable } from './disposable'\nimport { createLogger, type Logger } from './utils/logger'\n\nexport enum InterceptorReadyState {\n INACTIVE = 'INACTIVE',\n ACTIVE = 'ACTIVE',\n DISPOSED = 'DISPOSED',\n}\n\ndeclare global {\n var __MSW_INTERCEPTORS_REGISTRY: Map<symbol, Interceptor<any>> | undefined\n}\n\nconst interceptorsRegistry = (globalThis.__MSW_INTERCEPTORS_REGISTRY ??=\n new Map<symbol, Interceptor<any>>())\n\nexport abstract class Interceptor<\n Events extends DefaultEventMap,\n> extends Disposable {\n declare ['constructor']: typeof Interceptor\n\n protected emitter: Emitter<Events>\n protected readonly logger: Logger\n\n public readyState: InterceptorReadyState\n\n static readonly symbol: symbol\n\n #owners: Set<object>\n\n static singleton<T extends Interceptor<any>>(\n InterceptorClass: (new () => T) & { symbol: symbol }\n ): T {\n const symbol = InterceptorClass.symbol\n const existing = interceptorsRegistry.get(symbol)\n\n if (existing instanceof InterceptorClass) {\n return existing\n }\n\n const newInstance = new InterceptorClass()\n interceptorsRegistry.set(symbol, newInstance)\n return newInstance\n }\n\n constructor() {\n super()\n\n this.#owners = new Set()\n this.readyState = InterceptorReadyState.INACTIVE\n this.emitter = new Emitter()\n this.logger = createLogger(this.#getLoggerNamespace())\n }\n\n protected abstract predicate(): boolean\n protected abstract setup(): void\n\n public apply(owner: object = this): void {\n if (this.#owners.has(owner)) {\n return\n }\n\n if (\n this.readyState !== InterceptorReadyState.ACTIVE &&\n !this.predicate()\n ) {\n return\n }\n\n this.#owners.add(owner)\n\n if (this.readyState === InterceptorReadyState.ACTIVE) {\n return\n }\n\n try {\n this.setup()\n this.readyState = InterceptorReadyState.ACTIVE\n this.logger.info('apply')\n } catch (error) {\n this.dispose(owner)\n throw error\n }\n }\n\n public dispose(owner: object = this): void {\n if (!this.#owners.delete(owner)) {\n return\n }\n\n if (this.#owners.size > 0) {\n return\n }\n\n super.dispose()\n this.emitter.removeAllListeners()\n this.readyState = InterceptorReadyState.DISPOSED\n this.logger.info('disable')\n }\n\n public on: Emitter<Events>['on'] = (type, listener, options) => {\n return this.emitter.on(type, listener, options)\n }\n\n public once: Emitter<Events>['once'] = (type, listener, options) => {\n return this.emitter.once(type, listener, options)\n }\n\n public listeners: Emitter<Events>['listeners'] = (type) => {\n return this.emitter.listeners(type)\n }\n\n public listenerCount: Emitter<Events>['listenerCount'] = (type) => {\n return this.emitter.listenerCount(type)\n }\n\n public removeListener: Emitter<Events>['removeListener'] = (\n type,\n listener\n ) => {\n return this.emitter.removeListener(type, listener)\n }\n\n public removeAllListeners: Emitter<Events>['removeAllListeners'] = (type) => {\n this.logger.info('removeAllListeners %o', { eventType: type ?? '*' })\n return this.emitter.removeAllListeners(type)\n }\n\n #getLoggerNamespace(): string {\n const symbolDescription = this.constructor.symbol?.description\n\n if (symbolDescription) {\n return symbolDescription.replace(/-interceptor$/, '')\n }\n\n return this.constructor.name.replace(/Interceptor$/, '')\n }\n}\n","/**\n * Generate a random ID string to represent a request.\n * @example\n * createRequestId()\n * // \"f774b6c9c600f\"\n */\nexport function createRequestId(): string {\n return Math.random().toString(16).slice(2)\n}\n"],"mappings":";;;AAEA,IAAa,aAAb,MAAwB;;EACmC,KAAA,gBAAA,CAAC;;CAE1D,UAAiB;EACf,IAAI;EAEJ,OAAQ,eAAe,KAAK,cAAc,IAAI,GAC5C,aAAa;CAEjB;AACF;;;ACFA,MAAM,uBAAuB;AAE7B,SAAS,mBAAmB,WAA2B;CACrD,OAAO,UACJ,MAAM,GAAG,CAAC,CACV,KAAK,YAAY;EAChB,OAAO,QACJ,QAAQ,sBAAsB,OAAO,CAAC,CACtC,QAA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AAK,QAAQ,mBAAmB;EAChC,KAAK,aAAA;EACL,KAAK,OAAO,KAAK,SAAS;CAC5B;CA8BA,sBAA8B;EAC5B,MAAM,oBAAoB,KAAK,YAAY,QAAQ;EAEnD,IAAI,mBACF,OAAO,kBAAkB,QAAQ,iBAAiB,EAAE;EAGtD,OAAO,KAAK,YAAY,KAAK,QAAQ,gBAAgB,EAAE;CACzD;AACF;;;;;;;;;ACpIA,SAAgB,kBAA0B;CACxC,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC;AAC3C"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as formatResponse } from "./create-request-id-DlEd4GOA.js";
|
|
2
2
|
import { invariant } from "outvariant";
|
|
3
|
-
|
|
4
|
-
//#region src/InterceptorError.ts
|
|
3
|
+
//#region src/interceptor-error.ts
|
|
5
4
|
var InterceptorError = class InterceptorError extends Error {
|
|
6
5
|
constructor(message) {
|
|
7
6
|
super(message);
|
|
@@ -9,9 +8,8 @@ var InterceptorError = class InterceptorError extends Error {
|
|
|
9
8
|
Object.setPrototypeOf(this, InterceptorError.prototype);
|
|
10
9
|
}
|
|
11
10
|
};
|
|
12
|
-
|
|
13
11
|
//#endregion
|
|
14
|
-
//#region src/
|
|
12
|
+
//#region src/request-controller.ts
|
|
15
13
|
var RequestController = class RequestController {
|
|
16
14
|
static {
|
|
17
15
|
this.PENDING = 0;
|
|
@@ -25,14 +23,14 @@ var RequestController = class RequestController {
|
|
|
25
23
|
static {
|
|
26
24
|
this.ERROR = 3;
|
|
27
25
|
}
|
|
28
|
-
|
|
26
|
+
#handled;
|
|
27
|
+
constructor(request, source, options) {
|
|
29
28
|
this.request = request;
|
|
30
29
|
this.source = source;
|
|
30
|
+
this.options = options;
|
|
31
31
|
this.readyState = RequestController.PENDING;
|
|
32
|
-
this
|
|
33
|
-
|
|
34
|
-
get #handled() {
|
|
35
|
-
return this.handled;
|
|
32
|
+
this.#handled = Promise.withResolvers();
|
|
33
|
+
this.handled = this.#handled.promise;
|
|
36
34
|
}
|
|
37
35
|
/**
|
|
38
36
|
* Perform this request as-is.
|
|
@@ -40,6 +38,7 @@ var RequestController = class RequestController {
|
|
|
40
38
|
async passthrough() {
|
|
41
39
|
invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to passthrough the \"%s %s\" request: the request has already been handled", this.request.method, this.request.url);
|
|
42
40
|
this.readyState = RequestController.PASSTHROUGH;
|
|
41
|
+
if (this.options) this.options.logger.info("[%s] passthrough", this.options.requestId);
|
|
43
42
|
await this.source.passthrough();
|
|
44
43
|
this.#handled.resolve();
|
|
45
44
|
}
|
|
@@ -54,6 +53,12 @@ var RequestController = class RequestController {
|
|
|
54
53
|
respondWith(response) {
|
|
55
54
|
invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to respond to the \"%s %s\" request with \"%d %s\": the request has already been handled (%d)", this.request.method, this.request.url, response.status, response.statusText || "OK", this.readyState);
|
|
56
55
|
this.readyState = RequestController.RESPONSE;
|
|
56
|
+
if (this.options?.logger.isEnabled("default")) {
|
|
57
|
+
const { logger, requestId } = this.options;
|
|
58
|
+
formatResponse(response).then((message) => {
|
|
59
|
+
logger.info("[%s] mocked %s", requestId, message);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
57
62
|
this.#handled.resolve();
|
|
58
63
|
/**
|
|
59
64
|
* @note Although `source.respondWith()` is potentially asynchronous,
|
|
@@ -74,41 +79,115 @@ var RequestController = class RequestController {
|
|
|
74
79
|
errorWith(reason) {
|
|
75
80
|
invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to error the \"%s %s\" request with \"%s\": the request has already been handled (%d)", this.request.method, this.request.url, reason?.toString(), this.readyState);
|
|
76
81
|
this.readyState = RequestController.ERROR;
|
|
82
|
+
if (this.options) this.options.logger.info("[%s] error %o", this.options.requestId, reason);
|
|
77
83
|
this.source.errorWith(reason);
|
|
78
84
|
this.#handled.resolve();
|
|
79
85
|
}
|
|
80
86
|
};
|
|
81
|
-
|
|
82
87
|
//#endregion
|
|
83
|
-
//#region src/utils/
|
|
88
|
+
//#region src/interceptors/ClientRequest/utils/record-raw-headers.ts
|
|
89
|
+
const kRawHeaders = Symbol("kRawHeaders");
|
|
90
|
+
/**
|
|
91
|
+
* Define the raw headers symbol on the given `Headers` instance.
|
|
92
|
+
* If the symbol already exists, it gets overridden.
|
|
93
|
+
*/
|
|
94
|
+
function defineRawHeadersSymbol(headers, rawHeaders) {
|
|
95
|
+
Object.defineProperty(headers, kRawHeaders, {
|
|
96
|
+
value: rawHeaders,
|
|
97
|
+
enumerable: false,
|
|
98
|
+
configurable: true
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
function getRawFetchHeaders(headers) {
|
|
102
|
+
if (!Reflect.has(headers, kRawHeaders)) return Array.from(headers.entries());
|
|
103
|
+
const rawHeaders = Reflect.get(headers, kRawHeaders);
|
|
104
|
+
return rawHeaders.length > 0 ? rawHeaders : Array.from(headers.entries());
|
|
105
|
+
}
|
|
106
|
+
function copyRawHeaders(source, destination) {
|
|
107
|
+
const rawHeaders = [...getRawFetchHeaders(source)];
|
|
108
|
+
if (rawHeaders.length === 0) return;
|
|
109
|
+
/**
|
|
110
|
+
* @note Add headers from trhe destination that raw headers from the source
|
|
111
|
+
* don't have. Undici automatically appends a "Content-Type" header for responses
|
|
112
|
+
* and, for some reason, that change is not recorded. This preserves it.
|
|
113
|
+
*/
|
|
114
|
+
for (const [name, value] of destination) if (rawHeaders.every((header) => header[0].toLowerCase() !== name.toLowerCase())) rawHeaders.push([name, value]);
|
|
115
|
+
defineRawHeadersSymbol(destination, rawHeaders);
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
//#region src/utils/get-value-by-symbol.ts
|
|
119
|
+
/**
|
|
120
|
+
* Returns the value behind the symbol with the given name.
|
|
121
|
+
*/
|
|
122
|
+
function getValueBySymbol(symbolName, source) {
|
|
123
|
+
const symbol = Object.getOwnPropertySymbols(source).find((symbol) => {
|
|
124
|
+
return symbol.description === symbolName;
|
|
125
|
+
});
|
|
126
|
+
if (symbol) return Reflect.get(source, symbol);
|
|
127
|
+
}
|
|
128
|
+
//#endregion
|
|
129
|
+
//#region src/utils/is-object.ts
|
|
130
|
+
/**
|
|
131
|
+
* Determines if a given value is an instance of object.
|
|
132
|
+
*/
|
|
133
|
+
function isObject(value, loose = false) {
|
|
134
|
+
return loose ? Object.prototype.toString.call(value).startsWith("[object ") : Object.prototype.toString.call(value) === "[object Object]";
|
|
135
|
+
}
|
|
136
|
+
//#endregion
|
|
137
|
+
//#region src/utils/is-property-accessible.ts
|
|
84
138
|
/**
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
139
|
+
* A function that validates if property access is possible on an object
|
|
140
|
+
* without throwing. It returns `true` if the property access is possible
|
|
141
|
+
* and `false` otherwise.
|
|
142
|
+
*
|
|
143
|
+
* Environments like miniflare will throw on property access on certain objects
|
|
144
|
+
* like Request and Response, for unimplemented properties.
|
|
88
145
|
*/
|
|
89
|
-
function
|
|
146
|
+
function isPropertyAccessible(obj, key) {
|
|
90
147
|
try {
|
|
91
|
-
|
|
148
|
+
obj[key];
|
|
92
149
|
return true;
|
|
93
|
-
} catch
|
|
150
|
+
} catch {
|
|
94
151
|
return false;
|
|
95
152
|
}
|
|
96
153
|
}
|
|
97
|
-
|
|
98
154
|
//#endregion
|
|
99
|
-
//#region src/utils/
|
|
155
|
+
//#region src/utils/response-utils.ts
|
|
100
156
|
/**
|
|
101
|
-
*
|
|
157
|
+
* Creates a generic 500 Unhandled Exception response.
|
|
102
158
|
*/
|
|
103
|
-
function
|
|
104
|
-
|
|
105
|
-
|
|
159
|
+
function createServerErrorResponse(body) {
|
|
160
|
+
return new Response(JSON.stringify(body instanceof Error ? {
|
|
161
|
+
name: body.name,
|
|
162
|
+
message: body.message,
|
|
163
|
+
stack: body.stack
|
|
164
|
+
} : body), {
|
|
165
|
+
status: 500,
|
|
166
|
+
statusText: "Unhandled Exception",
|
|
167
|
+
headers: { "Content-Type": "application/json" }
|
|
106
168
|
});
|
|
107
|
-
if (symbol) return Reflect.get(source, symbol);
|
|
108
169
|
}
|
|
109
|
-
|
|
170
|
+
/**
|
|
171
|
+
* Check if the given response is a `Response.error()`.
|
|
172
|
+
*
|
|
173
|
+
* @note Some environments, like Miniflare (Cloudflare) do not
|
|
174
|
+
* implement the "Response.type" property and throw on its access.
|
|
175
|
+
* Safely check if we can access "type" on "Response" before continuing.
|
|
176
|
+
* @see https://github.com/mswjs/msw/issues/1834
|
|
177
|
+
*/
|
|
178
|
+
function isResponseError(response) {
|
|
179
|
+
return response != null && response instanceof Response && isPropertyAccessible(response, "type") && response.type === "error";
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Check if the given value is a `Response` or a Response-like object.
|
|
183
|
+
* This is different from `value instanceof Response` because it supports
|
|
184
|
+
* custom `Response` constructors, like the one when using Undici directly.
|
|
185
|
+
*/
|
|
186
|
+
function isResponseLike(value) {
|
|
187
|
+
return isObject(value, true) && isPropertyAccessible(value, "status") && isPropertyAccessible(value, "statusText") && isPropertyAccessible(value, "bodyUsed");
|
|
188
|
+
}
|
|
110
189
|
//#endregion
|
|
111
|
-
//#region src/utils/
|
|
190
|
+
//#region src/utils/fetch-utils.ts
|
|
112
191
|
var FetchRequest = class FetchRequest extends Request {
|
|
113
192
|
static #resolveProperty(input, init = {}, key) {
|
|
114
193
|
return init[key] ?? (input instanceof Request ? input[key] : void 0);
|
|
@@ -188,6 +267,18 @@ var FetchRequest = class FetchRequest extends Request {
|
|
|
188
267
|
const kStatus = Symbol("kStatus");
|
|
189
268
|
const kUrl = Symbol("kUrl");
|
|
190
269
|
var FetchResponse = class FetchResponse extends Response {
|
|
270
|
+
static from(response, init) {
|
|
271
|
+
if (response instanceof FetchResponse) return response;
|
|
272
|
+
if (isResponseError(response)) return response;
|
|
273
|
+
const fetchResponse = new FetchResponse(response.body, {
|
|
274
|
+
url: init?.url ?? response.url,
|
|
275
|
+
status: init?.status || response.status,
|
|
276
|
+
statusText: init?.statusText ?? response.statusText,
|
|
277
|
+
headers: init?.headers ?? response.headers
|
|
278
|
+
});
|
|
279
|
+
copyRawHeaders(response.headers, fetchResponse.headers);
|
|
280
|
+
return fetchResponse;
|
|
281
|
+
}
|
|
191
282
|
static {
|
|
192
283
|
this.STATUS_CODES_WITHOUT_BODY = [
|
|
193
284
|
101,
|
|
@@ -238,7 +329,7 @@ var FetchResponse = class FetchResponse extends Response {
|
|
|
238
329
|
});
|
|
239
330
|
}
|
|
240
331
|
static setUrl(url, response) {
|
|
241
|
-
if (!url || url === "about:" || !
|
|
332
|
+
if (!url || url === "about:" || !URL.canParse(url)) return;
|
|
242
333
|
const state = getValueBySymbol("state", response);
|
|
243
334
|
if (state) state.urlList.push(new URL(url));
|
|
244
335
|
else Object.defineProperty(response, "url", {
|
|
@@ -281,6 +372,8 @@ var FetchResponse = class FetchResponse extends Response {
|
|
|
281
372
|
});
|
|
282
373
|
}
|
|
283
374
|
}
|
|
375
|
+
#status;
|
|
376
|
+
#url;
|
|
284
377
|
constructor(body, init = {}) {
|
|
285
378
|
const status = init.status ?? 200;
|
|
286
379
|
const safeStatus = FetchResponse.isConfigurableStatusCode(status) ? status : 200;
|
|
@@ -307,29 +400,7 @@ var FetchResponse = class FetchResponse extends Response {
|
|
|
307
400
|
return clonedResponse;
|
|
308
401
|
}
|
|
309
402
|
};
|
|
310
|
-
|
|
311
403
|
//#endregion
|
|
312
|
-
|
|
313
|
-
const kRawRequest = Symbol("kRawRequest");
|
|
314
|
-
/**
|
|
315
|
-
* Returns a raw request instance associated with this request.
|
|
316
|
-
*
|
|
317
|
-
* @example
|
|
318
|
-
* interceptor.on('request', ({ request }) => {
|
|
319
|
-
* const rawRequest = getRawRequest(request)
|
|
320
|
-
*
|
|
321
|
-
* if (rawRequest instanceof http.ClientRequest) {
|
|
322
|
-
* console.log(rawRequest.rawHeaders)
|
|
323
|
-
* }
|
|
324
|
-
* })
|
|
325
|
-
*/
|
|
326
|
-
function getRawRequest(request) {
|
|
327
|
-
return Reflect.get(request, kRawRequest);
|
|
328
|
-
}
|
|
329
|
-
function setRawRequest(request, rawRequest) {
|
|
330
|
-
Reflect.set(request, kRawRequest, rawRequest);
|
|
331
|
-
}
|
|
404
|
+
export { isResponseLike as a, RequestController as c, isResponseError as i, InterceptorError as l, FetchResponse as n, isObject as o, createServerErrorResponse as r, copyRawHeaders as s, FetchRequest as t };
|
|
332
405
|
|
|
333
|
-
//#
|
|
334
|
-
export { canParseUrl as a, FetchResponse as i, setRawRequest as n, RequestController as o, FetchRequest as r, InterceptorError as s, getRawRequest as t };
|
|
335
|
-
//# sourceMappingURL=getRawRequest-B1BqgWG6.mjs.map
|
|
406
|
+
//# sourceMappingURL=fetch-utils-zxA_SD66.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch-utils-zxA_SD66.js","names":["#handled","#resolveProperty","#setInternalProperty"],"sources":["../../src/interceptor-error.ts","../../src/request-controller.ts","../../src/interceptors/ClientRequest/utils/record-raw-headers.ts","../../src/utils/get-value-by-symbol.ts","../../src/utils/is-object.ts","../../src/utils/is-property-accessible.ts","../../src/utils/response-utils.ts","../../src/utils/fetch-utils.ts"],"sourcesContent":["export class InterceptorError extends Error {\n constructor(message?: string) {\n super(message)\n this.name = 'InterceptorError'\n Object.setPrototypeOf(this, InterceptorError.prototype)\n }\n}\n","import { invariant } from 'outvariant'\nimport { InterceptorError } from './interceptor-error'\nimport { formatResponse, type Logger } from './utils/logger'\n\nexport interface RequestControllerSource {\n passthrough(): void | Promise<void>\n respondWith(response: Response): void | Promise<void>\n errorWith(reason?: unknown): void | Promise<void>\n}\n\ninterface RequestControllerOptions {\n logger: Logger\n requestId: string\n}\n\nexport class RequestController {\n static PENDING = 0 as const\n static PASSTHROUGH = 1 as const\n static RESPONSE = 2 as const\n static ERROR = 3 as const\n\n public readyState: number\n\n /**\n * A Promise that resolves when this controller handles a request.\n * See `controller.readyState` for more information on the handling result.\n */\n public handled: Promise<void>\n\n readonly #handled: PromiseWithResolvers<void>\n\n constructor(\n protected readonly request: Request,\n protected readonly source: RequestControllerSource,\n protected readonly options?: RequestControllerOptions\n ) {\n this.readyState = RequestController.PENDING\n this.#handled = Promise.withResolvers<void>()\n this.handled = this.#handled.promise\n }\n\n /**\n * Perform this request as-is.\n */\n public async passthrough(): Promise<void> {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to passthrough the \"%s %s\" request: the request has already been handled',\n this.request.method,\n this.request.url\n )\n\n this.readyState = RequestController.PASSTHROUGH\n if (this.options) {\n this.options.logger.info('[%s] passthrough', this.options.requestId)\n }\n await this.source.passthrough()\n this.#handled.resolve()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n *\n * @example\n * controller.respondWith(new Response())\n * controller.respondWith(Response.json({ id }))\n * controller.respondWith(Response.error())\n */\n public respondWith(response: Response): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to respond to the \"%s %s\" request with \"%d %s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n response.status,\n response.statusText || 'OK',\n this.readyState\n )\n\n this.readyState = RequestController.RESPONSE\n if (this.options?.logger.isEnabled('default')) {\n const { logger, requestId } = this.options\n\n void formatResponse(response).then((message) => {\n logger.info('[%s] mocked %s', requestId, message)\n })\n }\n this.#handled.resolve()\n\n /**\n * @note Although `source.respondWith()` is potentially asynchronous,\n * do NOT await it for backward-compatibility. Awaiting it will short-circuit\n * the request listener invocation as soon as a listener responds to a request.\n * Ideally, that's what we want, but that's not what we promise the user.\n */\n this.source.respondWith(response)\n }\n\n /**\n * Error this request with the given reason.\n *\n * @example\n * controller.errorWith()\n * controller.errorWith(new Error('Oops!'))\n * controller.errorWith({ message: 'Oops!'})\n */\n public errorWith(reason?: unknown): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to error the \"%s %s\" request with \"%s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n reason?.toString(),\n this.readyState\n )\n\n this.readyState = RequestController.ERROR\n if (this.options) {\n this.options.logger.info(\n '[%s] error %o',\n this.options.requestId,\n reason\n )\n }\n this.source.errorWith(reason)\n this.#handled.resolve()\n }\n}\n","import { FetchRequest, FetchResponse } from '../../../utils/fetch-utils'\n\ntype HeaderTuple = [string, string]\ntype RawHeaders = Array<HeaderTuple>\ntype SetHeaderBehavior = 'set' | 'append'\n\nconst kRawHeaders = Symbol('kRawHeaders')\nconst kRestorePatches = Symbol('kRestorePatches')\n\nfunction recordRawHeader(\n headers: Headers,\n args: HeaderTuple,\n behavior: SetHeaderBehavior\n) {\n ensureRawHeadersSymbol(headers, [])\n const rawHeaders = Reflect.get(headers, kRawHeaders) as RawHeaders\n\n if (behavior === 'set') {\n // When recording a set header, ensure we remove any matching existing headers.\n for (let index = rawHeaders.length - 1; index >= 0; index--) {\n if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) {\n rawHeaders.splice(index, 1)\n }\n }\n }\n\n rawHeaders.push(args)\n}\n\n/**\n * Define the raw headers symbol on the given `Headers` instance.\n * If the symbol already exists, this function does nothing.\n */\nfunction ensureRawHeadersSymbol(\n headers: Headers,\n rawHeaders: RawHeaders\n): void {\n if (Reflect.has(headers, kRawHeaders)) {\n return\n }\n\n defineRawHeadersSymbol(headers, rawHeaders)\n}\n\n/**\n * Define the raw headers symbol on the given `Headers` instance.\n * If the symbol already exists, it gets overridden.\n */\nfunction defineRawHeadersSymbol(headers: Headers, rawHeaders: RawHeaders) {\n Object.defineProperty(headers, kRawHeaders, {\n value: rawHeaders,\n enumerable: false,\n // Mark the symbol as configurable so its value can be overridden.\n // Overrides happen when merging raw headers from multiple sources.\n // E.g. new Request(new Request(url, { headers }), { headers })\n configurable: true,\n })\n}\n\n/**\n * Patch the global `Headers` class to store raw headers.\n * This is for compatibility with `IncomingMessage.prototype.rawHeaders`.\n *\n * @note Node.js has their own raw headers symbol but it\n * only records the first header name in case of multi-value headers.\n * Any other headers are normalized before comparing. This makes it\n * incompatible with the `rawHeaders` format.\n *\n * let h = new Headers()\n * h.append('X-Custom', 'one')\n * h.append('x-custom', 'two')\n * h[Symbol('headers map')] // Map { 'X-Custom' => 'one, two' }\n */\nexport function recordRawFetchHeaders(): () => void {\n // Prevent patching the Headers prototype multiple times.\n if (Reflect.get(Headers, kRestorePatches)) {\n return Reflect.get(Headers, kRestorePatches)\n }\n\n const {\n Headers: OriginalHeaders,\n Request: OriginalRequest,\n Response: OriginalResponse,\n } = globalThis\n const { set, append, delete: headersDeleteMethod } = Headers.prototype\n\n Object.defineProperty(Headers, kRestorePatches, {\n value: () => {\n Headers.prototype.set = set\n Headers.prototype.append = append\n Headers.prototype.delete = headersDeleteMethod\n globalThis.Headers = OriginalHeaders\n\n globalThis.Request = OriginalRequest\n globalThis.Response = OriginalResponse\n\n Object.setPrototypeOf(FetchRequest, OriginalRequest)\n Object.setPrototypeOf(FetchRequest.prototype, OriginalRequest.prototype)\n Object.setPrototypeOf(FetchResponse, OriginalResponse)\n Object.setPrototypeOf(FetchResponse.prototype, OriginalResponse.prototype)\n\n Reflect.deleteProperty(Headers, kRestorePatches)\n },\n enumerable: false,\n /**\n * @note Mark this property as configurable\n * so we can delete it using `Reflect.delete` during cleanup.\n */\n configurable: true,\n })\n\n Object.defineProperty(globalThis, 'Headers', {\n enumerable: true,\n writable: true,\n value: new Proxy(Headers, {\n construct(target, args, newTarget) {\n const headersInit = args[0] || []\n\n if (\n headersInit instanceof Headers &&\n Reflect.has(headersInit, kRawHeaders)\n ) {\n // Ensure each header tuple has exactly 2 elements (name, value).\n // Node.js 24+ may have stored tuples with extra internal arguments.\n const rawHeadersFromInit = Reflect.get(\n headersInit,\n kRawHeaders\n ) as RawHeaders\n const sanitizedHeaders = rawHeadersFromInit.map(\n (tuple): HeaderTuple => [tuple[0], tuple[1]]\n )\n const headers = Reflect.construct(\n target,\n [sanitizedHeaders],\n newTarget\n )\n ensureRawHeadersSymbol(headers, [\n /**\n * @note Spread the retrieved headers to clone them.\n * This prevents multiple Headers instances from pointing\n * at the same internal \"rawHeaders\" array.\n */\n ...sanitizedHeaders,\n ])\n return headers\n }\n\n const headers = Reflect.construct(target, args, newTarget)\n\n // Request/Response constructors will set the symbol\n // upon creating a new instance, using the raw developer\n // input as the raw headers. Skip the symbol altogether\n // in those cases because the input to Headers will be normalized.\n if (!Reflect.has(headers, kRawHeaders)) {\n const rawHeadersInit = Array.isArray(headersInit)\n ? headersInit\n : Object.entries(headersInit)\n ensureRawHeadersSymbol(headers, rawHeadersInit)\n }\n\n return headers\n },\n }),\n })\n\n Headers.prototype.set = new Proxy(Headers.prototype.set, {\n apply(target, thisArg, args: HeaderTuple) {\n // Use only the first two arguments (name, value) to record raw headers.\n // Node.js 24+ may pass additional internal arguments that should not\n // be included in the raw headers array.\n recordRawHeader(thisArg, [args[0], args[1]], 'set')\n return Reflect.apply(target, thisArg, args)\n },\n })\n\n Headers.prototype.append = new Proxy(Headers.prototype.append, {\n apply(target, thisArg, args: HeaderTuple) {\n // Use only the first two arguments (name, value) to record raw headers.\n // Node.js 24+ may pass additional internal arguments that should not\n // be included in the raw headers array.\n recordRawHeader(thisArg, [args[0], args[1]], 'append')\n return Reflect.apply(target, thisArg, args)\n },\n })\n\n Headers.prototype.delete = new Proxy(Headers.prototype.delete, {\n apply(target, thisArg, args: [string]) {\n const rawHeaders = Reflect.get(thisArg, kRawHeaders) as RawHeaders\n\n if (rawHeaders) {\n for (let index = rawHeaders.length - 1; index >= 0; index--) {\n if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) {\n rawHeaders.splice(index, 1)\n }\n }\n }\n\n return Reflect.apply(target, thisArg, args)\n },\n })\n\n Object.defineProperty(globalThis, 'Request', {\n enumerable: true,\n writable: true,\n value: new Proxy(Request, {\n construct(target, args, newTarget) {\n const request = Reflect.construct(target, args, newTarget)\n const inferredRawHeaders: RawHeaders = []\n\n // Infer raw headers from a `Request` instance used as init.\n if (typeof args[0] === 'object' && args[0].headers != null) {\n inferredRawHeaders.push(...inferRawHeaders(args[0].headers))\n }\n\n // Infer raw headers from the \"headers\" init argument.\n if (typeof args[1] === 'object' && args[1].headers != null) {\n inferredRawHeaders.push(...inferRawHeaders(args[1].headers))\n }\n\n if (inferredRawHeaders.length > 0) {\n ensureRawHeadersSymbol(request.headers, inferredRawHeaders)\n }\n\n return request\n },\n }),\n })\n\n Object.defineProperty(globalThis, 'Response', {\n enumerable: true,\n writable: true,\n value: new Proxy(Response, {\n construct(target, args, newTarget) {\n const response = Reflect.construct(target, args, newTarget)\n\n if (typeof args[1] === 'object' && args[1].headers != null) {\n ensureRawHeadersSymbol(\n response.headers,\n inferRawHeaders(args[1].headers)\n )\n }\n\n return response\n },\n }),\n })\n\n /**\n * Re-parent FetchRequest/FetchResponse so their `super()` calls go\n * through the proxied globalThis.Request/Response above. Without this,\n * FetchRequest extends the statically-captured (original) Request,\n * bypassing the construct proxy that records raw headers.\n */\n Object.setPrototypeOf(FetchRequest, globalThis.Request)\n Object.setPrototypeOf(FetchRequest.prototype, globalThis.Request.prototype)\n Object.setPrototypeOf(FetchResponse, globalThis.Response)\n Object.setPrototypeOf(FetchResponse.prototype, globalThis.Response.prototype)\n\n return restoreHeadersPrototype\n}\n\nexport function restoreHeadersPrototype() {\n if (!Reflect.get(Headers, kRestorePatches)) {\n return\n }\n\n Reflect.get(Headers, kRestorePatches)()\n}\n\nexport function getRawFetchHeaders(headers: Headers): RawHeaders {\n // If the raw headers recording failed for some reason,\n // use the normalized header entries instead.\n if (!Reflect.has(headers, kRawHeaders)) {\n return Array.from(headers.entries())\n }\n\n const rawHeaders = Reflect.get(headers, kRawHeaders) as RawHeaders\n return rawHeaders.length > 0 ? rawHeaders : Array.from(headers.entries())\n}\n\n/**\n * Infers the raw headers from the given `HeadersInit` provided\n * to the Request/Response constructor.\n *\n * If the `init.headers` is a Headers instance, use it directly.\n * That means the headers were created standalone and already have\n * the raw headers stored.\n * If the `init.headers` is a HeadersInit, create a new Headers\n * instance out of it.\n */\nfunction inferRawHeaders(headers: HeadersInit): RawHeaders {\n if (headers instanceof Headers) {\n return Reflect.get(headers, kRawHeaders) || []\n }\n\n return Reflect.get(new Headers(headers), kRawHeaders)\n}\n\nexport function copyRawHeaders(source: Headers, destination: Headers): void {\n const rawHeaders = [...getRawFetchHeaders(source)]\n\n if (rawHeaders.length === 0) {\n return\n }\n\n /**\n * @note Add headers from trhe destination that raw headers from the source\n * don't have. Undici automatically appends a \"Content-Type\" header for responses\n * and, for some reason, that change is not recorded. This preserves it.\n */\n for (const [name, value] of destination) {\n if (\n rawHeaders.every(\n (header) => header[0].toLowerCase() !== name.toLowerCase()\n )\n ) {\n rawHeaders.push([name, value])\n }\n }\n\n defineRawHeadersSymbol(destination, rawHeaders)\n}\n","/**\n * Returns the value behind the symbol with the given name.\n */\nexport function getValueBySymbol<T>(\n symbolName: string,\n source: object\n): T | undefined {\n const ownSymbols = Object.getOwnPropertySymbols(source)\n\n const symbol = ownSymbols.find((symbol) => {\n return symbol.description === symbolName\n })\n\n if (symbol) {\n return Reflect.get(source, symbol)\n }\n\n return\n}\n","/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject<T>(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible<Obj extends Record<string, any>>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isObject } from './is-object'\nimport { isPropertyAccessible } from './is-property-accessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * A key on the error a mocked `Response.error()` destroys the socket\n * with, referencing that error response. Allows the client-side\n * interceptors (e.g. fetch) to surface the error response to the\n * consumer instead of the internal socket error.\n */\nexport const kErrorResponse = Symbol('kErrorResponse')\n\n/**\n * Get the mocked error response that caused the given error, if any.\n */\nexport function getErrorResponse(error: unknown): ResponseError | undefined {\n if (\n error instanceof Error &&\n kErrorResponse in error &&\n isResponseError(error[kErrorResponse])\n ) {\n return error[kErrorResponse]\n }\n\n return undefined\n}\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: unknown): response is ResponseError {\n return (\n response != null &&\n response instanceof Response &&\n isPropertyAccessible(response, 'type') &&\n response.type === 'error'\n )\n}\n\n/**\n * Check if the given value is a `Response` or a Response-like object.\n * This is different from `value instanceof Response` because it supports\n * custom `Response` constructors, like the one when using Undici directly.\n */\nexport function isResponseLike(value: unknown): value is Response {\n return (\n isObject<Record<string, any>>(value, true) &&\n isPropertyAccessible(value, 'status') &&\n isPropertyAccessible(value, 'statusText') &&\n isPropertyAccessible(value, 'bodyUsed')\n )\n}\n","import { copyRawHeaders } from '../interceptors/ClientRequest/utils/record-raw-headers'\nimport { getValueBySymbol } from './get-value-by-symbol'\nimport { isResponseError } from './response-utils'\n\ninterface UndiciRequestState extends RequestInit {}\n\ninterface FetchRequestInit extends Omit<RequestInit, 'mode'> {\n mode?: RequestMode | 'websocket' | 'webtransport'\n duplex?: 'half' | 'full'\n}\n\nexport class FetchRequest extends Request {\n static #resolveProperty<T extends keyof FetchRequestInit & keyof Request>(\n input: RequestInfo | URL,\n init: FetchRequestInit = {},\n key: T\n ): FetchRequestInit[T] {\n return init[key] ?? (input instanceof Request ? input[key] : undefined)\n }\n\n /**\n * Check if the given request method is configurable.\n * @see https://fetch.spec.whatwg.org/#methods\n */\n static isConfigurableMethod(method: string): boolean {\n return method !== 'CONNECT' && method !== 'TRACE' && method !== 'TRACK'\n }\n\n static isMethodWithBody(method: string): boolean {\n return (\n method !== 'HEAD' &&\n method !== 'GET' &&\n FetchRequest.isConfigurableMethod(method)\n )\n }\n\n /**\n * Check if the given request `mode` is configurable.\n * @see https://fetch.spec.whatwg.org/#concept-request-mode\n */\n static isConfigurableMode(mode: string): boolean {\n return (\n mode !== 'navigate' && mode !== 'websocket' && mode !== 'webtransport'\n )\n }\n\n constructor(input: URL | RequestInfo, init?: FetchRequestInit) {\n const method = FetchRequest.#resolveProperty(input, init, 'method') || 'GET'\n const safeMethod = FetchRequest.isConfigurableMethod(method)\n ? method\n : 'GET'\n\n const hasExplicitBody = init != null && 'body' in init\n\n /**\n * Only include `body` in the super init when it needs to be overridden.\n * When `input` is a Request and no explicit body is in `init`, let the\n * Request constructor handle body transfer naturally so it properly\n * marks the original request's body as consumed (bodyUsed = true).\n */\n const bodyInit: { body?: BodyInit | null } = !FetchRequest.isMethodWithBody(\n method\n )\n ? { body: undefined }\n : hasExplicitBody\n ? { body: init.body }\n : {}\n\n const mode =\n (FetchRequest.#resolveProperty(input, init, 'mode') as RequestMode) ??\n undefined\n const safeMode = FetchRequest.isConfigurableMode(mode) ? mode : undefined\n\n super(input, {\n ...(init || {}),\n method: safeMethod,\n mode: safeMode,\n // @ts-expect-error Untyped Node.js property.\n duplex:\n init?.duplex ??\n (FetchRequest.isMethodWithBody(method) ? 'half' : undefined),\n ...bodyInit,\n })\n\n if (method !== safeMethod) {\n this.#setInternalProperty('method', method)\n }\n\n if (method === 'CONNECT') {\n const url = new URL(input instanceof Request ? input.url : input)\n\n let authority: string\n\n /**\n * @note Node.js has a bug parsing raw CONNECT requests URLs like\n * \"http://127.0.0.1:1337/localhost:80\". It would treat \"localhost:\" as a protocol.\n */\n if (url.protocol === 'localhost:') {\n authority = url.href\n } else {\n authority = url.pathname.replace(/^\\/+/, '')\n }\n\n /**\n * @note Define \"url\" as a getter because Undici uses their own\n * logic to resolve the \"request.url\" property. Simply reassigning\n * its value doesn't do anything. This is a destructive action\n * but it's safe because \"CONNECT\" requests are forbidden per fetch.\n */\n Object.defineProperty(this, 'url', {\n get: () => authority,\n enumerable: true,\n configurable: true,\n })\n }\n\n if (mode != null && mode !== safeMode) {\n this.#setInternalProperty('mode', mode)\n }\n }\n\n #setInternalProperty<T extends keyof Request>(\n key: T,\n value: Request[T]\n ): void {\n const internalState = getValueBySymbol<UndiciRequestState>('state', this)\n\n if (internalState) {\n Reflect.set(internalState, key, value)\n } else {\n Object.defineProperty(this, key, {\n value,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n }\n}\n\nexport interface FetchResponseInit extends ResponseInit {\n url?: string\n}\n\ninterface UndiciResponseState {\n aborted: boolean\n rangeRequested: boolean\n timingAllowPassed: boolean\n requestIncludesCredentials: boolean\n type: ResponseType\n status: number\n statusText: string\n timingInfo: unknown\n cacheState: unknown\n headersList: Record<symbol, Map<string, unknown>>\n urlList: Array<URL>\n body?: {\n stream: ReadableStream\n source: unknown\n length: number\n }\n}\n\nconst kStatus = Symbol('kStatus')\nconst kUrl = Symbol('kUrl')\n\nexport class FetchResponse extends Response {\n static from(response: Response, init?: FetchResponseInit): FetchResponse {\n if (response instanceof FetchResponse) {\n return response\n }\n\n if (isResponseError(response)) {\n return response\n }\n\n const fetchResponse = new FetchResponse(response.body, {\n url: init?.url ?? response.url,\n status: init?.status || response.status,\n statusText: init?.statusText ?? response.statusText,\n headers: init?.headers ?? response.headers,\n })\n\n copyRawHeaders(response.headers, fetchResponse.headers)\n\n return fetchResponse\n }\n\n /**\n * Response status codes for responses that cannot have body.\n * @see https://fetch.spec.whatwg.org/#statuses\n */\n static readonly STATUS_CODES_WITHOUT_BODY = [101, 103, 204, 205, 304]\n\n static readonly STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308]\n\n static isConfigurableStatusCode(status: number): boolean {\n return status >= 200 && status <= 599\n }\n\n static isRedirectResponse(status: number): boolean {\n return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status)\n }\n\n /**\n * Returns a boolean indicating whether the given response status\n * code represents a response that can have a body.\n */\n static isResponseWithBody(status: number): boolean {\n return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status)\n }\n\n static setStatus(status: number, response: Response): void {\n /**\n * @note Undici keeps an internal \"Symbol(state)\" that holds\n * the actual value of response status. Update that in Node.js.\n */\n const internalState = getValueBySymbol<UndiciResponseState>(\n 'state',\n response\n )\n\n if (internalState) {\n internalState.status = status\n } else {\n Object.defineProperty(response, 'status', {\n value: status,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n\n Object.defineProperty(response, kStatus, {\n value: status,\n enumerable: false,\n })\n }\n\n static setUrl(url: string | undefined, response: Response): void {\n if (!url || url === 'about:' || !URL.canParse(url)) {\n return\n }\n\n const state = getValueBySymbol<UndiciResponseState>('state', response)\n\n if (state) {\n // In Undici, push the URL to the internal list of URLs.\n // This will respect the `response.url` getter logic correctly.\n state.urlList.push(new URL(url))\n } else {\n // In other libraries, redefine the `url` property directly.\n Object.defineProperty(response, 'url', {\n value: url,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n\n Object.defineProperty(response, kUrl, {\n value: url,\n enumerable: false,\n })\n }\n\n /**\n * Parses the given raw HTTP headers into a Fetch API `Headers` instance.\n */\n static parseRawHeaders(rawHeaders: Array<string>): Headers {\n const headers = new Headers()\n\n for (let line = 0; line < rawHeaders.length; line += 2) {\n headers.append(rawHeaders[line], rawHeaders[line + 1])\n }\n\n return headers\n }\n\n /**\n * Safely clones the given `Response`.\n * Coerces response clone exceptions into 500 mocked responses.\n * Handy in the environments that introduce arbitrary response\n * cloning restrictions, like \"101 Switching Protocols\" cloning\n * in \"miniflare\".\n */\n static clone(response: Response): Response {\n try {\n const clone = response.clone()\n return clone\n } catch (error) {\n return Response.json(\n error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : {},\n {\n status: 500,\n statusText: 'Unclonable Response',\n }\n )\n }\n }\n\n #status?: number\n #url?: string\n\n constructor(body?: BodyInit | null, init: FetchResponseInit = {}) {\n const status = init.status ?? 200\n const safeStatus = FetchResponse.isConfigurableStatusCode(status)\n ? status\n : 200\n const finalBody = FetchResponse.isResponseWithBody(status) ? body : null\n\n super(finalBody, {\n status: safeStatus,\n statusText: init.statusText,\n headers: init.headers,\n })\n\n /**\n * Since Node.js v24, Undici stores the Response state in an inaccessible field \"#state\".\n * Forward the modified status/URL to the cloned response manually.\n * @see https://github.com/nodejs/undici/blob/f734c87280e626c75f59aad55b65eb6a89cef392/lib/web/fetch/response.js#L242\n */\n if (status !== safeStatus) {\n FetchResponse.setStatus(status, this)\n }\n\n FetchResponse.setUrl(init.url, this)\n }\n\n public clone() {\n const clonedResponse = super.clone()\n\n const customStatus = Reflect.get(this, kStatus) as number | undefined\n\n if (customStatus) {\n FetchResponse.setStatus(customStatus, clonedResponse)\n }\n\n const customUrl = Reflect.get(this, kUrl) as string | undefined\n\n if (customUrl) {\n FetchResponse.setUrl(customUrl, clonedResponse)\n }\n\n return clonedResponse\n }\n}\n"],"mappings":";;;AAAA,IAAa,mBAAb,MAAa,yBAAyB,MAAM;CAC1C,YAAY,SAAkB;EAC5B,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,iBAAiB,SAAS;CACxD;AACF;;;ACSA,IAAa,oBAAb,MAAa,kBAAkB;;EACZ,KAAA,UAAA;;;EACI,KAAA,cAAA;;;EACH,KAAA,WAAA;;;EACH,KAAA,QAAA;;CAUf;CAEA,YACE,SACA,QACA,SACA;EAHmB,KAAA,UAAA;EACA,KAAA,SAAA;EACA,KAAA,UAAA;EAEnB,K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