oricore 1.4.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -559,6 +559,22 @@ var init_models = __esm({
559
559
  open_weights: false,
560
560
  limit: { context: 2e5, output: 65536 }
561
561
  },
562
+ "gemini-3.1-pro-preview": {
563
+ name: "Gemini 3.1 Pro Preview",
564
+ attachment: true,
565
+ reasoning: true,
566
+ temperature: true,
567
+ tool_call: true,
568
+ knowledge: "2025-01",
569
+ release_date: "2026-02-19",
570
+ last_updated: "2026-02-19",
571
+ modalities: {
572
+ input: ["text", "image", "audio", "video", "pdf"],
573
+ output: ["text"]
574
+ },
575
+ open_weights: false,
576
+ limit: { context: 1048576, output: 65536 }
577
+ },
562
578
  "gemini-3-flash-preview": {
563
579
  name: "Gemini 3 Flash Preview",
564
580
  attachment: true,
@@ -1040,6 +1056,19 @@ var init_models = __esm({
1040
1056
  open_weights: true,
1041
1057
  limit: { context: 204800, output: 131072 }
1042
1058
  },
1059
+ "glm-5": {
1060
+ name: "GLM-5",
1061
+ attachment: false,
1062
+ reasoning: true,
1063
+ temperature: true,
1064
+ tool_call: true,
1065
+ knowledge: "2025-06",
1066
+ release_date: "2026-02-10",
1067
+ last_updated: "2026-02-10",
1068
+ modalities: { input: ["text"], output: ["text"] },
1069
+ open_weights: true,
1070
+ limit: { context: 262144, output: 131072 }
1071
+ },
1043
1072
  "sonoma-dusk-alpha": {
1044
1073
  name: "Sonoma Dusk Alpha",
1045
1074
  attachment: true,
@@ -1131,6 +1160,20 @@ var init_models = __esm({
1131
1160
  open_weights: false,
1132
1161
  limit: { context: 2e5, output: 128e3 }
1133
1162
  },
1163
+ "claude-sonnet-4-6": {
1164
+ name: "Claude Sonnet 4.6",
1165
+ shortName: "Sonnet 4.6",
1166
+ attachment: true,
1167
+ reasoning: true,
1168
+ temperature: true,
1169
+ tool_call: true,
1170
+ knowledge: "2025-07-31",
1171
+ release_date: "2026-02-17",
1172
+ last_updated: "2026-02-17",
1173
+ modalities: { input: ["text", "image", "pdf"], output: ["text"] },
1174
+ open_weights: false,
1175
+ limit: { context: 1e6, output: 64e3 }
1176
+ },
1134
1177
  "ling-1t": {
1135
1178
  name: "InclusionAI Ling-1T",
1136
1179
  attachment: true,
@@ -1273,6 +1316,32 @@ var init_models = __esm({
1273
1316
  modalities: { input: ["text"], output: ["text"] },
1274
1317
  open_weights: true,
1275
1318
  limit: { context: 204800, output: 131072 }
1319
+ },
1320
+ "minimax-m2.5": {
1321
+ name: "MiniMax M2.5",
1322
+ attachment: false,
1323
+ reasoning: true,
1324
+ temperature: true,
1325
+ tool_call: true,
1326
+ knowledge: "",
1327
+ release_date: "2026-02-13",
1328
+ last_updated: "2026-02-13",
1329
+ modalities: { input: ["text"], output: ["text"] },
1330
+ open_weights: true,
1331
+ limit: { context: 204800, output: 131072 }
1332
+ },
1333
+ "minimax-m2.7": {
1334
+ name: "MiniMax M2.7",
1335
+ attachment: false,
1336
+ reasoning: true,
1337
+ temperature: true,
1338
+ tool_call: true,
1339
+ knowledge: "",
1340
+ release_date: "2026-03-18",
1341
+ last_updated: "2026-03-18",
1342
+ modalities: { input: ["text"], output: ["text"] },
1343
+ open_weights: true,
1344
+ limit: { context: 204800, output: 131072 }
1276
1345
  }
1277
1346
  };
1278
1347
  }
@@ -1418,12 +1487,16 @@ var require_symbols = __commonJS({
1418
1487
  kListeners: /* @__PURE__ */ Symbol("listeners"),
1419
1488
  kHTTPContext: /* @__PURE__ */ Symbol("http context"),
1420
1489
  kMaxConcurrentStreams: /* @__PURE__ */ Symbol("max concurrent streams"),
1490
+ kHTTP2InitialWindowSize: /* @__PURE__ */ Symbol("http2 initial window size"),
1491
+ kHTTP2ConnectionWindowSize: /* @__PURE__ */ Symbol("http2 connection window size"),
1421
1492
  kEnableConnectProtocol: /* @__PURE__ */ Symbol("http2session connect protocol"),
1422
1493
  kRemoteSettings: /* @__PURE__ */ Symbol("http2session remote settings"),
1423
1494
  kHTTP2Stream: /* @__PURE__ */ Symbol("http2session client stream"),
1495
+ kPingInterval: /* @__PURE__ */ Symbol("ping interval"),
1424
1496
  kNoProxyAgent: /* @__PURE__ */ Symbol("no proxy agent"),
1425
1497
  kHttpProxyAgent: /* @__PURE__ */ Symbol("http proxy agent"),
1426
- kHttpsProxyAgent: /* @__PURE__ */ Symbol("https proxy agent")
1498
+ kHttpsProxyAgent: /* @__PURE__ */ Symbol("https proxy agent"),
1499
+ kSocks5ProxyAgent: /* @__PURE__ */ Symbol("socks5 proxy agent")
1427
1500
  };
1428
1501
  }
1429
1502
  });
@@ -2013,6 +2086,29 @@ var require_errors = __commonJS({
2013
2086
  return true;
2014
2087
  }
2015
2088
  };
2089
+ var Socks5ProxyError = class extends UndiciError {
2090
+ constructor(message, code) {
2091
+ super(message);
2092
+ this.name = "Socks5ProxyError";
2093
+ this.message = message || "SOCKS5 proxy error";
2094
+ this.code = code || "UND_ERR_SOCKS5";
2095
+ }
2096
+ };
2097
+ var kMessageSizeExceededError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED");
2098
+ var MessageSizeExceededError = class extends UndiciError {
2099
+ constructor(message) {
2100
+ super(message);
2101
+ this.name = "MessageSizeExceededError";
2102
+ this.message = message || "Max decompressed message size exceeded";
2103
+ this.code = "UND_ERR_WS_MESSAGE_SIZE_EXCEEDED";
2104
+ }
2105
+ static [Symbol.hasInstance](instance) {
2106
+ return instance && instance[kMessageSizeExceededError] === true;
2107
+ }
2108
+ get [kMessageSizeExceededError]() {
2109
+ return true;
2110
+ }
2111
+ };
2016
2112
  module2.exports = {
2017
2113
  AbortError,
2018
2114
  HTTPParserError,
@@ -2036,7 +2132,9 @@ var require_errors = __commonJS({
2036
2132
  RequestRetryError,
2037
2133
  ResponseError,
2038
2134
  SecureProxyConnectionError,
2039
- MaxOriginsReachedError
2135
+ MaxOriginsReachedError,
2136
+ Socks5ProxyError,
2137
+ MessageSizeExceededError
2040
2138
  };
2041
2139
  }
2042
2140
  });
@@ -2356,6 +2454,8 @@ var require_util = __commonJS({
2356
2454
  return body;
2357
2455
  } else if (body && typeof body.pipeTo === "function") {
2358
2456
  return new BodyAsyncIterable(body);
2457
+ } else if (body && isFormDataLike(body)) {
2458
+ return body;
2359
2459
  } else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable(body)) {
2360
2460
  return new BodyAsyncIterable(body);
2361
2461
  } else {
@@ -2480,6 +2580,11 @@ var require_util = __commonJS({
2480
2580
  function isIterable(obj) {
2481
2581
  return !!(obj != null && (typeof obj[Symbol.iterator] === "function" || typeof obj[Symbol.asyncIterator] === "function"));
2482
2582
  }
2583
+ function hasSafeIterator(obj) {
2584
+ const prototype = Object.getPrototypeOf(obj);
2585
+ const ownIterator = Object.prototype.hasOwnProperty.call(obj, Symbol.iterator);
2586
+ return ownIterator || prototype != null && prototype !== Object.prototype && typeof obj[Symbol.iterator] === "function";
2587
+ }
2483
2588
  function bodyLength(body) {
2484
2589
  if (body == null) {
2485
2590
  return 0;
@@ -2530,51 +2635,46 @@ var require_util = __commonJS({
2530
2635
  for (let i = 0; i < headers.length; i += 2) {
2531
2636
  const key = headerNameToString(headers[i]);
2532
2637
  let val = obj[key];
2533
- if (val) {
2534
- if (typeof val === "string") {
2535
- val = [val];
2536
- obj[key] = val;
2537
- }
2538
- val.push(headers[i + 1].toString("utf8"));
2539
- } else {
2540
- const headersValue = headers[i + 1];
2541
- if (typeof headersValue === "string") {
2542
- obj[key] = headersValue;
2638
+ if (val !== void 0) {
2639
+ if (!Object.hasOwn(obj, key)) {
2640
+ const headersValue = typeof headers[i + 1] === "string" ? headers[i + 1] : Array.isArray(headers[i + 1]) ? headers[i + 1].map((x) => x.toString("latin1")) : headers[i + 1].toString("latin1");
2641
+ if (key === "__proto__") {
2642
+ Object.defineProperty(obj, key, {
2643
+ value: headersValue,
2644
+ enumerable: true,
2645
+ configurable: true,
2646
+ writable: true
2647
+ });
2648
+ } else {
2649
+ obj[key] = headersValue;
2650
+ }
2543
2651
  } else {
2544
- obj[key] = Array.isArray(headersValue) ? headersValue.map((x) => x.toString("utf8")) : headersValue.toString("utf8");
2652
+ if (typeof val === "string") {
2653
+ val = [val];
2654
+ obj[key] = val;
2655
+ }
2656
+ val.push(headers[i + 1].toString("latin1"));
2545
2657
  }
2658
+ } else {
2659
+ const headersValue = typeof headers[i + 1] === "string" ? headers[i + 1] : Array.isArray(headers[i + 1]) ? headers[i + 1].map((x) => x.toString("latin1")) : headers[i + 1].toString("latin1");
2660
+ obj[key] = headersValue;
2546
2661
  }
2547
2662
  }
2548
- if ("content-length" in obj && "content-disposition" in obj) {
2549
- obj["content-disposition"] = Buffer.from(obj["content-disposition"]).toString("latin1");
2550
- }
2551
2663
  return obj;
2552
2664
  }
2553
2665
  function parseRawHeaders(headers) {
2554
2666
  const headersLength = headers.length;
2555
2667
  const ret = new Array(headersLength);
2556
- let hasContentLength = false;
2557
- let contentDispositionIdx = -1;
2558
2668
  let key;
2559
2669
  let val;
2560
- let kLen = 0;
2561
2670
  for (let n = 0; n < headersLength; n += 2) {
2562
2671
  key = headers[n];
2563
2672
  val = headers[n + 1];
2564
2673
  typeof key !== "string" && (key = key.toString());
2565
- typeof val !== "string" && (val = val.toString("utf8"));
2566
- kLen = key.length;
2567
- if (kLen === 14 && key[7] === "-" && (key === "content-length" || key.toLowerCase() === "content-length")) {
2568
- hasContentLength = true;
2569
- } else if (kLen === 19 && key[7] === "-" && (key === "content-disposition" || key.toLowerCase() === "content-disposition")) {
2570
- contentDispositionIdx = n + 1;
2571
- }
2674
+ typeof val !== "string" && (val = val.toString("latin1"));
2572
2675
  ret[n] = key;
2573
2676
  ret[n + 1] = val;
2574
2677
  }
2575
- if (hasContentLength && contentDispositionIdx !== -1) {
2576
- ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString("latin1");
2577
- }
2578
2678
  return ret;
2579
2679
  }
2580
2680
  function encodeRawHeaders(headers) {
@@ -3089,6 +3189,7 @@ var require_util = __commonJS({
3089
3189
  getServerName,
3090
3190
  isStream,
3091
3191
  isIterable,
3192
+ hasSafeIterator,
3092
3193
  isAsyncIterable,
3093
3194
  isDestroyed,
3094
3195
  headerNameToString,
@@ -3327,10 +3428,12 @@ var require_diagnostics = __commonJS({
3327
3428
  diagnosticsChannel.subscribe(
3328
3429
  "undici:websocket:open",
3329
3430
  (evt) => {
3330
- const {
3331
- address: { address, port }
3332
- } = evt;
3333
- debugLog("connection opened %s%s", address, port ? `:${port}` : "");
3431
+ if (evt.address != null) {
3432
+ const { address, port } = evt.address;
3433
+ debugLog("connection opened %s%s", address, port ? `:${port}` : "");
3434
+ } else {
3435
+ debugLog("connection opened");
3436
+ }
3334
3437
  }
3335
3438
  );
3336
3439
  diagnosticsChannel.subscribe(
@@ -3395,6 +3498,7 @@ var require_request = __commonJS({
3395
3498
  isBuffer,
3396
3499
  isFormDataLike,
3397
3500
  isIterable,
3501
+ hasSafeIterator,
3398
3502
  isBlobLike,
3399
3503
  serializePathWithQuery,
3400
3504
  assertRequestHandler,
@@ -3422,7 +3526,8 @@ var require_request = __commonJS({
3422
3526
  expectContinue,
3423
3527
  servername,
3424
3528
  throwOnError,
3425
- maxRedirections
3529
+ maxRedirections,
3530
+ typeOfService
3426
3531
  }, handler) {
3427
3532
  if (typeof path26 !== "string") {
3428
3533
  throw new InvalidArgumentError("path must be a string");
@@ -3439,6 +3544,9 @@ var require_request = __commonJS({
3439
3544
  if (upgrade && typeof upgrade !== "string") {
3440
3545
  throw new InvalidArgumentError("upgrade must be a string");
3441
3546
  }
3547
+ if (upgrade && !isValidHeaderValue(upgrade)) {
3548
+ throw new InvalidArgumentError("invalid upgrade header");
3549
+ }
3442
3550
  if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
3443
3551
  throw new InvalidArgumentError("invalid headersTimeout");
3444
3552
  }
@@ -3457,9 +3565,13 @@ var require_request = __commonJS({
3457
3565
  if (maxRedirections != null && maxRedirections !== 0) {
3458
3566
  throw new InvalidArgumentError("maxRedirections is not supported, use the redirect interceptor");
3459
3567
  }
3568
+ if (typeOfService != null && (!Number.isInteger(typeOfService) || typeOfService < 0 || typeOfService > 255)) {
3569
+ throw new InvalidArgumentError("typeOfService must be an integer between 0 and 255");
3570
+ }
3460
3571
  this.headersTimeout = headersTimeout;
3461
3572
  this.bodyTimeout = bodyTimeout;
3462
3573
  this.method = method;
3574
+ this.typeOfService = typeOfService ?? 0;
3463
3575
  this.abort = null;
3464
3576
  if (body == null) {
3465
3577
  this.body = null;
@@ -3515,7 +3627,7 @@ var require_request = __commonJS({
3515
3627
  processHeader(this, headers[i], headers[i + 1]);
3516
3628
  }
3517
3629
  } else if (headers && typeof headers === "object") {
3518
- if (headers[Symbol.iterator]) {
3630
+ if (hasSafeIterator(headers)) {
3519
3631
  for (const header of headers) {
3520
3632
  if (!Array.isArray(header) || header.length !== 2) {
3521
3633
  throw new InvalidArgumentError("headers must be in key-value pair format");
@@ -3684,12 +3796,18 @@ var require_request = __commonJS({
3684
3796
  } else {
3685
3797
  val = `${val}`;
3686
3798
  }
3687
- if (request.host === null && headerName === "host") {
3799
+ if (headerName === "host") {
3800
+ if (request.host !== null) {
3801
+ throw new InvalidArgumentError("duplicate host header");
3802
+ }
3688
3803
  if (typeof val !== "string") {
3689
3804
  throw new InvalidArgumentError("invalid host header");
3690
3805
  }
3691
3806
  request.host = val;
3692
- } else if (request.contentLength === null && headerName === "content-length") {
3807
+ } else if (headerName === "content-length") {
3808
+ if (request.contentLength !== null) {
3809
+ throw new InvalidArgumentError("duplicate content-length header");
3810
+ }
3693
3811
  request.contentLength = parseInt(val, 10);
3694
3812
  if (!Number.isFinite(request.contentLength)) {
3695
3813
  throw new InvalidArgumentError("invalid content-length header");
@@ -3700,12 +3818,18 @@ var require_request = __commonJS({
3700
3818
  } else if (headerName === "transfer-encoding" || headerName === "keep-alive" || headerName === "upgrade") {
3701
3819
  throw new InvalidArgumentError(`invalid ${headerName} header`);
3702
3820
  } else if (headerName === "connection") {
3703
- const value = typeof val === "string" ? val.toLowerCase() : null;
3704
- if (value !== "close" && value !== "keep-alive") {
3821
+ const value = typeof val === "string" ? val : null;
3822
+ if (value === null) {
3705
3823
  throw new InvalidArgumentError("invalid connection header");
3706
3824
  }
3707
- if (value === "close") {
3708
- request.reset = true;
3825
+ for (const token of value.toLowerCase().split(",")) {
3826
+ const trimmed = token.trim();
3827
+ if (!isValidHTTPToken(trimmed)) {
3828
+ throw new InvalidArgumentError("invalid connection header");
3829
+ }
3830
+ if (trimmed === "close") {
3831
+ request.reset = true;
3832
+ }
3709
3833
  }
3710
3834
  } else if (headerName === "expect") {
3711
3835
  throw new NotSupportedError("expect header not supported");
@@ -3734,6 +3858,9 @@ var require_wrap_handler = __commonJS({
3734
3858
  onConnect(abort, context) {
3735
3859
  return this.#handler.onConnect?.(abort, context);
3736
3860
  }
3861
+ onResponseStarted() {
3862
+ return this.#handler.onResponseStarted?.();
3863
+ }
3737
3864
  onHeaders(statusCode, rawHeaders, resume, statusMessage) {
3738
3865
  return this.#handler.onHeaders?.(statusCode, rawHeaders, resume, statusMessage);
3739
3866
  }
@@ -3759,14 +3886,14 @@ var require_wrap_handler = __commonJS({
3759
3886
  onRequestUpgrade(controller, statusCode, headers, socket) {
3760
3887
  const rawHeaders = [];
3761
3888
  for (const [key, val] of Object.entries(headers)) {
3762
- rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map((v) => Buffer.from(v)) : Buffer.from(val));
3889
+ rawHeaders.push(Buffer.from(key, "latin1"), toRawHeaderValue(val));
3763
3890
  }
3764
3891
  this.#handler.onUpgrade?.(statusCode, rawHeaders, socket);
3765
3892
  }
3766
3893
  onResponseStart(controller, statusCode, headers, statusMessage) {
3767
3894
  const rawHeaders = [];
3768
3895
  for (const [key, val] of Object.entries(headers)) {
3769
- rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map((v) => Buffer.from(v)) : Buffer.from(val));
3896
+ rawHeaders.push(Buffer.from(key, "latin1"), toRawHeaderValue(val));
3770
3897
  }
3771
3898
  if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) {
3772
3899
  controller.pause();
@@ -3780,7 +3907,7 @@ var require_wrap_handler = __commonJS({
3780
3907
  onResponseEnd(controller, trailers) {
3781
3908
  const rawTrailers = [];
3782
3909
  for (const [key, val] of Object.entries(trailers)) {
3783
- rawTrailers.push(Buffer.from(key), Array.isArray(val) ? val.map((v) => Buffer.from(v)) : Buffer.from(val));
3910
+ rawTrailers.push(Buffer.from(key, "latin1"), toRawHeaderValue(val));
3784
3911
  }
3785
3912
  this.#handler.onComplete?.(rawTrailers);
3786
3913
  }
@@ -3791,6 +3918,9 @@ var require_wrap_handler = __commonJS({
3791
3918
  this.#handler.onError?.(err);
3792
3919
  }
3793
3920
  };
3921
+ function toRawHeaderValue(value) {
3922
+ return Array.isArray(value) ? value.map((item) => Buffer.from(item, "latin1")) : Buffer.from(value, "latin1");
3923
+ }
3794
3924
  }
3795
3925
  });
3796
3926
 
@@ -3891,6 +4021,9 @@ var require_unwrap_handler = __commonJS({
3891
4021
  this.#controller = new UnwrapController(abort);
3892
4022
  this.#handler.onRequestStart?.(this.#controller, context);
3893
4023
  }
4024
+ onResponseStarted() {
4025
+ return this.#handler.onResponseStarted?.();
4026
+ }
3894
4027
  onUpgrade(statusCode, rawHeaders, socket) {
3895
4028
  this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket);
3896
4029
  }
@@ -5610,6 +5743,7 @@ var require_runtime_features = __commonJS({
5610
5743
  var require_webidl = __commonJS({
5611
5744
  "node_modules/undici/lib/web/webidl/index.js"(exports2, module2) {
5612
5745
  "use strict";
5746
+ var assert5 = require("assert");
5613
5747
  var { types, inspect } = require("util");
5614
5748
  var { runtimeFeatures } = require_runtime_features();
5615
5749
  var UNDEFINED = 1;
@@ -5896,6 +6030,7 @@ var require_webidl = __commonJS({
5896
6030
  };
5897
6031
  };
5898
6032
  webidl.dictionaryConverter = function(converters) {
6033
+ converters.sort((a, b) => (a.key > b.key) - (a.key < b.key));
5899
6034
  return (dictionary, prefix, argument) => {
5900
6035
  const dict = {};
5901
6036
  if (dictionary != null && webidl.util.Type(dictionary) !== OBJECT) {
@@ -5954,6 +6089,27 @@ var require_webidl = __commonJS({
5954
6089
  webidl.is.BufferSource = function(V) {
5955
6090
  return types.isArrayBuffer(V) || ArrayBuffer.isView(V) && types.isArrayBuffer(V.buffer);
5956
6091
  };
6092
+ webidl.util.getCopyOfBytesHeldByBufferSource = function(bufferSource) {
6093
+ const jsBufferSource = bufferSource;
6094
+ let jsArrayBuffer = jsBufferSource;
6095
+ let offset = 0;
6096
+ let length = 0;
6097
+ if (types.isTypedArray(jsBufferSource) || types.isDataView(jsBufferSource)) {
6098
+ jsArrayBuffer = jsBufferSource.buffer;
6099
+ offset = jsBufferSource.byteOffset;
6100
+ length = jsBufferSource.byteLength;
6101
+ } else {
6102
+ assert5(types.isAnyArrayBuffer(jsBufferSource));
6103
+ length = jsBufferSource.byteLength;
6104
+ }
6105
+ if (jsArrayBuffer.detached) {
6106
+ return new Uint8Array(0);
6107
+ }
6108
+ const bytes = new Uint8Array(length);
6109
+ const view = new Uint8Array(jsArrayBuffer, offset, length);
6110
+ bytes.set(view);
6111
+ return bytes;
6112
+ };
5957
6113
  webidl.converters.DOMString = function(V, prefix, argument, flags) {
5958
6114
  if (V === null && webidl.util.HasFlag(flags, webidl.attributes.LegacyNullToEmptyString)) {
5959
6115
  return "";
@@ -6878,6 +7034,15 @@ var require_util2 = __commonJS({
6878
7034
  }
6879
7035
  return gettingDecodingSplitting(value);
6880
7036
  }
7037
+ function hasAuthenticationEntry(request) {
7038
+ return false;
7039
+ }
7040
+ function includesCredentials(url) {
7041
+ return !!(url.username || url.password);
7042
+ }
7043
+ function isTraversableNavigable(navigable) {
7044
+ return true;
7045
+ }
6881
7046
  var EnvironmentSettingsObjectBase = class {
6882
7047
  get baseUrl() {
6883
7048
  return getGlobalOrigin();
@@ -6935,7 +7100,10 @@ var require_util2 = __commonJS({
6935
7100
  extractMimeType,
6936
7101
  getDecodeSplit,
6937
7102
  environmentSettingsObject,
6938
- isOriginIPPotentiallyTrustworthy
7103
+ isOriginIPPotentiallyTrustworthy,
7104
+ hasAuthenticationEntry,
7105
+ includesCredentials,
7106
+ isTraversableNavigable
6939
7107
  };
6940
7108
  }
6941
7109
  });
@@ -7112,9 +7280,9 @@ var require_formdata_parser = __commonJS({
7112
7280
  var { webidl } = require_webidl();
7113
7281
  var assert5 = require("assert");
7114
7282
  var { isomorphicDecode } = require_infra();
7115
- var { utf8DecodeBytes } = require_encoding();
7116
7283
  var dd = Buffer.from("--");
7117
7284
  var decoder = new TextDecoder();
7285
+ var decoderIgnoreBOM = new TextDecoder("utf-8", { ignoreBOM: true });
7118
7286
  function isAsciiString(chars) {
7119
7287
  for (let i = 0; i < chars.length; ++i) {
7120
7288
  if ((chars.charCodeAt(i) & ~127) !== 0) {
@@ -7191,7 +7359,7 @@ var require_formdata_parser = __commonJS({
7191
7359
  }
7192
7360
  value = new File([body], filename, { type: contentType });
7193
7361
  } else {
7194
- value = utf8DecodeBytes(Buffer.from(body));
7362
+ value = decoderIgnoreBOM.decode(Buffer.from(body));
7195
7363
  }
7196
7364
  assert5(webidl.is.USVString(name));
7197
7365
  assert5(typeof value === "string" && webidl.is.USVString(value) || webidl.is.File(value));
@@ -7460,7 +7628,7 @@ var require_body = __commonJS({
7460
7628
  var { webidl } = require_webidl();
7461
7629
  var assert5 = require("assert");
7462
7630
  var { isErrored, isDisturbed } = require("stream");
7463
- var { isArrayBuffer } = require("util/types");
7631
+ var { isUint8Array } = require("util/types");
7464
7632
  var { serializeAMimeType } = require_data_url();
7465
7633
  var { multipartFormDataParser } = require_formdata_parser();
7466
7634
  var { createDeferredPromise } = require_promise();
@@ -7479,20 +7647,19 @@ var require_body = __commonJS({
7479
7647
  });
7480
7648
  function extractBody(object, keepalive = false) {
7481
7649
  let stream = null;
7650
+ let controller = null;
7482
7651
  if (webidl.is.ReadableStream(object)) {
7483
7652
  stream = object;
7484
7653
  } else if (webidl.is.Blob(object)) {
7485
7654
  stream = object.stream();
7486
7655
  } else {
7487
7656
  stream = new ReadableStream({
7488
- pull(controller) {
7489
- const buffer = typeof source === "string" ? textEncoder.encode(source) : source;
7490
- if (buffer.byteLength) {
7491
- controller.enqueue(buffer);
7492
- }
7493
- queueMicrotask(() => readableStreamClose(controller));
7657
+ pull() {
7494
7658
  },
7495
- start() {
7659
+ start(c) {
7660
+ controller = c;
7661
+ },
7662
+ cancel() {
7496
7663
  },
7497
7664
  type: "bytes"
7498
7665
  });
@@ -7509,7 +7676,7 @@ var require_body = __commonJS({
7509
7676
  source = object.toString();
7510
7677
  type = "application/x-www-form-urlencoded;charset=UTF-8";
7511
7678
  } else if (webidl.is.BufferSource(object)) {
7512
- source = isArrayBuffer(object) ? new Uint8Array(object.slice()) : new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength));
7679
+ source = webidl.util.getCopyOfBytesHeldByBufferSource(object);
7513
7680
  } else if (webidl.is.FormData(object)) {
7514
7681
  const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, "0")}`;
7515
7682
  const prefix = `--${boundary}\r
@@ -7576,38 +7743,29 @@ Content-Type: ${value.type || "application/octet-stream"}\r
7576
7743
  }
7577
7744
  stream = webidl.is.ReadableStream(object) ? object : ReadableStreamFrom(object);
7578
7745
  }
7579
- if (typeof source === "string" || util.isBuffer(source)) {
7580
- length = Buffer.byteLength(source);
7746
+ if (typeof source === "string" || isUint8Array(source)) {
7747
+ action = () => {
7748
+ length = typeof source === "string" ? Buffer.byteLength(source) : source.length;
7749
+ return source;
7750
+ };
7581
7751
  }
7582
7752
  if (action != null) {
7583
- let iterator;
7584
- stream = new ReadableStream({
7585
- start() {
7586
- iterator = action(object)[Symbol.asyncIterator]();
7587
- },
7588
- pull(controller) {
7589
- return iterator.next().then(({ value, done }) => {
7590
- if (done) {
7591
- queueMicrotask(() => {
7592
- controller.close();
7593
- controller.byobRequest?.respond(0);
7594
- });
7595
- } else {
7596
- if (!isErrored(stream)) {
7597
- const buffer = new Uint8Array(value);
7598
- if (buffer.byteLength) {
7599
- controller.enqueue(buffer);
7600
- }
7601
- }
7753
+ ;
7754
+ (async () => {
7755
+ const result = action();
7756
+ const iterator = result?.[Symbol.asyncIterator]?.();
7757
+ if (iterator) {
7758
+ for await (const bytes of iterator) {
7759
+ if (isErrored(stream)) break;
7760
+ if (bytes.length) {
7761
+ controller.enqueue(new Uint8Array(bytes));
7602
7762
  }
7603
- return controller.desiredSize > 0;
7604
- });
7605
- },
7606
- cancel(reason) {
7607
- return iterator.return();
7608
- },
7609
- type: "bytes"
7610
- });
7763
+ }
7764
+ } else if (result?.length && !isErrored(stream)) {
7765
+ controller.enqueue(typeof result === "string" ? textEncoder.encode(result) : new Uint8Array(result));
7766
+ }
7767
+ queueMicrotask(() => readableStreamClose(controller));
7768
+ })();
7611
7769
  }
7612
7770
  const body = { stream, source, length };
7613
7771
  return [body, type];
@@ -7695,13 +7853,10 @@ Content-Type: ${value.type || "application/octet-stream"}\r
7695
7853
  } catch (e) {
7696
7854
  return Promise.reject(e);
7697
7855
  }
7698
- const state = getInternalState(object);
7699
- if (bodyUnusable(state)) {
7856
+ object = getInternalState(object);
7857
+ if (bodyUnusable(object)) {
7700
7858
  return Promise.reject(new TypeError("Body is unusable: Body has already been read"));
7701
7859
  }
7702
- if (state.aborted) {
7703
- return Promise.reject(new DOMException("The operation was aborted.", "AbortError"));
7704
- }
7705
7860
  const promise = createDeferredPromise();
7706
7861
  const errorSteps = promise.reject;
7707
7862
  const successSteps = (data) => {
@@ -7711,11 +7866,11 @@ Content-Type: ${value.type || "application/octet-stream"}\r
7711
7866
  errorSteps(e);
7712
7867
  }
7713
7868
  };
7714
- if (state.body == null) {
7869
+ if (object.body == null) {
7715
7870
  successSteps(Buffer.allocUnsafe(0));
7716
7871
  return promise.promise;
7717
7872
  }
7718
- fullyReadBody(state.body, successSteps, errorSteps);
7873
+ fullyReadBody(object.body, successSteps, errorSteps);
7719
7874
  return promise.promise;
7720
7875
  }
7721
7876
  function bodyUnusable(object) {
@@ -8317,8 +8472,12 @@ var require_client_h1 = __commonJS({
8317
8472
  return 0;
8318
8473
  }
8319
8474
  };
8320
- function onParserTimeout(parser) {
8321
- const { socket, timeoutType, client, paused } = parser.deref();
8475
+ function onParserTimeout(parserWeakRef) {
8476
+ const parser = parserWeakRef.deref();
8477
+ if (!parser) {
8478
+ return;
8479
+ }
8480
+ const { socket, timeoutType, client, paused } = parser;
8322
8481
  if (timeoutType === TIMEOUT_HEADERS) {
8323
8482
  if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
8324
8483
  assert5(!paused, "cannot be paused while waiting for headers");
@@ -8554,6 +8713,9 @@ var require_client_h1 = __commonJS({
8554
8713
  if (blocking) {
8555
8714
  socket[kBlocking] = true;
8556
8715
  }
8716
+ if (socket.setTypeOfService) {
8717
+ socket.setTypeOfService(request.typeOfService);
8718
+ }
8557
8719
  let header = `${method} ${path26} HTTP/1.1\r
8558
8720
  `;
8559
8721
  if (typeof host === "string") {
@@ -8928,7 +9090,10 @@ var require_client_h2 = __commonJS({
8928
9090
  kStrictContentLength,
8929
9091
  kOnError,
8930
9092
  kMaxConcurrentStreams,
9093
+ kPingInterval,
8931
9094
  kHTTP2Session,
9095
+ kHTTP2InitialWindowSize,
9096
+ kHTTP2ConnectionWindowSize,
8932
9097
  kResume,
8933
9098
  kSize,
8934
9099
  kHTTPContext,
@@ -8936,7 +9101,8 @@ var require_client_h2 = __commonJS({
8936
9101
  kBodyTimeout,
8937
9102
  kEnableConnectProtocol,
8938
9103
  kRemoteSettings,
8939
- kHTTP2Stream
9104
+ kHTTP2Stream,
9105
+ kHTTP2SessionState
8940
9106
  } = require_symbols();
8941
9107
  var { channels } = require_diagnostics();
8942
9108
  var kOpenStreams = /* @__PURE__ */ Symbol("open streams");
@@ -8976,20 +9142,31 @@ var require_client_h2 = __commonJS({
8976
9142
  }
8977
9143
  function connectH2(client, socket) {
8978
9144
  client[kSocket] = socket;
9145
+ const http2InitialWindowSize = client[kHTTP2InitialWindowSize];
9146
+ const http2ConnectionWindowSize = client[kHTTP2ConnectionWindowSize];
8979
9147
  const session = http2.connect(client[kUrl], {
8980
9148
  createConnection: () => socket,
8981
9149
  peerMaxConcurrentStreams: client[kMaxConcurrentStreams],
8982
9150
  settings: {
8983
9151
  // TODO(metcoder95): add support for PUSH
8984
- enablePush: false
9152
+ enablePush: false,
9153
+ ...http2InitialWindowSize != null ? { initialWindowSize: http2InitialWindowSize } : null
8985
9154
  }
8986
9155
  });
9156
+ client[kSocket] = socket;
8987
9157
  session[kOpenStreams] = 0;
8988
9158
  session[kClient] = client;
8989
9159
  session[kSocket] = socket;
8990
- session[kHTTP2Session] = null;
9160
+ session[kHTTP2SessionState] = {
9161
+ ping: {
9162
+ interval: client[kPingInterval] === 0 ? null : setInterval(onHttp2SendPing, client[kPingInterval], session).unref()
9163
+ }
9164
+ };
8991
9165
  session[kEnableConnectProtocol] = false;
8992
9166
  session[kRemoteSettings] = false;
9167
+ if (http2ConnectionWindowSize) {
9168
+ util.addListener(session, "connect", applyConnectionWindowSize.bind(session, http2ConnectionWindowSize));
9169
+ }
8993
9170
  util.addListener(session, "error", onHttp2SessionError);
8994
9171
  util.addListener(session, "frameError", onHttp2FrameError);
8995
9172
  util.addListener(session, "end", onHttp2SessionEnd);
@@ -9067,6 +9244,14 @@ var require_client_h2 = __commonJS({
9067
9244
  }
9068
9245
  }
9069
9246
  }
9247
+ function applyConnectionWindowSize(connectionWindowSize) {
9248
+ try {
9249
+ if (typeof this.setLocalWindowSize === "function") {
9250
+ this.setLocalWindowSize(connectionWindowSize);
9251
+ }
9252
+ } catch {
9253
+ }
9254
+ }
9070
9255
  function onHttp2RemoteSettings(settings) {
9071
9256
  this[kClient][kMaxConcurrentStreams] = settings.maxConcurrentStreams ?? this[kClient][kMaxConcurrentStreams];
9072
9257
  if (this[kRemoteSettings] === true && this[kEnableConnectProtocol] === true && settings.enableConnectProtocol === false) {
@@ -9079,6 +9264,26 @@ var require_client_h2 = __commonJS({
9079
9264
  this[kRemoteSettings] = true;
9080
9265
  this[kClient][kResume]();
9081
9266
  }
9267
+ function onHttp2SendPing(session) {
9268
+ const state = session[kHTTP2SessionState];
9269
+ if ((session.closed || session.destroyed) && state.ping.interval != null) {
9270
+ clearInterval(state.ping.interval);
9271
+ state.ping.interval = null;
9272
+ return;
9273
+ }
9274
+ session.ping(onPing.bind(session));
9275
+ function onPing(err, duration) {
9276
+ const client = this[kClient];
9277
+ const socket = this[kClient];
9278
+ if (err != null) {
9279
+ const error = new InformationalError(`HTTP/2: "PING" errored - type ${err.message}`);
9280
+ socket[kError] = error;
9281
+ client[kOnError](error);
9282
+ } else {
9283
+ client.emit("ping", duration);
9284
+ }
9285
+ }
9286
+ }
9082
9287
  function onHttp2SessionError(err) {
9083
9288
  assert5(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
9084
9289
  this[kSocket][kError] = err;
@@ -9116,11 +9321,15 @@ var require_client_h2 = __commonJS({
9116
9321
  client[kResume]();
9117
9322
  }
9118
9323
  function onHttp2SessionClose() {
9119
- const { [kClient]: client } = this;
9324
+ const { [kClient]: client, [kHTTP2SessionState]: state } = this;
9120
9325
  const { [kSocket]: socket } = client;
9121
9326
  const err = this[kSocket][kError] || this[kError] || new SocketError("closed", util.getSocketInfo(socket));
9122
9327
  client[kSocket] = null;
9123
9328
  client[kHTTPContext] = null;
9329
+ if (state.ping.interval != null) {
9330
+ clearInterval(state.ping.interval);
9331
+ state.ping.interval = null;
9332
+ }
9124
9333
  if (client.destroyed) {
9125
9334
  assert5(client[kPending] === 0);
9126
9335
  const requests = client[kQueue].splice(client[kRunningIdx]);
@@ -9325,9 +9534,11 @@ var require_client_h2 = __commonJS({
9325
9534
  }
9326
9535
  ++session[kOpenStreams];
9327
9536
  stream.setTimeout(requestTimeout);
9537
+ let responseReceived = false;
9328
9538
  stream.once("response", (headers2) => {
9329
9539
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
9330
9540
  request.onResponseStarted();
9541
+ responseReceived = true;
9331
9542
  if (request.aborted) {
9332
9543
  stream.removeAllListeners("data");
9333
9544
  return;
@@ -9335,26 +9546,25 @@ var require_client_h2 = __commonJS({
9335
9546
  if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), "") === false) {
9336
9547
  stream.pause();
9337
9548
  }
9549
+ stream.on("data", (chunk) => {
9550
+ if (request.aborted || request.completed) {
9551
+ return;
9552
+ }
9553
+ if (request.onData(chunk) === false) {
9554
+ stream.pause();
9555
+ }
9556
+ });
9338
9557
  });
9339
- stream.on("data", (chunk) => {
9340
- if (request.onData(chunk) === false) {
9341
- stream.pause();
9342
- }
9343
- });
9344
- stream.once("end", (err) => {
9558
+ stream.once("end", () => {
9345
9559
  stream.removeAllListeners("data");
9346
- if (stream.state?.state == null || stream.state.state < 6) {
9560
+ if (responseReceived) {
9347
9561
  if (!request.aborted && !request.completed) {
9348
9562
  request.onComplete({});
9349
9563
  }
9350
9564
  client[kQueue][client[kRunningIdx]++] = null;
9351
9565
  client[kResume]();
9352
9566
  } else {
9353
- --session[kOpenStreams];
9354
- if (session[kOpenStreams] === 0) {
9355
- session.unref();
9356
- }
9357
- abort(err ?? new InformationalError("HTTP/2: stream half-closed (remote)"));
9567
+ abort(new InformationalError("HTTP/2: stream half-closed (remote)"));
9358
9568
  client[kQueue][client[kRunningIdx]++] = null;
9359
9569
  client[kPendingIdx] = client[kRunningIdx];
9360
9570
  client[kResume]();
@@ -9391,6 +9601,7 @@ var require_client_h2 = __commonJS({
9391
9601
  if (request.aborted || request.completed) {
9392
9602
  return;
9393
9603
  }
9604
+ stream.removeAllListeners("data");
9394
9605
  request.onComplete(trailers);
9395
9606
  });
9396
9607
  return true;
@@ -9634,7 +9845,10 @@ var require_client = __commonJS({
9634
9845
  kOnError,
9635
9846
  kHTTPContext,
9636
9847
  kMaxConcurrentStreams,
9637
- kResume
9848
+ kHTTP2InitialWindowSize,
9849
+ kHTTP2ConnectionWindowSize,
9850
+ kResume,
9851
+ kPingInterval
9638
9852
  } = require_symbols();
9639
9853
  var connectH1 = require_client_h1();
9640
9854
  var connectH2 = require_client_h2();
@@ -9680,7 +9894,10 @@ var require_client = __commonJS({
9680
9894
  // h2
9681
9895
  maxConcurrentStreams,
9682
9896
  allowH2,
9683
- useH2c
9897
+ useH2c,
9898
+ initialWindowSize,
9899
+ connectionWindowSize,
9900
+ pingInterval
9684
9901
  } = {}) {
9685
9902
  if (keepAlive !== void 0) {
9686
9903
  throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead");
@@ -9749,6 +9966,15 @@ var require_client = __commonJS({
9749
9966
  if (useH2c != null && typeof useH2c !== "boolean") {
9750
9967
  throw new InvalidArgumentError("useH2c must be a valid boolean value");
9751
9968
  }
9969
+ if (initialWindowSize != null && (!Number.isInteger(initialWindowSize) || initialWindowSize < 1)) {
9970
+ throw new InvalidArgumentError("initialWindowSize must be a positive integer, greater than 0");
9971
+ }
9972
+ if (connectionWindowSize != null && (!Number.isInteger(connectionWindowSize) || connectionWindowSize < 1)) {
9973
+ throw new InvalidArgumentError("connectionWindowSize must be a positive integer, greater than 0");
9974
+ }
9975
+ if (pingInterval != null && (typeof pingInterval !== "number" || !Number.isInteger(pingInterval) || pingInterval < 0)) {
9976
+ throw new InvalidArgumentError("pingInterval must be a positive integer, greater or equal to 0");
9977
+ }
9752
9978
  super();
9753
9979
  if (typeof connect2 !== "function") {
9754
9980
  connect2 = buildConnector({
@@ -9761,6 +9987,9 @@ var require_client = __commonJS({
9761
9987
  ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
9762
9988
  ...connect2
9763
9989
  });
9990
+ } else if (socketPath != null) {
9991
+ const customConnect = connect2;
9992
+ connect2 = (opts, callback) => customConnect({ ...opts, socketPath }, callback);
9764
9993
  }
9765
9994
  this[kUrl] = util.parseOrigin(url);
9766
9995
  this[kConnector] = connect2;
@@ -9782,8 +10011,11 @@ var require_client = __commonJS({
9782
10011
  this[kMaxRequests] = maxRequestsPerClient;
9783
10012
  this[kClosedResolve] = null;
9784
10013
  this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1;
9785
- this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100;
9786
10014
  this[kHTTPContext] = null;
10015
+ this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100;
10016
+ this[kHTTP2InitialWindowSize] = initialWindowSize != null ? initialWindowSize : 262144;
10017
+ this[kHTTP2ConnectionWindowSize] = connectionWindowSize != null ? connectionWindowSize : 524288;
10018
+ this[kPingInterval] = pingInterval != null ? pingInterval : 6e4;
9787
10019
  this[kQueue] = [];
9788
10020
  this[kRunningIdx] = 0;
9789
10021
  this[kPendingIdx] = 0;
@@ -9906,56 +10138,61 @@ var require_client = __commonJS({
9906
10138
  connector: client[kConnector]
9907
10139
  });
9908
10140
  }
9909
- client[kConnector]({
9910
- host,
9911
- hostname,
9912
- protocol,
9913
- port,
9914
- servername: client[kServerName],
9915
- localAddress: client[kLocalAddress]
9916
- }, (err, socket) => {
9917
- if (err) {
9918
- handleConnectError(client, err, { host, hostname, protocol, port });
9919
- client[kResume]();
9920
- return;
9921
- }
9922
- if (client.destroyed) {
9923
- util.destroy(socket.on("error", noop), new ClientDestroyedError());
9924
- client[kResume]();
9925
- return;
9926
- }
9927
- assert5(socket);
9928
- try {
9929
- client[kHTTPContext] = socket.alpnProtocol === "h2" ? connectH2(client, socket) : connectH1(client, socket);
9930
- } catch (err2) {
9931
- socket.destroy().on("error", noop);
9932
- handleConnectError(client, err2, { host, hostname, protocol, port });
10141
+ try {
10142
+ client[kConnector]({
10143
+ host,
10144
+ hostname,
10145
+ protocol,
10146
+ port,
10147
+ servername: client[kServerName],
10148
+ localAddress: client[kLocalAddress]
10149
+ }, (err, socket) => {
10150
+ if (err) {
10151
+ handleConnectError(client, err, { host, hostname, protocol, port });
10152
+ client[kResume]();
10153
+ return;
10154
+ }
10155
+ if (client.destroyed) {
10156
+ util.destroy(socket.on("error", noop), new ClientDestroyedError());
10157
+ client[kResume]();
10158
+ return;
10159
+ }
10160
+ assert5(socket);
10161
+ try {
10162
+ client[kHTTPContext] = socket.alpnProtocol === "h2" ? connectH2(client, socket) : connectH1(client, socket);
10163
+ } catch (err2) {
10164
+ socket.destroy().on("error", noop);
10165
+ handleConnectError(client, err2, { host, hostname, protocol, port });
10166
+ client[kResume]();
10167
+ return;
10168
+ }
10169
+ client[kConnecting] = false;
10170
+ socket[kCounter] = 0;
10171
+ socket[kMaxRequests] = client[kMaxRequests];
10172
+ socket[kClient] = client;
10173
+ socket[kError] = null;
10174
+ if (channels.connected.hasSubscribers) {
10175
+ channels.connected.publish({
10176
+ connectParams: {
10177
+ host,
10178
+ hostname,
10179
+ protocol,
10180
+ port,
10181
+ version: client[kHTTPContext]?.version,
10182
+ servername: client[kServerName],
10183
+ localAddress: client[kLocalAddress]
10184
+ },
10185
+ connector: client[kConnector],
10186
+ socket
10187
+ });
10188
+ }
10189
+ client.emit("connect", client[kUrl], [client]);
9933
10190
  client[kResume]();
9934
- return;
9935
- }
9936
- client[kConnecting] = false;
9937
- socket[kCounter] = 0;
9938
- socket[kMaxRequests] = client[kMaxRequests];
9939
- socket[kClient] = client;
9940
- socket[kError] = null;
9941
- if (channels.connected.hasSubscribers) {
9942
- channels.connected.publish({
9943
- connectParams: {
9944
- host,
9945
- hostname,
9946
- protocol,
9947
- port,
9948
- version: client[kHTTPContext]?.version,
9949
- servername: client[kServerName],
9950
- localAddress: client[kLocalAddress]
9951
- },
9952
- connector: client[kConnector],
9953
- socket
9954
- });
9955
- }
9956
- client.emit("connect", client[kUrl], [client]);
10191
+ });
10192
+ } catch (err) {
10193
+ handleConnectError(client, err, { host, hostname, protocol, port });
9957
10194
  client[kResume]();
9958
- });
10195
+ }
9959
10196
  }
9960
10197
  function handleConnectError(client, err, { host, hostname, protocol, port }) {
9961
10198
  if (client.destroyed) {
@@ -10037,6 +10274,9 @@ var require_client = __commonJS({
10037
10274
  return;
10038
10275
  }
10039
10276
  const request = client[kQueue][client[kPendingIdx]];
10277
+ if (request === null) {
10278
+ return;
10279
+ }
10040
10280
  if (client[kUrl].protocol === "https:" && client[kServerName] !== request.servername) {
10041
10281
  if (client[kRunning] > 0) {
10042
10282
  return;
@@ -10183,9 +10423,12 @@ var require_pool_base = __commonJS({
10183
10423
  this.emit("drain", origin, [this, ...targets]);
10184
10424
  }
10185
10425
  if (this[kClosedResolve] && queue.isEmpty()) {
10186
- const closeAll = new Array(this[kClients].length);
10426
+ const closeAll = [];
10187
10427
  for (let i = 0; i < this[kClients].length; i++) {
10188
- closeAll[i] = this[kClients][i].close();
10428
+ const client2 = this[kClients][i];
10429
+ if (!client2.destroyed) {
10430
+ closeAll.push(client2.close());
10431
+ }
10189
10432
  }
10190
10433
  return Promise.all(closeAll).then(this[kClosedResolve]);
10191
10434
  }
@@ -10242,9 +10485,12 @@ var require_pool_base = __commonJS({
10242
10485
  }
10243
10486
  [kClose]() {
10244
10487
  if (this[kQueue].isEmpty()) {
10245
- const closeAll = new Array(this[kClients].length);
10488
+ const closeAll = [];
10246
10489
  for (let i = 0; i < this[kClients].length; i++) {
10247
- closeAll[i] = this[kClients][i].close();
10490
+ const client = this[kClients][i];
10491
+ if (!client.destroyed) {
10492
+ closeAll.push(client.close());
10493
+ }
10248
10494
  }
10249
10495
  return Promise.all(closeAll);
10250
10496
  } else {
@@ -10375,7 +10621,7 @@ var require_pool = __commonJS({
10375
10621
  super();
10376
10622
  this[kConnections] = connections || null;
10377
10623
  this[kUrl] = util.parseOrigin(origin);
10378
- this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl };
10624
+ this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl, socketPath };
10379
10625
  this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : void 0;
10380
10626
  this[kFactory] = factory;
10381
10627
  this.on("connect", (origin2, targets) => {
@@ -10432,7 +10678,7 @@ var require_balanced_pool = __commonJS({
10432
10678
  } = require_pool_base();
10433
10679
  var Pool = require_pool();
10434
10680
  var { kUrl } = require_symbols();
10435
- var { parseOrigin } = require_util();
10681
+ var util = require_util();
10436
10682
  var kFactory = /* @__PURE__ */ Symbol("factory");
10437
10683
  var kOptions = /* @__PURE__ */ Symbol("options");
10438
10684
  var kGreatestCommonDivisor = /* @__PURE__ */ Symbol("kGreatestCommonDivisor");
@@ -10459,7 +10705,8 @@ var require_balanced_pool = __commonJS({
10459
10705
  throw new InvalidArgumentError("factory must be a function.");
10460
10706
  }
10461
10707
  super();
10462
- this[kOptions] = opts;
10708
+ this[kOptions] = { ...util.deepClone(opts) };
10709
+ this[kOptions].interceptors = opts.interceptors ? { ...opts.interceptors } : void 0;
10463
10710
  this[kIndex] = -1;
10464
10711
  this[kCurrentWeight] = 0;
10465
10712
  this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100;
@@ -10474,11 +10721,11 @@ var require_balanced_pool = __commonJS({
10474
10721
  this._updateBalancedPoolStats();
10475
10722
  }
10476
10723
  addUpstream(upstream) {
10477
- const upstreamOrigin = parseOrigin(upstream).origin;
10724
+ const upstreamOrigin = util.parseOrigin(upstream).origin;
10478
10725
  if (this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true)) {
10479
10726
  return this;
10480
10727
  }
10481
- const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]));
10728
+ const pool = this[kFactory](upstreamOrigin, this[kOptions]);
10482
10729
  this[kAddClient](pool);
10483
10730
  pool.on("connect", () => {
10484
10731
  pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]);
@@ -10508,7 +10755,7 @@ var require_balanced_pool = __commonJS({
10508
10755
  this[kGreatestCommonDivisor] = result;
10509
10756
  }
10510
10757
  removeUpstream(upstream) {
10511
- const upstreamOrigin = parseOrigin(upstream).origin;
10758
+ const upstreamOrigin = util.parseOrigin(upstream).origin;
10512
10759
  const pool = this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true);
10513
10760
  if (pool) {
10514
10761
  this[kRemoveClient](pool);
@@ -10516,7 +10763,7 @@ var require_balanced_pool = __commonJS({
10516
10763
  return this;
10517
10764
  }
10518
10765
  getUpstream(upstream) {
10519
- const upstreamOrigin = parseOrigin(upstream).origin;
10766
+ const upstreamOrigin = util.parseOrigin(upstream).origin;
10520
10767
  return this[kClients].find((pool) => pool[kUrl].origin === upstreamOrigin && pool.closed !== true && pool.destroyed !== true);
10521
10768
  }
10522
10769
  get upstreams() {
@@ -10625,7 +10872,7 @@ var require_round_robin_pool = __commonJS({
10625
10872
  super();
10626
10873
  this[kConnections] = connections || null;
10627
10874
  this[kUrl] = util.parseOrigin(origin);
10628
- this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl };
10875
+ this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl, socketPath };
10629
10876
  this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : void 0;
10630
10877
  this[kFactory] = factory;
10631
10878
  this[kIndex] = -1;
@@ -10756,7 +11003,9 @@ var require_agent = __commonJS({
10756
11003
  if (connected) result2.count -= 1;
10757
11004
  if (result2.count <= 0) {
10758
11005
  this[kClients].delete(key);
10759
- result2.dispatcher.close();
11006
+ if (!result2.dispatcher.destroyed) {
11007
+ result2.dispatcher.close();
11008
+ }
10760
11009
  }
10761
11010
  this[kOrigins].delete(key);
10762
11011
  }
@@ -10809,6 +11058,667 @@ var require_agent = __commonJS({
10809
11058
  }
10810
11059
  });
10811
11060
 
11061
+ // node_modules/undici/lib/core/socks5-utils.js
11062
+ var require_socks5_utils = __commonJS({
11063
+ "node_modules/undici/lib/core/socks5-utils.js"(exports2, module2) {
11064
+ "use strict";
11065
+ var { Buffer: Buffer2 } = require("buffer");
11066
+ var net = require("net");
11067
+ var { InvalidArgumentError } = require_errors();
11068
+ function parseAddress(address) {
11069
+ if (net.isIPv4(address)) {
11070
+ const parts = address.split(".").map(Number);
11071
+ return {
11072
+ type: 1,
11073
+ // IPv4
11074
+ buffer: Buffer2.from(parts)
11075
+ };
11076
+ }
11077
+ if (net.isIPv6(address)) {
11078
+ return {
11079
+ type: 4,
11080
+ // IPv6
11081
+ buffer: parseIPv6(address)
11082
+ };
11083
+ }
11084
+ const domainBuffer = Buffer2.from(address, "utf8");
11085
+ if (domainBuffer.length > 255) {
11086
+ throw new InvalidArgumentError("Domain name too long (max 255 bytes)");
11087
+ }
11088
+ return {
11089
+ type: 3,
11090
+ // Domain
11091
+ buffer: Buffer2.concat([Buffer2.from([domainBuffer.length]), domainBuffer])
11092
+ };
11093
+ }
11094
+ function parseIPv6(address) {
11095
+ const buffer = Buffer2.alloc(16);
11096
+ const parts = address.split(":");
11097
+ let partIndex = 0;
11098
+ let bufferIndex = 0;
11099
+ const doubleColonIndex = address.indexOf("::");
11100
+ if (doubleColonIndex !== -1) {
11101
+ const nonEmptyParts = parts.filter((p) => p.length > 0).length;
11102
+ const skipParts = 8 - nonEmptyParts;
11103
+ for (let i = 0; i < parts.length; i++) {
11104
+ if (parts[i] === "" && i === doubleColonIndex / 3) {
11105
+ bufferIndex += skipParts * 2;
11106
+ } else if (parts[i] !== "") {
11107
+ const value = parseInt(parts[i], 16);
11108
+ buffer.writeUInt16BE(value, bufferIndex);
11109
+ bufferIndex += 2;
11110
+ }
11111
+ }
11112
+ } else {
11113
+ for (const part of parts) {
11114
+ if (part === "") continue;
11115
+ const value = parseInt(part, 16);
11116
+ buffer.writeUInt16BE(value, partIndex * 2);
11117
+ partIndex++;
11118
+ }
11119
+ }
11120
+ return buffer;
11121
+ }
11122
+ function buildAddressBuffer(type, addressBuffer, port) {
11123
+ const portBuffer = Buffer2.allocUnsafe(2);
11124
+ portBuffer.writeUInt16BE(port, 0);
11125
+ return Buffer2.concat([
11126
+ Buffer2.from([type]),
11127
+ addressBuffer,
11128
+ portBuffer
11129
+ ]);
11130
+ }
11131
+ function parseResponseAddress(buffer, offset = 0) {
11132
+ if (buffer.length < offset + 1) {
11133
+ throw new InvalidArgumentError("Buffer too small to contain address type");
11134
+ }
11135
+ const addressType = buffer[offset];
11136
+ let address;
11137
+ let currentOffset = offset + 1;
11138
+ switch (addressType) {
11139
+ case 1: {
11140
+ if (buffer.length < currentOffset + 6) {
11141
+ throw new InvalidArgumentError("Buffer too small for IPv4 address");
11142
+ }
11143
+ address = Array.from(buffer.subarray(currentOffset, currentOffset + 4)).join(".");
11144
+ currentOffset += 4;
11145
+ break;
11146
+ }
11147
+ case 3: {
11148
+ if (buffer.length < currentOffset + 1) {
11149
+ throw new InvalidArgumentError("Buffer too small for domain length");
11150
+ }
11151
+ const domainLength = buffer[currentOffset];
11152
+ currentOffset += 1;
11153
+ if (buffer.length < currentOffset + domainLength + 2) {
11154
+ throw new InvalidArgumentError("Buffer too small for domain address");
11155
+ }
11156
+ address = buffer.subarray(currentOffset, currentOffset + domainLength).toString("utf8");
11157
+ currentOffset += domainLength;
11158
+ break;
11159
+ }
11160
+ case 4: {
11161
+ if (buffer.length < currentOffset + 18) {
11162
+ throw new InvalidArgumentError("Buffer too small for IPv6 address");
11163
+ }
11164
+ const parts = [];
11165
+ for (let i = 0; i < 8; i++) {
11166
+ const value = buffer.readUInt16BE(currentOffset + i * 2);
11167
+ parts.push(value.toString(16));
11168
+ }
11169
+ address = parts.join(":");
11170
+ currentOffset += 16;
11171
+ break;
11172
+ }
11173
+ default:
11174
+ throw new InvalidArgumentError(`Invalid address type: ${addressType}`);
11175
+ }
11176
+ if (buffer.length < currentOffset + 2) {
11177
+ throw new InvalidArgumentError("Buffer too small for port");
11178
+ }
11179
+ const port = buffer.readUInt16BE(currentOffset);
11180
+ currentOffset += 2;
11181
+ return {
11182
+ address,
11183
+ port,
11184
+ bytesRead: currentOffset - offset
11185
+ };
11186
+ }
11187
+ function createReplyError(replyCode) {
11188
+ const messages = {
11189
+ 1: "General SOCKS server failure",
11190
+ 2: "Connection not allowed by ruleset",
11191
+ 3: "Network unreachable",
11192
+ 4: "Host unreachable",
11193
+ 5: "Connection refused",
11194
+ 6: "TTL expired",
11195
+ 7: "Command not supported",
11196
+ 8: "Address type not supported"
11197
+ };
11198
+ const message = messages[replyCode] || `Unknown SOCKS5 error code: ${replyCode}`;
11199
+ const error = new Error(message);
11200
+ error.code = `SOCKS5_${replyCode}`;
11201
+ return error;
11202
+ }
11203
+ module2.exports = {
11204
+ parseAddress,
11205
+ parseIPv6,
11206
+ buildAddressBuffer,
11207
+ parseResponseAddress,
11208
+ createReplyError
11209
+ };
11210
+ }
11211
+ });
11212
+
11213
+ // node_modules/undici/lib/core/socks5-client.js
11214
+ var require_socks5_client = __commonJS({
11215
+ "node_modules/undici/lib/core/socks5-client.js"(exports2, module2) {
11216
+ "use strict";
11217
+ var { EventEmitter: EventEmitter2 } = require("events");
11218
+ var { Buffer: Buffer2 } = require("buffer");
11219
+ var { InvalidArgumentError, Socks5ProxyError } = require_errors();
11220
+ var { debuglog } = require("util");
11221
+ var { parseAddress } = require_socks5_utils();
11222
+ var debug9 = debuglog("undici:socks5");
11223
+ var SOCKS_VERSION = 5;
11224
+ var AUTH_METHODS = {
11225
+ NO_AUTH: 0,
11226
+ GSSAPI: 1,
11227
+ USERNAME_PASSWORD: 2,
11228
+ NO_ACCEPTABLE: 255
11229
+ };
11230
+ var COMMANDS = {
11231
+ CONNECT: 1,
11232
+ BIND: 2,
11233
+ UDP_ASSOCIATE: 3
11234
+ };
11235
+ var ADDRESS_TYPES = {
11236
+ IPV4: 1,
11237
+ DOMAIN: 3,
11238
+ IPV6: 4
11239
+ };
11240
+ var REPLY_CODES = {
11241
+ SUCCEEDED: 0,
11242
+ GENERAL_FAILURE: 1,
11243
+ CONNECTION_NOT_ALLOWED: 2,
11244
+ NETWORK_UNREACHABLE: 3,
11245
+ HOST_UNREACHABLE: 4,
11246
+ CONNECTION_REFUSED: 5,
11247
+ TTL_EXPIRED: 6,
11248
+ COMMAND_NOT_SUPPORTED: 7,
11249
+ ADDRESS_TYPE_NOT_SUPPORTED: 8
11250
+ };
11251
+ var STATES = {
11252
+ INITIAL: "initial",
11253
+ HANDSHAKING: "handshaking",
11254
+ AUTHENTICATING: "authenticating",
11255
+ CONNECTING: "connecting",
11256
+ CONNECTED: "connected",
11257
+ ERROR: "error",
11258
+ CLOSED: "closed"
11259
+ };
11260
+ var Socks5Client = class extends EventEmitter2 {
11261
+ constructor(socket, options = {}) {
11262
+ super();
11263
+ if (!socket) {
11264
+ throw new InvalidArgumentError("socket is required");
11265
+ }
11266
+ this.socket = socket;
11267
+ this.options = options;
11268
+ this.state = STATES.INITIAL;
11269
+ this.buffer = Buffer2.alloc(0);
11270
+ this.authMethods = [];
11271
+ if (options.username && options.password) {
11272
+ this.authMethods.push(AUTH_METHODS.USERNAME_PASSWORD);
11273
+ }
11274
+ this.authMethods.push(AUTH_METHODS.NO_AUTH);
11275
+ this.socket.on("data", this.onData.bind(this));
11276
+ this.socket.on("error", this.onError.bind(this));
11277
+ this.socket.on("close", this.onClose.bind(this));
11278
+ }
11279
+ /**
11280
+ * Handle incoming data from the socket
11281
+ */
11282
+ onData(data) {
11283
+ debug9("received data", data.length, "bytes in state", this.state);
11284
+ this.buffer = Buffer2.concat([this.buffer, data]);
11285
+ try {
11286
+ switch (this.state) {
11287
+ case STATES.HANDSHAKING:
11288
+ this.handleHandshakeResponse();
11289
+ break;
11290
+ case STATES.AUTHENTICATING:
11291
+ this.handleAuthResponse();
11292
+ break;
11293
+ case STATES.CONNECTING:
11294
+ this.handleConnectResponse();
11295
+ break;
11296
+ }
11297
+ } catch (err) {
11298
+ this.onError(err);
11299
+ }
11300
+ }
11301
+ /**
11302
+ * Handle socket errors
11303
+ */
11304
+ onError(err) {
11305
+ debug9("socket error", err);
11306
+ this.state = STATES.ERROR;
11307
+ this.emit("error", err);
11308
+ this.destroy();
11309
+ }
11310
+ /**
11311
+ * Handle socket close
11312
+ */
11313
+ onClose() {
11314
+ debug9("socket closed");
11315
+ this.state = STATES.CLOSED;
11316
+ this.emit("close");
11317
+ }
11318
+ /**
11319
+ * Destroy the client and underlying socket
11320
+ */
11321
+ destroy() {
11322
+ if (this.socket && !this.socket.destroyed) {
11323
+ this.socket.destroy();
11324
+ }
11325
+ }
11326
+ /**
11327
+ * Start the SOCKS5 handshake
11328
+ */
11329
+ handshake() {
11330
+ if (this.state !== STATES.INITIAL) {
11331
+ throw new InvalidArgumentError("Handshake already started");
11332
+ }
11333
+ debug9("starting handshake with", this.authMethods.length, "auth methods");
11334
+ this.state = STATES.HANDSHAKING;
11335
+ const request = Buffer2.alloc(2 + this.authMethods.length);
11336
+ request[0] = SOCKS_VERSION;
11337
+ request[1] = this.authMethods.length;
11338
+ this.authMethods.forEach((method, i) => {
11339
+ request[2 + i] = method;
11340
+ });
11341
+ this.socket.write(request);
11342
+ }
11343
+ /**
11344
+ * Handle handshake response from server
11345
+ */
11346
+ handleHandshakeResponse() {
11347
+ if (this.buffer.length < 2) {
11348
+ return;
11349
+ }
11350
+ const version = this.buffer[0];
11351
+ const method = this.buffer[1];
11352
+ if (version !== SOCKS_VERSION) {
11353
+ throw new Socks5ProxyError(`Invalid SOCKS version: ${version}`, "UND_ERR_SOCKS5_VERSION");
11354
+ }
11355
+ if (method === AUTH_METHODS.NO_ACCEPTABLE) {
11356
+ throw new Socks5ProxyError("No acceptable authentication method", "UND_ERR_SOCKS5_AUTH_REJECTED");
11357
+ }
11358
+ this.buffer = this.buffer.subarray(2);
11359
+ debug9("server selected auth method", method);
11360
+ if (method === AUTH_METHODS.NO_AUTH) {
11361
+ this.emit("authenticated");
11362
+ } else if (method === AUTH_METHODS.USERNAME_PASSWORD) {
11363
+ this.state = STATES.AUTHENTICATING;
11364
+ this.sendAuthRequest();
11365
+ } else {
11366
+ throw new Socks5ProxyError(`Unsupported authentication method: ${method}`, "UND_ERR_SOCKS5_AUTH_METHOD");
11367
+ }
11368
+ }
11369
+ /**
11370
+ * Send username/password authentication request
11371
+ */
11372
+ sendAuthRequest() {
11373
+ const { username, password } = this.options;
11374
+ if (!username || !password) {
11375
+ throw new InvalidArgumentError("Username and password required for authentication");
11376
+ }
11377
+ debug9("sending username/password auth");
11378
+ const usernameBuffer = Buffer2.from(username);
11379
+ const passwordBuffer = Buffer2.from(password);
11380
+ if (usernameBuffer.length > 255 || passwordBuffer.length > 255) {
11381
+ throw new InvalidArgumentError("Username or password too long");
11382
+ }
11383
+ const request = Buffer2.alloc(3 + usernameBuffer.length + passwordBuffer.length);
11384
+ request[0] = 1;
11385
+ request[1] = usernameBuffer.length;
11386
+ usernameBuffer.copy(request, 2);
11387
+ request[2 + usernameBuffer.length] = passwordBuffer.length;
11388
+ passwordBuffer.copy(request, 3 + usernameBuffer.length);
11389
+ this.socket.write(request);
11390
+ }
11391
+ /**
11392
+ * Handle authentication response
11393
+ */
11394
+ handleAuthResponse() {
11395
+ if (this.buffer.length < 2) {
11396
+ return;
11397
+ }
11398
+ const version = this.buffer[0];
11399
+ const status = this.buffer[1];
11400
+ if (version !== 1) {
11401
+ throw new Socks5ProxyError(`Invalid auth sub-negotiation version: ${version}`, "UND_ERR_SOCKS5_AUTH_VERSION");
11402
+ }
11403
+ if (status !== 0) {
11404
+ throw new Socks5ProxyError("Authentication failed", "UND_ERR_SOCKS5_AUTH_FAILED");
11405
+ }
11406
+ this.buffer = this.buffer.subarray(2);
11407
+ debug9("authentication successful");
11408
+ this.emit("authenticated");
11409
+ }
11410
+ /**
11411
+ * Send CONNECT command
11412
+ * @param {string} address - Target address (IP or domain)
11413
+ * @param {number} port - Target port
11414
+ */
11415
+ connect(address, port) {
11416
+ if (this.state === STATES.CONNECTED) {
11417
+ throw new InvalidArgumentError("Already connected");
11418
+ }
11419
+ debug9("connecting to", address, port);
11420
+ this.state = STATES.CONNECTING;
11421
+ const request = this.buildConnectRequest(COMMANDS.CONNECT, address, port);
11422
+ this.socket.write(request);
11423
+ }
11424
+ /**
11425
+ * Build a SOCKS5 request
11426
+ */
11427
+ buildConnectRequest(command, address, port) {
11428
+ const { type: addressType, buffer: addressBuffer } = parseAddress(address);
11429
+ const request = Buffer2.alloc(4 + addressBuffer.length + 2);
11430
+ request[0] = SOCKS_VERSION;
11431
+ request[1] = command;
11432
+ request[2] = 0;
11433
+ request[3] = addressType;
11434
+ addressBuffer.copy(request, 4);
11435
+ request.writeUInt16BE(port, 4 + addressBuffer.length);
11436
+ return request;
11437
+ }
11438
+ /**
11439
+ * Handle CONNECT response
11440
+ */
11441
+ handleConnectResponse() {
11442
+ if (this.buffer.length < 4) {
11443
+ return;
11444
+ }
11445
+ const version = this.buffer[0];
11446
+ const reply = this.buffer[1];
11447
+ const addressType = this.buffer[3];
11448
+ if (version !== SOCKS_VERSION) {
11449
+ throw new Socks5ProxyError(`Invalid SOCKS version in reply: ${version}`, "UND_ERR_SOCKS5_REPLY_VERSION");
11450
+ }
11451
+ let responseLength = 4;
11452
+ if (addressType === ADDRESS_TYPES.IPV4) {
11453
+ responseLength += 4 + 2;
11454
+ } else if (addressType === ADDRESS_TYPES.DOMAIN) {
11455
+ if (this.buffer.length < 5) {
11456
+ return;
11457
+ }
11458
+ responseLength += 1 + this.buffer[4] + 2;
11459
+ } else if (addressType === ADDRESS_TYPES.IPV6) {
11460
+ responseLength += 16 + 2;
11461
+ } else {
11462
+ throw new Socks5ProxyError(`Invalid address type in reply: ${addressType}`, "UND_ERR_SOCKS5_ADDR_TYPE");
11463
+ }
11464
+ if (this.buffer.length < responseLength) {
11465
+ return;
11466
+ }
11467
+ if (reply !== REPLY_CODES.SUCCEEDED) {
11468
+ const errorMessage = this.getReplyErrorMessage(reply);
11469
+ throw new Socks5ProxyError(`SOCKS5 connection failed: ${errorMessage}`, `UND_ERR_SOCKS5_REPLY_${reply}`);
11470
+ }
11471
+ let boundAddress;
11472
+ let offset = 4;
11473
+ if (addressType === ADDRESS_TYPES.IPV4) {
11474
+ boundAddress = Array.from(this.buffer.subarray(offset, offset + 4)).join(".");
11475
+ offset += 4;
11476
+ } else if (addressType === ADDRESS_TYPES.DOMAIN) {
11477
+ const domainLength = this.buffer[offset];
11478
+ offset += 1;
11479
+ boundAddress = this.buffer.subarray(offset, offset + domainLength).toString();
11480
+ offset += domainLength;
11481
+ } else if (addressType === ADDRESS_TYPES.IPV6) {
11482
+ const parts = [];
11483
+ for (let i = 0; i < 8; i++) {
11484
+ const value = this.buffer.readUInt16BE(offset + i * 2);
11485
+ parts.push(value.toString(16));
11486
+ }
11487
+ boundAddress = parts.join(":");
11488
+ offset += 16;
11489
+ }
11490
+ const boundPort = this.buffer.readUInt16BE(offset);
11491
+ this.buffer = this.buffer.subarray(responseLength);
11492
+ this.state = STATES.CONNECTED;
11493
+ debug9("connected, bound address:", boundAddress, "port:", boundPort);
11494
+ this.emit("connected", { address: boundAddress, port: boundPort });
11495
+ }
11496
+ /**
11497
+ * Get human-readable error message for reply code
11498
+ */
11499
+ getReplyErrorMessage(reply) {
11500
+ switch (reply) {
11501
+ case REPLY_CODES.GENERAL_FAILURE:
11502
+ return "General SOCKS server failure";
11503
+ case REPLY_CODES.CONNECTION_NOT_ALLOWED:
11504
+ return "Connection not allowed by ruleset";
11505
+ case REPLY_CODES.NETWORK_UNREACHABLE:
11506
+ return "Network unreachable";
11507
+ case REPLY_CODES.HOST_UNREACHABLE:
11508
+ return "Host unreachable";
11509
+ case REPLY_CODES.CONNECTION_REFUSED:
11510
+ return "Connection refused";
11511
+ case REPLY_CODES.TTL_EXPIRED:
11512
+ return "TTL expired";
11513
+ case REPLY_CODES.COMMAND_NOT_SUPPORTED:
11514
+ return "Command not supported";
11515
+ case REPLY_CODES.ADDRESS_TYPE_NOT_SUPPORTED:
11516
+ return "Address type not supported";
11517
+ default:
11518
+ return `Unknown error code: ${reply}`;
11519
+ }
11520
+ }
11521
+ };
11522
+ module2.exports = {
11523
+ Socks5Client,
11524
+ AUTH_METHODS,
11525
+ COMMANDS,
11526
+ ADDRESS_TYPES,
11527
+ REPLY_CODES,
11528
+ STATES
11529
+ };
11530
+ }
11531
+ });
11532
+
11533
+ // node_modules/undici/lib/dispatcher/socks5-proxy-agent.js
11534
+ var require_socks5_proxy_agent = __commonJS({
11535
+ "node_modules/undici/lib/dispatcher/socks5-proxy-agent.js"(exports2, module2) {
11536
+ "use strict";
11537
+ var net = require("net");
11538
+ var { URL: URL2 } = require("url");
11539
+ var tls;
11540
+ var DispatcherBase = require_dispatcher_base();
11541
+ var { InvalidArgumentError } = require_errors();
11542
+ var { Socks5Client } = require_socks5_client();
11543
+ var { kDispatch, kClose, kDestroy } = require_symbols();
11544
+ var Pool = require_pool();
11545
+ var buildConnector = require_connect();
11546
+ var { debuglog } = require("util");
11547
+ var debug9 = debuglog("undici:socks5-proxy");
11548
+ var kProxyUrl = /* @__PURE__ */ Symbol("proxy url");
11549
+ var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
11550
+ var kProxyAuth = /* @__PURE__ */ Symbol("proxy auth");
11551
+ var kPool = /* @__PURE__ */ Symbol("pool");
11552
+ var kConnector = /* @__PURE__ */ Symbol("connector");
11553
+ var experimentalWarningEmitted = false;
11554
+ var Socks5ProxyAgent = class extends DispatcherBase {
11555
+ constructor(proxyUrl, options = {}) {
11556
+ super();
11557
+ if (!experimentalWarningEmitted) {
11558
+ process.emitWarning(
11559
+ "SOCKS5 proxy support is experimental and subject to change",
11560
+ "ExperimentalWarning"
11561
+ );
11562
+ experimentalWarningEmitted = true;
11563
+ }
11564
+ if (!proxyUrl) {
11565
+ throw new InvalidArgumentError("Proxy URL is mandatory");
11566
+ }
11567
+ const url = typeof proxyUrl === "string" ? new URL2(proxyUrl) : proxyUrl;
11568
+ if (url.protocol !== "socks5:" && url.protocol !== "socks:") {
11569
+ throw new InvalidArgumentError("Proxy URL must use socks5:// or socks:// protocol");
11570
+ }
11571
+ this[kProxyUrl] = url;
11572
+ this[kProxyHeaders] = options.headers || {};
11573
+ this[kProxyAuth] = {
11574
+ username: options.username || (url.username ? decodeURIComponent(url.username) : null),
11575
+ password: options.password || (url.password ? decodeURIComponent(url.password) : null)
11576
+ };
11577
+ this[kConnector] = options.connect || buildConnector({
11578
+ ...options.proxyTls,
11579
+ servername: options.proxyTls?.servername || url.hostname
11580
+ });
11581
+ this[kPool] = null;
11582
+ }
11583
+ /**
11584
+ * Create a SOCKS5 connection to the proxy
11585
+ */
11586
+ async createSocks5Connection(targetHost, targetPort) {
11587
+ const proxyHost = this[kProxyUrl].hostname;
11588
+ const proxyPort = parseInt(this[kProxyUrl].port) || 1080;
11589
+ debug9("creating SOCKS5 connection to", proxyHost, proxyPort);
11590
+ const socket = await new Promise((resolve4, reject) => {
11591
+ const onConnect = () => {
11592
+ socket2.removeListener("error", onError);
11593
+ resolve4(socket2);
11594
+ };
11595
+ const onError = (err) => {
11596
+ socket2.removeListener("connect", onConnect);
11597
+ reject(err);
11598
+ };
11599
+ const socket2 = net.connect({
11600
+ host: proxyHost,
11601
+ port: proxyPort
11602
+ });
11603
+ socket2.once("connect", onConnect);
11604
+ socket2.once("error", onError);
11605
+ });
11606
+ const socks5Client = new Socks5Client(socket, this[kProxyAuth]);
11607
+ socks5Client.on("error", (err) => {
11608
+ debug9("SOCKS5 error:", err);
11609
+ socket.destroy();
11610
+ });
11611
+ await socks5Client.handshake();
11612
+ await new Promise((resolve4, reject) => {
11613
+ const timeout = setTimeout(() => {
11614
+ reject(new Error("SOCKS5 authentication timeout"));
11615
+ }, 5e3);
11616
+ const onAuthenticated = () => {
11617
+ clearTimeout(timeout);
11618
+ socks5Client.removeListener("error", onError);
11619
+ resolve4();
11620
+ };
11621
+ const onError = (err) => {
11622
+ clearTimeout(timeout);
11623
+ socks5Client.removeListener("authenticated", onAuthenticated);
11624
+ reject(err);
11625
+ };
11626
+ if (socks5Client.state === "authenticated") {
11627
+ clearTimeout(timeout);
11628
+ resolve4();
11629
+ } else {
11630
+ socks5Client.once("authenticated", onAuthenticated);
11631
+ socks5Client.once("error", onError);
11632
+ }
11633
+ });
11634
+ await socks5Client.connect(targetHost, targetPort);
11635
+ await new Promise((resolve4, reject) => {
11636
+ const timeout = setTimeout(() => {
11637
+ reject(new Error("SOCKS5 connection timeout"));
11638
+ }, 5e3);
11639
+ const onConnected = (info) => {
11640
+ debug9("SOCKS5 tunnel established to", targetHost, targetPort, "via", info);
11641
+ clearTimeout(timeout);
11642
+ socks5Client.removeListener("error", onError);
11643
+ resolve4();
11644
+ };
11645
+ const onError = (err) => {
11646
+ clearTimeout(timeout);
11647
+ socks5Client.removeListener("connected", onConnected);
11648
+ reject(err);
11649
+ };
11650
+ socks5Client.once("connected", onConnected);
11651
+ socks5Client.once("error", onError);
11652
+ });
11653
+ return socket;
11654
+ }
11655
+ /**
11656
+ * Dispatch a request through the SOCKS5 proxy
11657
+ */
11658
+ async [kDispatch](opts, handler) {
11659
+ const { origin } = opts;
11660
+ debug9("dispatching request to", origin, "via SOCKS5");
11661
+ try {
11662
+ if (!this[kPool] || this[kPool].destroyed || this[kPool].closed) {
11663
+ this[kPool] = new Pool(origin, {
11664
+ pipelining: opts.pipelining,
11665
+ connections: opts.connections,
11666
+ connect: async (connectOpts, callback) => {
11667
+ try {
11668
+ const url = new URL2(origin);
11669
+ const targetHost = url.hostname;
11670
+ const targetPort = parseInt(url.port) || (url.protocol === "https:" ? 443 : 80);
11671
+ debug9("establishing SOCKS5 connection to", targetHost, targetPort);
11672
+ const socket = await this.createSocks5Connection(targetHost, targetPort);
11673
+ let finalSocket = socket;
11674
+ if (url.protocol === "https:") {
11675
+ if (!tls) {
11676
+ tls = require("tls");
11677
+ }
11678
+ debug9("upgrading to TLS");
11679
+ finalSocket = tls.connect({
11680
+ socket,
11681
+ servername: targetHost,
11682
+ ...connectOpts.tls || {}
11683
+ });
11684
+ await new Promise((resolve4, reject) => {
11685
+ finalSocket.once("secureConnect", resolve4);
11686
+ finalSocket.once("error", reject);
11687
+ });
11688
+ }
11689
+ callback(null, finalSocket);
11690
+ } catch (err) {
11691
+ debug9("SOCKS5 connection error:", err);
11692
+ callback(err);
11693
+ }
11694
+ }
11695
+ });
11696
+ }
11697
+ return this[kPool][kDispatch](opts, handler);
11698
+ } catch (err) {
11699
+ debug9("dispatch error:", err);
11700
+ if (typeof handler.onError === "function") {
11701
+ handler.onError(err);
11702
+ } else {
11703
+ throw err;
11704
+ }
11705
+ }
11706
+ }
11707
+ async [kClose]() {
11708
+ if (this[kPool]) {
11709
+ await this[kPool].close();
11710
+ }
11711
+ }
11712
+ async [kDestroy](err) {
11713
+ if (this[kPool]) {
11714
+ await this[kPool].destroy(err);
11715
+ }
11716
+ }
11717
+ };
11718
+ module2.exports = Socks5ProxyAgent;
11719
+ }
11720
+ });
11721
+
10812
11722
  // node_modules/undici/lib/dispatcher/proxy-agent.js
10813
11723
  var require_proxy_agent = __commonJS({
10814
11724
  "node_modules/undici/lib/dispatcher/proxy-agent.js"(exports2, module2) {
@@ -10821,6 +11731,7 @@ var require_proxy_agent = __commonJS({
10821
11731
  var buildConnector = require_connect();
10822
11732
  var Client = require_client();
10823
11733
  var { channels } = require_diagnostics();
11734
+ var Socks5ProxyAgent = require_socks5_proxy_agent();
10824
11735
  var kAgent = /* @__PURE__ */ Symbol("proxy agent");
10825
11736
  var kClient = /* @__PURE__ */ Symbol("proxy client");
10826
11737
  var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
@@ -10919,6 +11830,16 @@ var require_proxy_agent = __commonJS({
10919
11830
  const agentFactory = opts.factory || defaultAgentFactory;
10920
11831
  const factory = (origin2, options) => {
10921
11832
  const { protocol: protocol2 } = new URL(origin2);
11833
+ if (this[kProxy].protocol === "socks5:" || this[kProxy].protocol === "socks:") {
11834
+ return new Socks5ProxyAgent(this[kProxy].uri, {
11835
+ headers: this[kProxyHeaders],
11836
+ connect,
11837
+ factory: agentFactory,
11838
+ username: opts.username || username,
11839
+ password: opts.password || password,
11840
+ proxyTls: opts.proxyTls
11841
+ });
11842
+ }
10922
11843
  if (!this[kTunnelProxy] && protocol2 === "http:" && this[kProxy].protocol === "http:") {
10923
11844
  return new Http1ProxyWrapper(this[kProxy].uri, {
10924
11845
  headers: this[kProxyHeaders],
@@ -10928,11 +11849,19 @@ var require_proxy_agent = __commonJS({
10928
11849
  }
10929
11850
  return agentFactory(origin2, options);
10930
11851
  };
10931
- this[kClient] = clientFactory(url, { connect });
11852
+ if (protocol === "socks5:" || protocol === "socks:") {
11853
+ this[kClient] = null;
11854
+ } else {
11855
+ this[kClient] = clientFactory(url, { connect });
11856
+ }
10932
11857
  this[kAgent] = new Agent({
10933
11858
  ...opts,
10934
11859
  factory,
10935
11860
  connect: async (opts2, callback) => {
11861
+ if (!this[kClient]) {
11862
+ callback(new InvalidArgumentError("Cannot establish tunnel connection without a proxy client"));
11863
+ return;
11864
+ }
10936
11865
  let requestedPath = opts2.host;
10937
11866
  if (!opts2.port) {
10938
11867
  requestedPath += `:${defaultProtocolPort(opts2.protocol)}`;
@@ -11012,16 +11941,18 @@ var require_proxy_agent = __commonJS({
11012
11941
  }
11013
11942
  }
11014
11943
  [kClose]() {
11015
- return Promise.all([
11016
- this[kAgent].close(),
11017
- this[kClient].close()
11018
- ]);
11944
+ const promises = [this[kAgent].close()];
11945
+ if (this[kClient]) {
11946
+ promises.push(this[kClient].close());
11947
+ }
11948
+ return Promise.all(promises);
11019
11949
  }
11020
11950
  [kDestroy]() {
11021
- return Promise.all([
11022
- this[kAgent].destroy(),
11023
- this[kClient].destroy()
11024
- ]);
11951
+ const promises = [this[kAgent].destroy()];
11952
+ if (this[kClient]) {
11953
+ promises.push(this[kClient].destroy());
11954
+ }
11955
+ return Promise.all(promises);
11025
11956
  }
11026
11957
  };
11027
11958
  function buildHeaders(headers) {
@@ -11125,14 +12056,11 @@ var require_env_http_proxy_agent = __commonJS({
11125
12056
  if (entry.port && entry.port !== port) {
11126
12057
  continue;
11127
12058
  }
11128
- if (!/^[.*]/.test(entry.hostname)) {
11129
- if (hostname === entry.hostname) {
11130
- return false;
11131
- }
11132
- } else {
11133
- if (hostname.endsWith(entry.hostname.replace(/^\*/, ""))) {
11134
- return false;
11135
- }
12059
+ if (hostname === entry.hostname) {
12060
+ return false;
12061
+ }
12062
+ if (hostname.slice(-(entry.hostname.length + 1)) === `.${entry.hostname}`) {
12063
+ return false;
11136
12064
  }
11137
12065
  }
11138
12066
  return true;
@@ -11148,7 +12076,8 @@ var require_env_http_proxy_agent = __commonJS({
11148
12076
  }
11149
12077
  const parsed = entry.match(/^(.+):(\d+)$/);
11150
12078
  noProxyEntries.push({
11151
- hostname: (parsed ? parsed[1] : entry).toLowerCase(),
12079
+ // strip leading dot or asterisk with dot
12080
+ hostname: (parsed ? parsed[1] : entry).replace(/^\*?\./, "").toLowerCase(),
11152
12081
  port: parsed ? Number.parseInt(parsed[2], 10) : 0
11153
12082
  });
11154
12083
  }
@@ -12062,6 +12991,7 @@ var require_api_request = __commonJS({
12062
12991
  try {
12063
12992
  this.runInAsyncScope(callback, null, null, {
12064
12993
  statusCode,
12994
+ statusText: statusMessage,
12065
12995
  headers,
12066
12996
  trailers: this.trailers,
12067
12997
  opaque,
@@ -12803,7 +13733,8 @@ var require_mock_symbols = __commonJS({
12803
13733
  kMockAgentAddCallHistoryLog: /* @__PURE__ */ Symbol("mock agent add call history log"),
12804
13734
  kMockAgentIsCallHistoryEnabled: /* @__PURE__ */ Symbol("mock agent is call history enabled"),
12805
13735
  kMockAgentAcceptsNonStandardSearchParameters: /* @__PURE__ */ Symbol("mock agent accepts non standard search parameters"),
12806
- kMockCallHistoryAddLog: /* @__PURE__ */ Symbol("mock call history add log")
13736
+ kMockCallHistoryAddLog: /* @__PURE__ */ Symbol("mock call history add log"),
13737
+ kTotalDispatchCount: /* @__PURE__ */ Symbol("total dispatch count")
12807
13738
  };
12808
13739
  }
12809
13740
  });
@@ -12818,7 +13749,8 @@ var require_mock_utils = __commonJS({
12818
13749
  kMockAgent,
12819
13750
  kOriginalDispatch,
12820
13751
  kOrigin,
12821
- kGetNetConnect
13752
+ kGetNetConnect,
13753
+ kTotalDispatchCount
12822
13754
  } = require_mock_symbols();
12823
13755
  var { serializePathWithQuery } = require_util();
12824
13756
  var { STATUS_CODES } = require("http");
@@ -12978,6 +13910,7 @@ var require_mock_utils = __commonJS({
12978
13910
  const replyData = typeof data === "function" ? { callback: data } : { ...data };
12979
13911
  const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } };
12980
13912
  mockDispatches.push(newMockDispatch);
13913
+ mockDispatches[kTotalDispatchCount] = (mockDispatches[kTotalDispatchCount] || 0) + 1;
12981
13914
  return newMockDispatch;
12982
13915
  }
12983
13916
  function deleteMockDispatch(mockDispatches, key) {
@@ -13053,23 +13986,43 @@ var require_mock_utils = __commonJS({
13053
13986
  handler.onError(error);
13054
13987
  return true;
13055
13988
  }
13989
+ let aborted = false;
13990
+ let timer = null;
13991
+ function abort(err) {
13992
+ if (aborted) {
13993
+ return;
13994
+ }
13995
+ aborted = true;
13996
+ if (timer !== null) {
13997
+ clearTimeout(timer);
13998
+ timer = null;
13999
+ }
14000
+ handler.onError(err);
14001
+ }
14002
+ handler.onConnect?.(abort, null);
13056
14003
  if (typeof delay === "number" && delay > 0) {
13057
- setTimeout(() => {
14004
+ timer = setTimeout(() => {
14005
+ timer = null;
13058
14006
  handleReply(this[kDispatches]);
13059
14007
  }, delay);
13060
14008
  } else {
13061
14009
  handleReply(this[kDispatches]);
13062
14010
  }
13063
14011
  function handleReply(mockDispatches, _data = data) {
14012
+ if (aborted) {
14013
+ return;
14014
+ }
13064
14015
  const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers;
13065
14016
  const body = typeof _data === "function" ? _data({ ...opts, headers: optsHeaders }) : _data;
13066
14017
  if (isPromise2(body)) {
13067
14018
  return body.then((newData) => handleReply(mockDispatches, newData));
13068
14019
  }
14020
+ if (aborted) {
14021
+ return;
14022
+ }
13069
14023
  const responseData = getResponseData(body);
13070
14024
  const responseHeaders = generateKeyValues(headers);
13071
14025
  const responseTrailers = generateKeyValues(trailers);
13072
- handler.onConnect?.((err) => handler.onError(err), null);
13073
14026
  handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode));
13074
14027
  handler.onData?.(Buffer.from(responseData));
13075
14028
  handler.onComplete?.(responseTrailers);
@@ -13090,13 +14043,16 @@ var require_mock_utils = __commonJS({
13090
14043
  } catch (error) {
13091
14044
  if (error.code === "UND_MOCK_ERR_MOCK_NOT_MATCHED") {
13092
14045
  const netConnect = agent[kGetNetConnect]();
14046
+ const totalInterceptsCount = this[kDispatches][kTotalDispatchCount] || this[kDispatches].length;
14047
+ const pendingInterceptsCount = this[kDispatches].filter(({ consumed }) => !consumed).length;
14048
+ const interceptsMessage = `, ${pendingInterceptsCount} interceptor(s) remaining out of ${totalInterceptsCount} defined`;
13093
14049
  if (netConnect === false) {
13094
- throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`);
14050
+ throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)${interceptsMessage}`);
13095
14051
  }
13096
14052
  if (checkNetConnect(netConnect, origin)) {
13097
14053
  originalDispatch.call(this, opts, handler);
13098
14054
  } else {
13099
- throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`);
14055
+ throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)${interceptsMessage}`);
13100
14056
  }
13101
14057
  } else {
13102
14058
  throw error;
@@ -13116,6 +14072,15 @@ var require_mock_utils = __commonJS({
13116
14072
  }
13117
14073
  return false;
13118
14074
  }
14075
+ function normalizeOrigin(origin) {
14076
+ if (typeof origin !== "string" && !(origin instanceof URL)) {
14077
+ return origin;
14078
+ }
14079
+ if (origin instanceof URL) {
14080
+ return origin.origin;
14081
+ }
14082
+ return origin.toLowerCase();
14083
+ }
13119
14084
  function buildAndValidateMockOptions(opts) {
13120
14085
  const { agent, ...mockOptions } = opts;
13121
14086
  if ("enableCallHistory" in mockOptions && typeof mockOptions.enableCallHistory !== "boolean") {
@@ -13145,7 +14110,8 @@ var require_mock_utils = __commonJS({
13145
14110
  buildAndValidateMockOptions,
13146
14111
  getHeaderByName,
13147
14112
  buildHeadersFromArray,
13148
- normalizeSearchParams
14113
+ normalizeSearchParams,
14114
+ normalizeOrigin
13149
14115
  };
13150
14116
  }
13151
14117
  });
@@ -13703,7 +14669,7 @@ var require_mock_agent = __commonJS({
13703
14669
  } = require_mock_symbols();
13704
14670
  var MockClient = require_mock_client();
13705
14671
  var MockPool = require_mock_pool();
13706
- var { matchValue, normalizeSearchParams, buildAndValidateMockOptions } = require_mock_utils();
14672
+ var { matchValue, normalizeSearchParams, buildAndValidateMockOptions, normalizeOrigin } = require_mock_utils();
13707
14673
  var { InvalidArgumentError, UndiciError } = require_errors();
13708
14674
  var Dispatcher = require_dispatcher();
13709
14675
  var PendingInterceptorsFormatter = require_pending_interceptors_formatter();
@@ -13729,7 +14695,8 @@ var require_mock_agent = __commonJS({
13729
14695
  }
13730
14696
  }
13731
14697
  get(origin) {
13732
- const originKey = this[kIgnoreTrailingSlash] ? origin.replace(/\/$/, "") : origin;
14698
+ const normalizedOrigin = normalizeOrigin(origin);
14699
+ const originKey = this[kIgnoreTrailingSlash] ? normalizedOrigin.replace(/\/$/, "") : normalizedOrigin;
13733
14700
  let dispatcher = this[kMockAgentGet](originKey);
13734
14701
  if (!dispatcher) {
13735
14702
  dispatcher = this[kFactory](originKey);
@@ -13738,6 +14705,7 @@ var require_mock_agent = __commonJS({
13738
14705
  return dispatcher;
13739
14706
  }
13740
14707
  dispatch(opts, handler) {
14708
+ opts.origin = normalizeOrigin(opts.origin);
13741
14709
  this.get(opts.origin);
13742
14710
  this[kMockAgentAddCallHistoryLog](opts);
13743
14711
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
@@ -14856,7 +15824,7 @@ var require_redirect_handler = __commonJS({
14856
15824
  }
14857
15825
  }
14858
15826
  } else if (headers && typeof headers === "object") {
14859
- const entries = typeof headers[Symbol.iterator] === "function" ? headers : Object.entries(headers);
15827
+ const entries = util.hasSafeIterator(headers) ? headers : Object.entries(headers);
14860
15828
  for (const [key, value] of entries) {
14861
15829
  if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
14862
15830
  ret.push(key, value);
@@ -15094,6 +16062,85 @@ var require_dns = __commonJS({
15094
16062
  var DecoratorHandler = require_decorator_handler();
15095
16063
  var { InvalidArgumentError, InformationalError } = require_errors();
15096
16064
  var maxInt = Math.pow(2, 31) - 1;
16065
+ function hasSafeIterator(headers) {
16066
+ const prototype = Object.getPrototypeOf(headers);
16067
+ const ownIterator = Object.prototype.hasOwnProperty.call(headers, Symbol.iterator);
16068
+ return ownIterator || prototype != null && prototype !== Object.prototype && typeof headers[Symbol.iterator] === "function";
16069
+ }
16070
+ function isHostHeader(key) {
16071
+ return typeof key === "string" && key.toLowerCase() === "host";
16072
+ }
16073
+ function normalizeHeaders(headers) {
16074
+ if (headers == null) {
16075
+ return null;
16076
+ }
16077
+ if (Array.isArray(headers)) {
16078
+ if (headers.length === 0 || !Array.isArray(headers[0])) {
16079
+ return headers;
16080
+ }
16081
+ const normalized = [];
16082
+ for (const header of headers) {
16083
+ if (Array.isArray(header) && header.length === 2) {
16084
+ normalized.push(header[0], header[1]);
16085
+ } else {
16086
+ normalized.push(header);
16087
+ }
16088
+ }
16089
+ return normalized;
16090
+ }
16091
+ if (typeof headers === "object" && hasSafeIterator(headers)) {
16092
+ const normalized = [];
16093
+ for (const header of headers) {
16094
+ if (Array.isArray(header) && header.length === 2) {
16095
+ normalized.push(header[0], header[1]);
16096
+ } else {
16097
+ normalized.push(header);
16098
+ }
16099
+ }
16100
+ return normalized;
16101
+ }
16102
+ return headers;
16103
+ }
16104
+ function hasHostHeader(headers) {
16105
+ if (headers == null) {
16106
+ return false;
16107
+ }
16108
+ if (Array.isArray(headers)) {
16109
+ if (headers.length === 0) {
16110
+ return false;
16111
+ }
16112
+ for (let i = 0; i < headers.length; i += 2) {
16113
+ if (isHostHeader(headers[i])) {
16114
+ return true;
16115
+ }
16116
+ }
16117
+ return false;
16118
+ }
16119
+ if (typeof headers === "object") {
16120
+ for (const key in headers) {
16121
+ if (isHostHeader(key)) {
16122
+ return true;
16123
+ }
16124
+ }
16125
+ }
16126
+ return false;
16127
+ }
16128
+ function withHostHeader(host, headers) {
16129
+ const normalizedHeaders = normalizeHeaders(headers);
16130
+ if (hasHostHeader(normalizedHeaders)) {
16131
+ return normalizedHeaders;
16132
+ }
16133
+ if (Array.isArray(normalizedHeaders)) {
16134
+ return ["host", host, ...normalizedHeaders];
16135
+ }
16136
+ if (normalizedHeaders && typeof normalizedHeaders === "object") {
16137
+ return {
16138
+ host,
16139
+ ...normalizedHeaders
16140
+ };
16141
+ }
16142
+ return { host };
16143
+ }
15097
16144
  var DNSStorage = class {
15098
16145
  #maxItems = 0;
15099
16146
  #records = /* @__PURE__ */ new Map();
@@ -15352,7 +16399,8 @@ var require_dns = __commonJS({
15352
16399
  }
15353
16400
  const dispatchOpts = {
15354
16401
  ...this.#opts,
15355
- origin: `${this.#origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`
16402
+ origin: `${this.#origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`,
16403
+ headers: withHostHeader(this.#origin.host, this.#opts.headers)
15356
16404
  };
15357
16405
  this.#dispatch(dispatchOpts, this);
15358
16406
  return;
@@ -15427,10 +16475,7 @@ var require_dns = __commonJS({
15427
16475
  servername: origin.hostname,
15428
16476
  // For SNI on TLS
15429
16477
  origin: newOrigin.origin,
15430
- headers: {
15431
- host: origin.host,
15432
- ...origDispatchOpts.headers
15433
- }
16478
+ headers: withHostHeader(origin.host, origDispatchOpts.headers)
15434
16479
  };
15435
16480
  dispatch(
15436
16481
  dispatchOpts,
@@ -15453,7 +16498,8 @@ var require_cache = __commonJS({
15453
16498
  "use strict";
15454
16499
  var {
15455
16500
  safeHTTPMethods,
15456
- pathHasQueryOrFragment
16501
+ pathHasQueryOrFragment,
16502
+ hasSafeIterator
15457
16503
  } = require_util();
15458
16504
  var { serializePathWithQuery } = require_util();
15459
16505
  function makeCacheKey(opts) {
@@ -15475,22 +16521,23 @@ var require_cache = __commonJS({
15475
16521
  let headers;
15476
16522
  if (opts.headers == null) {
15477
16523
  headers = {};
15478
- } else if (typeof opts.headers[Symbol.iterator] === "function") {
16524
+ } else if (typeof opts.headers === "object") {
15479
16525
  headers = {};
15480
- for (const x of opts.headers) {
15481
- if (!Array.isArray(x)) {
15482
- throw new Error("opts.headers is not a valid header map");
16526
+ if (hasSafeIterator(opts.headers)) {
16527
+ for (const x of opts.headers) {
16528
+ if (!Array.isArray(x)) {
16529
+ throw new Error("opts.headers is not a valid header map");
16530
+ }
16531
+ const [key, val] = x;
16532
+ if (typeof key !== "string" || typeof val !== "string") {
16533
+ throw new Error("opts.headers is not a valid header map");
16534
+ }
16535
+ headers[key.toLowerCase()] = val;
15483
16536
  }
15484
- const [key, val] = x;
15485
- if (typeof key !== "string" || typeof val !== "string") {
15486
- throw new Error("opts.headers is not a valid header map");
16537
+ } else {
16538
+ for (const key of Object.keys(opts.headers)) {
16539
+ headers[key.toLowerCase()] = opts.headers[key];
15487
16540
  }
15488
- headers[key.toLowerCase()] = val;
15489
- }
15490
- } else if (typeof opts.headers === "object") {
15491
- headers = {};
15492
- for (const key of Object.keys(opts.headers)) {
15493
- headers[key.toLowerCase()] = opts.headers[key];
15494
16541
  }
15495
16542
  } else {
15496
16543
  throw new Error("opts.headers is not an object");
@@ -16314,7 +17361,7 @@ var require_cache_handler = __commonJS({
16314
17361
  return downstreamOnHeaders();
16315
17362
  }
16316
17363
  const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
16317
- if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives)) {
17364
+ if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
16318
17365
  return downstreamOnHeaders();
16319
17366
  }
16320
17367
  const now = Date.now();
@@ -16352,40 +17399,67 @@ var require_cache_handler = __commonJS({
16352
17399
  deleteAt
16353
17400
  };
16354
17401
  if (statusCode === 304) {
16355
- const cachedValue = this.#store.get(this.#cacheKey);
16356
- if (!cachedValue) {
16357
- return downstreamOnHeaders();
16358
- }
16359
- value.statusCode = cachedValue.statusCode;
16360
- value.statusMessage = cachedValue.statusMessage;
16361
- value.etag = cachedValue.etag;
16362
- value.headers = { ...cachedValue.headers, ...strippedHeaders };
16363
- downstreamOnHeaders();
16364
- this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
16365
- if (!this.#writeStream || !cachedValue?.body) {
16366
- return;
16367
- }
16368
- const bodyIterator = cachedValue.body.values();
16369
- const streamCachedBody = () => {
16370
- for (const chunk of bodyIterator) {
16371
- const full = this.#writeStream.write(chunk) === false;
16372
- this.#handler.onResponseData?.(controller, chunk);
16373
- if (full) {
16374
- break;
16375
- }
17402
+ const handle304 = (cachedValue) => {
17403
+ if (!cachedValue) {
17404
+ return downstreamOnHeaders();
16376
17405
  }
16377
- };
16378
- this.#writeStream.on("error", function() {
16379
- handler.#writeStream = void 0;
16380
- handler.#store.delete(handler.#cacheKey);
16381
- }).on("drain", () => {
16382
- streamCachedBody();
16383
- }).on("close", function() {
16384
- if (handler.#writeStream === this) {
16385
- handler.#writeStream = void 0;
17406
+ value.statusCode = cachedValue.statusCode;
17407
+ value.statusMessage = cachedValue.statusMessage;
17408
+ value.etag = cachedValue.etag;
17409
+ value.headers = { ...cachedValue.headers, ...strippedHeaders };
17410
+ downstreamOnHeaders();
17411
+ this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
17412
+ if (!this.#writeStream || !cachedValue?.body) {
17413
+ return;
16386
17414
  }
16387
- });
16388
- streamCachedBody();
17415
+ if (typeof cachedValue.body.values === "function") {
17416
+ const bodyIterator = cachedValue.body.values();
17417
+ const streamCachedBody = () => {
17418
+ for (const chunk of bodyIterator) {
17419
+ const full = this.#writeStream.write(chunk) === false;
17420
+ this.#handler.onResponseData?.(controller, chunk);
17421
+ if (full) {
17422
+ break;
17423
+ }
17424
+ }
17425
+ };
17426
+ this.#writeStream.on("error", function() {
17427
+ handler.#writeStream = void 0;
17428
+ handler.#store.delete(handler.#cacheKey);
17429
+ }).on("drain", () => {
17430
+ streamCachedBody();
17431
+ }).on("close", function() {
17432
+ if (handler.#writeStream === this) {
17433
+ handler.#writeStream = void 0;
17434
+ }
17435
+ });
17436
+ streamCachedBody();
17437
+ } else if (typeof cachedValue.body.on === "function") {
17438
+ cachedValue.body.on("data", (chunk) => {
17439
+ this.#writeStream.write(chunk);
17440
+ this.#handler.onResponseData?.(controller, chunk);
17441
+ }).on("end", () => {
17442
+ this.#writeStream.end();
17443
+ }).on("error", () => {
17444
+ this.#writeStream = void 0;
17445
+ this.#store.delete(this.#cacheKey);
17446
+ });
17447
+ this.#writeStream.on("error", function() {
17448
+ handler.#writeStream = void 0;
17449
+ handler.#store.delete(handler.#cacheKey);
17450
+ }).on("close", function() {
17451
+ if (handler.#writeStream === this) {
17452
+ handler.#writeStream = void 0;
17453
+ }
17454
+ });
17455
+ }
17456
+ };
17457
+ const result = this.#store.get(this.#cacheKey);
17458
+ if (result && typeof result.then === "function") {
17459
+ result.then(handle304);
17460
+ } else {
17461
+ handle304(result);
17462
+ }
16389
17463
  } else {
16390
17464
  if (typeof resHeaders.etag === "string" && isEtagUsable(resHeaders.etag)) {
16391
17465
  value.etag = resHeaders.etag;
@@ -16422,7 +17496,7 @@ var require_cache_handler = __commonJS({
16422
17496
  this.#handler.onResponseError?.(controller, err);
16423
17497
  }
16424
17498
  };
16425
- function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives) {
17499
+ function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
16426
17500
  if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) {
16427
17501
  return false;
16428
17502
  }
@@ -16439,8 +17513,11 @@ var require_cache_handler = __commonJS({
16439
17513
  if (resHeaders.vary?.includes("*")) {
16440
17514
  return false;
16441
17515
  }
16442
- if (resHeaders.authorization) {
16443
- if (!cacheControlDirectives.public || typeof resHeaders.authorization !== "string") {
17516
+ if (reqHeaders?.authorization) {
17517
+ if (!cacheControlDirectives.public && !cacheControlDirectives["s-maxage"] && !cacheControlDirectives["must-revalidate"]) {
17518
+ return false;
17519
+ }
17520
+ if (typeof reqHeaders.authorization !== "string") {
16444
17521
  return false;
16445
17522
  }
16446
17523
  if (Array.isArray(cacheControlDirectives["no-cache"]) && cacheControlDirectives["no-cache"].includes("authorization")) {
@@ -16509,9 +17586,13 @@ var require_cache_handler = __commonJS({
16509
17586
  if (cacheControlDirectives["stale-if-error"]) {
16510
17587
  staleIfError = staleAt + cacheControlDirectives["stale-if-error"] * 1e3;
16511
17588
  }
16512
- if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
17589
+ if (cacheControlDirectives.immutable && staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
16513
17590
  immutable = now + 31536e6;
16514
17591
  }
17592
+ if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) {
17593
+ const freshnessLifetime = staleAt - now;
17594
+ return staleAt + freshnessLifetime;
17595
+ }
16515
17596
  return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable);
16516
17597
  }
16517
17598
  function stripNecessaryHeaders(resHeaders, cacheControlDirectives) {
@@ -16832,6 +17913,18 @@ var require_cache2 = __commonJS({
16832
17913
  var CacheRevalidationHandler = require_cache_revalidation_handler();
16833
17914
  var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader } = require_cache();
16834
17915
  var { AbortError } = require_errors();
17916
+ function assertCacheOrigins(origins, name) {
17917
+ if (origins === void 0) return;
17918
+ if (!Array.isArray(origins)) {
17919
+ throw new TypeError(`expected ${name} to be an array or undefined, got ${typeof origins}`);
17920
+ }
17921
+ for (let i = 0; i < origins.length; i++) {
17922
+ const origin = origins[i];
17923
+ if (typeof origin !== "string" && !(origin instanceof RegExp)) {
17924
+ throw new TypeError(`expected ${name}[${i}] to be a string or RegExp, got ${typeof origin}`);
17925
+ }
17926
+ }
17927
+ }
16835
17928
  var nop = () => {
16836
17929
  };
16837
17930
  function needsRevalidation(result, cacheControlDirectives, { headers = {} }) {
@@ -16976,7 +18069,7 @@ var require_cache2 = __commonJS({
16976
18069
  if (!revalidate && withinStaleWhileRevalidateWindow(result)) {
16977
18070
  sendCachedValue(handler, opts, result, age, null, true);
16978
18071
  queueMicrotask(() => {
16979
- let headers2 = {
18072
+ const headers2 = {
16980
18073
  ...opts.headers,
16981
18074
  "if-modified-since": new Date(result.cachedAt).toUTCString()
16982
18075
  };
@@ -16984,10 +18077,11 @@ var require_cache2 = __commonJS({
16984
18077
  headers2["if-none-match"] = result.etag;
16985
18078
  }
16986
18079
  if (result.vary) {
16987
- headers2 = {
16988
- ...headers2,
16989
- ...result.vary
16990
- };
18080
+ for (const key in result.vary) {
18081
+ if (result.vary[key] != null) {
18082
+ headers2[key] = result.vary[key];
18083
+ }
18084
+ }
16991
18085
  }
16992
18086
  dispatch(
16993
18087
  {
@@ -17018,7 +18112,7 @@ var require_cache2 = __commonJS({
17018
18112
  if (staleIfErrorExpiry) {
17019
18113
  withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
17020
18114
  }
17021
- let headers = {
18115
+ const headers = {
17022
18116
  ...opts.headers,
17023
18117
  "if-modified-since": new Date(result.cachedAt).toUTCString()
17024
18118
  };
@@ -17026,10 +18120,11 @@ var require_cache2 = __commonJS({
17026
18120
  headers["if-none-match"] = result.etag;
17027
18121
  }
17028
18122
  if (result.vary) {
17029
- headers = {
17030
- ...headers,
17031
- ...result.vary
17032
- };
18123
+ for (const key in result.vary) {
18124
+ if (result.vary[key] != null) {
18125
+ headers[key] = result.vary[key];
18126
+ }
18127
+ }
17033
18128
  }
17034
18129
  return dispatch(
17035
18130
  {
@@ -17059,13 +18154,15 @@ var require_cache2 = __commonJS({
17059
18154
  store = new MemoryCacheStore(),
17060
18155
  methods = ["GET"],
17061
18156
  cacheByDefault = void 0,
17062
- type = "shared"
18157
+ type = "shared",
18158
+ origins = void 0
17063
18159
  } = opts;
17064
18160
  if (typeof opts !== "object" || opts === null) {
17065
18161
  throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`);
17066
18162
  }
17067
18163
  assertCacheStore(store, "opts.store");
17068
18164
  assertCacheMethods(methods, "opts.methods");
18165
+ assertCacheOrigins(origins, "opts.origins");
17069
18166
  if (typeof cacheByDefault !== "undefined" && typeof cacheByDefault !== "number") {
17070
18167
  throw new TypeError(`expected opts.cacheByDefault to be number or undefined, got ${typeof cacheByDefault}`);
17071
18168
  }
@@ -17084,6 +18181,25 @@ var require_cache2 = __commonJS({
17084
18181
  if (!opts2.origin || safeMethodsToNotCache.includes(opts2.method)) {
17085
18182
  return dispatch(opts2, handler);
17086
18183
  }
18184
+ if (origins !== void 0) {
18185
+ const requestOrigin = opts2.origin.toString().toLowerCase();
18186
+ let isAllowed = false;
18187
+ for (let i = 0; i < origins.length; i++) {
18188
+ const allowed = origins[i];
18189
+ if (typeof allowed === "string") {
18190
+ if (allowed.toLowerCase() === requestOrigin) {
18191
+ isAllowed = true;
18192
+ break;
18193
+ }
18194
+ } else if (allowed.test(requestOrigin)) {
18195
+ isAllowed = true;
18196
+ break;
18197
+ }
18198
+ }
18199
+ if (!isAllowed) {
18200
+ return dispatch(opts2, handler);
18201
+ }
18202
+ }
17087
18203
  opts2 = {
17088
18204
  ...opts2,
17089
18205
  headers: normalizeHeaders(opts2)
@@ -17149,8 +18265,6 @@ var require_decompress = __commonJS({
17149
18265
  var DecompressHandler = class extends DecoratorHandler {
17150
18266
  /** @type {Transform[]} */
17151
18267
  #decompressors = [];
17152
- /** @type {NodeJS.WritableStream&NodeJS.ReadableStream|null} */
17153
- #pipelineStream;
17154
18268
  /** @type {Readonly<number[]>} */
17155
18269
  #skipStatusCodes;
17156
18270
  /** @type {boolean} */
@@ -17237,7 +18351,7 @@ var require_decompress = __commonJS({
17237
18351
  #setupMultipleDecompressors(controller) {
17238
18352
  const lastDecompressor = this.#decompressors[this.#decompressors.length - 1];
17239
18353
  this.#setupDecompressorEvents(lastDecompressor, controller);
17240
- this.#pipelineStream = pipeline(this.#decompressors, (err) => {
18354
+ pipeline(this.#decompressors, (err) => {
17241
18355
  if (err) {
17242
18356
  super.onResponseError(controller, err);
17243
18357
  return;
@@ -17251,7 +18365,6 @@ var require_decompress = __commonJS({
17251
18365
  */
17252
18366
  #cleanupDecompressors() {
17253
18367
  this.#decompressors.length = 0;
17254
- this.#pipelineStream = null;
17255
18368
  }
17256
18369
  /**
17257
18370
  * @param {Controller} controller
@@ -17277,7 +18390,7 @@ var require_decompress = __commonJS({
17277
18390
  } else {
17278
18391
  this.#setupMultipleDecompressors(controller);
17279
18392
  }
17280
- super.onResponseStart(controller, statusCode, newHeaders, statusMessage);
18393
+ return super.onResponseStart(controller, statusCode, newHeaders, statusMessage);
17281
18394
  }
17282
18395
  /**
17283
18396
  * @param {Controller} controller
@@ -17342,19 +18455,21 @@ var require_decompress = __commonJS({
17342
18455
  var require_deduplication_handler = __commonJS({
17343
18456
  "node_modules/undici/lib/handler/deduplication-handler.js"(exports2, module2) {
17344
18457
  "use strict";
18458
+ var { RequestAbortedError } = require_errors();
18459
+ var DEFAULT_MAX_BUFFER_SIZE = 5 * 1024 * 1024;
17345
18460
  var DeduplicationHandler = class {
17346
18461
  /**
17347
18462
  * @type {DispatchHandler}
17348
18463
  */
17349
18464
  #primaryHandler;
17350
18465
  /**
17351
- * @type {DispatchHandler[]}
18466
+ * @type {WaitingHandler[]}
17352
18467
  */
17353
18468
  #waitingHandlers = [];
17354
18469
  /**
17355
- * @type {Buffer[]}
18470
+ * @type {number}
17356
18471
  */
17357
- #chunks = [];
18472
+ #maxBufferSize = DEFAULT_MAX_BUFFER_SIZE;
17358
18473
  /**
17359
18474
  * @type {number}
17360
18475
  */
@@ -17371,6 +18486,18 @@ var require_deduplication_handler = __commonJS({
17371
18486
  * @type {boolean}
17372
18487
  */
17373
18488
  #aborted = false;
18489
+ /**
18490
+ * @type {boolean}
18491
+ */
18492
+ #responseStarted = false;
18493
+ /**
18494
+ * @type {boolean}
18495
+ */
18496
+ #responseDataStarted = false;
18497
+ /**
18498
+ * @type {boolean}
18499
+ */
18500
+ #completed = false;
17374
18501
  /**
17375
18502
  * @type {import('../../types/dispatcher.d.ts').default.DispatchController | null}
17376
18503
  */
@@ -17382,20 +18509,51 @@ var require_deduplication_handler = __commonJS({
17382
18509
  /**
17383
18510
  * @param {DispatchHandler} primaryHandler The primary handler
17384
18511
  * @param {() => void} onComplete Callback when request completes
18512
+ * @param {number} [maxBufferSize] Maximum paused buffer size per waiting handler
17385
18513
  */
17386
- constructor(primaryHandler, onComplete) {
18514
+ constructor(primaryHandler, onComplete, maxBufferSize = DEFAULT_MAX_BUFFER_SIZE) {
17387
18515
  this.#primaryHandler = primaryHandler;
17388
18516
  this.#onComplete = onComplete;
18517
+ this.#maxBufferSize = maxBufferSize;
17389
18518
  }
17390
18519
  /**
17391
- * Add a waiting handler that will receive the buffered response
18520
+ * Add a waiting handler that will receive response events.
18521
+ * Returns false if deduplication can no longer safely attach this handler.
18522
+ *
17392
18523
  * @param {DispatchHandler} handler
18524
+ * @returns {boolean}
17393
18525
  */
17394
18526
  addWaitingHandler(handler) {
17395
- this.#waitingHandlers.push(handler);
18527
+ if (this.#completed || this.#responseDataStarted) {
18528
+ return false;
18529
+ }
18530
+ const waitingHandler = this.#createWaitingHandler(handler);
18531
+ const waitingController = waitingHandler.controller;
18532
+ try {
18533
+ handler.onRequestStart?.(waitingController, null);
18534
+ if (waitingController.aborted) {
18535
+ waitingHandler.done = true;
18536
+ return true;
18537
+ }
18538
+ if (this.#responseStarted) {
18539
+ handler.onResponseStart?.(
18540
+ waitingController,
18541
+ this.#statusCode,
18542
+ this.#headers,
18543
+ this.#statusMessage
18544
+ );
18545
+ }
18546
+ } catch {
18547
+ waitingHandler.done = true;
18548
+ return true;
18549
+ }
18550
+ if (!waitingController.aborted) {
18551
+ this.#waitingHandlers.push(waitingHandler);
18552
+ }
18553
+ return true;
17396
18554
  }
17397
18555
  /**
17398
- * @param {() => void} abort
18556
+ * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
17399
18557
  * @param {any} context
17400
18558
  */
17401
18559
  onRequestStart(controller, context) {
@@ -17418,26 +18576,95 @@ var require_deduplication_handler = __commonJS({
17418
18576
  * @param {string} statusMessage
17419
18577
  */
17420
18578
  onResponseStart(controller, statusCode, headers, statusMessage) {
18579
+ this.#responseStarted = true;
17421
18580
  this.#statusCode = statusCode;
17422
18581
  this.#headers = headers;
17423
18582
  this.#statusMessage = statusMessage;
17424
18583
  this.#primaryHandler.onResponseStart?.(controller, statusCode, headers, statusMessage);
18584
+ for (const waitingHandler of this.#waitingHandlers) {
18585
+ const { handler, controller: waitingController } = waitingHandler;
18586
+ if (waitingHandler.done || waitingController.aborted) {
18587
+ waitingHandler.done = true;
18588
+ continue;
18589
+ }
18590
+ try {
18591
+ handler.onResponseStart?.(
18592
+ waitingController,
18593
+ statusCode,
18594
+ headers,
18595
+ statusMessage
18596
+ );
18597
+ } catch {
18598
+ }
18599
+ if (waitingController.aborted) {
18600
+ waitingHandler.done = true;
18601
+ }
18602
+ }
18603
+ this.#pruneDoneWaitingHandlers();
17425
18604
  }
17426
18605
  /**
17427
18606
  * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
17428
18607
  * @param {Buffer} chunk
17429
18608
  */
17430
18609
  onResponseData(controller, chunk) {
17431
- this.#chunks.push(Buffer.from(chunk));
18610
+ if (this.#aborted || this.#completed) {
18611
+ return;
18612
+ }
18613
+ this.#responseDataStarted = true;
17432
18614
  this.#primaryHandler.onResponseData?.(controller, chunk);
18615
+ for (const waitingHandler of this.#waitingHandlers) {
18616
+ const { handler, controller: waitingController } = waitingHandler;
18617
+ if (waitingHandler.done || waitingController.aborted) {
18618
+ waitingHandler.done = true;
18619
+ continue;
18620
+ }
18621
+ if (waitingController.paused) {
18622
+ this.#bufferWaitingChunk(waitingHandler, chunk);
18623
+ continue;
18624
+ }
18625
+ try {
18626
+ handler.onResponseData?.(waitingController, chunk);
18627
+ } catch {
18628
+ }
18629
+ if (waitingController.aborted) {
18630
+ waitingHandler.done = true;
18631
+ waitingHandler.bufferedChunks = [];
18632
+ waitingHandler.bufferedBytes = 0;
18633
+ }
18634
+ }
18635
+ this.#pruneDoneWaitingHandlers();
17433
18636
  }
17434
18637
  /**
17435
18638
  * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
17436
18639
  * @param {object} trailers
17437
18640
  */
17438
18641
  onResponseEnd(controller, trailers) {
18642
+ if (this.#aborted || this.#completed) {
18643
+ return;
18644
+ }
18645
+ this.#completed = true;
17439
18646
  this.#primaryHandler.onResponseEnd?.(controller, trailers);
17440
- this.#notifyWaitingHandlers();
18647
+ for (const waitingHandler of this.#waitingHandlers) {
18648
+ if (waitingHandler.done || waitingHandler.controller.aborted) {
18649
+ waitingHandler.done = true;
18650
+ continue;
18651
+ }
18652
+ this.#flushWaitingHandler(waitingHandler);
18653
+ if (waitingHandler.done || waitingHandler.controller.aborted) {
18654
+ waitingHandler.done = true;
18655
+ continue;
18656
+ }
18657
+ if (waitingHandler.controller.paused && waitingHandler.bufferedChunks.length > 0) {
18658
+ waitingHandler.pendingTrailers = trailers;
18659
+ continue;
18660
+ }
18661
+ try {
18662
+ waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, trailers);
18663
+ } catch {
18664
+ }
18665
+ waitingHandler.done = true;
18666
+ }
18667
+ this.#pruneDoneWaitingHandlers();
17441
18668
  this.#onComplete?.();
17442
18669
  }
17443
18670
  /**
@@ -17445,89 +18672,138 @@ var require_deduplication_handler = __commonJS({
17445
18672
  * @param {Error} err
17446
18673
  */
17447
18674
  onResponseError(controller, err) {
18675
+ if (this.#completed) {
18676
+ return;
18677
+ }
17448
18678
  this.#aborted = true;
18679
+ this.#completed = true;
17449
18680
  this.#primaryHandler.onResponseError?.(controller, err);
17450
- this.#notifyWaitingHandlersError(err);
18681
+ for (const waitingHandler of this.#waitingHandlers) {
18682
+ this.#errorWaitingHandler(waitingHandler, err);
18683
+ }
18684
+ this.#waitingHandlers = [];
17451
18685
  this.#onComplete?.();
17452
18686
  }
17453
18687
  /**
17454
- * Notify all waiting handlers with the buffered response
18688
+ * @param {DispatchHandler} handler
18689
+ * @returns {WaitingHandler}
17455
18690
  */
17456
- #notifyWaitingHandlers() {
17457
- const body = Buffer.concat(this.#chunks);
17458
- for (const handler of this.#waitingHandlers) {
17459
- const waitingController = {
17460
- resume() {
17461
- },
17462
- pause() {
17463
- },
17464
- get paused() {
17465
- return false;
17466
- },
17467
- get aborted() {
17468
- return false;
17469
- },
17470
- get reason() {
17471
- return null;
17472
- },
17473
- abort() {
17474
- }
17475
- };
17476
- try {
17477
- handler.onRequestStart?.(waitingController, null);
17478
- if (waitingController.aborted) {
17479
- continue;
18691
+ #createWaitingHandler(handler) {
18692
+ const waitingHandler = {
18693
+ handler,
18694
+ controller: null,
18695
+ bufferedChunks: [],
18696
+ bufferedBytes: 0,
18697
+ pendingTrailers: null,
18698
+ done: false
18699
+ };
18700
+ const state = {
18701
+ aborted: false,
18702
+ paused: false,
18703
+ reason: null
18704
+ };
18705
+ waitingHandler.controller = {
18706
+ resume: () => {
18707
+ if (state.aborted) {
18708
+ return;
17480
18709
  }
17481
- handler.onResponseStart?.(
17482
- waitingController,
17483
- this.#statusCode,
17484
- this.#headers,
17485
- this.#statusMessage
17486
- );
17487
- if (waitingController.aborted) {
17488
- continue;
18710
+ state.paused = false;
18711
+ this.#flushWaitingHandler(waitingHandler);
18712
+ if (this.#completed && waitingHandler.pendingTrailers && waitingHandler.bufferedChunks.length === 0 && !state.paused && !state.aborted) {
18713
+ try {
18714
+ waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, waitingHandler.pendingTrailers);
18715
+ } catch {
18716
+ }
18717
+ waitingHandler.pendingTrailers = null;
18718
+ waitingHandler.done = true;
17489
18719
  }
17490
- if (body.length > 0) {
17491
- handler.onResponseData?.(waitingController, body);
18720
+ this.#pruneDoneWaitingHandlers();
18721
+ },
18722
+ pause: () => {
18723
+ if (!state.aborted) {
18724
+ state.paused = true;
17492
18725
  }
17493
- handler.onResponseEnd?.(waitingController, {});
17494
- } catch {
18726
+ },
18727
+ get paused() {
18728
+ return state.paused;
18729
+ },
18730
+ get aborted() {
18731
+ return state.aborted;
18732
+ },
18733
+ get reason() {
18734
+ return state.reason;
18735
+ },
18736
+ abort: (reason) => {
18737
+ state.aborted = true;
18738
+ state.reason = reason ?? null;
18739
+ waitingHandler.done = true;
18740
+ waitingHandler.pendingTrailers = null;
18741
+ waitingHandler.bufferedChunks = [];
18742
+ waitingHandler.bufferedBytes = 0;
17495
18743
  }
18744
+ };
18745
+ return waitingHandler;
18746
+ }
18747
+ /**
18748
+ * @param {WaitingHandler} waitingHandler
18749
+ * @param {Buffer} chunk
18750
+ */
18751
+ #bufferWaitingChunk(waitingHandler, chunk) {
18752
+ if (waitingHandler.done || waitingHandler.controller.aborted) {
18753
+ waitingHandler.done = true;
18754
+ waitingHandler.bufferedChunks = [];
18755
+ waitingHandler.bufferedBytes = 0;
18756
+ return;
18757
+ }
18758
+ const bufferedChunk = Buffer.from(chunk);
18759
+ waitingHandler.bufferedChunks.push(bufferedChunk);
18760
+ waitingHandler.bufferedBytes += bufferedChunk.length;
18761
+ if (waitingHandler.bufferedBytes > this.#maxBufferSize) {
18762
+ const err = new RequestAbortedError(`Deduplicated waiting handler exceeded maxBufferSize (${this.#maxBufferSize} bytes) while paused`);
18763
+ this.#errorWaitingHandler(waitingHandler, err);
17496
18764
  }
17497
- this.#waitingHandlers = [];
17498
- this.#chunks = [];
17499
18765
  }
17500
18766
  /**
17501
- * Notify all waiting handlers of an error
17502
- * @param {Error} err
18767
+ * @param {WaitingHandler} waitingHandler
17503
18768
  */
17504
- #notifyWaitingHandlersError(err) {
17505
- for (const handler of this.#waitingHandlers) {
17506
- const waitingController = {
17507
- resume() {
17508
- },
17509
- pause() {
17510
- },
17511
- get paused() {
17512
- return false;
17513
- },
17514
- get aborted() {
17515
- return true;
17516
- },
17517
- get reason() {
17518
- return err;
17519
- },
17520
- abort() {
17521
- }
17522
- };
18769
+ #flushWaitingHandler(waitingHandler) {
18770
+ const { handler, controller } = waitingHandler;
18771
+ while (!waitingHandler.done && !controller.aborted && !controller.paused && waitingHandler.bufferedChunks.length > 0) {
18772
+ const bufferedChunk = waitingHandler.bufferedChunks.shift();
18773
+ waitingHandler.bufferedBytes -= bufferedChunk.length;
17523
18774
  try {
17524
- handler.onRequestStart?.(waitingController, null);
17525
- handler.onResponseError?.(waitingController, err);
18775
+ handler.onResponseData?.(controller, bufferedChunk);
17526
18776
  } catch {
17527
18777
  }
18778
+ if (controller.aborted) {
18779
+ waitingHandler.done = true;
18780
+ waitingHandler.pendingTrailers = null;
18781
+ waitingHandler.bufferedChunks = [];
18782
+ waitingHandler.bufferedBytes = 0;
18783
+ break;
18784
+ }
17528
18785
  }
17529
- this.#waitingHandlers = [];
17530
- this.#chunks = [];
18786
+ }
18787
+ /**
18788
+ * @param {WaitingHandler} waitingHandler
18789
+ * @param {Error} err
18790
+ */
18791
+ #errorWaitingHandler(waitingHandler, err) {
18792
+ if (waitingHandler.done) {
18793
+ return;
18794
+ }
18795
+ waitingHandler.done = true;
18796
+ waitingHandler.pendingTrailers = null;
18797
+ waitingHandler.bufferedChunks = [];
18798
+ waitingHandler.bufferedBytes = 0;
18799
+ try {
18800
+ waitingHandler.controller.abort(err);
18801
+ waitingHandler.handler.onResponseError?.(waitingHandler.controller, err);
18802
+ } catch {
18803
+ }
18804
+ }
18805
+ #pruneDoneWaitingHandlers() {
18806
+ this.#waitingHandlers = this.#waitingHandlers.filter((waitingHandler) => waitingHandler.done === false);
17531
18807
  }
17532
18808
  };
17533
18809
  module2.exports = DeduplicationHandler;
@@ -17547,7 +18823,8 @@ var require_deduplicate = __commonJS({
17547
18823
  const {
17548
18824
  methods = ["GET"],
17549
18825
  skipHeaderNames = [],
17550
- excludeHeaderNames = []
18826
+ excludeHeaderNames = [],
18827
+ maxBufferSize = 5 * 1024 * 1024
17551
18828
  } = opts;
17552
18829
  if (typeof opts !== "object" || opts === null) {
17553
18830
  throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`);
@@ -17566,13 +18843,15 @@ var require_deduplicate = __commonJS({
17566
18843
  if (!Array.isArray(excludeHeaderNames)) {
17567
18844
  throw new TypeError(`expected opts.excludeHeaderNames to be an array, got ${typeof excludeHeaderNames}`);
17568
18845
  }
18846
+ if (!Number.isFinite(maxBufferSize) || maxBufferSize <= 0) {
18847
+ throw new TypeError(`expected opts.maxBufferSize to be a positive finite number, got ${maxBufferSize}`);
18848
+ }
17569
18849
  const skipHeaderNamesSet = new Set(skipHeaderNames.map((name) => name.toLowerCase()));
17570
18850
  const excludeHeaderNamesSet = new Set(excludeHeaderNames.map((name) => name.toLowerCase()));
17571
- const safeMethodsToNotDeduplicate = util.safeHTTPMethods.filter((method) => methods.includes(method) === false);
17572
18851
  const pendingRequests = /* @__PURE__ */ new Map();
17573
18852
  return (dispatch) => {
17574
18853
  return (opts2, handler) => {
17575
- if (!opts2.origin || safeMethodsToNotDeduplicate.includes(opts2.method)) {
18854
+ if (!opts2.origin || methods.includes(opts2.method) === false) {
17576
18855
  return dispatch(opts2, handler);
17577
18856
  }
17578
18857
  opts2 = {
@@ -17590,8 +18869,10 @@ var require_deduplicate = __commonJS({
17590
18869
  const dedupeKey = makeDeduplicationKey(cacheKey, excludeHeaderNamesSet);
17591
18870
  const pendingHandler = pendingRequests.get(dedupeKey);
17592
18871
  if (pendingHandler) {
17593
- pendingHandler.addWaitingHandler(handler);
17594
- return true;
18872
+ if (pendingHandler.addWaitingHandler(handler)) {
18873
+ return true;
18874
+ }
18875
+ return dispatch(opts2, handler);
17595
18876
  }
17596
18877
  const deduplicationHandler = new DeduplicationHandler(
17597
18878
  handler,
@@ -17600,7 +18881,8 @@ var require_deduplicate = __commonJS({
17600
18881
  if (pendingRequestsChannel.hasSubscribers) {
17601
18882
  pendingRequestsChannel.publish({ size: pendingRequests.size, key: dedupeKey, type: "removed" });
17602
18883
  }
17603
- }
18884
+ },
18885
+ maxBufferSize
17604
18886
  );
17605
18887
  pendingRequests.set(dedupeKey, deduplicationHandler);
17606
18888
  if (pendingRequestsChannel.hasSubscribers) {
@@ -18581,7 +19863,7 @@ var require_response = __commonJS({
18581
19863
  });
18582
19864
  }
18583
19865
  const clonedResponse = cloneResponse(this.#state);
18584
- if (this.#state.body?.stream) {
19866
+ if (this.#state.urlList.length !== 0 && this.#state.body?.stream) {
18585
19867
  streamRegistry.register(this, new WeakRef(this.#state.body.stream));
18586
19868
  }
18587
19869
  return fromInnerResponse(clonedResponse, getHeadersGuard(this.#headers));
@@ -18792,7 +20074,7 @@ var require_response = __commonJS({
18792
20074
  setResponseHeaders(response, headers);
18793
20075
  setHeadersList(headers, innerResponse.headersList);
18794
20076
  setHeadersGuard(headers, guard);
18795
- if (innerResponse.body?.stream) {
20077
+ if (innerResponse.urlList.length !== 0 && innerResponse.body?.stream) {
18796
20078
  streamRegistry.register(response, new WeakRef(innerResponse.body.stream));
18797
20079
  }
18798
20080
  return response;
@@ -19451,6 +20733,8 @@ var require_request2 = __commonJS({
19451
20733
  preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false,
19452
20734
  done: init.done ?? false,
19453
20735
  timingAllowFailed: init.timingAllowFailed ?? false,
20736
+ useURLCredentials: init.useURLCredentials ?? void 0,
20737
+ traversableForUserPrompts: init.traversableForUserPrompts ?? "client",
19454
20738
  urlList: init.urlList,
19455
20739
  url: init.urlList[0],
19456
20740
  headersList: init.headersList ? new HeadersList(init.headersList) : new HeadersList()
@@ -19792,7 +21076,10 @@ var require_fetch = __commonJS({
19792
21076
  simpleRangeHeaderValue,
19793
21077
  buildContentRange,
19794
21078
  createInflate,
19795
- extractMimeType
21079
+ extractMimeType,
21080
+ hasAuthenticationEntry,
21081
+ includesCredentials,
21082
+ isTraversableNavigable
19796
21083
  } = require_util2();
19797
21084
  var assert5 = require("assert");
19798
21085
  var { safelyExtractBody, extractBody } = require_body();
@@ -19863,7 +21150,7 @@ var require_fetch = __commonJS({
19863
21150
  }
19864
21151
  const request = getRequestState(requestObject);
19865
21152
  if (requestObject.signal.aborted) {
19866
- abortFetch(p, request, null, requestObject.signal.reason);
21153
+ abortFetch(p, request, null, requestObject.signal.reason, null);
19867
21154
  return p.promise;
19868
21155
  }
19869
21156
  const globalObject = request.client.globalObject;
@@ -19880,7 +21167,7 @@ var require_fetch = __commonJS({
19880
21167
  assert5(controller != null);
19881
21168
  controller.abort(requestObject.signal.reason);
19882
21169
  const realResponse = responseObject?.deref();
19883
- abortFetch(p, request, realResponse, requestObject.signal.reason);
21170
+ abortFetch(p, request, realResponse, requestObject.signal.reason, controller.controller);
19884
21171
  }
19885
21172
  );
19886
21173
  const processResponse = (response) => {
@@ -19888,7 +21175,7 @@ var require_fetch = __commonJS({
19888
21175
  return;
19889
21176
  }
19890
21177
  if (response.aborted) {
19891
- abortFetch(p, request, responseObject, controller.serializedAbortReason);
21178
+ abortFetch(p, request, responseObject, controller.serializedAbortReason, controller.controller);
19892
21179
  return;
19893
21180
  }
19894
21181
  if (response.type === "error") {
@@ -19903,8 +21190,11 @@ var require_fetch = __commonJS({
19903
21190
  request,
19904
21191
  processResponseEndOfBody: handleFetchDone,
19905
21192
  processResponse,
19906
- dispatcher: getRequestDispatcher(requestObject)
21193
+ dispatcher: getRequestDispatcher(requestObject),
19907
21194
  // undici
21195
+ // Keep requestObject alive to prevent its AbortController from being GC'd
21196
+ // See https://github.com/nodejs/undici/issues/4627
21197
+ requestObject
19908
21198
  });
19909
21199
  return p.promise;
19910
21200
  }
@@ -19944,7 +21234,7 @@ var require_fetch = __commonJS({
19944
21234
  );
19945
21235
  }
19946
21236
  var markResourceTiming = performance.markResourceTiming;
19947
- function abortFetch(p, request, responseObject, error) {
21237
+ function abortFetch(p, request, responseObject, error, controller) {
19948
21238
  if (p) {
19949
21239
  p.reject(error);
19950
21240
  }
@@ -19961,12 +21251,7 @@ var require_fetch = __commonJS({
19961
21251
  }
19962
21252
  const response = getResponseState(responseObject);
19963
21253
  if (response.body?.stream != null && isReadable(response.body.stream)) {
19964
- response.body.stream.cancel(error).catch((err) => {
19965
- if (err.code === "ERR_INVALID_STATE") {
19966
- return;
19967
- }
19968
- throw err;
19969
- });
21254
+ controller.error(error);
19970
21255
  }
19971
21256
  }
19972
21257
  function fetching({
@@ -19977,8 +21262,10 @@ var require_fetch = __commonJS({
19977
21262
  processResponseEndOfBody,
19978
21263
  processResponseConsumeBody,
19979
21264
  useParallelQueue = false,
19980
- dispatcher = getGlobalDispatcher()
21265
+ dispatcher = getGlobalDispatcher(),
19981
21266
  // undici
21267
+ requestObject = null
21268
+ // Keep alive to prevent AbortController GC, see #4627
19982
21269
  }) {
19983
21270
  assert5(dispatcher);
19984
21271
  let taskDestination = null;
@@ -20001,7 +21288,9 @@ var require_fetch = __commonJS({
20001
21288
  processResponseConsumeBody,
20002
21289
  processResponseEndOfBody,
20003
21290
  taskDestination,
20004
- crossOriginIsolatedCapability
21291
+ crossOriginIsolatedCapability,
21292
+ // Keep requestObject alive to prevent its AbortController from being GC'd
21293
+ requestObject
20005
21294
  };
20006
21295
  assert5(!request.body || request.body.stream);
20007
21296
  if (request.window === "client") {
@@ -20450,6 +21739,17 @@ var require_fetch = __commonJS({
20450
21739
  }
20451
21740
  httpRequest.headersList.delete("host", true);
20452
21741
  if (includeCredentials) {
21742
+ if (!httpRequest.headersList.contains("authorization", true)) {
21743
+ let authorizationValue = null;
21744
+ if (hasAuthenticationEntry(httpRequest) && (httpRequest.useURLCredentials === void 0 || !includesCredentials(requestCurrentURL(httpRequest)))) {
21745
+ } else if (includesCredentials(requestCurrentURL(httpRequest)) && isAuthenticationFetch) {
21746
+ const { username, password } = requestCurrentURL(httpRequest);
21747
+ authorizationValue = `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
21748
+ }
21749
+ if (authorizationValue !== null) {
21750
+ httpRequest.headersList.append("Authorization", authorizationValue, false);
21751
+ }
21752
+ }
20453
21753
  }
20454
21754
  if (httpCache == null) {
20455
21755
  httpRequest.cache = "no-store";
@@ -20478,6 +21778,22 @@ var require_fetch = __commonJS({
20478
21778
  response.rangeRequested = true;
20479
21779
  }
20480
21780
  response.requestIncludesCredentials = includeCredentials;
21781
+ if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && isTraversableNavigable(request.traversableForUserPrompts)) {
21782
+ if (request.body != null) {
21783
+ if (request.body.source == null) {
21784
+ return makeNetworkError("expected non-null body source");
21785
+ }
21786
+ request.body = safelyExtractBody(request.body.source)[0];
21787
+ }
21788
+ if (request.useURLCredentials === void 0 || isAuthenticationFetch) {
21789
+ if (isCancelled(fetchParams)) {
21790
+ return makeAppropriateNetworkError(fetchParams);
21791
+ }
21792
+ return response;
21793
+ }
21794
+ fetchParams.controller.connection.destroy();
21795
+ response = await httpNetworkOrCacheFetch(fetchParams, true);
21796
+ }
20481
21797
  if (response.status === 407) {
20482
21798
  if (request.window === "no-window") {
20483
21799
  return makeNetworkError();
@@ -20672,9 +21988,11 @@ var require_fetch = __commonJS({
20672
21988
  function dispatch({ body }) {
20673
21989
  const url = requestCurrentURL(request);
20674
21990
  const agent = fetchParams.controller.dispatcher;
21991
+ const path26 = url.pathname + url.search;
21992
+ const hasTrailingQuestionMark = url.search.length === 0 && url.href[url.href.length - url.hash.length - 1] === "?";
20675
21993
  return new Promise((resolve4, reject) => agent.dispatch(
20676
21994
  {
20677
- path: url.pathname + url.search,
21995
+ path: hasTrailingQuestionMark ? `${path26}?` : path26,
20678
21996
  origin: url.origin,
20679
21997
  method: request.method,
20680
21998
  body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
@@ -20787,6 +22105,32 @@ var require_fetch = __commonJS({
20787
22105
  fetchParams.controller.terminate(error);
20788
22106
  reject(error);
20789
22107
  },
22108
+ onRequestUpgrade(_controller, status, headers, socket) {
22109
+ if (socket.session != null && status !== 200 || socket.session == null && status !== 101) {
22110
+ return false;
22111
+ }
22112
+ const headersList = new HeadersList();
22113
+ for (const [name, value] of Object.entries(headers)) {
22114
+ if (value == null) {
22115
+ continue;
22116
+ }
22117
+ const headerName = name.toLowerCase();
22118
+ if (Array.isArray(value)) {
22119
+ for (const entry of value) {
22120
+ headersList.append(headerName, String(entry), true);
22121
+ }
22122
+ } else {
22123
+ headersList.append(headerName, String(value), true);
22124
+ }
22125
+ }
22126
+ resolve4({
22127
+ status,
22128
+ statusText: STATUS_CODES[status],
22129
+ headersList,
22130
+ socket
22131
+ });
22132
+ return true;
22133
+ },
20790
22134
  onUpgrade(status, rawHeaders, socket) {
20791
22135
  if (socket.session != null && status !== 200 || socket.session == null && status !== 101) {
20792
22136
  return false;
@@ -21335,8 +22679,8 @@ var require_cache3 = __commonJS({
21335
22679
  }
21336
22680
  const responseList = [];
21337
22681
  for (const response of responses) {
21338
- const responseObject = fromInnerResponse(response, "immutable");
21339
- responseList.push(responseObject.clone());
22682
+ const responseObject = fromInnerResponse(cloneResponse(response), "immutable");
22683
+ responseList.push(responseObject);
21340
22684
  if (responseList.length >= maxResponses) {
21341
22685
  break;
21342
22686
  }
@@ -22385,13 +23729,17 @@ var require_util5 = __commonJS({
22385
23729
  return extensionList;
22386
23730
  }
22387
23731
  function isValidClientWindowBits(value) {
23732
+ if (value.length === 0) {
23733
+ return false;
23734
+ }
22388
23735
  for (let i = 0; i < value.length; i++) {
22389
23736
  const byte = value.charCodeAt(i);
22390
23737
  if (byte < 48 || byte > 57) {
22391
23738
  return false;
22392
23739
  }
22393
23740
  }
22394
- return true;
23741
+ const num = Number.parseInt(value, 10);
23742
+ return num >= 8 && num <= 15;
22395
23743
  }
22396
23744
  function getURLRecord(url, baseURL) {
22397
23745
  let urlRecord;
@@ -22592,7 +23940,8 @@ var require_connection = __commonJS({
22592
23940
  mode: "websocket",
22593
23941
  credentials: "include",
22594
23942
  cache: "no-store",
22595
- redirect: "error"
23943
+ redirect: "error",
23944
+ useURLCredentials: true
22596
23945
  });
22597
23946
  if (options.headers) {
22598
23947
  const headersList = getHeadersList(new Headers(options.headers));
@@ -22727,18 +24076,31 @@ var require_permessage_deflate = __commonJS({
22727
24076
  "use strict";
22728
24077
  var { createInflateRaw, Z_DEFAULT_WINDOWBITS } = require("zlib");
22729
24078
  var { isValidClientWindowBits } = require_util5();
24079
+ var { MessageSizeExceededError } = require_errors();
22730
24080
  var tail = Buffer.from([0, 0, 255, 255]);
22731
24081
  var kBuffer = /* @__PURE__ */ Symbol("kBuffer");
22732
24082
  var kLength = /* @__PURE__ */ Symbol("kLength");
24083
+ var kDefaultMaxDecompressedSize = 4 * 1024 * 1024;
22733
24084
  var PerMessageDeflate = class {
22734
24085
  /** @type {import('node:zlib').InflateRaw} */
22735
24086
  #inflate;
22736
24087
  #options = {};
24088
+ /** @type {boolean} */
24089
+ #aborted = false;
24090
+ /** @type {Function|null} */
24091
+ #currentCallback = null;
24092
+ /**
24093
+ * @param {Map<string, string>} extensions
24094
+ */
22737
24095
  constructor(extensions) {
22738
24096
  this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover");
22739
24097
  this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits");
22740
24098
  }
22741
24099
  decompress(chunk, fin, callback) {
24100
+ if (this.#aborted) {
24101
+ callback(new MessageSizeExceededError());
24102
+ return;
24103
+ }
22742
24104
  if (!this.#inflate) {
22743
24105
  let windowBits = Z_DEFAULT_WINDOWBITS;
22744
24106
  if (this.#options.serverMaxWindowBits) {
@@ -22748,26 +24110,51 @@ var require_permessage_deflate = __commonJS({
22748
24110
  }
22749
24111
  windowBits = Number.parseInt(this.#options.serverMaxWindowBits);
22750
24112
  }
22751
- this.#inflate = createInflateRaw({ windowBits });
24113
+ try {
24114
+ this.#inflate = createInflateRaw({ windowBits });
24115
+ } catch (err) {
24116
+ callback(err);
24117
+ return;
24118
+ }
22752
24119
  this.#inflate[kBuffer] = [];
22753
24120
  this.#inflate[kLength] = 0;
22754
24121
  this.#inflate.on("data", (data) => {
22755
- this.#inflate[kBuffer].push(data);
24122
+ if (this.#aborted) {
24123
+ return;
24124
+ }
22756
24125
  this.#inflate[kLength] += data.length;
24126
+ if (this.#inflate[kLength] > kDefaultMaxDecompressedSize) {
24127
+ this.#aborted = true;
24128
+ this.#inflate.removeAllListeners();
24129
+ this.#inflate.destroy();
24130
+ this.#inflate = null;
24131
+ if (this.#currentCallback) {
24132
+ const cb = this.#currentCallback;
24133
+ this.#currentCallback = null;
24134
+ cb(new MessageSizeExceededError());
24135
+ }
24136
+ return;
24137
+ }
24138
+ this.#inflate[kBuffer].push(data);
22757
24139
  });
22758
24140
  this.#inflate.on("error", (err) => {
22759
24141
  this.#inflate = null;
22760
24142
  callback(err);
22761
24143
  });
22762
24144
  }
24145
+ this.#currentCallback = callback;
22763
24146
  this.#inflate.write(chunk);
22764
24147
  if (fin) {
22765
24148
  this.#inflate.write(tail);
22766
24149
  }
22767
24150
  this.#inflate.flush(() => {
24151
+ if (this.#aborted || !this.#inflate) {
24152
+ return;
24153
+ }
22768
24154
  const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]);
22769
24155
  this.#inflate[kBuffer].length = 0;
22770
24156
  this.#inflate[kLength] = 0;
24157
+ this.#currentCallback = null;
22771
24158
  callback(null, full);
22772
24159
  });
22773
24160
  }
@@ -22795,6 +24182,7 @@ var require_receiver = __commonJS({
22795
24182
  var { failWebsocketConnection } = require_connection();
22796
24183
  var { WebsocketFrameSend } = require_frame();
22797
24184
  var { PerMessageDeflate } = require_permessage_deflate();
24185
+ var { MessageSizeExceededError } = require_errors();
22798
24186
  var ByteParser = class extends Writable {
22799
24187
  #buffers = [];
22800
24188
  #fragmentsBytes = 0;
@@ -22807,6 +24195,10 @@ var require_receiver = __commonJS({
22807
24195
  #extensions;
22808
24196
  /** @type {import('./websocket').Handler} */
22809
24197
  #handler;
24198
+ /**
24199
+ * @param {import('./websocket').Handler} handler
24200
+ * @param {Map<string, string>|null} extensions
24201
+ */
22810
24202
  constructor(handler, extensions) {
22811
24203
  super();
22812
24204
  this.#handler = handler;
@@ -22910,12 +24302,12 @@ var require_receiver = __commonJS({
22910
24302
  }
22911
24303
  const buffer = this.consume(8);
22912
24304
  const upper = buffer.readUInt32BE(0);
22913
- if (upper > 2 ** 31 - 1) {
24305
+ const lower = buffer.readUInt32BE(4);
24306
+ if (upper !== 0 || lower > 2 ** 31 - 1) {
22914
24307
  failWebsocketConnection(this.#handler, 1009, "Received payload length > 2^31 bytes.");
22915
24308
  return;
22916
24309
  }
22917
- const lower = buffer.readUInt32BE(4);
22918
- this.#info.payloadLength = (upper << 8) + lower;
24310
+ this.#info.payloadLength = lower;
22919
24311
  this.#state = parserStates.READ_DATA;
22920
24312
  } else if (this.#state === parserStates.READ_DATA) {
22921
24313
  if (this.#byteOffset < this.#info.payloadLength) {
@@ -22935,7 +24327,8 @@ var require_receiver = __commonJS({
22935
24327
  } else {
22936
24328
  this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error, data) => {
22937
24329
  if (error) {
22938
- failWebsocketConnection(this.#handler, 1007, error.message);
24330
+ const code = error instanceof MessageSizeExceededError ? 1009 : 1007;
24331
+ failWebsocketConnection(this.#handler, code, error.message);
22939
24332
  return;
22940
24333
  }
22941
24334
  this.writeFragments(data);
@@ -23203,6 +24596,15 @@ var require_websocket = __commonJS({
23203
24596
  var { SendQueue } = require_sender();
23204
24597
  var { WebsocketFrameSend } = require_frame();
23205
24598
  var { channels } = require_diagnostics();
24599
+ function getSocketAddress(socket) {
24600
+ if (typeof socket?.address === "function") {
24601
+ return socket.address();
24602
+ }
24603
+ if (typeof socket?.session?.socket?.address === "function") {
24604
+ return socket.session.socket.address();
24605
+ }
24606
+ return null;
24607
+ }
23206
24608
  var WebSocket = class _WebSocket extends EventTarget {
23207
24609
  #events = {
23208
24610
  open: null,
@@ -23474,7 +24876,7 @@ var require_websocket = __commonJS({
23474
24876
  if (channels.open.hasSubscribers) {
23475
24877
  const headers = response.headersList.entries;
23476
24878
  channels.open.publish({
23477
- address: response.socket.address(),
24879
+ address: getSocketAddress(response.socket),
23478
24880
  protocol: this.#protocol,
23479
24881
  extensions: this.#extensions,
23480
24882
  websocket: this,
@@ -23961,7 +25363,7 @@ var require_websocketstream = __commonJS({
23961
25363
  if (!this.#handler.wasEverConnected) {
23962
25364
  this.#openedPromise.reject(new WebSocketError("Socket never opened"));
23963
25365
  }
23964
- const result = this.#parser.closingInfo;
25366
+ const result = this.#parser?.closingInfo;
23965
25367
  let code = result?.code ?? 1005;
23966
25368
  if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
23967
25369
  code = 1006;
@@ -23978,8 +25380,8 @@ var require_websocketstream = __commonJS({
23978
25380
  });
23979
25381
  } else {
23980
25382
  const error = createUnvalidatedWebSocketError("unclean close", code, reason);
23981
- this.#readableStreamController.error(error);
23982
- this.#writableStream.abort(error);
25383
+ this.#readableStreamController?.error(error);
25384
+ this.#writableStream?.abort(error);
23983
25385
  this.#closedPromise.reject(error);
23984
25386
  }
23985
25387
  }
@@ -24622,6 +26024,7 @@ var require_undici = __commonJS({
24622
26024
  var RoundRobinPool = require_round_robin_pool();
24623
26025
  var Agent = require_agent();
24624
26026
  var ProxyAgent2 = require_proxy_agent();
26027
+ var Socks5ProxyAgent = require_socks5_proxy_agent();
24625
26028
  var EnvHttpProxyAgent = require_env_http_proxy_agent();
24626
26029
  var RetryAgent = require_retry_agent();
24627
26030
  var H2CClient = require_h2c_client();
@@ -24648,6 +26051,7 @@ var require_undici = __commonJS({
24648
26051
  module2.exports.RoundRobinPool = RoundRobinPool;
24649
26052
  module2.exports.Agent = Agent;
24650
26053
  module2.exports.ProxyAgent = ProxyAgent2;
26054
+ module2.exports.Socks5ProxyAgent = Socks5ProxyAgent;
24651
26055
  module2.exports.EnvHttpProxyAgent = EnvHttpProxyAgent;
24652
26056
  module2.exports.RetryAgent = RetryAgent;
24653
26057
  module2.exports.H2CClient = H2CClient;
@@ -24717,10 +26121,31 @@ var require_undici = __commonJS({
24717
26121
  module2.exports.setGlobalDispatcher = setGlobalDispatcher;
24718
26122
  module2.exports.getGlobalDispatcher = getGlobalDispatcher;
24719
26123
  var fetchImpl = require_fetch().fetch;
26124
+ var currentFilename = typeof __filename !== "undefined" ? __filename : void 0;
26125
+ function appendFetchStackTrace(err, filename) {
26126
+ if (!err || typeof err !== "object") {
26127
+ return;
26128
+ }
26129
+ const stack = typeof err.stack === "string" ? err.stack : "";
26130
+ const normalizedFilename = filename.replace(/\\/g, "/");
26131
+ if (stack && (stack.includes(filename) || stack.includes(normalizedFilename))) {
26132
+ return;
26133
+ }
26134
+ const capture = {};
26135
+ Error.captureStackTrace(capture, appendFetchStackTrace);
26136
+ if (!capture.stack) {
26137
+ return;
26138
+ }
26139
+ const captureLines = capture.stack.split("\n").slice(1).join("\n");
26140
+ err.stack = stack ? `${stack}
26141
+ ${captureLines}` : capture.stack;
26142
+ }
24720
26143
  module2.exports.fetch = function fetch2(init, options = void 0) {
24721
26144
  return fetchImpl(init, options).catch((err) => {
24722
- if (err && typeof err === "object") {
24723
- Error.captureStackTrace(err);
26145
+ if (currentFilename) {
26146
+ appendFetchStackTrace(err, currentFilename);
26147
+ } else if (err && typeof err === "object") {
26148
+ Error.captureStackTrace(err, module2.exports.fetch);
24724
26149
  }
24725
26150
  throw err;
24726
26151
  });
@@ -24876,42 +26301,6 @@ var init_proxy2 = __esm({
24876
26301
  }
24877
26302
  });
24878
26303
 
24879
- // src/utils/mergeSystemMessagesMiddleware.ts
24880
- var mergeSystemMessagesMiddleware;
24881
- var init_mergeSystemMessagesMiddleware = __esm({
24882
- "src/utils/mergeSystemMessagesMiddleware.ts"() {
24883
- "use strict";
24884
- mergeSystemMessagesMiddleware = {
24885
- specificationVersion: "v3",
24886
- transformParams: async ({ params }) => {
24887
- const mergedPrompt = [];
24888
- let pendingSystemContent = [];
24889
- for (const msg of params.prompt) {
24890
- if (msg.role === "system") {
24891
- pendingSystemContent.push(msg.content);
24892
- } else {
24893
- if (pendingSystemContent.length > 0) {
24894
- mergedPrompt.push({
24895
- role: "system",
24896
- content: pendingSystemContent.join("\n\n")
24897
- });
24898
- pendingSystemContent = [];
24899
- }
24900
- mergedPrompt.push(msg);
24901
- }
24902
- }
24903
- if (pendingSystemContent.length > 0) {
24904
- mergedPrompt.push({
24905
- role: "system",
24906
- content: pendingSystemContent.join("\n\n")
24907
- });
24908
- }
24909
- return { ...params, prompt: mergedPrompt };
24910
- }
24911
- };
24912
- }
24913
- });
24914
-
24915
26304
  // src/core/model/providers.ts
24916
26305
  var import_anthropic, import_cerebras, import_google, import_huggingface, import_openai, import_openai_compatible, import_xai, import_ai_sdk_provider, import_ai_sdk_provider2, import_ai, import_assert, defaultModelCreator, defaultAnthropicModelCreator, openaiModelCreator, openaiModelResponseCreator, createModelCreatorCompatible, providers;
24917
26306
  var init_providers = __esm({
@@ -24931,7 +26320,6 @@ var init_providers = __esm({
24931
26320
  init_models();
24932
26321
  init_utils();
24933
26322
  init_proxy2();
24934
- init_mergeSystemMessagesMiddleware();
24935
26323
  defaultModelCreator = (name, provider) => {
24936
26324
  if (provider.id !== "openai") {
24937
26325
  (0, import_assert.default)(provider.api, `Provider ${provider.id} must have an api`);
@@ -25056,6 +26444,7 @@ var init_providers = __esm({
25056
26444
  "gemini-2.5-flash-lite": models["gemini-2.5-flash-lite-preview-06-17"],
25057
26445
  "gemini-2.5-pro": models["gemini-2.5-pro"],
25058
26446
  "gemini-3-pro-preview": models["gemini-3-pro-preview"],
26447
+ "gemini-3.1-pro-preview": models["gemini-3.1-pro-preview"],
25059
26448
  "gemini-3-flash-preview": models["gemini-3-flash-preview"]
25060
26449
  },
25061
26450
  createModel(name, provider) {
@@ -25123,7 +26512,8 @@ var init_providers = __esm({
25123
26512
  "claude-3-5-sonnet-20241022": models["claude-3-5-sonnet-20241022"],
25124
26513
  "claude-haiku-4-5": models["claude-haiku-4-5"],
25125
26514
  "claude-opus-4-5": models["claude-opus-4-5"],
25126
- "claude-opus-4-6": models["claude-opus-4-6"]
26515
+ "claude-opus-4-6": models["claude-opus-4-6"],
26516
+ "claude-sonnet-4-6": models["claude-sonnet-4-6"]
25127
26517
  },
25128
26518
  apiFormat: "anthropic",
25129
26519
  headers: {
@@ -25193,6 +26583,7 @@ var init_providers = __esm({
25193
26583
  "anthropic/claude-opus-4": models["claude-4-opus"],
25194
26584
  "anthropic/claude-opus-4.1": models["claude-4.1-opus"],
25195
26585
  "anthropic/claude-opus-4.5": models["claude-opus-4-5"],
26586
+ "anthropic/claude-sonnet-4.6": models["claude-sonnet-4-6"],
25196
26587
  "anthropic/claude-opus-4.6": models["claude-opus-4-6"],
25197
26588
  "deepseek/deepseek-r1-0528": models["deepseek-r1-0528"],
25198
26589
  "deepseek/deepseek-chat-v3-0324": models["deepseek-v3-0324"],
@@ -25237,7 +26628,9 @@ var init_providers = __esm({
25237
26628
  "z-ai/glm-4.6": models["glm-4.6"],
25238
26629
  "z-ai/glm-4.6v": models["glm-4.6v"],
25239
26630
  "z-ai/glm-4.7": models["glm-4.7"],
26631
+ "z-ai/glm-5": models["glm-5"],
25240
26632
  "minimax/minimax-m2": models["minimax-m2"],
26633
+ "minimax/minimax-m2.5": models["minimax-m2.5"],
25241
26634
  "openrouter/sherlock-dash-alpha": models["sherlock-dash-alpha"],
25242
26635
  "openrouter/sherlock-think-alpha": models["sherlock-think-alpha"],
25243
26636
  "xiaomi/mimo-v2-flash:free": models["mimo-v2-flash"]
@@ -25256,43 +26649,6 @@ var init_providers = __esm({
25256
26649
  ).chat(name);
25257
26650
  }
25258
26651
  },
25259
- iflow: {
25260
- id: "iflow",
25261
- source: "built-in",
25262
- env: ["IFLOW_API_KEY"],
25263
- name: "iFlow",
25264
- api: "https://apis.iflow.cn/v1/",
25265
- doc: "https://iflow.cn/",
25266
- models: {
25267
- "qwen3-coder-plus": models["qwen3-coder-plus"],
25268
- "kimi-k2": models["kimi-k2"],
25269
- "kimi-k2-0905": models["kimi-k2-0905"],
25270
- "deepseek-v3": models["deepseek-v3-0324"],
25271
- "deepseek-v3.2": models["deepseek-v3-2-exp"],
25272
- "deepseek-r1": models["deepseek-r1-0528"],
25273
- "glm-4.6": models["glm-4.6"],
25274
- "glm-4.7": models["glm-4.7"],
25275
- "minimax-m2.1": models["minimax-m2.1"],
25276
- "qwen3-max": models["qwen3-max"]
25277
- },
25278
- createModel: createModelCreatorCompatible({
25279
- fetch: (url, options) => {
25280
- return fetch(url, {
25281
- ...options,
25282
- headers: {
25283
- ...options.headers,
25284
- "user-agent": "iFlow-Cli"
25285
- }
25286
- });
25287
- },
25288
- middlewares: [
25289
- mergeSystemMessagesMiddleware,
25290
- (0, import_ai.extractReasoningMiddleware)({
25291
- tagName: "think"
25292
- })
25293
- ]
25294
- })
25295
- },
25296
26652
  moonshotai: {
25297
26653
  id: "moonshotai",
25298
26654
  source: "built-in",
@@ -25369,7 +26725,12 @@ var init_providers = __esm({
25369
26725
  "deepseek-ai/DeepSeek-R1": models["deepseek-r1-0528"],
25370
26726
  "deepseek-ai/DeepSeek-V3.1": models["deepseek-v3-1"],
25371
26727
  "deepseek-ai/DeepSeek-V3": models["deepseek-v3-0324"],
25372
- "zai-org/GLM-4.5": models["glm-4.5"]
26728
+ "zai-org/GLM-4.5": models["glm-4.5"],
26729
+ "Pro/moonshotai/Kimi-K2.5": models["kimi-k2-5"],
26730
+ "Pro/zai-org/GLM-5": models["glm-5"],
26731
+ "Pro/zai-org/GLM-4.7": models["glm-4.7"],
26732
+ "Pro/MiniMaxAI/MiniMax-M2.5": models["minimax-m2.5"],
26733
+ "Pro/deepseek-ai/DeepSeek-V3.2": models["deepseek-v3.2"]
25373
26734
  },
25374
26735
  createModel: defaultModelCreator
25375
26736
  },
@@ -25386,6 +26747,7 @@ var init_providers = __esm({
25386
26747
  "ZhipuAI/GLM-4.5": models["glm-4.5"],
25387
26748
  "ZhipuAI/GLM-4.5V": models["glm-4.5v"],
25388
26749
  "ZhipuAI/GLM-4.6": models["glm-4.6"],
26750
+ "ZhipuAI/GLM-5": models["glm-5"],
25389
26751
  "deepseek-ai/DeepSeek-V3.2": models["deepseek-v3.2"],
25390
26752
  "deepseek-ai/DeepSeek-V3.2-Speciale": models["deepseek-v3.2-speciale"]
25391
26753
  },
@@ -25420,7 +26782,8 @@ var init_providers = __esm({
25420
26782
  "glm-4.5v": models["glm-4.5v"],
25421
26783
  "glm-4.6": models["glm-4.6"],
25422
26784
  "glm-4.6v": models["glm-4.6v"],
25423
- "glm-4.7": models["glm-4.7"]
26785
+ "glm-4.7": models["glm-4.7"],
26786
+ "glm-5": models["glm-5"]
25424
26787
  },
25425
26788
  createModel: defaultModelCreator
25426
26789
  },
@@ -25438,10 +26801,31 @@ var init_providers = __esm({
25438
26801
  "glm-4.5": models["glm-4.5"],
25439
26802
  "glm-4.5-flash": models["glm-4.5-flash"],
25440
26803
  "glm-4.6v": models["glm-4.6v"],
25441
- "glm-4.7": models["glm-4.7"]
26804
+ "glm-4.7": models["glm-4.7"],
26805
+ "glm-5": models["glm-5"]
25442
26806
  },
25443
26807
  createModel: defaultModelCreator
25444
26808
  },
26809
+ "bailian-coding-plan": {
26810
+ id: "bailian-coding-plan",
26811
+ source: "built-in",
26812
+ env: ["BAILIAN_CODING_API_KEY"],
26813
+ name: "BaiLian Coding Plan",
26814
+ api: "https://coding.dashscope.aliyuncs.com/apps/anthropic/v1",
26815
+ doc: "https://www.aliyun.com/benefit/scene/codingplan",
26816
+ apiFormat: "anthropic",
26817
+ models: {
26818
+ "qwen3.5-plus": models["qwen3-5-plus"],
26819
+ "qwen3-max-2026-01-23": models["qwen3-max"],
26820
+ "qwen3-coder-next": models["qwen3-coder-plus"],
26821
+ "qwen3-coder-plus": models["qwen3-coder-plus"],
26822
+ "MiniMax-M2.5": models["minimax-m2.5"],
26823
+ "glm-5": models["glm-5"],
26824
+ "glm-4.7": models["glm-4.7"],
26825
+ "kimi-k2.5": models["kimi-k2-5"]
26826
+ },
26827
+ createModel: defaultAnthropicModelCreator
26828
+ },
25445
26829
  zhipuai: {
25446
26830
  id: "zhipuai",
25447
26831
  source: "built-in",
@@ -25456,7 +26840,8 @@ var init_providers = __esm({
25456
26840
  "glm-4.5": models["glm-4.5"],
25457
26841
  "glm-4.5-flash": models["glm-4.5-flash"],
25458
26842
  "glm-4.6v": models["glm-4.6v"],
25459
- "glm-4.7": models["glm-4.7"]
26843
+ "glm-4.7": models["glm-4.7"],
26844
+ "glm-5": models["glm-5"]
25460
26845
  },
25461
26846
  createModel: defaultModelCreator
25462
26847
  },
@@ -25490,9 +26875,12 @@ var init_providers = __esm({
25490
26875
  "z-ai/glm-4.6": models["glm-4.6"],
25491
26876
  "z-ai/glm-4.6v": models["glm-4.6v"],
25492
26877
  "z-ai/glm-4.6v-flash": models["glm-4.6v"],
26878
+ "z-ai/glm-4.7": models["glm-4.7"],
26879
+ "z-ai/glm-5": models["glm-5"],
25493
26880
  "deepseek/deepseek-v3.2-speciale": models["deepseek-v3.2-speciale"],
25494
26881
  "deepseek/deepseek-chat": models["deepseek-v3-2-exp"],
25495
- "deepseek/deepseek-reasoner": models["deepseek-r1-0528"]
26882
+ "deepseek/deepseek-reasoner": models["deepseek-r1-0528"],
26883
+ "minimax/minimax-m2.5": models["minimax-m2.5"]
25496
26884
  },
25497
26885
  headers: {
25498
26886
  "X-Title": "OriCore",
@@ -25508,7 +26896,9 @@ var init_providers = __esm({
25508
26896
  doc: "https://platform.minimaxi.io/docs/guides/quickstart",
25509
26897
  models: {
25510
26898
  "minimax-m2": models["minimax-m2"],
25511
- "minimax-m2.1": models["minimax-m2.1"]
26899
+ "minimax-m2.1": models["minimax-m2.1"],
26900
+ "minimax-m2.5": models["minimax-m2.5"],
26901
+ "minimax-m2.7": models["minimax-m2.7"]
25512
26902
  },
25513
26903
  createModel(name, provider) {
25514
26904
  const baseURL = getProviderBaseURL(provider);
@@ -25527,7 +26917,9 @@ var init_providers = __esm({
25527
26917
  doc: "https://platform.minimaxi.com/docs/guides/quickstart",
25528
26918
  models: {
25529
26919
  "minimax-m2": models["minimax-m2"],
25530
- "minimax-m2.1": models["minimax-m2.1"]
26920
+ "minimax-m2.1": models["minimax-m2.1"],
26921
+ "minimax-m2.5": models["minimax-m2.5"],
26922
+ "minimax-m2.7": models["minimax-m2.7"]
25531
26923
  },
25532
26924
  createModel(name, provider) {
25533
26925
  const baseURL = getProviderBaseURL(provider);
@@ -25656,7 +27048,9 @@ var init_providers = __esm({
25656
27048
  "zai/glm-4.7": models["glm-4.7"],
25657
27049
  "moonshotai/kimi-k2-thinking": models["kimi-k2-thinking"],
25658
27050
  "moonshotai/kimi-k2.5": models["kimi-k2.5"],
25659
- "deepseek/deepseek-chat-v3.2": models["deepseek-v3-2-exp"]
27051
+ "deepseek/deepseek-chat-v3.2": models["deepseek-v3-2-exp"],
27052
+ "openai/gpt-oss-120b": models["gpt-oss-120b"],
27053
+ "xiaomimimo/mimo-v2-flash": models["mimo-v2-flash"]
25660
27054
  },
25661
27055
  createModel: defaultModelCreator
25662
27056
  },
@@ -25676,6 +27070,7 @@ var init_providers = __esm({
25676
27070
  "claude-4-5-sonnet": models["claude-4-5-sonnet"],
25677
27071
  "claude-haiku-4-5": models["claude-haiku-4-5"],
25678
27072
  "claude-opus-4-5": models["claude-opus-4-5"],
27073
+ "claude-sonnet-4-6": models["claude-sonnet-4-6"],
25679
27074
  "claude-opus-4-6": models["claude-opus-4-6"],
25680
27075
  "gpt-5.1": models["gpt-5.1"],
25681
27076
  "gpt-5.1-codex-max": models["gpt-5.1-codex-max"],
@@ -25694,6 +27089,38 @@ var init_providers = __esm({
25694
27089
  }
25695
27090
  return defaultModelCreator(name, provider);
25696
27091
  }
27092
+ },
27093
+ kilo: {
27094
+ id: "kilo",
27095
+ source: "built-in",
27096
+ env: ["KILO_API_KEY"],
27097
+ name: "Kilo",
27098
+ api: "https://api.kilo.ai/api/gateway",
27099
+ doc: "https://kilo.ai",
27100
+ apiFormat: "openai",
27101
+ models: {
27102
+ "z-ai/glm-5": models["glm-5"],
27103
+ "z-ai/glm-5:free": models["glm-5"],
27104
+ "z-ai/glm-4.7": models["glm-4.7"],
27105
+ "anthropic/claude-opus-4.6": models["claude-opus-4-6"],
27106
+ "anthropic/claude-sonnet-4.6": models["claude-sonnet-4-6"],
27107
+ "anthropic/claude-haiku-4.5": models["claude-haiku-4-5"],
27108
+ "anthropic/claude-sonnet-4.5": models["claude-4-5-sonnet"],
27109
+ "google/gemini-3-flash-preview": models["gemini-3-flash-preview"],
27110
+ "google/gemini-3-pro-preview": models["gemini-3-pro-preview"],
27111
+ "minimax/minimax-m2.5:free": models["minimax-m2.5"],
27112
+ "minimax/minimax-m2.5": models["minimax-m2.5"],
27113
+ "moonshotai/kimi-k2.5": models["kimi-k2-5"]
27114
+ },
27115
+ createModel: (name, provider) => {
27116
+ if (name.includes("claude-")) {
27117
+ return defaultAnthropicModelCreator(name, provider);
27118
+ }
27119
+ if (name.includes("gemini-")) {
27120
+ return defaultAnthropicModelCreator(name, provider);
27121
+ }
27122
+ return defaultModelCreator(name, provider);
27123
+ }
25697
27124
  }
25698
27125
  };
25699
27126
  }
@@ -26265,6 +27692,17 @@ function transformVariants(model, provider) {
26265
27692
  return {};
26266
27693
  }
26267
27694
  const id = (model.id || "").toLowerCase();
27695
+ if (provider.id === "bailian-coding-plan") {
27696
+ if (id.includes("kimi") || id.includes("minimax") || id.includes("glm")) {
27697
+ return {
27698
+ on: {
27699
+ thinking: {
27700
+ type: "enabled"
27701
+ }
27702
+ }
27703
+ };
27704
+ }
27705
+ }
26268
27706
  if (id.includes("deepseek") || id.includes("minimax") || id.includes("glm") || id.includes("mistral") || // id.includes("kimi") ||
26269
27707
  id.includes("grok")) {
26270
27708
  return {};
@@ -26988,6 +28426,9 @@ function stripAnsi(string) {
26988
28426
  if (typeof string !== "string") {
26989
28427
  throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
26990
28428
  }
28429
+ if (!string.includes("\x1B") && !string.includes("\x9B")) {
28430
+ return string;
28431
+ }
26991
28432
  return string.replace(regex, "");
26992
28433
  }
26993
28434
  var regex;
@@ -28987,6 +30428,18 @@ function normalizeMessagesForCompact(messages) {
28987
30428
  content: "[Tool operations completed]"
28988
30429
  };
28989
30430
  }
30431
+ if (message.role === "user") {
30432
+ if (Array.isArray(message.content)) {
30433
+ const filteredContent = message.content.filter(
30434
+ (part) => part.type === "text"
30435
+ );
30436
+ return {
30437
+ ...message,
30438
+ content: filteredContent.length > 0 ? filteredContent : message.content
30439
+ };
30440
+ }
30441
+ return message;
30442
+ }
28990
30443
  return message;
28991
30444
  }).filter((message) => {
28992
30445
  if (typeof message.content === "string") {
@@ -29924,6 +31377,7 @@ async function runLoop(opts) {
29924
31377
  request: result.request,
29925
31378
  response: result.response
29926
31379
  });
31380
+ let finishChunkReceived = false;
29927
31381
  for await (const chunk of result.stream) {
29928
31382
  if (opts.signal?.aborted) {
29929
31383
  return createCancelError();
@@ -29955,6 +31409,7 @@ async function runLoop(opts) {
29955
31409
  });
29956
31410
  break;
29957
31411
  case "finish":
31412
+ finishChunkReceived = true;
29958
31413
  lastUsage = Usage.fromEventUsage(chunk.usage);
29959
31414
  totalUsage.add(lastUsage);
29960
31415
  if (toolCalls.length === 0 && text.trim() === "") {
@@ -29993,6 +31448,13 @@ async function runLoop(opts) {
29993
31448
  break;
29994
31449
  }
29995
31450
  }
31451
+ if (!finishChunkReceived && toolCalls.length === 0 && text.trim() === "") {
31452
+ const error = new Error(
31453
+ "Empty response: stream ended without any chunks"
31454
+ );
31455
+ error.isRetryable = true;
31456
+ throw error;
31457
+ }
29996
31458
  break;
29997
31459
  } catch (error) {
29998
31460
  const nextRetryCount = retryCount + 1;
@@ -30160,6 +31622,8 @@ async function runLoop(opts) {
30160
31622
  }
30161
31623
  }
30162
31624
  };
31625
+ const approvedToolUses = [];
31626
+ let earlyReturn = null;
30163
31627
  for (const toolCall of toolCalls) {
30164
31628
  let toolUse = {
30165
31629
  name: toolCall.toolName,
@@ -30183,25 +31647,10 @@ async function runLoop(opts) {
30183
31647
  }
30184
31648
  }
30185
31649
  if (approved) {
30186
- toolCallsCount++;
30187
31650
  if (updatedParams) {
30188
31651
  toolUse.params = { ...toolUse.params, ...updatedParams };
30189
31652
  }
30190
- let toolResult = await opts.tools.invoke(
30191
- toolUse.name,
30192
- JSON.stringify(toolUse.params),
30193
- toolUse.callId
30194
- );
30195
- if (opts.onToolResult) {
30196
- toolResult = await opts.onToolResult(toolUse, toolResult, approved);
30197
- }
30198
- toolResults.push({
30199
- toolCallId: toolUse.callId,
30200
- toolName: toolUse.name,
30201
- input: toolUse.params,
30202
- result: toolResult
30203
- });
30204
- turnsCount--;
31653
+ approvedToolUses.push(toolUse);
30205
31654
  } else {
30206
31655
  let message = "Error: Tool execution was denied by user.";
30207
31656
  if (denyReason) {
@@ -30212,7 +31661,7 @@ async function runLoop(opts) {
30212
31661
  isError: true
30213
31662
  };
30214
31663
  if (opts.onToolResult) {
30215
- toolResult = await opts.onToolResult(toolUse, toolResult, approved);
31664
+ toolResult = await opts.onToolResult(toolUse, toolResult, false);
30216
31665
  }
30217
31666
  toolResults.push({
30218
31667
  toolCallId: toolUse.callId,
@@ -30220,8 +31669,8 @@ async function runLoop(opts) {
30220
31669
  input: toolUse.params,
30221
31670
  result: toolResult
30222
31671
  });
30223
- await addDeniedResultsForRemainingTools();
30224
31672
  if (!denyReason) {
31673
+ await addDeniedResultsForRemainingTools();
30225
31674
  await history.addMessage({
30226
31675
  role: "tool",
30227
31676
  content: toolResults.map(
@@ -30233,7 +31682,7 @@ async function runLoop(opts) {
30233
31682
  )
30234
31683
  )
30235
31684
  });
30236
- return {
31685
+ earlyReturn = {
30237
31686
  success: false,
30238
31687
  error: {
30239
31688
  type: "tool_denied",
@@ -30245,9 +31694,60 @@ async function runLoop(opts) {
30245
31694
  }
30246
31695
  }
30247
31696
  };
30248
- } else {
30249
31697
  break;
30250
31698
  }
31699
+ await addDeniedResultsForRemainingTools();
31700
+ break;
31701
+ }
31702
+ }
31703
+ if (earlyReturn) {
31704
+ return earlyReturn;
31705
+ }
31706
+ if (approvedToolUses.length > 0) {
31707
+ const executionResults = await Promise.allSettled(
31708
+ approvedToolUses.map(async (toolUse) => {
31709
+ let toolResult = await opts.tools.invoke(
31710
+ toolUse.name,
31711
+ JSON.stringify(toolUse.params),
31712
+ toolUse.callId
31713
+ );
31714
+ if (opts.onToolResult) {
31715
+ toolResult = await opts.onToolResult(toolUse, toolResult, true);
31716
+ }
31717
+ return {
31718
+ toolCallId: toolUse.callId,
31719
+ toolName: toolUse.name,
31720
+ input: toolUse.params,
31721
+ result: toolResult
31722
+ };
31723
+ })
31724
+ );
31725
+ toolCallsCount += approvedToolUses.length;
31726
+ turnsCount -= approvedToolUses.length;
31727
+ for (let i = 0; i < executionResults.length; i++) {
31728
+ const settledResult = executionResults[i];
31729
+ if (settledResult.status === "fulfilled") {
31730
+ toolResults.push(settledResult.value);
31731
+ } else {
31732
+ const failedToolUse = approvedToolUses[i];
31733
+ let errorResult = {
31734
+ llmContent: `Tool execution error: ${settledResult.reason instanceof Error ? settledResult.reason.message : String(settledResult.reason)}`,
31735
+ isError: true
31736
+ };
31737
+ if (opts.onToolResult) {
31738
+ errorResult = await opts.onToolResult(
31739
+ failedToolUse,
31740
+ errorResult,
31741
+ true
31742
+ );
31743
+ }
31744
+ toolResults.push({
31745
+ toolCallId: failedToolUse.callId,
31746
+ toolName: failedToolUse.name,
31747
+ input: failedToolUse.params,
31748
+ result: errorResult
31749
+ });
31750
+ }
30251
31751
  }
30252
31752
  }
30253
31753
  if (opts.signal?.aborted) {
@@ -30630,8 +32130,8 @@ var init_ripgrep = __esm({
30630
32130
  }
30631
32131
  try {
30632
32132
  const url = import_meta.url;
30633
- const __filename = url.startsWith("file://") ? new URL(url).pathname : url;
30634
- const moduleDir = import_pathe10.default.dirname(__filename);
32133
+ const __filename2 = url.startsWith("file://") ? new URL(url).pathname : url;
32134
+ const moduleDir = import_pathe10.default.dirname(__filename2);
30635
32135
  return isDev ? import_pathe10.default.resolve(moduleDir, "../../") : import_pathe10.default.resolve(moduleDir, "../");
30636
32136
  } catch {
30637
32137
  return process.cwd();
@@ -34786,8 +36286,10 @@ var MCPManager = class _MCPManager {
34786
36286
  return true;
34787
36287
  }
34788
36288
  #convertAiSdkToolToLocal(toolName, toolDef, serverName, config) {
36289
+ const safeServerName = serverName.replace(/[^a-zA-Z0-9_-]/g, "");
36290
+ const safeToolName = toolName.replace(/[^a-zA-Z0-9_-]/g, "_");
34789
36291
  return {
34790
- name: `mcp__${serverName.replace(/[^a-zA-Z0-9_-]/g, "")}__${toolName}`,
36292
+ name: `mcp__${safeServerName}__${safeToolName}`,
34791
36293
  description: toolDef.description,
34792
36294
  getDescription: ({ params }) => {
34793
36295
  return formatParamsDescription(params);
@@ -35018,6 +36520,16 @@ var import_fs23 = __toESM(require("fs"), 1);
35018
36520
  var import_os9 = __toESM(require("os"), 1);
35019
36521
  var import_pathe26 = __toESM(require("pathe"), 1);
35020
36522
  init_plugin();
36523
+ function isDirOrSymlinkToDir(parentDir, entry) {
36524
+ if (entry.isDirectory()) return true;
36525
+ if (entry.isSymbolicLink()) {
36526
+ try {
36527
+ return import_fs23.default.statSync(import_pathe26.default.join(parentDir, entry.name)).isDirectory();
36528
+ } catch {
36529
+ }
36530
+ }
36531
+ return false;
36532
+ }
35021
36533
  var SkillSource = /* @__PURE__ */ ((SkillSource2) => {
35022
36534
  SkillSource2["Plugin"] = "plugin";
35023
36535
  SkillSource2["GlobalClaude"] = "global-claude";
@@ -35108,7 +36620,7 @@ var SkillManager = class {
35108
36620
  try {
35109
36621
  const entries = import_fs23.default.readdirSync(skillsDir, { withFileTypes: true });
35110
36622
  for (const entry of entries) {
35111
- if (entry.isDirectory()) {
36623
+ if (isDirOrSymlinkToDir(skillsDir, entry)) {
35112
36624
  const skillPath = import_pathe26.default.join(skillsDir, entry.name, "SKILL.md");
35113
36625
  if (import_fs23.default.existsSync(skillPath)) {
35114
36626
  this.loadSkillFile(skillPath, source);
@@ -35318,7 +36830,7 @@ var SkillManager = class {
35318
36830
  if (import_fs23.default.existsSync(skillsDir) && import_fs23.default.statSync(skillsDir).isDirectory()) {
35319
36831
  const entries2 = import_fs23.default.readdirSync(skillsDir, { withFileTypes: true });
35320
36832
  for (const entry of entries2) {
35321
- if (entry.isDirectory()) {
36833
+ if (isDirOrSymlinkToDir(skillsDir, entry)) {
35322
36834
  const skillPath = import_pathe26.default.join(skillsDir, entry.name, "SKILL.md");
35323
36835
  if (import_fs23.default.existsSync(skillPath)) {
35324
36836
  skills.push(skillPath);
@@ -35331,7 +36843,7 @@ var SkillManager = class {
35331
36843
  }
35332
36844
  const entries = import_fs23.default.readdirSync(dir, { withFileTypes: true });
35333
36845
  for (const entry of entries) {
35334
- if (entry.isDirectory()) {
36846
+ if (isDirOrSymlinkToDir(dir, entry)) {
35335
36847
  const skillPath = import_pathe26.default.join(dir, entry.name, "SKILL.md");
35336
36848
  if (import_fs23.default.existsSync(skillPath)) {
35337
36849
  skills.push(skillPath);