@workflow/web 4.1.25 → 4.1.27

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 (18) hide show
  1. package/build/client/assets/{encryption-BRhjWsZh.js → encryption-CVDhlDp_.js} +1 -1
  2. package/build/client/assets/{highlighted-body-B3W2YXNL-BRVsq_Ui.js → highlighted-body-B3W2YXNL-DNE7dweN.js} +1 -1
  3. package/build/client/assets/{home-CWZI6fn-.js → home-BcCTbe4i.js} +3 -3
  4. package/build/client/assets/{index-DZSXezpI.js → index-DhdkuKp5.js} +5 -1
  5. package/build/client/assets/{manifest-25c2e662.js → manifest-f88c7f34.js} +1 -1
  6. package/build/client/assets/{mermaid-3ZIDBTTL-871SHrja.js → mermaid-3ZIDBTTL-B1-N6W83.js} +9 -4
  7. package/build/client/assets/{root-8dRSI2dZ.js → root-C2Eu3fUP.js} +1 -1
  8. package/build/client/assets/{run-detail-CaG8UDwA.js → run-detail-CyImB2zR.js} +4 -4
  9. package/build/client/assets/{workflow-graph-viewer-C1On-L19.js → workflow-graph-viewer-lj3vdGSs.js} +2 -2
  10. package/build/server/assets/{app-C2ZMBpJF.js → app-uVbY_-qI.js} +1 -1
  11. package/build/server/assets/{highlighted-body-B3W2YXNL-CmiyUOiW.js → highlighted-body-B3W2YXNL-BAlPxI2y.js} +2 -2
  12. package/build/server/assets/{index-iPDTwQkr.js → index-ClImPOu-.js} +3 -3
  13. package/build/server/assets/{mermaid-3ZIDBTTL-Ku6qjB5F.js → mermaid-3ZIDBTTL-Ccs470KM.js} +2 -2
  14. package/build/server/assets/{server-build-BVUmxy06.js → server-build-tMGygzbW.js} +1736 -473
  15. package/build/server/assets/{token-CPIWEDbd.js → token-NxX4H9ze.js} +2 -2
  16. package/build/server/assets/{token-util-BszBIaAk.js → token-util-CXI_HnNu.js} +2 -2
  17. package/build/server/index.js +1 -1
  18. package/package.json +5 -5
@@ -18,7 +18,7 @@ import { createRequire as __wkfCreateRequire } from "node:module";
18
18
  if (typeof globalThis.require === "undefined") {
19
19
  globalThis.require = __wkfCreateRequire(import.meta.url);
20
20
  }
21
- import { a as requireReact, S as ServerRouter, c as createReadableStreamFromReadable, r as reactExports, g as getDefaultExportFromCjs, R as React, b as ReactExports, w as withComponentProps, d as withErrorBoundaryProps, M as Meta, L as Links, e as ScrollRestoration, f as Scripts, O as Outlet, u as useNavigate, h as useSearchParams, i as Link$1, j as useRouteError, k as isRouteErrorResponse, l as useLocation, m as useParams } from "./app-C2ZMBpJF.js";
21
+ import { a as requireReact, S as ServerRouter, c as createReadableStreamFromReadable, r as reactExports, g as getDefaultExportFromCjs, R as React, b as ReactExports, w as withComponentProps, d as withErrorBoundaryProps, M as Meta, L as Links, e as ScrollRestoration, f as Scripts, O as Outlet, u as useNavigate, h as useSearchParams, i as Link$1, j as useRouteError, k as isRouteErrorResponse, l as useLocation, m as useParams } from "./app-uVbY_-qI.js";
22
22
  import require$$0$5, { PassThrough, Transform as Transform$1 } from "node:stream";
23
23
  import require$$0 from "util";
24
24
  import require$$1 from "crypto";
@@ -49417,6 +49417,11 @@ function getWebRevivers() {
49417
49417
  BigInt: (value) => BigInt(value),
49418
49418
  BigInt64Array: (value) => new BigInt64Array(reviveArrayBuffer(value)),
49419
49419
  BigUint64Array: (value) => new BigUint64Array(reviveArrayBuffer(value)),
49420
+ // Deliberately not registered under `DataView`: payloads written before
49421
+ // core gained this reducer use devalue's built-in encoding, and a custom
49422
+ // reviver for that tag would strip their bounds and render the whole
49423
+ // backing buffer. See `getCommonReducers()` in core's `serialization.ts`.
49424
+ DataViewBytes: (value) => new DataView(reviveArrayBuffer(value)),
49420
49425
  Date: (value) => new Date(value),
49421
49426
  Error: (value) => {
49422
49427
  const error2 = new Error(value.message);
@@ -81968,7 +81973,7 @@ var tn = f("block", "before:content-[counter(line)]", "before:inline-block", "be
81968
81973
  var et = ({ className: e, language: t, style: o, isIncomplete: n, ...s2 }) => jsxRuntimeExports.jsx("div", { className: f("my-4 flex w-full flex-col gap-2 rounded-xl border border-border bg-sidebar p-2", e), "data-incomplete": n || void 0, "data-language": t, "data-streamdown": "code-block", style: { contentVisibility: "auto", containIntrinsicSize: "auto 200px", ...o }, ...s2 });
81969
81974
  var Se = reactExports.createContext({ code: "" }), de = () => reactExports.useContext(Se);
81970
81975
  var ot = ({ language: e }) => jsxRuntimeExports.jsx("div", { className: "flex h-8 items-center text-muted-foreground text-xs", "data-language": e, "data-streamdown": "code-block-header", children: jsxRuntimeExports.jsx("span", { className: "ml-1 font-mono lowercase", children: e }) });
81971
- var cn$1 = /\n+$/, dn = reactExports.lazy(() => import("./highlighted-body-B3W2YXNL-CmiyUOiW.js").then((e) => ({ default: e.HighlightedCodeBlockBody }))), rt = ({ code: e, language: t, className: o, children: n, isIncomplete: s2 = false, ...r2 }) => {
81976
+ var cn$1 = /\n+$/, dn = reactExports.lazy(() => import("./highlighted-body-B3W2YXNL-BAlPxI2y.js").then((e) => ({ default: e.HighlightedCodeBlockBody }))), rt = ({ code: e, language: t, className: o, children: n, isIncomplete: s2 = false, ...r2 }) => {
81972
81977
  let i = reactExports.useMemo(() => e.replace(cn$1, ""), [e]), c = reactExports.useMemo(() => ({ bg: "transparent", fg: "inherit", tokens: i.split(`
81973
81978
  `).map((a2) => [{ content: a2, color: "inherit", bgColor: "transparent", htmlStyle: {}, offset: 0 }]) }), [i]);
81974
81979
  return jsxRuntimeExports.jsx(Se.Provider, { value: { code: e }, children: jsxRuntimeExports.jsxs(et, { isIncomplete: s2, language: t, children: [jsxRuntimeExports.jsx(ot, { language: t }), n ? jsxRuntimeExports.jsx("div", { className: "pointer-events-none sticky top-2 z-10 -mt-10 flex h-8 items-center justify-end", children: jsxRuntimeExports.jsx("div", { className: "pointer-events-auto flex shrink-0 items-center gap-2 rounded-md border border-sidebar bg-sidebar/80 px-1.5 py-1 supports-[backdrop-filter]:bg-sidebar/70 supports-[backdrop-filter]:backdrop-blur", "data-streamdown": "code-block-actions", children: n }) }) : null, jsxRuntimeExports.jsx(reactExports.Suspense, { fallback: jsxRuntimeExports.jsx(Qe, { className: o, language: t, result: c, ...r2 }), children: jsxRuntimeExports.jsx(dn, { className: o, code: i, language: t, raw: c, ...r2 }) })] }) });
@@ -82290,7 +82295,7 @@ var Dt = ({ children: e, className: t, onDownload: o, onError: n }) => {
82290
82295
  }, []), jsxRuntimeExports.jsxs("div", { className: "relative", ref: i, children: [jsxRuntimeExports.jsx("button", { className: f("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50", t), disabled: c, onClick: () => r2(!s2), title: "Download table", type: "button", children: e != null ? e : jsxRuntimeExports.jsx(Z, { size: 14 }) }), s2 ? jsxRuntimeExports.jsxs("div", { className: "absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg", children: [jsxRuntimeExports.jsx("button", { className: "w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40", onClick: () => a2("csv"), title: "Download table as CSV", type: "button", children: "CSV" }), jsxRuntimeExports.jsx("button", { className: "w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40", onClick: () => a2("markdown"), title: "Download table as Markdown", type: "button", children: "Markdown" })] }) : null] });
82291
82296
  };
82292
82297
  var Vt = ({ children: e, className: t, showControls: o, ...n }) => jsxRuntimeExports.jsxs("div", { className: "my-4 flex flex-col gap-2 rounded-lg border border-border bg-sidebar p-2", "data-streamdown": "table-wrapper", children: [o ? jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-end gap-1", children: [jsxRuntimeExports.jsx(Ht, {}), jsxRuntimeExports.jsx(Dt, {})] }) : null, jsxRuntimeExports.jsx("div", { className: "border-collapse overflow-x-auto overscroll-y-auto rounded-md border border-border bg-background", children: jsxRuntimeExports.jsx("table", { className: f("w-full divide-y divide-border", t), "data-streamdown": "table", ...n, children: e }) })] });
82293
- var Jn = reactExports.lazy(() => import("./mermaid-3ZIDBTTL-Ku6qjB5F.js").then((e) => ({ default: e.Mermaid }))), Kn = /language-([^\s]+)/;
82298
+ var Jn = reactExports.lazy(() => import("./mermaid-3ZIDBTTL-Ccs470KM.js").then((e) => ({ default: e.Mermaid }))), Kn = /language-([^\s]+)/;
82294
82299
  function ke(e, t) {
82295
82300
  if (!(e != null && e.position || t != null && t.position)) return true;
82296
82301
  if (!(e != null && e.position && (t != null && t.position))) return false;
@@ -90913,6 +90918,17 @@ class WorkflowRunFailedError extends WorkflowError {
90913
90918
  super(`Workflow run "${runId}" failed: ${error2.message}`, {
90914
90919
  cause: causeError
90915
90920
  });
90921
+ /**
90922
+ * `failed` is terminal, and a run's terminal state is immutable. This error
90923
+ * is only ever thrown after a *successful* read of such a run, so re-running
90924
+ * the read returns the same record and throws the same error. Marking it
90925
+ * non-retryable is what stops the step executor from spending a retry budget
90926
+ * on that when the read happens inside a step — a parent awaiting a child's
90927
+ * `returnValue` — and then replacing this error with its retry-exhaustion
90928
+ * wrapper. A read that *fails* throws something else and stays retryable.
90929
+ * See `FatalError.is()`.
90930
+ */
90931
+ __publicField(this, "fatal", true);
90916
90932
  __publicField(this, "runId");
90917
90933
  this.name = "WorkflowRunFailedError";
90918
90934
  this.runId = runId;
@@ -91062,6 +91078,8 @@ class PreconditionFailedError extends WorkflowWorldError {
91062
91078
  class WorkflowRunCancelledError extends WorkflowError {
91063
91079
  constructor(runId) {
91064
91080
  super(`Workflow run "${runId}" cancelled`, {});
91081
+ /** Terminal and immutable, for the same reason as {@link WorkflowRunFailedError.fatal}. */
91082
+ __publicField(this, "fatal", true);
91065
91083
  __publicField(this, "runId");
91066
91084
  this.name = "WorkflowRunCancelledError";
91067
91085
  this.runId = runId;
@@ -91090,7 +91108,11 @@ class FatalError extends Error {
91090
91108
  this.name = "FatalError";
91091
91109
  }
91092
91110
  static is(value) {
91093
- return isError(value) && value.name === "FatalError";
91111
+ if (!isError(value))
91112
+ return false;
91113
+ if (value.name === "FatalError")
91114
+ return true;
91115
+ return value.fatal === true;
91094
91116
  }
91095
91117
  }
91096
91118
  class RetryableError extends Error {
@@ -92182,7 +92204,7 @@ createLogger("build", {
92182
92204
  debugNamespace: "workflow:build"
92183
92205
  });
92184
92206
  const MAX_QUEUE_DELIVERIES = 48;
92185
- const version$1 = "4.8.9";
92207
+ const version$1 = "4.8.11";
92186
92208
  const execFileAsync = promisify(execFile);
92187
92209
  function parsePort$1(value, radix = 10) {
92188
92210
  const port = parseInt(value, radix);
@@ -95871,10 +95893,27 @@ function requireRequest$1() {
95871
95893
  return false;
95872
95894
  }
95873
95895
  }
95874
- onUpgrade(statusCode, headers2, socket) {
95896
+ /**
95897
+ * @param {number} statusCode
95898
+ * @param {Buffer[]|string[]} headers
95899
+ * @param {import('node:stream').Duplex} socket
95900
+ * @param {string} [statusText]
95901
+ */
95902
+ onUpgrade(statusCode, headers2, socket, statusText = "") {
95903
+ this.onFinally();
95875
95904
  assert2(!this.aborted);
95876
95905
  assert2(!this.completed);
95877
- return this[kHandler].onUpgrade(statusCode, headers2, socket);
95906
+ if (channels.headers.hasSubscribers) {
95907
+ channels.headers.publish({ request: this, response: { statusCode, headers: headers2, statusText } });
95908
+ }
95909
+ const result = this[kHandler].onUpgrade(statusCode, headers2, socket);
95910
+ if (!this.aborted) {
95911
+ this.completed = true;
95912
+ if (channels.trailers.hasSubscribers) {
95913
+ channels.trailers.publish({ request: this, trailers: [] });
95914
+ }
95915
+ }
95916
+ return result;
95878
95917
  }
95879
95918
  onComplete(trailers) {
95880
95919
  this.onFinally();
@@ -95942,7 +95981,11 @@ function requireRequest$1() {
95942
95981
  } else if (typeof val[i] === "object") {
95943
95982
  throw new InvalidArgumentError(`invalid ${key} header`);
95944
95983
  } else {
95945
- arr.push(`${val[i]}`);
95984
+ const str = `${val[i]}`;
95985
+ if (!isValidHeaderValue(str)) {
95986
+ throw new InvalidArgumentError(`invalid ${key} header`);
95987
+ }
95988
+ arr.push(str);
95946
95989
  }
95947
95990
  }
95948
95991
  val = arr;
@@ -95954,6 +95997,9 @@ function requireRequest$1() {
95954
95997
  val = "";
95955
95998
  } else {
95956
95999
  val = `${val}`;
96000
+ if (!isValidHeaderValue(val)) {
96001
+ throw new InvalidArgumentError(`invalid ${key} header`);
96002
+ }
95957
96003
  }
95958
96004
  if (headerName === "host") {
95959
96005
  if (request2.host !== null) {
@@ -100170,6 +100216,7 @@ function requireClientH1() {
100170
100216
  RequestContentLengthMismatchError,
100171
100217
  ResponseContentLengthMismatchError,
100172
100218
  RequestAbortedError,
100219
+ InvalidArgumentError,
100173
100220
  HeadersTimeoutError,
100174
100221
  HeadersOverflowError,
100175
100222
  SocketError,
@@ -100223,7 +100270,13 @@ function requireClientH1() {
100223
100270
  function lazyllhttp() {
100224
100271
  const llhttpWasmData = process.env.JEST_WORKER_ID ? requireLlhttpWasm() : void 0;
100225
100272
  let mod;
100226
- let useWasmSIMD = process.arch !== "ppc64";
100273
+ let useWasmSIMD = true;
100274
+ if (process.arch === "ppc64") {
100275
+ const [major, minor] = process.versions.node.split(".").map((n) => parseInt(n, 10));
100276
+ if (major < 24 || major === 24 && minor < 12) {
100277
+ useWasmSIMD = false;
100278
+ }
100279
+ }
100227
100280
  if (process.env.UNDICI_NO_WASM_SIMD === "1") {
100228
100281
  useWasmSIMD = false;
100229
100282
  } else if (process.env.UNDICI_NO_WASM_SIMD === "0") {
@@ -100578,7 +100631,7 @@ function requireClientH1() {
100578
100631
  * @param {Buffer} head
100579
100632
  */
100580
100633
  onUpgrade(head) {
100581
- const { upgrade, client: client2, socket, headers: headers2, statusCode } = this;
100634
+ const { upgrade, client: client2, socket, headers: headers2, statusCode, statusText } = this;
100582
100635
  assert2(upgrade);
100583
100636
  assert2(client2[kSocket] === socket);
100584
100637
  assert2(!socket.destroyed);
@@ -100603,8 +100656,9 @@ function requireClientH1() {
100603
100656
  client2[kQueue][client2[kRunningIdx]++] = null;
100604
100657
  client2.emit("disconnect", client2[kUrl], [client2], new InformationalError("upgrade"));
100605
100658
  try {
100606
- request2.onUpgrade(statusCode, headers2, socket);
100659
+ request2.onUpgrade(statusCode, headers2, socket, statusText);
100607
100660
  } catch (err) {
100661
+ util2.errorRequest(client2, request2, err);
100608
100662
  util2.destroy(socket, err);
100609
100663
  }
100610
100664
  client2[kResume]();
@@ -100936,22 +100990,20 @@ function requireClientH1() {
100936
100990
  }
100937
100991
  function clearIdleSocketValidation(socket) {
100938
100992
  if (socket[kIdleSocketValidationTimeout]) {
100939
- clearTimeout(socket[kIdleSocketValidationTimeout]);
100993
+ clearImmediate(socket[kIdleSocketValidationTimeout]);
100940
100994
  socket[kIdleSocketValidationTimeout] = null;
100941
100995
  }
100942
100996
  socket[kIdleSocketValidation] = 0;
100943
100997
  }
100944
100998
  function scheduleIdleSocketValidation(client2, socket) {
100945
- var _a3, _b2;
100946
100999
  socket[kIdleSocketValidation] = 1;
100947
- socket[kIdleSocketValidationTimeout] = setTimeout(() => {
101000
+ socket[kIdleSocketValidationTimeout] = setImmediate(() => {
100948
101001
  socket[kIdleSocketValidationTimeout] = null;
100949
101002
  socket[kIdleSocketValidation] = 2;
100950
101003
  if (client2[kSocket] === socket && !socket.destroyed) {
100951
101004
  client2[kResume]();
100952
101005
  }
100953
- }, 0);
100954
- (_b2 = (_a3 = socket[kIdleSocketValidationTimeout]).unref) == null ? void 0 : _b2.call(_a3);
101006
+ });
100955
101007
  }
100956
101008
  function resumeH1(client2) {
100957
101009
  const socket = client2[kSocket];
@@ -101018,8 +101070,16 @@ function requireClientH1() {
101018
101070
  }
101019
101071
  body2 = bodyStream.stream;
101020
101072
  contentLength2 = bodyStream.length;
101021
- } else if (util2.isBlobLike(body2) && request2.contentType == null && body2.type) {
101022
- headers2.push("content-type", body2.type);
101073
+ } else if (util2.isBlobLike(body2) && request2.contentType == null) {
101074
+ const contentType = body2.type;
101075
+ if (contentType) {
101076
+ const contentTypeValue = `${contentType}`;
101077
+ if (!util2.isValidHeaderValue(contentTypeValue)) {
101078
+ util2.errorRequest(client2, request2, new InvalidArgumentError("invalid content-type header"));
101079
+ return false;
101080
+ }
101081
+ headers2.push("content-type", contentTypeValue);
101082
+ }
101023
101083
  }
101024
101084
  if (body2 && typeof body2.read === "function") {
101025
101085
  body2.read(0);
@@ -101433,7 +101493,9 @@ function requireClientH2() {
101433
101493
  RequestAbortedError,
101434
101494
  SocketError,
101435
101495
  InformationalError,
101436
- InvalidArgumentError
101496
+ InvalidArgumentError,
101497
+ HeadersTimeoutError,
101498
+ BodyTimeoutError
101437
101499
  } = requireErrors();
101438
101500
  const {
101439
101501
  kUrl,
@@ -101458,6 +101520,7 @@ function requireClientH2() {
101458
101520
  kHTTPContext,
101459
101521
  kClosed,
101460
101522
  kBodyTimeout,
101523
+ kHeadersTimeout,
101461
101524
  kEnableConnectProtocol,
101462
101525
  kRemoteSettings,
101463
101526
  kHTTP2Stream,
@@ -101594,7 +101657,7 @@ function requireClientH2() {
101594
101657
  function resumeH2(client2) {
101595
101658
  const socket = client2[kSocket];
101596
101659
  if ((socket == null ? void 0 : socket.destroyed) === false) {
101597
- if (client2[kSize] === 0 || client2[kMaxConcurrentStreams] === 0) {
101660
+ if (client2[kSize] === 0) {
101598
101661
  socket.unref();
101599
101662
  client2[kHTTP2Session].unref();
101600
101663
  } else {
@@ -101660,6 +101723,24 @@ function requireClientH2() {
101660
101723
  this.destroy(err);
101661
101724
  util2.destroy(this[kSocket], err);
101662
101725
  }
101726
+ function completeRequest(client2, request2, resetPendingIdx = false) {
101727
+ const queue = client2[kQueue];
101728
+ const runningIdx = client2[kRunningIdx];
101729
+ if (runningIdx < client2[kPendingIdx] && queue[runningIdx] === request2) {
101730
+ queue[runningIdx] = null;
101731
+ client2[kRunningIdx] = runningIdx + 1;
101732
+ return;
101733
+ }
101734
+ const index2 = queue.indexOf(request2, runningIdx);
101735
+ if (index2 === -1 || index2 >= client2[kPendingIdx]) {
101736
+ return;
101737
+ }
101738
+ queue.splice(index2, 1);
101739
+ client2[kPendingIdx]--;
101740
+ if (resetPendingIdx && client2[kPendingIdx] < client2[kRunningIdx]) {
101741
+ client2[kPendingIdx] = client2[kRunningIdx];
101742
+ }
101743
+ }
101663
101744
  function onHttp2SessionGoAway(errorCode) {
101664
101745
  const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util2.getSocketInfo(this[kSocket]));
101665
101746
  const client2 = this[kClient];
@@ -101671,7 +101752,9 @@ function requireClientH2() {
101671
101752
  if (client2[kRunningIdx] < client2[kQueue].length) {
101672
101753
  const request2 = client2[kQueue][client2[kRunningIdx]];
101673
101754
  client2[kQueue][client2[kRunningIdx]++] = null;
101674
- util2.errorRequest(client2, request2, err);
101755
+ if (request2 != null) {
101756
+ util2.errorRequest(client2, request2, err);
101757
+ }
101675
101758
  client2[kPendingIdx] = client2[kRunningIdx];
101676
101759
  }
101677
101760
  assert2(client2[kRunning] === 0);
@@ -101694,7 +101777,9 @@ function requireClientH2() {
101694
101777
  const requests = client2[kQueue].splice(client2[kRunningIdx]);
101695
101778
  for (let i = 0; i < requests.length; i++) {
101696
101779
  const request2 = requests[i];
101697
- util2.errorRequest(client2, request2, err);
101780
+ if (request2 != null) {
101781
+ util2.errorRequest(client2, request2, err);
101782
+ }
101698
101783
  }
101699
101784
  }
101700
101785
  }
@@ -101726,7 +101811,8 @@ function requireClientH2() {
101726
101811
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
101727
101812
  }
101728
101813
  function writeH2(client2, request2) {
101729
- const requestTimeout = request2.bodyTimeout ?? client2[kBodyTimeout];
101814
+ const headersTimeout = request2.headersTimeout ?? client2[kHeadersTimeout];
101815
+ const bodyTimeout = request2.bodyTimeout ?? client2[kBodyTimeout];
101730
101816
  const session = client2[kHTTP2Session];
101731
101817
  const { method, path: path2, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request2;
101732
101818
  let { body: body2 } = request2;
@@ -101774,6 +101860,7 @@ function requireClientH2() {
101774
101860
  stream.removeAllListeners("data");
101775
101861
  stream.close();
101776
101862
  client2[kOnError](err);
101863
+ completeRequest(client2, request2);
101777
101864
  client2[kResume]();
101778
101865
  }
101779
101866
  util2.destroy(body2, err);
@@ -101804,11 +101891,16 @@ function requireClientH2() {
101804
101891
  }
101805
101892
  stream = session.request(headers2, { endStream: false, signal });
101806
101893
  stream[kHTTP2Stream] = true;
101894
+ ++session[kOpenStreams];
101807
101895
  stream.once("response", (headers3, _flags) => {
101808
101896
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers3;
101809
- request2.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
101810
- ++session[kOpenStreams];
101811
- client2[kQueue][client2[kRunningIdx]++] = null;
101897
+ try {
101898
+ request2.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
101899
+ } catch (err) {
101900
+ abort(err);
101901
+ return;
101902
+ }
101903
+ completeRequest(client2, request2);
101812
101904
  });
101813
101905
  stream.on("error", () => {
101814
101906
  if (stream.rstCode === NGHTTP2_REFUSED_STREAM || stream.rstCode === NGHTTP2_CANCEL) {
@@ -101819,22 +101911,28 @@ function requireClientH2() {
101819
101911
  session[kOpenStreams] -= 1;
101820
101912
  if (session[kOpenStreams] === 0) session.unref();
101821
101913
  });
101822
- stream.setTimeout(requestTimeout);
101914
+ stream.setTimeout(headersTimeout);
101823
101915
  return true;
101824
101916
  }
101825
101917
  stream = session.request(headers2, { endStream: false, signal });
101826
101918
  stream[kHTTP2Stream] = true;
101919
+ ++session[kOpenStreams];
101827
101920
  stream.on("response", (headers3) => {
101828
101921
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers3;
101829
- request2.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
101830
- ++session[kOpenStreams];
101831
- client2[kQueue][client2[kRunningIdx]++] = null;
101922
+ try {
101923
+ request2.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
101924
+ } catch (err) {
101925
+ abort(err);
101926
+ return;
101927
+ }
101928
+ completeRequest(client2, request2);
101832
101929
  });
101930
+ stream.on("error", abort);
101833
101931
  stream.once("close", () => {
101834
101932
  session[kOpenStreams] -= 1;
101835
101933
  if (session[kOpenStreams] === 0) session.unref();
101836
101934
  });
101837
- stream.setTimeout(requestTimeout);
101935
+ stream.setTimeout(headersTimeout);
101838
101936
  return true;
101839
101937
  }
101840
101938
  headers2[HTTP2_HEADER_PATH] = path2;
@@ -101892,12 +101990,13 @@ function requireClientH2() {
101892
101990
  writeBodyH2();
101893
101991
  }
101894
101992
  ++session[kOpenStreams];
101895
- stream.setTimeout(requestTimeout);
101993
+ stream.setTimeout(headersTimeout);
101896
101994
  let responseReceived = false;
101897
101995
  stream.once("response", (headers3) => {
101898
101996
  const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers3;
101899
101997
  request2.onResponseStarted();
101900
101998
  responseReceived = true;
101999
+ stream.setTimeout(bodyTimeout);
101901
102000
  if (request2.aborted) {
101902
102001
  stream.removeAllListeners("data");
101903
102002
  return;
@@ -101920,12 +102019,11 @@ function requireClientH2() {
101920
102019
  if (!request2.aborted && !request2.completed) {
101921
102020
  request2.onComplete({});
101922
102021
  }
101923
- client2[kQueue][client2[kRunningIdx]++] = null;
102022
+ completeRequest(client2, request2);
101924
102023
  client2[kResume]();
101925
102024
  } else {
101926
102025
  abort(new InformationalError("HTTP/2: stream half-closed (remote)"));
101927
- client2[kQueue][client2[kRunningIdx]++] = null;
101928
- client2[kPendingIdx] = client2[kRunningIdx];
102026
+ completeRequest(client2, request2, true);
101929
102027
  client2[kResume]();
101930
102028
  }
101931
102029
  });
@@ -101935,6 +102033,9 @@ function requireClientH2() {
101935
102033
  if (session[kOpenStreams] === 0) {
101936
102034
  session.unref();
101937
102035
  }
102036
+ if (!request2.aborted && !request2.completed) {
102037
+ abort(new InformationalError("HTTP/2: stream closed before the response was complete"));
102038
+ }
101938
102039
  });
101939
102040
  stream.once("error", function(err) {
101940
102041
  stream.removeAllListeners("data");
@@ -101948,7 +102049,7 @@ function requireClientH2() {
101948
102049
  stream.removeAllListeners("data");
101949
102050
  });
101950
102051
  stream.on("timeout", () => {
101951
- const err = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`);
102052
+ const err = responseReceived ? new BodyTimeoutError(`HTTP/2: "body timeout after ${bodyTimeout}"`) : new HeadersTimeoutError(`HTTP/2: "headers timeout after ${headersTimeout}"`);
101952
102053
  stream.removeAllListeners("data");
101953
102054
  session[kOpenStreams] -= 1;
101954
102055
  if (session[kOpenStreams] === 0) {
@@ -102448,7 +102549,9 @@ function requireClient() {
102448
102549
  const requests = this[kQueue].splice(this[kPendingIdx]);
102449
102550
  for (let i = 0; i < requests.length; i++) {
102450
102551
  const request2 = requests[i];
102451
- util2.errorRequest(this, request2, err);
102552
+ if (request2 != null) {
102553
+ util2.errorRequest(this, request2, err);
102554
+ }
102452
102555
  }
102453
102556
  const callback = () => {
102454
102557
  if (this[kClosedResolve]) {
@@ -102473,7 +102576,9 @@ function requireClient() {
102473
102576
  const requests = client2[kQueue].splice(client2[kRunningIdx]);
102474
102577
  for (let i = 0; i < requests.length; i++) {
102475
102578
  const request2 = requests[i];
102476
- util2.errorRequest(client2, request2, err);
102579
+ if (request2 != null) {
102580
+ util2.errorRequest(client2, request2, err);
102581
+ }
102477
102582
  }
102478
102583
  assert2(client2[kSize] === 0);
102479
102584
  }
@@ -103076,12 +103181,14 @@ function requireBalancedPool() {
103076
103181
  return new Pool(origin, opts);
103077
103182
  }
103078
103183
  class BalancedPool extends PoolBase {
103079
- constructor(upstreams = [], { factory = defaultFactory, ...opts } = {}) {
103184
+ constructor(upstreams = [], { factory = defaultFactory, connect: connect2, tls, ...opts } = {}) {
103080
103185
  if (typeof factory !== "function") {
103081
103186
  throw new InvalidArgumentError("factory must be a function.");
103082
103187
  }
103083
103188
  super(opts);
103084
- this[kOptions] = { ...util2.deepClone(opts) };
103189
+ if (connect2 && typeof connect2 !== "function") connect2 = { ...connect2 };
103190
+ if (tls && typeof tls !== "function") tls = { ...tls };
103191
+ this[kOptions] = { ...util2.deepClone(opts), connect: connect2, tls };
103085
103192
  this[kOptions].interceptors = opts.interceptors ? { ...opts.interceptors } : void 0;
103086
103193
  this[kIndex] = -1;
103087
103194
  this[kCurrentWeight] = 0;
@@ -104526,6 +104633,7 @@ function requireEnvHttpProxyAgent() {
104526
104633
  var retryHandler;
104527
104634
  var hasRequiredRetryHandler;
104528
104635
  function requireRetryHandler() {
104636
+ var _paused, _target;
104529
104637
  if (hasRequiredRetryHandler) return retryHandler;
104530
104638
  hasRequiredRetryHandler = 1;
104531
104639
  const assert2 = require$$0$4;
@@ -104541,6 +104649,84 @@ function requireRetryHandler() {
104541
104649
  const retryTime = new Date(retryAfter).getTime();
104542
104650
  return isNaN(retryTime) ? 0 : retryTime - Date.now();
104543
104651
  }
104652
+ function validatePartialResponseContentLength(headers2, range2, statusCode, retryCount) {
104653
+ const contentLength2 = headers2["content-length"];
104654
+ if (contentLength2 == null) {
104655
+ return;
104656
+ }
104657
+ if (!Number.isFinite(range2.start) || !Number.isFinite(range2.end)) {
104658
+ return;
104659
+ }
104660
+ const length = Number(contentLength2);
104661
+ const expectedLength = range2.end - range2.start + 1;
104662
+ if (!Number.isFinite(length) || length !== expectedLength) {
104663
+ throw new RequestRetryError("Content-Length mismatch", statusCode, {
104664
+ headers: headers2,
104665
+ data: { count: retryCount }
104666
+ });
104667
+ }
104668
+ }
104669
+ class RetryController {
104670
+ constructor() {
104671
+ __privateAdd(this, _paused, false);
104672
+ __privateAdd(this, _target, null);
104673
+ }
104674
+ set target(target2) {
104675
+ __privateSet(this, _target, target2);
104676
+ if (__privateGet(this, _paused)) {
104677
+ target2 == null ? void 0 : target2.pause();
104678
+ }
104679
+ }
104680
+ get target() {
104681
+ return __privateGet(this, _target);
104682
+ }
104683
+ pause() {
104684
+ var _a3;
104685
+ __privateSet(this, _paused, true);
104686
+ (_a3 = __privateGet(this, _target)) == null ? void 0 : _a3.pause();
104687
+ }
104688
+ resume() {
104689
+ var _a3;
104690
+ __privateSet(this, _paused, false);
104691
+ (_a3 = __privateGet(this, _target)) == null ? void 0 : _a3.resume();
104692
+ }
104693
+ abort(reason) {
104694
+ var _a3;
104695
+ (_a3 = __privateGet(this, _target)) == null ? void 0 : _a3.abort(reason);
104696
+ }
104697
+ get paused() {
104698
+ var _a3;
104699
+ return __privateGet(this, _paused) || (((_a3 = __privateGet(this, _target)) == null ? void 0 : _a3.paused) ?? false);
104700
+ }
104701
+ get aborted() {
104702
+ var _a3;
104703
+ return ((_a3 = __privateGet(this, _target)) == null ? void 0 : _a3.aborted) ?? false;
104704
+ }
104705
+ get reason() {
104706
+ var _a3;
104707
+ return ((_a3 = __privateGet(this, _target)) == null ? void 0 : _a3.reason) ?? null;
104708
+ }
104709
+ get rawHeaders() {
104710
+ var _a3;
104711
+ return ((_a3 = __privateGet(this, _target)) == null ? void 0 : _a3.rawHeaders) ?? null;
104712
+ }
104713
+ set rawHeaders(value) {
104714
+ if (__privateGet(this, _target)) {
104715
+ __privateGet(this, _target).rawHeaders = value;
104716
+ }
104717
+ }
104718
+ get rawTrailers() {
104719
+ var _a3;
104720
+ return ((_a3 = __privateGet(this, _target)) == null ? void 0 : _a3.rawTrailers) ?? null;
104721
+ }
104722
+ set rawTrailers(value) {
104723
+ if (__privateGet(this, _target)) {
104724
+ __privateGet(this, _target).rawTrailers = value;
104725
+ }
104726
+ }
104727
+ }
104728
+ _paused = new WeakMap();
104729
+ _target = new WeakMap();
104544
104730
  class RetryHandler {
104545
104731
  constructor(opts, { dispatch: dispatch2, handler }) {
104546
104732
  const { retryOptions, ...dispatchOpts } = opts;
@@ -104595,13 +104781,19 @@ function requireRetryHandler() {
104595
104781
  this.start = 0;
104596
104782
  this.end = null;
104597
104783
  this.etag = null;
104784
+ this.controllerProxy = new RetryController();
104598
104785
  }
104599
104786
  onResponseStartWithRetry(controller, statusCode, headers2, statusMessage, err) {
104600
- var _a3, _b2, _c, _d;
104787
+ var _a3, _b2, _c, _d, _e2, _f;
104601
104788
  if (this.retryOpts.throwOnError) {
104602
104789
  if (this.retryOpts.statusCodes.includes(statusCode) === false) {
104603
- this.headersSent = true;
104604
- (_b2 = (_a3 = this.handler).onResponseStart) == null ? void 0 : _b2.call(_a3, controller, statusCode, headers2, statusMessage);
104790
+ if (this.headersSent) {
104791
+ (_b2 = (_a3 = this.handler).onResponseError) == null ? void 0 : _b2.call(_a3, this.controllerProxy, err);
104792
+ } else {
104793
+ this.headersSent = true;
104794
+ this.checkpointResponseEnd(headers2);
104795
+ (_d = (_c = this.handler).onResponseStart) == null ? void 0 : _d.call(_c, this.controllerProxy, statusCode, headers2, statusMessage);
104796
+ }
104605
104797
  } else {
104606
104798
  this.error = err;
104607
104799
  }
@@ -104609,14 +104801,20 @@ function requireRetryHandler() {
104609
104801
  }
104610
104802
  if (isDisturbed(this.opts.body)) {
104611
104803
  this.headersSent = true;
104612
- (_d = (_c = this.handler).onResponseStart) == null ? void 0 : _d.call(_c, controller, statusCode, headers2, statusMessage);
104804
+ this.checkpointResponseEnd(headers2);
104805
+ (_f = (_e2 = this.handler).onResponseStart) == null ? void 0 : _f.call(_e2, this.controllerProxy, statusCode, headers2, statusMessage);
104613
104806
  return;
104614
104807
  }
104615
104808
  function shouldRetry(passedErr) {
104616
- var _a4, _b3;
104809
+ var _a4, _b3, _c2, _d2;
104617
104810
  if (passedErr) {
104618
- this.headersSent = true;
104619
- (_b3 = (_a4 = this.handler).onResponseStart) == null ? void 0 : _b3.call(_a4, controller, statusCode, headers2, statusMessage);
104811
+ if (this.headersSent) {
104812
+ (_b3 = (_a4 = this.handler).onResponseError) == null ? void 0 : _b3.call(_a4, this.controllerProxy, passedErr);
104813
+ } else {
104814
+ this.headersSent = true;
104815
+ this.checkpointResponseEnd(headers2);
104816
+ (_d2 = (_c2 = this.handler).onResponseStart) == null ? void 0 : _d2.call(_c2, this.controllerProxy, statusCode, headers2, statusMessage);
104817
+ }
104620
104818
  controller.resume();
104621
104819
  return;
104622
104820
  }
@@ -104633,15 +104831,27 @@ function requireRetryHandler() {
104633
104831
  shouldRetry.bind(this)
104634
104832
  );
104635
104833
  }
104834
+ checkpointResponseEnd(headers2) {
104835
+ if (this.end == null && this.opts.method !== "HEAD") {
104836
+ const contentLength2 = headers2["content-length"];
104837
+ this.end = contentLength2 != null ? Number(contentLength2) - 1 : null;
104838
+ assert2(
104839
+ this.end == null || Number.isFinite(this.end),
104840
+ "invalid content-length"
104841
+ );
104842
+ this.resume = this.end != null;
104843
+ }
104844
+ }
104636
104845
  onRequestStart(controller, context) {
104637
104846
  var _a3, _b2;
104847
+ this.controllerProxy.target = controller;
104638
104848
  if (!this.headersSent) {
104639
- (_b2 = (_a3 = this.handler).onRequestStart) == null ? void 0 : _b2.call(_a3, controller, context);
104849
+ (_b2 = (_a3 = this.handler).onRequestStart) == null ? void 0 : _b2.call(_a3, this.controllerProxy, context);
104640
104850
  }
104641
104851
  }
104642
- onRequestUpgrade(controller, statusCode, headers2, socket) {
104852
+ onRequestUpgrade(_controller, statusCode, headers2, socket) {
104643
104853
  var _a3, _b2;
104644
- (_b2 = (_a3 = this.handler).onRequestUpgrade) == null ? void 0 : _b2.call(_a3, controller, statusCode, headers2, socket);
104854
+ (_b2 = (_a3 = this.handler).onRequestUpgrade) == null ? void 0 : _b2.call(_a3, this.controllerProxy, statusCode, headers2, socket);
104645
104855
  }
104646
104856
  static [kRetryHandlerDefaultRetry](err, { state, opts }, cb) {
104647
104857
  const { statusCode, code: code2, headers: headers2 } = err;
@@ -104714,9 +104924,14 @@ function requireRetryHandler() {
104714
104924
  data: { count: this.retryCount }
104715
104925
  });
104716
104926
  }
104927
+ validatePartialResponseContentLength(headers2, contentRange, statusCode, this.retryCount);
104717
104928
  const { start: start2, size: size2, end = size2 ? size2 - 1 : null } = contentRange;
104718
- assert2(this.start === start2, "content-range mismatch");
104719
- assert2(this.end == null || this.end === end, "content-range mismatch");
104929
+ if (this.start !== start2 || this.end != null && this.end !== end) {
104930
+ throw new RequestRetryError("Content-Range mismatch", statusCode, {
104931
+ headers: headers2,
104932
+ data: { count: this.retryCount }
104933
+ });
104934
+ }
104720
104935
  return;
104721
104936
  }
104722
104937
  if (this.end == null) {
@@ -104726,13 +104941,14 @@ function requireRetryHandler() {
104726
104941
  this.headersSent = true;
104727
104942
  (_b2 = (_a3 = this.handler).onResponseStart) == null ? void 0 : _b2.call(
104728
104943
  _a3,
104729
- controller,
104944
+ this.controllerProxy,
104730
104945
  statusCode,
104731
104946
  headers2,
104732
104947
  statusMessage
104733
104948
  );
104734
104949
  return;
104735
104950
  }
104951
+ validatePartialResponseContentLength(headers2, range2, statusCode, this.retryCount);
104736
104952
  const { start: start2, size: size2, end = size2 ? size2 - 1 : null } = range2;
104737
104953
  assert2(
104738
104954
  start2 != null && Number.isFinite(start2),
@@ -104759,7 +104975,7 @@ function requireRetryHandler() {
104759
104975
  this.headersSent = true;
104760
104976
  (_d = (_c = this.handler).onResponseStart) == null ? void 0 : _d.call(
104761
104977
  _c,
104762
- controller,
104978
+ this.controllerProxy,
104763
104979
  statusCode,
104764
104980
  headers2,
104765
104981
  statusMessage
@@ -104771,26 +104987,26 @@ function requireRetryHandler() {
104771
104987
  });
104772
104988
  }
104773
104989
  }
104774
- onResponseData(controller, chunk) {
104990
+ onResponseData(_controller, chunk) {
104775
104991
  var _a3, _b2;
104776
104992
  if (this.error) {
104777
104993
  return;
104778
104994
  }
104779
104995
  this.start += chunk.length;
104780
- (_b2 = (_a3 = this.handler).onResponseData) == null ? void 0 : _b2.call(_a3, controller, chunk);
104996
+ (_b2 = (_a3 = this.handler).onResponseData) == null ? void 0 : _b2.call(_a3, this.controllerProxy, chunk);
104781
104997
  }
104782
- onResponseEnd(controller, trailers) {
104998
+ onResponseEnd(_controller, trailers) {
104783
104999
  var _a3, _b2;
104784
105000
  if (this.error && this.retryOpts.throwOnError) {
104785
105001
  throw this.error;
104786
105002
  }
104787
105003
  if (!this.error) {
104788
105004
  this.retryCount = 0;
104789
- return (_b2 = (_a3 = this.handler).onResponseEnd) == null ? void 0 : _b2.call(_a3, controller, trailers);
105005
+ return (_b2 = (_a3 = this.handler).onResponseEnd) == null ? void 0 : _b2.call(_a3, this.controllerProxy, trailers);
104790
105006
  }
104791
- this.retry(controller);
105007
+ this.retry();
104792
105008
  }
104793
- retry(controller) {
105009
+ retry() {
104794
105010
  var _a3, _b2;
104795
105011
  if (this.start !== 0) {
104796
105012
  const headers2 = { range: `bytes=${this.start}-${this.end ?? ""}` };
@@ -104809,22 +105025,22 @@ function requireRetryHandler() {
104809
105025
  this.retryCountCheckpoint = this.retryCount;
104810
105026
  this.dispatch(this.opts, this);
104811
105027
  } catch (err) {
104812
- (_b2 = (_a3 = this.handler).onResponseError) == null ? void 0 : _b2.call(_a3, controller, err);
105028
+ (_b2 = (_a3 = this.handler).onResponseError) == null ? void 0 : _b2.call(_a3, this.controllerProxy, err);
104813
105029
  }
104814
105030
  }
104815
105031
  onResponseError(controller, err) {
104816
105032
  var _a3, _b2;
104817
- if ((controller == null ? void 0 : controller.aborted) || isDisturbed(this.opts.body)) {
104818
- (_b2 = (_a3 = this.handler).onResponseError) == null ? void 0 : _b2.call(_a3, controller, err);
105033
+ if ((controller == null ? void 0 : controller.aborted) || isDisturbed(this.opts.body) || this.headersSent && !this.resume) {
105034
+ (_b2 = (_a3 = this.handler).onResponseError) == null ? void 0 : _b2.call(_a3, this.controllerProxy, err);
104819
105035
  return;
104820
105036
  }
104821
105037
  function shouldRetry(returnedErr) {
104822
105038
  var _a4, _b3;
104823
105039
  if (!returnedErr) {
104824
- this.retry(controller);
105040
+ this.retry();
104825
105041
  return;
104826
105042
  }
104827
- (_b3 = (_a4 = this.handler) == null ? void 0 : _a4.onResponseError) == null ? void 0 : _b3.call(_a4, controller, returnedErr);
105043
+ (_b3 = (_a4 = this.handler) == null ? void 0 : _a4.onResponseError) == null ? void 0 : _b3.call(_a4, this.controllerProxy, returnedErr);
104828
105044
  }
104829
105045
  if (this.retryCount - this.retryCountCheckpoint > 0) {
104830
105046
  this.retryCount = this.retryCountCheckpoint + (this.retryCount - this.retryCountCheckpoint);
@@ -108459,7 +108675,7 @@ function requireRetry() {
108459
108675
  var dump;
108460
108676
  var hasRequiredDump;
108461
108677
  function requireDump() {
108462
- var _maxSize2, _dumped, _size2, _controller, _DumpHandler_instances, abort_fn;
108678
+ var _maxSize2, _dumped, _size2, _DumpHandler_instances, abort_fn;
108463
108679
  if (hasRequiredDump) return dump;
108464
108680
  hasRequiredDump = 1;
108465
108681
  const { InvalidArgumentError, RequestAbortedError } = requireErrors();
@@ -108474,14 +108690,12 @@ function requireDump() {
108474
108690
  __privateAdd(this, _maxSize2, 1024 * 1024);
108475
108691
  __privateAdd(this, _dumped, false);
108476
108692
  __privateAdd(this, _size2, 0);
108477
- __privateAdd(this, _controller, null);
108478
108693
  __publicField(this, "aborted", false);
108479
108694
  __publicField(this, "reason", false);
108480
108695
  __privateSet(this, _maxSize2, maxSize ?? __privateGet(this, _maxSize2));
108481
108696
  }
108482
108697
  onRequestStart(controller, context) {
108483
108698
  controller.abort = __privateMethod(this, _DumpHandler_instances, abort_fn).bind(this);
108484
- __privateSet(this, _controller, controller);
108485
108699
  return super.onRequestStart(controller, context);
108486
108700
  }
108487
108701
  onResponseStart(controller, statusCode, headers2, statusMessage) {
@@ -108497,40 +108711,31 @@ function requireDump() {
108497
108711
  return super.onResponseStart(controller, statusCode, headers2, statusMessage);
108498
108712
  }
108499
108713
  onResponseError(controller, err) {
108500
- var _a3;
108501
- if (__privateGet(this, _dumped)) {
108502
- return;
108503
- }
108504
- err = ((_a3 = __privateGet(this, _controller)) == null ? void 0 : _a3.reason) ?? err;
108505
- super.onResponseError(controller, err);
108714
+ super.onResponseError(controller, this.aborted === true ? this.reason : err);
108506
108715
  }
108507
108716
  onResponseData(controller, chunk) {
108508
108717
  __privateSet(this, _size2, __privateGet(this, _size2) + chunk.length);
108509
- if (__privateGet(this, _size2) >= __privateGet(this, _maxSize2)) {
108718
+ if (__privateGet(this, _size2) > __privateGet(this, _maxSize2)) {
108719
+ throw new RequestAbortedError(
108720
+ `Response size (${__privateGet(this, _size2)}) larger than maxSize (${__privateGet(this, _maxSize2)})`
108721
+ );
108722
+ }
108723
+ if (__privateGet(this, _size2) === __privateGet(this, _maxSize2)) {
108510
108724
  __privateSet(this, _dumped, true);
108511
- if (this.aborted === true) {
108512
- super.onResponseError(controller, this.reason);
108513
- } else {
108514
- super.onResponseEnd(controller, {});
108515
- }
108516
108725
  }
108517
108726
  return true;
108518
108727
  }
108519
108728
  onResponseEnd(controller, trailers) {
108520
- if (__privateGet(this, _dumped)) {
108521
- return;
108522
- }
108523
- if (__privateGet(this, _controller).aborted === true) {
108729
+ if (this.aborted === true) {
108524
108730
  super.onResponseError(controller, this.reason);
108525
108731
  return;
108526
108732
  }
108527
- super.onResponseEnd(controller, trailers);
108733
+ super.onResponseEnd(controller, __privateGet(this, _dumped) ? {} : trailers);
108528
108734
  }
108529
108735
  }
108530
108736
  _maxSize2 = new WeakMap();
108531
108737
  _dumped = new WeakMap();
108532
108738
  _size2 = new WeakMap();
108533
- _controller = new WeakMap();
108534
108739
  _DumpHandler_instances = new WeakSet();
108535
108740
  abort_fn = function(reason) {
108536
108741
  this.aborted = true;
@@ -109013,9 +109218,122 @@ function requireCache$2() {
109013
109218
  const {
109014
109219
  safeHTTPMethods,
109015
109220
  pathHasQueryOrFragment,
109016
- hasSafeIterator
109221
+ hasSafeIterator,
109222
+ isValidHTTPToken
109017
109223
  } = requireUtil$5();
109018
109224
  const { serializePathWithQuery } = requireUtil$5();
109225
+ const MAX_DELTA_SECONDS = 2147483647;
109226
+ const RESTRICTIVE_DIRECTIVE_NAMES = ["no-store", "private", "no-cache"];
109227
+ const kInvalidCacheControlDirectives = Symbol("invalid cache-control directives");
109228
+ function trimOWS(value) {
109229
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
109230
+ }
109231
+ function arrayIncludes(array2, value) {
109232
+ for (let i = 0; i < array2.length; i++) {
109233
+ if (array2[i] === value) {
109234
+ return true;
109235
+ }
109236
+ }
109237
+ return false;
109238
+ }
109239
+ function trimOWSStart(value) {
109240
+ return value.replace(/^[\t ]+/, "");
109241
+ }
109242
+ function trimOWSEnd(value) {
109243
+ return value.replace(/[\t ]+$/, "");
109244
+ }
109245
+ function findUnescapedQuote(value, start2) {
109246
+ let escaped = false;
109247
+ for (let i = start2; i < value.length; i++) {
109248
+ if (escaped) {
109249
+ escaped = false;
109250
+ } else if (value[i] === "\\") {
109251
+ escaped = true;
109252
+ } else if (value[i] === '"') {
109253
+ return i;
109254
+ }
109255
+ }
109256
+ return -1;
109257
+ }
109258
+ function splitCacheControlHeaderValue(value) {
109259
+ const directives = [];
109260
+ let start2 = 0;
109261
+ let quoteStart = -1;
109262
+ let inQuote = false;
109263
+ let escaped = false;
109264
+ for (let i = 0; i < value.length; i++) {
109265
+ if (inQuote) {
109266
+ if (escaped) {
109267
+ escaped = false;
109268
+ } else if (value[i] === "\\") {
109269
+ escaped = true;
109270
+ } else if (value[i] === '"') {
109271
+ inQuote = false;
109272
+ quoteStart = -1;
109273
+ }
109274
+ } else if (value[i] === '"') {
109275
+ inQuote = true;
109276
+ quoteStart = i;
109277
+ } else if (value[i] === ",") {
109278
+ directives.push({ value: value.substring(start2, i), fromMalformedQuote: false });
109279
+ start2 = i + 1;
109280
+ }
109281
+ }
109282
+ if (!inQuote) {
109283
+ directives.push({ value: value.substring(start2), fromMalformedQuote: false });
109284
+ return directives;
109285
+ }
109286
+ const tail = value.substring(start2);
109287
+ const quoteOffset = quoteStart - start2;
109288
+ let tailStart = 0;
109289
+ for (let i = 0; i < tail.length; i++) {
109290
+ if (tail[i] === ",") {
109291
+ directives.push({
109292
+ value: tail.substring(tailStart, i),
109293
+ fromMalformedQuote: tailStart > quoteOffset
109294
+ });
109295
+ tailStart = i + 1;
109296
+ }
109297
+ }
109298
+ directives.push({
109299
+ value: tail.substring(tailStart),
109300
+ fromMalformedQuote: tailStart > quoteOffset
109301
+ });
109302
+ return directives;
109303
+ }
109304
+ function markInvalidCacheControlDirective(directives, key) {
109305
+ let invalidDirectives = directives[kInvalidCacheControlDirectives];
109306
+ if (invalidDirectives === void 0) {
109307
+ invalidDirectives = /* @__PURE__ */ new Set();
109308
+ Object.defineProperty(directives, kInvalidCacheControlDirectives, {
109309
+ value: invalidDirectives
109310
+ });
109311
+ }
109312
+ invalidDirectives.add(key);
109313
+ }
109314
+ function hasInvalidCacheControlDirective(directives, key) {
109315
+ var _a3;
109316
+ return ((_a3 = directives[kInvalidCacheControlDirectives]) == null ? void 0 : _a3.has(key)) === true;
109317
+ }
109318
+ function getMalformedRestrictiveDirectiveName(key) {
109319
+ for (const directiveName of RESTRICTIVE_DIRECTIVE_NAMES) {
109320
+ if (key.startsWith(directiveName) && key.length > directiveName.length && !isValidHTTPToken(key[directiveName.length])) {
109321
+ return directiveName;
109322
+ }
109323
+ }
109324
+ let tokenOnlyKey = "";
109325
+ let hasInvalidTokenChar = false;
109326
+ for (let i = 0; i < key.length; i++) {
109327
+ if (isValidHTTPToken(key[i])) {
109328
+ tokenOnlyKey += key[i];
109329
+ } else {
109330
+ hasInvalidTokenChar = true;
109331
+ }
109332
+ }
109333
+ if (hasInvalidTokenChar && arrayIncludes(RESTRICTIVE_DIRECTIVE_NAMES, tokenOnlyKey)) {
109334
+ return tokenOnlyKey;
109335
+ }
109336
+ }
109019
109337
  function makeCacheKey(opts) {
109020
109338
  if (!opts.origin) {
109021
109339
  throw new Error("opts.origin is undefined");
@@ -109031,6 +109349,18 @@ function requireCache$2() {
109031
109349
  headers: opts.headers
109032
109350
  };
109033
109351
  }
109352
+ function appendHeader(headers2, key, val) {
109353
+ const headerName = key.toLowerCase();
109354
+ const current = headers2[headerName];
109355
+ const values = Array.isArray(val) ? val : [val];
109356
+ if (current === void 0) {
109357
+ headers2[headerName] = Array.isArray(val) ? val.slice() : val;
109358
+ } else if (Array.isArray(current)) {
109359
+ current.push(...values);
109360
+ } else {
109361
+ headers2[headerName] = [current, ...values];
109362
+ }
109363
+ }
109034
109364
  function normalizeHeaders(opts) {
109035
109365
  let headers2;
109036
109366
  if (opts.headers == null) {
@@ -109046,11 +109376,11 @@ function requireCache$2() {
109046
109376
  if (typeof key !== "string" || typeof val !== "string") {
109047
109377
  throw new Error("opts.headers is not a valid header map");
109048
109378
  }
109049
- headers2[key.toLowerCase()] = val;
109379
+ appendHeader(headers2, key, val);
109050
109380
  }
109051
109381
  } else {
109052
109382
  for (const key of Object.keys(opts.headers)) {
109053
- headers2[key.toLowerCase()] = opts.headers[key];
109383
+ appendHeader(headers2, key, opts.headers[key]);
109054
109384
  }
109055
109385
  }
109056
109386
  } else {
@@ -109095,25 +109425,32 @@ function requireCache$2() {
109095
109425
  }
109096
109426
  function parseCacheControlHeader(header) {
109097
109427
  const output = {};
109098
- let directives;
109099
- if (Array.isArray(header)) {
109100
- directives = [];
109101
- for (const directive of header) {
109102
- directives.push(...directive.split(","));
109103
- }
109104
- } else {
109105
- directives = header.split(",");
109106
- }
109428
+ const invalidNumericDirectives = /* @__PURE__ */ new Set();
109429
+ const invalidNoArgumentDirectives = /* @__PURE__ */ new Set();
109430
+ const directives = splitCacheControlHeaderValue(Array.isArray(header) ? header.join(",") : header);
109107
109431
  for (let i = 0; i < directives.length; i++) {
109108
- const directive = directives[i].toLowerCase();
109432
+ const directiveRecord = directives[i];
109433
+ const directive = directiveRecord.value.toLowerCase();
109434
+ const fromMalformedQuote = directiveRecord.fromMalformedQuote;
109109
109435
  const keyValueDelimiter = directive.indexOf("=");
109110
109436
  let key;
109111
109437
  let value;
109438
+ let keyHasTrailingWhitespace = false;
109439
+ let valueHasLeadingWhitespace = false;
109112
109440
  if (keyValueDelimiter !== -1) {
109113
- key = directive.substring(0, keyValueDelimiter).trimStart();
109114
- value = directive.substring(keyValueDelimiter + 1);
109441
+ const rawKey = directive.substring(0, keyValueDelimiter);
109442
+ const rawValue = directive.substring(keyValueDelimiter + 1);
109443
+ keyHasTrailingWhitespace = trimOWSEnd(rawKey) !== rawKey;
109444
+ valueHasLeadingWhitespace = trimOWSStart(rawValue) !== rawValue;
109445
+ key = trimOWS(rawKey);
109446
+ value = trimOWSStart(rawValue);
109115
109447
  } else {
109116
- key = directive.trim();
109448
+ key = trimOWS(directive);
109449
+ }
109450
+ const malformedRestrictiveDirectiveName = getMalformedRestrictiveDirectiveName(key);
109451
+ if (malformedRestrictiveDirectiveName !== void 0) {
109452
+ output[malformedRestrictiveDirectiveName] = true;
109453
+ continue;
109117
109454
  }
109118
109455
  switch (key) {
109119
109456
  case "min-fresh":
@@ -109122,48 +109459,85 @@ function requireCache$2() {
109122
109459
  case "s-maxage":
109123
109460
  case "stale-while-revalidate":
109124
109461
  case "stale-if-error": {
109125
- if (value === void 0 || value[0] === " ") {
109462
+ if (fromMalformedQuote || invalidNumericDirectives.has(key)) {
109463
+ continue;
109464
+ }
109465
+ if (value === void 0 || keyHasTrailingWhitespace || valueHasLeadingWhitespace) {
109466
+ delete output[key];
109467
+ invalidNumericDirectives.add(key);
109468
+ markInvalidCacheControlDirective(output, key);
109126
109469
  continue;
109127
109470
  }
109128
109471
  if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') {
109129
109472
  value = value.substring(1, value.length - 1);
109130
109473
  }
109131
- const parsedValue = parseInt(value, 10);
109132
- if (parsedValue !== parsedValue) {
109474
+ if (!/^[0-9]+$/.test(value)) {
109475
+ delete output[key];
109476
+ invalidNumericDirectives.add(key);
109477
+ markInvalidCacheControlDirective(output, key);
109133
109478
  continue;
109134
109479
  }
109135
- if (key === "max-age" && key in output && output[key] >= parsedValue) {
109136
- continue;
109480
+ const parsedValue = Math.min(parseInt(value, 10), MAX_DELTA_SECONDS);
109481
+ if (key === "min-fresh") {
109482
+ if (!(key in output) || output[key] < parsedValue) {
109483
+ output[key] = parsedValue;
109484
+ }
109485
+ } else if (!(key in output) || output[key] > parsedValue) {
109486
+ output[key] = parsedValue;
109137
109487
  }
109138
- output[key] = parsedValue;
109139
109488
  break;
109140
109489
  }
109141
109490
  case "private":
109142
109491
  case "no-cache": {
109492
+ if (fromMalformedQuote) {
109493
+ output[key] = true;
109494
+ break;
109495
+ }
109496
+ if (value !== void 0 && value.length === 0) {
109497
+ output[key] = true;
109498
+ break;
109499
+ }
109143
109500
  if (value) {
109144
109501
  if (value[0] === '"') {
109145
- const headers2 = [value.substring(1)];
109146
- let foundEndingQuote = value[value.length - 1] === '"';
109147
- if (!foundEndingQuote) {
109502
+ value = trimOWSEnd(value);
109503
+ let fieldList = "";
109504
+ let lastQuotedPart = i;
109505
+ let foundEndingQuote = false;
109506
+ const closingQuote = findUnescapedQuote(value, 1);
109507
+ if (closingQuote !== -1) {
109508
+ fieldList = value.substring(1, closingQuote);
109509
+ foundEndingQuote = true;
109510
+ } else {
109511
+ const fieldListParts = [value.substring(1)];
109148
109512
  for (let j2 = i + 1; j2 < directives.length; j2++) {
109149
- const nextPart = directives[j2];
109150
- const nextPartLength = nextPart.length;
109151
- headers2.push(nextPart.trim());
109152
- if (nextPartLength !== 0 && nextPart[nextPartLength - 1] === '"') {
109513
+ const nextPart = trimOWS(directives[j2].value);
109514
+ const closingQuote2 = findUnescapedQuote(nextPart, 0);
109515
+ lastQuotedPart = j2;
109516
+ if (closingQuote2 !== -1) {
109517
+ fieldListParts.push(nextPart.substring(0, closingQuote2));
109153
109518
  foundEndingQuote = true;
109154
109519
  break;
109155
109520
  }
109521
+ fieldListParts.push(nextPart);
109156
109522
  }
109523
+ fieldList = fieldListParts.join(",");
109157
109524
  }
109158
- if (foundEndingQuote) {
109159
- let lastHeader = headers2[headers2.length - 1];
109160
- if (lastHeader[lastHeader.length - 1] === '"') {
109161
- lastHeader = lastHeader.substring(0, lastHeader.length - 1);
109162
- headers2[headers2.length - 1] = lastHeader;
109163
- }
109164
- for (let j2 = 0; j2 < headers2.length; j2++) {
109165
- headers2[j2] = headers2[j2].trim();
109525
+ if (!foundEndingQuote) {
109526
+ output[key] = true;
109527
+ break;
109528
+ }
109529
+ i = lastQuotedPart;
109530
+ const headers2 = fieldList.split(",");
109531
+ let validFieldNames = true;
109532
+ for (let j2 = 0; j2 < headers2.length; j2++) {
109533
+ headers2[j2] = trimOWS(headers2[j2]);
109534
+ if (!isValidHTTPToken(headers2[j2])) {
109535
+ validFieldNames = false;
109166
109536
  }
109537
+ }
109538
+ if (!validFieldNames) {
109539
+ output[key] = true;
109540
+ } else if (output[key] !== true) {
109167
109541
  if (key in output) {
109168
109542
  output[key] = output[key].concat(headers2);
109169
109543
  } else {
@@ -109171,11 +109545,15 @@ function requireCache$2() {
109171
109545
  }
109172
109546
  }
109173
109547
  } else {
109174
- const fieldName = value.trim();
109175
- if (key in output) {
109176
- output[key] = output[key].concat(fieldName);
109177
- } else {
109178
- output[key] = [fieldName];
109548
+ const fieldName = trimOWS(value);
109549
+ if (!isValidHTTPToken(fieldName)) {
109550
+ output[key] = true;
109551
+ } else if (output[key] !== true) {
109552
+ if (key in output) {
109553
+ output[key] = output[key].concat(fieldName);
109554
+ } else {
109555
+ output[key] = [fieldName];
109556
+ }
109179
109557
  }
109180
109558
  }
109181
109559
  break;
@@ -109183,39 +109561,76 @@ function requireCache$2() {
109183
109561
  }
109184
109562
  // eslint-disable-next-line no-fallthrough
109185
109563
  case "public":
109186
- case "no-store":
109187
109564
  case "must-revalidate":
109188
109565
  case "proxy-revalidate":
109189
109566
  case "immutable":
109190
109567
  case "no-transform":
109191
109568
  case "must-understand":
109192
109569
  case "only-if-cached":
109193
- if (value) {
109570
+ if (fromMalformedQuote || invalidNoArgumentDirectives.has(key)) {
109571
+ continue;
109572
+ }
109573
+ if (value !== void 0) {
109574
+ delete output[key];
109575
+ invalidNoArgumentDirectives.add(key);
109194
109576
  continue;
109195
109577
  }
109196
109578
  output[key] = true;
109197
109579
  break;
109580
+ case "no-store":
109581
+ output[key] = true;
109582
+ break;
109198
109583
  default:
109199
109584
  continue;
109200
109585
  }
109201
109586
  }
109202
109587
  return output;
109203
109588
  }
109589
+ function splitVaryHeader(varyHeader) {
109590
+ const values = Array.isArray(varyHeader) ? varyHeader : [varyHeader];
109591
+ const output = [];
109592
+ for (let i = 0; i < values.length; i++) {
109593
+ const parts = values[i].split(",");
109594
+ for (let j2 = 0; j2 < parts.length; j2++) {
109595
+ output.push(parts[j2]);
109596
+ }
109597
+ }
109598
+ return output;
109599
+ }
109600
+ function hasVaryStar(varyHeader) {
109601
+ const values = splitVaryHeader(varyHeader);
109602
+ for (let i = 0; i < values.length; i++) {
109603
+ if (trimOWS(values[i]).indexOf("*") !== -1) {
109604
+ return true;
109605
+ }
109606
+ }
109607
+ return false;
109608
+ }
109204
109609
  function parseVaryHeader(varyHeader, headers2) {
109205
- if (typeof varyHeader === "string" && varyHeader.includes("*")) {
109610
+ if (hasVaryStar(varyHeader)) {
109206
109611
  return headers2;
109207
109612
  }
109208
109613
  const output = (
109209
109614
  /** @type {Record<string, string | string[] | null>} */
109210
109615
  {}
109211
109616
  );
109212
- const varyingHeaders = typeof varyHeader === "string" ? varyHeader.split(",") : varyHeader;
109617
+ const varyingHeaders = splitVaryHeader(varyHeader);
109213
109618
  for (const header of varyingHeaders) {
109214
- const trimmedHeader = header.trim().toLowerCase();
109215
- output[trimmedHeader] = headers2[trimmedHeader] ?? null;
109619
+ const trimmedHeader = trimOWS(header).toLowerCase();
109620
+ if (trimmedHeader.length === 0) {
109621
+ continue;
109622
+ }
109623
+ if (!isValidHTTPToken(trimmedHeader)) {
109624
+ return void 0;
109625
+ }
109626
+ const headerValue = headers2[trimmedHeader];
109627
+ output[trimmedHeader] = Array.isArray(headerValue) ? headerValue.slice() : headerValue ?? null;
109216
109628
  }
109217
109629
  return output;
109218
109630
  }
109631
+ function isInvalidOrWildcardVaryHeader(varyHeader) {
109632
+ return hasVaryStar(varyHeader) || parseVaryHeader(varyHeader, {}) === void 0;
109633
+ }
109219
109634
  function isEtagUsable(etag) {
109220
109635
  if (etag.length <= 2) {
109221
109636
  return false;
@@ -109246,7 +109661,7 @@ function requireCache$2() {
109246
109661
  throw new TypeError(`${name2} needs to have at least one method`);
109247
109662
  }
109248
109663
  for (const method of methods) {
109249
- if (!safeHTTPMethods.includes(method)) {
109664
+ if (!arrayIncludes(safeHTTPMethods, method)) {
109250
109665
  throw new TypeError(`element of ${name2}-array needs to be one of following values: ${safeHTTPMethods.join(", ")}, got ${method}`);
109251
109666
  }
109252
109667
  }
@@ -109270,7 +109685,10 @@ function requireCache$2() {
109270
109685
  assertCacheKey,
109271
109686
  assertCacheValue,
109272
109687
  parseCacheControlHeader,
109688
+ hasInvalidCacheControlDirective,
109273
109689
  parseVaryHeader,
109690
+ hasVaryStar,
109691
+ isInvalidOrWildcardVaryHeader,
109274
109692
  isEtagUsable,
109275
109693
  assertCacheMethods,
109276
109694
  assertCacheStore,
@@ -109293,6 +109711,13 @@ function requireDate() {
109293
109711
  return parseRfc850Date(date2);
109294
109712
  }
109295
109713
  }
109714
+ function makeDate(year, monthIdx, day, hour, minute, second, weekday) {
109715
+ const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
109716
+ if (year >= 0 && year <= 99) {
109717
+ result.setUTCFullYear(year);
109718
+ }
109719
+ 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;
109720
+ }
109296
109721
  function parseImfDate(date2) {
109297
109722
  if (date2.length !== 29 || date2[4] !== " " || date2[7] !== " " || date2[11] !== " " || date2[16] !== " " || date2[19] !== ":" || date2[22] !== ":" || date2[25] !== " " || date2[26] !== "G" || date2[27] !== "M" || date2[28] !== "T") {
109298
109723
  return void 0;
@@ -109453,8 +109878,7 @@ function requireDate() {
109453
109878
  }
109454
109879
  second = (code1 - 48) * 10 + (code2 - 48);
109455
109880
  }
109456
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
109457
- return result.getUTCDay() === weekday ? result : void 0;
109881
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
109458
109882
  }
109459
109883
  function parseAscTimeDate(date2) {
109460
109884
  if (date2.length !== 24 || date2[7] !== " " || date2[10] !== " " || date2[19] !== " ") {
@@ -109616,8 +110040,7 @@ function requireDate() {
109616
110040
  return void 0;
109617
110041
  }
109618
110042
  const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48);
109619
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
109620
- return result.getUTCDay() === weekday ? result : void 0;
110043
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
109621
110044
  }
109622
110045
  function parseRfc850Date(date2) {
109623
110046
  let commaIndex = -1;
@@ -109766,8 +110189,7 @@ function requireDate() {
109766
110189
  }
109767
110190
  second = (code1 - 48) * 10 + (code2 - 48);
109768
110191
  }
109769
- const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
109770
- return result.getUTCDay() === weekday ? result : void 0;
110192
+ return makeDate(year, monthIdx, day, hour, minute, second, weekday);
109771
110193
  }
109772
110194
  date$1 = {
109773
110195
  parseHttpDate
@@ -109783,7 +110205,10 @@ function requireCacheHandler() {
109783
110205
  const util2 = requireUtil$5();
109784
110206
  const {
109785
110207
  parseCacheControlHeader,
110208
+ hasInvalidCacheControlDirective,
109786
110209
  parseVaryHeader,
110210
+ hasVaryStar,
110211
+ isInvalidOrWildcardVaryHeader,
109787
110212
  isEtagUsable
109788
110213
  } = requireCache$2();
109789
110214
  const { parseHttpDate } = requireDate();
@@ -109807,6 +110232,78 @@ function requireCacheHandler() {
109807
110232
  206
109808
110233
  ];
109809
110234
  const MAX_RESPONSE_AGE = 2147483647e3;
110235
+ function trimOWS(value) {
110236
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
110237
+ }
110238
+ function arrayIncludes(array2, value) {
110239
+ for (let i = 0; i < array2.length; i++) {
110240
+ if (array2[i] === value) {
110241
+ return true;
110242
+ }
110243
+ }
110244
+ return false;
110245
+ }
110246
+ function appendConnectionHeaderTokens(headersToRemove, connectionHeader) {
110247
+ const values = Array.isArray(connectionHeader) ? connectionHeader : [connectionHeader];
110248
+ for (let i = 0; i < values.length; i++) {
110249
+ const tokens = values[i].split(",");
110250
+ for (let j2 = 0; j2 < tokens.length; j2++) {
110251
+ headersToRemove.push(trimOWS(tokens[j2]).toLowerCase());
110252
+ }
110253
+ }
110254
+ }
110255
+ function getSameOriginPath(cacheKey, location2) {
110256
+ if (typeof location2 !== "string") {
110257
+ return void 0;
110258
+ }
110259
+ let originUrl;
110260
+ let requestUrl;
110261
+ let locationUrl;
110262
+ try {
110263
+ originUrl = new URL(cacheKey.origin);
110264
+ requestUrl = new URL(cacheKey.path, originUrl);
110265
+ locationUrl = new URL(location2, requestUrl);
110266
+ } catch {
110267
+ return void 0;
110268
+ }
110269
+ if (locationUrl.origin !== originUrl.origin) {
110270
+ return void 0;
110271
+ }
110272
+ return locationUrl.pathname + locationUrl.search;
110273
+ }
110274
+ function deleteCachedUri(store, cacheKey, path2) {
110275
+ deleteCachedValue(store, {
110276
+ ...cacheKey,
110277
+ path: path2
110278
+ });
110279
+ for (let i = 0; i < util2.safeHTTPMethods.length; i++) {
110280
+ const method = util2.safeHTTPMethods[i];
110281
+ if (method !== cacheKey.method) {
110282
+ deleteCachedValue(store, {
110283
+ ...cacheKey,
110284
+ method,
110285
+ path: path2
110286
+ });
110287
+ }
110288
+ }
110289
+ }
110290
+ function deleteLocationTargets(store, cacheKey, headerValue) {
110291
+ if (headerValue === void 0) {
110292
+ return;
110293
+ }
110294
+ const values = Array.isArray(headerValue) ? headerValue : [headerValue];
110295
+ for (let i = 0; i < values.length; i++) {
110296
+ const path2 = getSameOriginPath(cacheKey, values[i]);
110297
+ if (path2 !== void 0) {
110298
+ deleteCachedUri(store, cacheKey, path2);
110299
+ }
110300
+ }
110301
+ }
110302
+ function invalidateUnsafeRequest(store, cacheKey, resHeaders) {
110303
+ deleteCachedUri(store, cacheKey, cacheKey.path);
110304
+ deleteLocationTargets(store, cacheKey, resHeaders.location);
110305
+ deleteLocationTargets(store, cacheKey, resHeaders["content-location"]);
110306
+ }
109810
110307
  class CacheHandler {
109811
110308
  /**
109812
110309
  * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} opts
@@ -109861,11 +110358,10 @@ function requireCacheHandler() {
109861
110358
  * @param {string} statusMessage
109862
110359
  */
109863
110360
  onResponseStart(controller, statusCode, resHeaders, statusMessage) {
109864
- var _a3, _b2;
109865
110361
  const downstreamOnHeaders = () => {
109866
- var _a4, _b3;
109867
- return (_b3 = (_a4 = __privateGet(this, _handler)).onResponseStart) == null ? void 0 : _b3.call(
109868
- _a4,
110362
+ var _a3, _b2;
110363
+ return (_b2 = (_a3 = __privateGet(this, _handler)).onResponseStart) == null ? void 0 : _b2.call(
110364
+ _a3,
109869
110365
  controller,
109870
110366
  statusCode,
109871
110367
  resHeaders,
@@ -109873,35 +110369,53 @@ function requireCacheHandler() {
109873
110369
  );
109874
110370
  };
109875
110371
  const handler = this;
109876
- if (!util2.safeHTTPMethods.includes(__privateGet(this, _cacheKey).method) && statusCode >= 200 && statusCode <= 399) {
109877
- try {
109878
- (_b2 = (_a3 = __privateGet(this, _store).delete(__privateGet(this, _cacheKey))) == null ? void 0 : _a3.catch) == null ? void 0 : _b2.call(_a3, noop3);
109879
- } catch {
109880
- }
110372
+ if (!arrayIncludes(util2.safeHTTPMethods, __privateGet(this, _cacheKey).method) && statusCode >= 200 && statusCode <= 399) {
110373
+ invalidateUnsafeRequest(__privateGet(this, _store), __privateGet(this, _cacheKey), resHeaders);
109881
110374
  return downstreamOnHeaders();
109882
110375
  }
109883
110376
  const cacheControlHeader = resHeaders["cache-control"];
109884
- const heuristicallyCacheable = resHeaders["last-modified"] && HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode);
110377
+ const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
110378
+ if (revalidationResponseDisallowsCachedReuse(__privateGet(this, _cacheType), resHeaders, cacheControlDirectives)) {
110379
+ deleteCachedValue(__privateGet(this, _store), __privateGet(this, _cacheKey));
110380
+ return downstreamOnHeaders();
110381
+ }
110382
+ const heuristicallyCacheable = resHeaders["last-modified"] && arrayIncludes(HEURISTICALLY_CACHEABLE_STATUS_CODES, statusCode);
109885
110383
  if (!cacheControlHeader && !resHeaders["expires"] && !heuristicallyCacheable && !__privateGet(this, _cacheByDefault)) {
110384
+ if (statusCode === 304 && resHeaders.vary && isInvalidOrWildcardVaryHeader(resHeaders.vary)) {
110385
+ deleteCachedValue(__privateGet(this, _store), __privateGet(this, _cacheKey));
110386
+ }
109886
110387
  return downstreamOnHeaders();
109887
110388
  }
109888
- const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
109889
- if (!canCacheResponse(__privateGet(this, _cacheType), statusCode, resHeaders, cacheControlDirectives, __privateGet(this, _cacheKey).headers)) {
110389
+ if (!canCacheResponse(__privateGet(this, _cacheType), __privateGet(this, _cacheKey).method, statusCode, resHeaders, cacheControlDirectives, __privateGet(this, _cacheKey).headers)) {
110390
+ if (statusCode === 304 && (cacheControlHeader || revalidationResponseDisallowsCachedReuse(__privateGet(this, _cacheType), resHeaders, cacheControlDirectives))) {
110391
+ deleteCachedValue(__privateGet(this, _store), __privateGet(this, _cacheKey));
110392
+ }
109890
110393
  return downstreamOnHeaders();
109891
110394
  }
109892
110395
  const now2 = Date.now();
109893
- const resAge = resHeaders.age ? getAge(resHeaders.age) : void 0;
109894
- if (resAge && resAge >= MAX_RESPONSE_AGE) {
110396
+ const resAge = Object.hasOwn(resHeaders, "age") ? getAge(resHeaders.age) : void 0;
110397
+ if (resAge !== void 0 && resAge >= MAX_RESPONSE_AGE) {
110398
+ deleteCachedValueIfNotModified(statusCode, __privateGet(this, _store), __privateGet(this, _cacheKey));
109895
110399
  return downstreamOnHeaders();
109896
110400
  }
109897
- const resDate = typeof resHeaders.date === "string" ? parseHttpDate(resHeaders.date) : void 0;
110401
+ const resDate = Object.hasOwn(resHeaders, "date") ? getDate(resHeaders.date) : void 0;
110402
+ if (resDate === null) {
110403
+ deleteCachedValueIfNotModified(statusCode, __privateGet(this, _store), __privateGet(this, _cacheKey));
110404
+ return downstreamOnHeaders();
110405
+ }
110406
+ const apparentAge = resDate ? Math.max(0, now2 - resDate.getTime()) : 0;
110407
+ const currentAge = Math.max(apparentAge, resAge ?? 0);
109898
110408
  const staleAt = determineStaleAt(__privateGet(this, _cacheType), now2, resAge, resHeaders, resDate, cacheControlDirectives) ?? __privateGet(this, _cacheByDefault);
109899
- if (staleAt === void 0 || resAge && resAge > staleAt) {
110409
+ if (staleAt === void 0 || currentAge >= staleAt) {
110410
+ if (cacheControlHeader || staleAt !== void 0) {
110411
+ deleteCachedValueIfNotModified(statusCode, __privateGet(this, _store), __privateGet(this, _cacheKey));
110412
+ }
109900
110413
  return downstreamOnHeaders();
109901
110414
  }
109902
- const baseTime = resDate ? resDate.getTime() : now2;
110415
+ const baseTime = now2 - currentAge;
109903
110416
  const absoluteStaleAt = staleAt + baseTime;
109904
110417
  if (now2 >= absoluteStaleAt) {
110418
+ deleteCachedValueIfNotModified(statusCode, __privateGet(this, _store), __privateGet(this, _cacheKey));
109905
110419
  return downstreamOnHeaders();
109906
110420
  }
109907
110421
  let varyDirectives;
@@ -109911,7 +110425,8 @@ function requireCacheHandler() {
109911
110425
  return downstreamOnHeaders();
109912
110426
  }
109913
110427
  }
109914
- const deleteAt = determineDeleteAt(baseTime, cacheControlDirectives, absoluteStaleAt);
110428
+ const cachedAt = baseTime;
110429
+ const deleteAt = determineDeleteAt(baseTime, now2, cacheControlDirectives, absoluteStaleAt);
109915
110430
  const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives);
109916
110431
  const value = {
109917
110432
  statusCode,
@@ -109919,7 +110434,7 @@ function requireCacheHandler() {
109919
110434
  headers: strippedHeaders,
109920
110435
  vary: varyDirectives,
109921
110436
  cacheControlDirectives,
109922
- cachedAt: resAge ? now2 - resAge : now2,
110437
+ cachedAt,
109923
110438
  staleAt: absoluteStaleAt,
109924
110439
  deleteAt
109925
110440
  };
@@ -109931,6 +110446,7 @@ function requireCacheHandler() {
109931
110446
  value.statusCode = cachedValue.statusCode;
109932
110447
  value.statusMessage = cachedValue.statusMessage;
109933
110448
  value.etag = cachedValue.etag;
110449
+ value.vary = varyDirectives ?? cachedValue.vary;
109934
110450
  value.headers = { ...cachedValue.headers, ...strippedHeaders };
109935
110451
  downstreamOnHeaders();
109936
110452
  __privateSet(this, _writeStream, __privateGet(this, _store).createWriteStream(__privateGet(this, _cacheKey), value));
@@ -109940,10 +110456,10 @@ function requireCacheHandler() {
109940
110456
  if (typeof cachedValue.body.values === "function") {
109941
110457
  const bodyIterator = cachedValue.body.values();
109942
110458
  const streamCachedBody = () => {
109943
- var _a4, _b3;
110459
+ var _a3, _b2;
109944
110460
  for (const chunk of bodyIterator) {
109945
110461
  const full = __privateGet(this, _writeStream).write(chunk) === false;
109946
- (_b3 = (_a4 = __privateGet(this, _handler)).onResponseData) == null ? void 0 : _b3.call(_a4, controller, chunk);
110462
+ (_b2 = (_a3 = __privateGet(this, _handler)).onResponseData) == null ? void 0 : _b2.call(_a3, controller, chunk);
109947
110463
  if (full) {
109948
110464
  break;
109949
110465
  }
@@ -109962,9 +110478,9 @@ function requireCacheHandler() {
109962
110478
  streamCachedBody();
109963
110479
  } else if (typeof cachedValue.body.on === "function") {
109964
110480
  cachedValue.body.on("data", (chunk) => {
109965
- var _a4, _b3;
110481
+ var _a3, _b2;
109966
110482
  __privateGet(this, _writeStream).write(chunk);
109967
- (_b3 = (_a4 = __privateGet(this, _handler)).onResponseData) == null ? void 0 : _b3.call(_a4, controller, chunk);
110483
+ (_b2 = (_a3 = __privateGet(this, _handler)).onResponseData) == null ? void 0 : _b2.call(_a3, controller, chunk);
109968
110484
  }).on("end", () => {
109969
110485
  __privateGet(this, _writeStream).end();
109970
110486
  }).on("error", () => {
@@ -110032,75 +110548,130 @@ function requireCacheHandler() {
110032
110548
  _store = new WeakMap();
110033
110549
  _handler = new WeakMap();
110034
110550
  _writeStream = new WeakMap();
110035
- function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
110036
- var _a3;
110037
- if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) {
110551
+ function deleteCachedValue(store, cacheKey) {
110552
+ var _a3, _b2;
110553
+ try {
110554
+ (_b2 = (_a3 = store.delete(cacheKey)) == null ? void 0 : _a3.catch) == null ? void 0 : _b2.call(_a3, noop3);
110555
+ } catch {
110556
+ }
110557
+ }
110558
+ function deleteCachedValueIfNotModified(statusCode, store, cacheKey) {
110559
+ if (statusCode === 304) {
110560
+ deleteCachedValue(store, cacheKey);
110561
+ }
110562
+ }
110563
+ function revalidationResponseDisallowsCachedReuse(cacheType, resHeaders, cacheControlDirectives) {
110564
+ return cacheControlDirectives["no-store"] === true || cacheType === "shared" && (cacheControlDirectives.private === true || Object.hasOwn(resHeaders, "set-cookie")) || (resHeaders.vary ? isInvalidOrWildcardVaryHeader(resHeaders.vary) : false);
110565
+ }
110566
+ function canCacheResponse(cacheType, method, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
110567
+ if (!arrayIncludes(util2.safeHTTPMethods, method)) {
110038
110568
  return false;
110039
110569
  }
110040
- 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
110570
+ if (statusCode < 200 || arrayIncludes(NOT_UNDERSTOOD_STATUS_CODES, statusCode)) {
110571
+ return false;
110572
+ }
110573
+ 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
110041
110574
  !(cacheControlDirectives.private && cacheType === "private") && !(cacheControlDirectives["s-maxage"] !== void 0 && cacheType === "shared")) {
110042
110575
  return false;
110043
110576
  }
110044
110577
  if (cacheControlDirectives["no-store"]) {
110045
110578
  return false;
110046
110579
  }
110047
- if (cacheType === "shared" && cacheControlDirectives.private === true) {
110580
+ if (cacheType === "shared" && (cacheControlDirectives.private === true || Object.hasOwn(resHeaders, "set-cookie"))) {
110048
110581
  return false;
110049
110582
  }
110050
- if ((_a3 = resHeaders.vary) == null ? void 0 : _a3.includes("*")) {
110583
+ if (resHeaders.vary && hasVaryStar(resHeaders.vary)) {
110051
110584
  return false;
110052
110585
  }
110053
- if (reqHeaders == null ? void 0 : reqHeaders.authorization) {
110586
+ if (reqHeaders != null && Object.hasOwn(reqHeaders, "authorization")) {
110054
110587
  if (!cacheControlDirectives.public && !cacheControlDirectives["s-maxage"] && !cacheControlDirectives["must-revalidate"]) {
110055
110588
  return false;
110056
110589
  }
110057
110590
  if (typeof reqHeaders.authorization !== "string") {
110058
110591
  return false;
110059
110592
  }
110060
- if (Array.isArray(cacheControlDirectives["no-cache"]) && cacheControlDirectives["no-cache"].includes("authorization")) {
110593
+ if (Array.isArray(cacheControlDirectives["no-cache"]) && arrayIncludes(cacheControlDirectives["no-cache"], "authorization")) {
110061
110594
  return false;
110062
110595
  }
110063
- if (Array.isArray(cacheControlDirectives["private"]) && cacheControlDirectives["private"].includes("authorization")) {
110596
+ if (Array.isArray(cacheControlDirectives["private"]) && arrayIncludes(cacheControlDirectives["private"], "authorization")) {
110064
110597
  return false;
110065
110598
  }
110066
110599
  }
110067
110600
  return true;
110068
110601
  }
110602
+ function getDate(dateHeader) {
110603
+ let dateValue = dateHeader;
110604
+ if (Array.isArray(dateValue)) {
110605
+ if (dateValue.length !== 1) {
110606
+ return null;
110607
+ }
110608
+ dateValue = dateValue[0];
110609
+ }
110610
+ if (typeof dateValue !== "string") {
110611
+ return null;
110612
+ }
110613
+ return parseHttpDate(dateValue);
110614
+ }
110069
110615
  function getAge(ageHeader) {
110070
- const age = parseInt(Array.isArray(ageHeader) ? ageHeader[0] : ageHeader);
110071
- return isNaN(age) ? void 0 : age * 1e3;
110616
+ let ageValue = ageHeader;
110617
+ if (Array.isArray(ageValue)) {
110618
+ if (ageValue.length !== 1) {
110619
+ return MAX_RESPONSE_AGE;
110620
+ }
110621
+ ageValue = ageValue[0];
110622
+ }
110623
+ if (typeof ageValue !== "string" || !/^[\t ]*[0-9]+[\t ]*$/.test(ageValue)) {
110624
+ return MAX_RESPONSE_AGE;
110625
+ }
110626
+ const age = BigInt(ageValue.replace(/^[\t ]+|[\t ]+$/g, ""));
110627
+ if (age >= BigInt(MAX_RESPONSE_AGE / 1e3)) {
110628
+ return MAX_RESPONSE_AGE;
110629
+ }
110630
+ return Number(age) * 1e3;
110072
110631
  }
110073
110632
  function determineStaleAt(cacheType, now2, age, resHeaders, responseDate, cacheControlDirectives) {
110074
110633
  if (cacheType === "shared") {
110634
+ if (hasInvalidCacheControlDirective(cacheControlDirectives, "s-maxage")) {
110635
+ return 0;
110636
+ }
110075
110637
  const sMaxAge = cacheControlDirectives["s-maxage"];
110076
110638
  if (sMaxAge !== void 0) {
110077
- return sMaxAge > 0 ? sMaxAge * 1e3 : void 0;
110639
+ return sMaxAge * 1e3;
110078
110640
  }
110079
110641
  }
110642
+ if (hasInvalidCacheControlDirective(cacheControlDirectives, "max-age")) {
110643
+ return 0;
110644
+ }
110080
110645
  const maxAge = cacheControlDirectives["max-age"];
110081
110646
  if (maxAge !== void 0) {
110082
- return maxAge > 0 ? maxAge * 1e3 : void 0;
110647
+ return maxAge * 1e3;
110083
110648
  }
110084
- if (typeof resHeaders.expires === "string") {
110649
+ if (Object.hasOwn(resHeaders, "expires")) {
110650
+ if (typeof resHeaders.expires !== "string") {
110651
+ return 0;
110652
+ }
110085
110653
  const expiresDate = parseHttpDate(resHeaders.expires);
110086
- if (expiresDate) {
110087
- if (now2 >= expiresDate.getTime()) {
110088
- return void 0;
110654
+ if (!expiresDate) {
110655
+ return 0;
110656
+ }
110657
+ if (now2 >= expiresDate.getTime()) {
110658
+ return 0;
110659
+ }
110660
+ if (responseDate) {
110661
+ if (responseDate >= expiresDate) {
110662
+ return 0;
110089
110663
  }
110090
- if (responseDate) {
110091
- if (responseDate >= expiresDate) {
110092
- return void 0;
110093
- }
110094
- if (age !== void 0 && age > expiresDate - responseDate) {
110095
- return void 0;
110096
- }
110664
+ const freshnessLifetime = expiresDate.getTime() - responseDate.getTime();
110665
+ if (age !== void 0 && age >= freshnessLifetime) {
110666
+ return 0;
110097
110667
  }
110098
- return expiresDate.getTime() - now2;
110668
+ return freshnessLifetime;
110099
110669
  }
110670
+ return expiresDate.getTime() - now2;
110100
110671
  }
110101
110672
  if (typeof resHeaders["last-modified"] === "string") {
110102
- const lastModified = new Date(resHeaders["last-modified"]);
110103
- if (isValidDate(lastModified)) {
110673
+ const lastModified = parseHttpDate(resHeaders["last-modified"]);
110674
+ if (lastModified) {
110104
110675
  if (lastModified.getTime() >= now2) {
110105
110676
  return void 0;
110106
110677
  }
@@ -110109,11 +110680,11 @@ function requireCacheHandler() {
110109
110680
  }
110110
110681
  }
110111
110682
  if (cacheControlDirectives.immutable) {
110112
- return 31536e3;
110683
+ return 31536e6;
110113
110684
  }
110114
110685
  return void 0;
110115
110686
  }
110116
- function determineDeleteAt(now2, cacheControlDirectives, staleAt) {
110687
+ function determineDeleteAt(baseTime, cachedAt, cacheControlDirectives, staleAt) {
110117
110688
  let staleWhileRevalidate = -Infinity;
110118
110689
  let staleIfError = -Infinity;
110119
110690
  let immutable = -Infinity;
@@ -110124,11 +110695,12 @@ function requireCacheHandler() {
110124
110695
  staleIfError = staleAt + cacheControlDirectives["stale-if-error"] * 1e3;
110125
110696
  }
110126
110697
  if (cacheControlDirectives.immutable && staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
110127
- immutable = now2 + 31536e6;
110698
+ immutable = cachedAt + 31536e6;
110128
110699
  }
110129
110700
  if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) {
110130
- const freshnessLifetime = staleAt - now2;
110131
- return staleAt + freshnessLifetime;
110701
+ const freshnessLifetime = staleAt - baseTime;
110702
+ const datePrecisionPadding = Math.min(Math.max(cachedAt - baseTime, 0), 1e3);
110703
+ return staleAt + freshnessLifetime + datePrecisionPadding;
110132
110704
  }
110133
110705
  return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable);
110134
110706
  }
@@ -110146,11 +110718,7 @@ function requireCacheHandler() {
110146
110718
  "age"
110147
110719
  ];
110148
110720
  if (resHeaders["connection"]) {
110149
- if (Array.isArray(resHeaders["connection"])) {
110150
- headersToRemove.push(...resHeaders["connection"].map((header) => header.trim()));
110151
- } else {
110152
- headersToRemove.push(...resHeaders["connection"].split(",").map((header) => header.trim()));
110153
- }
110721
+ appendConnectionHeaderTokens(headersToRemove, resHeaders["connection"]);
110154
110722
  }
110155
110723
  if (Array.isArray(cacheControlDirectives["no-cache"])) {
110156
110724
  headersToRemove.push(...cacheControlDirectives["no-cache"]);
@@ -110160,16 +110728,13 @@ function requireCacheHandler() {
110160
110728
  }
110161
110729
  let strippedHeaders;
110162
110730
  for (const headerName of headersToRemove) {
110163
- if (resHeaders[headerName]) {
110731
+ if (Object.hasOwn(resHeaders, headerName)) {
110164
110732
  strippedHeaders ?? (strippedHeaders = { ...resHeaders });
110165
110733
  delete strippedHeaders[headerName];
110166
110734
  }
110167
110735
  }
110168
110736
  return strippedHeaders ?? resHeaders;
110169
110737
  }
110170
- function isValidDate(date2) {
110171
- return date2 instanceof Date && Number.isFinite(date2.valueOf());
110172
- }
110173
110738
  cacheHandler = CacheHandler;
110174
110739
  return cacheHandler;
110175
110740
  }
@@ -110348,12 +110913,44 @@ function requireMemoryCacheStore() {
110348
110913
  _entries = new WeakMap();
110349
110914
  _hasEmittedMaxSizeEvent = new WeakMap();
110350
110915
  function findEntry(key, entries, now2) {
110351
- return entries.find((entry2) => entry2.deleteAt > now2 && entry2.method === key.method && (entry2.vary == null || Object.keys(entry2.vary).every((headerName) => {
110352
- if (entry2.vary[headerName] === null) {
110353
- return key.headers[headerName] === void 0;
110916
+ for (let i = 0; i < entries.length; i++) {
110917
+ const entry2 = entries[i];
110918
+ if (entry2.deleteAt > now2 && entry2.method === key.method && varyMatches(key, entry2)) {
110919
+ return entry2;
110354
110920
  }
110355
- return entry2.vary[headerName] === key.headers[headerName];
110356
- })));
110921
+ }
110922
+ }
110923
+ function varyMatches(key, entry2) {
110924
+ var _a3;
110925
+ if (entry2.vary == null) {
110926
+ return true;
110927
+ }
110928
+ for (const headerName in entry2.vary) {
110929
+ if (Object.hasOwn(entry2.vary, headerName) && !headerValueEquals((_a3 = key.headers) == null ? void 0 : _a3[headerName], entry2.vary[headerName])) {
110930
+ return false;
110931
+ }
110932
+ }
110933
+ return true;
110934
+ }
110935
+ function headerValueEquals(lhs, rhs) {
110936
+ if (lhs == null && rhs == null) {
110937
+ return true;
110938
+ }
110939
+ if (lhs == null && rhs != null || lhs != null && rhs == null) {
110940
+ return false;
110941
+ }
110942
+ if (Array.isArray(lhs) && Array.isArray(rhs)) {
110943
+ if (lhs.length !== rhs.length) {
110944
+ return false;
110945
+ }
110946
+ for (let i = 0; i < lhs.length; i++) {
110947
+ if (lhs[i] !== rhs[i]) {
110948
+ return false;
110949
+ }
110950
+ }
110951
+ return true;
110952
+ }
110953
+ return lhs === rhs;
110357
110954
  }
110358
110955
  memoryCacheStore = MemoryCacheStore;
110359
110956
  return memoryCacheStore;
@@ -110367,14 +110964,14 @@ function requireCacheRevalidationHandler() {
110367
110964
  const assert2 = require$$0$4;
110368
110965
  class CacheRevalidationHandler {
110369
110966
  /**
110370
- * @param {(boolean) => void} callback Function to call if the cached value is valid
110967
+ * @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
110371
110968
  * @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler
110372
110969
  * @param {boolean} allowErrorStatusCodes
110373
110970
  */
110374
110971
  constructor(callback, handler, allowErrorStatusCodes) {
110375
110972
  __privateAdd(this, _successful, false);
110376
110973
  /**
110377
- * @type {((boolean, any) => void) | null}
110974
+ * @type {((success: boolean, context?: any, statusCode?: number, headers?: import('../../types/header.d.ts').IncomingHttpHeaders) => void) | null}
110378
110975
  */
110379
110976
  __privateAdd(this, _callback);
110380
110977
  /**
@@ -110405,7 +111002,7 @@ function requireCacheRevalidationHandler() {
110405
111002
  var _a3, _b2, _c, _d;
110406
111003
  assert2(__privateGet(this, _callback) != null);
110407
111004
  __privateSet(this, _successful, statusCode === 304 || __privateGet(this, _allowErrorStatusCodes) && statusCode >= 500 && statusCode <= 504);
110408
- __privateGet(this, _callback).call(this, __privateGet(this, _successful), __privateGet(this, _context));
111005
+ __privateGet(this, _callback).call(this, __privateGet(this, _successful), __privateGet(this, _context), statusCode, headers2);
110409
111006
  __privateSet(this, _callback, null);
110410
111007
  if (__privateGet(this, _successful)) {
110411
111008
  return true;
@@ -110467,8 +111064,9 @@ function requireCache$1() {
110467
111064
  const CacheHandler = requireCacheHandler();
110468
111065
  const MemoryCacheStore = requireMemoryCacheStore();
110469
111066
  const CacheRevalidationHandler = requireCacheRevalidationHandler();
110470
- const { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader } = requireCache$2();
111067
+ const { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader, isInvalidOrWildcardVaryHeader } = requireCache$2();
110471
111068
  const { AbortError } = requireErrors();
111069
+ const { parseHttpDate } = requireDate();
110472
111070
  function assertCacheOrigins(origins, name2) {
110473
111071
  if (origins === void 0) return;
110474
111072
  if (!Array.isArray(origins)) {
@@ -110483,6 +111081,37 @@ function requireCache$1() {
110483
111081
  }
110484
111082
  const nop = () => {
110485
111083
  };
111084
+ function trimOWS(value) {
111085
+ return value.replace(/^[\t ]+|[\t ]+$/g, "");
111086
+ }
111087
+ function arrayIncludes(array2, value) {
111088
+ for (let i = 0; i < array2.length; i++) {
111089
+ if (array2[i] === value) {
111090
+ return true;
111091
+ }
111092
+ }
111093
+ return false;
111094
+ }
111095
+ function hasPragmaNoCache(headers2) {
111096
+ const pragma = headers2 == null ? void 0 : headers2.pragma;
111097
+ if (!pragma) {
111098
+ return false;
111099
+ }
111100
+ const values = Array.isArray(pragma) ? pragma : [pragma];
111101
+ for (let i = 0; i < values.length; i++) {
111102
+ const value = values[i];
111103
+ if (typeof value !== "string") {
111104
+ continue;
111105
+ }
111106
+ const directives = value.split(",");
111107
+ for (let j2 = 0; j2 < directives.length; j2++) {
111108
+ if (trimOWS(directives[j2]).toLowerCase() === "no-cache") {
111109
+ return true;
111110
+ }
111111
+ }
111112
+ }
111113
+ return false;
111114
+ }
110486
111115
  function needsRevalidation(result, cacheControlDirectives, { headers: headers2 = {} }) {
110487
111116
  var _a3;
110488
111117
  if (cacheControlDirectives == null ? void 0 : cacheControlDirectives["no-cache"]) {
@@ -110496,10 +111125,60 @@ function requireCache$1() {
110496
111125
  }
110497
111126
  return false;
110498
111127
  }
110499
- function isStale(result, cacheControlDirectives) {
111128
+ function staleResponseRequiresRevalidation(result, cacheType) {
111129
+ var _a3, _b2, _c;
111130
+ return ((_a3 = result.cacheControlDirectives) == null ? void 0 : _a3["must-revalidate"]) === true || cacheType === "shared" && (((_b2 = result.cacheControlDirectives) == null ? void 0 : _b2["proxy-revalidate"]) === true || // https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.10
111131
+ // s-maxage implies proxy-revalidate for shared caches.
111132
+ ((_c = result.cacheControlDirectives) == null ? void 0 : _c["s-maxage"]) !== void 0);
111133
+ }
111134
+ function revalidationResponseDisallowsCachedReuse(cacheType, headers2) {
111135
+ if (headers2.vary && isInvalidOrWildcardVaryHeader(headers2.vary) || cacheType === "shared" && Object.hasOwn(headers2, "set-cookie")) {
111136
+ return true;
111137
+ }
111138
+ const cacheControl = headers2["cache-control"];
111139
+ if (!cacheControl) {
111140
+ return false;
111141
+ }
111142
+ const cacheControlDirectives = parseCacheControlHeader(cacheControl);
111143
+ return cacheControlDirectives["no-store"] === true || cacheType === "shared" && cacheControlDirectives.private === true;
111144
+ }
111145
+ function revalidationResponseUpdatesCacheControl(headers2) {
111146
+ return headers2["cache-control"] !== void 0;
111147
+ }
111148
+ function deleteCachedValue(store, cacheKey) {
111149
+ var _a3, _b2;
111150
+ try {
111151
+ (_b2 = (_a3 = store.delete(cacheKey)) == null ? void 0 : _a3.catch) == null ? void 0 : _b2.call(_a3, nop);
111152
+ } catch {
111153
+ }
111154
+ }
111155
+ function getUsableLastModified(headers2) {
111156
+ const lastModified = headers2 == null ? void 0 : headers2["last-modified"];
111157
+ if (typeof lastModified === "string" && parseHttpDate(lastModified)) {
111158
+ return lastModified;
111159
+ }
111160
+ }
111161
+ function makeRevalidationHeaders(opts, result) {
111162
+ const headers2 = {
111163
+ ...opts.headers,
111164
+ "if-modified-since": getUsableLastModified(result.headers) ?? new Date(result.cachedAt).toUTCString()
111165
+ };
111166
+ if (result.etag) {
111167
+ headers2["if-none-match"] = result.etag;
111168
+ }
111169
+ if (result.vary) {
111170
+ for (const key in result.vary) {
111171
+ if (result.vary[key] != null) {
111172
+ headers2[key] = result.vary[key];
111173
+ }
111174
+ }
111175
+ }
111176
+ return headers2;
111177
+ }
111178
+ function isStale(result, cacheControlDirectives, cacheType) {
110500
111179
  const now2 = Date.now();
110501
111180
  if (now2 > result.staleAt) {
110502
- if (cacheControlDirectives == null ? void 0 : cacheControlDirectives["max-stale"]) {
111181
+ if (!staleResponseRequiresRevalidation(result, cacheType) && (cacheControlDirectives == null ? void 0 : cacheControlDirectives["max-stale"])) {
110503
111182
  const gracePeriod = result.staleAt + cacheControlDirectives["max-stale"] * 1e3;
110504
111183
  return now2 > gracePeriod;
110505
111184
  }
@@ -110512,10 +111191,10 @@ function requireCache$1() {
110512
111191
  }
110513
111192
  return false;
110514
111193
  }
110515
- function withinStaleWhileRevalidateWindow(result) {
111194
+ function withinStaleWhileRevalidateWindow(result, cacheType) {
110516
111195
  var _a3;
110517
111196
  const staleWhileRevalidate = (_a3 = result.cacheControlDirectives) == null ? void 0 : _a3["stale-while-revalidate"];
110518
- if (!staleWhileRevalidate) {
111197
+ if (!staleWhileRevalidate || staleResponseRequiresRevalidation(result, cacheType)) {
110519
111198
  return false;
110520
111199
  }
110521
111200
  const now2 = Date.now();
@@ -110613,37 +111292,29 @@ function requireCache$1() {
110613
111292
  if (!result) {
110614
111293
  return handleUncachedResponse(dispatch2, globalOpts, cacheKey, handler, opts, reqCacheControl);
110615
111294
  }
111295
+ if (globalOpts.type === "shared" && Object.hasOwn(result.headers, "set-cookie")) {
111296
+ if (util2.isStream(result.body)) {
111297
+ result.body.on("error", nop).destroy();
111298
+ }
111299
+ deleteCachedValue(globalOpts.store, cacheKey);
111300
+ return handleUncachedResponse(dispatch2, globalOpts, cacheKey, handler, opts, reqCacheControl);
111301
+ }
110616
111302
  const now2 = Date.now();
110617
111303
  if (now2 > result.deleteAt) {
110618
111304
  return dispatch2(opts, new CacheHandler(globalOpts, cacheKey, handler));
110619
111305
  }
110620
111306
  const age = Math.round((now2 - result.cachedAt) / 1e3);
110621
- if ((reqCacheControl == null ? void 0 : reqCacheControl["max-age"]) && age >= reqCacheControl["max-age"]) {
110622
- return dispatch2(opts, handler);
110623
- }
110624
- const stale = isStale(result, reqCacheControl);
110625
- const revalidate = needsRevalidation(result, reqCacheControl, opts);
111307
+ const requestMaxAgeExpired = (reqCacheControl == null ? void 0 : reqCacheControl["max-age"]) !== void 0 && age >= reqCacheControl["max-age"];
111308
+ const stale = requestMaxAgeExpired || isStale(result, reqCacheControl, globalOpts.type);
111309
+ const revalidate = requestMaxAgeExpired || needsRevalidation(result, reqCacheControl, opts);
110626
111310
  if (stale || revalidate) {
110627
111311
  if (util2.isStream(opts.body) && util2.bodyLength(opts.body) !== 0) {
110628
111312
  return dispatch2(opts, new CacheHandler(globalOpts, cacheKey, handler));
110629
111313
  }
110630
- if (!revalidate && withinStaleWhileRevalidateWindow(result)) {
111314
+ if (!revalidate && withinStaleWhileRevalidateWindow(result, globalOpts.type)) {
110631
111315
  sendCachedValue(handler, opts, result, age, null, true);
110632
111316
  queueMicrotask(() => {
110633
- const headers3 = {
110634
- ...opts.headers,
110635
- "if-modified-since": new Date(result.cachedAt).toUTCString()
110636
- };
110637
- if (result.etag) {
110638
- headers3["if-none-match"] = result.etag;
110639
- }
110640
- if (result.vary) {
110641
- for (const key in result.vary) {
110642
- if (result.vary[key] != null) {
110643
- headers3[key] = result.vary[key];
110644
- }
110645
- }
110646
- }
111317
+ const headers3 = makeRevalidationHeaders(opts, result);
110647
111318
  dispatch2(
110648
111319
  {
110649
111320
  ...opts,
@@ -110669,32 +111340,33 @@ function requireCache$1() {
110669
111340
  return true;
110670
111341
  }
110671
111342
  let withinStaleIfErrorThreshold = false;
110672
- const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? (reqCacheControl == null ? void 0 : reqCacheControl["stale-if-error"]);
110673
- if (staleIfErrorExpiry) {
110674
- withinStaleIfErrorThreshold = now2 < result.staleAt + staleIfErrorExpiry * 1e3;
110675
- }
110676
- const headers2 = {
110677
- ...opts.headers,
110678
- "if-modified-since": new Date(result.cachedAt).toUTCString()
110679
- };
110680
- if (result.etag) {
110681
- headers2["if-none-match"] = result.etag;
110682
- }
110683
- if (result.vary) {
110684
- for (const key in result.vary) {
110685
- if (result.vary[key] != null) {
110686
- headers2[key] = result.vary[key];
110687
- }
111343
+ if (!staleResponseRequiresRevalidation(result, globalOpts.type)) {
111344
+ const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? (reqCacheControl == null ? void 0 : reqCacheControl["stale-if-error"]);
111345
+ if (staleIfErrorExpiry) {
111346
+ withinStaleIfErrorThreshold = now2 < result.staleAt + staleIfErrorExpiry * 1e3;
110688
111347
  }
110689
111348
  }
111349
+ const headers2 = makeRevalidationHeaders(opts, result);
110690
111350
  return dispatch2(
110691
111351
  {
110692
111352
  ...opts,
110693
111353
  headers: headers2
110694
111354
  },
110695
111355
  new CacheRevalidationHandler(
110696
- (success2, context) => {
111356
+ (success2, context, statusCode, headers3) => {
110697
111357
  if (success2) {
111358
+ if (statusCode === 304) {
111359
+ if (revalidationResponseDisallowsCachedReuse(globalOpts.type, headers3)) {
111360
+ if (util2.isStream(result.body)) {
111361
+ result.body.on("error", nop).destroy();
111362
+ }
111363
+ deleteCachedValue(globalOpts.store, cacheKey);
111364
+ return dispatch2(opts, new CacheHandler(globalOpts, cacheKey, handler));
111365
+ }
111366
+ if (revalidationResponseUpdatesCacheControl(headers3)) {
111367
+ deleteCachedValue(globalOpts.store, cacheKey);
111368
+ }
111369
+ }
110698
111370
  sendCachedValue(handler, opts, result, age, context, stale);
110699
111371
  } else if (util2.isStream(result.body)) {
110700
111372
  result.body.on("error", nop).destroy();
@@ -110736,11 +111408,17 @@ function requireCache$1() {
110736
111408
  cacheByDefault,
110737
111409
  type
110738
111410
  };
110739
- const safeMethodsToNotCache = util2.safeHTTPMethods.filter((method) => methods.includes(method) === false);
111411
+ const safeMethodsToNotCache = [];
111412
+ for (let i = 0; i < util2.safeHTTPMethods.length; i++) {
111413
+ const method = util2.safeHTTPMethods[i];
111414
+ if (!arrayIncludes(methods, method)) {
111415
+ safeMethodsToNotCache.push(method);
111416
+ }
111417
+ }
110740
111418
  return (dispatch2) => {
110741
111419
  return (opts2, handler) => {
110742
111420
  var _a3;
110743
- if (!opts2.origin || safeMethodsToNotCache.includes(opts2.method)) {
111421
+ if (!opts2.origin || arrayIncludes(safeMethodsToNotCache, opts2.method)) {
110744
111422
  return dispatch2(opts2, handler);
110745
111423
  }
110746
111424
  if (origins !== void 0) {
@@ -110766,11 +111444,14 @@ function requireCache$1() {
110766
111444
  ...opts2,
110767
111445
  headers: normalizeHeaders(opts2)
110768
111446
  };
110769
- const reqCacheControl = ((_a3 = opts2.headers) == null ? void 0 : _a3["cache-control"]) ? parseCacheControlHeader(opts2.headers["cache-control"]) : void 0;
111447
+ const reqCacheControl = ((_a3 = opts2.headers) == null ? void 0 : _a3["cache-control"]) ? parseCacheControlHeader(opts2.headers["cache-control"]) : hasPragmaNoCache(opts2.headers) ? { "no-cache": true } : void 0;
110770
111448
  if (reqCacheControl == null ? void 0 : reqCacheControl["no-store"]) {
110771
111449
  return dispatch2(opts2, handler);
110772
111450
  }
110773
111451
  const cacheKey = makeCacheKey(opts2);
111452
+ if (!arrayIncludes(util2.safeHTTPMethods, opts2.method)) {
111453
+ return dispatch2(opts2, new CacheHandler(globalOpts, cacheKey, handler));
111454
+ }
110774
111455
  const result = store.get(cacheKey);
110775
111456
  if (result && typeof result.then === "function") {
110776
111457
  return result.then((result2) => handleResult(
@@ -110801,13 +111482,78 @@ function requireCache$1() {
110801
111482
  var decompress;
110802
111483
  var hasRequiredDecompress;
110803
111484
  function requireDecompress() {
110804
- var _decompressors, _skipStatusCodes, _skipErrorResponses, _DecompressHandler_instances, shouldSkipDecompression_fn, createDecompressionChain_fn, setupDecompressorEvents_fn, setupSingleDecompressor_fn, setupMultipleDecompressors_fn, cleanupDecompressors_fn;
111485
+ var _onPause, _onResume, _onAbort, _paused, _decompressors, _trailers, _skipStatusCodes, _skipErrorResponses, _maxSize2, _decompressedSize, _terminated, _inputEnded, _inputBackpressured, _upstreamPaused, _draining, _drainRequested, _completionPending, _finalDecompressor, _controller, _DecompressHandler_instances, onDownstreamPause_fn, onDownstreamResume_fn, pauseUpstream_fn, resumeUpstreamIfNeeded_fn, drainOutput_fn, finishIfReady_fn, onDecompressionEnd_fn, shouldSkipDecompression_fn, createDecompressionChain_fn, fail_fn, setupDecompressorEvents_fn, setupSingleDecompressor_fn, setupMultipleDecompressors_fn, setupInputBackpressure_fn, cleanupDecompressors_fn;
110805
111486
  if (hasRequiredDecompress) return decompress;
110806
111487
  hasRequiredDecompress = 1;
110807
111488
  const { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = zlib;
110808
- const { pipeline } = require$$0$5;
111489
+ const { pipeline, Transform: TransformStream2 } = require$$0$5;
111490
+ const { InvalidArgumentError, ResponseExceededMaxSizeError } = requireErrors();
110809
111491
  const DecoratorHandler = requireDecoratorHandler();
110810
111492
  const { runtimeFeatures: runtimeFeatures2 } = requireRuntimeFeatures();
111493
+ class DecompressController {
111494
+ constructor(onPause, onResume, onAbort) {
111495
+ __privateAdd(this, _onPause);
111496
+ __privateAdd(this, _onResume);
111497
+ __privateAdd(this, _onAbort);
111498
+ __privateAdd(this, _paused, false);
111499
+ __privateSet(this, _onPause, onPause);
111500
+ __privateSet(this, _onResume, onResume);
111501
+ __privateSet(this, _onAbort, onAbort);
111502
+ this.target = null;
111503
+ }
111504
+ pause() {
111505
+ if (__privateGet(this, _paused)) {
111506
+ return;
111507
+ }
111508
+ __privateSet(this, _paused, true);
111509
+ __privateGet(this, _onPause).call(this);
111510
+ }
111511
+ resume() {
111512
+ if (!__privateGet(this, _paused)) {
111513
+ return;
111514
+ }
111515
+ __privateSet(this, _paused, false);
111516
+ __privateGet(this, _onResume).call(this);
111517
+ }
111518
+ abort(reason) {
111519
+ var _a3;
111520
+ (_a3 = this.target) == null ? void 0 : _a3.abort(reason);
111521
+ __privateGet(this, _onAbort).call(this, reason);
111522
+ }
111523
+ get paused() {
111524
+ return __privateGet(this, _paused);
111525
+ }
111526
+ get aborted() {
111527
+ var _a3;
111528
+ return ((_a3 = this.target) == null ? void 0 : _a3.aborted) ?? false;
111529
+ }
111530
+ get reason() {
111531
+ var _a3;
111532
+ return ((_a3 = this.target) == null ? void 0 : _a3.reason) ?? null;
111533
+ }
111534
+ get rawHeaders() {
111535
+ var _a3;
111536
+ return ((_a3 = this.target) == null ? void 0 : _a3.rawHeaders) ?? null;
111537
+ }
111538
+ set rawHeaders(value) {
111539
+ if (this.target) {
111540
+ this.target.rawHeaders = value;
111541
+ }
111542
+ }
111543
+ get rawTrailers() {
111544
+ var _a3;
111545
+ return ((_a3 = this.target) == null ? void 0 : _a3.rawTrailers) ?? null;
111546
+ }
111547
+ set rawTrailers(value) {
111548
+ if (this.target) {
111549
+ this.target.rawTrailers = value;
111550
+ }
111551
+ }
111552
+ }
111553
+ _onPause = new WeakMap();
111554
+ _onResume = new WeakMap();
111555
+ _onAbort = new WeakMap();
111556
+ _paused = new WeakMap();
110811
111557
  const supportedEncodings = {
110812
111558
  gzip: createGunzip,
110813
111559
  "x-gzip": createGunzip,
@@ -110821,22 +111567,83 @@ function requireDecompress() {
110821
111567
  /** @type {const} */
110822
111568
  [204, 304]
110823
111569
  );
111570
+ const defaultMaxSize = 0;
111571
+ function createMaxSizeLimiter(maxSize) {
111572
+ let size2 = 0;
111573
+ return new TransformStream2({
111574
+ transform(chunk, _encoding, callback) {
111575
+ const decompressedSize = size2 + chunk.length;
111576
+ if (decompressedSize > maxSize) {
111577
+ callback(new ResponseExceededMaxSizeError(
111578
+ `Decompressed response size (${decompressedSize}) exceeded maxSize (${maxSize})`
111579
+ ));
111580
+ return;
111581
+ }
111582
+ size2 = decompressedSize;
111583
+ callback(null, chunk);
111584
+ }
111585
+ });
111586
+ }
110824
111587
  let warningEmitted = (
110825
111588
  /** @type {boolean} */
110826
111589
  false
110827
111590
  );
110828
111591
  const _DecompressHandler = class _DecompressHandler extends DecoratorHandler {
110829
- constructor(handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true } = {}) {
111592
+ constructor(handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true, maxSize = defaultMaxSize } = {}) {
111593
+ if (!Number.isSafeInteger(maxSize) || maxSize < 0) {
111594
+ throw new InvalidArgumentError("maxSize must be a non-negative integer");
111595
+ }
110830
111596
  super(handler);
110831
111597
  __privateAdd(this, _DecompressHandler_instances);
110832
111598
  /** @type {Transform[]} */
110833
111599
  __privateAdd(this, _decompressors, []);
111600
+ /** @type {Record<string, string | string[]> | undefined} */
111601
+ __privateAdd(this, _trailers);
110834
111602
  /** @type {Readonly<number[]>} */
110835
111603
  __privateAdd(this, _skipStatusCodes);
110836
111604
  /** @type {boolean} */
110837
111605
  __privateAdd(this, _skipErrorResponses);
111606
+ /** @type {number} */
111607
+ __privateAdd(this, _maxSize2);
111608
+ /** @type {number} */
111609
+ __privateAdd(this, _decompressedSize, 0);
111610
+ /** @type {boolean} */
111611
+ __privateAdd(this, _terminated, false);
111612
+ /** @type {boolean} */
111613
+ __privateAdd(this, _inputEnded, false);
111614
+ /** @type {boolean} */
111615
+ __privateAdd(this, _inputBackpressured, false);
111616
+ /** @type {boolean} */
111617
+ __privateAdd(this, _upstreamPaused, false);
111618
+ /** @type {boolean} */
111619
+ __privateAdd(this, _draining, false);
111620
+ /** @type {boolean} */
111621
+ __privateAdd(this, _drainRequested, false);
111622
+ /** @type {boolean} */
111623
+ __privateAdd(this, _completionPending, false);
111624
+ /** @type {DecompressorStream | undefined} */
111625
+ __privateAdd(this, _finalDecompressor);
111626
+ /** @type {DecompressController} */
111627
+ __privateAdd(this, _controller);
110838
111628
  __privateSet(this, _skipStatusCodes, skipStatusCodes);
110839
111629
  __privateSet(this, _skipErrorResponses, skipErrorResponses);
111630
+ __privateSet(this, _maxSize2, maxSize);
111631
+ __privateSet(this, _controller, new DecompressController(
111632
+ () => __privateMethod(this, _DecompressHandler_instances, onDownstreamPause_fn).call(this),
111633
+ () => __privateMethod(this, _DecompressHandler_instances, onDownstreamResume_fn).call(this),
111634
+ (reason) => {
111635
+ if (__privateGet(this, _inputEnded) && !__privateGet(this, _terminated)) {
111636
+ this.onResponseError(__privateGet(this, _controller), reason);
111637
+ }
111638
+ }
111639
+ ));
111640
+ }
111641
+ onRequestStart(controller, context) {
111642
+ __privateGet(this, _controller).target = controller;
111643
+ return super.onRequestStart(__privateGet(this, _controller), context);
111644
+ }
111645
+ onRequestUpgrade(controller, statusCode, headers2, socket) {
111646
+ return super.onRequestUpgrade(__privateGet(this, _controller), statusCode, headers2, socket);
110840
111647
  }
110841
111648
  /**
110842
111649
  * @param {Controller} controller
@@ -110848,21 +111655,45 @@ function requireDecompress() {
110848
111655
  onResponseStart(controller, statusCode, headers2, statusMessage) {
110849
111656
  const contentEncoding = headers2["content-encoding"];
110850
111657
  if (__privateMethod(this, _DecompressHandler_instances, shouldSkipDecompression_fn).call(this, contentEncoding, statusCode)) {
110851
- return super.onResponseStart(controller, statusCode, headers2, statusMessage);
111658
+ return super.onResponseStart(__privateGet(this, _controller), statusCode, headers2, statusMessage);
110852
111659
  }
110853
111660
  const decompressors = __privateMethod(this, _DecompressHandler_instances, createDecompressionChain_fn).call(this, contentEncoding.toLowerCase());
110854
111661
  if (decompressors.length === 0) {
110855
111662
  __privateMethod(this, _DecompressHandler_instances, cleanupDecompressors_fn).call(this);
110856
- return super.onResponseStart(controller, statusCode, headers2, statusMessage);
111663
+ return super.onResponseStart(__privateGet(this, _controller), statusCode, headers2, statusMessage);
110857
111664
  }
110858
111665
  __privateSet(this, _decompressors, decompressors);
110859
111666
  const { "content-encoding": _2, "content-length": __, ...newHeaders } = headers2;
111667
+ if (__privateGet(this, _controller).rawHeaders) {
111668
+ const rawHeaders = __privateGet(this, _controller).rawHeaders;
111669
+ if (Array.isArray(rawHeaders)) {
111670
+ const filteredHeaders = [];
111671
+ for (let i = 0; i < rawHeaders.length; i += 2) {
111672
+ const headerName = rawHeaders[i];
111673
+ const name2 = Buffer.isBuffer(headerName) ? headerName.toString("latin1") : `${headerName}`;
111674
+ const lowerName = name2.toLowerCase();
111675
+ if (lowerName === "content-encoding" || lowerName === "content-length") {
111676
+ continue;
111677
+ }
111678
+ filteredHeaders.push(rawHeaders[i], rawHeaders[i + 1]);
111679
+ }
111680
+ rawHeaders.splice(0, rawHeaders.length, ...filteredHeaders);
111681
+ } else if (typeof rawHeaders === "object") {
111682
+ for (const name2 of Object.keys(rawHeaders)) {
111683
+ const lowerName = name2.toLowerCase();
111684
+ if (lowerName === "content-encoding" || lowerName === "content-length") {
111685
+ delete rawHeaders[name2];
111686
+ }
111687
+ }
111688
+ }
111689
+ }
111690
+ __privateMethod(this, _DecompressHandler_instances, setupInputBackpressure_fn).call(this);
110860
111691
  if (__privateGet(this, _decompressors).length === 1) {
110861
- __privateMethod(this, _DecompressHandler_instances, setupSingleDecompressor_fn).call(this, controller);
111692
+ __privateMethod(this, _DecompressHandler_instances, setupSingleDecompressor_fn).call(this);
110862
111693
  } else {
110863
- __privateMethod(this, _DecompressHandler_instances, setupMultipleDecompressors_fn).call(this, controller);
111694
+ __privateMethod(this, _DecompressHandler_instances, setupMultipleDecompressors_fn).call(this);
110864
111695
  }
110865
- return super.onResponseStart(controller, statusCode, newHeaders, statusMessage);
111696
+ return super.onResponseStart(__privateGet(this, _controller), statusCode, newHeaders, statusMessage);
110866
111697
  }
110867
111698
  /**
110868
111699
  * @param {Controller} controller
@@ -110871,10 +111702,13 @@ function requireDecompress() {
110871
111702
  */
110872
111703
  onResponseData(controller, chunk) {
110873
111704
  if (__privateGet(this, _decompressors).length > 0) {
110874
- __privateGet(this, _decompressors)[0].write(chunk);
111705
+ if (!__privateGet(this, _decompressors)[0].write(chunk)) {
111706
+ __privateSet(this, _inputBackpressured, true);
111707
+ __privateMethod(this, _DecompressHandler_instances, pauseUpstream_fn).call(this);
111708
+ }
110875
111709
  return;
110876
111710
  }
110877
- super.onResponseData(controller, chunk);
111711
+ return super.onResponseData(__privateGet(this, _controller), chunk);
110878
111712
  }
110879
111713
  /**
110880
111714
  * @param {Controller} controller
@@ -110883,11 +111717,12 @@ function requireDecompress() {
110883
111717
  */
110884
111718
  onResponseEnd(controller, trailers) {
110885
111719
  if (__privateGet(this, _decompressors).length > 0) {
111720
+ __privateSet(this, _inputEnded, true);
111721
+ __privateSet(this, _trailers, trailers);
110886
111722
  __privateGet(this, _decompressors)[0].end();
110887
- __privateMethod(this, _DecompressHandler_instances, cleanupDecompressors_fn).call(this);
110888
111723
  return;
110889
111724
  }
110890
- super.onResponseEnd(controller, trailers);
111725
+ return super.onResponseEnd(__privateGet(this, _controller), trailers);
110891
111726
  }
110892
111727
  /**
110893
111728
  * @param {Controller} controller
@@ -110895,19 +111730,112 @@ function requireDecompress() {
110895
111730
  * @returns {void}
110896
111731
  */
110897
111732
  onResponseError(controller, err) {
110898
- if (__privateGet(this, _decompressors).length > 0) {
110899
- for (const decompressor of __privateGet(this, _decompressors)) {
110900
- decompressor.destroy(err);
110901
- }
110902
- __privateMethod(this, _DecompressHandler_instances, cleanupDecompressors_fn).call(this);
111733
+ if (__privateGet(this, _terminated)) {
111734
+ return;
110903
111735
  }
110904
- super.onResponseError(controller, err);
111736
+ __privateSet(this, _terminated, true);
111737
+ for (const decompressor of __privateGet(this, _decompressors)) {
111738
+ decompressor.destroy();
111739
+ }
111740
+ __privateMethod(this, _DecompressHandler_instances, cleanupDecompressors_fn).call(this);
111741
+ super.onResponseError(__privateGet(this, _controller), err);
110905
111742
  }
110906
111743
  };
110907
111744
  _decompressors = new WeakMap();
111745
+ _trailers = new WeakMap();
110908
111746
  _skipStatusCodes = new WeakMap();
110909
111747
  _skipErrorResponses = new WeakMap();
111748
+ _maxSize2 = new WeakMap();
111749
+ _decompressedSize = new WeakMap();
111750
+ _terminated = new WeakMap();
111751
+ _inputEnded = new WeakMap();
111752
+ _inputBackpressured = new WeakMap();
111753
+ _upstreamPaused = new WeakMap();
111754
+ _draining = new WeakMap();
111755
+ _drainRequested = new WeakMap();
111756
+ _completionPending = new WeakMap();
111757
+ _finalDecompressor = new WeakMap();
111758
+ _controller = new WeakMap();
110910
111759
  _DecompressHandler_instances = new WeakSet();
111760
+ onDownstreamPause_fn = function() {
111761
+ __privateMethod(this, _DecompressHandler_instances, pauseUpstream_fn).call(this);
111762
+ };
111763
+ onDownstreamResume_fn = function() {
111764
+ const drainWasDeferred = __privateGet(this, _draining);
111765
+ __privateMethod(this, _DecompressHandler_instances, drainOutput_fn).call(this);
111766
+ if (!drainWasDeferred) {
111767
+ __privateMethod(this, _DecompressHandler_instances, resumeUpstreamIfNeeded_fn).call(this);
111768
+ __privateMethod(this, _DecompressHandler_instances, finishIfReady_fn).call(this);
111769
+ }
111770
+ };
111771
+ pauseUpstream_fn = function() {
111772
+ var _a3;
111773
+ if (!__privateGet(this, _upstreamPaused) && !__privateGet(this, _terminated)) {
111774
+ __privateSet(this, _upstreamPaused, true);
111775
+ (_a3 = __privateGet(this, _controller).target) == null ? void 0 : _a3.pause();
111776
+ }
111777
+ };
111778
+ resumeUpstreamIfNeeded_fn = function() {
111779
+ var _a3;
111780
+ if (__privateGet(this, _upstreamPaused) && !__privateGet(this, _controller).paused && !__privateGet(this, _inputBackpressured)) {
111781
+ __privateSet(this, _upstreamPaused, false);
111782
+ if (!__privateGet(this, _inputEnded)) {
111783
+ (_a3 = __privateGet(this, _controller).target) == null ? void 0 : _a3.resume();
111784
+ }
111785
+ }
111786
+ };
111787
+ drainOutput_fn = function() {
111788
+ if (__privateGet(this, _terminated) || __privateGet(this, _controller).paused || !__privateGet(this, _finalDecompressor)) {
111789
+ return;
111790
+ }
111791
+ if (__privateGet(this, _draining)) {
111792
+ __privateSet(this, _drainRequested, true);
111793
+ return;
111794
+ }
111795
+ __privateSet(this, _draining, true);
111796
+ try {
111797
+ do {
111798
+ __privateSet(this, _drainRequested, false);
111799
+ let chunk;
111800
+ while (!__privateGet(this, _terminated) && !__privateGet(this, _controller).paused && (chunk = __privateGet(this, _finalDecompressor).read()) !== null) {
111801
+ if (__privateGet(this, _maxSize2) > 0) {
111802
+ const decompressedSize = __privateGet(this, _decompressedSize) + chunk.length;
111803
+ if (decompressedSize > __privateGet(this, _maxSize2)) {
111804
+ __privateMethod(this, _DecompressHandler_instances, fail_fn).call(this, new ResponseExceededMaxSizeError(
111805
+ `Decompressed response size (${decompressedSize}) exceeded maxSize (${__privateGet(this, _maxSize2)})`
111806
+ ));
111807
+ return;
111808
+ }
111809
+ __privateSet(this, _decompressedSize, decompressedSize);
111810
+ }
111811
+ const result = __superGet(_DecompressHandler.prototype, this, "onResponseData").call(this, __privateGet(this, _controller), chunk);
111812
+ if (result === false && !__privateGet(this, _controller).paused) {
111813
+ __privateGet(this, _controller).pause();
111814
+ }
111815
+ }
111816
+ } while (__privateGet(this, _drainRequested) && !__privateGet(this, _terminated) && !__privateGet(this, _controller).paused);
111817
+ } finally {
111818
+ __privateSet(this, _draining, false);
111819
+ }
111820
+ __privateMethod(this, _DecompressHandler_instances, resumeUpstreamIfNeeded_fn).call(this);
111821
+ __privateMethod(this, _DecompressHandler_instances, finishIfReady_fn).call(this);
111822
+ };
111823
+ finishIfReady_fn = function() {
111824
+ if (__privateGet(this, _terminated) || !__privateGet(this, _completionPending) || __privateGet(this, _controller).paused || __privateGet(this, _draining)) {
111825
+ return;
111826
+ }
111827
+ __privateSet(this, _terminated, true);
111828
+ __privateMethod(this, _DecompressHandler_instances, cleanupDecompressors_fn).call(this);
111829
+ __superGet(_DecompressHandler.prototype, this, "onResponseEnd").call(this, __privateGet(this, _controller), __privateGet(this, _trailers));
111830
+ };
111831
+ onDecompressionEnd_fn = function() {
111832
+ if (__privateGet(this, _terminated)) {
111833
+ return;
111834
+ }
111835
+ __privateSet(this, _completionPending, true);
111836
+ __privateMethod(this, _DecompressHandler_instances, drainOutput_fn).call(this);
111837
+ __privateMethod(this, _DecompressHandler_instances, finishIfReady_fn).call(this);
111838
+ };
110911
111839
  /**
110912
111840
  * Determines if decompression should be skipped based on encoding and status code
110913
111841
  * @param {string} contentEncoding - Content-Encoding header value
@@ -110924,7 +111852,7 @@ function requireDecompress() {
110924
111852
  * Creates a chain of decompressors for multiple content encodings
110925
111853
  *
110926
111854
  * @param {string} encodings - Comma-separated list of content encodings
110927
- * @returns {Array<DecompressorStream>} - Array of decompressor streams
111855
+ * @returns {Array<Transform>} - Array of decompressor and limiting streams
110928
111856
  * @throws {Error} - If the number of content-encodings exceeds the maximum allowed
110929
111857
  */
110930
111858
  createDecompressionChain_fn = function(encodings) {
@@ -110943,54 +111871,81 @@ function requireDecompress() {
110943
111871
  }
110944
111872
  decompressors.push(supportedEncodings[encoding2]());
110945
111873
  }
110946
- return decompressors;
111874
+ if (decompressors.length < 2) {
111875
+ return decompressors;
111876
+ }
111877
+ const streams = [];
111878
+ for (let i = 0; i < decompressors.length; i++) {
111879
+ streams.push(decompressors[i]);
111880
+ if (i < decompressors.length - 1 && __privateGet(this, _maxSize2) > 0) {
111881
+ streams.push(createMaxSizeLimiter(__privateGet(this, _maxSize2)));
111882
+ }
111883
+ }
111884
+ return streams;
111885
+ };
111886
+ /**
111887
+ * Stops decompression and reports an error.
111888
+ * @param {Error} error - The decompression error
111889
+ * @returns {void}
111890
+ */
111891
+ fail_fn = function(error2) {
111892
+ if (__privateGet(this, _terminated)) {
111893
+ return;
111894
+ }
111895
+ if (__privateGet(this, _inputEnded)) {
111896
+ this.onResponseError(__privateGet(this, _controller), error2);
111897
+ } else {
111898
+ __privateGet(this, _controller).abort(error2);
111899
+ }
110947
111900
  };
110948
111901
  /**
110949
- * Sets up event handlers for a decompressor stream using readable events
111902
+ * Sets up event handlers for the final decompressor stream.
110950
111903
  * @param {DecompressorStream} decompressor - The decompressor stream
110951
- * @param {Controller} controller - The controller to coordinate with
110952
111904
  * @returns {void}
110953
111905
  */
110954
- setupDecompressorEvents_fn = function(decompressor, controller) {
110955
- decompressor.on("readable", () => {
110956
- let chunk;
110957
- while ((chunk = decompressor.read()) !== null) {
110958
- const result = __superGet(_DecompressHandler.prototype, this, "onResponseData").call(this, controller, chunk);
110959
- if (result === false) {
110960
- break;
110961
- }
110962
- }
110963
- });
110964
- decompressor.on("error", (error2) => {
110965
- __superGet(_DecompressHandler.prototype, this, "onResponseError").call(this, controller, error2);
110966
- });
111906
+ setupDecompressorEvents_fn = function(decompressor) {
111907
+ __privateSet(this, _finalDecompressor, decompressor);
111908
+ decompressor.on("readable", () => __privateMethod(this, _DecompressHandler_instances, drainOutput_fn).call(this));
111909
+ decompressor.on("error", (error2) => __privateMethod(this, _DecompressHandler_instances, fail_fn).call(this, error2));
110967
111910
  };
110968
111911
  /**
110969
111912
  * Sets up event handling for a single decompressor
110970
- * @param {Controller} controller - The controller to handle events
110971
111913
  * @returns {void}
110972
111914
  */
110973
- setupSingleDecompressor_fn = function(controller) {
111915
+ setupSingleDecompressor_fn = function() {
110974
111916
  const decompressor = __privateGet(this, _decompressors)[0];
110975
- __privateMethod(this, _DecompressHandler_instances, setupDecompressorEvents_fn).call(this, decompressor, controller);
110976
- decompressor.on("end", () => {
110977
- __superGet(_DecompressHandler.prototype, this, "onResponseEnd").call(this, controller, {});
110978
- });
111917
+ __privateMethod(this, _DecompressHandler_instances, setupDecompressorEvents_fn).call(this, decompressor);
111918
+ decompressor.on("end", () => __privateMethod(this, _DecompressHandler_instances, onDecompressionEnd_fn).call(this));
110979
111919
  };
110980
111920
  /**
110981
111921
  * Sets up event handling for multiple chained decompressors using pipeline
110982
- * @param {Controller} controller - The controller to handle events
110983
111922
  * @returns {void}
110984
111923
  */
110985
- setupMultipleDecompressors_fn = function(controller) {
111924
+ setupMultipleDecompressors_fn = function() {
110986
111925
  const lastDecompressor = __privateGet(this, _decompressors)[__privateGet(this, _decompressors).length - 1];
110987
- __privateMethod(this, _DecompressHandler_instances, setupDecompressorEvents_fn).call(this, lastDecompressor, controller);
111926
+ __privateMethod(this, _DecompressHandler_instances, setupDecompressorEvents_fn).call(this, lastDecompressor);
110988
111927
  pipeline(__privateGet(this, _decompressors), (err) => {
111928
+ if (__privateGet(this, _terminated)) {
111929
+ return;
111930
+ }
110989
111931
  if (err) {
110990
- __superGet(_DecompressHandler.prototype, this, "onResponseError").call(this, controller, err);
111932
+ __privateMethod(this, _DecompressHandler_instances, fail_fn).call(this, err);
110991
111933
  return;
110992
111934
  }
110993
- __superGet(_DecompressHandler.prototype, this, "onResponseEnd").call(this, controller, {});
111935
+ __privateMethod(this, _DecompressHandler_instances, onDecompressionEnd_fn).call(this);
111936
+ });
111937
+ };
111938
+ setupInputBackpressure_fn = function() {
111939
+ const decompressor = __privateGet(this, _decompressors)[0];
111940
+ decompressor.on("drain", () => {
111941
+ if (__privateGet(this, _terminated)) {
111942
+ return;
111943
+ }
111944
+ __privateSet(this, _inputBackpressured, false);
111945
+ if (!__privateGet(this, _controller).paused) {
111946
+ __privateMethod(this, _DecompressHandler_instances, drainOutput_fn).call(this);
111947
+ __privateMethod(this, _DecompressHandler_instances, resumeUpstreamIfNeeded_fn).call(this);
111948
+ }
110994
111949
  });
110995
111950
  };
110996
111951
  /**
@@ -110999,6 +111954,7 @@ function requireDecompress() {
110999
111954
  */
111000
111955
  cleanupDecompressors_fn = function() {
111001
111956
  __privateGet(this, _decompressors).length = 0;
111957
+ __privateSet(this, _finalDecompressor, void 0);
111002
111958
  };
111003
111959
  let DecompressHandler = _DecompressHandler;
111004
111960
  function createDecompressInterceptor(options = {}) {
@@ -111843,7 +112799,12 @@ function requireSqliteCacheStore() {
111843
112799
  if (lhs.length !== rhs.length) {
111844
112800
  return false;
111845
112801
  }
111846
- return lhs.every((x2, i) => x2 === rhs[i]);
112802
+ for (let i = 0; i < lhs.length; i++) {
112803
+ if (lhs[i] !== rhs[i]) {
112804
+ return false;
112805
+ }
112806
+ }
112807
+ return true;
111847
112808
  }
111848
112809
  return lhs === rhs;
111849
112810
  }
@@ -115558,14 +116519,48 @@ function requireUtil$2() {
115558
116519
  for (let i = 0; i < path2.length; ++i) {
115559
116520
  const code2 = path2.charCodeAt(i);
115560
116521
  if (code2 < 32 || // exclude CTLs (0-31)
115561
- code2 === 127 || // DEL
116522
+ code2 > 126 || // exclude DEL and non-ascii
115562
116523
  code2 === 59) {
115563
116524
  throw new Error("Invalid cookie path");
115564
116525
  }
115565
116526
  }
115566
116527
  }
116528
+ function isLetterOrDigit(code2) {
116529
+ return code2 >= 48 && code2 <= 57 || // 0-9
116530
+ code2 >= 65 && code2 <= 90 || // A-Z
116531
+ code2 >= 97 && code2 <= 122;
116532
+ }
115567
116533
  function validateCookieDomain(domain2) {
115568
- if (domain2.startsWith("-") || domain2.endsWith(".") || domain2.endsWith("-")) {
116534
+ if (domain2 === " ") {
116535
+ return;
116536
+ }
116537
+ if (domain2.length > 255) {
116538
+ throw new Error("Invalid cookie domain");
116539
+ }
116540
+ let labelLength = 0;
116541
+ for (let i = 0; i < domain2.length; ++i) {
116542
+ const code2 = domain2.charCodeAt(i);
116543
+ if (code2 === 46) {
116544
+ if (labelLength === 0) {
116545
+ throw new Error("Invalid cookie domain");
116546
+ }
116547
+ if (domain2.charCodeAt(i - 1) === 45) {
116548
+ throw new Error("Invalid cookie domain");
116549
+ }
116550
+ labelLength = 0;
116551
+ continue;
116552
+ }
116553
+ if (labelLength === 0 && !isLetterOrDigit(code2)) {
116554
+ throw new Error("Invalid cookie domain");
116555
+ }
116556
+ if (!isLetterOrDigit(code2) && code2 !== 45) {
116557
+ throw new Error("Invalid cookie domain");
116558
+ }
116559
+ if (++labelLength > 63) {
116560
+ throw new Error("Invalid cookie domain");
116561
+ }
116562
+ }
116563
+ if (labelLength === 0 || domain2.charCodeAt(domain2.length - 1) === 45) {
115569
116564
  throw new Error("Invalid cookie domain");
115570
116565
  }
115571
116566
  }
@@ -115648,7 +116643,11 @@ function requireUtil$2() {
115648
116643
  throw new Error("Invalid unparsed");
115649
116644
  }
115650
116645
  const [key, ...value] = part.split("=");
115651
- out.push(`${key.trim()}=${value.join("=")}`);
116646
+ const trimmedKey = key.trim();
116647
+ const joinedValue = value.join("=");
116648
+ validateCookieName(trimmedKey);
116649
+ validateCookieValue(joinedValue);
116650
+ out.push(`${trimmedKey}=${joinedValue}`);
115652
116651
  }
115653
116652
  return out.join("; ");
115654
116653
  }
@@ -116602,11 +117601,11 @@ function requireConnection() {
116602
117601
  var _a3, _b2, _c, _d;
116603
117602
  if (response2.type === "error" || response2.status !== 101) {
116604
117603
  if (((_a3 = response2.socket) == null ? void 0 : _a3.session) == null) {
116605
- failWebsocketConnection(handler, 1002, "Received network error or non-101 status code.", response2.error);
117604
+ failHandshake(handler, response2, 1002, "Received network error or non-101 status code.", response2.error);
116606
117605
  return;
116607
117606
  }
116608
117607
  if (response2.status !== 200) {
116609
- failWebsocketConnection(handler, 1002, "Received network error or non-200 status code.", response2.error);
117608
+ failHandshake(handler, response2, 1002, "Received network error or non-200 status code.", response2.error);
116610
117609
  return;
116611
117610
  }
116612
117611
  }
@@ -116615,21 +117614,21 @@ function requireConnection() {
116615
117614
  warningEmitted = true;
116616
117615
  }
116617
117616
  if (protocols.length !== 0 && !response2.headersList.get("Sec-WebSocket-Protocol")) {
116618
- failWebsocketConnection(handler, 1002, "Server did not respond with sent protocols.");
117617
+ failHandshake(handler, response2, 1002, "Server did not respond with sent protocols.");
116619
117618
  return;
116620
117619
  }
116621
117620
  if (response2.socket.session == null && ((_c = response2.headersList.get("Upgrade")) == null ? void 0 : _c.toLowerCase()) !== "websocket") {
116622
- failWebsocketConnection(handler, 1002, 'Server did not set Upgrade header to "websocket".');
117621
+ failHandshake(handler, response2, 1002, 'Server did not set Upgrade header to "websocket".');
116623
117622
  return;
116624
117623
  }
116625
117624
  if (response2.socket.session == null && ((_d = response2.headersList.get("Connection")) == null ? void 0 : _d.toLowerCase()) !== "upgrade") {
116626
- failWebsocketConnection(handler, 1002, 'Server did not set Connection header to "upgrade".');
117625
+ failHandshake(handler, response2, 1002, 'Server did not set Connection header to "upgrade".');
116627
117626
  return;
116628
117627
  }
116629
117628
  const secWSAccept = response2.headersList.get("Sec-WebSocket-Accept");
116630
117629
  const digest = crypto$1.hash("sha1", keyValue + uid, "base64");
116631
117630
  if (secWSAccept !== digest) {
116632
- failWebsocketConnection(handler, 1002, "Incorrect hash received in Sec-WebSocket-Accept header.");
117631
+ failHandshake(handler, response2, 1002, "Incorrect hash received in Sec-WebSocket-Accept header.");
116633
117632
  return;
116634
117633
  }
116635
117634
  const secExtension = response2.headersList.get("Sec-WebSocket-Extensions");
@@ -116637,15 +117636,15 @@ function requireConnection() {
116637
117636
  if (secExtension !== null) {
116638
117637
  extensions2 = parseExtensions(secExtension);
116639
117638
  if (!extensions2.has("permessage-deflate")) {
116640
- failWebsocketConnection(handler, 1002, "Sec-WebSocket-Extensions header does not match.");
117639
+ failHandshake(handler, response2, 1002, "Sec-WebSocket-Extensions header does not match.");
116641
117640
  return;
116642
117641
  }
116643
117642
  }
116644
117643
  const secProtocol = response2.headersList.get("Sec-WebSocket-Protocol");
116645
117644
  if (secProtocol !== null) {
116646
117645
  const requestProtocols = getDecodeSplit("sec-websocket-protocol", request2.headersList);
116647
- if (!requestProtocols.includes(secProtocol)) {
116648
- failWebsocketConnection(handler, 1002, "Protocol was not set in the opening handshake.");
117646
+ if (requestProtocols === null || !requestProtocols.includes(secProtocol)) {
117647
+ failHandshake(handler, response2, 1002, "Protocol was not set in the opening handshake.");
116649
117648
  return;
116650
117649
  }
116651
117650
  }
@@ -116691,6 +117690,13 @@ function requireConnection() {
116691
117690
  object2.readyState = states.CLOSING;
116692
117691
  }
116693
117692
  }
117693
+ function failHandshake(handler, response2, code2, reason, cause) {
117694
+ var _a3;
117695
+ if (((_a3 = response2.socket) == null ? void 0 : _a3.session) != null && !response2.socket.destroyed) {
117696
+ response2.socket.destroy();
117697
+ }
117698
+ failWebsocketConnection(handler, code2, reason);
117699
+ }
116694
117700
  function failWebsocketConnection(handler, code2, reason, cause) {
116695
117701
  var _a3;
116696
117702
  if (isEstablished(handler.readyState)) {
@@ -116764,6 +117770,7 @@ function requirePermessageDeflate() {
116764
117770
  if (__privateGet(this, _maxPayloadSize) > 0 && __privateGet(this, _inflate)[kLength] > __privateGet(this, _maxPayloadSize)) {
116765
117771
  callback(new MessageSizeExceededError());
116766
117772
  __privateGet(this, _inflate).removeAllListeners();
117773
+ __privateGet(this, _inflate).destroy();
116767
117774
  __privateSet(this, _inflate, null);
116768
117775
  return;
116769
117776
  }
@@ -117854,7 +118861,7 @@ function requireWebsocketerror() {
117854
118861
  var websocketstream;
117855
118862
  var hasRequiredWebsocketstream;
117856
118863
  function requireWebsocketstream() {
117857
- var _url2, _openedPromise, _closedPromise, _readableStream, _readableStreamController, _writableStream, _handshakeAborted, _handler, _parser, _WebSocketStream_instances, write_fn, onConnectionEstablished_fn, onMessage_fn, onSocketClose_fn, closeUsingReason_fn, cancel_fn;
118864
+ var _url2, _openedPromise, _closedPromise, _readableStream, _readableStreamController, _writableStreamController, _handshakeAborted, _handler, _parser, _WebSocketStream_instances, write_fn, onConnectionEstablished_fn, onMessage_fn, onSocketClose_fn, closeUsingReason_fn, cancel_fn;
117858
118865
  if (hasRequiredWebsocketstream) return websocketstream;
117859
118866
  hasRequiredWebsocketstream = 1;
117860
118867
  const { createDeferredPromise } = requirePromise();
@@ -117887,9 +118894,9 @@ function requireWebsocketstream() {
117887
118894
  __privateAdd(this, _readableStream);
117888
118895
  /** @type {ReadableStreamDefaultController} */
117889
118896
  __privateAdd(this, _readableStreamController);
117890
- // Each WebSocketStream object has an associated writable stream , which is a WritableStream .
117891
- /** @type {WritableStream} */
117892
- __privateAdd(this, _writableStream);
118897
+ // Retain the controller so the writable stream can be errored while locked.
118898
+ /** @type {WritableStreamDefaultController} */
118899
+ __privateAdd(this, _writableStreamController);
117893
118900
  // Each WebSocketStream object has an associated boolean handshake aborted , which is initially false.
117894
118901
  __privateAdd(this, _handshakeAborted, false);
117895
118902
  /** @type {import('../websocket').Handler} */
@@ -118000,7 +119007,7 @@ function requireWebsocketstream() {
118000
119007
  _closedPromise = new WeakMap();
118001
119008
  _readableStream = new WeakMap();
118002
119009
  _readableStreamController = new WeakMap();
118003
- _writableStream = new WeakMap();
119010
+ _writableStreamController = new WeakMap();
118004
119011
  _handshakeAborted = new WeakMap();
118005
119012
  _handler = new WeakMap();
118006
119013
  _parser = new WeakMap();
@@ -118055,12 +119062,14 @@ function requireWebsocketstream() {
118055
119062
  cancel: (reason) => __privateMethod(this, _WebSocketStream_instances, cancel_fn).call(this, reason)
118056
119063
  });
118057
119064
  const writable = new WritableStream({
119065
+ start: (controller) => {
119066
+ __privateSet(this, _writableStreamController, controller);
119067
+ },
118058
119068
  write: (chunk) => __privateMethod(this, _WebSocketStream_instances, write_fn).call(this, chunk),
118059
119069
  close: () => closeWebSocketConnection(__privateGet(this, _handler), null, null),
118060
119070
  abort: (reason) => __privateMethod(this, _WebSocketStream_instances, closeUsingReason_fn).call(this, reason)
118061
119071
  });
118062
119072
  __privateSet(this, _readableStream, readable2);
118063
- __privateSet(this, _writableStream, writable);
118064
119073
  __privateGet(this, _openedPromise).resolve({
118065
119074
  extensions: extensions2,
118066
119075
  protocol,
@@ -118105,9 +119114,7 @@ function requireWebsocketstream() {
118105
119114
  const reason = (result == null ? void 0 : result.reason) == null ? "" : utf8DecodeBytes(Buffer.from(result.reason));
118106
119115
  if (wasClean) {
118107
119116
  __privateGet(this, _readableStreamController).close();
118108
- if (!__privateGet(this, _writableStream).locked) {
118109
- __privateGet(this, _writableStream).abort(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
118110
- }
119117
+ __privateGet(this, _writableStreamController).error(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
118111
119118
  __privateGet(this, _closedPromise).resolve({
118112
119119
  closeCode: code2,
118113
119120
  reason
@@ -118115,7 +119122,7 @@ function requireWebsocketstream() {
118115
119122
  } else {
118116
119123
  const error2 = createUnvalidatedWebSocketError("unclean close", code2, reason);
118117
119124
  (_b2 = __privateGet(this, _readableStreamController)) == null ? void 0 : _b2.error(error2);
118118
- (_c = __privateGet(this, _writableStream)) == null ? void 0 : _c.abort(error2);
119125
+ (_c = __privateGet(this, _writableStreamController)) == null ? void 0 : _c.error(error2);
118119
119126
  __privateGet(this, _closedPromise).reject(error2);
118120
119127
  }
118121
119128
  };
@@ -118209,6 +119216,40 @@ function requireEventsourceStream() {
118209
119216
  const CR = 13;
118210
119217
  const COLON = 58;
118211
119218
  const SPACE = 32;
119219
+ const DATA = Buffer.from("data");
119220
+ const EVENT = Buffer.from("event");
119221
+ const ID2 = Buffer.from("id");
119222
+ const RETRY2 = Buffer.from("retry");
119223
+ function isASCIINumberBytes(buffer2, start2) {
119224
+ if (start2 >= buffer2.length) {
119225
+ return false;
119226
+ }
119227
+ for (let i = start2; i < buffer2.length; i++) {
119228
+ if (buffer2[i] < 48 || buffer2[i] > 57) {
119229
+ return false;
119230
+ }
119231
+ }
119232
+ return true;
119233
+ }
119234
+ function isValidLastEventIdBytes(buffer2, start2) {
119235
+ for (let i = start2; i < buffer2.length; i++) {
119236
+ if (buffer2[i] === 0) {
119237
+ return false;
119238
+ }
119239
+ }
119240
+ return true;
119241
+ }
119242
+ function isFieldName(line, length, field) {
119243
+ if (length !== field.length) {
119244
+ return false;
119245
+ }
119246
+ for (let i = 0; i < length; i++) {
119247
+ if (line[i] !== field[i]) {
119248
+ return false;
119249
+ }
119250
+ }
119251
+ return true;
119252
+ }
118212
119253
  class EventSourceStream extends Transform2 {
118213
119254
  /**
118214
119255
  * @param {object} options
@@ -118237,10 +119278,13 @@ function requireEventsourceStream() {
118237
119278
  */
118238
119279
  __publicField(this, "eventEndCheck", false);
118239
119280
  /**
118240
- * @type {Buffer|null}
119281
+ * @type {Buffer[]}
118241
119282
  */
118242
- __publicField(this, "buffer", null);
119283
+ __publicField(this, "chunks", []);
119284
+ __publicField(this, "chunkIndex", 0);
118243
119285
  __publicField(this, "pos", 0);
119286
+ __publicField(this, "lineChunkIndex", 0);
119287
+ __publicField(this, "linePos", 0);
118244
119288
  __publicField(this, "event", {
118245
119289
  data: void 0,
118246
119290
  event: void 0,
@@ -118263,63 +119307,30 @@ function requireEventsourceStream() {
118263
119307
  callback();
118264
119308
  return;
118265
119309
  }
118266
- if (this.buffer) {
118267
- this.buffer = Buffer.concat([this.buffer, chunk]);
118268
- } else {
118269
- this.buffer = chunk;
118270
- }
119310
+ this.chunks.push(chunk);
118271
119311
  if (this.checkBOM) {
118272
- switch (this.buffer.length) {
118273
- case 1:
118274
- if (this.buffer[0] === BOM[0]) {
118275
- callback();
118276
- return;
118277
- }
118278
- this.checkBOM = false;
118279
- callback();
118280
- return;
118281
- case 2:
118282
- if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) {
118283
- callback();
118284
- return;
118285
- }
118286
- this.checkBOM = false;
118287
- break;
118288
- case 3:
118289
- if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
118290
- this.buffer = Buffer.alloc(0);
118291
- this.checkBOM = false;
118292
- callback();
118293
- return;
118294
- }
118295
- this.checkBOM = false;
118296
- break;
118297
- default:
118298
- if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
118299
- this.buffer = this.buffer.subarray(3);
118300
- }
118301
- this.checkBOM = false;
118302
- break;
119312
+ if (this.handleBOM()) {
119313
+ callback();
119314
+ return;
118303
119315
  }
118304
119316
  }
118305
- while (this.pos < this.buffer.length) {
119317
+ while (this.hasCurrentByte()) {
119318
+ const byte = this.currentByte();
118306
119319
  if (this.eventEndCheck) {
118307
119320
  if (this.crlfCheck) {
118308
- if (this.buffer[this.pos] === LF) {
118309
- this.buffer = this.buffer.subarray(this.pos + 1);
118310
- this.pos = 0;
119321
+ if (byte === LF) {
118311
119322
  this.crlfCheck = false;
119323
+ this.consumeCurrentByte();
118312
119324
  continue;
118313
119325
  }
118314
119326
  this.crlfCheck = false;
118315
119327
  }
118316
- if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
118317
- if (this.buffer[this.pos] === CR) {
119328
+ if (byte === LF || byte === CR) {
119329
+ if (byte === CR) {
118318
119330
  this.crlfCheck = true;
118319
119331
  }
118320
- this.buffer = this.buffer.subarray(this.pos + 1);
118321
- this.pos = 0;
118322
- if (this.event.data !== void 0 || this.event.event || this.event.id !== void 0 || this.event.retry) {
119332
+ this.consumeCurrentByte();
119333
+ if (this.hasPendingEvent()) {
118323
119334
  this.processEvent(this.event);
118324
119335
  }
118325
119336
  this.clearEvent();
@@ -118328,17 +119339,16 @@ function requireEventsourceStream() {
118328
119339
  this.eventEndCheck = false;
118329
119340
  continue;
118330
119341
  }
118331
- if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
118332
- if (this.buffer[this.pos] === CR) {
119342
+ if (byte === LF || byte === CR) {
119343
+ if (byte === CR) {
118333
119344
  this.crlfCheck = true;
118334
119345
  }
118335
- this.parseLine(this.buffer.subarray(0, this.pos), this.event);
118336
- this.buffer = this.buffer.subarray(this.pos + 1);
118337
- this.pos = 0;
119346
+ this.parseLine(this.readLine(), this.event);
119347
+ this.consumeCurrentByte();
118338
119348
  this.eventEndCheck = true;
118339
119349
  continue;
118340
119350
  }
118341
- this.pos++;
119351
+ this.advanceCursor();
118342
119352
  }
118343
119353
  callback();
118344
119354
  }
@@ -118354,43 +119364,42 @@ function requireEventsourceStream() {
118354
119364
  if (colonPosition === 0) {
118355
119365
  return;
118356
119366
  }
118357
- let field = "";
118358
- let value = "";
119367
+ let fieldLength = line.length;
119368
+ let valueStart = line.length;
118359
119369
  if (colonPosition !== -1) {
118360
- field = line.subarray(0, colonPosition).toString("utf8");
118361
- let valueStart = colonPosition + 1;
119370
+ fieldLength = colonPosition;
119371
+ valueStart = colonPosition + 1;
118362
119372
  if (line[valueStart] === SPACE) {
118363
119373
  ++valueStart;
118364
119374
  }
118365
- value = line.subarray(valueStart).toString("utf8");
118366
- } else {
118367
- field = line.toString("utf8");
118368
- value = "";
118369
119375
  }
118370
- switch (field) {
118371
- case "data":
118372
- if (event[field] === void 0) {
118373
- event[field] = value;
118374
- } else {
118375
- event[field] += `
119376
+ if (isFieldName(line, fieldLength, DATA)) {
119377
+ const value = line.toString("utf8", valueStart);
119378
+ if (event.data === void 0) {
119379
+ event.data = value;
119380
+ } else {
119381
+ event.data += `
118376
119382
  ${value}`;
118377
- }
118378
- break;
118379
- case "retry":
118380
- if (isASCIINumber(value)) {
118381
- event[field] = value;
118382
- }
118383
- break;
118384
- case "id":
118385
- if (isValidLastEventId(value)) {
118386
- event[field] = value;
118387
- }
118388
- break;
118389
- case "event":
118390
- if (value.length > 0) {
118391
- event[field] = value;
118392
- }
118393
- break;
119383
+ }
119384
+ return;
119385
+ }
119386
+ if (isFieldName(line, fieldLength, RETRY2)) {
119387
+ if (isASCIINumberBytes(line, valueStart)) {
119388
+ event.retry = line.toString("utf8", valueStart);
119389
+ }
119390
+ return;
119391
+ }
119392
+ if (isFieldName(line, fieldLength, ID2)) {
119393
+ if (isValidLastEventIdBytes(line, valueStart)) {
119394
+ event.id = line.toString("utf8", valueStart);
119395
+ }
119396
+ return;
119397
+ }
119398
+ if (isFieldName(line, fieldLength, EVENT)) {
119399
+ const value = line.toString("utf8", valueStart);
119400
+ if (value.length > 0) {
119401
+ event.event = value;
119402
+ }
118394
119403
  }
118395
119404
  }
118396
119405
  /**
@@ -118415,12 +119424,120 @@ ${value}`;
118415
119424
  }
118416
119425
  }
118417
119426
  clearEvent() {
118418
- this.event = {
118419
- data: void 0,
118420
- event: void 0,
118421
- id: void 0,
118422
- retry: void 0
118423
- };
119427
+ this.event.data = void 0;
119428
+ this.event.event = void 0;
119429
+ this.event.id = void 0;
119430
+ this.event.retry = void 0;
119431
+ }
119432
+ hasPendingEvent() {
119433
+ return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0;
119434
+ }
119435
+ hasCurrentByte() {
119436
+ return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length;
119437
+ }
119438
+ currentByte() {
119439
+ return this.chunks[this.chunkIndex][this.pos];
119440
+ }
119441
+ consumeCurrentByte() {
119442
+ this.advanceCursor();
119443
+ this.syncLineStartToCursor();
119444
+ }
119445
+ advanceCursor() {
119446
+ this.pos++;
119447
+ while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) {
119448
+ this.chunkIndex++;
119449
+ this.pos = 0;
119450
+ }
119451
+ }
119452
+ syncLineStartToCursor() {
119453
+ this.lineChunkIndex = this.chunkIndex;
119454
+ this.linePos = this.pos;
119455
+ this.dropConsumedChunks();
119456
+ }
119457
+ dropConsumedChunks() {
119458
+ while (this.lineChunkIndex > 0) {
119459
+ this.chunks.shift();
119460
+ this.lineChunkIndex--;
119461
+ this.chunkIndex--;
119462
+ }
119463
+ if (this.chunkIndex === this.chunks.length) {
119464
+ this.chunks.length = 0;
119465
+ this.chunkIndex = 0;
119466
+ this.pos = 0;
119467
+ this.lineChunkIndex = 0;
119468
+ this.linePos = 0;
119469
+ }
119470
+ }
119471
+ readLine() {
119472
+ if (this.lineChunkIndex === this.chunkIndex) {
119473
+ return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos);
119474
+ }
119475
+ const chunks = [];
119476
+ let length = 0;
119477
+ for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) {
119478
+ const chunk = this.chunks[i];
119479
+ const start2 = i === this.lineChunkIndex ? this.linePos : 0;
119480
+ const end = i === this.chunkIndex ? this.pos : chunk.length;
119481
+ const slice = chunk.subarray(start2, end);
119482
+ length += slice.length;
119483
+ chunks.push(slice);
119484
+ }
119485
+ return Buffer.concat(chunks, length);
119486
+ }
119487
+ peekBufferedByte(offset2) {
119488
+ let chunkIndex = this.lineChunkIndex;
119489
+ let pos = this.linePos;
119490
+ while (chunkIndex < this.chunks.length) {
119491
+ const chunk = this.chunks[chunkIndex];
119492
+ const remaining = chunk.length - pos;
119493
+ if (offset2 < remaining) {
119494
+ return chunk[pos + offset2];
119495
+ }
119496
+ offset2 -= remaining;
119497
+ chunkIndex++;
119498
+ pos = 0;
119499
+ }
119500
+ }
119501
+ discardLeadingBytes(count2) {
119502
+ while (count2 > 0 && this.lineChunkIndex < this.chunks.length) {
119503
+ const chunk = this.chunks[this.lineChunkIndex];
119504
+ const remaining = chunk.length - this.linePos;
119505
+ if (count2 < remaining) {
119506
+ this.linePos += count2;
119507
+ count2 = 0;
119508
+ } else {
119509
+ count2 -= remaining;
119510
+ this.lineChunkIndex++;
119511
+ this.linePos = 0;
119512
+ }
119513
+ }
119514
+ this.chunkIndex = this.lineChunkIndex;
119515
+ this.pos = this.linePos;
119516
+ this.dropConsumedChunks();
119517
+ }
119518
+ handleBOM() {
119519
+ const first = this.peekBufferedByte(0);
119520
+ const second = this.peekBufferedByte(1);
119521
+ const third = this.peekBufferedByte(2);
119522
+ if (second === void 0) {
119523
+ if (first === BOM[0]) {
119524
+ return true;
119525
+ }
119526
+ this.checkBOM = false;
119527
+ return true;
119528
+ }
119529
+ if (third === void 0) {
119530
+ if (first === BOM[0] && second === BOM[1]) {
119531
+ return true;
119532
+ }
119533
+ this.checkBOM = false;
119534
+ return false;
119535
+ }
119536
+ if (first === BOM[0] && second === BOM[1] && third === BOM[2]) {
119537
+ this.discardLeadingBytes(3);
119538
+ }
119539
+ this.checkBOM = false;
119540
+ return !this.hasCurrentByte();
118424
119541
  }
118425
119542
  }
118426
119543
  eventsourceStream = {
@@ -120844,7 +121961,7 @@ function createLocalWorld(args) {
120844
121961
  const basedir = mergedConfig.dataDir;
120845
121962
  const hooksDir = path$3.join(basedir, "hooks");
120846
121963
  const taggedHookFiles = await listTaggedFiles(hooksDir, tag);
120847
- const { HookSchema: HookSchema2 } = await import("./index-iPDTwQkr.js");
121964
+ const { HookSchema: HookSchema2 } = await import("./index-ClImPOu-.js");
120848
121965
  await Promise.all(taggedHookFiles.map(async (hookFile) => {
120849
121966
  const hook = await readJSON(path$3.join(hooksDir, hookFile), HookSchema2);
120850
121967
  if (hook == null ? void 0 : hook.token) {
@@ -121031,6 +122148,12 @@ function getRetryAgentOptions() {
121031
122148
  maxRetries: MAX_RETRIES
121032
122149
  };
121033
122150
  }
122151
+ function getEventsRetryAgentOptions() {
122152
+ return {
122153
+ ...getRetryAgentOptions(),
122154
+ errorCodes: [...RETRY_ERROR_CODES, "ERR_HTTP2_STREAM_ERROR"]
122155
+ };
122156
+ }
121034
122157
  const STREAM_RETRY_OPTIONS = {
121035
122158
  retryAfter: true,
121036
122159
  methods: ["PUT"],
@@ -121053,14 +122176,17 @@ function contentLength(headers2) {
121053
122176
  const raw2 = record2["content-length"] ?? record2["Content-Length"];
121054
122177
  return typeof raw2 === "string" || typeof raw2 === "number" ? Number(raw2) : Number.NaN;
121055
122178
  }
121056
- function h2MultiplexInterceptor(dispatch2) {
121057
- return (opts, handler) => {
122179
+ function createH2MultiplexInterceptor(fallback) {
122180
+ return (dispatch2) => (opts, handler) => {
121058
122181
  const body2 = opts.body;
121059
122182
  const isAsyncIterable = !!body2 && typeof body2 !== "string" && !Buffer.isBuffer(body2) && typeof body2[Symbol.asyncIterator] === "function";
121060
122183
  const length = contentLength(opts.headers);
121061
- if (!isAsyncIterable || !(length >= 0) || length > H2_REBUFFER_MAX_BYTES) {
122184
+ if (!isAsyncIterable) {
121062
122185
  return dispatch2({ ...opts, idempotent: true }, handler);
121063
122186
  }
122187
+ if (!(length >= 0) || length > H2_REBUFFER_MAX_BYTES) {
122188
+ return fallback ? fallback.dispatch(opts, handler) : dispatch2({ ...opts, idempotent: true }, handler);
122189
+ }
121064
122190
  void (async () => {
121065
122191
  var _a3;
121066
122192
  try {
@@ -121084,7 +122210,15 @@ const RECYCLABLE_ERROR_CODES = /* @__PURE__ */ new Set([
121084
122210
  // Covers H2 stream timeout, frameError and GOAWAY (undici InformationalError).
121085
122211
  "UND_ERR_INFO",
121086
122212
  "UND_ERR_HEADERS_TIMEOUT",
121087
- "UND_ERR_BODY_TIMEOUT"
122213
+ "UND_ERR_BODY_TIMEOUT",
122214
+ // Node can surface these directly instead of undici's UND_ERR_INFO. Once
122215
+ // repeated, retire the pool even when classification used its fallback.
122216
+ // Keep this scoped to session/stream failures: ERR_HTTP2_* also contains
122217
+ // request-validation and caller-cancellation errors a new pool cannot fix.
122218
+ "ERR_HTTP2_GOAWAY_SESSION",
122219
+ "ERR_HTTP2_INVALID_SESSION",
122220
+ "ERR_HTTP2_SESSION_ERROR",
122221
+ "ERR_HTTP2_STREAM_ERROR"
121088
122222
  ]);
121089
122223
  const MAX_CAUSE_DEPTH = 8;
121090
122224
  function isRecyclableTransportError(error2) {
@@ -121186,22 +122320,38 @@ function createEventsDispatcher(agentOverrides) {
121186
122320
  const agent2 = new undiciExports.RetryAgent(new undiciExports.Agent({
121187
122321
  ...h2 ? getEventsAgentOptions() : getEventsAgentOptionsNoH2(),
121188
122322
  ...agentOverrides
121189
- }), getRetryAgentOptions());
121190
- if (!h2) {
122323
+ }), getEventsRetryAgentOptions());
122324
+ if (!h2 || !supportsCompose(agent2)) {
121191
122325
  return agent2;
121192
122326
  }
121193
- return withBoundLifecycle(agent2, agent2.compose(h2MultiplexInterceptor));
122327
+ const streamedBodyAgent = new undiciExports.RetryAgent(new undiciExports.Agent({ ...getEventsAgentOptionsNoH2(), ...agentOverrides }), getEventsRetryAgentOptions());
122328
+ return withBoundLifecycle(agent2, agent2.compose(createH2MultiplexInterceptor(streamedBodyAgent)), streamedBodyAgent);
122329
+ }
122330
+ function supportsCompose(dispatcher2) {
122331
+ return typeof dispatcher2.compose === "function";
121194
122332
  }
121195
- function withBoundLifecycle(agent2, composed) {
122333
+ function withBoundLifecycle(agent2, composed, companion) {
121196
122334
  return new Proxy(composed, {
121197
- get: (target2, key) => key === "close" || key === "destroy" ? agent2[key].bind(agent2) : target2[key]
122335
+ get: (target2, key) => {
122336
+ if (key !== "close" && key !== "destroy") {
122337
+ return target2[key];
122338
+ }
122339
+ const own2 = agent2[key].bind(agent2);
122340
+ if (!companion)
122341
+ return own2;
122342
+ const other = companion[key].bind(companion);
122343
+ return async (...args) => {
122344
+ await Promise.all([own2(...args), other(...args)]);
122345
+ };
122346
+ }
121198
122347
  });
121199
122348
  }
121200
122349
  function createStreamDispatcher(retryOptions, agentOverrides) {
121201
122350
  return new undiciExports.RetryAgent(new undiciExports.Agent({ ...getStreamAgentOptions(), ...agentOverrides }), retryOptions);
121202
122351
  }
121203
122352
  function createQueueDispatcher() {
121204
- return new undiciExports.RetryAgent(new undiciExports.Agent(getQueueAgentOptions()).compose(deadlineInterceptor(getQueueRequestTimeoutMs())), getRetryAgentOptions());
122353
+ const agent2 = new undiciExports.Agent(getQueueAgentOptions());
122354
+ return new undiciExports.RetryAgent(supportsCompose(agent2) ? agent2.compose(deadlineInterceptor(getQueueRequestTimeoutMs())) : agent2, getRetryAgentOptions());
121205
122355
  }
121206
122356
  function getDefaultQueueDispatcher() {
121207
122357
  _queueDispatcher ?? (_queueDispatcher = createQueueDispatcher());
@@ -121337,8 +122487,8 @@ function requireGetVercelOidcToken() {
121337
122487
  }
121338
122488
  try {
121339
122489
  const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
121340
- await import("./token-util-BszBIaAk.js").then((n) => n.t),
121341
- await import("./token-CPIWEDbd.js").then((n) => n.t)
122490
+ await import("./token-util-CXI_HnNu.js").then((n) => n.t),
122491
+ await import("./token-NxX4H9ze.js").then((n) => n.t)
121342
122492
  ]);
121343
122493
  if (!token || isExpired(getTokenPayload(token), options == null ? void 0 : options.expirationBufferMs)) {
121344
122494
  await refreshToken(options);
@@ -122002,6 +123152,51 @@ function getTransientTransportCode(error2) {
122002
123152
  }
122003
123153
  return void 0;
122004
123154
  }
123155
+ function validateHttpUrl(url2) {
123156
+ const { protocol, username, password } = new URL(url2);
123157
+ if (protocol !== "http:" && protocol !== "https:") {
123158
+ throw new TypeError(`Unsupported URL protocol ${protocol}; expected http: or https:`);
123159
+ }
123160
+ if (username || password) {
123161
+ throw new TypeError("HTTP(S) URLs with embedded credentials are unsupported");
123162
+ }
123163
+ }
123164
+ const REQUEST_CONSTRUCTION_ERROR_CODES = /* @__PURE__ */ new Set([
123165
+ "ERR_INVALID_URL",
123166
+ "ERR_INVALID_ARG_TYPE",
123167
+ "ERR_INVALID_ARG_VALUE",
123168
+ "ERR_INVALID_CHAR",
123169
+ "ERR_INVALID_HTTP_TOKEN",
123170
+ "ERR_HTTP_INVALID_HEADER_VALUE",
123171
+ "ERR_UNESCAPED_CHARACTERS",
123172
+ // Undici validates request options and headers during dispatch, after
123173
+ // Fetch has constructed the Request (e.g. unsupported Expect headers).
123174
+ "UND_ERR_INVALID_ARG",
123175
+ "UND_ERR_NOT_SUPPORTED"
123176
+ ]);
123177
+ function describeTransportFailure(error2) {
123178
+ const known = getTransientTransportCode(error2);
123179
+ if (known)
123180
+ return known;
123181
+ let firstCode;
123182
+ let innermostName;
123183
+ let current = error2;
123184
+ for (let depth = 0; current && depth < 8; depth++) {
123185
+ const { code: code2, name: name2, message: message2 } = current;
123186
+ if (name2 === "Error" && message2 === "bad port" && code2 === void 0) {
123187
+ return void 0;
123188
+ }
123189
+ if (typeof code2 === "string" && code2) {
123190
+ if (REQUEST_CONSTRUCTION_ERROR_CODES.has(code2))
123191
+ return void 0;
123192
+ firstCode ?? (firstCode = code2);
123193
+ }
123194
+ if (typeof name2 === "string" && name2)
123195
+ innermostName = name2;
123196
+ current = current.cause;
123197
+ }
123198
+ return firstCode ?? innermostName ?? "unknown";
123199
+ }
122005
123200
  const HTTP_DEBUG_ENABLED = typeof process !== "undefined" && typeof process.env.DEBUG === "string" && (process.env.DEBUG.includes("workflow:") || process.env.DEBUG === "*");
122006
123201
  const DIAGNOSTIC_HEADERS = [
122007
123202
  "x-vercel-id",
@@ -122094,6 +123289,7 @@ function httpClientSpanAttributes(args) {
122094
123289
  async function instrumentedFetch(opts) {
122095
123290
  const { method, url: url2, headers: headers2, body: body2, dispatcher: dispatcher2, peerService = "workflow-server", timeoutMs = REQUEST_TIMEOUT_MS, signal: callerSignal, injectTraceContext = true, cacheBust = true, logLabel, buildError, onTransportOutcome, deferTransportSuccessUntilBody = false } = opts;
122096
123291
  const label = logLabel ?? url2;
123292
+ validateHttpUrl(url2);
122097
123293
  return trace(`http ${method}`, { kind: await getSpanKind("CLIENT") }, async (span) => {
122098
123294
  var _a3, _b2, _c, _d, _e2;
122099
123295
  span == null ? void 0 : span.setAttributes(httpClientSpanAttributes({ method, url: url2, peerService }));
@@ -122103,13 +123299,13 @@ async function instrumentedFetch(opts) {
122103
123299
  headers2.set("X-Request-Time", Date.now().toString());
122104
123300
  const timeoutSignal = timeoutMs != null ? AbortSignal.timeout(timeoutMs) : void 0;
122105
123301
  const signal = callerSignal && timeoutSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : callerSignal ?? timeoutSignal;
123302
+ const nodeAgents = dispatcher2 ? void 0 : getNodeHttpAgents();
123303
+ span == null ? void 0 : span.setAttributes({
123304
+ ...WorkflowHttpTransport(nodeAgents ? "node-http" : "undici")
123305
+ });
122106
123306
  const start2 = Date.now();
122107
123307
  let response2;
122108
123308
  try {
122109
- const nodeAgents = dispatcher2 ? void 0 : getNodeHttpAgents();
122110
- span == null ? void 0 : span.setAttributes({
122111
- ...WorkflowHttpTransport(nodeAgents ? "node-http" : "undici")
122112
- });
122113
123309
  response2 = nodeAgents ? await nodeHttpFetch(url2, {
122114
123310
  method,
122115
123311
  headers: headers2,
@@ -122138,7 +123334,7 @@ async function instrumentedFetch(opts) {
122138
123334
  (_a3 = span == null ? void 0 : span.recordException) == null ? void 0 : _a3.call(span, timeoutError);
122139
123335
  throw timeoutError;
122140
123336
  }
122141
- const transportCode = getTransientTransportCode(error2);
123337
+ const transportCode = describeTransportFailure(error2);
122142
123338
  if (transportCode) {
122143
123339
  const transportError2 = new WorkflowWorldError(`${method} ${label} transport failure after ${elapsed}ms (${transportCode})`, { url: url2, code: "TRANSPORT", cause: error2 });
122144
123340
  span == null ? void 0 : span.setAttributes({ ...ErrorType("TRANSPORT") });
@@ -126884,7 +128080,7 @@ var QueueClient = class {
126884
128080
  setApi(this, new ApiClient({ ...options, region }));
126885
128081
  }
126886
128082
  };
126887
- const version = "4.7.4";
128083
+ const version = "4.7.6";
126888
128084
  const IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
126889
128085
  const MAX_BODY_PARSE_RETRIES = 2;
126890
128086
  const BODY_PARSE_RETRY_BASE_MS = 100;
@@ -126995,6 +128191,7 @@ async function makeRequest({ endpoint, options = {}, config: config2 = {}, schem
126995
128191
  const method = (options.method || "GET").toUpperCase();
126996
128192
  const { baseUrl, headers: headers2 } = await getHttpConfig(config2);
126997
128193
  const url2 = `${baseUrl}${endpoint}`;
128194
+ validateHttpUrl(url2);
126998
128195
  return trace(`http ${method}`, { kind: await getSpanKind("CLIENT") }, async (span) => {
126999
128196
  var _a3, _b2, _c;
127000
128197
  span == null ? void 0 : span.setAttributes(httpClientSpanAttributes({
@@ -127016,13 +128213,15 @@ async function makeRequest({ endpoint, options = {}, config: config2 = {}, schem
127016
128213
  headers2.set("X-Request-Time", Date.now().toString());
127017
128214
  const timeoutSignal = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
127018
128215
  const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;
128216
+ const nodeAgents = getNodeHttpAgents(config2);
128217
+ const undiciRequest = nodeAgents ? void 0 : new Request(url2, { ...options, body: body2, headers: headers2, signal });
128218
+ const undiciDispatcher = nodeAgents ? void 0 : getDispatcher(config2);
128219
+ span == null ? void 0 : span.setAttributes({
128220
+ ...WorkflowHttpTransport(nodeAgents ? "node-http" : "undici")
128221
+ });
127019
128222
  const fetchStart = Date.now();
127020
128223
  let response2;
127021
128224
  try {
127022
- const nodeAgents = getNodeHttpAgents(config2);
127023
- span == null ? void 0 : span.setAttributes({
127024
- ...WorkflowHttpTransport(nodeAgents ? "node-http" : "undici")
127025
- });
127026
128225
  response2 = nodeAgents ? await nodeHttpFetch(url2, {
127027
128226
  method,
127028
128227
  headers: headers2,
@@ -127033,9 +128232,9 @@ async function makeRequest({ endpoint, options = {}, config: config2 = {}, schem
127033
128232
  // with: without these the node:http path arms no stalled-socket
127034
128233
  // deadline.
127035
128234
  ...getNodeHttpPhaseTimeouts()
127036
- }) : await fetch(new Request(url2, { ...options, body: body2, headers: headers2, signal }), {
128235
+ }) : await fetch(undiciRequest, {
127037
128236
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- undici v7 dispatcher types don't match @types/node's RequestInit
127038
- dispatcher: getDispatcher(config2)
128237
+ dispatcher: undiciDispatcher
127039
128238
  });
127040
128239
  } catch (error2) {
127041
128240
  const elapsed = Date.now() - fetchStart;
@@ -127045,7 +128244,7 @@ async function makeRequest({ endpoint, options = {}, config: config2 = {}, schem
127045
128244
  (_a3 = span == null ? void 0 : span.recordException) == null ? void 0 : _a3.call(span, timeoutError);
127046
128245
  throw timeoutError;
127047
128246
  }
127048
- const transportCode = getTransientTransportCode(error2);
128247
+ const transportCode = describeTransportFailure(error2);
127049
128248
  if (transportCode) {
127050
128249
  if (retryConnectTimeout && canRetryRead && transportCode === "UND_ERR_CONNECT_TIMEOUT" && attempt === 0) {
127051
128250
  await new Promise((resolve2) => setTimeout(resolve2, BODY_PARSE_RETRY_BASE_MS));
@@ -127230,10 +128429,20 @@ const MAX_DELAY_SECONDS = Number(
127230
128429
  const HANDLER_ERROR_RETRY_AFTER_SECONDS = 1;
127231
128430
  const HANDLER_ERROR_MAX_RETRY_AFTER_SECONDS = 900;
127232
128431
  const HANDLER_ERROR_RETRY_JITTER_RATIO = 0.25;
127233
- function getHandlerErrorRetryAfterSeconds(deliveryCount) {
128432
+ function getErrorRetryAfterSeconds(error2) {
128433
+ if (typeof error2 !== "object" || error2 === null)
128434
+ return void 0;
128435
+ const retryAfter = error2.retryAfter;
128436
+ if (typeof retryAfter !== "number" || !Number.isFinite(retryAfter) || retryAfter <= 0) {
128437
+ return void 0;
128438
+ }
128439
+ return Math.min(Math.ceil(retryAfter), HANDLER_ERROR_MAX_RETRY_AFTER_SECONDS);
128440
+ }
128441
+ function getHandlerErrorRetryAfterSeconds(error2, deliveryCount) {
127234
128442
  const backoffSeconds = Math.min(Math.max(HANDLER_ERROR_RETRY_AFTER_SECONDS, 2 ** (deliveryCount - 1)), HANDLER_ERROR_MAX_RETRY_AFTER_SECONDS);
127235
128443
  const jitterSeconds = Math.floor(Math.random() * (Math.ceil(backoffSeconds * HANDLER_ERROR_RETRY_JITTER_RATIO) + 1));
127236
- return Math.max(HANDLER_ERROR_RETRY_AFTER_SECONDS, backoffSeconds - jitterSeconds);
128444
+ const jitteredBackoffSeconds = Math.max(HANDLER_ERROR_RETRY_AFTER_SECONDS, backoffSeconds - jitterSeconds);
128445
+ return Math.max(jitteredBackoffSeconds, getErrorRetryAfterSeconds(error2) ?? HANDLER_ERROR_RETRY_AFTER_SECONDS);
127237
128446
  }
127238
128447
  function getHeadersFromPayload(payload) {
127239
128448
  const headers2 = {};
@@ -127335,7 +128544,7 @@ function createQueue$1(config2) {
127335
128544
  // redrive in lockstep. Workflow handlers are event-sourced and must
127336
128545
  // remain idempotent because queue retries can happen close together.
127337
128546
  retry: (error2, { messageId, deliveryCount }) => {
127338
- const afterSeconds = getHandlerErrorRetryAfterSeconds(deliveryCount);
128547
+ const afterSeconds = getHandlerErrorRetryAfterSeconds(error2, deliveryCount);
127339
128548
  console.error(`[workflow] Queue handler failed for message "${messageId}" on delivery attempt ${deliveryCount}; retrying in ${afterSeconds}s:`, error2);
127340
128549
  return { afterSeconds };
127341
128550
  }
@@ -127698,7 +128907,7 @@ async function fetchV4(url2, init2, config2, opName) {
127698
128907
  }
127699
128908
  } catch (cause) {
127700
128909
  noteEventsTransportOutcome(dispatcher2, cause);
127701
- const transportCode = getTransientTransportCode(cause);
128910
+ const transportCode = describeTransportFailure(cause);
127702
128911
  controller.error(transportCode ? new WorkflowWorldError(`v4 ${opName}: response stream transport failure (${transportCode})`, { url: url2, code: "TRANSPORT", cause }) : cause);
127703
128912
  }
127704
128913
  },
@@ -129679,6 +130888,23 @@ function getCommonReducers(global2 = globalThis) {
129679
130888
  BigInt: (value) => typeof value === "bigint" && value.toString(),
129680
130889
  BigInt64Array: (value) => value instanceof global2.BigInt64Array && viewToBase64(value),
129681
130890
  BigUint64Array: (value) => value instanceof global2.BigUint64Array && viewToBase64(value),
130891
+ // Claims `DataView` for the same reason every typed array is claimed:
130892
+ // devalue's built-in `DataView` encoding emits the *whole* backing
130893
+ // ArrayBuffer plus the view's offset and length. For a view onto Node's
130894
+ // shared `Buffer` pool (`Buffer.allocUnsafe`, and `Buffer.from` below
130895
+ // `Buffer.poolSize >>> 1`) that whole buffer is 8 KiB of unrelated
130896
+ // allocations, so a four-byte view would persist bytes the workflow
130897
+ // never handed us into the run's event log. Base64 of the viewed range
130898
+ // keeps the payload to the bytes the view actually spans.
130899
+ //
130900
+ // The tag deliberately is *not* `DataView`. devalue skips its built-in
130901
+ // branch for any tag that has a custom reviver, so registering one under
130902
+ // that name would strip the bounds off `["DataView", buf, offset, length]`
130903
+ // tuples already in event logs — the o11y UI and CLI read those with
130904
+ // current code, and would render the whole pooled slab this reducer
130905
+ // exists to keep out. Under a distinct tag the built-in branch stays
130906
+ // reachable and those payloads still revive with their bounds.
130907
+ DataViewBytes: (value) => value instanceof global2.DataView && viewToBase64(value),
129682
130908
  // Class and Instance are intentionally placed before Error so that
129683
130909
  // custom Error subclasses with WORKFLOW_SERIALIZE take precedence
129684
130910
  // over the generic Error serialization (devalue uses first-match-wins).
@@ -129946,6 +131172,12 @@ function getCommonRevivers(global2 = globalThis) {
129946
131172
  const ab = reviveArrayBuffer(value);
129947
131173
  return new global2.BigUint64Array(ab);
129948
131174
  },
131175
+ // No `DataView` reviver: see the `DataViewBytes` reducer. Older payloads
131176
+ // tagged `DataView` must keep reaching devalue's built-in branch.
131177
+ DataViewBytes: (value) => {
131178
+ const ab = reviveArrayBuffer(value);
131179
+ return new global2.DataView(ab);
131180
+ },
129949
131181
  Date: (value) => new global2.Date(value),
129950
131182
  DOMException: (value) => {
129951
131183
  const error2 = new global2.DOMException(value.message, value.name);
@@ -130033,6 +131265,13 @@ async function getForwardedWritableEncryptionKey(runId, deploymentId) {
130033
131265
  const rawKey = deploymentId ? await world.getEncryptionKeyForRun(runId, { deploymentId }) : await world.getEncryptionKeyForRun(await world.runs.get(runId));
130034
131266
  return rawKey ? await importKey(rawKey, ["encrypt"]) : void 0;
130035
131267
  }
131268
+ function lazyForwardedWritableEncryptionKey(runId, deploymentId) {
131269
+ let keyPromise;
131270
+ return () => {
131271
+ keyPromise ?? (keyPromise = getForwardedWritableEncryptionKey(runId, deploymentId));
131272
+ return keyPromise;
131273
+ };
131274
+ }
130036
131275
  function getExternalRevivers(global2 = globalThis, ops, runId, cryptoKey) {
130037
131276
  return {
130038
131277
  ...getCommonRevivers(global2),
@@ -130083,7 +131322,7 @@ function getExternalRevivers(global2 = globalThis, ops, runId, cryptoKey) {
130083
131322
  },
130084
131323
  WritableStream: (value) => {
130085
131324
  const targetRunId = typeof value.runId === "string" ? value.runId : runId;
130086
- const targetKey = targetRunId === runId ? cryptoKey : getForwardedWritableEncryptionKey(targetRunId, value.deploymentId);
131325
+ const targetKey = targetRunId === runId ? cryptoKey : lazyForwardedWritableEncryptionKey(targetRunId, value.deploymentId);
130087
131326
  const serialize2 = getSerializeStream(getExternalReducers(global2, ops, targetRunId, targetKey), targetKey);
130088
131327
  const serverWritable = new WorkflowServerWritableStream(value.name, targetRunId);
130089
131328
  const state = createFlushableState();
@@ -130313,7 +131552,7 @@ function getStepRevivers(global2 = globalThis, ops, runId, cryptoKey, deployment
130313
131552
  WritableStream: (value) => {
130314
131553
  const targetRunId = typeof value.runId === "string" ? value.runId : runId;
130315
131554
  const targetDeploymentId = typeof value.deploymentId === "string" ? value.deploymentId : targetRunId === runId ? deploymentId : void 0;
130316
- const targetKey = targetRunId === runId ? cryptoKey : getForwardedWritableEncryptionKey(targetRunId, targetDeploymentId);
131555
+ const targetKey = targetRunId === runId ? cryptoKey : lazyForwardedWritableEncryptionKey(targetRunId, targetDeploymentId);
130317
131556
  const serialize2 = getSerializeStream(getStepReducers(global2, ops, targetRunId, targetKey), targetKey);
130318
131557
  const serverWritable = new WorkflowServerWritableStream(value.name, targetRunId);
130319
131558
  const state = createFlushableState();
@@ -133362,17 +134601,29 @@ async function start$1(workflow, argsOrOptions, options) {
133362
134601
  ...WorkflowArgumentsCount(args.length)
133363
134602
  });
133364
134603
  const world = (opts == null ? void 0 : opts.world) ?? getWorld();
133365
- const currentDeploymentId = await world.getDeploymentId();
133366
- let deploymentId = opts.deploymentId ?? currentDeploymentId;
133367
- if (deploymentId === "latest") {
133368
- if (world.resolveLatestDeploymentId) {
133369
- deploymentId = await world.resolveLatestDeploymentId();
133370
- } else {
133371
- if (!hasWarnedLatestNoOp) {
133372
- hasWarnedLatestNoOp = true;
133373
- runtimeLogger.warn("deploymentId: 'latest' has no effect in this world and was ignored. It is only supported by worlds with atomic deployments, such as Vercel. The run will target the current deployment.", { currentDeploymentId });
134604
+ let currentDeploymentId;
134605
+ let deploymentId;
134606
+ if (opts.deploymentId === void 0 || opts.deploymentId === "latest") {
134607
+ const current = await world.getDeploymentId();
134608
+ currentDeploymentId = current;
134609
+ deploymentId = opts.deploymentId ?? current;
134610
+ if (deploymentId === "latest") {
134611
+ if (world.resolveLatestDeploymentId) {
134612
+ deploymentId = await world.resolveLatestDeploymentId();
134613
+ } else {
134614
+ if (!hasWarnedLatestNoOp) {
134615
+ hasWarnedLatestNoOp = true;
134616
+ runtimeLogger.warn("deploymentId: 'latest' has no effect in this world and was ignored. It is only supported by worlds with atomic deployments, such as Vercel. The run will target the current deployment.", { currentDeploymentId });
134617
+ }
134618
+ deploymentId = current;
133374
134619
  }
133375
- deploymentId = currentDeploymentId;
134620
+ }
134621
+ } else {
134622
+ deploymentId = opts.deploymentId;
134623
+ try {
134624
+ currentDeploymentId = await world.getDeploymentId();
134625
+ } catch (err) {
134626
+ runtimeLogger.debug("Current deployment is unavailable; starting as a cross-deployment run", { deploymentId, error: String(err) });
133376
134627
  }
133377
134628
  }
133378
134629
  let framedByteStreams;
@@ -133803,8 +135054,8 @@ createQueueHandler(stepPrefix, async (message_, metadata) => {
133803
135054
  stepName: stepNameFromQueue,
133804
135055
  attempt: metadata.attempt
133805
135056
  });
135057
+ const world = getWorld();
133806
135058
  try {
133807
- const world = getWorld();
133808
135059
  await world.events.create(workflowRunId, {
133809
135060
  eventType: "step_failed",
133810
135061
  specVersion: SPEC_VERSION_CURRENT,
@@ -133814,22 +135065,34 @@ createQueueHandler(stepPrefix, async (message_, metadata) => {
133814
135065
  error: `Step exceeded maximum queue deliveries (${metadata.attempt}/${MAX_QUEUE_DELIVERIES})`
133815
135066
  }
133816
135067
  }, { requestId });
133817
- await queueMessage(world, getWorkflowQueueName(workflowName, stepNamespace), {
133818
- runId: workflowRunId,
133819
- traceCarrier: await serializeTraceCarrier(),
133820
- requestedAt: /* @__PURE__ */ new Date()
133821
- });
133822
135068
  } catch (err) {
133823
- if (EntityConflictError.is(err) || RunExpiredError.is(err)) {
135069
+ if (RunExpiredError.is(err)) {
135070
+ return;
135071
+ }
135072
+ if (!EntityConflictError.is(err)) {
135073
+ if (isRetryableWorldError(err)) {
135074
+ runtimeLogger.warn("Transient error marking step as failed after max deliveries, retrying via queue redelivery", {
135075
+ workflowRunId,
135076
+ stepId,
135077
+ attempt: metadata.attempt,
135078
+ error: err instanceof Error ? err.message : String(err)
135079
+ });
135080
+ throw err;
135081
+ }
135082
+ runtimeLogger.error(`Failed to mark step as failed after ${metadata.attempt} delivery attempts. A persistent error is preventing the step from being terminated. The run will remain in its current state until manually resolved. This is most likely due to a persistent outage of the workflow backend or a bug in the workflow runtime and should be reported to the Workflow team.`, {
135083
+ workflowRunId,
135084
+ stepId,
135085
+ attempt: metadata.attempt,
135086
+ error: err instanceof Error ? err.message : String(err)
135087
+ });
133824
135088
  return;
133825
135089
  }
133826
- runtimeLogger.error(`Failed to mark step as failed after ${metadata.attempt} delivery attempts. A persistent error is preventing the step from being terminated. The run will remain in its current state until manually resolved. This is most likely due to a persistent outage of the workflow backend or a bug in the workflow runtime and should be reported to the Workflow team.`, {
133827
- workflowRunId,
133828
- stepId,
133829
- attempt: metadata.attempt,
133830
- error: err instanceof Error ? err.message : String(err)
133831
- });
133832
135090
  }
135091
+ await queueMessage(world, getWorkflowQueueName(workflowName, stepNamespace), {
135092
+ runId: workflowRunId,
135093
+ traceCarrier: await serializeTraceCarrier(),
135094
+ requestedAt: /* @__PURE__ */ new Date()
135095
+ });
133833
135096
  return;
133834
135097
  }
133835
135098
  const spanLinks = await linkToCurrentContext();
@@ -156092,7 +157355,7 @@ const route4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProper
156092
157355
  __proto__: null,
156093
157356
  loader
156094
157357
  }, Symbol.toStringTag, { value: "Module" }));
156095
- const serverManifest = { "entry": { "module": "/assets/entry.client-C_C46bD6.js", "imports": ["/assets/index-BsV8i_Jn.js"], "css": [] }, "routes": { "root": { "id": "root", "parentId": void 0, "path": "", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": true, "module": "/assets/root-8dRSI2dZ.js", "imports": ["/assets/index-BsV8i_Jn.js", "/assets/mermaid-3ZIDBTTL-871SHrja.js"], "css": ["/assets/root-BOS11TzD.css", "/assets/mermaid-3ZIDBTTL-yyHEMZs4.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/home": { "id": "routes/home", "parentId": "root", "path": void 0, "index": true, "caseSensitive": void 0, "hasAction": false, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": false, "module": "/assets/home-CWZI6fn-.js", "imports": ["/assets/index-BsV8i_Jn.js", "/assets/workflow-graph-viewer-C1On-L19.js", "/assets/mermaid-3ZIDBTTL-871SHrja.js", "/assets/index-DZSXezpI.js"], "css": ["/assets/workflow-graph-viewer-yls6qlc0.css", "/assets/mermaid-3ZIDBTTL-yyHEMZs4.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/run-detail": { "id": "routes/run-detail", "parentId": "root", "path": "run/:runId", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": false, "module": "/assets/run-detail-CaG8UDwA.js", "imports": ["/assets/index-BsV8i_Jn.js", "/assets/workflow-graph-viewer-C1On-L19.js", "/assets/mermaid-3ZIDBTTL-871SHrja.js", "/assets/encryption-BRhjWsZh.js", "/assets/index-DZSXezpI.js"], "css": ["/assets/workflow-graph-viewer-yls6qlc0.css", "/assets/mermaid-3ZIDBTTL-yyHEMZs4.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/api.rpc": { "id": "routes/api.rpc", "parentId": "root", "path": "api/rpc", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": false, "hasErrorBoundary": false, "module": "/assets/api.rpc-l0sNRNKZ.js", "imports": [], "css": [], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/api.stream.$streamId": { "id": "routes/api.stream.$streamId", "parentId": "root", "path": "api/stream/:streamId", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": false, "hasErrorBoundary": false, "module": "/assets/api.stream._streamId-l0sNRNKZ.js", "imports": [], "css": [], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 } }, "url": "/assets/manifest-25c2e662.js", "version": "25c2e662", "sri": void 0 };
157358
+ const serverManifest = { "entry": { "module": "/assets/entry.client-C_C46bD6.js", "imports": ["/assets/index-BsV8i_Jn.js"], "css": [] }, "routes": { "root": { "id": "root", "parentId": void 0, "path": "", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": true, "module": "/assets/root-C2Eu3fUP.js", "imports": ["/assets/index-BsV8i_Jn.js", "/assets/mermaid-3ZIDBTTL-B1-N6W83.js"], "css": ["/assets/root-BOS11TzD.css", "/assets/mermaid-3ZIDBTTL-yyHEMZs4.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/home": { "id": "routes/home", "parentId": "root", "path": void 0, "index": true, "caseSensitive": void 0, "hasAction": false, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": false, "module": "/assets/home-BcCTbe4i.js", "imports": ["/assets/index-BsV8i_Jn.js", "/assets/workflow-graph-viewer-lj3vdGSs.js", "/assets/mermaid-3ZIDBTTL-B1-N6W83.js", "/assets/index-DhdkuKp5.js"], "css": ["/assets/workflow-graph-viewer-yls6qlc0.css", "/assets/mermaid-3ZIDBTTL-yyHEMZs4.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/run-detail": { "id": "routes/run-detail", "parentId": "root", "path": "run/:runId", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": false, "module": "/assets/run-detail-CyImB2zR.js", "imports": ["/assets/index-BsV8i_Jn.js", "/assets/workflow-graph-viewer-lj3vdGSs.js", "/assets/mermaid-3ZIDBTTL-B1-N6W83.js", "/assets/encryption-CVDhlDp_.js", "/assets/index-DhdkuKp5.js"], "css": ["/assets/workflow-graph-viewer-yls6qlc0.css", "/assets/mermaid-3ZIDBTTL-yyHEMZs4.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/api.rpc": { "id": "routes/api.rpc", "parentId": "root", "path": "api/rpc", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": false, "hasErrorBoundary": false, "module": "/assets/api.rpc-l0sNRNKZ.js", "imports": [], "css": [], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/api.stream.$streamId": { "id": "routes/api.stream.$streamId", "parentId": "root", "path": "api/stream/:streamId", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": false, "hasErrorBoundary": false, "module": "/assets/api.stream._streamId-l0sNRNKZ.js", "imports": [], "css": [], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 } }, "url": "/assets/manifest-f88c7f34.js", "version": "f88c7f34", "sri": void 0 };
156096
157359
  const assetsBuildDirectory = "build/client";
156097
157360
  const basename = "/";
156098
157361
  const future = { "unstable_optimizeDeps": false, "unstable_subResourceIntegrity": false, "unstable_trailingSlashAwareDataRequests": false, "unstable_previewServerPrerendering": false, "v8_middleware": false, "v8_splitRouteModules": false, "v8_viteEnvironmentApi": false };