@mswjs/interceptors 0.39.8 → 0.40.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/lib/browser/{chunk-E3CCOBRX.js → chunk-2MCNQOY3.js} +54 -49
- package/lib/browser/chunk-2MCNQOY3.js.map +1 -0
- package/lib/browser/chunk-57RIRQUY.js +218 -0
- package/lib/browser/chunk-57RIRQUY.js.map +1 -0
- package/lib/browser/chunk-FW45TRCB.js +178 -0
- package/lib/browser/chunk-FW45TRCB.js.map +1 -0
- package/lib/browser/{chunk-TIPR373R.js → chunk-JQ2S7G56.js} +19 -3
- package/lib/browser/chunk-JQ2S7G56.js.map +1 -0
- package/lib/browser/{chunk-3RXCRGL2.mjs → chunk-LIKZF2VU.mjs} +102 -1
- package/lib/browser/chunk-LIKZF2VU.mjs.map +1 -0
- package/lib/browser/{chunk-H74PGQ4Y.js → chunk-MNT2FUCH.js} +58 -53
- package/lib/browser/chunk-MNT2FUCH.js.map +1 -0
- package/lib/browser/chunk-VOUOVDAW.mjs +178 -0
- package/lib/browser/chunk-VOUOVDAW.mjs.map +1 -0
- package/lib/browser/{chunk-E7UVBHVO.mjs → chunk-WADP6VHN.mjs} +48 -43
- package/lib/browser/chunk-WADP6VHN.mjs.map +1 -0
- package/lib/browser/{chunk-Q7K2XAEP.mjs → chunk-WOWPV4GR.mjs} +50 -45
- package/lib/browser/chunk-WOWPV4GR.mjs.map +1 -0
- package/lib/browser/{chunk-QED3Q6Z2.mjs → chunk-Z5TSB3T6.mjs} +17 -1
- package/lib/browser/{chunk-QED3Q6Z2.mjs.map → chunk-Z5TSB3T6.mjs.map} +1 -1
- package/lib/browser/{glossary-7152281e.d.ts → glossary-f7ee1c9d.d.ts} +22 -17
- package/lib/browser/index.d.ts +1 -2
- package/lib/browser/index.js +6 -4
- package/lib/browser/index.js.map +1 -1
- package/lib/browser/index.mjs +4 -2
- package/lib/browser/index.mjs.map +1 -1
- package/lib/browser/interceptors/WebSocket/index.js +3 -3
- package/lib/browser/interceptors/WebSocket/index.mjs +1 -1
- package/lib/browser/interceptors/XMLHttpRequest/index.d.ts +1 -2
- package/lib/browser/interceptors/XMLHttpRequest/index.js +5 -5
- package/lib/browser/interceptors/XMLHttpRequest/index.mjs +4 -4
- package/lib/browser/interceptors/fetch/index.d.ts +1 -2
- package/lib/browser/interceptors/fetch/index.js +5 -5
- package/lib/browser/interceptors/fetch/index.mjs +4 -4
- package/lib/browser/presets/browser.d.ts +1 -2
- package/lib/browser/presets/browser.js +7 -7
- package/lib/browser/presets/browser.mjs +5 -5
- package/lib/node/{BatchInterceptor-5b72232f.d.ts → BatchInterceptor-cb9a2eee.d.ts} +1 -1
- package/lib/node/{Interceptor-bc5a9d8e.d.ts → Interceptor-dc0a39b5.d.ts} +22 -16
- package/lib/node/RemoteHttpInterceptor.d.ts +2 -3
- package/lib/node/RemoteHttpInterceptor.js +31 -27
- package/lib/node/RemoteHttpInterceptor.js.map +1 -1
- package/lib/node/RemoteHttpInterceptor.mjs +28 -24
- package/lib/node/RemoteHttpInterceptor.mjs.map +1 -1
- package/lib/node/{chunk-EKNRB5ZS.mjs → chunk-5UGIB6OX.mjs} +40 -29
- package/lib/node/chunk-5UGIB6OX.mjs.map +1 -0
- package/lib/node/{chunk-4NEYTVWD.mjs → chunk-5V3SIIW2.mjs} +48 -43
- package/lib/node/chunk-5V3SIIW2.mjs.map +1 -0
- package/lib/node/{chunk-VV2LUF5K.js → chunk-6B3ZQOO2.js} +51 -46
- package/lib/node/chunk-6B3ZQOO2.js.map +1 -0
- package/lib/node/chunk-7Q53NNPV.js +189 -0
- package/lib/node/chunk-7Q53NNPV.js.map +1 -0
- package/lib/node/{chunk-A7U44ARP.js → chunk-DOWWQYXZ.js} +104 -3
- package/lib/node/chunk-DOWWQYXZ.js.map +1 -0
- package/lib/node/{chunk-Z5LWCBZS.js → chunk-FRZQJNBO.js} +56 -51
- package/lib/node/chunk-FRZQJNBO.js.map +1 -0
- package/lib/node/{chunk-TJDMZZXE.mjs → chunk-GKN5RBVR.mjs} +2 -2
- package/lib/node/{chunk-R6JVCM7X.js → chunk-J5MULIHT.js} +3 -3
- package/lib/node/{chunk-IHJSPMYM.mjs → chunk-JXGB54LE.mjs} +102 -1
- package/lib/node/chunk-JXGB54LE.mjs.map +1 -0
- package/lib/node/{chunk-3CNGDJFB.mjs → chunk-OFW5L5ET.mjs} +50 -45
- package/lib/node/chunk-OFW5L5ET.mjs.map +1 -0
- package/lib/node/{chunk-A7Q4RTDJ.mjs → chunk-R6T7CL5E.mjs} +55 -115
- package/lib/node/chunk-R6T7CL5E.mjs.map +1 -0
- package/lib/node/{chunk-RC2XPCC4.mjs → chunk-SQ6RHTJR.mjs} +2 -2
- package/lib/node/chunk-SRMAQGPM.js +30 -0
- package/lib/node/chunk-SRMAQGPM.js.map +1 -0
- package/lib/node/{chunk-4YBV77DG.js → chunk-T3TW4P64.js} +3 -3
- package/lib/node/{chunk-N4ZZFE24.js → chunk-VYO5XDY2.js} +56 -45
- package/lib/node/chunk-VYO5XDY2.js.map +1 -0
- package/lib/node/chunk-YWNGXXUQ.mjs +30 -0
- package/lib/node/{chunk-3GJB4JDF.mjs.map → chunk-YWNGXXUQ.mjs.map} +1 -1
- package/lib/node/index.d.ts +2 -3
- package/lib/node/index.js +6 -4
- package/lib/node/index.js.map +1 -1
- package/lib/node/index.mjs +5 -3
- package/lib/node/index.mjs.map +1 -1
- package/lib/node/interceptors/ClientRequest/index.d.ts +1 -2
- package/lib/node/interceptors/ClientRequest/index.js +6 -6
- package/lib/node/interceptors/ClientRequest/index.mjs +5 -5
- package/lib/node/interceptors/XMLHttpRequest/index.d.ts +1 -2
- package/lib/node/interceptors/XMLHttpRequest/index.js +5 -5
- package/lib/node/interceptors/XMLHttpRequest/index.mjs +4 -4
- package/lib/node/interceptors/fetch/index.d.ts +1 -2
- package/lib/node/interceptors/fetch/index.js +5 -5
- package/lib/node/interceptors/fetch/index.mjs +4 -4
- package/lib/node/presets/node.d.ts +1 -2
- package/lib/node/presets/node.js +10 -10
- package/lib/node/presets/node.mjs +7 -7
- package/lib/node/utils/node/index.js +3 -3
- package/lib/node/utils/node/index.mjs +2 -2
- package/package.json +2 -1
- package/src/RemoteHttpInterceptor.ts +18 -13
- package/src/RequestController.test.ts +78 -31
- package/src/RequestController.ts +63 -39
- package/src/index.ts +4 -0
- package/src/interceptors/ClientRequest/MockHttpSocket.ts +24 -3
- package/src/interceptors/ClientRequest/index.ts +14 -18
- package/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts +45 -35
- package/src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +24 -21
- package/src/interceptors/fetch/index.ts +61 -50
- package/src/utils/handleRequest.ts +65 -95
- package/lib/browser/chunk-2QICSCCS.js +0 -238
- package/lib/browser/chunk-2QICSCCS.js.map +0 -1
- package/lib/browser/chunk-3RXCRGL2.mjs.map +0 -1
- package/lib/browser/chunk-E3CCOBRX.js.map +0 -1
- package/lib/browser/chunk-E7UVBHVO.mjs.map +0 -1
- package/lib/browser/chunk-H74PGQ4Y.js.map +0 -1
- package/lib/browser/chunk-PTTUYYVR.mjs +0 -238
- package/lib/browser/chunk-PTTUYYVR.mjs.map +0 -1
- package/lib/browser/chunk-Q7K2XAEP.mjs.map +0 -1
- package/lib/browser/chunk-T7TBRNJZ.js +0 -117
- package/lib/browser/chunk-T7TBRNJZ.js.map +0 -1
- package/lib/browser/chunk-TIPR373R.js.map +0 -1
- package/lib/node/chunk-3CNGDJFB.mjs.map +0 -1
- package/lib/node/chunk-3GJB4JDF.mjs +0 -14
- package/lib/node/chunk-4NEYTVWD.mjs.map +0 -1
- package/lib/node/chunk-72ZIHMEB.js +0 -249
- package/lib/node/chunk-72ZIHMEB.js.map +0 -1
- package/lib/node/chunk-A7Q4RTDJ.mjs.map +0 -1
- package/lib/node/chunk-A7U44ARP.js.map +0 -1
- package/lib/node/chunk-EKNRB5ZS.mjs.map +0 -1
- package/lib/node/chunk-IHJSPMYM.mjs.map +0 -1
- package/lib/node/chunk-N4ZZFE24.js.map +0 -1
- package/lib/node/chunk-SMXZPJEA.js +0 -14
- package/lib/node/chunk-SMXZPJEA.js.map +0 -1
- package/lib/node/chunk-VV2LUF5K.js.map +0 -1
- package/lib/node/chunk-Z5LWCBZS.js.map +0 -1
- package/src/utils/RequestController.ts +0 -21
- /package/lib/node/{chunk-TJDMZZXE.mjs.map → chunk-GKN5RBVR.mjs.map} +0 -0
- /package/lib/node/{chunk-R6JVCM7X.js.map → chunk-J5MULIHT.js.map} +0 -0
- /package/lib/node/{chunk-RC2XPCC4.mjs.map → chunk-SQ6RHTJR.mjs.map} +0 -0
- /package/lib/node/{chunk-4YBV77DG.js.map → chunk-T3TW4P64.js.map} +0 -0
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
var _chunk57RIRQUYjs = require('./chunk-57RIRQUY.js');
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
var _chunk2HUMWGRDjs = require('./chunk-2HUMWGRD.js');
|
|
8
|
+
|
|
9
|
+
// src/utils/isObject.ts
|
|
10
|
+
function isObject(value, loose = false) {
|
|
11
|
+
return loose ? Object.prototype.toString.call(value).startsWith("[object ") : Object.prototype.toString.call(value) === "[object Object]";
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// src/utils/isPropertyAccessible.ts
|
|
15
|
+
function isPropertyAccessible(obj, key) {
|
|
16
|
+
try {
|
|
17
|
+
obj[key];
|
|
18
|
+
return true;
|
|
19
|
+
} catch (e) {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// src/utils/responseUtils.ts
|
|
25
|
+
function createServerErrorResponse(body) {
|
|
26
|
+
return new Response(
|
|
27
|
+
JSON.stringify(
|
|
28
|
+
body instanceof Error ? {
|
|
29
|
+
name: body.name,
|
|
30
|
+
message: body.message,
|
|
31
|
+
stack: body.stack
|
|
32
|
+
} : body
|
|
33
|
+
),
|
|
34
|
+
{
|
|
35
|
+
status: 500,
|
|
36
|
+
statusText: "Unhandled Exception",
|
|
37
|
+
headers: {
|
|
38
|
+
"Content-Type": "application/json"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
function isResponseError(response) {
|
|
44
|
+
return response != null && response instanceof Response && isPropertyAccessible(response, "type") && response.type === "error";
|
|
45
|
+
}
|
|
46
|
+
function isResponseLike(value) {
|
|
47
|
+
return isObject(value, true) && isPropertyAccessible(value, "status") && isPropertyAccessible(value, "statusText") && isPropertyAccessible(value, "bodyUsed");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// src/utils/handleRequest.ts
|
|
51
|
+
var _deferredpromise = require('@open-draft/deferred-promise');
|
|
52
|
+
var _until = require('@open-draft/until');
|
|
53
|
+
|
|
54
|
+
// src/utils/isNodeLikeError.ts
|
|
55
|
+
function isNodeLikeError(error) {
|
|
56
|
+
if (error == null) {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
if (!(error instanceof Error)) {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
return "code" in error && "errno" in error;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// src/utils/handleRequest.ts
|
|
66
|
+
async function handleRequest(options) {
|
|
67
|
+
const handleResponse = async (response) => {
|
|
68
|
+
if (response instanceof Error) {
|
|
69
|
+
await options.controller.errorWith(response);
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
if (isResponseError(response)) {
|
|
73
|
+
await options.controller.respondWith(response);
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
if (isResponseLike(response)) {
|
|
77
|
+
await options.controller.respondWith(response);
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
if (isObject(response)) {
|
|
81
|
+
await options.controller.errorWith(response);
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
return false;
|
|
85
|
+
};
|
|
86
|
+
const handleResponseError = async (error) => {
|
|
87
|
+
if (error instanceof _chunk57RIRQUYjs.InterceptorError) {
|
|
88
|
+
throw result.error;
|
|
89
|
+
}
|
|
90
|
+
if (isNodeLikeError(error)) {
|
|
91
|
+
await options.controller.errorWith(error);
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
if (error instanceof Response) {
|
|
95
|
+
return await handleResponse(error);
|
|
96
|
+
}
|
|
97
|
+
return false;
|
|
98
|
+
};
|
|
99
|
+
const requestAbortPromise = new (0, _deferredpromise.DeferredPromise)();
|
|
100
|
+
if (options.request.signal) {
|
|
101
|
+
if (options.request.signal.aborted) {
|
|
102
|
+
await options.controller.errorWith(options.request.signal.reason);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
options.request.signal.addEventListener(
|
|
106
|
+
"abort",
|
|
107
|
+
() => {
|
|
108
|
+
requestAbortPromise.reject(options.request.signal.reason);
|
|
109
|
+
},
|
|
110
|
+
{ once: true }
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
const result = await _until.until.call(void 0, async () => {
|
|
114
|
+
const requestListenersPromise = _chunk2HUMWGRDjs.emitAsync.call(void 0, options.emitter, "request", {
|
|
115
|
+
requestId: options.requestId,
|
|
116
|
+
request: options.request,
|
|
117
|
+
controller: options.controller
|
|
118
|
+
});
|
|
119
|
+
await Promise.race([
|
|
120
|
+
// Short-circuit the request handling promise if the request gets aborted.
|
|
121
|
+
requestAbortPromise,
|
|
122
|
+
requestListenersPromise,
|
|
123
|
+
options.controller.handled
|
|
124
|
+
]);
|
|
125
|
+
});
|
|
126
|
+
if (requestAbortPromise.state === "rejected") {
|
|
127
|
+
await options.controller.errorWith(requestAbortPromise.rejectionReason);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (result.error) {
|
|
131
|
+
if (await handleResponseError(result.error)) {
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (options.emitter.listenerCount("unhandledException") > 0) {
|
|
135
|
+
const unhandledExceptionController = new (0, _chunk57RIRQUYjs.RequestController)(
|
|
136
|
+
options.request,
|
|
137
|
+
{
|
|
138
|
+
/**
|
|
139
|
+
* @note Intentionally empty passthrough handle.
|
|
140
|
+
* This controller is created within another controller and we only need
|
|
141
|
+
* to know if `unhandledException` listeners handled the request.
|
|
142
|
+
*/
|
|
143
|
+
passthrough() {
|
|
144
|
+
},
|
|
145
|
+
async respondWith(response) {
|
|
146
|
+
await handleResponse(response);
|
|
147
|
+
},
|
|
148
|
+
async errorWith(reason) {
|
|
149
|
+
await options.controller.errorWith(reason);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
);
|
|
153
|
+
await _chunk2HUMWGRDjs.emitAsync.call(void 0, options.emitter, "unhandledException", {
|
|
154
|
+
error: result.error,
|
|
155
|
+
request: options.request,
|
|
156
|
+
requestId: options.requestId,
|
|
157
|
+
controller: unhandledExceptionController
|
|
158
|
+
});
|
|
159
|
+
if (unhandledExceptionController.readyState !== _chunk57RIRQUYjs.RequestController.PENDING) {
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
await options.controller.respondWith(
|
|
164
|
+
createServerErrorResponse(result.error)
|
|
165
|
+
);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (options.controller.readyState === _chunk57RIRQUYjs.RequestController.PENDING) {
|
|
169
|
+
return await options.controller.passthrough();
|
|
170
|
+
}
|
|
171
|
+
return options.controller.handled;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
exports.isResponseError = isResponseError; exports.handleRequest = handleRequest;
|
|
178
|
+
//# sourceMappingURL=chunk-FW45TRCB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/isObject.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/handle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H,CAAC;AAGD,MAAI,oBAAoB,UAAU,YAAY;AAC5C,UAAM,QAAQ,WAAW,UAAU,oBAAoB,eAAe;AACtE;AAAA,EACF;AAEA,MAAI,OAAO,OAAO;AAGhB,QAAI,MAAM,oBAAoB,OAAO,KAAK,GAAG;AAC3C;AAAA,IACF;AAKA,QAAI,QAAQ,QAAQ,cAAc,oBAAoB,IAAI,GAAG;AAI3D,YAAM,+BAA+B,IAAI;AAAA,QACvC,QAAQ;AAAA,QACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAME,cAAc;AAAA,UAAC;AAAA,UACf,MAAM,YAAY,UAAU;AAC1B,kBAAM,eAAe,QAAQ;AAAA,UAC/B;AAAA,UACA,MAAM,UAAU,QAAQ;AAQtB,kBAAM,QAAQ,WAAW,UAAU,MAAM;AAAA,UAC3C;AAAA,QACF;AAAA,MACF;AAEA,YAAM,UAAU,QAAQ,SAAS,sBAAsB;AAAA,QACrD,OAAO,OAAO;AAAA,QACd,SAAS,QAAQ;AAAA,QACjB,WAAW,QAAQ;AAAA,QACnB,YAAY;AAAA,MACd,CAAC;AAID,UACE,6BAA6B,eAAe,kBAAkB,SAC9D;AACA;AAAA,MACF;AAAA,IACF;AAGA,UAAM,QAAQ,WAAW;AAAA,MACvB,0BAA0B,OAAO,KAAK;AAAA,IACxC;AACA;AAAA,EACF;AAGA,MAAI,QAAQ,WAAW,eAAe,kBAAkB,SAAS;AAC/D,WAAO,MAAM,QAAQ,WAAW,YAAY;AAAA,EAC9C;AAEA,SAAO,QAAQ,WAAW;AAC5B","sourcesContent":["/**\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 './isObject'\nimport { isPropertyAccessible } from './isPropertyAccessible'\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 * 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 type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\nimport { isObject } from './isObject'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter<HttpRequestEventMap>\n controller: RequestController\n}\n\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise<void> {\n const handleResponse = async (\n response: Response | Error | Record<string, any>\n ) => {\n if (response instanceof Error) {\n await options.controller.errorWith(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n /**\n * Handle normal responses or response-like objects.\n * @note This must come before the arbitrary object check\n * since Response instances are, in fact, objects.\n */\n if (isResponseLike(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n await options.controller.errorWith(response)\n return true\n }\n\n return false\n }\n\n const handleResponseError = async (error: unknown): Promise<boolean> => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n await options.controller.errorWith(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n // options.emitter.once('request', async ({ requestId: pendingRequestId }) => {\n // if (\n // pendingRequestId === options.requestId &&\n // options.controller.readyState === RequestController.PENDING\n // ) {\n // await options.controller.passthrough()\n // }\n // })\n\n const requestAbortPromise = new DeferredPromise<void, unknown>()\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n await options.controller.errorWith(options.request.signal.reason)\n return\n }\n\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\n )\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListenersPromise,\n options.controller.handled,\n ])\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n await options.controller.errorWith(requestAbortPromise.rejectionReason)\n return\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request,\n {\n /**\n * @note Intentionally empty passthrough handle.\n * This controller is created within another controller and we only need\n * to know if `unhandledException` listeners handled the request.\n */\n passthrough() {},\n async respondWith(response) {\n await handleResponse(response)\n },\n async errorWith(reason) {\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n await options.controller.errorWith(reason)\n },\n }\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n })\n\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the request in any way, passthrough.\n if (\n unhandledExceptionController.readyState !== RequestController.PENDING\n ) {\n return\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n await options.controller.respondWith(\n createServerErrorResponse(result.error)\n )\n return\n }\n\n // If the request hasn't been handled by this point, passthrough.\n if (options.controller.readyState === RequestController.PENDING) {\n return await options.controller.passthrough()\n }\n\n return options.controller.handled\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n"]}
|
|
@@ -1,4 +1,18 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true})
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var __accessCheck = (obj, member, msg) => {
|
|
2
|
+
if (!member.has(obj))
|
|
3
|
+
throw TypeError("Cannot " + msg);
|
|
4
|
+
};
|
|
5
|
+
var __privateGet = (obj, member, getter) => {
|
|
6
|
+
__accessCheck(obj, member, "read from private field");
|
|
7
|
+
return getter ? getter.call(obj) : member.get(obj);
|
|
8
|
+
};
|
|
9
|
+
var __privateAdd = (obj, member, value) => {
|
|
10
|
+
if (member.has(obj))
|
|
11
|
+
throw TypeError("Cannot add the same private member more than once");
|
|
12
|
+
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
// src/Interceptor.ts
|
|
2
16
|
var _logger = require('@open-draft/logger');
|
|
3
17
|
var _stricteventemitter = require('strict-event-emitter');
|
|
4
18
|
var INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id";
|
|
@@ -165,5 +179,7 @@ function createRequestId() {
|
|
|
165
179
|
|
|
166
180
|
|
|
167
181
|
|
|
168
|
-
|
|
169
|
-
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
exports.__privateGet = __privateGet; exports.__privateAdd = __privateAdd; exports.INTERNAL_REQUEST_ID_HEADER_NAME = INTERNAL_REQUEST_ID_HEADER_NAME; exports.getGlobalSymbol = getGlobalSymbol; exports.deleteGlobalSymbol = deleteGlobalSymbol; exports.InterceptorReadyState = InterceptorReadyState; exports.Interceptor = Interceptor; exports.createRequestId = createRequestId;
|
|
185
|
+
//# sourceMappingURL=chunk-JQ2S7G56.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/Interceptor.ts","../../src/createRequestId.ts"],"names":["InterceptorReadyState"],"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F;AAIA,SAAK,cAAc;AAEnB,WAAO,KAAK,0BAA0B,gBAAgB,KAAK,MAAM,CAAC;AAElE,QAAI,KAAK,cAAc,SAAS,GAAG;AACjC,aAAO,KAAK,oCAAoC,KAAK,cAAc,MAAM;AAEzE,iBAAW,WAAW,KAAK,eAAe;AACxC,gBAAQ;AAAA,MACV;AAEA,WAAK,gBAAgB,CAAC;AAEtB,aAAO,KAAK,kCAAkC,KAAK,cAAc,MAAM;AAAA,IACzE;AAEA,SAAK,QAAQ,mBAAmB;AAChC,WAAO,KAAK,yBAAyB;AAErC,SAAK,aAAa;AAAA,EACpB;AAAA,EAEQ,cAAgC;AAzO1C;AA0OI,UAAM,WAAW,gBAAsB,KAAK,MAAM;AAClD,SAAK,OAAO,KAAK,+BAA8B,0CAAU,gBAAV,mBAAuB,IAAI;AAC1E,WAAO;AAAA,EACT;AAAA,EAEQ,cAAoB;AAC1B,oBAAgB,KAAK,QAAQ,IAAI;AACjC,SAAK,OAAO,KAAK,wBAAwB,KAAK,OAAO,WAAW;AAAA,EAClE;AAAA,EAEQ,gBAAsB;AAC5B,uBAAmB,KAAK,MAAM;AAC9B,SAAK,OAAO,KAAK,4BAA4B,KAAK,OAAO,WAAW;AAAA,EACtE;AACF;;;AClPO,SAAS,kBAA0B;AACxC,SAAO,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC;AAC3C","sourcesContent":["import { Logger } from '@open-draft/logger'\nimport { Emitter, Listener } from 'strict-event-emitter'\n\nexport type InterceptorEventMap = Record<string, any>\nexport type InterceptorSubscription = () => void\n\n/**\n * Request header name to detect when a single request\n * is being handled by nested interceptors (XHR -> ClientRequest).\n * Obscure by design to prevent collisions with user-defined headers.\n * Ideally, come up with the Interceptor-level mechanism for this.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\nexport const INTERNAL_REQUEST_ID_HEADER_NAME =\n 'x-interceptors-internal-request-id'\n\nexport function getGlobalSymbol<V>(symbol: Symbol): V | undefined {\n return (\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587\n globalThis[symbol] || undefined\n )\n}\n\nfunction setGlobalSymbol(symbol: Symbol, value: any): void {\n // @ts-ignore\n globalThis[symbol] = value\n}\n\nexport function deleteGlobalSymbol(symbol: Symbol): void {\n // @ts-ignore\n delete globalThis[symbol]\n}\n\nexport enum InterceptorReadyState {\n INACTIVE = 'INACTIVE',\n APPLYING = 'APPLYING',\n APPLIED = 'APPLIED',\n DISPOSING = 'DISPOSING',\n DISPOSED = 'DISPOSED',\n}\n\nexport type ExtractEventNames<Events extends Record<string, any>> =\n Events extends Record<infer EventName, any> ? EventName : never\n\nexport class Interceptor<Events extends InterceptorEventMap> {\n protected emitter: Emitter<Events>\n protected subscriptions: Array<InterceptorSubscription>\n protected logger: Logger\n\n public readyState: InterceptorReadyState\n\n constructor(private readonly symbol: symbol) {\n this.readyState = InterceptorReadyState.INACTIVE\n\n this.emitter = new Emitter()\n this.subscriptions = []\n this.logger = new Logger(symbol.description!)\n\n // Do not limit the maximum number of listeners\n // so not to limit the maximum amount of parallel events emitted.\n this.emitter.setMaxListeners(0)\n\n this.logger.info('constructing the interceptor...')\n }\n\n /**\n * Determine if this interceptor can be applied\n * in the current environment.\n */\n protected checkEnvironment(): boolean {\n return true\n }\n\n /**\n * Apply this interceptor to the current process.\n * Returns an already running interceptor instance if it's present.\n */\n public apply(): void {\n const logger = this.logger.extend('apply')\n logger.info('applying the interceptor...')\n\n if (this.readyState === InterceptorReadyState.APPLIED) {\n logger.info('intercepted already applied!')\n return\n }\n\n const shouldApply = this.checkEnvironment()\n\n if (!shouldApply) {\n logger.info('the interceptor cannot be applied in this environment!')\n return\n }\n\n this.readyState = InterceptorReadyState.APPLYING\n\n // Whenever applying a new interceptor, check if it hasn't been applied already.\n // This enables to apply the same interceptor multiple times, for example from a different\n // interceptor, only proxying events but keeping the stubs in a single place.\n const runningInstance = this.getInstance()\n\n if (runningInstance) {\n logger.info('found a running instance, reusing...')\n\n // Proxy any listeners you set on this instance to the running instance.\n this.on = (event, listener) => {\n logger.info('proxying the \"%s\" listener', event)\n\n // Add listeners to the running instance so they appear\n // at the top of the event listeners list and are executed first.\n runningInstance.emitter.addListener(event, listener)\n\n // Ensure that once this interceptor instance is disposed,\n // it removes all listeners it has appended to the running interceptor instance.\n this.subscriptions.push(() => {\n runningInstance.emitter.removeListener(event, listener)\n logger.info('removed proxied \"%s\" listener!', event)\n })\n\n return this\n }\n\n this.readyState = InterceptorReadyState.APPLIED\n\n return\n }\n\n logger.info('no running instance found, setting up a new instance...')\n\n // Setup the interceptor.\n this.setup()\n\n // Store the newly applied interceptor instance globally.\n this.setInstance()\n\n this.readyState = InterceptorReadyState.APPLIED\n }\n\n /**\n * Setup the module augments and stubs necessary for this interceptor.\n * This method is not run if there's a running interceptor instance\n * to prevent instantiating an interceptor multiple times.\n */\n protected setup(): void {}\n\n /**\n * Listen to the interceptor's public events.\n */\n public on<EventName extends ExtractEventNames<Events>>(\n event: EventName,\n listener: Listener<Events[EventName]>\n ): this {\n const logger = this.logger.extend('on')\n\n if (\n this.readyState === InterceptorReadyState.DISPOSING ||\n this.readyState === InterceptorReadyState.DISPOSED\n ) {\n logger.info('cannot listen to events, already disposed!')\n return this\n }\n\n logger.info('adding \"%s\" event listener:', event, listener)\n\n this.emitter.on(event, listener)\n return this\n }\n\n public once<EventName extends ExtractEventNames<Events>>(\n event: EventName,\n listener: Listener<Events[EventName]>\n ): this {\n this.emitter.once(event, listener)\n return this\n }\n\n public off<EventName extends ExtractEventNames<Events>>(\n event: EventName,\n listener: Listener<Events[EventName]>\n ): this {\n this.emitter.off(event, listener)\n return this\n }\n\n public removeAllListeners<EventName extends ExtractEventNames<Events>>(\n event?: EventName\n ): this {\n this.emitter.removeAllListeners(event)\n return this\n }\n\n /**\n * Disposes of any side-effects this interceptor has introduced.\n */\n public dispose(): void {\n const logger = this.logger.extend('dispose')\n\n if (this.readyState === InterceptorReadyState.DISPOSED) {\n logger.info('cannot dispose, already disposed!')\n return\n }\n\n logger.info('disposing the interceptor...')\n this.readyState = InterceptorReadyState.DISPOSING\n\n if (!this.getInstance()) {\n logger.info('no interceptors running, skipping dispose...')\n return\n }\n\n // Delete the global symbol as soon as possible,\n // indicating that the interceptor is no longer running.\n this.clearInstance()\n\n logger.info('global symbol deleted:', getGlobalSymbol(this.symbol))\n\n if (this.subscriptions.length > 0) {\n logger.info('disposing of %d subscriptions...', this.subscriptions.length)\n\n for (const dispose of this.subscriptions) {\n dispose()\n }\n\n this.subscriptions = []\n\n logger.info('disposed of all subscriptions!', this.subscriptions.length)\n }\n\n this.emitter.removeAllListeners()\n logger.info('destroyed the listener!')\n\n this.readyState = InterceptorReadyState.DISPOSED\n }\n\n private getInstance(): this | undefined {\n const instance = getGlobalSymbol<this>(this.symbol)\n this.logger.info('retrieved global instance:', instance?.constructor?.name)\n return instance\n }\n\n private setInstance(): void {\n setGlobalSymbol(this.symbol, this)\n this.logger.info('set global instance!', this.symbol.description)\n }\n\n private clearInstance(): void {\n deleteGlobalSymbol(this.symbol)\n this.logger.info('cleared global instance!', this.symbol.description)\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"]}
|
|
@@ -1,6 +1,105 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__privateAdd,
|
|
3
|
+
__privateGet
|
|
4
|
+
} from "./chunk-Z5TSB3T6.mjs";
|
|
5
|
+
|
|
1
6
|
// src/glossary.ts
|
|
2
7
|
var IS_PATCHED_MODULE = Symbol("isPatchedModule");
|
|
3
8
|
|
|
9
|
+
// src/RequestController.ts
|
|
10
|
+
import { DeferredPromise } from "@open-draft/deferred-promise";
|
|
11
|
+
import { invariant } from "outvariant";
|
|
12
|
+
|
|
13
|
+
// src/InterceptorError.ts
|
|
14
|
+
var InterceptorError = class extends Error {
|
|
15
|
+
constructor(message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "InterceptorError";
|
|
18
|
+
Object.setPrototypeOf(this, InterceptorError.prototype);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// src/RequestController.ts
|
|
23
|
+
var _handled, handled_get;
|
|
24
|
+
var _RequestController = class {
|
|
25
|
+
constructor(request, source) {
|
|
26
|
+
this.request = request;
|
|
27
|
+
this.source = source;
|
|
28
|
+
__privateAdd(this, _handled);
|
|
29
|
+
this.readyState = _RequestController.PENDING;
|
|
30
|
+
this.handled = new DeferredPromise();
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Perform this request as-is.
|
|
34
|
+
*/
|
|
35
|
+
async passthrough() {
|
|
36
|
+
invariant.as(
|
|
37
|
+
InterceptorError,
|
|
38
|
+
this.readyState === _RequestController.PENDING,
|
|
39
|
+
'Failed to passthrough the "%s %s" request: the request has already been handled',
|
|
40
|
+
this.request.method,
|
|
41
|
+
this.request.url
|
|
42
|
+
);
|
|
43
|
+
this.readyState = _RequestController.PASSTHROUGH;
|
|
44
|
+
await this.source.passthrough();
|
|
45
|
+
__privateGet(this, _handled, handled_get).resolve();
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Respond to this request with the given `Response` instance.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* controller.respondWith(new Response())
|
|
52
|
+
* controller.respondWith(Response.json({ id }))
|
|
53
|
+
* controller.respondWith(Response.error())
|
|
54
|
+
*/
|
|
55
|
+
respondWith(response) {
|
|
56
|
+
invariant.as(
|
|
57
|
+
InterceptorError,
|
|
58
|
+
this.readyState === _RequestController.PENDING,
|
|
59
|
+
'Failed to respond to the "%s %s" request with "%d %s": the request has already been handled (%d)',
|
|
60
|
+
this.request.method,
|
|
61
|
+
this.request.url,
|
|
62
|
+
response.status,
|
|
63
|
+
response.statusText || "OK",
|
|
64
|
+
this.readyState
|
|
65
|
+
);
|
|
66
|
+
this.readyState = _RequestController.RESPONSE;
|
|
67
|
+
__privateGet(this, _handled, handled_get).resolve();
|
|
68
|
+
this.source.respondWith(response);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Error this request with the given reason.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* controller.errorWith()
|
|
75
|
+
* controller.errorWith(new Error('Oops!'))
|
|
76
|
+
* controller.errorWith({ message: 'Oops!'})
|
|
77
|
+
*/
|
|
78
|
+
errorWith(reason) {
|
|
79
|
+
invariant.as(
|
|
80
|
+
InterceptorError,
|
|
81
|
+
this.readyState === _RequestController.PENDING,
|
|
82
|
+
'Failed to error the "%s %s" request with "%s": the request has already been handled (%d)',
|
|
83
|
+
this.request.method,
|
|
84
|
+
this.request.url,
|
|
85
|
+
reason == null ? void 0 : reason.toString(),
|
|
86
|
+
this.readyState
|
|
87
|
+
);
|
|
88
|
+
this.readyState = _RequestController.ERROR;
|
|
89
|
+
this.source.errorWith(reason);
|
|
90
|
+
__privateGet(this, _handled, handled_get).resolve();
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
var RequestController = _RequestController;
|
|
94
|
+
_handled = new WeakSet();
|
|
95
|
+
handled_get = function() {
|
|
96
|
+
return this.handled;
|
|
97
|
+
};
|
|
98
|
+
RequestController.PENDING = 0;
|
|
99
|
+
RequestController.PASSTHROUGH = 1;
|
|
100
|
+
RequestController.RESPONSE = 2;
|
|
101
|
+
RequestController.ERROR = 3;
|
|
102
|
+
|
|
4
103
|
// src/utils/canParseUrl.ts
|
|
5
104
|
function canParseUrl(url) {
|
|
6
105
|
try {
|
|
@@ -109,9 +208,11 @@ function setRawRequest(request, rawRequest) {
|
|
|
109
208
|
|
|
110
209
|
export {
|
|
111
210
|
IS_PATCHED_MODULE,
|
|
211
|
+
InterceptorError,
|
|
212
|
+
RequestController,
|
|
112
213
|
canParseUrl,
|
|
113
214
|
FetchResponse,
|
|
114
215
|
getRawRequest,
|
|
115
216
|
setRawRequest
|
|
116
217
|
};
|
|
117
|
-
//# sourceMappingURL=chunk-
|
|
218
|
+
//# sourceMappingURL=chunk-LIKZF2VU.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/glossary.ts","../../src/RequestController.ts","../../src/InterceptorError.ts","../../src/utils/canParseUrl.ts","../../src/utils/getValueBySymbol.ts","../../src/utils/fetchUtils.ts","../../src/getRawRequest.ts"],"sourcesContent":["import type { RequestController } from './RequestController'\n\nexport const IS_PATCHED_MODULE: unique symbol = Symbol('isPatchedModule')\n\n/**\n * @note Export `RequestController` as a type only.\n * It's never meant to be created in the userland.\n */\nexport type { RequestController }\n\nexport type RequestCredentials = 'omit' | 'include' | 'same-origin'\n\nexport type HttpRequestEventMap = {\n request: [\n args: {\n request: Request\n requestId: string\n controller: RequestController\n }\n ]\n response: [\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ]\n unhandledException: [\n args: {\n error: unknown\n request: Request\n requestId: string\n controller: RequestController\n }\n ]\n}\n","import { DeferredPromise } from '@open-draft/deferred-promise'\nimport { invariant } from 'outvariant'\nimport { InterceptorError } from './InterceptorError'\n\nexport interface RequestControllerSource {\n passthrough(): void\n respondWith(response: Response): void\n errorWith(reason?: unknown): void\n}\n\nexport class RequestController {\n static PENDING = 0 as const\n static PASSTHROUGH = 1 as const\n static RESPONSE = 2 as const\n static ERROR = 3 as const\n\n public readyState: number\n\n /**\n * A Promise that resolves when this controller handles a request.\n * See `controller.readyState` for more information on the handling result.\n */\n public handled: Promise<void>\n\n constructor(\n protected readonly request: Request,\n protected readonly source: RequestControllerSource\n ) {\n this.readyState = RequestController.PENDING\n this.handled = new DeferredPromise<void>()\n }\n\n get #handled() {\n return this.handled as DeferredPromise<void>\n }\n\n /**\n * Perform this request as-is.\n */\n public async passthrough(): Promise<void> {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to passthrough the \"%s %s\" request: the request has already been handled',\n this.request.method,\n this.request.url\n )\n\n this.readyState = RequestController.PASSTHROUGH\n await this.source.passthrough()\n this.#handled.resolve()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n *\n * @example\n * controller.respondWith(new Response())\n * controller.respondWith(Response.json({ id }))\n * controller.respondWith(Response.error())\n */\n public respondWith(response: Response): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to respond to the \"%s %s\" request with \"%d %s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n response.status,\n response.statusText || 'OK',\n this.readyState\n )\n\n this.readyState = RequestController.RESPONSE\n this.#handled.resolve()\n\n /**\n * @note Although `source.respondWith()` is potentially asynchronous,\n * do NOT await it for backward-compatibility. Awaiting it will short-circuit\n * the request listener invocation as soon as a listener responds to a request.\n * Ideally, that's what we want, but that's not what we promise the user.\n */\n this.source.respondWith(response)\n }\n\n /**\n * Error this request with the given reason.\n *\n * @example\n * controller.errorWith()\n * controller.errorWith(new Error('Oops!'))\n * controller.errorWith({ message: 'Oops!'})\n */\n public errorWith(reason?: unknown): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to error the \"%s %s\" request with \"%s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n reason?.toString(),\n this.readyState\n )\n\n this.readyState = RequestController.ERROR\n this.source.errorWith(reason)\n this.#handled.resolve()\n }\n}\n","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","/**\n * Returns a boolean indicating whether the given URL string\n * can be parsed into a `URL` instance.\n * A substitute for `URL.canParse()` for Node.js 18.\n */\nexport function canParseUrl(url: string): boolean {\n try {\n new URL(url)\n return true\n } catch (_error) {\n return false\n }\n}\n","/**\n * Returns the value behind the symbol with the given name.\n */\nexport function getValueBySymbol<T>(\n symbolName: string,\n source: object\n): T | undefined {\n const ownSymbols = Object.getOwnPropertySymbols(source)\n\n const symbol = ownSymbols.find((symbol) => {\n return symbol.description === symbolName\n })\n\n if (symbol) {\n return Reflect.get(source, symbol)\n }\n\n return\n}\n","import { canParseUrl } from './canParseUrl'\nimport { getValueBySymbol } from './getValueBySymbol'\n\nexport interface FetchResponseInit extends ResponseInit {\n url?: string\n}\n\ninterface UndiciFetchInternalState {\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\nexport class FetchResponse extends Response {\n /**\n * Response status codes for responses that cannot have body.\n * @see https://fetch.spec.whatwg.org/#statuses\n */\n static readonly STATUS_CODES_WITHOUT_BODY = [101, 103, 204, 205, 304]\n\n static readonly STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308]\n\n static isConfigurableStatusCode(status: number): boolean {\n return status >= 200 && status <= 599\n }\n\n static isRedirectResponse(status: number): boolean {\n return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status)\n }\n\n /**\n * Returns a boolean indicating whether the given response status\n * code represents a response that can have a body.\n */\n static isResponseWithBody(status: number): boolean {\n return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status)\n }\n\n static setUrl(url: string | undefined, response: Response): void {\n if (!url || url === 'about:' || !canParseUrl(url)) {\n return\n }\n\n const state = getValueBySymbol<UndiciFetchInternalState>('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\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 for (let line = 0; line < rawHeaders.length; line += 2) {\n headers.append(rawHeaders[line], rawHeaders[line + 1])\n }\n return headers\n }\n\n constructor(body?: BodyInit | null, init: FetchResponseInit = {}) {\n const status = init.status ?? 200\n const safeStatus = FetchResponse.isConfigurableStatusCode(status)\n ? status\n : 200\n const finalBody = FetchResponse.isResponseWithBody(status) ? body : null\n\n super(finalBody, {\n status: safeStatus,\n statusText: init.statusText,\n headers: init.headers,\n })\n\n if (status !== safeStatus) {\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 state = getValueBySymbol<UndiciFetchInternalState>('state', this)\n\n if (state) {\n state.status = status\n } else {\n Object.defineProperty(this, 'status', {\n value: status,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n }\n\n FetchResponse.setUrl(init.url, this)\n }\n}\n","const kRawRequest = Symbol('kRawRequest')\n\n/**\n * Returns a raw request instance associated with this request.\n *\n * @example\n * interceptor.on('request', ({ request }) => {\n * const rawRequest = getRawRequest(request)\n *\n * if (rawRequest instanceof http.ClientRequest) {\n * console.log(rawRequest.rawHeaders)\n * }\n * })\n */\nexport function getRawRequest(request: Request): unknown | undefined {\n return Reflect.get(request, kRawRequest)\n}\n\nexport function setRawRequest(request: Request, rawRequest: unknown): void {\n Reflect.set(request, kRawRequest, rawRequest)\n}\n"],"mappings":";;;;;;AAEO,IAAM,oBAAmC,OAAO,iBAAiB;;;ACFxE,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;;;ACDnB,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAkB;AAC5B,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,iBAAiB,SAAS;AAAA,EACxD;AACF;;;ADNA;AAUO,IAAM,qBAAN,MAAwB;AAAA,EAc7B,YACqB,SACA,QACnB;AAFmB;AACA;AAMrB,uBAAI;AAJF,SAAK,aAAa,mBAAkB;AACpC,SAAK,UAAU,IAAI,gBAAsB;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA,EASA,MAAa,cAA6B;A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c,yBAAyB,MAAM,IAC5D,SACA;AACJ,UAAM,YAAY,eAAc,mBAAmB,MAAM,IAAI,OAAO;AAEpE,UAAM,WAAW;AAAA,MACf,QAAQ;AAAA,MACR,YAAY,KAAK;AAAA,MACjB,SAAS,KAAK;AAAA,IAChB,CAAC;AAED,QAAI,WAAW,YAAY;AAKzB,YAAM,QAAQ,iBAA2C,SAAS,IAAI;AAEtE,UAAI,OAAO;AACT,cAAM,SAAS;AAAA,MACjB,OAAO;AACL,eAAO,eAAe,MAAM,UAAU;AAAA,UACpC,OAAO;AAAA,UACP,YAAY;AAAA,UACZ,cAAc;AAAA,UACd,UAAU;AAAA,QACZ,CAAC;AAAA,MACH;AAAA,IACF;AAEA,mBAAc,OAAO,KAAK,KAAK,IAAI;AAAA,EACrC;AACF;AA5FO,IAAM,gBAAN;AAAA;AAAA;AAAA;AAAA;AAAM,cAKK,4BAA4B,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG;AALzD,cAOK,6BAA6B,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG;;;ACjCvE,IAAM,cAAc,OAAO,aAAa;AAcjC,SAAS,cAAc,SAAuC;AACnE,SAAO,QAAQ,IAAI,SAAS,WAAW;AACzC;AAEO,SAAS,cAAc,SAAkB,YAA2B;AACzE,UAAQ,IAAI,SAAS,aAAa,UAAU;AAC9C;","names":["symbol"]}
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
var
|
|
4
|
+
var _chunkFW45TRCBjs = require('./chunk-FW45TRCB.js');
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
|
|
11
|
+
var _chunk57RIRQUYjs = require('./chunk-57RIRQUY.js');
|
|
11
12
|
|
|
12
13
|
|
|
13
14
|
|
|
@@ -15,10 +16,11 @@ var _chunk2HUMWGRDjs = require('./chunk-2HUMWGRD.js');
|
|
|
15
16
|
|
|
16
17
|
|
|
17
18
|
|
|
18
|
-
var
|
|
19
|
+
var _chunkJQ2S7G56js = require('./chunk-JQ2S7G56.js');
|
|
19
20
|
|
|
20
21
|
// src/interceptors/fetch/index.ts
|
|
21
22
|
var _outvariant = require('outvariant');
|
|
23
|
+
var _until = require('@open-draft/until');
|
|
22
24
|
var _deferredpromise = require('@open-draft/deferred-promise');
|
|
23
25
|
|
|
24
26
|
// src/interceptors/fetch/utils/createNetworkError.ts
|
|
@@ -167,7 +169,7 @@ function decompressResponse(response) {
|
|
|
167
169
|
}
|
|
168
170
|
|
|
169
171
|
// src/interceptors/fetch/index.ts
|
|
170
|
-
var _FetchInterceptor = class extends
|
|
172
|
+
var _FetchInterceptor = class extends _chunkJQ2S7G56js.Interceptor {
|
|
171
173
|
constructor() {
|
|
172
174
|
super(_FetchInterceptor.symbol);
|
|
173
175
|
}
|
|
@@ -177,37 +179,53 @@ var _FetchInterceptor = class extends _chunkTIPR373Rjs.Interceptor {
|
|
|
177
179
|
async setup() {
|
|
178
180
|
const pureFetch = globalThis.fetch;
|
|
179
181
|
_outvariant.invariant.call(void 0,
|
|
180
|
-
!pureFetch[
|
|
182
|
+
!pureFetch[_chunk57RIRQUYjs.IS_PATCHED_MODULE],
|
|
181
183
|
'Failed to patch the "fetch" module: already patched.'
|
|
182
184
|
);
|
|
183
185
|
globalThis.fetch = async (input, init) => {
|
|
184
|
-
const requestId =
|
|
185
|
-
const resolvedInput = typeof input === "string" && typeof location !== "undefined" && !
|
|
186
|
+
const requestId = _chunkJQ2S7G56js.createRequestId.call(void 0, );
|
|
187
|
+
const resolvedInput = typeof input === "string" && typeof location !== "undefined" && !_chunk57RIRQUYjs.canParseUrl.call(void 0, input) ? new URL(input, location.href) : input;
|
|
186
188
|
const request = new Request(resolvedInput, init);
|
|
187
189
|
if (input instanceof Request) {
|
|
188
|
-
|
|
190
|
+
_chunk57RIRQUYjs.setRawRequest.call(void 0, request, input);
|
|
189
191
|
}
|
|
190
192
|
const responsePromise = new (0, _deferredpromise.DeferredPromise)();
|
|
191
|
-
const controller = new (0,
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
193
|
+
const controller = new (0, _chunk57RIRQUYjs.RequestController)(request, {
|
|
194
|
+
passthrough: async () => {
|
|
195
|
+
this.logger.info("request has not been handled, passthrough...");
|
|
196
|
+
const requestCloneForResponseEvent = request.clone();
|
|
197
|
+
const { error: responseError, data: originalResponse } = await _until.until.call(void 0,
|
|
198
|
+
() => pureFetch(request)
|
|
199
|
+
);
|
|
200
|
+
if (responseError) {
|
|
201
|
+
return responsePromise.reject(responseError);
|
|
202
|
+
}
|
|
203
|
+
this.logger.info("original fetch performed", originalResponse);
|
|
204
|
+
if (this.emitter.listenerCount("response") > 0) {
|
|
205
|
+
this.logger.info('emitting the "response" event...');
|
|
206
|
+
const responseClone = originalResponse.clone();
|
|
207
|
+
await _chunk2HUMWGRDjs.emitAsync.call(void 0, this.emitter, "response", {
|
|
208
|
+
response: responseClone,
|
|
209
|
+
isMockedResponse: false,
|
|
210
|
+
request: requestCloneForResponseEvent,
|
|
211
|
+
requestId
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
responsePromise.resolve(originalResponse);
|
|
215
|
+
},
|
|
216
|
+
respondWith: async (rawResponse) => {
|
|
217
|
+
if (_chunkFW45TRCBjs.isResponseError.call(void 0, rawResponse)) {
|
|
218
|
+
this.logger.info("request has errored!", { response: rawResponse });
|
|
219
|
+
responsePromise.reject(createNetworkError(rawResponse));
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
204
222
|
this.logger.info("received mocked response!", {
|
|
205
223
|
rawResponse
|
|
206
224
|
});
|
|
207
225
|
const decompressedStream = decompressResponse(rawResponse);
|
|
208
|
-
const response = decompressedStream === null ? rawResponse : new (0,
|
|
209
|
-
|
|
210
|
-
if (
|
|
226
|
+
const response = decompressedStream === null ? rawResponse : new (0, _chunk57RIRQUYjs.FetchResponse)(decompressedStream, rawResponse);
|
|
227
|
+
_chunk57RIRQUYjs.FetchResponse.setUrl(request.url, response);
|
|
228
|
+
if (_chunk57RIRQUYjs.FetchResponse.isRedirectResponse(response.status)) {
|
|
211
229
|
if (request.redirect === "error") {
|
|
212
230
|
responsePromise.reject(createNetworkError("unexpected redirect"));
|
|
213
231
|
return;
|
|
@@ -238,45 +256,32 @@ var _FetchInterceptor = class extends _chunkTIPR373Rjs.Interceptor {
|
|
|
238
256
|
}
|
|
239
257
|
responsePromise.resolve(response);
|
|
240
258
|
},
|
|
241
|
-
|
|
242
|
-
this.logger.info("request has
|
|
243
|
-
responsePromise.reject(
|
|
244
|
-
},
|
|
245
|
-
onError: (error) => {
|
|
246
|
-
this.logger.info("request has been aborted!", { error });
|
|
247
|
-
responsePromise.reject(error);
|
|
259
|
+
errorWith: (reason) => {
|
|
260
|
+
this.logger.info("request has been aborted!", { reason });
|
|
261
|
+
responsePromise.reject(reason);
|
|
248
262
|
}
|
|
249
263
|
});
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
return responsePromise;
|
|
253
|
-
}
|
|
264
|
+
this.logger.info("[%s] %s", request.method, request.url);
|
|
265
|
+
this.logger.info("awaiting for the mocked response...");
|
|
254
266
|
this.logger.info(
|
|
255
|
-
|
|
267
|
+
'emitting the "request" event for %s listener(s)...',
|
|
268
|
+
this.emitter.listenerCount("request")
|
|
256
269
|
);
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
const responseClone = response.clone();
|
|
263
|
-
await _chunk2HUMWGRDjs.emitAsync.call(void 0, this.emitter, "response", {
|
|
264
|
-
response: responseClone,
|
|
265
|
-
isMockedResponse: false,
|
|
266
|
-
request: requestCloneForResponseEvent,
|
|
267
|
-
requestId
|
|
268
|
-
});
|
|
269
|
-
}
|
|
270
|
-
return response;
|
|
270
|
+
await _chunkFW45TRCBjs.handleRequest.call(void 0, {
|
|
271
|
+
request,
|
|
272
|
+
requestId,
|
|
273
|
+
emitter: this.emitter,
|
|
274
|
+
controller
|
|
271
275
|
});
|
|
276
|
+
return responsePromise;
|
|
272
277
|
};
|
|
273
|
-
Object.defineProperty(globalThis.fetch,
|
|
278
|
+
Object.defineProperty(globalThis.fetch, _chunk57RIRQUYjs.IS_PATCHED_MODULE, {
|
|
274
279
|
enumerable: true,
|
|
275
280
|
configurable: true,
|
|
276
281
|
value: true
|
|
277
282
|
});
|
|
278
283
|
this.subscriptions.push(() => {
|
|
279
|
-
Object.defineProperty(globalThis.fetch,
|
|
284
|
+
Object.defineProperty(globalThis.fetch, _chunk57RIRQUYjs.IS_PATCHED_MODULE, {
|
|
280
285
|
value: void 0
|
|
281
286
|
});
|
|
282
287
|
globalThis.fetch = pureFetch;
|
|
@@ -293,4 +298,4 @@ FetchInterceptor.symbol = Symbol("fetch");
|
|
|
293
298
|
|
|
294
299
|
|
|
295
300
|
exports.FetchInterceptor = FetchInterceptor;
|
|
296
|
-
//# sourceMappingURL=chunk-
|
|
301
|
+
//# sourceMappingURL=chunk-MNT2FUCH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/interceptors/fetch/index.ts","../../src/interceptors/fetch/utils/createNetworkError.ts","../../src/interceptors/fetch/utils/followRedirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.browser.ts","../../src/interceptors/fetch/utils/decompression.ts"],"names":["readable","transformers","response"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,aAAa;AACtB,SAAS,uBAAuB;;;ACFzB,SAAS,mBAAmB,OAAiB;AAClD,SAAO,OAAO,OAAO,IAAI,UAAU,iBAAiB,GAAG;AAAA,IACrD;AAAA,EACF,CAAC;AACH;;;ACFA,IAAM,uBAAuB;AAAA,EAC3B;AAAA,E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,cAAc;AAAA,MACd,OAAO;AAAA,IACT,CAAC;AAED,SAAK,cAAc,KAAK,MAAM;AAC5B,aAAO,eAAe,WAAW,OAAO,mBAAmB;AAAA,QACzD,OAAO;AAAA,MACT,CAAC;AAED,iBAAW,QAAQ;AAEnB,WAAK,OAAO;AAAA,QACV;AAAA,QACA,WAAW,MAAM;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAnMO,IAAM,mBAAN;AAAM,iBACJ,SAAS,OAAO,OAAO","sourcesContent":["import { invariant } from 'outvariant'\nimport { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\n\nexport class FetchInterceptor extends Interceptor<HttpRequestEventMap> {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const pureFetch = globalThis.fetch\n\n invariant(\n !(pureFetch as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"fetch\" module: already patched.'\n )\n\n globalThis.fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new Request(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise<Response>()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = originalResponse.clone()\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response =\n decompressedStream === null\n ? rawResponse\n : new FetchResponse(decompressedStream, rawResponse)\n\n FetchResponse.setUrl(request.url, response)\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: response.clone(),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.fetch = pureFetch\n\n this.logger.info(\n 'restored native \"globalThis.fetch\"!',\n globalThis.fetch.name\n )\n })\n }\n}\n","export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise<Response> {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","export class BrotliDecompressionStream extends TransformStream {\n constructor() {\n console.warn(\n '[Interceptors]: Brotli decompression of response streams is not supported in the browser'\n )\n\n super({\n transform(chunk, controller) {\n // Keep the stream as passthrough, it does nothing.\n controller.enqueue(chunk)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array<TransformStream>,\n ...strategies: Array<QueuingStrategy>\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array<string> {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight<Array<TransformStream>>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream<any> | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n"]}
|