@mswjs/interceptors 0.20.0 → 0.21.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.
Files changed (176) hide show
  1. package/README.md +7 -7
  2. package/lib/browser/Interceptor-959f650e.d.ts +104 -0
  3. package/lib/browser/chunk-5B525MKF.mjs +2139 -0
  4. package/lib/browser/chunk-BQYA7ER5.mjs +258 -0
  5. package/lib/browser/chunk-IIY3SHU3.js +2139 -0
  6. package/lib/browser/chunk-QWL3EOEY.js +258 -0
  7. package/lib/browser/chunk-STA6QBYM.mjs +64 -0
  8. package/lib/browser/chunk-ZJOF5MEZ.js +64 -0
  9. package/lib/browser/index.d.ts +31 -0
  10. package/lib/browser/index.js +51 -0
  11. package/lib/browser/index.mjs +51 -0
  12. package/lib/browser/interceptors/XMLHttpRequest/index.d.ts +14 -0
  13. package/lib/browser/interceptors/XMLHttpRequest/index.js +657 -0
  14. package/lib/browser/interceptors/XMLHttpRequest/index.mjs +657 -0
  15. package/lib/browser/interceptors/fetch/index.d.ts +12 -0
  16. package/lib/browser/interceptors/fetch/index.js +94 -0
  17. package/lib/browser/interceptors/fetch/index.mjs +94 -0
  18. package/lib/node/BatchInterceptor-a7261b26.d.ts +21 -0
  19. package/lib/node/Interceptor-997045eb.d.ts +104 -0
  20. package/lib/{RemoteHttpInterceptor.d.ts → node/RemoteHttpInterceptor.d.ts} +17 -12
  21. package/lib/node/RemoteHttpInterceptor.js +176 -0
  22. package/lib/node/RemoteHttpInterceptor.mjs +176 -0
  23. package/lib/node/chunk-6GWWOJ23.js +29 -0
  24. package/lib/node/chunk-6V3JXLBF.js +6093 -0
  25. package/lib/node/chunk-CIN5URNI.mjs +29 -0
  26. package/lib/node/chunk-FCIAOT7W.mjs +660 -0
  27. package/lib/node/chunk-GFH37L5D.mjs +6 -0
  28. package/lib/node/chunk-HDUJCCWF.js +661 -0
  29. package/lib/node/chunk-JISWS3Y3.mjs +31 -0
  30. package/lib/node/chunk-KZJG2UW7.js +31 -0
  31. package/lib/node/chunk-NNVTJLQA.mjs +6093 -0
  32. package/lib/node/chunk-QMIXLBOU.js +291 -0
  33. package/lib/node/chunk-STA6QBYM.mjs +64 -0
  34. package/lib/node/chunk-VKKFXSTL.js +660 -0
  35. package/lib/node/chunk-VQ4DZOBB.js +6 -0
  36. package/lib/node/chunk-ZJOF5MEZ.js +64 -0
  37. package/lib/node/chunk-ZSI7MX3V.mjs +291 -0
  38. package/lib/node/chunk-ZWCZGO3W.mjs +661 -0
  39. package/lib/node/index.d.ts +14 -0
  40. package/lib/node/index.js +32 -0
  41. package/lib/node/index.mjs +32 -0
  42. package/lib/node/interceptors/ClientRequest/index.d.ts +22 -0
  43. package/lib/node/interceptors/ClientRequest/index.js +9 -0
  44. package/lib/node/interceptors/ClientRequest/index.mjs +9 -0
  45. package/lib/node/interceptors/XMLHttpRequest/index.d.ts +14 -0
  46. package/lib/node/interceptors/XMLHttpRequest/index.js +11 -0
  47. package/lib/node/interceptors/XMLHttpRequest/index.mjs +11 -0
  48. package/lib/node/interceptors/fetch/index.d.ts +12 -0
  49. package/lib/node/interceptors/fetch/index.js +96 -0
  50. package/lib/node/interceptors/fetch/index.mjs +96 -0
  51. package/package.json +58 -9
  52. package/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts +1 -1
  53. package/src/shims/webEncoding.ts +9 -0
  54. package/src/utils/bufferUtils.ts +1 -1
  55. package/lib/BatchInterceptor.d.ts +0 -18
  56. package/lib/BatchInterceptor.js +0 -34
  57. package/lib/BatchInterceptor.js.map +0 -1
  58. package/lib/Interceptor.d.ts +0 -50
  59. package/lib/Interceptor.js +0 -172
  60. package/lib/Interceptor.js.map +0 -1
  61. package/lib/RemoteHttpInterceptor.js +0 -158
  62. package/lib/RemoteHttpInterceptor.js.map +0 -1
  63. package/lib/glossary.d.ts +0 -7
  64. package/lib/glossary.js +0 -5
  65. package/lib/glossary.js.map +0 -1
  66. package/lib/index.d.ts +0 -5
  67. package/lib/index.js +0 -23
  68. package/lib/index.js.map +0 -1
  69. package/lib/interceptors/ClientRequest/NodeClientRequest.d.ts +0 -46
  70. package/lib/interceptors/ClientRequest/NodeClientRequest.js +0 -325
  71. package/lib/interceptors/ClientRequest/NodeClientRequest.js.map +0 -1
  72. package/lib/interceptors/ClientRequest/http.get.d.ts +0 -4
  73. package/lib/interceptors/ClientRequest/http.get.js +0 -19
  74. package/lib/interceptors/ClientRequest/http.get.js.map +0 -1
  75. package/lib/interceptors/ClientRequest/http.request.d.ts +0 -4
  76. package/lib/interceptors/ClientRequest/http.request.js +0 -16
  77. package/lib/interceptors/ClientRequest/http.request.js.map +0 -1
  78. package/lib/interceptors/ClientRequest/index.d.ts +0 -19
  79. package/lib/interceptors/ClientRequest/index.js +0 -50
  80. package/lib/interceptors/ClientRequest/index.js.map +0 -1
  81. package/lib/interceptors/ClientRequest/utils/cloneIncomingMessage.d.ts +0 -10
  82. package/lib/interceptors/ClientRequest/utils/cloneIncomingMessage.js +0 -60
  83. package/lib/interceptors/ClientRequest/utils/cloneIncomingMessage.js.map +0 -1
  84. package/lib/interceptors/ClientRequest/utils/createRequest.d.ts +0 -6
  85. package/lib/interceptors/ClientRequest/utils/createRequest.js +0 -30
  86. package/lib/interceptors/ClientRequest/utils/createRequest.js.map +0 -1
  87. package/lib/interceptors/ClientRequest/utils/createResponse.d.ts +0 -8
  88. package/lib/interceptors/ClientRequest/utils/createResponse.js +0 -24
  89. package/lib/interceptors/ClientRequest/utils/createResponse.js.map +0 -1
  90. package/lib/interceptors/ClientRequest/utils/getIncomingMessageBody.d.ts +0 -3
  91. package/lib/interceptors/ClientRequest/utils/getIncomingMessageBody.js +0 -57
  92. package/lib/interceptors/ClientRequest/utils/getIncomingMessageBody.js.map +0 -1
  93. package/lib/interceptors/ClientRequest/utils/normalizeClientRequestArgs.d.ts +0 -17
  94. package/lib/interceptors/ClientRequest/utils/normalizeClientRequestArgs.js +0 -151
  95. package/lib/interceptors/ClientRequest/utils/normalizeClientRequestArgs.js.map +0 -1
  96. package/lib/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.d.ts +0 -15
  97. package/lib/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.js +0 -33
  98. package/lib/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.js.map +0 -1
  99. package/lib/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.d.ts +0 -13
  100. package/lib/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.js +0 -20
  101. package/lib/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.js.map +0 -1
  102. package/lib/interceptors/XMLHttpRequest/XMLHttpRequestController.d.ts +0 -44
  103. package/lib/interceptors/XMLHttpRequest/XMLHttpRequestController.js +0 -413
  104. package/lib/interceptors/XMLHttpRequest/XMLHttpRequestController.js.map +0 -1
  105. package/lib/interceptors/XMLHttpRequest/XMLHttpRequestProxy.d.ts +0 -20
  106. package/lib/interceptors/XMLHttpRequest/XMLHttpRequestProxy.js +0 -75
  107. package/lib/interceptors/XMLHttpRequest/XMLHttpRequestProxy.js.map +0 -1
  108. package/lib/interceptors/XMLHttpRequest/index.d.ts +0 -12
  109. package/lib/interceptors/XMLHttpRequest/index.js +0 -41
  110. package/lib/interceptors/XMLHttpRequest/index.js.map +0 -1
  111. package/lib/interceptors/XMLHttpRequest/polyfills/EventPolyfill.d.ts +0 -31
  112. package/lib/interceptors/XMLHttpRequest/polyfills/EventPolyfill.js +0 -44
  113. package/lib/interceptors/XMLHttpRequest/polyfills/EventPolyfill.js.map +0 -1
  114. package/lib/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.d.ts +0 -8
  115. package/lib/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.js +0 -15
  116. package/lib/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.js.map +0 -1
  117. package/lib/interceptors/XMLHttpRequest/utils/concatArrayBuffer.d.ts +0 -4
  118. package/lib/interceptors/XMLHttpRequest/utils/concatArrayBuffer.js +0 -14
  119. package/lib/interceptors/XMLHttpRequest/utils/concatArrayBuffer.js.map +0 -1
  120. package/lib/interceptors/XMLHttpRequest/utils/createEvent.d.ts +0 -2
  121. package/lib/interceptors/XMLHttpRequest/utils/createEvent.js +0 -37
  122. package/lib/interceptors/XMLHttpRequest/utils/createEvent.js.map +0 -1
  123. package/lib/interceptors/XMLHttpRequest/utils/createResponse.d.ts +0 -2
  124. package/lib/interceptors/XMLHttpRequest/utils/createResponse.js +0 -14
  125. package/lib/interceptors/XMLHttpRequest/utils/createResponse.js.map +0 -1
  126. package/lib/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.d.ts +0 -1
  127. package/lib/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.js +0 -17
  128. package/lib/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.js.map +0 -1
  129. package/lib/interceptors/fetch/index.d.ts +0 -8
  130. package/lib/interceptors/fetch/index.js +0 -81
  131. package/lib/interceptors/fetch/index.js.map +0 -1
  132. package/lib/presets/browser.d.ts +0 -8
  133. package/lib/presets/browser.js +0 -10
  134. package/lib/presets/browser.js.map +0 -1
  135. package/lib/presets/node.d.ts +0 -8
  136. package/lib/presets/node.js +0 -10
  137. package/lib/presets/node.js.map +0 -1
  138. package/lib/utils/AsyncEventEmitter.d.ts +0 -33
  139. package/lib/utils/AsyncEventEmitter.js +0 -148
  140. package/lib/utils/AsyncEventEmitter.js.map +0 -1
  141. package/lib/utils/bufferUtils.d.ts +0 -8
  142. package/lib/utils/bufferUtils.js +0 -24
  143. package/lib/utils/bufferUtils.js.map +0 -1
  144. package/lib/utils/cloneObject.d.ts +0 -1
  145. package/lib/utils/cloneObject.js +0 -28
  146. package/lib/utils/cloneObject.js.map +0 -1
  147. package/lib/utils/createLazyCallback.d.ts +0 -11
  148. package/lib/utils/createLazyCallback.js +0 -40
  149. package/lib/utils/createLazyCallback.js.map +0 -1
  150. package/lib/utils/createProxy.d.ts +0 -8
  151. package/lib/utils/createProxy.js +0 -45
  152. package/lib/utils/createProxy.js.map +0 -1
  153. package/lib/utils/getCleanUrl.d.ts +0 -4
  154. package/lib/utils/getCleanUrl.js +0 -11
  155. package/lib/utils/getCleanUrl.js.map +0 -1
  156. package/lib/utils/getRequestOptionsByUrl.d.ts +0 -8
  157. package/lib/utils/getRequestOptionsByUrl.js +0 -28
  158. package/lib/utils/getRequestOptionsByUrl.js.map +0 -1
  159. package/lib/utils/getUrlByRequestOptions.d.ts +0 -11
  160. package/lib/utils/getUrlByRequestOptions.js +0 -78
  161. package/lib/utils/getUrlByRequestOptions.js.map +0 -1
  162. package/lib/utils/isObject.d.ts +0 -4
  163. package/lib/utils/isObject.js +0 -11
  164. package/lib/utils/isObject.js.map +0 -1
  165. package/lib/utils/nextTick.d.ts +0 -2
  166. package/lib/utils/nextTick.js +0 -16
  167. package/lib/utils/nextTick.js.map +0 -1
  168. package/lib/utils/parseJson.d.ts +0 -5
  169. package/lib/utils/parseJson.js +0 -18
  170. package/lib/utils/parseJson.js.map +0 -1
  171. package/lib/utils/toInteractiveRequest.d.ts +0 -7
  172. package/lib/utils/toInteractiveRequest.js +0 -20
  173. package/lib/utils/toInteractiveRequest.js.map +0 -1
  174. package/lib/utils/uuid.d.ts +0 -1
  175. package/lib/utils/uuid.js +0 -12
  176. package/lib/utils/uuid.js.map +0 -1
@@ -0,0 +1,660 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
+
3
+
4
+
5
+ var _chunk6V3JXLBFjs = require('./chunk-6V3JXLBF.js');
6
+
7
+
8
+
9
+ var _chunkZJOF5MEZjs = require('./chunk-ZJOF5MEZ.js');
10
+
11
+
12
+
13
+ var _chunkQMIXLBOUjs = require('./chunk-QMIXLBOU.js');
14
+
15
+ // src/interceptors/ClientRequest/index.ts
16
+ var _http = require('http'); var _http2 = _interopRequireDefault(_http);
17
+ var _https = require('https'); var _https2 = _interopRequireDefault(_https);
18
+
19
+ // src/interceptors/ClientRequest/NodeClientRequest.ts
20
+
21
+ var _until = require('@open-draft/until');
22
+
23
+ // src/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.ts
24
+ var debug = _chunkQMIXLBOUjs.__require.call(void 0, "debug")("http normalizeClientRequestEndArgs");
25
+ function normalizeClientRequestEndArgs(...args) {
26
+ debug("arguments", args);
27
+ const normalizedArgs = new Array(3).fill(null).map((value, index) => args[index] || value);
28
+ normalizedArgs.sort((a, b) => {
29
+ if (typeof a === "function") {
30
+ return 1;
31
+ }
32
+ if (typeof b === "function") {
33
+ return -1;
34
+ }
35
+ if (typeof a === "string" && typeof b === "string") {
36
+ return normalizedArgs.indexOf(a) - normalizedArgs.indexOf(b);
37
+ }
38
+ return 0;
39
+ });
40
+ debug("normalized args", normalizedArgs);
41
+ return normalizedArgs;
42
+ }
43
+
44
+ // src/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.ts
45
+ var _debug = require('debug');
46
+ var log = _debug.debug.call(void 0, "http normalizeWriteArgs");
47
+ function normalizeClientRequestWriteArgs(args) {
48
+ log("normalizing ClientRequest.write arguments...", args);
49
+ const chunk = args[0];
50
+ const encoding = typeof args[1] === "string" ? args[1] : void 0;
51
+ const callback = typeof args[1] === "function" ? args[1] : args[2];
52
+ const writeArgs = [
53
+ chunk,
54
+ encoding,
55
+ callback
56
+ ];
57
+ log("successfully normalized ClientRequest.write arguments:", writeArgs);
58
+ return writeArgs;
59
+ }
60
+
61
+ // src/interceptors/ClientRequest/utils/cloneIncomingMessage.ts
62
+
63
+ var _stream = require('stream');
64
+ var IS_CLONE = Symbol("isClone");
65
+ function cloneIncomingMessage(message) {
66
+ const clone = message.pipe(new (0, _stream.PassThrough)());
67
+ inheritProperties(message, clone);
68
+ const clonedPrototype = Object.create(_http.IncomingMessage.prototype);
69
+ getPrototypes(clone).forEach((prototype) => {
70
+ inheritProperties(prototype, clonedPrototype);
71
+ });
72
+ Object.setPrototypeOf(clone, clonedPrototype);
73
+ Object.defineProperty(clone, IS_CLONE, {
74
+ enumerable: true,
75
+ value: true
76
+ });
77
+ return clone;
78
+ }
79
+ function getPrototypes(source) {
80
+ const prototypes = [];
81
+ let current = source;
82
+ while (current = Object.getPrototypeOf(current)) {
83
+ prototypes.push(current);
84
+ }
85
+ return prototypes;
86
+ }
87
+ function inheritProperties(source, target) {
88
+ const properties = [
89
+ ...Object.getOwnPropertyNames(source),
90
+ ...Object.getOwnPropertySymbols(source)
91
+ ];
92
+ for (const property of properties) {
93
+ if (target.hasOwnProperty(property)) {
94
+ continue;
95
+ }
96
+ const descriptor = Object.getOwnPropertyDescriptor(source, property);
97
+ if (!descriptor) {
98
+ continue;
99
+ }
100
+ Object.defineProperty(target, property, descriptor);
101
+ }
102
+ }
103
+
104
+ // src/interceptors/ClientRequest/utils/createResponse.ts
105
+ var _headerspolyfill = require('headers-polyfill');
106
+ function createResponse(message) {
107
+ const readable = new (0, _chunk6V3JXLBFjs.ReadableStream)({
108
+ start(controller) {
109
+ message.on("data", (chunk) => controller.enqueue(chunk));
110
+ message.on("end", () => controller.close());
111
+ }
112
+ });
113
+ return new (0, _chunk6V3JXLBFjs.Response)(readable, {
114
+ status: message.statusCode,
115
+ statusText: message.statusMessage,
116
+ headers: _headerspolyfill.objectToHeaders.call(void 0, message.headers)
117
+ });
118
+ }
119
+
120
+ // src/interceptors/ClientRequest/utils/createRequest.ts
121
+
122
+ function createRequest(clientRequest) {
123
+ const headers = new (0, _headerspolyfill.Headers)();
124
+ const outgoingHeaders = clientRequest.getHeaders();
125
+ for (const headerName in outgoingHeaders) {
126
+ const headerValue = outgoingHeaders[headerName];
127
+ if (!headerValue) {
128
+ continue;
129
+ }
130
+ const valuesList = Array.prototype.concat([], headerValue);
131
+ for (const value of valuesList) {
132
+ headers.append(headerName, value.toString());
133
+ }
134
+ }
135
+ return new (0, _chunk6V3JXLBFjs.Request)(clientRequest.url, {
136
+ method: clientRequest.method || "GET",
137
+ headers,
138
+ credentials: "same-origin",
139
+ body: clientRequest.requestBuffer
140
+ });
141
+ }
142
+
143
+ // src/interceptors/ClientRequest/NodeClientRequest.ts
144
+ var _NodeClientRequest = class extends _http.ClientRequest {
145
+ constructor([url, requestOptions, callback], options) {
146
+ super(requestOptions, callback);
147
+ this.chunks = [];
148
+ this.responseSource = "mock";
149
+ this.log = options.log.extend(
150
+ `request ${requestOptions.method} ${url.href}`
151
+ );
152
+ this.log("constructing ClientRequest using options:", {
153
+ url,
154
+ requestOptions,
155
+ callback
156
+ });
157
+ this.url = url;
158
+ this.emitter = options.emitter;
159
+ this.requestBuffer = null;
160
+ this.response = new (0, _http.IncomingMessage)(this.socket);
161
+ }
162
+ writeRequestBodyChunk(chunk, encoding) {
163
+ if (chunk == null) {
164
+ return;
165
+ }
166
+ if (this.requestBuffer == null) {
167
+ this.requestBuffer = Buffer.from([]);
168
+ }
169
+ const resolvedChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding);
170
+ this.requestBuffer = Buffer.concat([this.requestBuffer, resolvedChunk]);
171
+ }
172
+ write(...args) {
173
+ var _a;
174
+ const [chunk, encoding, callback] = normalizeClientRequestWriteArgs(args);
175
+ this.log("write:", { chunk, encoding, callback });
176
+ this.chunks.push({ chunk, encoding });
177
+ this.writeRequestBodyChunk(chunk, encoding);
178
+ this.log("chunk successfully stored!", (_a = this.requestBuffer) == null ? void 0 : _a.byteLength);
179
+ if (!chunk || chunk.length === 0) {
180
+ this.log("written chunk is empty, skipping callback...");
181
+ } else {
182
+ callback == null ? void 0 : callback();
183
+ }
184
+ return true;
185
+ }
186
+ end(...args) {
187
+ this.log("end", args);
188
+ const requestId = _chunkZJOF5MEZjs.uuidv4.call(void 0, );
189
+ const [chunk, encoding, callback] = normalizeClientRequestEndArgs(...args);
190
+ this.log("normalized arguments:", { chunk, encoding, callback });
191
+ this.writeRequestBodyChunk(chunk, encoding || void 0);
192
+ const capturedRequest = createRequest(this);
193
+ const interactiveRequest = _chunkZJOF5MEZjs.toInteractiveRequest.call(void 0, capturedRequest);
194
+ if (this.getHeader("X-Request-Id") != null) {
195
+ this.removeHeader("X-Request-Id");
196
+ return this.passthrough(chunk, encoding, callback);
197
+ }
198
+ this.log(
199
+ 'emitting the "request" event for %d listener(s)...',
200
+ this.emitter.listenerCount("request")
201
+ );
202
+ this.emitter.emit("request", interactiveRequest, requestId);
203
+ _until.until.call(void 0, async () => {
204
+ await this.emitter.untilIdle(
205
+ "request",
206
+ ({ args: [, pendingRequestId] }) => {
207
+ return pendingRequestId === requestId;
208
+ }
209
+ );
210
+ const [mockedResponse] = await interactiveRequest.respondWith.invoked();
211
+ this.log("event.respondWith called with:", mockedResponse);
212
+ return mockedResponse;
213
+ }).then(([resolverException, mockedResponse]) => {
214
+ this.log("the listeners promise awaited!");
215
+ if (resolverException) {
216
+ this.log(
217
+ "encountered resolver exception, aborting request...",
218
+ resolverException
219
+ );
220
+ this.emit("error", resolverException);
221
+ this.terminate();
222
+ return this;
223
+ }
224
+ for (const [headerName, headerValue] of capturedRequest.headers) {
225
+ this.setHeader(headerName, headerValue);
226
+ }
227
+ if (mockedResponse) {
228
+ const responseClone = mockedResponse.clone();
229
+ this.log("received mocked response:", mockedResponse);
230
+ this.responseSource = "mock";
231
+ this.respondWith(mockedResponse);
232
+ this.log(mockedResponse.status, mockedResponse.statusText, "(MOCKED)");
233
+ callback == null ? void 0 : callback();
234
+ this.log('emitting the custom "response" event...');
235
+ this.emitter.emit("response", responseClone, capturedRequest, requestId);
236
+ this.log("request (mock) is completed");
237
+ return this;
238
+ }
239
+ this.log("no mocked response received!");
240
+ this.once("response-internal", (message) => {
241
+ this.log(message.statusCode, message.statusMessage);
242
+ this.log("original response headers:", message.headers);
243
+ this.log('emitting the custom "response" event...');
244
+ this.emitter.emit(
245
+ "response",
246
+ createResponse(message),
247
+ capturedRequest,
248
+ requestId
249
+ );
250
+ });
251
+ return this.passthrough(chunk, encoding, callback);
252
+ });
253
+ return this;
254
+ }
255
+ emit(event, ...data) {
256
+ this.log("emit: %s", event);
257
+ if (event === "response") {
258
+ this.log('found "response" event, cloning the response...');
259
+ try {
260
+ const response = data[0];
261
+ const firstClone = cloneIncomingMessage(response);
262
+ const secondClone = cloneIncomingMessage(response);
263
+ this.emit("response-internal", secondClone);
264
+ this.log('response successfully cloned, emitting "response" event...');
265
+ return super.emit(event, firstClone, ...data.slice(1));
266
+ } catch (error) {
267
+ this.log("error when cloning response:", error);
268
+ return super.emit(event, ...data);
269
+ }
270
+ }
271
+ if (event === "error") {
272
+ const error = data[0];
273
+ const errorCode = error.code || "";
274
+ this.log("error:\n", error);
275
+ if (this.responseSource === "mock" && _NodeClientRequest.suppressErrorCodes.includes(errorCode)) {
276
+ if (!this.capturedError) {
277
+ this.capturedError = error;
278
+ this.log("captured the first error:", this.capturedError);
279
+ }
280
+ return false;
281
+ }
282
+ }
283
+ return super.emit(event, ...data);
284
+ }
285
+ passthrough(chunk, encoding, callback) {
286
+ this.responseSource = "bypass";
287
+ if (this.capturedError) {
288
+ this.emit("error", this.capturedError);
289
+ return this;
290
+ }
291
+ this.log("writing request chunks...", this.chunks);
292
+ for (const { chunk: chunk2, encoding: encoding2 } of this.chunks) {
293
+ if (encoding2) {
294
+ super.write(chunk2, encoding2);
295
+ } else {
296
+ super.write(chunk2);
297
+ }
298
+ }
299
+ this.once("error", (error) => {
300
+ this.log("original request error:", error);
301
+ });
302
+ this.once("abort", () => {
303
+ this.log("original request aborted!");
304
+ });
305
+ this.once("response-internal", (message) => {
306
+ this.log(message.statusCode, message.statusMessage);
307
+ this.log("original response headers:", message.headers);
308
+ });
309
+ this.log("performing original request...");
310
+ return super.end(...[chunk, encoding, callback].filter(Boolean));
311
+ }
312
+ respondWith(mockedResponse) {
313
+ this.log("responding with a mocked response...", mockedResponse);
314
+ const { status, statusText, headers, body } = mockedResponse;
315
+ this.response.statusCode = status;
316
+ this.response.statusMessage = statusText;
317
+ if (headers) {
318
+ this.response.headers = {};
319
+ headers.forEach((headerValue, headerName) => {
320
+ this.response.rawHeaders.push(headerName, headerValue);
321
+ const insensitiveHeaderName = headerName.toLowerCase();
322
+ const prevHeaders = this.response.headers[insensitiveHeaderName];
323
+ this.response.headers[insensitiveHeaderName] = prevHeaders ? Array.prototype.concat([], prevHeaders, headerValue) : headerValue;
324
+ });
325
+ }
326
+ this.log("mocked response headers ready:", headers);
327
+ const closeResponseStream = () => {
328
+ this.response.push(null);
329
+ this.response.complete = true;
330
+ };
331
+ if (body) {
332
+ const bodyReader = body.getReader();
333
+ const readNextChunk = async () => {
334
+ const { done, value } = await bodyReader.read();
335
+ if (done) {
336
+ closeResponseStream();
337
+ return;
338
+ }
339
+ this.response.push(value);
340
+ return readNextChunk();
341
+ };
342
+ readNextChunk();
343
+ } else {
344
+ closeResponseStream();
345
+ }
346
+ this.res = this.response;
347
+ this.finished = true;
348
+ Object.defineProperty(this, "writableEnded", {
349
+ value: true
350
+ });
351
+ this.emit("finish");
352
+ this.emit("response", this.response);
353
+ this.terminate();
354
+ }
355
+ terminate() {
356
+ var _a;
357
+ (_a = this.agent) == null ? void 0 : _a.destroy();
358
+ }
359
+ };
360
+ var NodeClientRequest = _NodeClientRequest;
361
+ NodeClientRequest.suppressErrorCodes = [
362
+ "ENOTFOUND",
363
+ "ECONNREFUSED",
364
+ "ECONNRESET",
365
+ "EAI_AGAIN"
366
+ ];
367
+
368
+ // src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts
369
+
370
+
371
+
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
+ // src/utils/getRequestOptionsByUrl.ts
380
+ function getRequestOptionsByUrl(url) {
381
+ const options = {
382
+ method: "GET",
383
+ protocol: url.protocol,
384
+ hostname: typeof url.hostname === "string" && url.hostname.startsWith("[") ? url.hostname.slice(1, -1) : url.hostname,
385
+ host: url.host,
386
+ path: `${url.pathname}${url.search || ""}`
387
+ };
388
+ if (!!url.port) {
389
+ options.port = Number(url.port);
390
+ }
391
+ if (url.username || url.password) {
392
+ options.auth = `${url.username}:${url.password}`;
393
+ }
394
+ return options;
395
+ }
396
+
397
+ // src/utils/getUrlByRequestOptions.ts
398
+
399
+ var debug3 = _chunkQMIXLBOUjs.__require.call(void 0, "debug")("utils getUrlByRequestOptions");
400
+ var DEFAULT_PATH = "/";
401
+ var DEFAULT_PROTOCOL = "http:";
402
+ var DEFAULT_HOST = "localhost";
403
+ var DEFAULT_PORT = 80;
404
+ var SSL_PORT = 443;
405
+ function getAgent(options) {
406
+ return options.agent instanceof _http.Agent ? options.agent : void 0;
407
+ }
408
+ function getProtocolByRequestOptions(options) {
409
+ var _a;
410
+ if (options.protocol) {
411
+ return options.protocol;
412
+ }
413
+ const agent = getAgent(options);
414
+ const agentProtocol = agent == null ? void 0 : agent.protocol;
415
+ if (agentProtocol) {
416
+ return agentProtocol;
417
+ }
418
+ const port = getPortByRequestOptions(options);
419
+ const isSecureRequest = options.cert || port === SSL_PORT;
420
+ return isSecureRequest ? "https:" : ((_a = options.uri) == null ? void 0 : _a.protocol) || DEFAULT_PROTOCOL;
421
+ }
422
+ function getPortByRequestOptions(options) {
423
+ const agent = getAgent(options);
424
+ const agentPort = (agent == null ? void 0 : agent.options.port) || (agent == null ? void 0 : agent.defaultPort);
425
+ const optionsPort = options.port;
426
+ if (optionsPort || agentPort) {
427
+ const explicitPort = optionsPort || agentPort || DEFAULT_PORT;
428
+ return Number(explicitPort);
429
+ }
430
+ }
431
+ function getHostByRequestOptions(options) {
432
+ return options.hostname || options.host || DEFAULT_HOST;
433
+ }
434
+ function getAuthByRequestOptions(options) {
435
+ if (options.auth) {
436
+ const [username, password] = options.auth.split(":");
437
+ return { username, password };
438
+ }
439
+ }
440
+ function getUrlByRequestOptions(options) {
441
+ debug3("request options", options);
442
+ const protocol = getProtocolByRequestOptions(options);
443
+ const host = getHostByRequestOptions(options);
444
+ const port = getPortByRequestOptions(options);
445
+ const path = options.path || DEFAULT_PATH;
446
+ const auth = getAuthByRequestOptions(options);
447
+ debug3("protocol", protocol);
448
+ debug3("host", host);
449
+ debug3("port", port);
450
+ debug3("path", path);
451
+ const baseUrl = `${protocol}//${host}`;
452
+ debug3("base URL:", baseUrl);
453
+ const url = options.uri ? new URL(options.uri.href) : new URL(path, baseUrl);
454
+ if (port) {
455
+ debug3("detected explicit port", port);
456
+ url.port = port.toString();
457
+ }
458
+ if (auth) {
459
+ debug3("resolved auth", auth);
460
+ url.username = auth.username;
461
+ url.password = auth.password;
462
+ }
463
+ debug3("created URL:", url);
464
+ return url;
465
+ }
466
+
467
+ // src/utils/cloneObject.ts
468
+ var debug4 = _chunkQMIXLBOUjs.__require.call(void 0, "debug")("cloneObject");
469
+ function isPlainObject(obj) {
470
+ var _a;
471
+ debug4("is plain object?", obj);
472
+ if (obj == null || !((_a = obj.constructor) == null ? void 0 : _a.name)) {
473
+ debug4("given object is undefined, not a plain object...");
474
+ return false;
475
+ }
476
+ debug4("checking the object constructor:", obj.constructor.name);
477
+ return obj.constructor.name === "Object";
478
+ }
479
+ function cloneObject(obj) {
480
+ debug4("cloning object:", obj);
481
+ const enumerableProperties = Object.entries(obj).reduce(
482
+ (acc, [key, value]) => {
483
+ debug4("analyzing key-value pair:", key, value);
484
+ acc[key] = isPlainObject(value) ? cloneObject(value) : value;
485
+ return acc;
486
+ },
487
+ {}
488
+ );
489
+ return isPlainObject(obj) ? enumerableProperties : Object.assign(Object.getPrototypeOf(obj), enumerableProperties);
490
+ }
491
+
492
+ // src/utils/isObject.ts
493
+ function isObject(value) {
494
+ return Object.prototype.toString.call(value) === "[object Object]";
495
+ }
496
+
497
+ // src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts
498
+ var log2 = _debug.debug.call(void 0, "http normalizeClientRequestArgs");
499
+ function resolveRequestOptions(args, url) {
500
+ if (typeof args[1] === "undefined" || typeof args[1] === "function") {
501
+ log2("request options not provided, deriving from the url", url);
502
+ return getRequestOptionsByUrl(url);
503
+ }
504
+ if (args[1]) {
505
+ log2("has custom RequestOptions!", args[1]);
506
+ const requestOptionsFromUrl = getRequestOptionsByUrl(url);
507
+ log2("derived RequestOptions from the URL:", requestOptionsFromUrl);
508
+ log2("cloning RequestOptions...");
509
+ const clonedRequestOptions = cloneObject(args[1]);
510
+ log2("successfully cloned RequestOptions!", clonedRequestOptions);
511
+ return {
512
+ ...requestOptionsFromUrl,
513
+ ...clonedRequestOptions
514
+ };
515
+ }
516
+ log2("using an empty object as request options");
517
+ return {};
518
+ }
519
+ function resolveCallback(args) {
520
+ return typeof args[1] === "function" ? args[1] : args[2];
521
+ }
522
+ function normalizeClientRequestArgs(defaultProtocol, ...args) {
523
+ let url;
524
+ let options;
525
+ let callback;
526
+ log2("arguments", args);
527
+ log2("using default protocol:", defaultProtocol);
528
+ if (typeof args[0] === "string") {
529
+ log2("first argument is a location string:", args[0]);
530
+ url = new URL(args[0]);
531
+ log2("created a url:", url);
532
+ const requestOptionsFromUrl = getRequestOptionsByUrl(url);
533
+ log2("request options from url:", requestOptionsFromUrl);
534
+ options = resolveRequestOptions(args, url);
535
+ log2("resolved request options:", options);
536
+ callback = resolveCallback(args);
537
+ } else if (args[0] instanceof URL) {
538
+ url = args[0];
539
+ log2("first argument is a URL:", url);
540
+ options = resolveRequestOptions(args, url);
541
+ log2("derived request options:", options);
542
+ callback = resolveCallback(args);
543
+ } else if ("hash" in args[0] && !("method" in args[0])) {
544
+ const [legacyUrl] = args;
545
+ log2("first argument is a legacy URL:", legacyUrl);
546
+ if (legacyUrl.hostname === null) {
547
+ log2("given legacy URL is relative (no hostname)");
548
+ return isObject(args[1]) ? normalizeClientRequestArgs(
549
+ defaultProtocol,
550
+ { path: legacyUrl.path, ...args[1] },
551
+ args[2]
552
+ ) : normalizeClientRequestArgs(
553
+ defaultProtocol,
554
+ { path: legacyUrl.path },
555
+ args[1]
556
+ );
557
+ }
558
+ log2("given legacy url is absolute");
559
+ const resolvedUrl = new URL(legacyUrl.href);
560
+ return args[1] === void 0 ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl) : typeof args[1] === "function" ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl, args[1]) : normalizeClientRequestArgs(
561
+ defaultProtocol,
562
+ resolvedUrl,
563
+ args[1],
564
+ args[2]
565
+ );
566
+ } else if (isObject(args[0])) {
567
+ options = args[0];
568
+ log2("first argument is RequestOptions:", options);
569
+ options.protocol = options.protocol || defaultProtocol;
570
+ log2("normalized request options:", options);
571
+ url = getUrlByRequestOptions(options);
572
+ log2("created a URL from RequestOptions:", url.href);
573
+ callback = resolveCallback(args);
574
+ } else {
575
+ throw new Error(
576
+ `Failed to construct ClientRequest with these parameters: ${args}`
577
+ );
578
+ }
579
+ options.protocol = options.protocol || url.protocol;
580
+ options.method = options.method || "GET";
581
+ if (typeof options.agent === "undefined") {
582
+ const agent = options.protocol === "https:" ? new (0, _https.Agent)({
583
+ rejectUnauthorized: options.rejectUnauthorized
584
+ }) : new (0, _http.Agent)();
585
+ options.agent = agent;
586
+ log2("resolved fallback agent:", agent);
587
+ }
588
+ if (!options._defaultAgent) {
589
+ log2(
590
+ 'has no default agent, setting the default agent for "%s"',
591
+ options.protocol
592
+ );
593
+ options._defaultAgent = options.protocol === "https:" ? _https.globalAgent : _http.globalAgent;
594
+ }
595
+ log2("successfully resolved url:", url.href);
596
+ log2("successfully resolved options:", options);
597
+ log2("successfully resolved callback:", callback);
598
+ return [url, options, callback];
599
+ }
600
+
601
+ // src/interceptors/ClientRequest/http.get.ts
602
+ function get(protocol, options) {
603
+ return (...args) => {
604
+ const clientRequestArgs = normalizeClientRequestArgs(
605
+ `${protocol}:`,
606
+ ...args
607
+ );
608
+ const request2 = new NodeClientRequest(clientRequestArgs, options);
609
+ request2.end();
610
+ return request2;
611
+ };
612
+ }
613
+
614
+ // src/interceptors/ClientRequest/http.request.ts
615
+
616
+ var log3 = _debug.debug.call(void 0, "http request");
617
+ function request(protocol, options) {
618
+ return (...args) => {
619
+ log3('request call (protocol "%s"):', protocol, args);
620
+ const clientRequestArgs = normalizeClientRequestArgs(
621
+ `${protocol}:`,
622
+ ...args
623
+ );
624
+ return new NodeClientRequest(clientRequestArgs, options);
625
+ };
626
+ }
627
+
628
+ // src/interceptors/ClientRequest/index.ts
629
+ var _ClientRequestInterceptor = class extends _chunkQMIXLBOUjs.Interceptor {
630
+ constructor() {
631
+ super(_ClientRequestInterceptor.symbol);
632
+ this.modules = /* @__PURE__ */ new Map();
633
+ this.modules.set("http", _http2.default);
634
+ this.modules.set("https", _https2.default);
635
+ }
636
+ setup() {
637
+ const log4 = this.log.extend("setup");
638
+ for (const [protocol, requestModule] of this.modules) {
639
+ const { request: pureRequest, get: pureGet } = requestModule;
640
+ this.subscriptions.push(() => {
641
+ requestModule.request = pureRequest;
642
+ requestModule.get = pureGet;
643
+ log4('native "%s" module restored!', protocol);
644
+ });
645
+ const options = {
646
+ emitter: this.emitter,
647
+ log: this.log
648
+ };
649
+ requestModule.request = request(protocol, options);
650
+ requestModule.get = get(protocol, options);
651
+ log4('native "%s" module patched!', protocol);
652
+ }
653
+ }
654
+ };
655
+ var ClientRequestInterceptor = _ClientRequestInterceptor;
656
+ ClientRequestInterceptor.symbol = Symbol("http");
657
+
658
+
659
+
660
+ exports.ClientRequestInterceptor = ClientRequestInterceptor;
@@ -0,0 +1,6 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/glossary.ts
2
+ var IS_PATCHED_MODULE = Symbol("isPatchedModule");
3
+
4
+
5
+
6
+ exports.IS_PATCHED_MODULE = IS_PATCHED_MODULE;