@node9/proxy 2.8.2 → 2.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +1 -0
  2. package/dist/cli.js +1586 -513
  3. package/dist/cli.mjs +1586 -513
  4. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -24187,6 +24187,18 @@ var require_request = __commonJS({
24187
24187
  var { channels } = require_diagnostics();
24188
24188
  var { headerNameLowerCasedRecord } = require_constants();
24189
24189
  var invalidPathRegex = /[^\u0021-\u00ff]/;
24190
+ function isValidContentLengthHeaderValue(val) {
24191
+ if (typeof val !== "string" || val.length === 0) {
24192
+ return false;
24193
+ }
24194
+ for (let i = 0; i < val.length; i++) {
24195
+ const charCode = val.charCodeAt(i);
24196
+ if (charCode < 48 || charCode > 57) {
24197
+ return false;
24198
+ }
24199
+ }
24200
+ return true;
24201
+ }
24190
24202
  var kHandler = /* @__PURE__ */ Symbol("handler");
24191
24203
  var Request = class {
24192
24204
  constructor(origin, {
@@ -24461,7 +24473,11 @@ var require_request = __commonJS({
24461
24473
  } else if (typeof val[i] === "object") {
24462
24474
  throw new InvalidArgumentError(`invalid ${key} header`);
24463
24475
  } else {
24464
- arr.push(`${val[i]}`);
24476
+ const str2 = `${val[i]}`;
24477
+ if (!isValidHeaderValue(str2)) {
24478
+ throw new InvalidArgumentError(`invalid ${key} header`);
24479
+ }
24480
+ arr.push(str2);
24465
24481
  }
24466
24482
  }
24467
24483
  val = arr;
@@ -24473,6 +24489,9 @@ var require_request = __commonJS({
24473
24489
  val = "";
24474
24490
  } else {
24475
24491
  val = `${val}`;
24492
+ if (!isValidHeaderValue(val)) {
24493
+ throw new InvalidArgumentError(`invalid ${key} header`);
24494
+ }
24476
24495
  }
24477
24496
  if (headerName === "host") {
24478
24497
  if (request2.host !== null) {
@@ -24486,10 +24505,10 @@ var require_request = __commonJS({
24486
24505
  if (request2.contentLength !== null) {
24487
24506
  throw new InvalidArgumentError("duplicate content-length header");
24488
24507
  }
24489
- request2.contentLength = parseInt(val, 10);
24490
- if (!Number.isFinite(request2.contentLength)) {
24508
+ if (!isValidContentLengthHeaderValue(val)) {
24491
24509
  throw new InvalidArgumentError("invalid content-length header");
24492
24510
  }
24511
+ request2.contentLength = parseInt(val, 10);
24493
24512
  } else if (request2.contentType === null && headerName === "content-type") {
24494
24513
  request2.contentType = val;
24495
24514
  request2.headers.push(key, val);
@@ -24657,6 +24676,8 @@ var require_unwrap_handler = __commonJS({
24657
24676
  #aborted = false;
24658
24677
  #abort;
24659
24678
  [kResume] = null;
24679
+ rawHeaders = null;
24680
+ rawTrailers = null;
24660
24681
  constructor(abort) {
24661
24682
  this.#abort = abort;
24662
24683
  }
@@ -24703,10 +24724,12 @@ var require_unwrap_handler = __commonJS({
24703
24724
  return this.#handler.onResponseStarted?.();
24704
24725
  }
24705
24726
  onUpgrade(statusCode, rawHeaders, socket) {
24727
+ this.#controller.rawHeaders = rawHeaders;
24706
24728
  this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket);
24707
24729
  }
24708
24730
  onHeaders(statusCode, rawHeaders, resume, statusMessage) {
24709
24731
  this.#controller[kResume] = resume;
24732
+ this.#controller.rawHeaders = rawHeaders;
24710
24733
  this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders(rawHeaders), statusMessage);
24711
24734
  return !this.#controller.paused;
24712
24735
  }
@@ -24715,6 +24738,7 @@ var require_unwrap_handler = __commonJS({
24715
24738
  return !this.#controller.paused;
24716
24739
  }
24717
24740
  onComplete(rawTrailers) {
24741
+ this.#controller.rawTrailers = rawTrailers;
24718
24742
  this.#handler.onResponseEnd?.(this.#controller, parseHeaders(rawTrailers));
24719
24743
  }
24720
24744
  onError(err2) {
@@ -24741,6 +24765,7 @@ var require_dispatcher_base = __commonJS({
24741
24765
  var { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require_symbols();
24742
24766
  var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed");
24743
24767
  var kOnClosed = /* @__PURE__ */ Symbol("onClosed");
24768
+ var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions");
24744
24769
  var DispatcherBase = class extends Dispatcher {
24745
24770
  /** @type {boolean} */
24746
24771
  [kDestroyed] = false;
@@ -24750,6 +24775,23 @@ var require_dispatcher_base = __commonJS({
24750
24775
  [kClosed] = false;
24751
24776
  /** @type {Array<Function>|null} */
24752
24777
  [kOnClosed] = null;
24778
+ /**
24779
+ * @param {import('../../types/dispatcher').DispatcherOptions} [opts]
24780
+ */
24781
+ constructor(opts) {
24782
+ super();
24783
+ this[kWebSocketOptions] = opts?.webSocket ?? {};
24784
+ }
24785
+ /**
24786
+ * @returns {import('../../types/dispatcher').WebSocketOptions}
24787
+ */
24788
+ get webSocketOptions() {
24789
+ return {
24790
+ maxFragments: this[kWebSocketOptions].maxFragments ?? 131072,
24791
+ maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024
24792
+ // 128 MB default
24793
+ };
24794
+ }
24753
24795
  /** @returns {boolean} */
24754
24796
  get destroyed() {
24755
24797
  return this[kDestroyed];
@@ -24892,6 +24934,20 @@ var require_connect = __commonJS({
24892
24934
  if (this._maxCachedSessions === 0) {
24893
24935
  return;
24894
24936
  }
24937
+ if (this._sessionCache.has(sessionKey)) {
24938
+ this._sessionCache.delete(sessionKey);
24939
+ } else if (this._sessionCache.size >= this._maxCachedSessions) {
24940
+ for (const [key, ref] of this._sessionCache) {
24941
+ if (ref.deref() === void 0) {
24942
+ this._sessionCache.delete(key);
24943
+ return;
24944
+ }
24945
+ }
24946
+ const oldest = this._sessionCache.keys().next();
24947
+ if (!oldest.done) {
24948
+ this._sessionCache.delete(oldest.value);
24949
+ }
24950
+ }
24895
24951
  this._sessionCache.set(sessionKey, new WeakRef(session));
24896
24952
  this._sessionRegistry.register(session, sessionKey);
24897
24953
  }
@@ -26559,7 +26615,7 @@ var require_webidl = __commonJS({
26559
26615
  lowerBound = 0;
26560
26616
  upperBound = Math.pow(2, bitLength) - 1;
26561
26617
  } else {
26562
- lowerBound = Math.pow(-2, bitLength) - 1;
26618
+ lowerBound = -Math.pow(2, bitLength - 1);
26563
26619
  upperBound = Math.pow(2, bitLength - 1) - 1;
26564
26620
  }
26565
26621
  let x = Number(V);
@@ -26596,7 +26652,7 @@ var require_webidl = __commonJS({
26596
26652
  }
26597
26653
  x = webidl.util.IntegerPart(x);
26598
26654
  x = x % Math.pow(2, bitLength);
26599
- if (signedness === "signed" && x >= Math.pow(2, bitLength) - 1) {
26655
+ if (signedness === "signed" && x >= Math.pow(2, bitLength - 1)) {
26600
26656
  return x - Math.pow(2, bitLength);
26601
26657
  }
26602
26658
  return x;
@@ -27719,7 +27775,7 @@ var require_util2 = __commonJS({
27719
27775
  return !!(url.username || url.password);
27720
27776
  }
27721
27777
  function isTraversableNavigable(navigable) {
27722
- return true;
27778
+ return navigable != null && navigable !== "client" && navigable !== "no-traversable";
27723
27779
  }
27724
27780
  var EnvironmentSettingsObjectBase = class {
27725
27781
  get baseUrl() {
@@ -28114,7 +28170,7 @@ var require_formdata_parser = __commonJS({
28114
28170
  );
28115
28171
  value = decoder.decode(tokenValue);
28116
28172
  }
28117
- return { name: attrNameStr, value };
28173
+ return { name: attrNameStr, value, extended: isExtended };
28118
28174
  }
28119
28175
  function parseMultipartFormDataHeaders(input, position) {
28120
28176
  let name = null;
@@ -28149,6 +28205,7 @@ var require_formdata_parser = __commonJS({
28149
28205
  switch (bufferToLowerCasedHeaderName(headerName)) {
28150
28206
  case "content-disposition": {
28151
28207
  name = filename = null;
28208
+ let filenameIsExtended = false;
28152
28209
  const dispositionType = collectASequenceOfBytes(
28153
28210
  (char) => isToken(char),
28154
28211
  input,
@@ -28157,7 +28214,7 @@ var require_formdata_parser = __commonJS({
28157
28214
  if (dispositionType.toString("ascii").toLowerCase() !== "form-data") {
28158
28215
  throw parsingError("expected form-data for content-disposition header");
28159
28216
  }
28160
- while (position.position < input.length && input[position.position] !== 13 && input[position.position + 1] !== 10) {
28217
+ while (position.position < input.length && (input[position.position] !== 13 || input[position.position + 1] !== 10)) {
28161
28218
  const attribute = parseContentDispositionAttribute(input, position);
28162
28219
  if (!attribute) {
28163
28220
  break;
@@ -28165,7 +28222,12 @@ var require_formdata_parser = __commonJS({
28165
28222
  if (attribute.name === "name") {
28166
28223
  name = attribute.value;
28167
28224
  } else if (attribute.name === "filename") {
28168
- filename = attribute.value;
28225
+ if (attribute.extended) {
28226
+ filename = attribute.value;
28227
+ filenameIsExtended = true;
28228
+ } else if (!filenameIsExtended) {
28229
+ filename = attribute.value;
28230
+ }
28169
28231
  }
28170
28232
  }
28171
28233
  if (name === null) {
@@ -28201,7 +28263,7 @@ var require_formdata_parser = __commonJS({
28201
28263
  );
28202
28264
  }
28203
28265
  }
28204
- if (input[position.position] !== 13 && input[position.position + 1] !== 10) {
28266
+ if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
28205
28267
  throw parsingError("expected CRLF");
28206
28268
  } else {
28207
28269
  position.position += 2;
@@ -28586,6 +28648,7 @@ var require_client_h1 = __commonJS({
28586
28648
  RequestContentLengthMismatchError,
28587
28649
  ResponseContentLengthMismatchError,
28588
28650
  RequestAbortedError,
28651
+ InvalidArgumentError,
28589
28652
  HeadersTimeoutError,
28590
28653
  HeadersOverflowError,
28591
28654
  SocketError,
@@ -28632,15 +28695,18 @@ var require_client_h1 = __commonJS({
28632
28695
  var EMPTY_BUF = Buffer.alloc(0);
28633
28696
  var FastBuffer = Buffer[Symbol.species];
28634
28697
  var removeAllListeners = util.removeAllListeners;
28698
+ var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation");
28699
+ var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout");
28700
+ var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed");
28635
28701
  var extractBody;
28636
28702
  function lazyllhttp() {
28637
28703
  const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0;
28638
28704
  let mod;
28639
28705
  let useWasmSIMD = process.arch !== "ppc64";
28640
28706
  if (process.env.UNDICI_NO_WASM_SIMD === "1") {
28641
- useWasmSIMD = true;
28642
- } else if (process.env.UNDICI_NO_WASM_SIMD === "0") {
28643
28707
  useWasmSIMD = false;
28708
+ } else if (process.env.UNDICI_NO_WASM_SIMD === "0") {
28709
+ useWasmSIMD = true;
28644
28710
  }
28645
28711
  if (useWasmSIMD) {
28646
28712
  try {
@@ -28758,6 +28824,7 @@ var require_client_h1 = __commonJS({
28758
28824
  this.client = client;
28759
28825
  this.socket = socket;
28760
28826
  this.timeout = null;
28827
+ this.timeoutWeakRef = new WeakRef(this);
28761
28828
  this.timeoutValue = null;
28762
28829
  this.timeoutType = null;
28763
28830
  this.statusCode = 0;
@@ -28783,9 +28850,9 @@ var require_client_h1 = __commonJS({
28783
28850
  }
28784
28851
  if (delay) {
28785
28852
  if (type & USE_FAST_TIMER) {
28786
- this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this));
28853
+ this.timeout = timers.setFastTimeout(onParserTimeout, delay, this.timeoutWeakRef);
28787
28854
  } else {
28788
- this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this));
28855
+ this.timeout = setTimeout(onParserTimeout, delay, this.timeoutWeakRef);
28789
28856
  this.timeout?.unref();
28790
28857
  }
28791
28858
  }
@@ -28857,19 +28924,47 @@ var require_client_h1 = __commonJS({
28857
28924
  this.paused = true;
28858
28925
  socket.unshift(data);
28859
28926
  } else {
28860
- const ptr = llhttp.llhttp_get_error_reason(this.ptr);
28861
- let message = "";
28862
- if (ptr) {
28863
- const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0);
28864
- message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
28865
- }
28866
- throw new HTTPParserError(message, constants.ERROR[ret], data);
28927
+ throw this.createError(ret, data);
28867
28928
  }
28868
28929
  }
28869
28930
  } catch (err2) {
28870
28931
  util.destroy(socket, err2);
28871
28932
  }
28872
28933
  }
28934
+ finish() {
28935
+ assert(currentParser === null);
28936
+ assert(this.ptr != null);
28937
+ assert(!this.paused);
28938
+ const { llhttp } = this;
28939
+ let ret;
28940
+ try {
28941
+ currentParser = this;
28942
+ ret = llhttp.llhttp_finish(this.ptr);
28943
+ } finally {
28944
+ currentParser = null;
28945
+ }
28946
+ if (ret === constants.ERROR.OK) {
28947
+ return null;
28948
+ }
28949
+ if (ret === constants.ERROR.PAUSED || ret === constants.ERROR.PAUSED_UPGRADE) {
28950
+ this.paused = true;
28951
+ return null;
28952
+ }
28953
+ return this.createError(ret, EMPTY_BUF);
28954
+ }
28955
+ createError(ret, data) {
28956
+ const { llhttp, contentLength, bytesRead } = this;
28957
+ if (contentLength && bytesRead !== parseInt(contentLength, 10)) {
28958
+ return new ResponseContentLengthMismatchError();
28959
+ }
28960
+ const ptr = llhttp.llhttp_get_error_reason(this.ptr);
28961
+ let message = "";
28962
+ if (ptr) {
28963
+ const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0);
28964
+ message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
28965
+ }
28966
+ return new HTTPParserError(message, constants.ERROR[ret], data);
28967
+ }
28873
28968
  destroy() {
28874
28969
  assert(currentParser === null);
28875
28970
  assert(this.ptr != null);
@@ -28897,6 +28992,10 @@ var require_client_h1 = __commonJS({
28897
28992
  if (socket.destroyed) {
28898
28993
  return -1;
28899
28994
  }
28995
+ if (client[kRunning] === 0) {
28996
+ util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket)));
28997
+ return -1;
28998
+ }
28900
28999
  const request2 = client[kQueue][client[kRunningIdx]];
28901
29000
  if (!request2) {
28902
29001
  return -1;
@@ -28999,6 +29098,10 @@ var require_client_h1 = __commonJS({
28999
29098
  if (socket.destroyed) {
29000
29099
  return -1;
29001
29100
  }
29101
+ if (client[kRunning] === 0) {
29102
+ util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket)));
29103
+ return -1;
29104
+ }
29002
29105
  const request2 = client[kQueue][client[kRunningIdx]];
29003
29106
  if (!request2) {
29004
29107
  return -1;
@@ -29132,6 +29235,7 @@ var require_client_h1 = __commonJS({
29132
29235
  }
29133
29236
  request2.onComplete(headers);
29134
29237
  client[kQueue][client[kRunningIdx]++] = null;
29238
+ socket[kSocketUsed] = client[kPending] === 0;
29135
29239
  if (socket[kWriting]) {
29136
29240
  assert(client[kRunning] === 0);
29137
29241
  util.destroy(socket, new InformationalError("reset"));
@@ -29185,6 +29289,9 @@ var require_client_h1 = __commonJS({
29185
29289
  socket[kWriting] = false;
29186
29290
  socket[kReset] = false;
29187
29291
  socket[kBlocking] = false;
29292
+ socket[kIdleSocketValidation] = 0;
29293
+ socket[kIdleSocketValidationTimeout] = null;
29294
+ socket[kSocketUsed] = false;
29188
29295
  socket[kParser] = new Parser(client, socket, llhttpInstance);
29189
29296
  util.addListener(socket, "error", onHttpSocketError);
29190
29297
  util.addListener(socket, "readable", onHttpSocketReadable);
@@ -29224,7 +29331,7 @@ var require_client_h1 = __commonJS({
29224
29331
  * @returns {boolean}
29225
29332
  */
29226
29333
  busy(request2) {
29227
- if (socket[kWriting] || socket[kReset] || socket[kBlocking]) {
29334
+ if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) {
29228
29335
  return true;
29229
29336
  }
29230
29337
  if (request2) {
@@ -29246,7 +29353,11 @@ var require_client_h1 = __commonJS({
29246
29353
  assert(err2.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
29247
29354
  const parser = this[kParser];
29248
29355
  if (err2.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) {
29249
- parser.onMessageComplete();
29356
+ const parserErr = parser.finish();
29357
+ if (parserErr) {
29358
+ this[kError] = parserErr;
29359
+ this[kClient][kOnError](parserErr);
29360
+ }
29250
29361
  return;
29251
29362
  }
29252
29363
  this[kError] = err2;
@@ -29258,16 +29369,20 @@ var require_client_h1 = __commonJS({
29258
29369
  function onHttpSocketEnd() {
29259
29370
  const parser = this[kParser];
29260
29371
  if (parser.statusCode && !parser.shouldKeepAlive) {
29261
- parser.onMessageComplete();
29372
+ const parserErr = parser.finish();
29373
+ if (parserErr) {
29374
+ util.destroy(this, parserErr);
29375
+ }
29262
29376
  return;
29263
29377
  }
29264
29378
  util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this)));
29265
29379
  }
29266
29380
  function onHttpSocketClose() {
29267
29381
  const parser = this[kParser];
29382
+ clearIdleSocketValidation(this);
29268
29383
  if (parser) {
29269
29384
  if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
29270
- parser.onMessageComplete();
29385
+ this[kError] = parser.finish() || this[kError];
29271
29386
  }
29272
29387
  this[kParser].destroy();
29273
29388
  this[kParser] = null;
@@ -29296,6 +29411,23 @@ var require_client_h1 = __commonJS({
29296
29411
  function onSocketClose() {
29297
29412
  this[kClosed] = true;
29298
29413
  }
29414
+ function clearIdleSocketValidation(socket) {
29415
+ if (socket[kIdleSocketValidationTimeout]) {
29416
+ clearImmediate(socket[kIdleSocketValidationTimeout]);
29417
+ socket[kIdleSocketValidationTimeout] = null;
29418
+ }
29419
+ socket[kIdleSocketValidation] = 0;
29420
+ }
29421
+ function scheduleIdleSocketValidation(client, socket) {
29422
+ socket[kIdleSocketValidation] = 1;
29423
+ socket[kIdleSocketValidationTimeout] = setImmediate(() => {
29424
+ socket[kIdleSocketValidationTimeout] = null;
29425
+ socket[kIdleSocketValidation] = 2;
29426
+ if (client[kSocket] === socket && !socket.destroyed) {
29427
+ client[kResume]();
29428
+ }
29429
+ });
29430
+ }
29299
29431
  function resumeH1(client) {
29300
29432
  const socket = client[kSocket];
29301
29433
  if (socket && !socket.destroyed) {
@@ -29308,6 +29440,29 @@ var require_client_h1 = __commonJS({
29308
29440
  socket.ref();
29309
29441
  socket[kNoRef] = false;
29310
29442
  }
29443
+ if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) {
29444
+ if (socket[kIdleSocketValidation] === 0) {
29445
+ scheduleIdleSocketValidation(client, socket);
29446
+ socket[kParser].readMore();
29447
+ if (socket.destroyed) {
29448
+ return;
29449
+ }
29450
+ return;
29451
+ }
29452
+ if (socket[kIdleSocketValidation] === 1) {
29453
+ socket[kParser].readMore();
29454
+ if (socket.destroyed) {
29455
+ return;
29456
+ }
29457
+ return;
29458
+ }
29459
+ }
29460
+ if (client[kRunning] === 0) {
29461
+ socket[kParser].readMore();
29462
+ if (socket.destroyed) {
29463
+ return;
29464
+ }
29465
+ }
29311
29466
  if (client[kSize] === 0) {
29312
29467
  if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
29313
29468
  socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE);
@@ -29338,8 +29493,16 @@ var require_client_h1 = __commonJS({
29338
29493
  }
29339
29494
  body = bodyStream.stream;
29340
29495
  contentLength = bodyStream.length;
29341
- } else if (util.isBlobLike(body) && request2.contentType == null && body.type) {
29342
- headers.push("content-type", body.type);
29496
+ } else if (util.isBlobLike(body) && request2.contentType == null) {
29497
+ const contentType = body.type;
29498
+ if (contentType) {
29499
+ const contentTypeValue = `${contentType}`;
29500
+ if (!util.isValidHeaderValue(contentTypeValue)) {
29501
+ util.errorRequest(client, request2, new InvalidArgumentError("invalid content-type header"));
29502
+ return false;
29503
+ }
29504
+ headers.push("content-type", contentTypeValue);
29505
+ }
29343
29506
  }
29344
29507
  if (body && typeof body.read === "function") {
29345
29508
  body.read(0);
@@ -29360,6 +29523,7 @@ var require_client_h1 = __commonJS({
29360
29523
  process.emitWarning(new RequestContentLengthMismatchError());
29361
29524
  }
29362
29525
  const socket = client[kSocket];
29526
+ clearIdleSocketValidation(socket);
29363
29527
  const abort = (err2) => {
29364
29528
  if (request2.aborted || request2.completed) {
29365
29529
  return;
@@ -29752,7 +29916,9 @@ var require_client_h2 = __commonJS({
29752
29916
  RequestAbortedError,
29753
29917
  SocketError,
29754
29918
  InformationalError,
29755
- InvalidArgumentError
29919
+ InvalidArgumentError,
29920
+ HeadersTimeoutError,
29921
+ BodyTimeoutError
29756
29922
  } = require_errors();
29757
29923
  var {
29758
29924
  kUrl,
@@ -29777,6 +29943,7 @@ var require_client_h2 = __commonJS({
29777
29943
  kHTTPContext,
29778
29944
  kClosed,
29779
29945
  kBodyTimeout,
29946
+ kHeadersTimeout,
29780
29947
  kEnableConnectProtocol,
29781
29948
  kRemoteSettings,
29782
29949
  kHTTP2Stream,
@@ -29913,7 +30080,7 @@ var require_client_h2 = __commonJS({
29913
30080
  function resumeH2(client) {
29914
30081
  const socket = client[kSocket];
29915
30082
  if (socket?.destroyed === false) {
29916
- if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) {
30083
+ if (client[kSize] === 0) {
29917
30084
  socket.unref();
29918
30085
  client[kHTTP2Session].unref();
29919
30086
  } else {
@@ -29979,6 +30146,24 @@ var require_client_h2 = __commonJS({
29979
30146
  this.destroy(err2);
29980
30147
  util.destroy(this[kSocket], err2);
29981
30148
  }
30149
+ function completeRequest(client, request2, resetPendingIdx = false) {
30150
+ const queue = client[kQueue];
30151
+ const runningIdx = client[kRunningIdx];
30152
+ if (runningIdx < client[kPendingIdx] && queue[runningIdx] === request2) {
30153
+ queue[runningIdx] = null;
30154
+ client[kRunningIdx] = runningIdx + 1;
30155
+ return;
30156
+ }
30157
+ const index = queue.indexOf(request2, runningIdx);
30158
+ if (index === -1 || index >= client[kPendingIdx]) {
30159
+ return;
30160
+ }
30161
+ queue.splice(index, 1);
30162
+ client[kPendingIdx]--;
30163
+ if (resetPendingIdx && client[kPendingIdx] < client[kRunningIdx]) {
30164
+ client[kPendingIdx] = client[kRunningIdx];
30165
+ }
30166
+ }
29982
30167
  function onHttp2SessionGoAway(errorCode) {
29983
30168
  const err2 = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(this[kSocket]));
29984
30169
  const client = this[kClient];
@@ -29990,7 +30175,9 @@ var require_client_h2 = __commonJS({
29990
30175
  if (client[kRunningIdx] < client[kQueue].length) {
29991
30176
  const request2 = client[kQueue][client[kRunningIdx]];
29992
30177
  client[kQueue][client[kRunningIdx]++] = null;
29993
- util.errorRequest(client, request2, err2);
30178
+ if (request2 != null) {
30179
+ util.errorRequest(client, request2, err2);
30180
+ }
29994
30181
  client[kPendingIdx] = client[kRunningIdx];
29995
30182
  }
29996
30183
  assert(client[kRunning] === 0);
@@ -30013,7 +30200,9 @@ var require_client_h2 = __commonJS({
30013
30200
  const requests = client[kQueue].splice(client[kRunningIdx]);
30014
30201
  for (let i = 0; i < requests.length; i++) {
30015
30202
  const request2 = requests[i];
30016
- util.errorRequest(client, request2, err2);
30203
+ if (request2 != null) {
30204
+ util.errorRequest(client, request2, err2);
30205
+ }
30017
30206
  }
30018
30207
  }
30019
30208
  }
@@ -30045,7 +30234,8 @@ var require_client_h2 = __commonJS({
30045
30234
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
30046
30235
  }
30047
30236
  function writeH2(client, request2) {
30048
- const requestTimeout = request2.bodyTimeout ?? client[kBodyTimeout];
30237
+ const headersTimeout = request2.headersTimeout ?? client[kHeadersTimeout];
30238
+ const bodyTimeout = request2.bodyTimeout ?? client[kBodyTimeout];
30049
30239
  const session = client[kHTTP2Session];
30050
30240
  const { method, path: path74, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request2;
30051
30241
  let { body } = request2;
@@ -30093,6 +30283,7 @@ var require_client_h2 = __commonJS({
30093
30283
  stream.removeAllListeners("data");
30094
30284
  stream.close();
30095
30285
  client[kOnError](err2);
30286
+ completeRequest(client, request2);
30096
30287
  client[kResume]();
30097
30288
  }
30098
30289
  util.destroy(body, err2);
@@ -30127,7 +30318,7 @@ var require_client_h2 = __commonJS({
30127
30318
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
30128
30319
  request2.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
30129
30320
  ++session[kOpenStreams];
30130
- client[kQueue][client[kRunningIdx]++] = null;
30321
+ completeRequest(client, request2);
30131
30322
  });
30132
30323
  stream.on("error", () => {
30133
30324
  if (stream.rstCode === NGHTTP2_REFUSED_STREAM || stream.rstCode === NGHTTP2_CANCEL) {
@@ -30138,7 +30329,7 @@ var require_client_h2 = __commonJS({
30138
30329
  session[kOpenStreams] -= 1;
30139
30330
  if (session[kOpenStreams] === 0) session.unref();
30140
30331
  });
30141
- stream.setTimeout(requestTimeout);
30332
+ stream.setTimeout(headersTimeout);
30142
30333
  return true;
30143
30334
  }
30144
30335
  stream = session.request(headers, { endStream: false, signal });
@@ -30147,13 +30338,14 @@ var require_client_h2 = __commonJS({
30147
30338
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
30148
30339
  request2.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
30149
30340
  ++session[kOpenStreams];
30150
- client[kQueue][client[kRunningIdx]++] = null;
30341
+ completeRequest(client, request2);
30151
30342
  });
30343
+ stream.on("error", abort);
30152
30344
  stream.once("close", () => {
30153
30345
  session[kOpenStreams] -= 1;
30154
30346
  if (session[kOpenStreams] === 0) session.unref();
30155
30347
  });
30156
- stream.setTimeout(requestTimeout);
30348
+ stream.setTimeout(headersTimeout);
30157
30349
  return true;
30158
30350
  }
30159
30351
  headers[HTTP2_HEADER_PATH] = path74;
@@ -30211,12 +30403,13 @@ var require_client_h2 = __commonJS({
30211
30403
  writeBodyH2();
30212
30404
  }
30213
30405
  ++session[kOpenStreams];
30214
- stream.setTimeout(requestTimeout);
30406
+ stream.setTimeout(headersTimeout);
30215
30407
  let responseReceived = false;
30216
30408
  stream.once("response", (headers2) => {
30217
30409
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
30218
30410
  request2.onResponseStarted();
30219
30411
  responseReceived = true;
30412
+ stream.setTimeout(bodyTimeout);
30220
30413
  if (request2.aborted) {
30221
30414
  stream.removeAllListeners("data");
30222
30415
  return;
@@ -30239,12 +30432,11 @@ var require_client_h2 = __commonJS({
30239
30432
  if (!request2.aborted && !request2.completed) {
30240
30433
  request2.onComplete({});
30241
30434
  }
30242
- client[kQueue][client[kRunningIdx]++] = null;
30435
+ completeRequest(client, request2);
30243
30436
  client[kResume]();
30244
30437
  } else {
30245
30438
  abort(new InformationalError("HTTP/2: stream half-closed (remote)"));
30246
- client[kQueue][client[kRunningIdx]++] = null;
30247
- client[kPendingIdx] = client[kRunningIdx];
30439
+ completeRequest(client, request2, true);
30248
30440
  client[kResume]();
30249
30441
  }
30250
30442
  });
@@ -30254,6 +30446,9 @@ var require_client_h2 = __commonJS({
30254
30446
  if (session[kOpenStreams] === 0) {
30255
30447
  session.unref();
30256
30448
  }
30449
+ if (!request2.aborted && !request2.completed) {
30450
+ abort(new InformationalError("HTTP/2: stream closed before the response was complete"));
30451
+ }
30257
30452
  });
30258
30453
  stream.once("error", function(err2) {
30259
30454
  stream.removeAllListeners("data");
@@ -30267,7 +30462,7 @@ var require_client_h2 = __commonJS({
30267
30462
  stream.removeAllListeners("data");
30268
30463
  });
30269
30464
  stream.on("timeout", () => {
30270
- const err2 = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`);
30465
+ const err2 = responseReceived ? new BodyTimeoutError(`HTTP/2: "body timeout after ${bodyTimeout}"`) : new HeadersTimeoutError(`HTTP/2: "headers timeout after ${headersTimeout}"`);
30271
30466
  stream.removeAllListeners("data");
30272
30467
  session[kOpenStreams] -= 1;
30273
30468
  if (session[kOpenStreams] === 0) {
@@ -30575,7 +30770,8 @@ var require_client = __commonJS({
30575
30770
  useH2c,
30576
30771
  initialWindowSize,
30577
30772
  connectionWindowSize,
30578
- pingInterval
30773
+ pingInterval,
30774
+ webSocket
30579
30775
  } = {}) {
30580
30776
  if (keepAlive !== void 0) {
30581
30777
  throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead");
@@ -30653,7 +30849,7 @@ var require_client = __commonJS({
30653
30849
  if (pingInterval != null && (typeof pingInterval !== "number" || !Number.isInteger(pingInterval) || pingInterval < 0)) {
30654
30850
  throw new InvalidArgumentError("pingInterval must be a positive integer, greater or equal to 0");
30655
30851
  }
30656
- super();
30852
+ super({ webSocket });
30657
30853
  if (typeof connect2 !== "function") {
30658
30854
  connect2 = buildConnector({
30659
30855
  ...tls,
@@ -30665,9 +30861,13 @@ var require_client = __commonJS({
30665
30861
  ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
30666
30862
  ...connect2
30667
30863
  });
30668
- } else if (socketPath != null) {
30864
+ } else {
30669
30865
  const customConnect = connect2;
30670
- connect2 = (opts, callback) => customConnect({ ...opts, socketPath }, callback);
30866
+ connect2 = (opts, callback) => customConnect({
30867
+ ...opts,
30868
+ ...socketPath != null ? { socketPath } : null,
30869
+ ...allowH2 != null ? { allowH2 } : null
30870
+ }, callback);
30671
30871
  }
30672
30872
  this[kUrl] = util.parseOrigin(url);
30673
30873
  this[kConnector] = connect2;
@@ -30760,7 +30960,9 @@ var require_client = __commonJS({
30760
30960
  const requests = this[kQueue].splice(this[kPendingIdx]);
30761
30961
  for (let i = 0; i < requests.length; i++) {
30762
30962
  const request2 = requests[i];
30763
- util.errorRequest(this, request2, err2);
30963
+ if (request2 != null) {
30964
+ util.errorRequest(this, request2, err2);
30965
+ }
30764
30966
  }
30765
30967
  const callback = () => {
30766
30968
  if (this[kClosedResolve]) {
@@ -30785,7 +30987,9 @@ var require_client = __commonJS({
30785
30987
  const requests = client[kQueue].splice(client[kRunningIdx]);
30786
30988
  for (let i = 0; i < requests.length; i++) {
30787
30989
  const request2 = requests[i];
30788
- util.errorRequest(client, request2, err2);
30990
+ if (request2 != null) {
30991
+ util.errorRequest(client, request2, err2);
30992
+ }
30789
30993
  }
30790
30994
  assert(client[kSize] === 0);
30791
30995
  }
@@ -31296,7 +31500,7 @@ var require_pool = __commonJS({
31296
31500
  ...connect
31297
31501
  });
31298
31502
  }
31299
- super();
31503
+ super(options);
31300
31504
  this[kConnections] = connections || null;
31301
31505
  this[kUrl] = util.parseOrigin(origin);
31302
31506
  this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl, socketPath };
@@ -31378,12 +31582,14 @@ var require_balanced_pool = __commonJS({
31378
31582
  return new Pool(origin, opts);
31379
31583
  }
31380
31584
  var BalancedPool = class extends PoolBase {
31381
- constructor(upstreams = [], { factory = defaultFactory, ...opts } = {}) {
31585
+ constructor(upstreams = [], { factory = defaultFactory, connect, tls, ...opts } = {}) {
31382
31586
  if (typeof factory !== "function") {
31383
31587
  throw new InvalidArgumentError("factory must be a function.");
31384
31588
  }
31385
- super();
31386
- this[kOptions] = { ...util.deepClone(opts) };
31589
+ super(opts);
31590
+ if (connect && typeof connect !== "function") connect = { ...connect };
31591
+ if (tls && typeof tls !== "function") tls = { ...tls };
31592
+ this[kOptions] = { ...util.deepClone(opts), connect, tls };
31387
31593
  this[kOptions].interceptors = opts.interceptors ? { ...opts.interceptors } : void 0;
31388
31594
  this[kIndex] = -1;
31389
31595
  this[kCurrentWeight] = 0;
@@ -31634,7 +31840,7 @@ var require_agent = __commonJS({
31634
31840
  if (typeof maxOrigins !== "number" || Number.isNaN(maxOrigins) || maxOrigins <= 0) {
31635
31841
  throw new InvalidArgumentError("maxOrigins must be a number greater than 0");
31636
31842
  }
31637
- super();
31843
+ super(options);
31638
31844
  if (connect && typeof connect !== "function") {
31639
31845
  connect = { ...connect };
31640
31846
  }
@@ -31771,28 +31977,37 @@ var require_socks5_utils = __commonJS({
31771
31977
  }
31772
31978
  function parseIPv6(address) {
31773
31979
  const buffer = Buffer2.alloc(16);
31774
- const parts = address.split(":");
31775
- let partIndex = 0;
31776
- let bufferIndex = 0;
31777
- const doubleColonIndex = address.indexOf("::");
31980
+ let normalizedAddress = address;
31981
+ if (address.includes(".")) {
31982
+ const lastColonIndex = address.lastIndexOf(":");
31983
+ const ipv4Part = address.slice(lastColonIndex + 1);
31984
+ if (net3.isIPv4(ipv4Part)) {
31985
+ const octets = ipv4Part.split(".").map(Number);
31986
+ const high = (octets[0] << 8 | octets[1]).toString(16);
31987
+ const low = (octets[2] << 8 | octets[3]).toString(16);
31988
+ normalizedAddress = `${address.slice(0, lastColonIndex)}:${high}:${low}`;
31989
+ }
31990
+ }
31991
+ const doubleColonIndex = normalizedAddress.indexOf("::");
31778
31992
  if (doubleColonIndex !== -1) {
31779
- const nonEmptyParts = parts.filter((p) => p.length > 0).length;
31780
- const skipParts = 8 - nonEmptyParts;
31781
- for (let i = 0; i < parts.length; i++) {
31782
- if (parts[i] === "" && i === doubleColonIndex / 3) {
31783
- bufferIndex += skipParts * 2;
31784
- } else if (parts[i] !== "") {
31785
- const value = parseInt(parts[i], 16);
31786
- buffer.writeUInt16BE(value, bufferIndex);
31787
- bufferIndex += 2;
31788
- }
31993
+ const before = normalizedAddress.slice(0, doubleColonIndex);
31994
+ const after = normalizedAddress.slice(doubleColonIndex + 2);
31995
+ const beforeParts = before === "" ? [] : before.split(":");
31996
+ const afterParts = after === "" ? [] : after.split(":");
31997
+ let bufferIndex = 0;
31998
+ for (const part of beforeParts) {
31999
+ buffer.writeUInt16BE(parseInt(part, 16), bufferIndex);
32000
+ bufferIndex += 2;
32001
+ }
32002
+ bufferIndex = 16 - afterParts.length * 2;
32003
+ for (const part of afterParts) {
32004
+ buffer.writeUInt16BE(parseInt(part, 16), bufferIndex);
32005
+ bufferIndex += 2;
31789
32006
  }
31790
32007
  } else {
31791
- for (const part of parts) {
31792
- if (part === "") continue;
31793
- const value = parseInt(part, 16);
31794
- buffer.writeUInt16BE(value, partIndex * 2);
31795
- partIndex++;
32008
+ const parts = normalizedAddress.split(":");
32009
+ for (let i = 0; i < parts.length; i++) {
32010
+ buffer.writeUInt16BE(parseInt(parts[i], 16), i * 2);
31796
32011
  }
31797
32012
  }
31798
32013
  return buffer;
@@ -31898,6 +32113,7 @@ var require_socks5_client = __commonJS({
31898
32113
  var { debuglog } = require("util");
31899
32114
  var { parseAddress } = require_socks5_utils();
31900
32115
  var debug = debuglog("undici:socks5");
32116
+ var EMPTY_BUFFER = Buffer2.alloc(0);
31901
32117
  var SOCKS_VERSION = 5;
31902
32118
  var AUTH_METHODS = {
31903
32119
  NO_AUTH: 0,
@@ -31930,6 +32146,7 @@ var require_socks5_client = __commonJS({
31930
32146
  INITIAL: "initial",
31931
32147
  HANDSHAKING: "handshaking",
31932
32148
  AUTHENTICATING: "authenticating",
32149
+ AUTHENTICATED: "authenticated",
31933
32150
  CONNECTING: "connecting",
31934
32151
  CONNECTED: "connected",
31935
32152
  ERROR: "error",
@@ -31944,15 +32161,18 @@ var require_socks5_client = __commonJS({
31944
32161
  this.socket = socket;
31945
32162
  this.options = options;
31946
32163
  this.state = STATES.INITIAL;
31947
- this.buffer = Buffer2.alloc(0);
32164
+ this.buffer = EMPTY_BUFFER;
32165
+ this.onSocketData = this.onData.bind(this);
32166
+ this.onSocketError = this.onError.bind(this);
32167
+ this.onSocketClose = this.onClose.bind(this);
31948
32168
  this.authMethods = [];
31949
32169
  if (options.username && options.password) {
31950
32170
  this.authMethods.push(AUTH_METHODS.USERNAME_PASSWORD);
31951
32171
  }
31952
32172
  this.authMethods.push(AUTH_METHODS.NO_AUTH);
31953
- this.socket.on("data", this.onData.bind(this));
31954
- this.socket.on("error", this.onError.bind(this));
31955
- this.socket.on("close", this.onClose.bind(this));
32173
+ this.socket.on("data", this.onSocketData);
32174
+ this.socket.on("error", this.onSocketError);
32175
+ this.socket.on("close", this.onSocketClose);
31956
32176
  }
31957
32177
  /**
31958
32178
  * Handle incoming data from the socket
@@ -32001,6 +32221,10 @@ var require_socks5_client = __commonJS({
32001
32221
  this.socket.destroy();
32002
32222
  }
32003
32223
  }
32224
+ markAuthenticated() {
32225
+ this.state = STATES.AUTHENTICATED;
32226
+ this.emit("authenticated");
32227
+ }
32004
32228
  /**
32005
32229
  * Start the SOCKS5 handshake
32006
32230
  */
@@ -32036,7 +32260,7 @@ var require_socks5_client = __commonJS({
32036
32260
  this.buffer = this.buffer.subarray(2);
32037
32261
  debug("server selected auth method", method);
32038
32262
  if (method === AUTH_METHODS.NO_AUTH) {
32039
- this.emit("authenticated");
32263
+ this.markAuthenticated();
32040
32264
  } else if (method === AUTH_METHODS.USERNAME_PASSWORD) {
32041
32265
  this.state = STATES.AUTHENTICATING;
32042
32266
  this.sendAuthRequest();
@@ -32083,7 +32307,7 @@ var require_socks5_client = __commonJS({
32083
32307
  }
32084
32308
  this.buffer = this.buffer.subarray(2);
32085
32309
  debug("authentication successful");
32086
- this.emit("authenticated");
32310
+ this.markAuthenticated();
32087
32311
  }
32088
32312
  /**
32089
32313
  * Send CONNECT command
@@ -32091,8 +32315,11 @@ var require_socks5_client = __commonJS({
32091
32315
  * @param {number} port - Target port
32092
32316
  */
32093
32317
  connect(address, port) {
32094
- if (this.state === STATES.CONNECTED) {
32095
- throw new InvalidArgumentError("Already connected");
32318
+ if (this.state === STATES.CONNECTING || this.state === STATES.CONNECTED) {
32319
+ throw new InvalidArgumentError("Connection already in progress");
32320
+ }
32321
+ if (this.state !== STATES.AUTHENTICATED) {
32322
+ throw new InvalidArgumentError("Client must be authenticated before CONNECT");
32096
32323
  }
32097
32324
  debug("connecting to", address, port);
32098
32325
  this.state = STATES.CONNECTING;
@@ -32166,8 +32393,9 @@ var require_socks5_client = __commonJS({
32166
32393
  offset += 16;
32167
32394
  }
32168
32395
  const boundPort = this.buffer.readUInt16BE(offset);
32169
- this.buffer = this.buffer.subarray(responseLength);
32396
+ this.buffer = EMPTY_BUFFER;
32170
32397
  this.state = STATES.CONNECTED;
32398
+ this.socket.removeListener("data", this.onSocketData);
32171
32399
  debug("connected, bound address:", boundAddress, "port:", boundPort);
32172
32400
  this.emit("connected", { address: boundAddress, port: boundPort });
32173
32401
  }
@@ -32212,12 +32440,11 @@ var require_socks5_client = __commonJS({
32212
32440
  var require_socks5_proxy_agent = __commonJS({
32213
32441
  "node_modules/undici/lib/dispatcher/socks5-proxy-agent.js"(exports2, module2) {
32214
32442
  "use strict";
32215
- var net3 = require("net");
32216
32443
  var { URL: URL6 } = require("url");
32217
32444
  var tls;
32218
32445
  var DispatcherBase = require_dispatcher_base();
32219
32446
  var { InvalidArgumentError } = require_errors();
32220
- var { Socks5Client } = require_socks5_client();
32447
+ var { Socks5Client, STATES } = require_socks5_client();
32221
32448
  var { kDispatch, kClose, kDestroy } = require_symbols();
32222
32449
  var Pool = require_pool();
32223
32450
  var buildConnector = require_connect();
@@ -32226,8 +32453,10 @@ var require_socks5_proxy_agent = __commonJS({
32226
32453
  var kProxyUrl = /* @__PURE__ */ Symbol("proxy url");
32227
32454
  var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
32228
32455
  var kProxyAuth = /* @__PURE__ */ Symbol("proxy auth");
32229
- var kPool = /* @__PURE__ */ Symbol("pool");
32456
+ var kProxyProtocol = /* @__PURE__ */ Symbol("proxy protocol");
32457
+ var kPools = /* @__PURE__ */ Symbol("pools");
32230
32458
  var kConnector = /* @__PURE__ */ Symbol("connector");
32459
+ var kRequestTls = /* @__PURE__ */ Symbol("request tls settings");
32231
32460
  var experimentalWarningEmitted = false;
32232
32461
  var Socks5ProxyAgent = class extends DispatcherBase {
32233
32462
  constructor(proxyUrl, options = {}) {
@@ -32248,6 +32477,8 @@ var require_socks5_proxy_agent = __commonJS({
32248
32477
  }
32249
32478
  this[kProxyUrl] = url;
32250
32479
  this[kProxyHeaders] = options.headers || {};
32480
+ this[kProxyProtocol] = options.proxyTls ? "https:" : "http:";
32481
+ this[kRequestTls] = options.requestTls;
32251
32482
  this[kProxyAuth] = {
32252
32483
  username: options.username || (url.username ? decodeURIComponent(url.username) : null),
32253
32484
  password: options.password || (url.password ? decodeURIComponent(url.password) : null)
@@ -32256,7 +32487,7 @@ var require_socks5_proxy_agent = __commonJS({
32256
32487
  ...options.proxyTls,
32257
32488
  servername: options.proxyTls?.servername || url.hostname
32258
32489
  });
32259
- this[kPool] = null;
32490
+ this[kPools] = /* @__PURE__ */ new Map();
32260
32491
  }
32261
32492
  /**
32262
32493
  * Create a SOCKS5 connection to the proxy
@@ -32266,20 +32497,18 @@ var require_socks5_proxy_agent = __commonJS({
32266
32497
  const proxyPort = parseInt(this[kProxyUrl].port) || 1080;
32267
32498
  debug("creating SOCKS5 connection to", proxyHost, proxyPort);
32268
32499
  const socket = await new Promise((resolve2, reject) => {
32269
- const onConnect = () => {
32270
- socket2.removeListener("error", onError);
32271
- resolve2(socket2);
32272
- };
32273
- const onError = (err2) => {
32274
- socket2.removeListener("connect", onConnect);
32275
- reject(err2);
32276
- };
32277
- const socket2 = net3.connect({
32500
+ this[kConnector]({
32501
+ hostname: proxyHost,
32278
32502
  host: proxyHost,
32279
- port: proxyPort
32503
+ port: proxyPort,
32504
+ protocol: this[kProxyProtocol]
32505
+ }, (err2, socket2) => {
32506
+ if (err2) {
32507
+ reject(err2);
32508
+ } else {
32509
+ resolve2(socket2);
32510
+ }
32280
32511
  });
32281
- socket2.once("connect", onConnect);
32282
- socket2.once("error", onError);
32283
32512
  });
32284
32513
  const socks5Client = new Socks5Client(socket, this[kProxyAuth]);
32285
32514
  socks5Client.on("error", (err2) => {
@@ -32301,7 +32530,7 @@ var require_socks5_proxy_agent = __commonJS({
32301
32530
  socks5Client.removeListener("authenticated", onAuthenticated);
32302
32531
  reject(err2);
32303
32532
  };
32304
- if (socks5Client.state === "authenticated") {
32533
+ if (socks5Client.state === STATES.AUTHENTICATED) {
32305
32534
  clearTimeout(timeout);
32306
32535
  resolve2();
32307
32536
  } else {
@@ -32333,12 +32562,14 @@ var require_socks5_proxy_agent = __commonJS({
32333
32562
  /**
32334
32563
  * Dispatch a request through the SOCKS5 proxy
32335
32564
  */
32336
- async [kDispatch](opts, handler) {
32565
+ [kDispatch](opts, handler) {
32337
32566
  const { origin } = opts;
32338
32567
  debug("dispatching request to", origin, "via SOCKS5");
32339
32568
  try {
32340
- if (!this[kPool] || this[kPool].destroyed || this[kPool].closed) {
32341
- this[kPool] = new Pool(origin, {
32569
+ const originKey = String(origin);
32570
+ let pool = this[kPools].get(originKey);
32571
+ if (!pool || pool.destroyed || pool.closed) {
32572
+ pool = new Pool(origin, {
32342
32573
  pipelining: opts.pipelining,
32343
32574
  connections: opts.connections,
32344
32575
  connect: async (connectOpts, callback) => {
@@ -32355,9 +32586,9 @@ var require_socks5_proxy_agent = __commonJS({
32355
32586
  }
32356
32587
  debug("upgrading to TLS");
32357
32588
  finalSocket = tls.connect({
32589
+ ...this[kRequestTls],
32358
32590
  socket,
32359
- servername: targetHost,
32360
- ...connectOpts.tls || {}
32591
+ servername: this[kRequestTls]?.servername || targetHost
32361
32592
  });
32362
32593
  await new Promise((resolve2, reject) => {
32363
32594
  finalSocket.once("secureConnect", resolve2);
@@ -32371,26 +32602,37 @@ var require_socks5_proxy_agent = __commonJS({
32371
32602
  }
32372
32603
  }
32373
32604
  });
32605
+ this[kPools].set(originKey, pool);
32374
32606
  }
32375
- return this[kPool][kDispatch](opts, handler);
32607
+ return pool[kDispatch](opts, handler);
32376
32608
  } catch (err2) {
32377
32609
  debug("dispatch error:", err2);
32378
- if (typeof handler.onError === "function") {
32610
+ if (typeof handler.onResponseError === "function") {
32611
+ handler.onResponseError(null, err2);
32612
+ return false;
32613
+ } else if (typeof handler.onError === "function") {
32379
32614
  handler.onError(err2);
32615
+ return false;
32380
32616
  } else {
32381
32617
  throw err2;
32382
32618
  }
32383
32619
  }
32384
32620
  }
32385
32621
  async [kClose]() {
32386
- if (this[kPool]) {
32387
- await this[kPool].close();
32622
+ const closePromises = [];
32623
+ for (const pool of this[kPools].values()) {
32624
+ closePromises.push(pool.close());
32388
32625
  }
32626
+ this[kPools].clear();
32627
+ await Promise.all(closePromises);
32389
32628
  }
32390
32629
  async [kDestroy](err2) {
32391
- if (this[kPool]) {
32392
- await this[kPool].destroy(err2);
32630
+ const destroyPromises = [];
32631
+ for (const pool of this[kPools].values()) {
32632
+ destroyPromises.push(pool.destroy(err2));
32393
32633
  }
32634
+ this[kPools].clear();
32635
+ await Promise.all(destroyPromises);
32394
32636
  }
32395
32637
  };
32396
32638
  module2.exports = Socks5ProxyAgent;
@@ -32515,7 +32757,8 @@ var require_proxy_agent = __commonJS({
32515
32757
  factory: agentFactory,
32516
32758
  username: opts.username || username,
32517
32759
  password: opts.password || password,
32518
- proxyTls: opts.proxyTls
32760
+ proxyTls: opts.proxyTls,
32761
+ requestTls: opts.requestTls
32519
32762
  });
32520
32763
  }
32521
32764
  if (!this[kTunnelProxy] && protocol2 === "http:" && this[kProxy].protocol === "http:") {
@@ -32793,6 +33036,23 @@ var require_retry_handler = __commonJS({
32793
33036
  const retryTime = new Date(retryAfter).getTime();
32794
33037
  return isNaN(retryTime) ? 0 : retryTime - Date.now();
32795
33038
  }
33039
+ function validatePartialResponseContentLength(headers, range, statusCode, retryCount) {
33040
+ const contentLength = headers["content-length"];
33041
+ if (contentLength == null) {
33042
+ return;
33043
+ }
33044
+ if (!Number.isFinite(range.start) || !Number.isFinite(range.end)) {
33045
+ return;
33046
+ }
33047
+ const length = Number(contentLength);
33048
+ const expectedLength = range.end - range.start + 1;
33049
+ if (!Number.isFinite(length) || length !== expectedLength) {
33050
+ throw new RequestRetryError("Content-Length mismatch", statusCode, {
33051
+ headers,
33052
+ data: { count: retryCount }
33053
+ });
33054
+ }
33055
+ }
32796
33056
  var RetryHandler = class _RetryHandler {
32797
33057
  constructor(opts, { dispatch, handler }) {
32798
33058
  const { retryOptions, ...dispatchOpts } = opts;
@@ -32851,8 +33111,13 @@ var require_retry_handler = __commonJS({
32851
33111
  onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err2) {
32852
33112
  if (this.retryOpts.throwOnError) {
32853
33113
  if (this.retryOpts.statusCodes.includes(statusCode) === false) {
32854
- this.headersSent = true;
32855
- this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33114
+ if (this.headersSent) {
33115
+ this.handler.onResponseError?.(controller, err2);
33116
+ } else {
33117
+ this.headersSent = true;
33118
+ this.checkpointResponseEnd(headers);
33119
+ this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33120
+ }
32856
33121
  } else {
32857
33122
  this.error = err2;
32858
33123
  }
@@ -32860,13 +33125,19 @@ var require_retry_handler = __commonJS({
32860
33125
  }
32861
33126
  if (isDisturbed(this.opts.body)) {
32862
33127
  this.headersSent = true;
33128
+ this.checkpointResponseEnd(headers);
32863
33129
  this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
32864
33130
  return;
32865
33131
  }
32866
33132
  function shouldRetry(passedErr) {
32867
33133
  if (passedErr) {
32868
- this.headersSent = true;
32869
- this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33134
+ if (this.headersSent) {
33135
+ this.handler.onResponseError?.(controller, passedErr);
33136
+ } else {
33137
+ this.headersSent = true;
33138
+ this.checkpointResponseEnd(headers);
33139
+ this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
33140
+ }
32870
33141
  controller.resume();
32871
33142
  return;
32872
33143
  }
@@ -32883,6 +33154,17 @@ var require_retry_handler = __commonJS({
32883
33154
  shouldRetry.bind(this)
32884
33155
  );
32885
33156
  }
33157
+ checkpointResponseEnd(headers) {
33158
+ if (this.end == null && this.opts.method !== "HEAD") {
33159
+ const contentLength = headers["content-length"];
33160
+ this.end = contentLength != null ? Number(contentLength) - 1 : null;
33161
+ assert(
33162
+ this.end == null || Number.isFinite(this.end),
33163
+ "invalid content-length"
33164
+ );
33165
+ this.resume = this.end != null;
33166
+ }
33167
+ }
32886
33168
  onRequestStart(controller, context) {
32887
33169
  if (!this.headersSent) {
32888
33170
  this.handler.onRequestStart?.(controller, context);
@@ -32961,9 +33243,14 @@ var require_retry_handler = __commonJS({
32961
33243
  data: { count: this.retryCount }
32962
33244
  });
32963
33245
  }
33246
+ validatePartialResponseContentLength(headers, contentRange, statusCode, this.retryCount);
32964
33247
  const { start, size, end = size ? size - 1 : null } = contentRange;
32965
- assert(this.start === start, "content-range mismatch");
32966
- assert(this.end == null || this.end === end, "content-range mismatch");
33248
+ if (this.start !== start || this.end != null && this.end !== end) {
33249
+ throw new RequestRetryError("Content-Range mismatch", statusCode, {
33250
+ headers,
33251
+ data: { count: this.retryCount }
33252
+ });
33253
+ }
32967
33254
  return;
32968
33255
  }
32969
33256
  if (this.end == null) {
@@ -32979,6 +33266,7 @@ var require_retry_handler = __commonJS({
32979
33266
  );
32980
33267
  return;
32981
33268
  }
33269
+ validatePartialResponseContentLength(headers, range, statusCode, this.retryCount);
32982
33270
  const { start, size, end = size ? size - 1 : null } = range;
32983
33271
  assert(
32984
33272
  start != null && Number.isFinite(start),
@@ -33055,7 +33343,7 @@ var require_retry_handler = __commonJS({
33055
33343
  }
33056
33344
  }
33057
33345
  onResponseError(controller, err2) {
33058
- if (controller?.aborted || isDisturbed(this.opts.body)) {
33346
+ if (controller?.aborted || isDisturbed(this.opts.body) || this.headersSent && !this.resume) {
33059
33347
  this.handler.onResponseError?.(controller, err2);
33060
33348
  return;
33061
33349
  }
@@ -33136,7 +33424,7 @@ var require_h2c_client = __commonJS({
33136
33424
  "h2c-client: Only h2c protocol is supported"
33137
33425
  );
33138
33426
  }
33139
- const { connect, maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {};
33427
+ const { maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {};
33140
33428
  let defaultMaxConcurrentStreams = 100;
33141
33429
  let defaultPipelining = 100;
33142
33430
  if (maxConcurrentStreams != null && Number.isInteger(maxConcurrentStreams) && maxConcurrentStreams > 0) {
@@ -33586,7 +33874,7 @@ var require_api_request = __commonJS({
33586
33874
  if (typeof callback !== "function") {
33587
33875
  throw new InvalidArgumentError("invalid callback");
33588
33876
  }
33589
- if (highWaterMark && (typeof highWaterMark !== "number" || highWaterMark < 0)) {
33877
+ if (highWaterMark != null && (!Number.isFinite(highWaterMark) || highWaterMark < 0)) {
33590
33878
  throw new InvalidArgumentError("invalid highWaterMark");
33591
33879
  }
33592
33880
  if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
@@ -35025,13 +35313,13 @@ var require_mock_call_history = __commonJS({
35025
35313
  "use strict";
35026
35314
  var { kMockCallHistoryAddLog } = require_mock_symbols();
35027
35315
  var { InvalidArgumentError } = require_errors();
35028
- function handleFilterCallsWithOptions(criteria, options, handler, store) {
35316
+ function handleFilterCallsWithOptions(criteria, options, handler, store, allLogs) {
35029
35317
  switch (options.operator) {
35030
35318
  case "OR":
35031
- store.push(...handler(criteria));
35319
+ store.push(...handler(criteria, allLogs));
35032
35320
  return store;
35033
35321
  case "AND":
35034
- return handler.call({ logs: store }, criteria);
35322
+ return handler(criteria, store);
35035
35323
  default:
35036
35324
  throw new InvalidArgumentError("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");
35037
35325
  }
@@ -35050,14 +35338,14 @@ var require_mock_call_history = __commonJS({
35050
35338
  return finalOptions;
35051
35339
  }
35052
35340
  function makeFilterCalls(parameterName) {
35053
- return (parameterValue) => {
35341
+ return (parameterValue, logs) => {
35054
35342
  if (typeof parameterValue === "string" || parameterValue == null) {
35055
- return this.logs.filter((log) => {
35343
+ return logs.filter((log) => {
35056
35344
  return log[parameterName] === parameterValue;
35057
35345
  });
35058
35346
  }
35059
35347
  if (parameterValue instanceof RegExp) {
35060
- return this.logs.filter((log) => {
35348
+ return logs.filter((log) => {
35061
35349
  return parameterValue.test(log[parameterName]);
35062
35350
  });
35063
35351
  }
@@ -35162,30 +35450,30 @@ var require_mock_call_history = __commonJS({
35162
35450
  return this.logs;
35163
35451
  }
35164
35452
  const finalOptions = { operator: "OR", ...buildAndValidateFilterCallsOptions(options) };
35165
- let maybeDuplicatedLogsFiltered = [];
35453
+ let maybeDuplicatedLogsFiltered = finalOptions.operator === "AND" ? this.logs : [];
35166
35454
  if ("protocol" in criteria) {
35167
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered);
35455
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered, this.logs);
35168
35456
  }
35169
35457
  if ("host" in criteria) {
35170
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered);
35458
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered, this.logs);
35171
35459
  }
35172
35460
  if ("port" in criteria) {
35173
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered);
35461
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered, this.logs);
35174
35462
  }
35175
35463
  if ("origin" in criteria) {
35176
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered);
35464
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered, this.logs);
35177
35465
  }
35178
35466
  if ("path" in criteria) {
35179
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered);
35467
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered, this.logs);
35180
35468
  }
35181
35469
  if ("hash" in criteria) {
35182
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered);
35470
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered, this.logs);
35183
35471
  }
35184
35472
  if ("fullUrl" in criteria) {
35185
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered);
35473
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered, this.logs);
35186
35474
  }
35187
35475
  if ("method" in criteria) {
35188
- maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered);
35476
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered, this.logs);
35189
35477
  }
35190
35478
  const uniqLogsFiltered = [...new Set(maybeDuplicatedLogsFiltered)];
35191
35479
  return uniqLogsFiltered;
@@ -36258,7 +36546,8 @@ var require_snapshot_agent = __commonJS({
36258
36546
  var require_global2 = __commonJS({
36259
36547
  "node_modules/undici/lib/global.js"(exports2, module2) {
36260
36548
  "use strict";
36261
- var globalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
36549
+ var globalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.2");
36550
+ var legacyGlobalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
36262
36551
  var { InvalidArgumentError } = require_errors();
36263
36552
  var Agent = require_agent();
36264
36553
  if (getGlobalDispatcher() === void 0) {
@@ -36274,9 +36563,15 @@ var require_global2 = __commonJS({
36274
36563
  enumerable: false,
36275
36564
  configurable: false
36276
36565
  });
36566
+ Object.defineProperty(globalThis, legacyGlobalDispatcher, {
36567
+ value: agent,
36568
+ writable: true,
36569
+ enumerable: false,
36570
+ configurable: false
36571
+ });
36277
36572
  }
36278
36573
  function getGlobalDispatcher() {
36279
- return globalThis[globalDispatcher];
36574
+ return globalThis[legacyGlobalDispatcher];
36280
36575
  }
36281
36576
  var installedExports = (
36282
36577
  /** @type {const} */
@@ -36655,7 +36950,6 @@ var require_dump = __commonJS({
36655
36950
  #maxSize = 1024 * 1024;
36656
36951
  #dumped = false;
36657
36952
  #size = 0;
36658
- #controller = null;
36659
36953
  aborted = false;
36660
36954
  reason = false;
36661
36955
  constructor({ maxSize, signal }, handler) {
@@ -36671,7 +36965,6 @@ var require_dump = __commonJS({
36671
36965
  }
36672
36966
  onRequestStart(controller, context) {
36673
36967
  controller.abort = this.#abort.bind(this);
36674
- this.#controller = controller;
36675
36968
  return super.onRequestStart(controller, context);
36676
36969
  }
36677
36970
  onResponseStart(controller, statusCode, headers, statusMessage) {
@@ -36687,33 +36980,26 @@ var require_dump = __commonJS({
36687
36980
  return super.onResponseStart(controller, statusCode, headers, statusMessage);
36688
36981
  }
36689
36982
  onResponseError(controller, err2) {
36690
- if (this.#dumped) {
36691
- return;
36692
- }
36693
- err2 = this.#controller?.reason ?? err2;
36694
- super.onResponseError(controller, err2);
36983
+ super.onResponseError(controller, this.aborted === true ? this.reason : err2);
36695
36984
  }
36696
36985
  onResponseData(controller, chunk2) {
36697
36986
  this.#size = this.#size + chunk2.length;
36698
- if (this.#size >= this.#maxSize) {
36987
+ if (this.#size > this.#maxSize) {
36988
+ throw new RequestAbortedError(
36989
+ `Response size (${this.#size}) larger than maxSize (${this.#maxSize})`
36990
+ );
36991
+ }
36992
+ if (this.#size === this.#maxSize) {
36699
36993
  this.#dumped = true;
36700
- if (this.aborted === true) {
36701
- super.onResponseError(controller, this.reason);
36702
- } else {
36703
- super.onResponseEnd(controller, {});
36704
- }
36705
36994
  }
36706
36995
  return true;
36707
36996
  }
36708
36997
  onResponseEnd(controller, trailers) {
36709
- if (this.#dumped) {
36710
- return;
36711
- }
36712
- if (this.#controller.aborted === true) {
36998
+ if (this.aborted === true) {
36713
36999
  super.onResponseError(controller, this.reason);
36714
37000
  return;
36715
37001
  }
36716
- super.onResponseEnd(controller, trailers);
37002
+ super.onResponseEnd(controller, this.#dumped ? {} : trailers);
36717
37003
  }
36718
37004
  };
36719
37005
  function createDumpInterceptor({ maxSize: defaultMaxSize } = {
@@ -37177,15 +37463,127 @@ var require_cache = __commonJS({
37177
37463
  var {
37178
37464
  safeHTTPMethods,
37179
37465
  pathHasQueryOrFragment,
37180
- hasSafeIterator
37466
+ hasSafeIterator,
37467
+ isValidHTTPToken
37181
37468
  } = require_util();
37182
37469
  var { serializePathWithQuery } = require_util();
37470
+ var MAX_DELTA_SECONDS = 2147483647;
37471
+ var RESTRICTIVE_DIRECTIVE_NAMES = ["no-store", "private", "no-cache"];
37472
+ var kInvalidCacheControlDirectives = /* @__PURE__ */ Symbol("invalid cache-control directives");
37473
+ function trimOWS(value) {
37474
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
37475
+ }
37476
+ function arrayIncludes(array, value) {
37477
+ for (let i = 0; i < array.length; i++) {
37478
+ if (array[i] === value) {
37479
+ return true;
37480
+ }
37481
+ }
37482
+ return false;
37483
+ }
37484
+ function trimOWSStart(value) {
37485
+ return value.replace(/^[\t ]+/, "");
37486
+ }
37487
+ function trimOWSEnd(value) {
37488
+ return value.replace(/[\t ]+$/, "");
37489
+ }
37490
+ function findUnescapedQuote(value, start) {
37491
+ let escaped = false;
37492
+ for (let i = start; i < value.length; i++) {
37493
+ if (escaped) {
37494
+ escaped = false;
37495
+ } else if (value[i] === "\\") {
37496
+ escaped = true;
37497
+ } else if (value[i] === '"') {
37498
+ return i;
37499
+ }
37500
+ }
37501
+ return -1;
37502
+ }
37503
+ function splitCacheControlHeaderValue(value) {
37504
+ const directives = [];
37505
+ let start = 0;
37506
+ let quoteStart = -1;
37507
+ let inQuote = false;
37508
+ let escaped = false;
37509
+ for (let i = 0; i < value.length; i++) {
37510
+ if (inQuote) {
37511
+ if (escaped) {
37512
+ escaped = false;
37513
+ } else if (value[i] === "\\") {
37514
+ escaped = true;
37515
+ } else if (value[i] === '"') {
37516
+ inQuote = false;
37517
+ quoteStart = -1;
37518
+ }
37519
+ } else if (value[i] === '"') {
37520
+ inQuote = true;
37521
+ quoteStart = i;
37522
+ } else if (value[i] === ",") {
37523
+ directives.push({ value: value.substring(start, i), fromMalformedQuote: false });
37524
+ start = i + 1;
37525
+ }
37526
+ }
37527
+ if (!inQuote) {
37528
+ directives.push({ value: value.substring(start), fromMalformedQuote: false });
37529
+ return directives;
37530
+ }
37531
+ const tail = value.substring(start);
37532
+ const quoteOffset = quoteStart - start;
37533
+ let tailStart = 0;
37534
+ for (let i = 0; i < tail.length; i++) {
37535
+ if (tail[i] === ",") {
37536
+ directives.push({
37537
+ value: tail.substring(tailStart, i),
37538
+ fromMalformedQuote: tailStart > quoteOffset
37539
+ });
37540
+ tailStart = i + 1;
37541
+ }
37542
+ }
37543
+ directives.push({
37544
+ value: tail.substring(tailStart),
37545
+ fromMalformedQuote: tailStart > quoteOffset
37546
+ });
37547
+ return directives;
37548
+ }
37549
+ function markInvalidCacheControlDirective(directives, key) {
37550
+ let invalidDirectives = directives[kInvalidCacheControlDirectives];
37551
+ if (invalidDirectives === void 0) {
37552
+ invalidDirectives = /* @__PURE__ */ new Set();
37553
+ Object.defineProperty(directives, kInvalidCacheControlDirectives, {
37554
+ value: invalidDirectives
37555
+ });
37556
+ }
37557
+ invalidDirectives.add(key);
37558
+ }
37559
+ function hasInvalidCacheControlDirective(directives, key) {
37560
+ return directives[kInvalidCacheControlDirectives]?.has(key) === true;
37561
+ }
37562
+ function getMalformedRestrictiveDirectiveName(key) {
37563
+ for (const directiveName of RESTRICTIVE_DIRECTIVE_NAMES) {
37564
+ if (key.startsWith(directiveName) && key.length > directiveName.length && !isValidHTTPToken(key[directiveName.length])) {
37565
+ return directiveName;
37566
+ }
37567
+ }
37568
+ let tokenOnlyKey = "";
37569
+ let hasInvalidTokenChar = false;
37570
+ for (let i = 0; i < key.length; i++) {
37571
+ if (isValidHTTPToken(key[i])) {
37572
+ tokenOnlyKey += key[i];
37573
+ } else {
37574
+ hasInvalidTokenChar = true;
37575
+ }
37576
+ }
37577
+ if (hasInvalidTokenChar && arrayIncludes(RESTRICTIVE_DIRECTIVE_NAMES, tokenOnlyKey)) {
37578
+ return tokenOnlyKey;
37579
+ }
37580
+ }
37183
37581
  function makeCacheKey(opts) {
37184
37582
  if (!opts.origin) {
37185
37583
  throw new Error("opts.origin is undefined");
37186
37584
  }
37187
37585
  let fullPath = opts.path || "/";
37188
- if (opts.query && !pathHasQueryOrFragment(opts.path)) {
37586
+ if (opts.query && !pathHasQueryOrFragment(fullPath)) {
37189
37587
  fullPath = serializePathWithQuery(fullPath, opts.query);
37190
37588
  }
37191
37589
  return {
@@ -37195,6 +37593,18 @@ var require_cache = __commonJS({
37195
37593
  headers: opts.headers
37196
37594
  };
37197
37595
  }
37596
+ function appendHeader(headers, key, val) {
37597
+ const headerName = key.toLowerCase();
37598
+ const current = headers[headerName];
37599
+ const values = Array.isArray(val) ? val : [val];
37600
+ if (current === void 0) {
37601
+ headers[headerName] = Array.isArray(val) ? val.slice() : val;
37602
+ } else if (Array.isArray(current)) {
37603
+ current.push(...values);
37604
+ } else {
37605
+ headers[headerName] = [current, ...values];
37606
+ }
37607
+ }
37198
37608
  function normalizeHeaders(opts) {
37199
37609
  let headers;
37200
37610
  if (opts.headers == null) {
@@ -37210,11 +37620,11 @@ var require_cache = __commonJS({
37210
37620
  if (typeof key !== "string" || typeof val !== "string") {
37211
37621
  throw new Error("opts.headers is not a valid header map");
37212
37622
  }
37213
- headers[key.toLowerCase()] = val;
37623
+ appendHeader(headers, key, val);
37214
37624
  }
37215
37625
  } else {
37216
37626
  for (const key of Object.keys(opts.headers)) {
37217
- headers[key.toLowerCase()] = opts.headers[key];
37627
+ appendHeader(headers, key, opts.headers[key]);
37218
37628
  }
37219
37629
  }
37220
37630
  } else {
@@ -37259,25 +37669,32 @@ var require_cache = __commonJS({
37259
37669
  }
37260
37670
  function parseCacheControlHeader(header) {
37261
37671
  const output = {};
37262
- let directives;
37263
- if (Array.isArray(header)) {
37264
- directives = [];
37265
- for (const directive of header) {
37266
- directives.push(...directive.split(","));
37267
- }
37268
- } else {
37269
- directives = header.split(",");
37270
- }
37672
+ const invalidNumericDirectives = /* @__PURE__ */ new Set();
37673
+ const invalidNoArgumentDirectives = /* @__PURE__ */ new Set();
37674
+ const directives = splitCacheControlHeaderValue(Array.isArray(header) ? header.join(",") : header);
37271
37675
  for (let i = 0; i < directives.length; i++) {
37272
- const directive = directives[i].toLowerCase();
37676
+ const directiveRecord = directives[i];
37677
+ const directive = directiveRecord.value.toLowerCase();
37678
+ const fromMalformedQuote = directiveRecord.fromMalformedQuote;
37273
37679
  const keyValueDelimiter = directive.indexOf("=");
37274
37680
  let key;
37275
37681
  let value;
37682
+ let keyHasTrailingWhitespace = false;
37683
+ let valueHasLeadingWhitespace = false;
37276
37684
  if (keyValueDelimiter !== -1) {
37277
- key = directive.substring(0, keyValueDelimiter).trimStart();
37278
- value = directive.substring(keyValueDelimiter + 1);
37685
+ const rawKey = directive.substring(0, keyValueDelimiter);
37686
+ const rawValue = directive.substring(keyValueDelimiter + 1);
37687
+ keyHasTrailingWhitespace = trimOWSEnd(rawKey) !== rawKey;
37688
+ valueHasLeadingWhitespace = trimOWSStart(rawValue) !== rawValue;
37689
+ key = trimOWS(rawKey);
37690
+ value = trimOWSStart(rawValue);
37279
37691
  } else {
37280
- key = directive.trim();
37692
+ key = trimOWS(directive);
37693
+ }
37694
+ const malformedRestrictiveDirectiveName = getMalformedRestrictiveDirectiveName(key);
37695
+ if (malformedRestrictiveDirectiveName !== void 0) {
37696
+ output[malformedRestrictiveDirectiveName] = true;
37697
+ continue;
37281
37698
  }
37282
37699
  switch (key) {
37283
37700
  case "min-fresh":
@@ -37286,45 +37703,85 @@ var require_cache = __commonJS({
37286
37703
  case "s-maxage":
37287
37704
  case "stale-while-revalidate":
37288
37705
  case "stale-if-error": {
37289
- if (value === void 0 || value[0] === " ") {
37706
+ if (fromMalformedQuote || invalidNumericDirectives.has(key)) {
37707
+ continue;
37708
+ }
37709
+ if (value === void 0 || keyHasTrailingWhitespace || valueHasLeadingWhitespace) {
37710
+ delete output[key];
37711
+ invalidNumericDirectives.add(key);
37712
+ markInvalidCacheControlDirective(output, key);
37290
37713
  continue;
37291
37714
  }
37292
37715
  if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') {
37293
37716
  value = value.substring(1, value.length - 1);
37294
37717
  }
37295
- const parsedValue = parseInt(value, 10);
37296
- if (parsedValue !== parsedValue) {
37718
+ if (!/^[0-9]+$/.test(value)) {
37719
+ delete output[key];
37720
+ invalidNumericDirectives.add(key);
37721
+ markInvalidCacheControlDirective(output, key);
37297
37722
  continue;
37298
37723
  }
37299
- if (key === "max-age" && key in output && output[key] >= parsedValue) {
37300
- continue;
37724
+ const parsedValue = Math.min(parseInt(value, 10), MAX_DELTA_SECONDS);
37725
+ if (key === "min-fresh") {
37726
+ if (!(key in output) || output[key] < parsedValue) {
37727
+ output[key] = parsedValue;
37728
+ }
37729
+ } else if (!(key in output) || output[key] > parsedValue) {
37730
+ output[key] = parsedValue;
37301
37731
  }
37302
- output[key] = parsedValue;
37303
37732
  break;
37304
37733
  }
37305
37734
  case "private":
37306
37735
  case "no-cache": {
37736
+ if (fromMalformedQuote) {
37737
+ output[key] = true;
37738
+ break;
37739
+ }
37740
+ if (value !== void 0 && value.length === 0) {
37741
+ output[key] = true;
37742
+ break;
37743
+ }
37307
37744
  if (value) {
37308
37745
  if (value[0] === '"') {
37309
- const headers = [value.substring(1)];
37310
- let foundEndingQuote = value[value.length - 1] === '"';
37311
- if (!foundEndingQuote) {
37746
+ value = trimOWSEnd(value);
37747
+ let fieldList = "";
37748
+ let lastQuotedPart = i;
37749
+ let foundEndingQuote = false;
37750
+ const closingQuote = findUnescapedQuote(value, 1);
37751
+ if (closingQuote !== -1) {
37752
+ fieldList = value.substring(1, closingQuote);
37753
+ foundEndingQuote = true;
37754
+ } else {
37755
+ const fieldListParts = [value.substring(1)];
37312
37756
  for (let j = i + 1; j < directives.length; j++) {
37313
- const nextPart = directives[j];
37314
- const nextPartLength = nextPart.length;
37315
- headers.push(nextPart.trim());
37316
- if (nextPartLength !== 0 && nextPart[nextPartLength - 1] === '"') {
37757
+ const nextPart = trimOWS(directives[j].value);
37758
+ const closingQuote2 = findUnescapedQuote(nextPart, 0);
37759
+ lastQuotedPart = j;
37760
+ if (closingQuote2 !== -1) {
37761
+ fieldListParts.push(nextPart.substring(0, closingQuote2));
37317
37762
  foundEndingQuote = true;
37318
37763
  break;
37319
37764
  }
37765
+ fieldListParts.push(nextPart);
37320
37766
  }
37767
+ fieldList = fieldListParts.join(",");
37321
37768
  }
37322
- if (foundEndingQuote) {
37323
- let lastHeader = headers[headers.length - 1];
37324
- if (lastHeader[lastHeader.length - 1] === '"') {
37325
- lastHeader = lastHeader.substring(0, lastHeader.length - 1);
37326
- headers[headers.length - 1] = lastHeader;
37769
+ if (!foundEndingQuote) {
37770
+ output[key] = true;
37771
+ break;
37772
+ }
37773
+ i = lastQuotedPart;
37774
+ const headers = fieldList.split(",");
37775
+ let validFieldNames = true;
37776
+ for (let j = 0; j < headers.length; j++) {
37777
+ headers[j] = trimOWS(headers[j]);
37778
+ if (!isValidHTTPToken(headers[j])) {
37779
+ validFieldNames = false;
37327
37780
  }
37781
+ }
37782
+ if (!validFieldNames) {
37783
+ output[key] = true;
37784
+ } else if (output[key] !== true) {
37328
37785
  if (key in output) {
37329
37786
  output[key] = output[key].concat(headers);
37330
37787
  } else {
@@ -37332,10 +37789,15 @@ var require_cache = __commonJS({
37332
37789
  }
37333
37790
  }
37334
37791
  } else {
37335
- if (key in output) {
37336
- output[key] = output[key].concat(value);
37337
- } else {
37338
- output[key] = [value];
37792
+ const fieldName = trimOWS(value);
37793
+ if (!isValidHTTPToken(fieldName)) {
37794
+ output[key] = true;
37795
+ } else if (output[key] !== true) {
37796
+ if (key in output) {
37797
+ output[key] = output[key].concat(fieldName);
37798
+ } else {
37799
+ output[key] = [fieldName];
37800
+ }
37339
37801
  }
37340
37802
  }
37341
37803
  break;
@@ -37343,39 +37805,76 @@ var require_cache = __commonJS({
37343
37805
  }
37344
37806
  // eslint-disable-next-line no-fallthrough
37345
37807
  case "public":
37346
- case "no-store":
37347
37808
  case "must-revalidate":
37348
37809
  case "proxy-revalidate":
37349
37810
  case "immutable":
37350
37811
  case "no-transform":
37351
37812
  case "must-understand":
37352
37813
  case "only-if-cached":
37353
- if (value) {
37814
+ if (fromMalformedQuote || invalidNoArgumentDirectives.has(key)) {
37815
+ continue;
37816
+ }
37817
+ if (value !== void 0) {
37818
+ delete output[key];
37819
+ invalidNoArgumentDirectives.add(key);
37354
37820
  continue;
37355
37821
  }
37356
37822
  output[key] = true;
37357
37823
  break;
37824
+ case "no-store":
37825
+ output[key] = true;
37826
+ break;
37358
37827
  default:
37359
37828
  continue;
37360
37829
  }
37361
37830
  }
37362
37831
  return output;
37363
37832
  }
37833
+ function splitVaryHeader(varyHeader) {
37834
+ const values = Array.isArray(varyHeader) ? varyHeader : [varyHeader];
37835
+ const output = [];
37836
+ for (let i = 0; i < values.length; i++) {
37837
+ const parts = values[i].split(",");
37838
+ for (let j = 0; j < parts.length; j++) {
37839
+ output.push(parts[j]);
37840
+ }
37841
+ }
37842
+ return output;
37843
+ }
37844
+ function hasVaryStar(varyHeader) {
37845
+ const values = splitVaryHeader(varyHeader);
37846
+ for (let i = 0; i < values.length; i++) {
37847
+ if (trimOWS(values[i]).indexOf("*") !== -1) {
37848
+ return true;
37849
+ }
37850
+ }
37851
+ return false;
37852
+ }
37364
37853
  function parseVaryHeader(varyHeader, headers) {
37365
- if (typeof varyHeader === "string" && varyHeader.includes("*")) {
37854
+ if (hasVaryStar(varyHeader)) {
37366
37855
  return headers;
37367
37856
  }
37368
37857
  const output = (
37369
37858
  /** @type {Record<string, string | string[] | null>} */
37370
37859
  {}
37371
37860
  );
37372
- const varyingHeaders = typeof varyHeader === "string" ? varyHeader.split(",") : varyHeader;
37861
+ const varyingHeaders = splitVaryHeader(varyHeader);
37373
37862
  for (const header of varyingHeaders) {
37374
- const trimmedHeader = header.trim().toLowerCase();
37375
- output[trimmedHeader] = headers[trimmedHeader] ?? null;
37863
+ const trimmedHeader = trimOWS(header).toLowerCase();
37864
+ if (trimmedHeader.length === 0) {
37865
+ continue;
37866
+ }
37867
+ if (!isValidHTTPToken(trimmedHeader)) {
37868
+ return void 0;
37869
+ }
37870
+ const headerValue = headers[trimmedHeader];
37871
+ output[trimmedHeader] = Array.isArray(headerValue) ? headerValue.slice() : headerValue ?? null;
37376
37872
  }
37377
37873
  return output;
37378
37874
  }
37875
+ function isInvalidOrWildcardVaryHeader(varyHeader) {
37876
+ return hasVaryStar(varyHeader) || parseVaryHeader(varyHeader, {}) === void 0;
37877
+ }
37379
37878
  function isEtagUsable(etag) {
37380
37879
  if (etag.length <= 2) {
37381
37880
  return false;
@@ -37406,24 +37905,23 @@ var require_cache = __commonJS({
37406
37905
  throw new TypeError(`${name} needs to have at least one method`);
37407
37906
  }
37408
37907
  for (const method of methods) {
37409
- if (!safeHTTPMethods.includes(method)) {
37908
+ if (!arrayIncludes(safeHTTPMethods, method)) {
37410
37909
  throw new TypeError(`element of ${name}-array needs to be one of following values: ${safeHTTPMethods.join(", ")}, got ${method}`);
37411
37910
  }
37412
37911
  }
37413
37912
  }
37414
37913
  function makeDeduplicationKey(cacheKey, excludeHeaders) {
37415
- let key = `${cacheKey.origin}:${cacheKey.method}:${cacheKey.path}`;
37914
+ const headers = {};
37416
37915
  if (cacheKey.headers) {
37417
37916
  const sortedHeaders = Object.keys(cacheKey.headers).sort();
37418
37917
  for (const header of sortedHeaders) {
37419
37918
  if (excludeHeaders?.has(header.toLowerCase())) {
37420
37919
  continue;
37421
37920
  }
37422
- const value = cacheKey.headers[header];
37423
- key += `:${header}=${Array.isArray(value) ? value.join(",") : value}`;
37921
+ headers[header] = cacheKey.headers[header];
37424
37922
  }
37425
37923
  }
37426
- return key;
37924
+ return JSON.stringify([cacheKey.origin, cacheKey.method, cacheKey.path, headers]);
37427
37925
  }
37428
37926
  module2.exports = {
37429
37927
  makeCacheKey,
@@ -37431,7 +37929,10 @@ var require_cache = __commonJS({
37431
37929
  assertCacheKey,
37432
37930
  assertCacheValue,
37433
37931
  parseCacheControlHeader,
37932
+ hasInvalidCacheControlDirective,
37434
37933
  parseVaryHeader,
37934
+ hasVaryStar,
37935
+ isInvalidOrWildcardVaryHeader,
37435
37936
  isEtagUsable,
37436
37937
  assertCacheMethods,
37437
37938
  assertCacheStore,
@@ -37454,6 +37955,13 @@ var require_date = __commonJS({
37454
37955
  return parseRfc850Date(date);
37455
37956
  }
37456
37957
  }
37958
+ function makeDate(year, monthIdx, day, hour, minute, second, weekday) {
37959
+ const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37960
+ if (year >= 0 && year <= 99) {
37961
+ result.setUTCFullYear(year);
37962
+ }
37963
+ return result.getUTCFullYear() === year && result.getUTCMonth() === monthIdx && result.getUTCDate() === day && result.getUTCHours() === hour && result.getUTCMinutes() === minute && result.getUTCSeconds() === second && result.getUTCDay() === weekday ? result : void 0;
37964
+ }
37457
37965
  function parseImfDate(date) {
37458
37966
  if (date.length !== 29 || date[4] !== " " || date[7] !== " " || date[11] !== " " || date[16] !== " " || date[19] !== ":" || date[22] !== ":" || date[25] !== " " || date[26] !== "G" || date[27] !== "M" || date[28] !== "T") {
37459
37967
  return void 0;
@@ -37614,8 +38122,7 @@ var require_date = __commonJS({
37614
38122
  }
37615
38123
  second = (code1 - 48) * 10 + (code2 - 48);
37616
38124
  }
37617
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37618
- return result.getUTCDay() === weekday ? result : void 0;
38125
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
37619
38126
  }
37620
38127
  function parseAscTimeDate(date) {
37621
38128
  if (date.length !== 24 || date[7] !== " " || date[10] !== " " || date[19] !== " ") {
@@ -37777,8 +38284,7 @@ var require_date = __commonJS({
37777
38284
  return void 0;
37778
38285
  }
37779
38286
  const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48);
37780
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37781
- return result.getUTCDay() === weekday ? result : void 0;
38287
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
37782
38288
  }
37783
38289
  function parseRfc850Date(date) {
37784
38290
  let commaIndex = -1;
@@ -37927,8 +38433,7 @@ var require_date = __commonJS({
37927
38433
  }
37928
38434
  second = (code1 - 48) * 10 + (code2 - 48);
37929
38435
  }
37930
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
37931
- return result.getUTCDay() === weekday ? result : void 0;
38436
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
37932
38437
  }
37933
38438
  module2.exports = {
37934
38439
  parseHttpDate
@@ -37943,7 +38448,10 @@ var require_cache_handler = __commonJS({
37943
38448
  var util = require_util();
37944
38449
  var {
37945
38450
  parseCacheControlHeader,
38451
+ hasInvalidCacheControlDirective,
37946
38452
  parseVaryHeader,
38453
+ hasVaryStar,
38454
+ isInvalidOrWildcardVaryHeader,
37947
38455
  isEtagUsable
37948
38456
  } = require_cache();
37949
38457
  var { parseHttpDate } = require_date();
@@ -37967,6 +38475,78 @@ var require_cache_handler = __commonJS({
37967
38475
  206
37968
38476
  ];
37969
38477
  var MAX_RESPONSE_AGE = 2147483647e3;
38478
+ function trimOWS(value) {
38479
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
38480
+ }
38481
+ function arrayIncludes(array, value) {
38482
+ for (let i = 0; i < array.length; i++) {
38483
+ if (array[i] === value) {
38484
+ return true;
38485
+ }
38486
+ }
38487
+ return false;
38488
+ }
38489
+ function appendConnectionHeaderTokens(headersToRemove, connectionHeader) {
38490
+ const values = Array.isArray(connectionHeader) ? connectionHeader : [connectionHeader];
38491
+ for (let i = 0; i < values.length; i++) {
38492
+ const tokens = values[i].split(",");
38493
+ for (let j = 0; j < tokens.length; j++) {
38494
+ headersToRemove.push(trimOWS(tokens[j]).toLowerCase());
38495
+ }
38496
+ }
38497
+ }
38498
+ function getSameOriginPath(cacheKey, location) {
38499
+ if (typeof location !== "string") {
38500
+ return void 0;
38501
+ }
38502
+ let originUrl;
38503
+ let requestUrl;
38504
+ let locationUrl;
38505
+ try {
38506
+ originUrl = new URL(cacheKey.origin);
38507
+ requestUrl = new URL(cacheKey.path, originUrl);
38508
+ locationUrl = new URL(location, requestUrl);
38509
+ } catch {
38510
+ return void 0;
38511
+ }
38512
+ if (locationUrl.origin !== originUrl.origin) {
38513
+ return void 0;
38514
+ }
38515
+ return locationUrl.pathname + locationUrl.search;
38516
+ }
38517
+ function deleteCachedUri(store, cacheKey, path74) {
38518
+ deleteCachedValue(store, {
38519
+ ...cacheKey,
38520
+ path: path74
38521
+ });
38522
+ for (let i = 0; i < util.safeHTTPMethods.length; i++) {
38523
+ const method = util.safeHTTPMethods[i];
38524
+ if (method !== cacheKey.method) {
38525
+ deleteCachedValue(store, {
38526
+ ...cacheKey,
38527
+ method,
38528
+ path: path74
38529
+ });
38530
+ }
38531
+ }
38532
+ }
38533
+ function deleteLocationTargets(store, cacheKey, headerValue) {
38534
+ if (headerValue === void 0) {
38535
+ return;
38536
+ }
38537
+ const values = Array.isArray(headerValue) ? headerValue : [headerValue];
38538
+ for (let i = 0; i < values.length; i++) {
38539
+ const path74 = getSameOriginPath(cacheKey, values[i]);
38540
+ if (path74 !== void 0) {
38541
+ deleteCachedUri(store, cacheKey, path74);
38542
+ }
38543
+ }
38544
+ }
38545
+ function invalidateUnsafeRequest(store, cacheKey, resHeaders) {
38546
+ deleteCachedUri(store, cacheKey, cacheKey.path);
38547
+ deleteLocationTargets(store, cacheKey, resHeaders.location);
38548
+ deleteLocationTargets(store, cacheKey, resHeaders["content-location"]);
38549
+ }
37970
38550
  var CacheHandler = class {
37971
38551
  /**
37972
38552
  * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
@@ -38026,35 +38606,53 @@ var require_cache_handler = __commonJS({
38026
38606
  statusMessage
38027
38607
  );
38028
38608
  const handler = this;
38029
- if (!util.safeHTTPMethods.includes(this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) {
38030
- try {
38031
- this.#store.delete(this.#cacheKey)?.catch?.(noop);
38032
- } catch {
38033
- }
38609
+ if (!arrayIncludes(util.safeHTTPMethods, this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) {
38610
+ invalidateUnsafeRequest(this.#store, this.#cacheKey, resHeaders);
38034
38611
  return downstreamOnHeaders();
38035
38612
  }
38036
38613
  const cacheControlHeader = resHeaders["cache-control"];
38037
- const heuristicallyCacheable = resHeaders["last-modified"] && HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode);
38614
+ const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
38615
+ if (revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives)) {
38616
+ deleteCachedValue(this.#store, this.#cacheKey);
38617
+ return downstreamOnHeaders();
38618
+ }
38619
+ const heuristicallyCacheable = resHeaders["last-modified"] && arrayIncludes(HEURISTICALLY_CACHEABLE_STATUS_CODES, statusCode);
38038
38620
  if (!cacheControlHeader && !resHeaders["expires"] && !heuristicallyCacheable && !this.#cacheByDefault) {
38621
+ if (statusCode === 304 && resHeaders.vary && isInvalidOrWildcardVaryHeader(resHeaders.vary)) {
38622
+ deleteCachedValue(this.#store, this.#cacheKey);
38623
+ }
38039
38624
  return downstreamOnHeaders();
38040
38625
  }
38041
- const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
38042
- if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
38626
+ if (!canCacheResponse(this.#cacheType, this.#cacheKey.method, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
38627
+ if (statusCode === 304 && (cacheControlHeader || revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives))) {
38628
+ deleteCachedValue(this.#store, this.#cacheKey);
38629
+ }
38043
38630
  return downstreamOnHeaders();
38044
38631
  }
38045
38632
  const now = Date.now();
38046
- const resAge = resHeaders.age ? getAge(resHeaders.age) : void 0;
38047
- if (resAge && resAge >= MAX_RESPONSE_AGE) {
38633
+ const resAge = Object.hasOwn(resHeaders, "age") ? getAge(resHeaders.age) : void 0;
38634
+ if (resAge !== void 0 && resAge >= MAX_RESPONSE_AGE) {
38635
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38048
38636
  return downstreamOnHeaders();
38049
38637
  }
38050
- const resDate = typeof resHeaders.date === "string" ? parseHttpDate(resHeaders.date) : void 0;
38638
+ const resDate = Object.hasOwn(resHeaders, "date") ? getDate(resHeaders.date) : void 0;
38639
+ if (resDate === null) {
38640
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38641
+ return downstreamOnHeaders();
38642
+ }
38643
+ const apparentAge = resDate ? Math.max(0, now - resDate.getTime()) : 0;
38644
+ const currentAge = Math.max(apparentAge, resAge ?? 0);
38051
38645
  const staleAt = determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives) ?? this.#cacheByDefault;
38052
- if (staleAt === void 0 || resAge && resAge > staleAt) {
38646
+ if (staleAt === void 0 || currentAge >= staleAt) {
38647
+ if (cacheControlHeader || staleAt !== void 0) {
38648
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38649
+ }
38053
38650
  return downstreamOnHeaders();
38054
38651
  }
38055
- const baseTime = resDate ? resDate.getTime() : now;
38652
+ const baseTime = now - currentAge;
38056
38653
  const absoluteStaleAt = staleAt + baseTime;
38057
38654
  if (now >= absoluteStaleAt) {
38655
+ deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey);
38058
38656
  return downstreamOnHeaders();
38059
38657
  }
38060
38658
  let varyDirectives;
@@ -38064,7 +38662,8 @@ var require_cache_handler = __commonJS({
38064
38662
  return downstreamOnHeaders();
38065
38663
  }
38066
38664
  }
38067
- const deleteAt = determineDeleteAt(baseTime, cacheControlDirectives, absoluteStaleAt);
38665
+ const cachedAt = baseTime;
38666
+ const deleteAt = determineDeleteAt(baseTime, now, cacheControlDirectives, absoluteStaleAt);
38068
38667
  const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives);
38069
38668
  const value = {
38070
38669
  statusCode,
@@ -38072,7 +38671,7 @@ var require_cache_handler = __commonJS({
38072
38671
  headers: strippedHeaders,
38073
38672
  vary: varyDirectives,
38074
38673
  cacheControlDirectives,
38075
- cachedAt: resAge ? now - resAge : now,
38674
+ cachedAt,
38076
38675
  staleAt: absoluteStaleAt,
38077
38676
  deleteAt
38078
38677
  };
@@ -38084,6 +38683,7 @@ var require_cache_handler = __commonJS({
38084
38683
  value.statusCode = cachedValue.statusCode;
38085
38684
  value.statusMessage = cachedValue.statusMessage;
38086
38685
  value.etag = cachedValue.etag;
38686
+ value.vary = varyDirectives ?? cachedValue.vary;
38087
38687
  value.headers = { ...cachedValue.headers, ...strippedHeaders };
38088
38688
  downstreamOnHeaders();
38089
38689
  this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
@@ -38174,74 +38774,129 @@ var require_cache_handler = __commonJS({
38174
38774
  this.#handler.onResponseError?.(controller, err2);
38175
38775
  }
38176
38776
  };
38177
- function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
38178
- if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) {
38777
+ function deleteCachedValue(store, cacheKey) {
38778
+ try {
38779
+ store.delete(cacheKey)?.catch?.(noop);
38780
+ } catch {
38781
+ }
38782
+ }
38783
+ function deleteCachedValueIfNotModified(statusCode, store, cacheKey) {
38784
+ if (statusCode === 304) {
38785
+ deleteCachedValue(store, cacheKey);
38786
+ }
38787
+ }
38788
+ function revalidationResponseDisallowsCachedReuse(cacheType, resHeaders, cacheControlDirectives) {
38789
+ return cacheControlDirectives["no-store"] === true || cacheType === "shared" && (cacheControlDirectives.private === true || Object.hasOwn(resHeaders, "set-cookie")) || (resHeaders.vary ? isInvalidOrWildcardVaryHeader(resHeaders.vary) : false);
38790
+ }
38791
+ function canCacheResponse(cacheType, method, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
38792
+ if (!arrayIncludes(util.safeHTTPMethods, method)) {
38179
38793
  return false;
38180
38794
  }
38181
- if (!HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode) && !resHeaders["expires"] && !cacheControlDirectives.public && cacheControlDirectives["max-age"] === void 0 && // RFC 9111: a private response directive, if the cache is not shared
38795
+ if (statusCode < 200 || arrayIncludes(NOT_UNDERSTOOD_STATUS_CODES, statusCode)) {
38796
+ return false;
38797
+ }
38798
+ if (!arrayIncludes(HEURISTICALLY_CACHEABLE_STATUS_CODES, statusCode) && !resHeaders["expires"] && !cacheControlDirectives.public && cacheControlDirectives["max-age"] === void 0 && // RFC 9111: a private response directive, if the cache is not shared
38182
38799
  !(cacheControlDirectives.private && cacheType === "private") && !(cacheControlDirectives["s-maxage"] !== void 0 && cacheType === "shared")) {
38183
38800
  return false;
38184
38801
  }
38185
38802
  if (cacheControlDirectives["no-store"]) {
38186
38803
  return false;
38187
38804
  }
38188
- if (cacheType === "shared" && cacheControlDirectives.private === true) {
38805
+ if (cacheType === "shared" && (cacheControlDirectives.private === true || Object.hasOwn(resHeaders, "set-cookie"))) {
38189
38806
  return false;
38190
38807
  }
38191
- if (resHeaders.vary?.includes("*")) {
38808
+ if (resHeaders.vary && hasVaryStar(resHeaders.vary)) {
38192
38809
  return false;
38193
38810
  }
38194
- if (reqHeaders?.authorization) {
38811
+ if (reqHeaders != null && Object.hasOwn(reqHeaders, "authorization")) {
38195
38812
  if (!cacheControlDirectives.public && !cacheControlDirectives["s-maxage"] && !cacheControlDirectives["must-revalidate"]) {
38196
38813
  return false;
38197
38814
  }
38198
38815
  if (typeof reqHeaders.authorization !== "string") {
38199
38816
  return false;
38200
38817
  }
38201
- if (Array.isArray(cacheControlDirectives["no-cache"]) && cacheControlDirectives["no-cache"].includes("authorization")) {
38818
+ if (Array.isArray(cacheControlDirectives["no-cache"]) && arrayIncludes(cacheControlDirectives["no-cache"], "authorization")) {
38202
38819
  return false;
38203
38820
  }
38204
- if (Array.isArray(cacheControlDirectives["private"]) && cacheControlDirectives["private"].includes("authorization")) {
38821
+ if (Array.isArray(cacheControlDirectives["private"]) && arrayIncludes(cacheControlDirectives["private"], "authorization")) {
38205
38822
  return false;
38206
38823
  }
38207
38824
  }
38208
38825
  return true;
38209
38826
  }
38827
+ function getDate(dateHeader) {
38828
+ let dateValue = dateHeader;
38829
+ if (Array.isArray(dateValue)) {
38830
+ if (dateValue.length !== 1) {
38831
+ return null;
38832
+ }
38833
+ dateValue = dateValue[0];
38834
+ }
38835
+ if (typeof dateValue !== "string") {
38836
+ return null;
38837
+ }
38838
+ return parseHttpDate(dateValue);
38839
+ }
38210
38840
  function getAge(ageHeader) {
38211
- const age = parseInt(Array.isArray(ageHeader) ? ageHeader[0] : ageHeader);
38212
- return isNaN(age) ? void 0 : age * 1e3;
38841
+ let ageValue = ageHeader;
38842
+ if (Array.isArray(ageValue)) {
38843
+ if (ageValue.length !== 1) {
38844
+ return MAX_RESPONSE_AGE;
38845
+ }
38846
+ ageValue = ageValue[0];
38847
+ }
38848
+ if (typeof ageValue !== "string" || !/^[\t ]*[0-9]+[\t ]*$/.test(ageValue)) {
38849
+ return MAX_RESPONSE_AGE;
38850
+ }
38851
+ const age = BigInt(ageValue.replace(/^[\t ]+|[\t ]+$/g, ""));
38852
+ if (age >= BigInt(MAX_RESPONSE_AGE / 1e3)) {
38853
+ return MAX_RESPONSE_AGE;
38854
+ }
38855
+ return Number(age) * 1e3;
38213
38856
  }
38214
38857
  function determineStaleAt(cacheType, now, age, resHeaders, responseDate, cacheControlDirectives) {
38215
38858
  if (cacheType === "shared") {
38859
+ if (hasInvalidCacheControlDirective(cacheControlDirectives, "s-maxage")) {
38860
+ return 0;
38861
+ }
38216
38862
  const sMaxAge = cacheControlDirectives["s-maxage"];
38217
38863
  if (sMaxAge !== void 0) {
38218
- return sMaxAge > 0 ? sMaxAge * 1e3 : void 0;
38864
+ return sMaxAge * 1e3;
38219
38865
  }
38220
38866
  }
38867
+ if (hasInvalidCacheControlDirective(cacheControlDirectives, "max-age")) {
38868
+ return 0;
38869
+ }
38221
38870
  const maxAge = cacheControlDirectives["max-age"];
38222
38871
  if (maxAge !== void 0) {
38223
- return maxAge > 0 ? maxAge * 1e3 : void 0;
38872
+ return maxAge * 1e3;
38224
38873
  }
38225
- if (typeof resHeaders.expires === "string") {
38874
+ if (Object.hasOwn(resHeaders, "expires")) {
38875
+ if (typeof resHeaders.expires !== "string") {
38876
+ return 0;
38877
+ }
38226
38878
  const expiresDate = parseHttpDate(resHeaders.expires);
38227
- if (expiresDate) {
38228
- if (now >= expiresDate.getTime()) {
38229
- return void 0;
38879
+ if (!expiresDate) {
38880
+ return 0;
38881
+ }
38882
+ if (now >= expiresDate.getTime()) {
38883
+ return 0;
38884
+ }
38885
+ if (responseDate) {
38886
+ if (responseDate >= expiresDate) {
38887
+ return 0;
38230
38888
  }
38231
- if (responseDate) {
38232
- if (responseDate >= expiresDate) {
38233
- return void 0;
38234
- }
38235
- if (age !== void 0 && age > expiresDate - responseDate) {
38236
- return void 0;
38237
- }
38889
+ const freshnessLifetime = expiresDate.getTime() - responseDate.getTime();
38890
+ if (age !== void 0 && age >= freshnessLifetime) {
38891
+ return 0;
38238
38892
  }
38239
- return expiresDate.getTime() - now;
38893
+ return freshnessLifetime;
38240
38894
  }
38895
+ return expiresDate.getTime() - now;
38241
38896
  }
38242
38897
  if (typeof resHeaders["last-modified"] === "string") {
38243
- const lastModified = new Date(resHeaders["last-modified"]);
38244
- if (isValidDate(lastModified)) {
38898
+ const lastModified = parseHttpDate(resHeaders["last-modified"]);
38899
+ if (lastModified) {
38245
38900
  if (lastModified.getTime() >= now) {
38246
38901
  return void 0;
38247
38902
  }
@@ -38250,11 +38905,11 @@ var require_cache_handler = __commonJS({
38250
38905
  }
38251
38906
  }
38252
38907
  if (cacheControlDirectives.immutable) {
38253
- return 31536e3;
38908
+ return 31536e6;
38254
38909
  }
38255
38910
  return void 0;
38256
38911
  }
38257
- function determineDeleteAt(now, cacheControlDirectives, staleAt) {
38912
+ function determineDeleteAt(baseTime, cachedAt, cacheControlDirectives, staleAt) {
38258
38913
  let staleWhileRevalidate = -Infinity;
38259
38914
  let staleIfError = -Infinity;
38260
38915
  let immutable = -Infinity;
@@ -38265,11 +38920,12 @@ var require_cache_handler = __commonJS({
38265
38920
  staleIfError = staleAt + cacheControlDirectives["stale-if-error"] * 1e3;
38266
38921
  }
38267
38922
  if (cacheControlDirectives.immutable && staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
38268
- immutable = now + 31536e6;
38923
+ immutable = cachedAt + 31536e6;
38269
38924
  }
38270
38925
  if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) {
38271
- const freshnessLifetime = staleAt - now;
38272
- return staleAt + freshnessLifetime;
38926
+ const freshnessLifetime = staleAt - baseTime;
38927
+ const datePrecisionPadding = Math.min(Math.max(cachedAt - baseTime, 0), 1e3);
38928
+ return staleAt + freshnessLifetime + datePrecisionPadding;
38273
38929
  }
38274
38930
  return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable);
38275
38931
  }
@@ -38287,11 +38943,7 @@ var require_cache_handler = __commonJS({
38287
38943
  "age"
38288
38944
  ];
38289
38945
  if (resHeaders["connection"]) {
38290
- if (Array.isArray(resHeaders["connection"])) {
38291
- headersToRemove.push(...resHeaders["connection"].map((header) => header.trim()));
38292
- } else {
38293
- headersToRemove.push(...resHeaders["connection"].split(",").map((header) => header.trim()));
38294
- }
38946
+ appendConnectionHeaderTokens(headersToRemove, resHeaders["connection"]);
38295
38947
  }
38296
38948
  if (Array.isArray(cacheControlDirectives["no-cache"])) {
38297
38949
  headersToRemove.push(...cacheControlDirectives["no-cache"]);
@@ -38301,16 +38953,13 @@ var require_cache_handler = __commonJS({
38301
38953
  }
38302
38954
  let strippedHeaders;
38303
38955
  for (const headerName of headersToRemove) {
38304
- if (resHeaders[headerName]) {
38956
+ if (Object.hasOwn(resHeaders, headerName)) {
38305
38957
  strippedHeaders ??= { ...resHeaders };
38306
38958
  delete strippedHeaders[headerName];
38307
38959
  }
38308
38960
  }
38309
38961
  return strippedHeaders ?? resHeaders;
38310
38962
  }
38311
- function isValidDate(date) {
38312
- return date instanceof Date && Number.isFinite(date.valueOf());
38313
- }
38314
38963
  module2.exports = CacheHandler;
38315
38964
  }
38316
38965
  });
@@ -38481,12 +39130,43 @@ var require_memory_cache_store = __commonJS({
38481
39130
  }
38482
39131
  };
38483
39132
  function findEntry(key, entries, now) {
38484
- return entries.find((entry) => entry.deleteAt > now && entry.method === key.method && (entry.vary == null || Object.keys(entry.vary).every((headerName) => {
38485
- if (entry.vary[headerName] === null) {
38486
- return key.headers[headerName] === void 0;
39133
+ for (let i = 0; i < entries.length; i++) {
39134
+ const entry = entries[i];
39135
+ if (entry.deleteAt > now && entry.method === key.method && varyMatches(key, entry)) {
39136
+ return entry;
39137
+ }
39138
+ }
39139
+ }
39140
+ function varyMatches(key, entry) {
39141
+ if (entry.vary == null) {
39142
+ return true;
39143
+ }
39144
+ for (const headerName in entry.vary) {
39145
+ if (Object.hasOwn(entry.vary, headerName) && !headerValueEquals(key.headers?.[headerName], entry.vary[headerName])) {
39146
+ return false;
39147
+ }
39148
+ }
39149
+ return true;
39150
+ }
39151
+ function headerValueEquals(lhs, rhs) {
39152
+ if (lhs == null && rhs == null) {
39153
+ return true;
39154
+ }
39155
+ if (lhs == null && rhs != null || lhs != null && rhs == null) {
39156
+ return false;
39157
+ }
39158
+ if (Array.isArray(lhs) && Array.isArray(rhs)) {
39159
+ if (lhs.length !== rhs.length) {
39160
+ return false;
38487
39161
  }
38488
- return entry.vary[headerName] === key.headers[headerName];
38489
- })));
39162
+ for (let i = 0; i < lhs.length; i++) {
39163
+ if (lhs[i] !== rhs[i]) {
39164
+ return false;
39165
+ }
39166
+ }
39167
+ return true;
39168
+ }
39169
+ return lhs === rhs;
38490
39170
  }
38491
39171
  module2.exports = MemoryCacheStore;
38492
39172
  }
@@ -38500,7 +39180,7 @@ var require_cache_revalidation_handler = __commonJS({
38500
39180
  var CacheRevalidationHandler = class {
38501
39181
  #successful = false;
38502
39182
  /**
38503
- * @type {((boolean, any) => void) | null}
39183
+ * @type {((success: boolean, context?: any, statusCode?: number, headers?: import('../../types/header.d.ts').IncomingHttpHeaders) => void) | null}
38504
39184
  */
38505
39185
  #callback;
38506
39186
  /**
@@ -38513,7 +39193,7 @@ var require_cache_revalidation_handler = __commonJS({
38513
39193
  */
38514
39194
  #allowErrorStatusCodes;
38515
39195
  /**
38516
- * @param {(boolean) => void} callback Function to call if the cached value is valid
39196
+ * @param {(success: boolean, context?: any, statusCode?: number, headers?: import('../../types/header.d.ts').IncomingHttpHeaders) => void} callback Function to call if the cached value is valid
38517
39197
  * @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler
38518
39198
  * @param {boolean} allowErrorStatusCodes
38519
39199
  */
@@ -38535,7 +39215,7 @@ var require_cache_revalidation_handler = __commonJS({
38535
39215
  onResponseStart(controller, statusCode, headers, statusMessage) {
38536
39216
  assert(this.#callback != null);
38537
39217
  this.#successful = statusCode === 304 || this.#allowErrorStatusCodes && statusCode >= 500 && statusCode <= 504;
38538
- this.#callback(this.#successful, this.#context);
39218
+ this.#callback(this.#successful, this.#context, statusCode, headers);
38539
39219
  this.#callback = null;
38540
39220
  if (this.#successful) {
38541
39221
  return true;
@@ -38589,8 +39269,9 @@ var require_cache2 = __commonJS({
38589
39269
  var CacheHandler = require_cache_handler();
38590
39270
  var MemoryCacheStore = require_memory_cache_store();
38591
39271
  var CacheRevalidationHandler = require_cache_revalidation_handler();
38592
- var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader } = require_cache();
39272
+ var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader, isInvalidOrWildcardVaryHeader } = require_cache();
38593
39273
  var { AbortError } = require_errors();
39274
+ var { parseHttpDate } = require_date();
38594
39275
  function assertCacheOrigins(origins, name) {
38595
39276
  if (origins === void 0) return;
38596
39277
  if (!Array.isArray(origins)) {
@@ -38605,6 +39286,37 @@ var require_cache2 = __commonJS({
38605
39286
  }
38606
39287
  var nop = () => {
38607
39288
  };
39289
+ function trimOWS(value) {
39290
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
39291
+ }
39292
+ function arrayIncludes(array, value) {
39293
+ for (let i = 0; i < array.length; i++) {
39294
+ if (array[i] === value) {
39295
+ return true;
39296
+ }
39297
+ }
39298
+ return false;
39299
+ }
39300
+ function hasPragmaNoCache(headers) {
39301
+ const pragma = headers?.pragma;
39302
+ if (!pragma) {
39303
+ return false;
39304
+ }
39305
+ const values = Array.isArray(pragma) ? pragma : [pragma];
39306
+ for (let i = 0; i < values.length; i++) {
39307
+ const value = values[i];
39308
+ if (typeof value !== "string") {
39309
+ continue;
39310
+ }
39311
+ const directives = value.split(",");
39312
+ for (let j = 0; j < directives.length; j++) {
39313
+ if (trimOWS(directives[j]).toLowerCase() === "no-cache") {
39314
+ return true;
39315
+ }
39316
+ }
39317
+ }
39318
+ return false;
39319
+ }
38608
39320
  function needsRevalidation(result, cacheControlDirectives, { headers = {} }) {
38609
39321
  if (cacheControlDirectives?.["no-cache"]) {
38610
39322
  return true;
@@ -38617,10 +39329,58 @@ var require_cache2 = __commonJS({
38617
39329
  }
38618
39330
  return false;
38619
39331
  }
38620
- function isStale(result, cacheControlDirectives) {
39332
+ function staleResponseRequiresRevalidation(result, cacheType) {
39333
+ return result.cacheControlDirectives?.["must-revalidate"] === true || cacheType === "shared" && (result.cacheControlDirectives?.["proxy-revalidate"] === true || // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.10
39334
+ // s-maxage implies proxy-revalidate for shared caches.
39335
+ result.cacheControlDirectives?.["s-maxage"] !== void 0);
39336
+ }
39337
+ function revalidationResponseDisallowsCachedReuse(cacheType, headers) {
39338
+ if (headers.vary && isInvalidOrWildcardVaryHeader(headers.vary) || cacheType === "shared" && Object.hasOwn(headers, "set-cookie")) {
39339
+ return true;
39340
+ }
39341
+ const cacheControl = headers["cache-control"];
39342
+ if (!cacheControl) {
39343
+ return false;
39344
+ }
39345
+ const cacheControlDirectives = parseCacheControlHeader(cacheControl);
39346
+ return cacheControlDirectives["no-store"] === true || cacheType === "shared" && cacheControlDirectives.private === true;
39347
+ }
39348
+ function revalidationResponseUpdatesCacheControl(headers) {
39349
+ return headers["cache-control"] !== void 0;
39350
+ }
39351
+ function deleteCachedValue(store, cacheKey) {
39352
+ try {
39353
+ store.delete(cacheKey)?.catch?.(nop);
39354
+ } catch {
39355
+ }
39356
+ }
39357
+ function getUsableLastModified(headers) {
39358
+ const lastModified = headers?.["last-modified"];
39359
+ if (typeof lastModified === "string" && parseHttpDate(lastModified)) {
39360
+ return lastModified;
39361
+ }
39362
+ }
39363
+ function makeRevalidationHeaders(opts, result) {
39364
+ const headers = {
39365
+ ...opts.headers,
39366
+ "if-modified-since": getUsableLastModified(result.headers) ?? new Date(result.cachedAt).toUTCString()
39367
+ };
39368
+ if (result.etag) {
39369
+ headers["if-none-match"] = result.etag;
39370
+ }
39371
+ if (result.vary) {
39372
+ for (const key in result.vary) {
39373
+ if (result.vary[key] != null) {
39374
+ headers[key] = result.vary[key];
39375
+ }
39376
+ }
39377
+ }
39378
+ return headers;
39379
+ }
39380
+ function isStale(result, cacheControlDirectives, cacheType) {
38621
39381
  const now = Date.now();
38622
39382
  if (now > result.staleAt) {
38623
- if (cacheControlDirectives?.["max-stale"]) {
39383
+ if (!staleResponseRequiresRevalidation(result, cacheType) && cacheControlDirectives?.["max-stale"]) {
38624
39384
  const gracePeriod = result.staleAt + cacheControlDirectives["max-stale"] * 1e3;
38625
39385
  return now > gracePeriod;
38626
39386
  }
@@ -38633,9 +39393,9 @@ var require_cache2 = __commonJS({
38633
39393
  }
38634
39394
  return false;
38635
39395
  }
38636
- function withinStaleWhileRevalidateWindow(result) {
39396
+ function withinStaleWhileRevalidateWindow(result, cacheType) {
38637
39397
  const staleWhileRevalidate = result.cacheControlDirectives?.["stale-while-revalidate"];
38638
- if (!staleWhileRevalidate) {
39398
+ if (!staleWhileRevalidate || staleResponseRequiresRevalidation(result, cacheType)) {
38639
39399
  return false;
38640
39400
  }
38641
39401
  const now = Date.now();
@@ -38730,37 +39490,29 @@ var require_cache2 = __commonJS({
38730
39490
  if (!result) {
38731
39491
  return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl);
38732
39492
  }
39493
+ if (globalOpts.type === "shared" && Object.hasOwn(result.headers, "set-cookie")) {
39494
+ if (util.isStream(result.body)) {
39495
+ result.body.on("error", nop).destroy();
39496
+ }
39497
+ deleteCachedValue(globalOpts.store, cacheKey);
39498
+ return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl);
39499
+ }
38733
39500
  const now = Date.now();
38734
39501
  if (now > result.deleteAt) {
38735
39502
  return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
38736
39503
  }
38737
39504
  const age = Math.round((now - result.cachedAt) / 1e3);
38738
- if (reqCacheControl?.["max-age"] && age >= reqCacheControl["max-age"]) {
38739
- return dispatch(opts, handler);
38740
- }
38741
- const stale = isStale(result, reqCacheControl);
38742
- const revalidate = needsRevalidation(result, reqCacheControl, opts);
39505
+ const requestMaxAgeExpired = reqCacheControl?.["max-age"] !== void 0 && age >= reqCacheControl["max-age"];
39506
+ const stale = requestMaxAgeExpired || isStale(result, reqCacheControl, globalOpts.type);
39507
+ const revalidate = requestMaxAgeExpired || needsRevalidation(result, reqCacheControl, opts);
38743
39508
  if (stale || revalidate) {
38744
39509
  if (util.isStream(opts.body) && util.bodyLength(opts.body) !== 0) {
38745
39510
  return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
38746
39511
  }
38747
- if (!revalidate && withinStaleWhileRevalidateWindow(result)) {
39512
+ if (!revalidate && withinStaleWhileRevalidateWindow(result, globalOpts.type)) {
38748
39513
  sendCachedValue(handler, opts, result, age, null, true);
38749
39514
  queueMicrotask(() => {
38750
- const headers2 = {
38751
- ...opts.headers,
38752
- "if-modified-since": new Date(result.cachedAt).toUTCString()
38753
- };
38754
- if (result.etag) {
38755
- headers2["if-none-match"] = result.etag;
38756
- }
38757
- if (result.vary) {
38758
- for (const key in result.vary) {
38759
- if (result.vary[key] != null) {
38760
- headers2[key] = result.vary[key];
38761
- }
38762
- }
38763
- }
39515
+ const headers2 = makeRevalidationHeaders(opts, result);
38764
39516
  dispatch(
38765
39517
  {
38766
39518
  ...opts,
@@ -38786,32 +39538,33 @@ var require_cache2 = __commonJS({
38786
39538
  return true;
38787
39539
  }
38788
39540
  let withinStaleIfErrorThreshold = false;
38789
- const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
38790
- if (staleIfErrorExpiry) {
38791
- withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
38792
- }
38793
- const headers = {
38794
- ...opts.headers,
38795
- "if-modified-since": new Date(result.cachedAt).toUTCString()
38796
- };
38797
- if (result.etag) {
38798
- headers["if-none-match"] = result.etag;
38799
- }
38800
- if (result.vary) {
38801
- for (const key in result.vary) {
38802
- if (result.vary[key] != null) {
38803
- headers[key] = result.vary[key];
38804
- }
39541
+ if (!staleResponseRequiresRevalidation(result, globalOpts.type)) {
39542
+ const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
39543
+ if (staleIfErrorExpiry) {
39544
+ withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
38805
39545
  }
38806
39546
  }
39547
+ const headers = makeRevalidationHeaders(opts, result);
38807
39548
  return dispatch(
38808
39549
  {
38809
39550
  ...opts,
38810
39551
  headers
38811
39552
  },
38812
39553
  new CacheRevalidationHandler(
38813
- (success, context) => {
39554
+ (success, context, statusCode, headers2) => {
38814
39555
  if (success) {
39556
+ if (statusCode === 304) {
39557
+ if (revalidationResponseDisallowsCachedReuse(globalOpts.type, headers2)) {
39558
+ if (util.isStream(result.body)) {
39559
+ result.body.on("error", nop).destroy();
39560
+ }
39561
+ deleteCachedValue(globalOpts.store, cacheKey);
39562
+ return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
39563
+ }
39564
+ if (revalidationResponseUpdatesCacheControl(headers2)) {
39565
+ deleteCachedValue(globalOpts.store, cacheKey);
39566
+ }
39567
+ }
38815
39568
  sendCachedValue(handler, opts, result, age, context, stale);
38816
39569
  } else if (util.isStream(result.body)) {
38817
39570
  result.body.on("error", nop).destroy();
@@ -38853,10 +39606,16 @@ var require_cache2 = __commonJS({
38853
39606
  cacheByDefault,
38854
39607
  type
38855
39608
  };
38856
- const safeMethodsToNotCache = util.safeHTTPMethods.filter((method) => methods.includes(method) === false);
39609
+ const safeMethodsToNotCache = [];
39610
+ for (let i = 0; i < util.safeHTTPMethods.length; i++) {
39611
+ const method = util.safeHTTPMethods[i];
39612
+ if (!arrayIncludes(methods, method)) {
39613
+ safeMethodsToNotCache.push(method);
39614
+ }
39615
+ }
38857
39616
  return (dispatch) => {
38858
39617
  return (opts2, handler) => {
38859
- if (!opts2.origin || safeMethodsToNotCache.includes(opts2.method)) {
39618
+ if (!opts2.origin || arrayIncludes(safeMethodsToNotCache, opts2.method)) {
38860
39619
  return dispatch(opts2, handler);
38861
39620
  }
38862
39621
  if (origins !== void 0) {
@@ -38882,11 +39641,14 @@ var require_cache2 = __commonJS({
38882
39641
  ...opts2,
38883
39642
  headers: normalizeHeaders(opts2)
38884
39643
  };
38885
- const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : void 0;
39644
+ const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : hasPragmaNoCache(opts2.headers) ? { "no-cache": true } : void 0;
38886
39645
  if (reqCacheControl?.["no-store"]) {
38887
39646
  return dispatch(opts2, handler);
38888
39647
  }
38889
39648
  const cacheKey = makeCacheKey(opts2);
39649
+ if (!arrayIncludes(util.safeHTTPMethods, opts2.method)) {
39650
+ return dispatch(opts2, new CacheHandler(globalOpts, cacheKey, handler));
39651
+ }
38890
39652
  const result = store.get(cacheKey);
38891
39653
  if (result && typeof result.then === "function") {
38892
39654
  return result.then((result2) => handleResult(
@@ -38920,7 +39682,8 @@ var require_decompress = __commonJS({
38920
39682
  "node_modules/undici/lib/interceptor/decompress.js"(exports2, module2) {
38921
39683
  "use strict";
38922
39684
  var { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = require("zlib");
38923
- var { pipeline } = require("stream");
39685
+ var { pipeline, Transform: TransformStream2 } = require("stream");
39686
+ var { InvalidArgumentError, ResponseExceededMaxSizeError } = require_errors();
38924
39687
  var DecoratorHandler = require_decorator_handler();
38925
39688
  var { runtimeFeatures } = require_runtime_features();
38926
39689
  var supportedEncodings = {
@@ -38936,6 +39699,23 @@ var require_decompress = __commonJS({
38936
39699
  /** @type {const} */
38937
39700
  [204, 304]
38938
39701
  );
39702
+ var defaultMaxSize = 64 * 1024 * 1024;
39703
+ function createMaxSizeLimiter(maxSize) {
39704
+ let size = 0;
39705
+ return new TransformStream2({
39706
+ transform(chunk2, _encoding, callback) {
39707
+ const decompressedSize = size + chunk2.length;
39708
+ if (decompressedSize > maxSize) {
39709
+ callback(new ResponseExceededMaxSizeError(
39710
+ `Decompressed response size (${decompressedSize}) exceeded maxSize (${maxSize})`
39711
+ ));
39712
+ return;
39713
+ }
39714
+ size = decompressedSize;
39715
+ callback(null, chunk2);
39716
+ }
39717
+ });
39718
+ }
38939
39719
  var warningEmitted = (
38940
39720
  /** @type {boolean} */
38941
39721
  false
@@ -38943,14 +39723,28 @@ var require_decompress = __commonJS({
38943
39723
  var DecompressHandler = class extends DecoratorHandler {
38944
39724
  /** @type {Transform[]} */
38945
39725
  #decompressors = [];
39726
+ /** @type {Record<string, string | string[]> | undefined} */
39727
+ #trailers;
38946
39728
  /** @type {Readonly<number[]>} */
38947
39729
  #skipStatusCodes;
38948
39730
  /** @type {boolean} */
38949
39731
  #skipErrorResponses;
38950
- constructor(handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true } = {}) {
39732
+ /** @type {number} */
39733
+ #maxSize;
39734
+ /** @type {number} */
39735
+ #decompressedSize = 0;
39736
+ /** @type {boolean} */
39737
+ #terminated = false;
39738
+ /** @type {boolean} */
39739
+ #inputEnded = false;
39740
+ constructor(handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true, maxSize = defaultMaxSize } = {}) {
39741
+ if (!Number.isSafeInteger(maxSize) || maxSize < 1) {
39742
+ throw new InvalidArgumentError("maxSize must be a positive integer");
39743
+ }
38951
39744
  super(handler);
38952
39745
  this.#skipStatusCodes = skipStatusCodes;
38953
39746
  this.#skipErrorResponses = skipErrorResponses;
39747
+ this.#maxSize = maxSize;
38954
39748
  }
38955
39749
  /**
38956
39750
  * Determines if decompression should be skipped based on encoding and status code
@@ -38968,7 +39762,7 @@ var require_decompress = __commonJS({
38968
39762
  * Creates a chain of decompressors for multiple content encodings
38969
39763
  *
38970
39764
  * @param {string} encodings - Comma-separated list of content encodings
38971
- * @returns {Array<DecompressorStream>} - Array of decompressor streams
39765
+ * @returns {Array<Transform>} - Array of decompressor and limiting streams
38972
39766
  * @throws {Error} - If the number of content-encodings exceeds the maximum allowed
38973
39767
  */
38974
39768
  #createDecompressionChain(encodings) {
@@ -38987,7 +39781,33 @@ var require_decompress = __commonJS({
38987
39781
  }
38988
39782
  decompressors.push(supportedEncodings[encoding]());
38989
39783
  }
38990
- return decompressors;
39784
+ if (decompressors.length < 2) {
39785
+ return decompressors;
39786
+ }
39787
+ const streams = [];
39788
+ for (let i = 0; i < decompressors.length; i++) {
39789
+ streams.push(decompressors[i]);
39790
+ if (i < decompressors.length - 1) {
39791
+ streams.push(createMaxSizeLimiter(this.#maxSize));
39792
+ }
39793
+ }
39794
+ return streams;
39795
+ }
39796
+ /**
39797
+ * Stops decompression and reports an error.
39798
+ * @param {Controller} controller - The controller to coordinate with
39799
+ * @param {Error} error - The decompression error
39800
+ * @returns {void}
39801
+ */
39802
+ #fail(controller, error) {
39803
+ if (this.#terminated) {
39804
+ return;
39805
+ }
39806
+ if (this.#inputEnded) {
39807
+ this.onResponseError(controller, error);
39808
+ } else {
39809
+ controller.abort(error);
39810
+ }
38991
39811
  }
38992
39812
  /**
38993
39813
  * Sets up event handlers for a decompressor stream using readable events
@@ -38997,8 +39817,19 @@ var require_decompress = __commonJS({
38997
39817
  */
38998
39818
  #setupDecompressorEvents(decompressor, controller) {
38999
39819
  decompressor.on("readable", () => {
39820
+ if (this.#terminated) {
39821
+ return;
39822
+ }
39000
39823
  let chunk2;
39001
39824
  while ((chunk2 = decompressor.read()) !== null) {
39825
+ const decompressedSize = this.#decompressedSize + chunk2.length;
39826
+ if (decompressedSize > this.#maxSize) {
39827
+ this.#fail(controller, new ResponseExceededMaxSizeError(
39828
+ `Decompressed response size (${decompressedSize}) exceeded maxSize (${this.#maxSize})`
39829
+ ));
39830
+ return;
39831
+ }
39832
+ this.#decompressedSize = decompressedSize;
39002
39833
  const result = super.onResponseData(controller, chunk2);
39003
39834
  if (result === false) {
39004
39835
  break;
@@ -39006,7 +39837,7 @@ var require_decompress = __commonJS({
39006
39837
  }
39007
39838
  });
39008
39839
  decompressor.on("error", (error) => {
39009
- super.onResponseError(controller, error);
39840
+ this.#fail(controller, error);
39010
39841
  });
39011
39842
  }
39012
39843
  /**
@@ -39018,7 +39849,12 @@ var require_decompress = __commonJS({
39018
39849
  const decompressor = this.#decompressors[0];
39019
39850
  this.#setupDecompressorEvents(decompressor, controller);
39020
39851
  decompressor.on("end", () => {
39021
- super.onResponseEnd(controller, {});
39852
+ if (this.#terminated) {
39853
+ return;
39854
+ }
39855
+ this.#terminated = true;
39856
+ this.#cleanupDecompressors();
39857
+ super.onResponseEnd(controller, this.#trailers);
39022
39858
  });
39023
39859
  }
39024
39860
  /**
@@ -39030,11 +39866,16 @@ var require_decompress = __commonJS({
39030
39866
  const lastDecompressor = this.#decompressors[this.#decompressors.length - 1];
39031
39867
  this.#setupDecompressorEvents(lastDecompressor, controller);
39032
39868
  pipeline(this.#decompressors, (err2) => {
39869
+ if (this.#terminated) {
39870
+ return;
39871
+ }
39033
39872
  if (err2) {
39034
- super.onResponseError(controller, err2);
39873
+ this.#fail(controller, err2);
39035
39874
  return;
39036
39875
  }
39037
- super.onResponseEnd(controller, {});
39876
+ this.#terminated = true;
39877
+ this.#cleanupDecompressors();
39878
+ super.onResponseEnd(controller, this.#trailers);
39038
39879
  });
39039
39880
  }
39040
39881
  /**
@@ -39063,6 +39904,29 @@ var require_decompress = __commonJS({
39063
39904
  }
39064
39905
  this.#decompressors = decompressors;
39065
39906
  const { "content-encoding": _, "content-length": __, ...newHeaders } = headers;
39907
+ if (controller?.rawHeaders) {
39908
+ const rawHeaders = controller.rawHeaders;
39909
+ if (Array.isArray(rawHeaders)) {
39910
+ const filteredHeaders = [];
39911
+ for (let i = 0; i < rawHeaders.length; i += 2) {
39912
+ const headerName = rawHeaders[i];
39913
+ const name = Buffer.isBuffer(headerName) ? headerName.toString("latin1") : `${headerName}`;
39914
+ const lowerName = name.toLowerCase();
39915
+ if (lowerName === "content-encoding" || lowerName === "content-length") {
39916
+ continue;
39917
+ }
39918
+ filteredHeaders.push(rawHeaders[i], rawHeaders[i + 1]);
39919
+ }
39920
+ rawHeaders.splice(0, rawHeaders.length, ...filteredHeaders);
39921
+ } else if (typeof rawHeaders === "object") {
39922
+ for (const name of Object.keys(rawHeaders)) {
39923
+ const lowerName = name.toLowerCase();
39924
+ if (lowerName === "content-encoding" || lowerName === "content-length") {
39925
+ delete rawHeaders[name];
39926
+ }
39927
+ }
39928
+ }
39929
+ }
39066
39930
  if (this.#decompressors.length === 1) {
39067
39931
  this.#setupSingleDecompressor(controller);
39068
39932
  } else {
@@ -39089,8 +39953,9 @@ var require_decompress = __commonJS({
39089
39953
  */
39090
39954
  onResponseEnd(controller, trailers) {
39091
39955
  if (this.#decompressors.length > 0) {
39956
+ this.#inputEnded = true;
39957
+ this.#trailers = trailers;
39092
39958
  this.#decompressors[0].end();
39093
- this.#cleanupDecompressors();
39094
39959
  return;
39095
39960
  }
39096
39961
  super.onResponseEnd(controller, trailers);
@@ -39101,12 +39966,14 @@ var require_decompress = __commonJS({
39101
39966
  * @returns {void}
39102
39967
  */
39103
39968
  onResponseError(controller, err2) {
39104
- if (this.#decompressors.length > 0) {
39105
- for (const decompressor of this.#decompressors) {
39106
- decompressor.destroy(err2);
39107
- }
39108
- this.#cleanupDecompressors();
39969
+ if (this.#terminated) {
39970
+ return;
39109
39971
  }
39972
+ this.#terminated = true;
39973
+ for (const decompressor of this.#decompressors) {
39974
+ decompressor.destroy();
39975
+ }
39976
+ this.#cleanupDecompressors();
39110
39977
  super.onResponseError(controller, err2);
39111
39978
  }
39112
39979
  };
@@ -39738,7 +40605,7 @@ var require_sqlite_cache_store = __commonJS({
39738
40605
  SELECT
39739
40606
  id
39740
40607
  FROM cacheInterceptorV${VERSION}
39741
- ORDER BY cachedAt DESC
40608
+ ORDER BY cachedAt ASC
39742
40609
  LIMIT ?
39743
40610
  )
39744
40611
  `);
@@ -39793,7 +40660,6 @@ var require_sqlite_cache_store = __commonJS({
39793
40660
  existingValue.id
39794
40661
  );
39795
40662
  } else {
39796
- this.#prune();
39797
40663
  this.#insertValueQuery.run(
39798
40664
  url,
39799
40665
  key.method,
@@ -39808,6 +40674,7 @@ var require_sqlite_cache_store = __commonJS({
39808
40674
  value.cachedAt,
39809
40675
  value.staleAt
39810
40676
  );
40677
+ this.#prune();
39811
40678
  }
39812
40679
  }
39813
40680
  /**
@@ -39895,7 +40762,7 @@ var require_sqlite_cache_store = __commonJS({
39895
40762
  const now = Date.now();
39896
40763
  for (const value of values) {
39897
40764
  if (now >= value.deleteAt && !canBeExpired) {
39898
- return void 0;
40765
+ continue;
39899
40766
  }
39900
40767
  let matches = true;
39901
40768
  if (value.vary) {
@@ -39925,7 +40792,12 @@ var require_sqlite_cache_store = __commonJS({
39925
40792
  if (lhs.length !== rhs.length) {
39926
40793
  return false;
39927
40794
  }
39928
- return lhs.every((x, i) => x === rhs[i]);
40795
+ for (let i = 0; i < lhs.length; i++) {
40796
+ if (lhs[i] !== rhs[i]) {
40797
+ return false;
40798
+ }
40799
+ }
40800
+ return true;
39929
40801
  }
39930
40802
  return lhs === rhs;
39931
40803
  }
@@ -42214,7 +43086,7 @@ var require_fetch = __commonJS({
42214
43086
  cacheState = "";
42215
43087
  }
42216
43088
  let responseStatus = 0;
42217
- if (fetchParams.request.mode !== "navigator" || !response.hasCrossOriginRedirects) {
43089
+ if (fetchParams.request.mode !== "navigate" || !response.hasCrossOriginRedirects) {
42218
43090
  responseStatus = response.status;
42219
43091
  const mimeType = extractMimeType(response.headersList);
42220
43092
  if (mimeType !== "failure") {
@@ -42378,7 +43250,7 @@ var require_fetch = __commonJS({
42378
43250
  if (contentLength != null) {
42379
43251
  contentLengthHeaderValue = isomorphicEncode(`${contentLength}`);
42380
43252
  }
42381
- if (contentLengthHeaderValue != null) {
43253
+ if (contentLengthHeaderValue != null && !httpRequest.headersList.contains("content-length", true)) {
42382
43254
  httpRequest.headersList.append("content-length", contentLengthHeaderValue, true);
42383
43255
  }
42384
43256
  if (contentLength != null && httpRequest.keepalive) {
@@ -42456,10 +43328,10 @@ var require_fetch = __commonJS({
42456
43328
  response.rangeRequested = true;
42457
43329
  }
42458
43330
  response.requestIncludesCredentials = includeCredentials;
42459
- if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && isTraversableNavigable(request2.traversableForUserPrompts)) {
43331
+ if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && (request2.useURLCredentials !== void 0 || isTraversableNavigable(request2.traversableForUserPrompts))) {
42460
43332
  if (request2.body != null) {
42461
43333
  if (request2.body.source == null) {
42462
- return makeNetworkError("expected non-null body source");
43334
+ return response;
42463
43335
  }
42464
43336
  request2.body = safelyExtractBody(request2.body.source)[0];
42465
43337
  }
@@ -42701,7 +43573,15 @@ var require_fetch = __commonJS({
42701
43573
  }
42702
43574
  const headersList = new HeadersList();
42703
43575
  for (let i = 0; i < rawHeaders.length; i += 2) {
42704
- headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString("latin1"), true);
43576
+ const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i]);
43577
+ const value = rawHeaders[i + 1];
43578
+ if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) {
43579
+ for (const val of value) {
43580
+ headersList.append(nameStr, val.toString("latin1"), true);
43581
+ }
43582
+ } else {
43583
+ headersList.append(nameStr, value.toString("latin1"), true);
43584
+ }
42705
43585
  }
42706
43586
  const location = headersList.get("location", true);
42707
43587
  this.body = new Readable({ read: resume });
@@ -42815,7 +43695,15 @@ var require_fetch = __commonJS({
42815
43695
  }
42816
43696
  const headersList = new HeadersList();
42817
43697
  for (let i = 0; i < rawHeaders.length; i += 2) {
42818
- headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString("latin1"), true);
43698
+ const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i]);
43699
+ const value = rawHeaders[i + 1];
43700
+ if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) {
43701
+ for (const val of value) {
43702
+ headersList.append(nameStr, val.toString("latin1"), true);
43703
+ }
43704
+ } else {
43705
+ headersList.append(nameStr, value.toString("latin1"), true);
43706
+ }
42819
43707
  }
42820
43708
  resolve2({
42821
43709
  status,
@@ -43605,14 +44493,48 @@ var require_util4 = __commonJS({
43605
44493
  for (let i = 0; i < path74.length; ++i) {
43606
44494
  const code = path74.charCodeAt(i);
43607
44495
  if (code < 32 || // exclude CTLs (0-31)
43608
- code === 127 || // DEL
44496
+ code > 126 || // exclude DEL and non-ascii
43609
44497
  code === 59) {
43610
44498
  throw new Error("Invalid cookie path");
43611
44499
  }
43612
44500
  }
43613
44501
  }
44502
+ function isLetterOrDigit(code) {
44503
+ return code >= 48 && code <= 57 || // 0-9
44504
+ code >= 65 && code <= 90 || // A-Z
44505
+ code >= 97 && code <= 122;
44506
+ }
43614
44507
  function validateCookieDomain(domain) {
43615
- if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) {
44508
+ if (domain === " ") {
44509
+ return;
44510
+ }
44511
+ if (domain.length > 255) {
44512
+ throw new Error("Invalid cookie domain");
44513
+ }
44514
+ let labelLength = 0;
44515
+ for (let i = 0; i < domain.length; ++i) {
44516
+ const code = domain.charCodeAt(i);
44517
+ if (code === 46) {
44518
+ if (labelLength === 0) {
44519
+ throw new Error("Invalid cookie domain");
44520
+ }
44521
+ if (domain.charCodeAt(i - 1) === 45) {
44522
+ throw new Error("Invalid cookie domain");
44523
+ }
44524
+ labelLength = 0;
44525
+ continue;
44526
+ }
44527
+ if (labelLength === 0 && !isLetterOrDigit(code)) {
44528
+ throw new Error("Invalid cookie domain");
44529
+ }
44530
+ if (!isLetterOrDigit(code) && code !== 45) {
44531
+ throw new Error("Invalid cookie domain");
44532
+ }
44533
+ if (++labelLength > 63) {
44534
+ throw new Error("Invalid cookie domain");
44535
+ }
44536
+ }
44537
+ if (labelLength === 0 || domain.charCodeAt(domain.length - 1) === 45) {
43616
44538
  throw new Error("Invalid cookie domain");
43617
44539
  }
43618
44540
  }
@@ -43695,7 +44617,11 @@ var require_util4 = __commonJS({
43695
44617
  throw new Error("Invalid unparsed");
43696
44618
  }
43697
44619
  const [key, ...value] = part.split("=");
43698
- out.push(`${key.trim()}=${value.join("=")}`);
44620
+ const trimmedKey = key.trim();
44621
+ const joinedValue = value.join("=");
44622
+ validateCookieName(trimmedKey);
44623
+ validateCookieValue(joinedValue);
44624
+ out.push(`${trimmedKey}=${joinedValue}`);
43699
44625
  }
43700
44626
  return out.join("; ");
43701
44627
  }
@@ -43718,7 +44644,6 @@ var require_parse = __commonJS({
43718
44644
  var { maxNameValuePairSize, maxAttributeValueSize } = require_constants4();
43719
44645
  var { isCTLExcludingHtab } = require_util4();
43720
44646
  var assert = require("assert");
43721
- var { unescape: qsUnescape } = require("querystring");
43722
44647
  function parseSetCookie(header) {
43723
44648
  if (isCTLExcludingHtab(header)) {
43724
44649
  return null;
@@ -43752,7 +44677,7 @@ var require_parse = __commonJS({
43752
44677
  }
43753
44678
  return {
43754
44679
  name,
43755
- value: qsUnescape(value),
44680
+ value,
43756
44681
  ...parseUnparsedAttributes(unparsedAttributes)
43757
44682
  };
43758
44683
  }
@@ -43826,18 +44751,14 @@ var require_parse = __commonJS({
43826
44751
  } else if (attributeNameLowercase === "httponly") {
43827
44752
  cookieAttributeList.httpOnly = true;
43828
44753
  } else if (attributeNameLowercase === "samesite") {
43829
- let enforcement = "Default";
43830
44754
  const attributeValueLowercase = attributeValue.toLowerCase();
43831
- if (attributeValueLowercase.includes("none")) {
43832
- enforcement = "None";
43833
- }
43834
- if (attributeValueLowercase.includes("strict")) {
43835
- enforcement = "Strict";
43836
- }
43837
- if (attributeValueLowercase.includes("lax")) {
43838
- enforcement = "Lax";
44755
+ if (attributeValueLowercase === "none") {
44756
+ cookieAttributeList.sameSite = "None";
44757
+ } else if (attributeValueLowercase === "strict") {
44758
+ cookieAttributeList.sameSite = "Strict";
44759
+ } else if (attributeValueLowercase === "lax") {
44760
+ cookieAttributeList.sameSite = "Lax";
43839
44761
  }
43840
- cookieAttributeList.sameSite = enforcement;
43841
44762
  } else {
43842
44763
  cookieAttributeList.unparsed ??= [];
43843
44764
  cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`);
@@ -44682,7 +45603,7 @@ var require_connection = __commonJS({
44682
45603
  const secProtocol = response.headersList.get("Sec-WebSocket-Protocol");
44683
45604
  if (secProtocol !== null) {
44684
45605
  const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList);
44685
- if (!requestProtocols.includes(secProtocol)) {
45606
+ if (requestProtocols === null || !requestProtocols.includes(secProtocol)) {
44686
45607
  failWebsocketConnection(handler, 1002, "Protocol was not set in the opening handshake.");
44687
45608
  return;
44688
45609
  }
@@ -44758,27 +45679,26 @@ var require_permessage_deflate = __commonJS({
44758
45679
  var tail = Buffer.from([0, 0, 255, 255]);
44759
45680
  var kBuffer = /* @__PURE__ */ Symbol("kBuffer");
44760
45681
  var kLength = /* @__PURE__ */ Symbol("kLength");
44761
- var kDefaultMaxDecompressedSize = 4 * 1024 * 1024;
44762
45682
  var PerMessageDeflate = class {
44763
45683
  /** @type {import('node:zlib').InflateRaw} */
44764
45684
  #inflate;
44765
45685
  #options = {};
44766
- /** @type {boolean} */
44767
- #aborted = false;
44768
- /** @type {Function|null} */
44769
- #currentCallback = null;
45686
+ #maxPayloadSize = 0;
44770
45687
  /**
44771
45688
  * @param {Map<string, string>} extensions
44772
45689
  */
44773
- constructor(extensions) {
45690
+ constructor(extensions, options) {
44774
45691
  this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover");
44775
45692
  this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits");
45693
+ this.#maxPayloadSize = options.maxPayloadSize;
44776
45694
  }
45695
+ /**
45696
+ * Decompress a compressed payload.
45697
+ * @param {Buffer} chunk Compressed data
45698
+ * @param {boolean} fin Final fragment flag
45699
+ * @param {Function} callback Callback function
45700
+ */
44777
45701
  decompress(chunk2, fin, callback) {
44778
- if (this.#aborted) {
44779
- callback(new MessageSizeExceededError());
44780
- return;
44781
- }
44782
45702
  if (!this.#inflate) {
44783
45703
  let windowBits = Z_DEFAULT_WINDOWBITS;
44784
45704
  if (this.#options.serverMaxWindowBits) {
@@ -44797,20 +45717,12 @@ var require_permessage_deflate = __commonJS({
44797
45717
  this.#inflate[kBuffer] = [];
44798
45718
  this.#inflate[kLength] = 0;
44799
45719
  this.#inflate.on("data", (data) => {
44800
- if (this.#aborted) {
44801
- return;
44802
- }
44803
45720
  this.#inflate[kLength] += data.length;
44804
- if (this.#inflate[kLength] > kDefaultMaxDecompressedSize) {
44805
- this.#aborted = true;
45721
+ if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) {
45722
+ callback(new MessageSizeExceededError());
44806
45723
  this.#inflate.removeAllListeners();
44807
45724
  this.#inflate.destroy();
44808
45725
  this.#inflate = null;
44809
- if (this.#currentCallback) {
44810
- const cb = this.#currentCallback;
44811
- this.#currentCallback = null;
44812
- cb(new MessageSizeExceededError());
44813
- }
44814
45726
  return;
44815
45727
  }
44816
45728
  this.#inflate[kBuffer].push(data);
@@ -44820,19 +45732,17 @@ var require_permessage_deflate = __commonJS({
44820
45732
  callback(err2);
44821
45733
  });
44822
45734
  }
44823
- this.#currentCallback = callback;
44824
45735
  this.#inflate.write(chunk2);
44825
45736
  if (fin) {
44826
45737
  this.#inflate.write(tail);
44827
45738
  }
44828
45739
  this.#inflate.flush(() => {
44829
- if (this.#aborted || !this.#inflate) {
45740
+ if (!this.#inflate) {
44830
45741
  return;
44831
45742
  }
44832
45743
  const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]);
44833
45744
  this.#inflate[kBuffer].length = 0;
44834
45745
  this.#inflate[kLength] = 0;
44835
- this.#currentCallback = null;
44836
45746
  callback(null, full);
44837
45747
  });
44838
45748
  }
@@ -44873,16 +45783,23 @@ var require_receiver = __commonJS({
44873
45783
  #extensions;
44874
45784
  /** @type {import('./websocket').Handler} */
44875
45785
  #handler;
45786
+ /** @type {number} */
45787
+ #maxFragments;
45788
+ /** @type {number} */
45789
+ #maxPayloadSize;
44876
45790
  /**
44877
45791
  * @param {import('./websocket').Handler} handler
44878
45792
  * @param {Map<string, string>|null} extensions
45793
+ * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options]
44879
45794
  */
44880
- constructor(handler, extensions) {
45795
+ constructor(handler, extensions, options = {}) {
44881
45796
  super();
44882
45797
  this.#handler = handler;
44883
45798
  this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions;
45799
+ this.#maxFragments = options.maxFragments ?? 0;
45800
+ this.#maxPayloadSize = options.maxPayloadSize ?? 0;
44884
45801
  if (this.#extensions.has("permessage-deflate")) {
44885
- this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions));
45802
+ this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options));
44886
45803
  }
44887
45804
  }
44888
45805
  /**
@@ -44895,6 +45812,13 @@ var require_receiver = __commonJS({
44895
45812
  this.#loop = true;
44896
45813
  this.run(callback);
44897
45814
  }
45815
+ #validatePayloadLength() {
45816
+ if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) {
45817
+ failWebsocketConnection(this.#handler, 1009, "Payload size exceeds maximum allowed size");
45818
+ return false;
45819
+ }
45820
+ return true;
45821
+ }
44898
45822
  /**
44899
45823
  * Runs whenever a new chunk is received.
44900
45824
  * Callback is called whenever there are no more chunks buffering,
@@ -44954,6 +45878,9 @@ var require_receiver = __commonJS({
44954
45878
  if (payloadLength <= 125) {
44955
45879
  this.#info.payloadLength = payloadLength;
44956
45880
  this.#state = parserStates.READ_DATA;
45881
+ if (!this.#validatePayloadLength()) {
45882
+ return;
45883
+ }
44957
45884
  } else if (payloadLength === 126) {
44958
45885
  this.#state = parserStates.PAYLOADLENGTH_16;
44959
45886
  } else if (payloadLength === 127) {
@@ -44974,6 +45901,9 @@ var require_receiver = __commonJS({
44974
45901
  const buffer = this.consume(2);
44975
45902
  this.#info.payloadLength = buffer.readUInt16BE(0);
44976
45903
  this.#state = parserStates.READ_DATA;
45904
+ if (!this.#validatePayloadLength()) {
45905
+ return;
45906
+ }
44977
45907
  } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
44978
45908
  if (this.#byteOffset < 8) {
44979
45909
  return callback();
@@ -44987,6 +45917,9 @@ var require_receiver = __commonJS({
44987
45917
  }
44988
45918
  this.#info.payloadLength = lower;
44989
45919
  this.#state = parserStates.READ_DATA;
45920
+ if (!this.#validatePayloadLength()) {
45921
+ return;
45922
+ }
44990
45923
  } else if (this.#state === parserStates.READ_DATA) {
44991
45924
  if (this.#byteOffset < this.#info.payloadLength) {
44992
45925
  return callback();
@@ -44997,30 +45930,43 @@ var require_receiver = __commonJS({
44997
45930
  this.#state = parserStates.INFO;
44998
45931
  } else {
44999
45932
  if (!this.#info.compressed) {
45000
- this.writeFragments(body);
45933
+ if (!this.writeFragments(body)) {
45934
+ return;
45935
+ }
45001
45936
  if (!this.#info.fragmented && this.#info.fin) {
45002
45937
  websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
45003
45938
  }
45004
45939
  this.#state = parserStates.INFO;
45005
45940
  } else {
45006
- this.#extensions.get("permessage-deflate").decompress(body, this.#info.fin, (error, data) => {
45007
- if (error) {
45008
- const code = error instanceof MessageSizeExceededError ? 1009 : 1007;
45009
- failWebsocketConnection(this.#handler, code, error.message);
45010
- return;
45011
- }
45012
- this.writeFragments(data);
45013
- if (!this.#info.fin) {
45014
- this.#state = parserStates.INFO;
45941
+ this.#extensions.get("permessage-deflate").decompress(
45942
+ body,
45943
+ this.#info.fin,
45944
+ (error, data) => {
45945
+ if (error) {
45946
+ const code = error instanceof MessageSizeExceededError ? 1009 : 1007;
45947
+ failWebsocketConnection(this.#handler, code, error.message);
45948
+ return;
45949
+ }
45950
+ if (!this.writeFragments(data)) {
45951
+ return;
45952
+ }
45953
+ if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) {
45954
+ failWebsocketConnection(this.#handler, 1009, new MessageSizeExceededError().message);
45955
+ return;
45956
+ }
45957
+ if (!this.#info.fin) {
45958
+ this.#state = parserStates.INFO;
45959
+ this.#loop = true;
45960
+ this.run(callback);
45961
+ return;
45962
+ }
45963
+ websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
45015
45964
  this.#loop = true;
45965
+ this.#state = parserStates.INFO;
45016
45966
  this.run(callback);
45017
- return;
45018
- }
45019
- websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
45020
- this.#loop = true;
45021
- this.#state = parserStates.INFO;
45022
- this.run(callback);
45023
- });
45967
+ },
45968
+ this.#fragmentsBytes
45969
+ );
45024
45970
  this.#loop = false;
45025
45971
  break;
45026
45972
  }
@@ -45068,8 +46014,13 @@ var require_receiver = __commonJS({
45068
46014
  }
45069
46015
  }
45070
46016
  writeFragments(fragment) {
46017
+ if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) {
46018
+ failWebsocketConnection(this.#handler, 1008, "Too many message fragments");
46019
+ return false;
46020
+ }
45071
46021
  this.#fragmentsBytes += fragment.length;
45072
46022
  this.#fragments.push(fragment);
46023
+ return true;
45073
46024
  }
45074
46025
  consumeFragments() {
45075
46026
  const fragments = this.#fragments;
@@ -45536,7 +46487,13 @@ var require_websocket = __commonJS({
45536
46487
  */
45537
46488
  #onConnectionEstablished(response, parsedExtensions) {
45538
46489
  this.#handler.socket = response.socket;
45539
- const parser = new ByteParser(this.#handler, parsedExtensions);
46490
+ const webSocketOptions = this.#handler.controller.dispatcher?.webSocketOptions;
46491
+ const maxFragments = webSocketOptions?.maxFragments;
46492
+ const maxPayloadSize = webSocketOptions?.maxPayloadSize;
46493
+ const parser = new ByteParser(this.#handler, parsedExtensions, {
46494
+ maxFragments,
46495
+ maxPayloadSize
46496
+ });
45540
46497
  parser.on("drain", () => this.#handler.onParserDrain());
45541
46498
  parser.on("error", (err2) => this.#handler.onParserError(err2));
45542
46499
  this.#parser = parser;
@@ -45842,9 +46799,9 @@ var require_websocketstream = __commonJS({
45842
46799
  #readableStream;
45843
46800
  /** @type {ReadableStreamDefaultController} */
45844
46801
  #readableStreamController;
45845
- // Each WebSocketStream object has an associated writable stream , which is a WritableStream .
45846
- /** @type {WritableStream} */
45847
- #writableStream;
46802
+ // Retain the controller so the writable stream can be errored while locked.
46803
+ /** @type {WritableStreamDefaultController} */
46804
+ #writableStreamController;
45848
46805
  // Each WebSocketStream object has an associated boolean handshake aborted , which is initially false.
45849
46806
  #handshakeAborted = false;
45850
46807
  /** @type {import('../websocket').Handler} */
@@ -45980,7 +46937,12 @@ var require_websocketstream = __commonJS({
45980
46937
  /** @type {import('../websocket').Handler['onConnectionEstablished']} */
45981
46938
  #onConnectionEstablished(response, parsedExtensions) {
45982
46939
  this.#handler.socket = response.socket;
45983
- const parser = new ByteParser(this.#handler, parsedExtensions);
46940
+ const maxFragments = this.#handler.controller.dispatcher?.webSocketOptions?.maxFragments;
46941
+ const maxPayloadSize = this.#handler.controller.dispatcher?.webSocketOptions?.maxPayloadSize;
46942
+ const parser = new ByteParser(this.#handler, parsedExtensions, {
46943
+ maxFragments,
46944
+ maxPayloadSize
46945
+ });
45984
46946
  parser.on("drain", () => this.#handler.onParserDrain());
45985
46947
  parser.on("error", (err2) => this.#handler.onParserError(err2));
45986
46948
  this.#parser = parser;
@@ -45991,21 +46953,17 @@ var require_websocketstream = __commonJS({
45991
46953
  start: (controller) => {
45992
46954
  this.#readableStreamController = controller;
45993
46955
  },
45994
- pull(controller) {
45995
- let chunk2;
45996
- while (controller.desiredSize > 0 && (chunk2 = response.socket.read()) !== null) {
45997
- controller.enqueue(chunk2);
45998
- }
45999
- },
46000
46956
  cancel: (reason) => this.#cancel(reason)
46001
46957
  });
46002
46958
  const writable = new WritableStream({
46959
+ start: (controller) => {
46960
+ this.#writableStreamController = controller;
46961
+ },
46003
46962
  write: (chunk2) => this.#write(chunk2),
46004
46963
  close: () => closeWebSocketConnection(this.#handler, null, null),
46005
46964
  abort: (reason) => this.#closeUsingReason(reason)
46006
46965
  });
46007
46966
  this.#readableStream = readable;
46008
- this.#writableStream = writable;
46009
46967
  this.#openedPromise.resolve({
46010
46968
  extensions,
46011
46969
  protocol,
@@ -46023,7 +46981,7 @@ var require_websocketstream = __commonJS({
46023
46981
  try {
46024
46982
  chunk2 = utf8Decode(data);
46025
46983
  } catch {
46026
- failWebsocketConnection(this.#handler, "Received invalid UTF-8 in text frame.");
46984
+ failWebsocketConnection(this.#handler, 1007, "Received invalid UTF-8 in text frame.");
46027
46985
  return;
46028
46986
  }
46029
46987
  } else if (type === opcodes.BINARY) {
@@ -46049,9 +47007,7 @@ var require_websocketstream = __commonJS({
46049
47007
  const reason = result?.reason == null ? "" : utf8DecodeBytes(Buffer.from(result.reason));
46050
47008
  if (wasClean) {
46051
47009
  this.#readableStreamController.close();
46052
- if (!this.#writableStream.locked) {
46053
- this.#writableStream.abort(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
46054
- }
47010
+ this.#writableStreamController.error(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
46055
47011
  this.#closedPromise.resolve({
46056
47012
  closeCode: code,
46057
47013
  reason
@@ -46059,7 +47015,7 @@ var require_websocketstream = __commonJS({
46059
47015
  } else {
46060
47016
  const error = createUnvalidatedWebSocketError("unclean close", code, reason);
46061
47017
  this.#readableStreamController?.error(error);
46062
- this.#writableStream?.abort(error);
47018
+ this.#writableStreamController?.error(error);
46063
47019
  this.#closedPromise.reject(error);
46064
47020
  }
46065
47021
  }
@@ -46154,6 +47110,40 @@ var require_eventsource_stream = __commonJS({
46154
47110
  var CR = 13;
46155
47111
  var COLON = 58;
46156
47112
  var SPACE = 32;
47113
+ var DATA = Buffer.from("data");
47114
+ var EVENT = Buffer.from("event");
47115
+ var ID = Buffer.from("id");
47116
+ var RETRY = Buffer.from("retry");
47117
+ function isASCIINumberBytes(buffer, start) {
47118
+ if (start >= buffer.length) {
47119
+ return false;
47120
+ }
47121
+ for (let i = start; i < buffer.length; i++) {
47122
+ if (buffer[i] < 48 || buffer[i] > 57) {
47123
+ return false;
47124
+ }
47125
+ }
47126
+ return true;
47127
+ }
47128
+ function isValidLastEventIdBytes(buffer, start) {
47129
+ for (let i = start; i < buffer.length; i++) {
47130
+ if (buffer[i] === 0) {
47131
+ return false;
47132
+ }
47133
+ }
47134
+ return true;
47135
+ }
47136
+ function isFieldName(line, length, field) {
47137
+ if (length !== field.length) {
47138
+ return false;
47139
+ }
47140
+ for (let i = 0; i < length; i++) {
47141
+ if (line[i] !== field[i]) {
47142
+ return false;
47143
+ }
47144
+ }
47145
+ return true;
47146
+ }
46157
47147
  var EventSourceStream = class extends Transform {
46158
47148
  /**
46159
47149
  * @type {eventSourceSettings}
@@ -46173,10 +47163,13 @@ var require_eventsource_stream = __commonJS({
46173
47163
  */
46174
47164
  eventEndCheck = false;
46175
47165
  /**
46176
- * @type {Buffer|null}
47166
+ * @type {Buffer[]}
46177
47167
  */
46178
- buffer = null;
47168
+ chunks = [];
47169
+ chunkIndex = 0;
46179
47170
  pos = 0;
47171
+ lineChunkIndex = 0;
47172
+ linePos = 0;
46180
47173
  event = {
46181
47174
  data: void 0,
46182
47175
  event: void 0,
@@ -46208,63 +47201,30 @@ var require_eventsource_stream = __commonJS({
46208
47201
  callback();
46209
47202
  return;
46210
47203
  }
46211
- if (this.buffer) {
46212
- this.buffer = Buffer.concat([this.buffer, chunk2]);
46213
- } else {
46214
- this.buffer = chunk2;
46215
- }
47204
+ this.chunks.push(chunk2);
46216
47205
  if (this.checkBOM) {
46217
- switch (this.buffer.length) {
46218
- case 1:
46219
- if (this.buffer[0] === BOM[0]) {
46220
- callback();
46221
- return;
46222
- }
46223
- this.checkBOM = false;
46224
- callback();
46225
- return;
46226
- case 2:
46227
- if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) {
46228
- callback();
46229
- return;
46230
- }
46231
- this.checkBOM = false;
46232
- break;
46233
- case 3:
46234
- if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
46235
- this.buffer = Buffer.alloc(0);
46236
- this.checkBOM = false;
46237
- callback();
46238
- return;
46239
- }
46240
- this.checkBOM = false;
46241
- break;
46242
- default:
46243
- if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
46244
- this.buffer = this.buffer.subarray(3);
46245
- }
46246
- this.checkBOM = false;
46247
- break;
47206
+ if (this.handleBOM()) {
47207
+ callback();
47208
+ return;
46248
47209
  }
46249
47210
  }
46250
- while (this.pos < this.buffer.length) {
47211
+ while (this.hasCurrentByte()) {
47212
+ const byte = this.currentByte();
46251
47213
  if (this.eventEndCheck) {
46252
47214
  if (this.crlfCheck) {
46253
- if (this.buffer[this.pos] === LF) {
46254
- this.buffer = this.buffer.subarray(this.pos + 1);
46255
- this.pos = 0;
47215
+ if (byte === LF) {
46256
47216
  this.crlfCheck = false;
47217
+ this.consumeCurrentByte();
46257
47218
  continue;
46258
47219
  }
46259
47220
  this.crlfCheck = false;
46260
47221
  }
46261
- if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
46262
- if (this.buffer[this.pos] === CR) {
47222
+ if (byte === LF || byte === CR) {
47223
+ if (byte === CR) {
46263
47224
  this.crlfCheck = true;
46264
47225
  }
46265
- this.buffer = this.buffer.subarray(this.pos + 1);
46266
- this.pos = 0;
46267
- if (this.event.data !== void 0 || this.event.event || this.event.id !== void 0 || this.event.retry) {
47226
+ this.consumeCurrentByte();
47227
+ if (this.hasPendingEvent()) {
46268
47228
  this.processEvent(this.event);
46269
47229
  }
46270
47230
  this.clearEvent();
@@ -46273,17 +47233,16 @@ var require_eventsource_stream = __commonJS({
46273
47233
  this.eventEndCheck = false;
46274
47234
  continue;
46275
47235
  }
46276
- if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
46277
- if (this.buffer[this.pos] === CR) {
47236
+ if (byte === LF || byte === CR) {
47237
+ if (byte === CR) {
46278
47238
  this.crlfCheck = true;
46279
47239
  }
46280
- this.parseLine(this.buffer.subarray(0, this.pos), this.event);
46281
- this.buffer = this.buffer.subarray(this.pos + 1);
46282
- this.pos = 0;
47240
+ this.parseLine(this.readLine(), this.event);
47241
+ this.consumeCurrentByte();
46283
47242
  this.eventEndCheck = true;
46284
47243
  continue;
46285
47244
  }
46286
- this.pos++;
47245
+ this.advanceCursor();
46287
47246
  }
46288
47247
  callback();
46289
47248
  }
@@ -46299,43 +47258,42 @@ var require_eventsource_stream = __commonJS({
46299
47258
  if (colonPosition === 0) {
46300
47259
  return;
46301
47260
  }
46302
- let field = "";
46303
- let value = "";
47261
+ let fieldLength = line.length;
47262
+ let valueStart = line.length;
46304
47263
  if (colonPosition !== -1) {
46305
- field = line.subarray(0, colonPosition).toString("utf8");
46306
- let valueStart = colonPosition + 1;
47264
+ fieldLength = colonPosition;
47265
+ valueStart = colonPosition + 1;
46307
47266
  if (line[valueStart] === SPACE) {
46308
47267
  ++valueStart;
46309
47268
  }
46310
- value = line.subarray(valueStart).toString("utf8");
46311
- } else {
46312
- field = line.toString("utf8");
46313
- value = "";
46314
47269
  }
46315
- switch (field) {
46316
- case "data":
46317
- if (event[field] === void 0) {
46318
- event[field] = value;
46319
- } else {
46320
- event[field] += `
47270
+ if (isFieldName(line, fieldLength, DATA)) {
47271
+ const value = line.toString("utf8", valueStart);
47272
+ if (event.data === void 0) {
47273
+ event.data = value;
47274
+ } else {
47275
+ event.data += `
46321
47276
  ${value}`;
46322
- }
46323
- break;
46324
- case "retry":
46325
- if (isASCIINumber(value)) {
46326
- event[field] = value;
46327
- }
46328
- break;
46329
- case "id":
46330
- if (isValidLastEventId(value)) {
46331
- event[field] = value;
46332
- }
46333
- break;
46334
- case "event":
46335
- if (value.length > 0) {
46336
- event[field] = value;
46337
- }
46338
- break;
47277
+ }
47278
+ return;
47279
+ }
47280
+ if (isFieldName(line, fieldLength, RETRY)) {
47281
+ if (isASCIINumberBytes(line, valueStart)) {
47282
+ event.retry = line.toString("utf8", valueStart);
47283
+ }
47284
+ return;
47285
+ }
47286
+ if (isFieldName(line, fieldLength, ID)) {
47287
+ if (isValidLastEventIdBytes(line, valueStart)) {
47288
+ event.id = line.toString("utf8", valueStart);
47289
+ }
47290
+ return;
47291
+ }
47292
+ if (isFieldName(line, fieldLength, EVENT)) {
47293
+ const value = line.toString("utf8", valueStart);
47294
+ if (value.length > 0) {
47295
+ event.event = value;
47296
+ }
46339
47297
  }
46340
47298
  }
46341
47299
  /**
@@ -46360,12 +47318,120 @@ ${value}`;
46360
47318
  }
46361
47319
  }
46362
47320
  clearEvent() {
46363
- this.event = {
46364
- data: void 0,
46365
- event: void 0,
46366
- id: void 0,
46367
- retry: void 0
46368
- };
47321
+ this.event.data = void 0;
47322
+ this.event.event = void 0;
47323
+ this.event.id = void 0;
47324
+ this.event.retry = void 0;
47325
+ }
47326
+ hasPendingEvent() {
47327
+ return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0;
47328
+ }
47329
+ hasCurrentByte() {
47330
+ return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length;
47331
+ }
47332
+ currentByte() {
47333
+ return this.chunks[this.chunkIndex][this.pos];
47334
+ }
47335
+ consumeCurrentByte() {
47336
+ this.advanceCursor();
47337
+ this.syncLineStartToCursor();
47338
+ }
47339
+ advanceCursor() {
47340
+ this.pos++;
47341
+ while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) {
47342
+ this.chunkIndex++;
47343
+ this.pos = 0;
47344
+ }
47345
+ }
47346
+ syncLineStartToCursor() {
47347
+ this.lineChunkIndex = this.chunkIndex;
47348
+ this.linePos = this.pos;
47349
+ this.dropConsumedChunks();
47350
+ }
47351
+ dropConsumedChunks() {
47352
+ while (this.lineChunkIndex > 0) {
47353
+ this.chunks.shift();
47354
+ this.lineChunkIndex--;
47355
+ this.chunkIndex--;
47356
+ }
47357
+ if (this.chunkIndex === this.chunks.length) {
47358
+ this.chunks.length = 0;
47359
+ this.chunkIndex = 0;
47360
+ this.pos = 0;
47361
+ this.lineChunkIndex = 0;
47362
+ this.linePos = 0;
47363
+ }
47364
+ }
47365
+ readLine() {
47366
+ if (this.lineChunkIndex === this.chunkIndex) {
47367
+ return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos);
47368
+ }
47369
+ const chunks = [];
47370
+ let length = 0;
47371
+ for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) {
47372
+ const chunk2 = this.chunks[i];
47373
+ const start = i === this.lineChunkIndex ? this.linePos : 0;
47374
+ const end = i === this.chunkIndex ? this.pos : chunk2.length;
47375
+ const slice = chunk2.subarray(start, end);
47376
+ length += slice.length;
47377
+ chunks.push(slice);
47378
+ }
47379
+ return Buffer.concat(chunks, length);
47380
+ }
47381
+ peekBufferedByte(offset) {
47382
+ let chunkIndex = this.lineChunkIndex;
47383
+ let pos = this.linePos;
47384
+ while (chunkIndex < this.chunks.length) {
47385
+ const chunk2 = this.chunks[chunkIndex];
47386
+ const remaining = chunk2.length - pos;
47387
+ if (offset < remaining) {
47388
+ return chunk2[pos + offset];
47389
+ }
47390
+ offset -= remaining;
47391
+ chunkIndex++;
47392
+ pos = 0;
47393
+ }
47394
+ }
47395
+ discardLeadingBytes(count) {
47396
+ while (count > 0 && this.lineChunkIndex < this.chunks.length) {
47397
+ const chunk2 = this.chunks[this.lineChunkIndex];
47398
+ const remaining = chunk2.length - this.linePos;
47399
+ if (count < remaining) {
47400
+ this.linePos += count;
47401
+ count = 0;
47402
+ } else {
47403
+ count -= remaining;
47404
+ this.lineChunkIndex++;
47405
+ this.linePos = 0;
47406
+ }
47407
+ }
47408
+ this.chunkIndex = this.lineChunkIndex;
47409
+ this.pos = this.linePos;
47410
+ this.dropConsumedChunks();
47411
+ }
47412
+ handleBOM() {
47413
+ const first = this.peekBufferedByte(0);
47414
+ const second = this.peekBufferedByte(1);
47415
+ const third = this.peekBufferedByte(2);
47416
+ if (second === void 0) {
47417
+ if (first === BOM[0]) {
47418
+ return true;
47419
+ }
47420
+ this.checkBOM = false;
47421
+ return true;
47422
+ }
47423
+ if (third === void 0) {
47424
+ if (first === BOM[0] && second === BOM[1]) {
47425
+ return true;
47426
+ }
47427
+ this.checkBOM = false;
47428
+ return false;
47429
+ }
47430
+ if (first === BOM[0] && second === BOM[1] && third === BOM[2]) {
47431
+ this.discardLeadingBytes(3);
47432
+ }
47433
+ this.checkBOM = false;
47434
+ return !this.hasCurrentByte();
46369
47435
  }
46370
47436
  };
46371
47437
  module2.exports = {
@@ -48278,33 +49344,39 @@ REQUIRED ACTIONS:
48278
49344
  1. Remove the hardcoded credential from your command or code.
48279
49345
  2. Use an environment variable or a dedicated secrets manager instead.
48280
49346
  3. Treat the leaked credential as compromised and rotate it immediately.
48281
- Do NOT attempt to bypass this check or pass the credential through another tool.`;
49347
+ Do NOT attempt to bypass this check or pass the credential through another tool.
49348
+ - Tell the user node9 blocked this and why, then ask how to proceed.`;
48282
49349
  }
48283
49350
  if (label2.includes("sql safety") && label2.includes("delete without where")) {
48284
49351
  return `NODE9: Blocked \u2014 DELETE without WHERE clause would wipe the entire table.
48285
49352
  INSTRUCTION: Add a WHERE clause to scope the deletion (e.g. WHERE id = <value>).
48286
- Do NOT retry without a WHERE clause.`;
49353
+ Do NOT retry without a WHERE clause.
49354
+ - Tell the user node9 blocked this and why, then ask how to proceed.`;
48287
49355
  }
48288
49356
  if (label2.includes("sql safety") && label2.includes("update without where")) {
48289
49357
  return `NODE9: Blocked \u2014 UPDATE without WHERE clause would update every row.
48290
49358
  INSTRUCTION: Add a WHERE clause to scope the update (e.g. WHERE id = <value>).
48291
- Do NOT retry without a WHERE clause.`;
49359
+ Do NOT retry without a WHERE clause.
49360
+ - Tell the user node9 blocked this and why, then ask how to proceed.`;
48292
49361
  }
48293
49362
  if (label2.includes("dangerous word")) {
48294
49363
  const match = blockedByLabel.match(/dangerous word: "([^"]+)"/i);
48295
49364
  const word = match?.[1] ?? "a dangerous keyword";
48296
49365
  return `NODE9: Blocked \u2014 command contains forbidden keyword "${word}".
48297
49366
  INSTRUCTION: Do NOT use "${word}". Use a non-destructive alternative.
48298
- Do NOT attempt to bypass this with shell tricks or aliases \u2014 it will be blocked again.`;
49367
+ Do NOT attempt to bypass this with shell tricks or aliases \u2014 it will be blocked again.
49368
+ - Tell the user node9 blocked this and why, then ask how to proceed.`;
48299
49369
  }
48300
49370
  if (label2.includes("path blocked") || label2.includes("sandbox")) {
48301
49371
  return `NODE9: Blocked \u2014 operation targets a path outside the allowed sandbox.
48302
49372
  INSTRUCTION: Move your output to an allowed directory such as /tmp/ or the project directory.
48303
- Do NOT retry on the same path.`;
49373
+ Do NOT retry on the same path.
49374
+ - Tell the user node9 blocked this and why, then ask how to proceed.`;
48304
49375
  }
48305
49376
  if (label2.includes("inline execution")) {
48306
49377
  return `NODE9: Blocked \u2014 inline code execution (e.g. bash -c "...") is not allowed.
48307
- INSTRUCTION: Use individual tool calls instead of embedding code in a shell string.`;
49378
+ INSTRUCTION: Use individual tool calls instead of embedding code in a shell string.
49379
+ - Tell the user node9 blocked this and why, then ask how to proceed.`;
48308
49380
  }
48309
49381
  if (label2.includes("strict mode")) {
48310
49382
  return `NODE9: Blocked \u2014 strict mode is active. All tool calls require explicit human approval.
@@ -48315,7 +49387,8 @@ INSTRUCTION: Inform the user this action is pending approval. Wait for them to a
48315
49387
  const rule = match?.[1] ?? "a policy rule";
48316
49388
  return `NODE9: Blocked \u2014 action "${rule}" is forbidden by security policy.
48317
49389
  INSTRUCTION: Do NOT use "${rule}". Find a read-only or non-destructive alternative.
48318
- Do NOT attempt to bypass this rule.`;
49390
+ Do NOT attempt to bypass this rule.
49391
+ - Tell the user node9 blocked this and why, then ask how to proceed.`;
48319
49392
  }
48320
49393
  const recovery = recoveryCommand ? `
48321
49394
  REQUIRED ACTION: Run \`${recoveryCommand}\` first, then retry your original command.` : "\n- Pivot to a non-destructive or read-only alternative.";