@cloudflare/vitest-pool-workers 0.2.1 → 0.2.2

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 (54) hide show
  1. package/dist/config/d1.d.ts +7 -0
  2. package/dist/config/index.cjs +130 -0
  3. package/dist/config/index.cjs.map +6 -0
  4. package/dist/config/index.d.ts +21 -0
  5. package/dist/pool/config.d.ts +82 -0
  6. package/dist/pool/helpers.d.ts +5 -0
  7. package/dist/pool/index.mjs +1529 -0
  8. package/dist/pool/index.mjs.map +6 -0
  9. package/dist/shared/d1.d.ts +4 -0
  10. package/dist/worker/index.mjs +352 -0
  11. package/dist/worker/index.mjs.map +6 -0
  12. package/dist/worker/lib/cloudflare/empty-internal.cjs +27 -0
  13. package/dist/worker/lib/cloudflare/empty-internal.cjs.map +6 -0
  14. package/dist/worker/lib/cloudflare/mock-agent.cjs +2056 -0
  15. package/dist/worker/lib/cloudflare/mock-agent.cjs.map +6 -0
  16. package/dist/worker/lib/cloudflare/test-internal.mjs +739 -0
  17. package/dist/worker/lib/cloudflare/test-internal.mjs.map +6 -0
  18. package/dist/worker/lib/cloudflare/test-runner.mjs +222 -0
  19. package/dist/worker/lib/cloudflare/test-runner.mjs.map +6 -0
  20. package/dist/worker/lib/cloudflare/test.mjs +30 -0
  21. package/dist/worker/lib/cloudflare/test.mjs.map +6 -0
  22. package/dist/worker/lib/debug.mjs +9 -0
  23. package/dist/worker/lib/debug.mjs.map +6 -0
  24. package/dist/worker/lib/mlly.mjs +48 -0
  25. package/dist/worker/lib/mlly.mjs.map +6 -0
  26. package/dist/worker/lib/node/console.mjs +104 -0
  27. package/dist/worker/lib/node/console.mjs.map +6 -0
  28. package/dist/worker/lib/node/dns.mjs +6 -0
  29. package/dist/worker/lib/node/dns.mjs.map +6 -0
  30. package/dist/worker/lib/node/fs/promises.mjs +6 -0
  31. package/dist/worker/lib/node/fs/promises.mjs.map +6 -0
  32. package/dist/worker/lib/node/fs.mjs +25 -0
  33. package/dist/worker/lib/node/fs.mjs.map +6 -0
  34. package/dist/worker/lib/node/http.cjs +97 -0
  35. package/dist/worker/lib/node/http.cjs.map +6 -0
  36. package/dist/worker/lib/node/module.mjs +15 -0
  37. package/dist/worker/lib/node/module.mjs.map +6 -0
  38. package/dist/worker/lib/node/net.cjs +27 -0
  39. package/dist/worker/lib/node/net.cjs.map +6 -0
  40. package/dist/worker/lib/node/perf_hooks.mjs +6 -0
  41. package/dist/worker/lib/node/perf_hooks.mjs.map +6 -0
  42. package/dist/worker/lib/node/querystring.cjs +44 -0
  43. package/dist/worker/lib/node/querystring.cjs.map +6 -0
  44. package/dist/worker/lib/node/timers.mjs +6 -0
  45. package/dist/worker/lib/node/timers.mjs.map +6 -0
  46. package/dist/worker/lib/node/tty.mjs +8 -0
  47. package/dist/worker/lib/node/tty.mjs.map +6 -0
  48. package/dist/worker/lib/node/url.mjs +75 -0
  49. package/dist/worker/lib/node/url.mjs.map +6 -0
  50. package/dist/worker/lib/node/vm.mjs +17 -0
  51. package/dist/worker/lib/node/vm.mjs.map +6 -0
  52. package/dist/worker/lib/tinypool.mjs +6 -0
  53. package/dist/worker/lib/tinypool.mjs.map +6 -0
  54. package/package.json +2 -2
@@ -0,0 +1,2056 @@
1
+ "use strict";
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __commonJS = (cb, mod) => function __require() {
4
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
5
+ };
6
+
7
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/core/symbols.js
8
+ var require_symbols = __commonJS({
9
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/core/symbols.js"(exports2, module2) {
10
+ module2.exports = {
11
+ kClose: Symbol("close"),
12
+ kDestroy: Symbol("destroy"),
13
+ kDispatch: Symbol("dispatch"),
14
+ kUrl: Symbol("url"),
15
+ kWriting: Symbol("writing"),
16
+ kResuming: Symbol("resuming"),
17
+ kQueue: Symbol("queue"),
18
+ kConnect: Symbol("connect"),
19
+ kConnecting: Symbol("connecting"),
20
+ kHeadersList: Symbol("headers list"),
21
+ kKeepAliveDefaultTimeout: Symbol("default keep alive timeout"),
22
+ kKeepAliveMaxTimeout: Symbol("max keep alive timeout"),
23
+ kKeepAliveTimeoutThreshold: Symbol("keep alive timeout threshold"),
24
+ kKeepAliveTimeoutValue: Symbol("keep alive timeout"),
25
+ kKeepAlive: Symbol("keep alive"),
26
+ kHeadersTimeout: Symbol("headers timeout"),
27
+ kBodyTimeout: Symbol("body timeout"),
28
+ kServerName: Symbol("server name"),
29
+ kLocalAddress: Symbol("local address"),
30
+ kHost: Symbol("host"),
31
+ kNoRef: Symbol("no ref"),
32
+ kBodyUsed: Symbol("used"),
33
+ kRunning: Symbol("running"),
34
+ kBlocking: Symbol("blocking"),
35
+ kPending: Symbol("pending"),
36
+ kSize: Symbol("size"),
37
+ kBusy: Symbol("busy"),
38
+ kQueued: Symbol("queued"),
39
+ kFree: Symbol("free"),
40
+ kConnected: Symbol("connected"),
41
+ kClosed: Symbol("closed"),
42
+ kNeedDrain: Symbol("need drain"),
43
+ kReset: Symbol("reset"),
44
+ kDestroyed: Symbol.for("nodejs.stream.destroyed"),
45
+ kMaxHeadersSize: Symbol("max headers size"),
46
+ kRunningIdx: Symbol("running index"),
47
+ kPendingIdx: Symbol("pending index"),
48
+ kError: Symbol("error"),
49
+ kClients: Symbol("clients"),
50
+ kClient: Symbol("client"),
51
+ kParser: Symbol("parser"),
52
+ kOnDestroyed: Symbol("destroy callbacks"),
53
+ kPipelining: Symbol("pipelining"),
54
+ kSocket: Symbol("socket"),
55
+ kHostHeader: Symbol("host header"),
56
+ kConnector: Symbol("connector"),
57
+ kStrictContentLength: Symbol("strict content length"),
58
+ kMaxRedirections: Symbol("maxRedirections"),
59
+ kMaxRequests: Symbol("maxRequestsPerClient"),
60
+ kProxy: Symbol("proxy agent options"),
61
+ kCounter: Symbol("socket request counter"),
62
+ kInterceptors: Symbol("dispatch interceptors"),
63
+ kMaxResponseSize: Symbol("max response size"),
64
+ kHTTP2Session: Symbol("http2Session"),
65
+ kHTTP2SessionState: Symbol("http2Session state"),
66
+ kHTTP2BuildRequest: Symbol("http2 build request"),
67
+ kHTTP1BuildRequest: Symbol("http1 build request"),
68
+ kHTTP2CopyHeaders: Symbol("http2 copy headers"),
69
+ kHTTPConnVersion: Symbol("http connection version"),
70
+ kRetryHandlerDefaultRetry: Symbol("retry agent default retry"),
71
+ kConstruct: Symbol("constructable")
72
+ };
73
+ }
74
+ });
75
+
76
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/core/errors.js
77
+ var require_errors = __commonJS({
78
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/core/errors.js"(exports2, module2) {
79
+ "use strict";
80
+ var UndiciError = class extends Error {
81
+ constructor(message) {
82
+ super(message);
83
+ this.name = "UndiciError";
84
+ this.code = "UND_ERR";
85
+ }
86
+ };
87
+ var ConnectTimeoutError = class extends UndiciError {
88
+ constructor(message) {
89
+ super(message);
90
+ Error.captureStackTrace(this, ConnectTimeoutError);
91
+ this.name = "ConnectTimeoutError";
92
+ this.message = message || "Connect Timeout Error";
93
+ this.code = "UND_ERR_CONNECT_TIMEOUT";
94
+ }
95
+ };
96
+ var HeadersTimeoutError = class extends UndiciError {
97
+ constructor(message) {
98
+ super(message);
99
+ Error.captureStackTrace(this, HeadersTimeoutError);
100
+ this.name = "HeadersTimeoutError";
101
+ this.message = message || "Headers Timeout Error";
102
+ this.code = "UND_ERR_HEADERS_TIMEOUT";
103
+ }
104
+ };
105
+ var HeadersOverflowError = class extends UndiciError {
106
+ constructor(message) {
107
+ super(message);
108
+ Error.captureStackTrace(this, HeadersOverflowError);
109
+ this.name = "HeadersOverflowError";
110
+ this.message = message || "Headers Overflow Error";
111
+ this.code = "UND_ERR_HEADERS_OVERFLOW";
112
+ }
113
+ };
114
+ var BodyTimeoutError = class extends UndiciError {
115
+ constructor(message) {
116
+ super(message);
117
+ Error.captureStackTrace(this, BodyTimeoutError);
118
+ this.name = "BodyTimeoutError";
119
+ this.message = message || "Body Timeout Error";
120
+ this.code = "UND_ERR_BODY_TIMEOUT";
121
+ }
122
+ };
123
+ var ResponseStatusCodeError = class extends UndiciError {
124
+ constructor(message, statusCode, headers, body) {
125
+ super(message);
126
+ Error.captureStackTrace(this, ResponseStatusCodeError);
127
+ this.name = "ResponseStatusCodeError";
128
+ this.message = message || "Response Status Code Error";
129
+ this.code = "UND_ERR_RESPONSE_STATUS_CODE";
130
+ this.body = body;
131
+ this.status = statusCode;
132
+ this.statusCode = statusCode;
133
+ this.headers = headers;
134
+ }
135
+ };
136
+ var InvalidArgumentError = class extends UndiciError {
137
+ constructor(message) {
138
+ super(message);
139
+ Error.captureStackTrace(this, InvalidArgumentError);
140
+ this.name = "InvalidArgumentError";
141
+ this.message = message || "Invalid Argument Error";
142
+ this.code = "UND_ERR_INVALID_ARG";
143
+ }
144
+ };
145
+ var InvalidReturnValueError = class extends UndiciError {
146
+ constructor(message) {
147
+ super(message);
148
+ Error.captureStackTrace(this, InvalidReturnValueError);
149
+ this.name = "InvalidReturnValueError";
150
+ this.message = message || "Invalid Return Value Error";
151
+ this.code = "UND_ERR_INVALID_RETURN_VALUE";
152
+ }
153
+ };
154
+ var RequestAbortedError = class extends UndiciError {
155
+ constructor(message) {
156
+ super(message);
157
+ Error.captureStackTrace(this, RequestAbortedError);
158
+ this.name = "AbortError";
159
+ this.message = message || "Request aborted";
160
+ this.code = "UND_ERR_ABORTED";
161
+ }
162
+ };
163
+ var InformationalError = class extends UndiciError {
164
+ constructor(message) {
165
+ super(message);
166
+ Error.captureStackTrace(this, InformationalError);
167
+ this.name = "InformationalError";
168
+ this.message = message || "Request information";
169
+ this.code = "UND_ERR_INFO";
170
+ }
171
+ };
172
+ var RequestContentLengthMismatchError = class extends UndiciError {
173
+ constructor(message) {
174
+ super(message);
175
+ Error.captureStackTrace(this, RequestContentLengthMismatchError);
176
+ this.name = "RequestContentLengthMismatchError";
177
+ this.message = message || "Request body length does not match content-length header";
178
+ this.code = "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH";
179
+ }
180
+ };
181
+ var ResponseContentLengthMismatchError = class extends UndiciError {
182
+ constructor(message) {
183
+ super(message);
184
+ Error.captureStackTrace(this, ResponseContentLengthMismatchError);
185
+ this.name = "ResponseContentLengthMismatchError";
186
+ this.message = message || "Response body length does not match content-length header";
187
+ this.code = "UND_ERR_RES_CONTENT_LENGTH_MISMATCH";
188
+ }
189
+ };
190
+ var ClientDestroyedError = class extends UndiciError {
191
+ constructor(message) {
192
+ super(message);
193
+ Error.captureStackTrace(this, ClientDestroyedError);
194
+ this.name = "ClientDestroyedError";
195
+ this.message = message || "The client is destroyed";
196
+ this.code = "UND_ERR_DESTROYED";
197
+ }
198
+ };
199
+ var ClientClosedError = class extends UndiciError {
200
+ constructor(message) {
201
+ super(message);
202
+ Error.captureStackTrace(this, ClientClosedError);
203
+ this.name = "ClientClosedError";
204
+ this.message = message || "The client is closed";
205
+ this.code = "UND_ERR_CLOSED";
206
+ }
207
+ };
208
+ var SocketError = class extends UndiciError {
209
+ constructor(message, socket) {
210
+ super(message);
211
+ Error.captureStackTrace(this, SocketError);
212
+ this.name = "SocketError";
213
+ this.message = message || "Socket error";
214
+ this.code = "UND_ERR_SOCKET";
215
+ this.socket = socket;
216
+ }
217
+ };
218
+ var NotSupportedError = class extends UndiciError {
219
+ constructor(message) {
220
+ super(message);
221
+ Error.captureStackTrace(this, NotSupportedError);
222
+ this.name = "NotSupportedError";
223
+ this.message = message || "Not supported error";
224
+ this.code = "UND_ERR_NOT_SUPPORTED";
225
+ }
226
+ };
227
+ var BalancedPoolMissingUpstreamError = class extends UndiciError {
228
+ constructor(message) {
229
+ super(message);
230
+ Error.captureStackTrace(this, NotSupportedError);
231
+ this.name = "MissingUpstreamError";
232
+ this.message = message || "No upstream has been added to the BalancedPool";
233
+ this.code = "UND_ERR_BPL_MISSING_UPSTREAM";
234
+ }
235
+ };
236
+ var HTTPParserError = class extends Error {
237
+ constructor(message, code, data) {
238
+ super(message);
239
+ Error.captureStackTrace(this, HTTPParserError);
240
+ this.name = "HTTPParserError";
241
+ this.code = code ? `HPE_${code}` : void 0;
242
+ this.data = data ? data.toString() : void 0;
243
+ }
244
+ };
245
+ var ResponseExceededMaxSizeError = class extends UndiciError {
246
+ constructor(message) {
247
+ super(message);
248
+ Error.captureStackTrace(this, ResponseExceededMaxSizeError);
249
+ this.name = "ResponseExceededMaxSizeError";
250
+ this.message = message || "Response content exceeded max size";
251
+ this.code = "UND_ERR_RES_EXCEEDED_MAX_SIZE";
252
+ }
253
+ };
254
+ var RequestRetryError = class extends UndiciError {
255
+ constructor(message, code, { headers, data }) {
256
+ super(message);
257
+ Error.captureStackTrace(this, RequestRetryError);
258
+ this.name = "RequestRetryError";
259
+ this.message = message || "Request retry error";
260
+ this.code = "UND_ERR_REQ_RETRY";
261
+ this.statusCode = code;
262
+ this.data = data;
263
+ this.headers = headers;
264
+ }
265
+ };
266
+ module2.exports = {
267
+ HTTPParserError,
268
+ UndiciError,
269
+ HeadersTimeoutError,
270
+ HeadersOverflowError,
271
+ BodyTimeoutError,
272
+ RequestContentLengthMismatchError,
273
+ ConnectTimeoutError,
274
+ ResponseStatusCodeError,
275
+ InvalidArgumentError,
276
+ InvalidReturnValueError,
277
+ RequestAbortedError,
278
+ ClientDestroyedError,
279
+ ClientClosedError,
280
+ InformationalError,
281
+ SocketError,
282
+ NotSupportedError,
283
+ ResponseContentLengthMismatchError,
284
+ BalancedPoolMissingUpstreamError,
285
+ ResponseExceededMaxSizeError,
286
+ RequestRetryError
287
+ };
288
+ }
289
+ });
290
+
291
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/dispatcher.js
292
+ var require_dispatcher = __commonJS({
293
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/dispatcher.js"(exports2, module2) {
294
+ "use strict";
295
+ var EventEmitter = require("events");
296
+ var Dispatcher = class extends EventEmitter {
297
+ dispatch() {
298
+ throw new Error("not implemented");
299
+ }
300
+ close() {
301
+ throw new Error("not implemented");
302
+ }
303
+ destroy() {
304
+ throw new Error("not implemented");
305
+ }
306
+ };
307
+ module2.exports = Dispatcher;
308
+ }
309
+ });
310
+
311
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/dispatcher-base.js
312
+ var require_dispatcher_base = __commonJS({
313
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/dispatcher-base.js"(exports2, module2) {
314
+ "use strict";
315
+ var Dispatcher = require_dispatcher();
316
+ var {
317
+ ClientDestroyedError,
318
+ ClientClosedError,
319
+ InvalidArgumentError
320
+ } = require_errors();
321
+ var { kDestroy, kClose, kDispatch, kInterceptors } = require_symbols();
322
+ var kDestroyed = Symbol("destroyed");
323
+ var kClosed = Symbol("closed");
324
+ var kOnDestroyed = Symbol("onDestroyed");
325
+ var kOnClosed = Symbol("onClosed");
326
+ var kInterceptedDispatch = Symbol("Intercepted Dispatch");
327
+ var DispatcherBase = class extends Dispatcher {
328
+ constructor() {
329
+ super();
330
+ this[kDestroyed] = false;
331
+ this[kOnDestroyed] = null;
332
+ this[kClosed] = false;
333
+ this[kOnClosed] = [];
334
+ }
335
+ get destroyed() {
336
+ return this[kDestroyed];
337
+ }
338
+ get closed() {
339
+ return this[kClosed];
340
+ }
341
+ get interceptors() {
342
+ return this[kInterceptors];
343
+ }
344
+ set interceptors(newInterceptors) {
345
+ if (newInterceptors) {
346
+ for (let i = newInterceptors.length - 1; i >= 0; i--) {
347
+ const interceptor = this[kInterceptors][i];
348
+ if (typeof interceptor !== "function") {
349
+ throw new InvalidArgumentError("interceptor must be an function");
350
+ }
351
+ }
352
+ }
353
+ this[kInterceptors] = newInterceptors;
354
+ }
355
+ close(callback) {
356
+ if (callback === void 0) {
357
+ return new Promise((resolve, reject) => {
358
+ this.close((err, data) => {
359
+ return err ? reject(err) : resolve(data);
360
+ });
361
+ });
362
+ }
363
+ if (typeof callback !== "function") {
364
+ throw new InvalidArgumentError("invalid callback");
365
+ }
366
+ if (this[kDestroyed]) {
367
+ queueMicrotask(() => callback(new ClientDestroyedError(), null));
368
+ return;
369
+ }
370
+ if (this[kClosed]) {
371
+ if (this[kOnClosed]) {
372
+ this[kOnClosed].push(callback);
373
+ } else {
374
+ queueMicrotask(() => callback(null, null));
375
+ }
376
+ return;
377
+ }
378
+ this[kClosed] = true;
379
+ this[kOnClosed].push(callback);
380
+ const onClosed = () => {
381
+ const callbacks = this[kOnClosed];
382
+ this[kOnClosed] = null;
383
+ for (let i = 0; i < callbacks.length; i++) {
384
+ callbacks[i](null, null);
385
+ }
386
+ };
387
+ this[kClose]().then(() => this.destroy()).then(() => {
388
+ queueMicrotask(onClosed);
389
+ });
390
+ }
391
+ destroy(err, callback) {
392
+ if (typeof err === "function") {
393
+ callback = err;
394
+ err = null;
395
+ }
396
+ if (callback === void 0) {
397
+ return new Promise((resolve, reject) => {
398
+ this.destroy(err, (err2, data) => {
399
+ return err2 ? (
400
+ /* istanbul ignore next: should never error */
401
+ reject(err2)
402
+ ) : resolve(data);
403
+ });
404
+ });
405
+ }
406
+ if (typeof callback !== "function") {
407
+ throw new InvalidArgumentError("invalid callback");
408
+ }
409
+ if (this[kDestroyed]) {
410
+ if (this[kOnDestroyed]) {
411
+ this[kOnDestroyed].push(callback);
412
+ } else {
413
+ queueMicrotask(() => callback(null, null));
414
+ }
415
+ return;
416
+ }
417
+ if (!err) {
418
+ err = new ClientDestroyedError();
419
+ }
420
+ this[kDestroyed] = true;
421
+ this[kOnDestroyed] = this[kOnDestroyed] || [];
422
+ this[kOnDestroyed].push(callback);
423
+ const onDestroyed = () => {
424
+ const callbacks = this[kOnDestroyed];
425
+ this[kOnDestroyed] = null;
426
+ for (let i = 0; i < callbacks.length; i++) {
427
+ callbacks[i](null, null);
428
+ }
429
+ };
430
+ this[kDestroy](err).then(() => {
431
+ queueMicrotask(onDestroyed);
432
+ });
433
+ }
434
+ [kInterceptedDispatch](opts, handler) {
435
+ if (!this[kInterceptors] || this[kInterceptors].length === 0) {
436
+ this[kInterceptedDispatch] = this[kDispatch];
437
+ return this[kDispatch](opts, handler);
438
+ }
439
+ let dispatch = this[kDispatch].bind(this);
440
+ for (let i = this[kInterceptors].length - 1; i >= 0; i--) {
441
+ dispatch = this[kInterceptors][i](dispatch);
442
+ }
443
+ this[kInterceptedDispatch] = dispatch;
444
+ return dispatch(opts, handler);
445
+ }
446
+ dispatch(opts, handler) {
447
+ if (!handler || typeof handler !== "object") {
448
+ throw new InvalidArgumentError("handler must be an object");
449
+ }
450
+ try {
451
+ if (!opts || typeof opts !== "object") {
452
+ throw new InvalidArgumentError("opts must be an object.");
453
+ }
454
+ if (this[kDestroyed] || this[kOnDestroyed]) {
455
+ throw new ClientDestroyedError();
456
+ }
457
+ if (this[kClosed]) {
458
+ throw new ClientClosedError();
459
+ }
460
+ return this[kInterceptedDispatch](opts, handler);
461
+ } catch (err) {
462
+ if (typeof handler.onError !== "function") {
463
+ throw new InvalidArgumentError("invalid onError method");
464
+ }
465
+ handler.onError(err);
466
+ return false;
467
+ }
468
+ }
469
+ };
470
+ module2.exports = DispatcherBase;
471
+ }
472
+ });
473
+
474
+ // src/mock-agent/pool.cjs
475
+ var require_pool = __commonJS({
476
+ "src/mock-agent/pool.cjs"(exports2, module2) {
477
+ var assert = require("node:assert");
478
+ module2.exports = class Pool {
479
+ constructor() {
480
+ assert.fail("Pool is not implemented in worker");
481
+ }
482
+ };
483
+ }
484
+ });
485
+
486
+ // src/mock-agent/dispatcher.cjs
487
+ var require_dispatcher2 = __commonJS({
488
+ "src/mock-agent/dispatcher.cjs"(exports2, module2) {
489
+ "use strict";
490
+ var dispatcher;
491
+ module2.exports = {
492
+ getDispatcher() {
493
+ return dispatcher;
494
+ },
495
+ setDispatcher(newDispatcher) {
496
+ dispatcher = newDispatcher;
497
+ }
498
+ };
499
+ }
500
+ });
501
+
502
+ // src/mock-agent/client.cjs
503
+ var require_client = __commonJS({
504
+ "src/mock-agent/client.cjs"(exports2, module2) {
505
+ var assert = require("node:assert");
506
+ var DispatcherBase = require_dispatcher_base();
507
+ var { kDispatch, kClose, kDestroy } = require_symbols();
508
+ var { getDispatcher } = require_dispatcher2();
509
+ module2.exports = class Client extends DispatcherBase {
510
+ [kDispatch](opts, handler) {
511
+ const dispatcher = getDispatcher();
512
+ if (dispatcher === void 0) {
513
+ assert.fail("setDispatcher() must be called before Client#[kDispatch]()");
514
+ }
515
+ dispatcher(opts, handler);
516
+ return true;
517
+ }
518
+ async [kClose]() {
519
+ }
520
+ async [kDestroy](_err) {
521
+ }
522
+ };
523
+ }
524
+ });
525
+
526
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/core/util.js
527
+ var require_util = __commonJS({
528
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/core/util.js"(exports2, module2) {
529
+ "use strict";
530
+ var assert = require("assert");
531
+ var { kDestroyed, kBodyUsed } = require_symbols();
532
+ var { IncomingMessage } = require("http");
533
+ var stream = require("stream");
534
+ var net = require("net");
535
+ var { InvalidArgumentError } = require_errors();
536
+ var { Blob } = require("buffer");
537
+ var nodeUtil = require("util");
538
+ var { stringify } = require("querystring");
539
+ var [nodeMajor, nodeMinor] = process.versions.node.split(".").map((v) => Number(v));
540
+ function nop() {
541
+ }
542
+ function isStream(obj) {
543
+ return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function";
544
+ }
545
+ function isBlobLike(object) {
546
+ return Blob && object instanceof Blob || object && typeof object === "object" && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && /^(Blob|File)$/.test(object[Symbol.toStringTag]);
547
+ }
548
+ function buildURL(url, queryParams) {
549
+ if (url.includes("?") || url.includes("#")) {
550
+ throw new Error('Query params cannot be passed when url already contains "?" or "#".');
551
+ }
552
+ const stringified = stringify(queryParams);
553
+ if (stringified) {
554
+ url += "?" + stringified;
555
+ }
556
+ return url;
557
+ }
558
+ function parseURL(url) {
559
+ if (typeof url === "string") {
560
+ url = new URL(url);
561
+ if (!/^https?:/.test(url.origin || url.protocol)) {
562
+ throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
563
+ }
564
+ return url;
565
+ }
566
+ if (!url || typeof url !== "object") {
567
+ throw new InvalidArgumentError("Invalid URL: The URL argument must be a non-null object.");
568
+ }
569
+ if (!/^https?:/.test(url.origin || url.protocol)) {
570
+ throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
571
+ }
572
+ if (!(url instanceof URL)) {
573
+ if (url.port != null && url.port !== "" && !Number.isFinite(parseInt(url.port))) {
574
+ throw new InvalidArgumentError("Invalid URL: port must be a valid integer or a string representation of an integer.");
575
+ }
576
+ if (url.path != null && typeof url.path !== "string") {
577
+ throw new InvalidArgumentError("Invalid URL path: the path must be a string or null/undefined.");
578
+ }
579
+ if (url.pathname != null && typeof url.pathname !== "string") {
580
+ throw new InvalidArgumentError("Invalid URL pathname: the pathname must be a string or null/undefined.");
581
+ }
582
+ if (url.hostname != null && typeof url.hostname !== "string") {
583
+ throw new InvalidArgumentError("Invalid URL hostname: the hostname must be a string or null/undefined.");
584
+ }
585
+ if (url.origin != null && typeof url.origin !== "string") {
586
+ throw new InvalidArgumentError("Invalid URL origin: the origin must be a string or null/undefined.");
587
+ }
588
+ const port = url.port != null ? url.port : url.protocol === "https:" ? 443 : 80;
589
+ let origin = url.origin != null ? url.origin : `${url.protocol}//${url.hostname}:${port}`;
590
+ let path = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`;
591
+ if (origin.endsWith("/")) {
592
+ origin = origin.substring(0, origin.length - 1);
593
+ }
594
+ if (path && !path.startsWith("/")) {
595
+ path = `/${path}`;
596
+ }
597
+ url = new URL(origin + path);
598
+ }
599
+ return url;
600
+ }
601
+ function parseOrigin(url) {
602
+ url = parseURL(url);
603
+ if (url.pathname !== "/" || url.search || url.hash) {
604
+ throw new InvalidArgumentError("invalid url");
605
+ }
606
+ return url;
607
+ }
608
+ function getHostname(host) {
609
+ if (host[0] === "[") {
610
+ const idx2 = host.indexOf("]");
611
+ assert(idx2 !== -1);
612
+ return host.substring(1, idx2);
613
+ }
614
+ const idx = host.indexOf(":");
615
+ if (idx === -1)
616
+ return host;
617
+ return host.substring(0, idx);
618
+ }
619
+ function getServerName(host) {
620
+ if (!host) {
621
+ return null;
622
+ }
623
+ assert.strictEqual(typeof host, "string");
624
+ const servername = getHostname(host);
625
+ if (net.isIP(servername)) {
626
+ return "";
627
+ }
628
+ return servername;
629
+ }
630
+ function deepClone(obj) {
631
+ return JSON.parse(JSON.stringify(obj));
632
+ }
633
+ function isAsyncIterable(obj) {
634
+ return !!(obj != null && typeof obj[Symbol.asyncIterator] === "function");
635
+ }
636
+ function isIterable(obj) {
637
+ return !!(obj != null && (typeof obj[Symbol.iterator] === "function" || typeof obj[Symbol.asyncIterator] === "function"));
638
+ }
639
+ function bodyLength(body) {
640
+ if (body == null) {
641
+ return 0;
642
+ } else if (isStream(body)) {
643
+ const state = body._readableState;
644
+ return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) ? state.length : null;
645
+ } else if (isBlobLike(body)) {
646
+ return body.size != null ? body.size : null;
647
+ } else if (isBuffer(body)) {
648
+ return body.byteLength;
649
+ }
650
+ return null;
651
+ }
652
+ function isDestroyed(stream2) {
653
+ return !stream2 || !!(stream2.destroyed || stream2[kDestroyed]);
654
+ }
655
+ function isReadableAborted(stream2) {
656
+ const state = stream2 && stream2._readableState;
657
+ return isDestroyed(stream2) && state && !state.endEmitted;
658
+ }
659
+ function destroy(stream2, err) {
660
+ if (stream2 == null || !isStream(stream2) || isDestroyed(stream2)) {
661
+ return;
662
+ }
663
+ if (typeof stream2.destroy === "function") {
664
+ if (Object.getPrototypeOf(stream2).constructor === IncomingMessage) {
665
+ stream2.socket = null;
666
+ }
667
+ stream2.destroy(err);
668
+ } else if (err) {
669
+ process.nextTick((stream3, err2) => {
670
+ stream3.emit("error", err2);
671
+ }, stream2, err);
672
+ }
673
+ if (stream2.destroyed !== true) {
674
+ stream2[kDestroyed] = true;
675
+ }
676
+ }
677
+ var KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/;
678
+ function parseKeepAliveTimeout(val) {
679
+ const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR);
680
+ return m ? parseInt(m[1], 10) * 1e3 : null;
681
+ }
682
+ function parseHeaders(headers, obj = {}) {
683
+ if (!Array.isArray(headers))
684
+ return headers;
685
+ for (let i = 0; i < headers.length; i += 2) {
686
+ const key = headers[i].toString().toLowerCase();
687
+ let val = obj[key];
688
+ if (!val) {
689
+ if (Array.isArray(headers[i + 1])) {
690
+ obj[key] = headers[i + 1].map((x) => x.toString("utf8"));
691
+ } else {
692
+ obj[key] = headers[i + 1].toString("utf8");
693
+ }
694
+ } else {
695
+ if (!Array.isArray(val)) {
696
+ val = [val];
697
+ obj[key] = val;
698
+ }
699
+ val.push(headers[i + 1].toString("utf8"));
700
+ }
701
+ }
702
+ if ("content-length" in obj && "content-disposition" in obj) {
703
+ obj["content-disposition"] = Buffer.from(obj["content-disposition"]).toString("latin1");
704
+ }
705
+ return obj;
706
+ }
707
+ function parseRawHeaders(headers) {
708
+ const ret = [];
709
+ let hasContentLength = false;
710
+ let contentDispositionIdx = -1;
711
+ for (let n = 0; n < headers.length; n += 2) {
712
+ const key = headers[n + 0].toString();
713
+ const val = headers[n + 1].toString("utf8");
714
+ if (key.length === 14 && (key === "content-length" || key.toLowerCase() === "content-length")) {
715
+ ret.push(key, val);
716
+ hasContentLength = true;
717
+ } else if (key.length === 19 && (key === "content-disposition" || key.toLowerCase() === "content-disposition")) {
718
+ contentDispositionIdx = ret.push(key, val) - 1;
719
+ } else {
720
+ ret.push(key, val);
721
+ }
722
+ }
723
+ if (hasContentLength && contentDispositionIdx !== -1) {
724
+ ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString("latin1");
725
+ }
726
+ return ret;
727
+ }
728
+ function isBuffer(buffer) {
729
+ return buffer instanceof Uint8Array || Buffer.isBuffer(buffer);
730
+ }
731
+ function validateHandler(handler, method, upgrade) {
732
+ if (!handler || typeof handler !== "object") {
733
+ throw new InvalidArgumentError("handler must be an object");
734
+ }
735
+ if (typeof handler.onConnect !== "function") {
736
+ throw new InvalidArgumentError("invalid onConnect method");
737
+ }
738
+ if (typeof handler.onError !== "function") {
739
+ throw new InvalidArgumentError("invalid onError method");
740
+ }
741
+ if (typeof handler.onBodySent !== "function" && handler.onBodySent !== void 0) {
742
+ throw new InvalidArgumentError("invalid onBodySent method");
743
+ }
744
+ if (upgrade || method === "CONNECT") {
745
+ if (typeof handler.onUpgrade !== "function") {
746
+ throw new InvalidArgumentError("invalid onUpgrade method");
747
+ }
748
+ } else {
749
+ if (typeof handler.onHeaders !== "function") {
750
+ throw new InvalidArgumentError("invalid onHeaders method");
751
+ }
752
+ if (typeof handler.onData !== "function") {
753
+ throw new InvalidArgumentError("invalid onData method");
754
+ }
755
+ if (typeof handler.onComplete !== "function") {
756
+ throw new InvalidArgumentError("invalid onComplete method");
757
+ }
758
+ }
759
+ }
760
+ function isDisturbed(body) {
761
+ return !!(body && (stream.isDisturbed ? stream.isDisturbed(body) || body[kBodyUsed] : body[kBodyUsed] || body.readableDidRead || body._readableState && body._readableState.dataEmitted || isReadableAborted(body)));
762
+ }
763
+ function isErrored(body) {
764
+ return !!(body && (stream.isErrored ? stream.isErrored(body) : /state: 'errored'/.test(
765
+ nodeUtil.inspect(body)
766
+ )));
767
+ }
768
+ function isReadable(body) {
769
+ return !!(body && (stream.isReadable ? stream.isReadable(body) : /state: 'readable'/.test(
770
+ nodeUtil.inspect(body)
771
+ )));
772
+ }
773
+ function getSocketInfo(socket) {
774
+ return {
775
+ localAddress: socket.localAddress,
776
+ localPort: socket.localPort,
777
+ remoteAddress: socket.remoteAddress,
778
+ remotePort: socket.remotePort,
779
+ remoteFamily: socket.remoteFamily,
780
+ timeout: socket.timeout,
781
+ bytesWritten: socket.bytesWritten,
782
+ bytesRead: socket.bytesRead
783
+ };
784
+ }
785
+ async function* convertIterableToBuffer(iterable) {
786
+ for await (const chunk of iterable) {
787
+ yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
788
+ }
789
+ }
790
+ var ReadableStream;
791
+ function ReadableStreamFrom(iterable) {
792
+ if (!ReadableStream) {
793
+ ReadableStream = require("stream/web").ReadableStream;
794
+ }
795
+ if (ReadableStream.from) {
796
+ return ReadableStream.from(convertIterableToBuffer(iterable));
797
+ }
798
+ let iterator;
799
+ return new ReadableStream(
800
+ {
801
+ async start() {
802
+ iterator = iterable[Symbol.asyncIterator]();
803
+ },
804
+ async pull(controller) {
805
+ const { done, value } = await iterator.next();
806
+ if (done) {
807
+ queueMicrotask(() => {
808
+ controller.close();
809
+ });
810
+ } else {
811
+ const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
812
+ controller.enqueue(new Uint8Array(buf));
813
+ }
814
+ return controller.desiredSize > 0;
815
+ },
816
+ async cancel(reason) {
817
+ await iterator.return();
818
+ }
819
+ },
820
+ 0
821
+ );
822
+ }
823
+ function isFormDataLike(object) {
824
+ return object && typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && object[Symbol.toStringTag] === "FormData";
825
+ }
826
+ function throwIfAborted(signal) {
827
+ if (!signal) {
828
+ return;
829
+ }
830
+ if (typeof signal.throwIfAborted === "function") {
831
+ signal.throwIfAborted();
832
+ } else {
833
+ if (signal.aborted) {
834
+ const err = new Error("The operation was aborted");
835
+ err.name = "AbortError";
836
+ throw err;
837
+ }
838
+ }
839
+ }
840
+ function addAbortListener(signal, listener) {
841
+ if ("addEventListener" in signal) {
842
+ signal.addEventListener("abort", listener, { once: true });
843
+ return () => signal.removeEventListener("abort", listener);
844
+ }
845
+ signal.addListener("abort", listener);
846
+ return () => signal.removeListener("abort", listener);
847
+ }
848
+ var hasToWellFormed = !!String.prototype.toWellFormed;
849
+ function toUSVString(val) {
850
+ if (hasToWellFormed) {
851
+ return `${val}`.toWellFormed();
852
+ } else if (nodeUtil.toUSVString) {
853
+ return nodeUtil.toUSVString(val);
854
+ }
855
+ return `${val}`;
856
+ }
857
+ function parseRangeHeader(range) {
858
+ if (range == null || range === "")
859
+ return { start: 0, end: null, size: null };
860
+ const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null;
861
+ return m ? {
862
+ start: parseInt(m[1]),
863
+ end: m[2] ? parseInt(m[2]) : null,
864
+ size: m[3] ? parseInt(m[3]) : null
865
+ } : null;
866
+ }
867
+ var kEnumerableProperty = /* @__PURE__ */ Object.create(null);
868
+ kEnumerableProperty.enumerable = true;
869
+ module2.exports = {
870
+ kEnumerableProperty,
871
+ nop,
872
+ isDisturbed,
873
+ isErrored,
874
+ isReadable,
875
+ toUSVString,
876
+ isReadableAborted,
877
+ isBlobLike,
878
+ parseOrigin,
879
+ parseURL,
880
+ getServerName,
881
+ isStream,
882
+ isIterable,
883
+ isAsyncIterable,
884
+ isDestroyed,
885
+ parseRawHeaders,
886
+ parseHeaders,
887
+ parseKeepAliveTimeout,
888
+ destroy,
889
+ bodyLength,
890
+ deepClone,
891
+ ReadableStreamFrom,
892
+ isBuffer,
893
+ validateHandler,
894
+ getSocketInfo,
895
+ isFormDataLike,
896
+ buildURL,
897
+ throwIfAborted,
898
+ addAbortListener,
899
+ parseRangeHeader,
900
+ nodeMajor,
901
+ nodeMinor,
902
+ nodeHasAutoSelectFamily: nodeMajor > 18 || nodeMajor === 18 && nodeMinor >= 13,
903
+ safeHTTPMethods: ["GET", "HEAD", "OPTIONS", "TRACE"]
904
+ };
905
+ }
906
+ });
907
+
908
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/handler/RedirectHandler.js
909
+ var require_RedirectHandler = __commonJS({
910
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/handler/RedirectHandler.js"(exports2, module2) {
911
+ "use strict";
912
+ var util = require_util();
913
+ var { kBodyUsed } = require_symbols();
914
+ var assert = require("assert");
915
+ var { InvalidArgumentError } = require_errors();
916
+ var EE = require("events");
917
+ var redirectableStatusCodes = [300, 301, 302, 303, 307, 308];
918
+ var kBody = Symbol("body");
919
+ var BodyAsyncIterable = class {
920
+ constructor(body) {
921
+ this[kBody] = body;
922
+ this[kBodyUsed] = false;
923
+ }
924
+ async *[Symbol.asyncIterator]() {
925
+ assert(!this[kBodyUsed], "disturbed");
926
+ this[kBodyUsed] = true;
927
+ yield* this[kBody];
928
+ }
929
+ };
930
+ var RedirectHandler = class {
931
+ constructor(dispatch, maxRedirections, opts, handler) {
932
+ if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
933
+ throw new InvalidArgumentError("maxRedirections must be a positive number");
934
+ }
935
+ util.validateHandler(handler, opts.method, opts.upgrade);
936
+ this.dispatch = dispatch;
937
+ this.location = null;
938
+ this.abort = null;
939
+ this.opts = { ...opts, maxRedirections: 0 };
940
+ this.maxRedirections = maxRedirections;
941
+ this.handler = handler;
942
+ this.history = [];
943
+ if (util.isStream(this.opts.body)) {
944
+ if (util.bodyLength(this.opts.body) === 0) {
945
+ this.opts.body.on("data", function() {
946
+ assert(false);
947
+ });
948
+ }
949
+ if (typeof this.opts.body.readableDidRead !== "boolean") {
950
+ this.opts.body[kBodyUsed] = false;
951
+ EE.prototype.on.call(this.opts.body, "data", function() {
952
+ this[kBodyUsed] = true;
953
+ });
954
+ }
955
+ } else if (this.opts.body && typeof this.opts.body.pipeTo === "function") {
956
+ this.opts.body = new BodyAsyncIterable(this.opts.body);
957
+ } else if (this.opts.body && typeof this.opts.body !== "string" && !ArrayBuffer.isView(this.opts.body) && util.isIterable(this.opts.body)) {
958
+ this.opts.body = new BodyAsyncIterable(this.opts.body);
959
+ }
960
+ }
961
+ onConnect(abort) {
962
+ this.abort = abort;
963
+ this.handler.onConnect(abort, { history: this.history });
964
+ }
965
+ onUpgrade(statusCode, headers, socket) {
966
+ this.handler.onUpgrade(statusCode, headers, socket);
967
+ }
968
+ onError(error) {
969
+ this.handler.onError(error);
970
+ }
971
+ onHeaders(statusCode, headers, resume, statusText) {
972
+ this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) ? null : parseLocation(statusCode, headers);
973
+ if (this.opts.origin) {
974
+ this.history.push(new URL(this.opts.path, this.opts.origin));
975
+ }
976
+ if (!this.location) {
977
+ return this.handler.onHeaders(statusCode, headers, resume, statusText);
978
+ }
979
+ const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
980
+ const path = search ? `${pathname}${search}` : pathname;
981
+ this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
982
+ this.opts.path = path;
983
+ this.opts.origin = origin;
984
+ this.opts.maxRedirections = 0;
985
+ this.opts.query = null;
986
+ if (statusCode === 303 && this.opts.method !== "HEAD") {
987
+ this.opts.method = "GET";
988
+ this.opts.body = null;
989
+ }
990
+ }
991
+ onData(chunk) {
992
+ if (this.location) {
993
+ } else {
994
+ return this.handler.onData(chunk);
995
+ }
996
+ }
997
+ onComplete(trailers) {
998
+ if (this.location) {
999
+ this.location = null;
1000
+ this.abort = null;
1001
+ this.dispatch(this.opts, this);
1002
+ } else {
1003
+ this.handler.onComplete(trailers);
1004
+ }
1005
+ }
1006
+ onBodySent(chunk) {
1007
+ if (this.handler.onBodySent) {
1008
+ this.handler.onBodySent(chunk);
1009
+ }
1010
+ }
1011
+ };
1012
+ function parseLocation(statusCode, headers) {
1013
+ if (redirectableStatusCodes.indexOf(statusCode) === -1) {
1014
+ return null;
1015
+ }
1016
+ for (let i = 0; i < headers.length; i += 2) {
1017
+ if (headers[i].toString().toLowerCase() === "location") {
1018
+ return headers[i + 1];
1019
+ }
1020
+ }
1021
+ }
1022
+ function shouldRemoveHeader(header, removeContent, unknownOrigin) {
1023
+ return header.length === 4 && header.toString().toLowerCase() === "host" || removeContent && header.toString().toLowerCase().indexOf("content-") === 0 || unknownOrigin && header.length === 13 && header.toString().toLowerCase() === "authorization" || unknownOrigin && header.length === 6 && header.toString().toLowerCase() === "cookie";
1024
+ }
1025
+ function cleanRequestHeaders(headers, removeContent, unknownOrigin) {
1026
+ const ret = [];
1027
+ if (Array.isArray(headers)) {
1028
+ for (let i = 0; i < headers.length; i += 2) {
1029
+ if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {
1030
+ ret.push(headers[i], headers[i + 1]);
1031
+ }
1032
+ }
1033
+ } else if (headers && typeof headers === "object") {
1034
+ for (const key of Object.keys(headers)) {
1035
+ if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
1036
+ ret.push(key, headers[key]);
1037
+ }
1038
+ }
1039
+ } else {
1040
+ assert(headers == null, "headers must be an object or an array");
1041
+ }
1042
+ return ret;
1043
+ }
1044
+ module2.exports = RedirectHandler;
1045
+ }
1046
+ });
1047
+
1048
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/interceptor/redirectInterceptor.js
1049
+ var require_redirectInterceptor = __commonJS({
1050
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/interceptor/redirectInterceptor.js"(exports2, module2) {
1051
+ "use strict";
1052
+ var RedirectHandler = require_RedirectHandler();
1053
+ function createRedirectInterceptor({ maxRedirections: defaultMaxRedirections }) {
1054
+ return (dispatch) => {
1055
+ return function Intercept(opts, handler) {
1056
+ const { maxRedirections = defaultMaxRedirections } = opts;
1057
+ if (!maxRedirections) {
1058
+ return dispatch(opts, handler);
1059
+ }
1060
+ const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler);
1061
+ opts = { ...opts, maxRedirections: 0 };
1062
+ return dispatch(opts, redirectHandler);
1063
+ };
1064
+ };
1065
+ }
1066
+ module2.exports = createRedirectInterceptor;
1067
+ }
1068
+ });
1069
+
1070
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/compat/dispatcher-weakref.js
1071
+ var require_dispatcher_weakref = __commonJS({
1072
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/compat/dispatcher-weakref.js"(exports2, module2) {
1073
+ "use strict";
1074
+ var { kConnected, kSize } = require_symbols();
1075
+ var CompatWeakRef = class {
1076
+ constructor(value) {
1077
+ this.value = value;
1078
+ }
1079
+ deref() {
1080
+ return this.value[kConnected] === 0 && this.value[kSize] === 0 ? void 0 : this.value;
1081
+ }
1082
+ };
1083
+ var CompatFinalizer = class {
1084
+ constructor(finalizer) {
1085
+ this.finalizer = finalizer;
1086
+ }
1087
+ register(dispatcher, key) {
1088
+ if (dispatcher.on) {
1089
+ dispatcher.on("disconnect", () => {
1090
+ if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
1091
+ this.finalizer(key);
1092
+ }
1093
+ });
1094
+ }
1095
+ }
1096
+ };
1097
+ module2.exports = function() {
1098
+ if (process.env.NODE_V8_COVERAGE) {
1099
+ return {
1100
+ WeakRef: CompatWeakRef,
1101
+ FinalizationRegistry: CompatFinalizer
1102
+ };
1103
+ }
1104
+ return {
1105
+ WeakRef: global.WeakRef || CompatWeakRef,
1106
+ FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer
1107
+ };
1108
+ };
1109
+ }
1110
+ });
1111
+
1112
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/agent.js
1113
+ var require_agent = __commonJS({
1114
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/agent.js"(exports2, module2) {
1115
+ "use strict";
1116
+ var { InvalidArgumentError } = require_errors();
1117
+ var { kClients: kClients2, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require_symbols();
1118
+ var DispatcherBase = require_dispatcher_base();
1119
+ var Pool = require_pool();
1120
+ var Client = require_client();
1121
+ var util = require_util();
1122
+ var createRedirectInterceptor = require_redirectInterceptor();
1123
+ var { WeakRef, FinalizationRegistry } = require_dispatcher_weakref()();
1124
+ var kOnConnect = Symbol("onConnect");
1125
+ var kOnDisconnect = Symbol("onDisconnect");
1126
+ var kOnConnectionError = Symbol("onConnectionError");
1127
+ var kMaxRedirections = Symbol("maxRedirections");
1128
+ var kOnDrain = Symbol("onDrain");
1129
+ var kFactory = Symbol("factory");
1130
+ var kFinalizer = Symbol("finalizer");
1131
+ var kOptions = Symbol("options");
1132
+ function defaultFactory(origin, opts) {
1133
+ return opts && opts.connections === 1 ? new Client(origin, opts) : new Pool(origin, opts);
1134
+ }
1135
+ var Agent = class extends DispatcherBase {
1136
+ constructor({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
1137
+ super();
1138
+ if (typeof factory !== "function") {
1139
+ throw new InvalidArgumentError("factory must be a function.");
1140
+ }
1141
+ if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
1142
+ throw new InvalidArgumentError("connect must be a function or an object");
1143
+ }
1144
+ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
1145
+ throw new InvalidArgumentError("maxRedirections must be a positive number");
1146
+ }
1147
+ if (connect && typeof connect !== "function") {
1148
+ connect = { ...connect };
1149
+ }
1150
+ this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) ? options.interceptors.Agent : [createRedirectInterceptor({ maxRedirections })];
1151
+ this[kOptions] = { ...util.deepClone(options), connect };
1152
+ this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : void 0;
1153
+ this[kMaxRedirections] = maxRedirections;
1154
+ this[kFactory] = factory;
1155
+ this[kClients2] = /* @__PURE__ */ new Map();
1156
+ this[kFinalizer] = new FinalizationRegistry(
1157
+ /* istanbul ignore next: gc is undeterministic */
1158
+ (key) => {
1159
+ const ref = this[kClients2].get(key);
1160
+ if (ref !== void 0 && ref.deref() === void 0) {
1161
+ this[kClients2].delete(key);
1162
+ }
1163
+ }
1164
+ );
1165
+ const agent = this;
1166
+ this[kOnDrain] = (origin, targets) => {
1167
+ agent.emit("drain", origin, [agent, ...targets]);
1168
+ };
1169
+ this[kOnConnect] = (origin, targets) => {
1170
+ agent.emit("connect", origin, [agent, ...targets]);
1171
+ };
1172
+ this[kOnDisconnect] = (origin, targets, err) => {
1173
+ agent.emit("disconnect", origin, [agent, ...targets], err);
1174
+ };
1175
+ this[kOnConnectionError] = (origin, targets, err) => {
1176
+ agent.emit("connectionError", origin, [agent, ...targets], err);
1177
+ };
1178
+ }
1179
+ get [kRunning]() {
1180
+ let ret = 0;
1181
+ for (const ref of this[kClients2].values()) {
1182
+ const client = ref.deref();
1183
+ if (client) {
1184
+ ret += client[kRunning];
1185
+ }
1186
+ }
1187
+ return ret;
1188
+ }
1189
+ [kDispatch](opts, handler) {
1190
+ let key;
1191
+ if (opts.origin && (typeof opts.origin === "string" || opts.origin instanceof URL)) {
1192
+ key = String(opts.origin);
1193
+ } else {
1194
+ throw new InvalidArgumentError("opts.origin must be a non-empty string or URL.");
1195
+ }
1196
+ const ref = this[kClients2].get(key);
1197
+ let dispatcher = ref ? ref.deref() : null;
1198
+ if (!dispatcher) {
1199
+ dispatcher = this[kFactory](opts.origin, this[kOptions]).on("drain", this[kOnDrain]).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]);
1200
+ this[kClients2].set(key, new WeakRef(dispatcher));
1201
+ this[kFinalizer].register(dispatcher, key);
1202
+ }
1203
+ return dispatcher.dispatch(opts, handler);
1204
+ }
1205
+ async [kClose]() {
1206
+ const closePromises = [];
1207
+ for (const ref of this[kClients2].values()) {
1208
+ const client = ref.deref();
1209
+ if (client) {
1210
+ closePromises.push(client.close());
1211
+ }
1212
+ }
1213
+ await Promise.all(closePromises);
1214
+ }
1215
+ async [kDestroy](err) {
1216
+ const destroyPromises = [];
1217
+ for (const ref of this[kClients2].values()) {
1218
+ const client = ref.deref();
1219
+ if (client) {
1220
+ destroyPromises.push(client.destroy(err));
1221
+ }
1222
+ }
1223
+ await Promise.all(destroyPromises);
1224
+ }
1225
+ };
1226
+ module2.exports = Agent;
1227
+ }
1228
+ });
1229
+
1230
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/mock-symbols.js
1231
+ var require_mock_symbols = __commonJS({
1232
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/mock-symbols.js"(exports2, module2) {
1233
+ "use strict";
1234
+ module2.exports = {
1235
+ kAgent: Symbol("agent"),
1236
+ kOptions: Symbol("options"),
1237
+ kFactory: Symbol("factory"),
1238
+ kDispatches: Symbol("dispatches"),
1239
+ kDispatchKey: Symbol("dispatch key"),
1240
+ kDefaultHeaders: Symbol("default headers"),
1241
+ kDefaultTrailers: Symbol("default trailers"),
1242
+ kContentLength: Symbol("content length"),
1243
+ kMockAgent: Symbol("mock agent"),
1244
+ kMockAgentSet: Symbol("mock agent set"),
1245
+ kMockAgentGet: Symbol("mock agent get"),
1246
+ kMockDispatch: Symbol("mock dispatch"),
1247
+ kClose: Symbol("close"),
1248
+ kOriginalClose: Symbol("original agent close"),
1249
+ kOrigin: Symbol("origin"),
1250
+ kIsMockActive: Symbol("is mock active"),
1251
+ kNetConnect: Symbol("net connect"),
1252
+ kGetNetConnect: Symbol("get net connect"),
1253
+ kConnected: Symbol("connected")
1254
+ };
1255
+ }
1256
+ });
1257
+
1258
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/mock-errors.js
1259
+ var require_mock_errors = __commonJS({
1260
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/mock-errors.js"(exports2, module2) {
1261
+ "use strict";
1262
+ var { UndiciError } = require_errors();
1263
+ var MockNotMatchedError = class extends UndiciError {
1264
+ constructor(message) {
1265
+ super(message);
1266
+ Error.captureStackTrace(this, MockNotMatchedError);
1267
+ this.name = "MockNotMatchedError";
1268
+ this.message = message || "The request does not match any registered mock dispatches";
1269
+ this.code = "UND_MOCK_ERR_MOCK_NOT_MATCHED";
1270
+ }
1271
+ };
1272
+ module2.exports = {
1273
+ MockNotMatchedError
1274
+ };
1275
+ }
1276
+ });
1277
+
1278
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/mock-utils.js
1279
+ var require_mock_utils = __commonJS({
1280
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/mock-utils.js"(exports2, module2) {
1281
+ "use strict";
1282
+ var { MockNotMatchedError } = require_mock_errors();
1283
+ var {
1284
+ kDispatches: kDispatches2,
1285
+ kMockAgent,
1286
+ kOriginalDispatch,
1287
+ kOrigin,
1288
+ kGetNetConnect
1289
+ } = require_mock_symbols();
1290
+ var { buildURL, nop } = require_util();
1291
+ var { STATUS_CODES } = require("http");
1292
+ var {
1293
+ types: {
1294
+ isPromise
1295
+ }
1296
+ } = require("util");
1297
+ function matchValue(match, value) {
1298
+ if (typeof match === "string") {
1299
+ return match === value;
1300
+ }
1301
+ if (match instanceof RegExp) {
1302
+ return match.test(value);
1303
+ }
1304
+ if (typeof match === "function") {
1305
+ return match(value) === true;
1306
+ }
1307
+ return false;
1308
+ }
1309
+ function lowerCaseEntries(headers) {
1310
+ return Object.fromEntries(
1311
+ Object.entries(headers).map(([headerName, headerValue]) => {
1312
+ return [headerName.toLocaleLowerCase(), headerValue];
1313
+ })
1314
+ );
1315
+ }
1316
+ function getHeaderByName(headers, key) {
1317
+ if (Array.isArray(headers)) {
1318
+ for (let i = 0; i < headers.length; i += 2) {
1319
+ if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {
1320
+ return headers[i + 1];
1321
+ }
1322
+ }
1323
+ return void 0;
1324
+ } else if (typeof headers.get === "function") {
1325
+ return headers.get(key);
1326
+ } else {
1327
+ return lowerCaseEntries(headers)[key.toLocaleLowerCase()];
1328
+ }
1329
+ }
1330
+ function buildHeadersFromArray(headers) {
1331
+ const clone = headers.slice();
1332
+ const entries = [];
1333
+ for (let index = 0; index < clone.length; index += 2) {
1334
+ entries.push([clone[index], clone[index + 1]]);
1335
+ }
1336
+ return Object.fromEntries(entries);
1337
+ }
1338
+ function matchHeaders(mockDispatch2, headers) {
1339
+ if (typeof mockDispatch2.headers === "function") {
1340
+ if (Array.isArray(headers)) {
1341
+ headers = buildHeadersFromArray(headers);
1342
+ }
1343
+ return mockDispatch2.headers(headers ? lowerCaseEntries(headers) : {});
1344
+ }
1345
+ if (typeof mockDispatch2.headers === "undefined") {
1346
+ return true;
1347
+ }
1348
+ if (typeof headers !== "object" || typeof mockDispatch2.headers !== "object") {
1349
+ return false;
1350
+ }
1351
+ for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch2.headers)) {
1352
+ const headerValue = getHeaderByName(headers, matchHeaderName);
1353
+ if (!matchValue(matchHeaderValue, headerValue)) {
1354
+ return false;
1355
+ }
1356
+ }
1357
+ return true;
1358
+ }
1359
+ function safeUrl(path) {
1360
+ if (typeof path !== "string") {
1361
+ return path;
1362
+ }
1363
+ const pathSegments = path.split("?");
1364
+ if (pathSegments.length !== 2) {
1365
+ return path;
1366
+ }
1367
+ const qp = new URLSearchParams(pathSegments.pop());
1368
+ qp.sort();
1369
+ return [...pathSegments, qp.toString()].join("?");
1370
+ }
1371
+ function matchKey(mockDispatch2, { path, method, body, headers }) {
1372
+ const pathMatch = matchValue(mockDispatch2.path, path);
1373
+ const methodMatch = matchValue(mockDispatch2.method, method);
1374
+ const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
1375
+ const headersMatch = matchHeaders(mockDispatch2, headers);
1376
+ return pathMatch && methodMatch && bodyMatch && headersMatch;
1377
+ }
1378
+ function getResponseData(data) {
1379
+ if (Buffer.isBuffer(data)) {
1380
+ return data;
1381
+ } else if (typeof data === "object") {
1382
+ return JSON.stringify(data);
1383
+ } else {
1384
+ return data.toString();
1385
+ }
1386
+ }
1387
+ function getMockDispatch(mockDispatches, key) {
1388
+ const basePath = key.query ? buildURL(key.path, key.query) : key.path;
1389
+ const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
1390
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath));
1391
+ if (matchedMockDispatches.length === 0) {
1392
+ throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
1393
+ }
1394
+ matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method));
1395
+ if (matchedMockDispatches.length === 0) {
1396
+ throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`);
1397
+ }
1398
+ matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== "undefined" ? matchValue(body, key.body) : true);
1399
+ if (matchedMockDispatches.length === 0) {
1400
+ throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`);
1401
+ }
1402
+ matchedMockDispatches = matchedMockDispatches.filter((mockDispatch2) => matchHeaders(mockDispatch2, key.headers));
1403
+ if (matchedMockDispatches.length === 0) {
1404
+ throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === "object" ? JSON.stringify(key.headers) : key.headers}'`);
1405
+ }
1406
+ return matchedMockDispatches[0];
1407
+ }
1408
+ function addMockDispatch(mockDispatches, key, data) {
1409
+ const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false };
1410
+ const replyData = typeof data === "function" ? { callback: data } : { ...data };
1411
+ const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } };
1412
+ mockDispatches.push(newMockDispatch);
1413
+ return newMockDispatch;
1414
+ }
1415
+ function deleteMockDispatch(mockDispatches, key) {
1416
+ const index = mockDispatches.findIndex((dispatch) => {
1417
+ if (!dispatch.consumed) {
1418
+ return false;
1419
+ }
1420
+ return matchKey(dispatch, key);
1421
+ });
1422
+ if (index !== -1) {
1423
+ mockDispatches.splice(index, 1);
1424
+ }
1425
+ }
1426
+ function buildKey(opts) {
1427
+ const { path, method, body, headers, query } = opts;
1428
+ return {
1429
+ path,
1430
+ method,
1431
+ body,
1432
+ headers,
1433
+ query
1434
+ };
1435
+ }
1436
+ function generateKeyValues(data) {
1437
+ return Object.entries(data).reduce((keyValuePairs, [key, value]) => [
1438
+ ...keyValuePairs,
1439
+ Buffer.from(`${key}`),
1440
+ Array.isArray(value) ? value.map((x) => Buffer.from(`${x}`)) : Buffer.from(`${value}`)
1441
+ ], []);
1442
+ }
1443
+ function getStatusText(statusCode) {
1444
+ return STATUS_CODES[statusCode] || "unknown";
1445
+ }
1446
+ async function getResponse(body) {
1447
+ const buffers = [];
1448
+ for await (const data of body) {
1449
+ buffers.push(data);
1450
+ }
1451
+ return Buffer.concat(buffers).toString("utf8");
1452
+ }
1453
+ function mockDispatch(opts, handler) {
1454
+ const key = buildKey(opts);
1455
+ const mockDispatch2 = getMockDispatch(this[kDispatches2], key);
1456
+ mockDispatch2.timesInvoked++;
1457
+ if (mockDispatch2.data.callback) {
1458
+ mockDispatch2.data = { ...mockDispatch2.data, ...mockDispatch2.data.callback(opts) };
1459
+ }
1460
+ const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch2;
1461
+ const { timesInvoked, times } = mockDispatch2;
1462
+ mockDispatch2.consumed = !persist && timesInvoked >= times;
1463
+ mockDispatch2.pending = timesInvoked < times;
1464
+ if (error !== null) {
1465
+ deleteMockDispatch(this[kDispatches2], key);
1466
+ handler.onError(error);
1467
+ return true;
1468
+ }
1469
+ if (typeof delay === "number" && delay > 0) {
1470
+ setTimeout(() => {
1471
+ handleReply(this[kDispatches2]);
1472
+ }, delay);
1473
+ } else {
1474
+ handleReply(this[kDispatches2]);
1475
+ }
1476
+ function handleReply(mockDispatches, _data = data) {
1477
+ const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers;
1478
+ const body = typeof _data === "function" ? _data({ ...opts, headers: optsHeaders }) : _data;
1479
+ if (isPromise(body)) {
1480
+ body.then((newData) => handleReply(mockDispatches, newData));
1481
+ return;
1482
+ }
1483
+ const responseData = getResponseData(body);
1484
+ const responseHeaders = generateKeyValues(headers);
1485
+ const responseTrailers = generateKeyValues(trailers);
1486
+ handler.abort = nop;
1487
+ handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode));
1488
+ handler.onData(Buffer.from(responseData));
1489
+ handler.onComplete(responseTrailers);
1490
+ deleteMockDispatch(mockDispatches, key);
1491
+ }
1492
+ function resume() {
1493
+ }
1494
+ return true;
1495
+ }
1496
+ function buildMockDispatch() {
1497
+ const agent = this[kMockAgent];
1498
+ const origin = this[kOrigin];
1499
+ const originalDispatch = this[kOriginalDispatch];
1500
+ return function dispatch(opts, handler) {
1501
+ if (agent.isMockActive) {
1502
+ try {
1503
+ mockDispatch.call(this, opts, handler);
1504
+ } catch (error) {
1505
+ if (error instanceof MockNotMatchedError) {
1506
+ const netConnect = agent[kGetNetConnect]();
1507
+ if (netConnect === false) {
1508
+ throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`);
1509
+ }
1510
+ if (checkNetConnect(netConnect, origin)) {
1511
+ originalDispatch.call(this, opts, handler);
1512
+ } else {
1513
+ throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`);
1514
+ }
1515
+ } else {
1516
+ throw error;
1517
+ }
1518
+ }
1519
+ } else {
1520
+ originalDispatch.call(this, opts, handler);
1521
+ }
1522
+ };
1523
+ }
1524
+ function checkNetConnect(netConnect, origin) {
1525
+ const url = new URL(origin);
1526
+ if (netConnect === true) {
1527
+ return true;
1528
+ } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {
1529
+ return true;
1530
+ }
1531
+ return false;
1532
+ }
1533
+ function buildMockOptions(opts) {
1534
+ if (opts) {
1535
+ const { agent, ...mockOptions } = opts;
1536
+ return mockOptions;
1537
+ }
1538
+ }
1539
+ module2.exports = {
1540
+ getResponseData,
1541
+ getMockDispatch,
1542
+ addMockDispatch,
1543
+ deleteMockDispatch,
1544
+ buildKey,
1545
+ generateKeyValues,
1546
+ matchValue,
1547
+ getResponse,
1548
+ getStatusText,
1549
+ mockDispatch,
1550
+ buildMockDispatch,
1551
+ checkNetConnect,
1552
+ buildMockOptions,
1553
+ getHeaderByName
1554
+ };
1555
+ }
1556
+ });
1557
+
1558
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/mock-interceptor.js
1559
+ var require_mock_interceptor = __commonJS({
1560
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/mock-interceptor.js"(exports2, module2) {
1561
+ "use strict";
1562
+ var { getResponseData, buildKey, addMockDispatch } = require_mock_utils();
1563
+ var {
1564
+ kDispatches: kDispatches2,
1565
+ kDispatchKey,
1566
+ kDefaultHeaders,
1567
+ kDefaultTrailers,
1568
+ kContentLength,
1569
+ kMockDispatch
1570
+ } = require_mock_symbols();
1571
+ var { InvalidArgumentError } = require_errors();
1572
+ var { buildURL } = require_util();
1573
+ var MockScope = class {
1574
+ constructor(mockDispatch) {
1575
+ this[kMockDispatch] = mockDispatch;
1576
+ }
1577
+ /**
1578
+ * Delay a reply by a set amount in ms.
1579
+ */
1580
+ delay(waitInMs) {
1581
+ if (typeof waitInMs !== "number" || !Number.isInteger(waitInMs) || waitInMs <= 0) {
1582
+ throw new InvalidArgumentError("waitInMs must be a valid integer > 0");
1583
+ }
1584
+ this[kMockDispatch].delay = waitInMs;
1585
+ return this;
1586
+ }
1587
+ /**
1588
+ * For a defined reply, never mark as consumed.
1589
+ */
1590
+ persist() {
1591
+ this[kMockDispatch].persist = true;
1592
+ return this;
1593
+ }
1594
+ /**
1595
+ * Allow one to define a reply for a set amount of matching requests.
1596
+ */
1597
+ times(repeatTimes) {
1598
+ if (typeof repeatTimes !== "number" || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {
1599
+ throw new InvalidArgumentError("repeatTimes must be a valid integer > 0");
1600
+ }
1601
+ this[kMockDispatch].times = repeatTimes;
1602
+ return this;
1603
+ }
1604
+ };
1605
+ var MockInterceptor = class {
1606
+ constructor(opts, mockDispatches) {
1607
+ if (typeof opts !== "object") {
1608
+ throw new InvalidArgumentError("opts must be an object");
1609
+ }
1610
+ if (typeof opts.path === "undefined") {
1611
+ throw new InvalidArgumentError("opts.path must be defined");
1612
+ }
1613
+ if (typeof opts.method === "undefined") {
1614
+ opts.method = "GET";
1615
+ }
1616
+ if (typeof opts.path === "string") {
1617
+ if (opts.query) {
1618
+ opts.path = buildURL(opts.path, opts.query);
1619
+ } else {
1620
+ const parsedURL = new URL(opts.path, "data://");
1621
+ opts.path = parsedURL.pathname + parsedURL.search;
1622
+ }
1623
+ }
1624
+ if (typeof opts.method === "string") {
1625
+ opts.method = opts.method.toUpperCase();
1626
+ }
1627
+ this[kDispatchKey] = buildKey(opts);
1628
+ this[kDispatches2] = mockDispatches;
1629
+ this[kDefaultHeaders] = {};
1630
+ this[kDefaultTrailers] = {};
1631
+ this[kContentLength] = false;
1632
+ }
1633
+ createMockScopeDispatchData(statusCode, data, responseOptions = {}) {
1634
+ const responseData = getResponseData(data);
1635
+ const contentLength = this[kContentLength] ? { "content-length": responseData.length } : {};
1636
+ const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers };
1637
+ const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers };
1638
+ return { statusCode, data, headers, trailers };
1639
+ }
1640
+ validateReplyParameters(statusCode, data, responseOptions) {
1641
+ if (typeof statusCode === "undefined") {
1642
+ throw new InvalidArgumentError("statusCode must be defined");
1643
+ }
1644
+ if (typeof data === "undefined") {
1645
+ throw new InvalidArgumentError("data must be defined");
1646
+ }
1647
+ if (typeof responseOptions !== "object") {
1648
+ throw new InvalidArgumentError("responseOptions must be an object");
1649
+ }
1650
+ }
1651
+ /**
1652
+ * Mock an undici request with a defined reply.
1653
+ */
1654
+ reply(replyData) {
1655
+ if (typeof replyData === "function") {
1656
+ const wrappedDefaultsCallback = (opts) => {
1657
+ const resolvedData = replyData(opts);
1658
+ if (typeof resolvedData !== "object") {
1659
+ throw new InvalidArgumentError("reply options callback must return an object");
1660
+ }
1661
+ const { statusCode: statusCode2, data: data2 = "", responseOptions: responseOptions2 = {} } = resolvedData;
1662
+ this.validateReplyParameters(statusCode2, data2, responseOptions2);
1663
+ return {
1664
+ ...this.createMockScopeDispatchData(statusCode2, data2, responseOptions2)
1665
+ };
1666
+ };
1667
+ const newMockDispatch2 = addMockDispatch(this[kDispatches2], this[kDispatchKey], wrappedDefaultsCallback);
1668
+ return new MockScope(newMockDispatch2);
1669
+ }
1670
+ const [statusCode, data = "", responseOptions = {}] = [...arguments];
1671
+ this.validateReplyParameters(statusCode, data, responseOptions);
1672
+ const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions);
1673
+ const newMockDispatch = addMockDispatch(this[kDispatches2], this[kDispatchKey], dispatchData);
1674
+ return new MockScope(newMockDispatch);
1675
+ }
1676
+ /**
1677
+ * Mock an undici request with a defined error.
1678
+ */
1679
+ replyWithError(error) {
1680
+ if (typeof error === "undefined") {
1681
+ throw new InvalidArgumentError("error must be defined");
1682
+ }
1683
+ const newMockDispatch = addMockDispatch(this[kDispatches2], this[kDispatchKey], { error });
1684
+ return new MockScope(newMockDispatch);
1685
+ }
1686
+ /**
1687
+ * Set default reply headers on the interceptor for subsequent replies
1688
+ */
1689
+ defaultReplyHeaders(headers) {
1690
+ if (typeof headers === "undefined") {
1691
+ throw new InvalidArgumentError("headers must be defined");
1692
+ }
1693
+ this[kDefaultHeaders] = headers;
1694
+ return this;
1695
+ }
1696
+ /**
1697
+ * Set default reply trailers on the interceptor for subsequent replies
1698
+ */
1699
+ defaultReplyTrailers(trailers) {
1700
+ if (typeof trailers === "undefined") {
1701
+ throw new InvalidArgumentError("trailers must be defined");
1702
+ }
1703
+ this[kDefaultTrailers] = trailers;
1704
+ return this;
1705
+ }
1706
+ /**
1707
+ * Set reply content length header for replies on the interceptor
1708
+ */
1709
+ replyContentLength() {
1710
+ this[kContentLength] = true;
1711
+ return this;
1712
+ }
1713
+ };
1714
+ module2.exports.MockInterceptor = MockInterceptor;
1715
+ module2.exports.MockScope = MockScope;
1716
+ }
1717
+ });
1718
+
1719
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/mock-client.js
1720
+ var require_mock_client = __commonJS({
1721
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/mock-client.js"(exports2, module2) {
1722
+ "use strict";
1723
+ var { promisify } = require("util");
1724
+ var Client = require_client();
1725
+ var { buildMockDispatch } = require_mock_utils();
1726
+ var {
1727
+ kDispatches: kDispatches2,
1728
+ kMockAgent,
1729
+ kClose,
1730
+ kOriginalClose,
1731
+ kOrigin,
1732
+ kOriginalDispatch,
1733
+ kConnected
1734
+ } = require_mock_symbols();
1735
+ var { MockInterceptor } = require_mock_interceptor();
1736
+ var Symbols = require_symbols();
1737
+ var { InvalidArgumentError } = require_errors();
1738
+ var MockClient = class extends Client {
1739
+ constructor(origin, opts) {
1740
+ super(origin, opts);
1741
+ if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
1742
+ throw new InvalidArgumentError("Argument opts.agent must implement Agent");
1743
+ }
1744
+ this[kMockAgent] = opts.agent;
1745
+ this[kOrigin] = origin;
1746
+ this[kDispatches2] = [];
1747
+ this[kConnected] = 1;
1748
+ this[kOriginalDispatch] = this.dispatch;
1749
+ this[kOriginalClose] = this.close.bind(this);
1750
+ this.dispatch = buildMockDispatch.call(this);
1751
+ this.close = this[kClose];
1752
+ }
1753
+ get [Symbols.kConnected]() {
1754
+ return this[kConnected];
1755
+ }
1756
+ /**
1757
+ * Sets up the base interceptor for mocking replies from undici.
1758
+ */
1759
+ intercept(opts) {
1760
+ return new MockInterceptor(opts, this[kDispatches2]);
1761
+ }
1762
+ async [kClose]() {
1763
+ await promisify(this[kOriginalClose])();
1764
+ this[kConnected] = 0;
1765
+ this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
1766
+ }
1767
+ };
1768
+ module2.exports = MockClient;
1769
+ }
1770
+ });
1771
+
1772
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/mock-pool.js
1773
+ var require_mock_pool = __commonJS({
1774
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/mock-pool.js"(exports2, module2) {
1775
+ "use strict";
1776
+ var { promisify } = require("util");
1777
+ var Pool = require_pool();
1778
+ var { buildMockDispatch } = require_mock_utils();
1779
+ var {
1780
+ kDispatches: kDispatches2,
1781
+ kMockAgent,
1782
+ kClose,
1783
+ kOriginalClose,
1784
+ kOrigin,
1785
+ kOriginalDispatch,
1786
+ kConnected
1787
+ } = require_mock_symbols();
1788
+ var { MockInterceptor } = require_mock_interceptor();
1789
+ var Symbols = require_symbols();
1790
+ var { InvalidArgumentError } = require_errors();
1791
+ var MockPool = class extends Pool {
1792
+ constructor(origin, opts) {
1793
+ super(origin, opts);
1794
+ if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
1795
+ throw new InvalidArgumentError("Argument opts.agent must implement Agent");
1796
+ }
1797
+ this[kMockAgent] = opts.agent;
1798
+ this[kOrigin] = origin;
1799
+ this[kDispatches2] = [];
1800
+ this[kConnected] = 1;
1801
+ this[kOriginalDispatch] = this.dispatch;
1802
+ this[kOriginalClose] = this.close.bind(this);
1803
+ this.dispatch = buildMockDispatch.call(this);
1804
+ this.close = this[kClose];
1805
+ }
1806
+ get [Symbols.kConnected]() {
1807
+ return this[kConnected];
1808
+ }
1809
+ /**
1810
+ * Sets up the base interceptor for mocking replies from undici.
1811
+ */
1812
+ intercept(opts) {
1813
+ return new MockInterceptor(opts, this[kDispatches2]);
1814
+ }
1815
+ async [kClose]() {
1816
+ await promisify(this[kOriginalClose])();
1817
+ this[kConnected] = 0;
1818
+ this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
1819
+ }
1820
+ };
1821
+ module2.exports = MockPool;
1822
+ }
1823
+ });
1824
+
1825
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/pluralizer.js
1826
+ var require_pluralizer = __commonJS({
1827
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/pluralizer.js"(exports2, module2) {
1828
+ "use strict";
1829
+ var singulars = {
1830
+ pronoun: "it",
1831
+ is: "is",
1832
+ was: "was",
1833
+ this: "this"
1834
+ };
1835
+ var plurals = {
1836
+ pronoun: "they",
1837
+ is: "are",
1838
+ was: "were",
1839
+ this: "these"
1840
+ };
1841
+ module2.exports = class Pluralizer {
1842
+ constructor(singular, plural) {
1843
+ this.singular = singular;
1844
+ this.plural = plural;
1845
+ }
1846
+ pluralize(count) {
1847
+ const one = count === 1;
1848
+ const keys = one ? singulars : plurals;
1849
+ const noun = one ? this.singular : this.plural;
1850
+ return { ...keys, count, noun };
1851
+ }
1852
+ };
1853
+ }
1854
+ });
1855
+
1856
+ // src/mock-agent/pending-interceptor-formatter.cjs
1857
+ var require_pending_interceptor_formatter = __commonJS({
1858
+ "src/mock-agent/pending-interceptor-formatter.cjs"(exports2, module2) {
1859
+ var util = require("node:util");
1860
+ module2.exports = class PendingInterceptorsFormatter {
1861
+ constructor({ disableColors } = {}) {
1862
+ this.inspectOptions = {
1863
+ breakLength: Infinity,
1864
+ colors: !disableColors && !process.env.CI
1865
+ };
1866
+ }
1867
+ format(pendingInterceptors) {
1868
+ const formatted = pendingInterceptors.map(
1869
+ ({
1870
+ method,
1871
+ path,
1872
+ data: { statusCode },
1873
+ persist,
1874
+ times,
1875
+ timesInvoked,
1876
+ origin
1877
+ }) => {
1878
+ const meta = {
1879
+ persist: Boolean(persist),
1880
+ invoked: timesInvoked,
1881
+ remaining: persist ? Infinity : times - timesInvoked
1882
+ };
1883
+ const inspectedMeta = util.inspect(meta, this.inspectOptions);
1884
+ return `- ${method} ${origin}${path} ${statusCode} ${inspectedMeta}`;
1885
+ }
1886
+ );
1887
+ return formatted.join("\n");
1888
+ }
1889
+ };
1890
+ }
1891
+ });
1892
+
1893
+ // ../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/mock-agent.js
1894
+ var require_mock_agent = __commonJS({
1895
+ "../../node_modules/.pnpm/undici@5.28.3/node_modules/undici/lib/mock/mock-agent.js"(exports2, module2) {
1896
+ "use strict";
1897
+ var { kClients: kClients2 } = require_symbols();
1898
+ var Agent = require_agent();
1899
+ var {
1900
+ kAgent,
1901
+ kMockAgentSet,
1902
+ kMockAgentGet,
1903
+ kDispatches: kDispatches2,
1904
+ kIsMockActive: kIsMockActive2,
1905
+ kNetConnect,
1906
+ kGetNetConnect,
1907
+ kOptions,
1908
+ kFactory
1909
+ } = require_mock_symbols();
1910
+ var MockClient = require_mock_client();
1911
+ var MockPool = require_mock_pool();
1912
+ var { matchValue, buildMockOptions } = require_mock_utils();
1913
+ var { InvalidArgumentError, UndiciError } = require_errors();
1914
+ var Dispatcher = require_dispatcher();
1915
+ var Pluralizer = require_pluralizer();
1916
+ var PendingInterceptorsFormatter = require_pending_interceptor_formatter();
1917
+ var FakeWeakRef = class {
1918
+ constructor(value) {
1919
+ this.value = value;
1920
+ }
1921
+ deref() {
1922
+ return this.value;
1923
+ }
1924
+ };
1925
+ var MockAgent2 = class extends Dispatcher {
1926
+ constructor(opts) {
1927
+ super(opts);
1928
+ this[kNetConnect] = true;
1929
+ this[kIsMockActive2] = true;
1930
+ if (opts && opts.agent && typeof opts.agent.dispatch !== "function") {
1931
+ throw new InvalidArgumentError("Argument opts.agent must implement Agent");
1932
+ }
1933
+ const agent = opts && opts.agent ? opts.agent : new Agent(opts);
1934
+ this[kAgent] = agent;
1935
+ this[kClients2] = agent[kClients2];
1936
+ this[kOptions] = buildMockOptions(opts);
1937
+ }
1938
+ get(origin) {
1939
+ let dispatcher = this[kMockAgentGet](origin);
1940
+ if (!dispatcher) {
1941
+ dispatcher = this[kFactory](origin);
1942
+ this[kMockAgentSet](origin, dispatcher);
1943
+ }
1944
+ return dispatcher;
1945
+ }
1946
+ dispatch(opts, handler) {
1947
+ this.get(opts.origin);
1948
+ return this[kAgent].dispatch(opts, handler);
1949
+ }
1950
+ async close() {
1951
+ await this[kAgent].close();
1952
+ this[kClients2].clear();
1953
+ }
1954
+ deactivate() {
1955
+ this[kIsMockActive2] = false;
1956
+ }
1957
+ activate() {
1958
+ this[kIsMockActive2] = true;
1959
+ }
1960
+ enableNetConnect(matcher) {
1961
+ if (typeof matcher === "string" || typeof matcher === "function" || matcher instanceof RegExp) {
1962
+ if (Array.isArray(this[kNetConnect])) {
1963
+ this[kNetConnect].push(matcher);
1964
+ } else {
1965
+ this[kNetConnect] = [matcher];
1966
+ }
1967
+ } else if (typeof matcher === "undefined") {
1968
+ this[kNetConnect] = true;
1969
+ } else {
1970
+ throw new InvalidArgumentError("Unsupported matcher. Must be one of String|Function|RegExp.");
1971
+ }
1972
+ }
1973
+ disableNetConnect() {
1974
+ this[kNetConnect] = false;
1975
+ }
1976
+ // This is required to bypass issues caused by using global symbols - see:
1977
+ // https://github.com/nodejs/undici/issues/1447
1978
+ get isMockActive() {
1979
+ return this[kIsMockActive2];
1980
+ }
1981
+ [kMockAgentSet](origin, dispatcher) {
1982
+ this[kClients2].set(origin, new FakeWeakRef(dispatcher));
1983
+ }
1984
+ [kFactory](origin) {
1985
+ const mockOptions = Object.assign({ agent: this }, this[kOptions]);
1986
+ return this[kOptions] && this[kOptions].connections === 1 ? new MockClient(origin, mockOptions) : new MockPool(origin, mockOptions);
1987
+ }
1988
+ [kMockAgentGet](origin) {
1989
+ const ref = this[kClients2].get(origin);
1990
+ if (ref) {
1991
+ return ref.deref();
1992
+ }
1993
+ if (typeof origin !== "string") {
1994
+ const dispatcher = this[kFactory]("http://localhost:9999");
1995
+ this[kMockAgentSet](origin, dispatcher);
1996
+ return dispatcher;
1997
+ }
1998
+ for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients2])) {
1999
+ const nonExplicitDispatcher = nonExplicitRef.deref();
2000
+ if (nonExplicitDispatcher && typeof keyMatcher !== "string" && matchValue(keyMatcher, origin)) {
2001
+ const dispatcher = this[kFactory](origin);
2002
+ this[kMockAgentSet](origin, dispatcher);
2003
+ dispatcher[kDispatches2] = nonExplicitDispatcher[kDispatches2];
2004
+ return dispatcher;
2005
+ }
2006
+ }
2007
+ }
2008
+ [kGetNetConnect]() {
2009
+ return this[kNetConnect];
2010
+ }
2011
+ pendingInterceptors() {
2012
+ const mockAgentClients = this[kClients2];
2013
+ return Array.from(mockAgentClients.entries()).flatMap(([origin, scope]) => scope.deref()[kDispatches2].map((dispatch) => ({ ...dispatch, origin }))).filter(({ pending }) => pending);
2014
+ }
2015
+ assertNoPendingInterceptors({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
2016
+ const pending = this.pendingInterceptors();
2017
+ if (pending.length === 0) {
2018
+ return;
2019
+ }
2020
+ const pluralizer = new Pluralizer("interceptor", "interceptors").pluralize(pending.length);
2021
+ throw new UndiciError(`
2022
+ ${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:
2023
+
2024
+ ${pendingInterceptorsFormatter.format(pending)}
2025
+ `.trim());
2026
+ }
2027
+ };
2028
+ module2.exports = MockAgent2;
2029
+ }
2030
+ });
2031
+
2032
+ // src/mock-agent/index.cjs
2033
+ globalThis.global = globalThis;
2034
+ process.versions = { node: "18.0.0" };
2035
+ var MockAgent = require_mock_agent();
2036
+ var { kClients } = require_symbols();
2037
+ var { kIsMockActive, kDispatches } = require_mock_symbols();
2038
+ var { setDispatcher } = require_dispatcher2();
2039
+ function isMockActive(agent) {
2040
+ return agent[kIsMockActive];
2041
+ }
2042
+ function resetMockAgent(agent) {
2043
+ agent.deactivate();
2044
+ agent.enableNetConnect();
2045
+ for (const mockClient of agent[kClients].values()) {
2046
+ mockClient.deref()?.[kDispatches].splice(0);
2047
+ }
2048
+ agent.assertNoPendingInterceptors();
2049
+ }
2050
+ module.exports = {
2051
+ MockAgent,
2052
+ setDispatcher,
2053
+ isMockActive,
2054
+ resetMockAgent
2055
+ };
2056
+ //# sourceMappingURL=mock-agent.cjs.map