@workflow/web 4.1.15 → 4.1.17

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.
@@ -14,7 +14,11 @@ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "
14
14
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
15
15
  var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj);
16
16
  var _a2, _b, _root, _hasMagic, _uflag, _parts, _parent, _parentIndex, _negs, _filledNegs, _options, _toString, _emptyExt, _AST_instances, fillNegs_fn, _AST_static, parseAST_fn, canAdoptWithSpace_fn, canAdopt_fn, canAdoptType_fn, adoptWithSpace_fn, adopt_fn, canUsurpType_fn, canUsurp_fn, usurp_fn, flatten_fn, partsToRegExp_fn, parseGlob_fn, _Minimatch_instances, matchGlobstar_fn, matchGlobStarBodySections_fn, matchOne_fn, _reader;
17
- 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-C0o0w-Mo.js";
17
+ import { createRequire as __wkfCreateRequire } from "node:module";
18
+ if (typeof globalThis.require === "undefined") {
19
+ globalThis.require = __wkfCreateRequire(import.meta.url);
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-Pzk6cskY.js";
18
22
  import require$$0$5, { PassThrough } from "node:stream";
19
23
  import require$$0 from "util";
20
24
  import require$$1 from "crypto";
@@ -81828,7 +81832,7 @@ var tn = f("block", "before:content-[counter(line)]", "before:inline-block", "be
81828
81832
  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 });
81829
81833
  var Se = reactExports.createContext({ code: "" }), de = () => reactExports.useContext(Se);
81830
81834
  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 }) });
81831
- var cn$1 = /\n+$/, dn = reactExports.lazy(() => import("./highlighted-body-B3W2YXNL-DyZmWYQX.js").then((e) => ({ default: e.HighlightedCodeBlockBody }))), rt = ({ code: e, language: t, className: o, children: n, isIncomplete: s2 = false, ...r2 }) => {
81835
+ var cn$1 = /\n+$/, dn = reactExports.lazy(() => import("./highlighted-body-B3W2YXNL-DdYG7JBx.js").then((e) => ({ default: e.HighlightedCodeBlockBody }))), rt = ({ code: e, language: t, className: o, children: n, isIncomplete: s2 = false, ...r2 }) => {
81832
81836
  let i = reactExports.useMemo(() => e.replace(cn$1, ""), [e]), c = reactExports.useMemo(() => ({ bg: "transparent", fg: "inherit", tokens: i.split(`
81833
81837
  `).map((a2) => [{ content: a2, color: "inherit", bgColor: "transparent", htmlStyle: {}, offset: 0 }]) }), [i]);
81834
81838
  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 }) })] }) });
@@ -82150,7 +82154,7 @@ var Dt = ({ children: e, className: t, onDownload: o, onError: n }) => {
82150
82154
  }, []), 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] });
82151
82155
  };
82152
82156
  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 }) })] });
82153
- var Jn = reactExports.lazy(() => import("./mermaid-3ZIDBTTL-Cf251uS3.js").then((e) => ({ default: e.Mermaid }))), Kn = /language-([^\s]+)/;
82157
+ var Jn = reactExports.lazy(() => import("./mermaid-3ZIDBTTL-Dys2uWXl.js").then((e) => ({ default: e.Mermaid }))), Kn = /language-([^\s]+)/;
82154
82158
  function ke(e, t) {
82155
82159
  if (!(e != null && e.position || t != null && t.position)) return true;
82156
82160
  if (!(e != null && e.position && (t != null && t.position))) return false;
@@ -91897,7 +91901,7 @@ async function withTraceContext(traceCarrier, fn2) {
91897
91901
  }
91898
91902
  const OtelApi = once$1(async () => {
91899
91903
  try {
91900
- return await import("./index-meg9qk8y.js");
91904
+ return await import("./index-hBO56emR.js");
91901
91905
  } catch {
91902
91906
  runtimeLogger.info("OpenTelemetry not available, tracing will be disabled");
91903
91907
  return null;
@@ -92042,7 +92046,7 @@ createLogger("build", {
92042
92046
  debugNamespace: "workflow:build"
92043
92047
  });
92044
92048
  const MAX_QUEUE_DELIVERIES = 48;
92045
- const version$1 = "4.7.0";
92049
+ const version$1 = "4.8.1";
92046
92050
  const execFileAsync = promisify(execFile);
92047
92051
  function parsePort$1(value, radix = 10) {
92048
92052
  const port = parseInt(value, radix);
@@ -92497,7 +92501,7 @@ async function readFirstByte(filePath) {
92497
92501
  }
92498
92502
  async function deleteJSON(filePath) {
92499
92503
  try {
92500
- await promises.unlink(filePath);
92504
+ await withWindowsRetry(() => promises.unlink(filePath));
92501
92505
  } catch (error2) {
92502
92506
  if (error2.code !== "ENOENT")
92503
92507
  throw error2;
@@ -92802,7 +92806,7 @@ async function initDataDir(dataDir) {
92802
92806
  let otelApiPromise$1 = null;
92803
92807
  async function getOtelApi$1() {
92804
92808
  if (!otelApiPromise$1) {
92805
- otelApiPromise$1 = import("./index-meg9qk8y.js").catch(() => null);
92809
+ otelApiPromise$1 = import("./index-hBO56emR.js").catch(() => null);
92806
92810
  }
92807
92811
  return otelApiPromise$1;
92808
92812
  }
@@ -100042,8 +100046,8 @@ function requireClientH1() {
100042
100046
  return this.createError(ret, EMPTY_BUF);
100043
100047
  }
100044
100048
  createError(ret, data) {
100045
- const { llhttp, contentLength, bytesRead } = this;
100046
- if (contentLength && bytesRead !== parseInt(contentLength, 10)) {
100049
+ const { llhttp, contentLength: contentLength2, bytesRead } = this;
100050
+ if (contentLength2 && bytesRead !== parseInt(contentLength2, 10)) {
100047
100051
  return new ResponseContentLengthMismatchError();
100048
100052
  }
100049
100053
  const ptr = llhttp.llhttp_get_error_reason(this.ptr);
@@ -100296,7 +100300,7 @@ function requireClientH1() {
100296
100300
  * @returns {number}
100297
100301
  */
100298
100302
  onMessageComplete() {
100299
- const { client: client2, socket, statusCode, upgrade, headers: headers2, contentLength, bytesRead, shouldKeepAlive } = this;
100303
+ const { client: client2, socket, statusCode, upgrade, headers: headers2, contentLength: contentLength2, bytesRead, shouldKeepAlive } = this;
100300
100304
  if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
100301
100305
  return -1;
100302
100306
  }
@@ -100318,7 +100322,7 @@ function requireClientH1() {
100318
100322
  if (statusCode < 200) {
100319
100323
  return 0;
100320
100324
  }
100321
- if (request2.method !== "HEAD" && contentLength && bytesRead !== parseInt(contentLength, 10)) {
100325
+ if (request2.method !== "HEAD" && contentLength2 && bytesRead !== parseInt(contentLength2, 10)) {
100322
100326
  util2.destroy(socket, new ResponseContentLengthMismatchError());
100323
100327
  return -1;
100324
100328
  }
@@ -100573,7 +100577,7 @@ function requireClientH1() {
100573
100577
  }
100574
100578
  function writeH1(client2, request2) {
100575
100579
  const { method, path: path2, host, upgrade, blocking, reset } = request2;
100576
- let { body: body2, headers: headers2, contentLength } = request2;
100580
+ let { body: body2, headers: headers2, contentLength: contentLength2 } = request2;
100577
100581
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
100578
100582
  if (util2.isFormDataLike(body2)) {
100579
100583
  if (!extractBody) {
@@ -100584,7 +100588,7 @@ function requireClientH1() {
100584
100588
  headers2.push("content-type", contentType);
100585
100589
  }
100586
100590
  body2 = bodyStream.stream;
100587
- contentLength = bodyStream.length;
100591
+ contentLength2 = bodyStream.length;
100588
100592
  } else if (util2.isBlobLike(body2) && request2.contentType == null && body2.type) {
100589
100593
  headers2.push("content-type", body2.type);
100590
100594
  }
@@ -100592,14 +100596,14 @@ function requireClientH1() {
100592
100596
  body2.read(0);
100593
100597
  }
100594
100598
  const bodyLength = util2.bodyLength(body2);
100595
- contentLength = bodyLength ?? contentLength;
100596
- if (contentLength === null) {
100597
- contentLength = request2.contentLength;
100599
+ contentLength2 = bodyLength ?? contentLength2;
100600
+ if (contentLength2 === null) {
100601
+ contentLength2 = request2.contentLength;
100598
100602
  }
100599
- if (contentLength === 0 && !expectsPayload) {
100600
- contentLength = null;
100603
+ if (contentLength2 === 0 && !expectsPayload) {
100604
+ contentLength2 = null;
100601
100605
  }
100602
- if (shouldSendContentLength(method) && contentLength > 0 && request2.contentLength !== null && request2.contentLength !== contentLength) {
100606
+ if (shouldSendContentLength(method) && contentLength2 > 0 && request2.contentLength !== null && request2.contentLength !== contentLength2) {
100603
100607
  if (client2[kStrictContentLength]) {
100604
100608
  util2.errorRequest(client2, request2, new RequestContentLengthMismatchError());
100605
100609
  return false;
@@ -100678,28 +100682,28 @@ upgrade: ${upgrade}\r
100678
100682
  channels.sendHeaders.publish({ request: request2, headers: header, socket });
100679
100683
  }
100680
100684
  if (!body2 || bodyLength === 0) {
100681
- writeBuffer2(abort, null, client2, request2, socket, contentLength, header, expectsPayload);
100685
+ writeBuffer2(abort, null, client2, request2, socket, contentLength2, header, expectsPayload);
100682
100686
  } else if (util2.isBuffer(body2)) {
100683
- writeBuffer2(abort, body2, client2, request2, socket, contentLength, header, expectsPayload);
100687
+ writeBuffer2(abort, body2, client2, request2, socket, contentLength2, header, expectsPayload);
100684
100688
  } else if (util2.isBlobLike(body2)) {
100685
100689
  if (typeof body2.stream === "function") {
100686
- writeIterable(abort, body2.stream(), client2, request2, socket, contentLength, header, expectsPayload);
100690
+ writeIterable(abort, body2.stream(), client2, request2, socket, contentLength2, header, expectsPayload);
100687
100691
  } else {
100688
- writeBlob(abort, body2, client2, request2, socket, contentLength, header, expectsPayload);
100692
+ writeBlob(abort, body2, client2, request2, socket, contentLength2, header, expectsPayload);
100689
100693
  }
100690
100694
  } else if (util2.isStream(body2)) {
100691
- writeStream(abort, body2, client2, request2, socket, contentLength, header, expectsPayload);
100695
+ writeStream(abort, body2, client2, request2, socket, contentLength2, header, expectsPayload);
100692
100696
  } else if (util2.isIterable(body2)) {
100693
- writeIterable(abort, body2, client2, request2, socket, contentLength, header, expectsPayload);
100697
+ writeIterable(abort, body2, client2, request2, socket, contentLength2, header, expectsPayload);
100694
100698
  } else {
100695
100699
  assert2(false);
100696
100700
  }
100697
100701
  return true;
100698
100702
  }
100699
- function writeStream(abort, body2, client2, request2, socket, contentLength, header, expectsPayload) {
100700
- assert2(contentLength !== 0 || client2[kRunning] === 0, "stream body cannot be pipelined");
100703
+ function writeStream(abort, body2, client2, request2, socket, contentLength2, header, expectsPayload) {
100704
+ assert2(contentLength2 !== 0 || client2[kRunning] === 0, "stream body cannot be pipelined");
100701
100705
  let finished = false;
100702
- const writer = new AsyncWriter({ abort, socket, request: request2, contentLength, client: client2, expectsPayload, header });
100706
+ const writer = new AsyncWriter({ abort, socket, request: request2, contentLength: contentLength2, client: client2, expectsPayload, header });
100703
100707
  const onData = function(chunk) {
100704
100708
  if (finished) {
100705
100709
  return;
@@ -100765,22 +100769,22 @@ upgrade: ${upgrade}\r
100765
100769
  setImmediate(onClose);
100766
100770
  }
100767
100771
  }
100768
- function writeBuffer2(abort, body2, client2, request2, socket, contentLength, header, expectsPayload) {
100772
+ function writeBuffer2(abort, body2, client2, request2, socket, contentLength2, header, expectsPayload) {
100769
100773
  try {
100770
100774
  if (!body2) {
100771
- if (contentLength === 0) {
100775
+ if (contentLength2 === 0) {
100772
100776
  socket.write(`${header}content-length: 0\r
100773
100777
  \r
100774
100778
  `, "latin1");
100775
100779
  } else {
100776
- assert2(contentLength === null, "no body must not have content length");
100780
+ assert2(contentLength2 === null, "no body must not have content length");
100777
100781
  socket.write(`${header}\r
100778
100782
  `, "latin1");
100779
100783
  }
100780
100784
  } else if (util2.isBuffer(body2)) {
100781
- assert2(contentLength === body2.byteLength, "buffer body must have content length");
100785
+ assert2(contentLength2 === body2.byteLength, "buffer body must have content length");
100782
100786
  socket.cork();
100783
- socket.write(`${header}content-length: ${contentLength}\r
100787
+ socket.write(`${header}content-length: ${contentLength2}\r
100784
100788
  \r
100785
100789
  `, "latin1");
100786
100790
  socket.write(body2);
@@ -100796,15 +100800,15 @@ upgrade: ${upgrade}\r
100796
100800
  abort(err);
100797
100801
  }
100798
100802
  }
100799
- async function writeBlob(abort, body2, client2, request2, socket, contentLength, header, expectsPayload) {
100800
- assert2(contentLength === body2.size, "blob body must have content length");
100803
+ async function writeBlob(abort, body2, client2, request2, socket, contentLength2, header, expectsPayload) {
100804
+ assert2(contentLength2 === body2.size, "blob body must have content length");
100801
100805
  try {
100802
- if (contentLength != null && contentLength !== body2.size) {
100806
+ if (contentLength2 != null && contentLength2 !== body2.size) {
100803
100807
  throw new RequestContentLengthMismatchError();
100804
100808
  }
100805
100809
  const buffer2 = Buffer.from(await body2.arrayBuffer());
100806
100810
  socket.cork();
100807
- socket.write(`${header}content-length: ${contentLength}\r
100811
+ socket.write(`${header}content-length: ${contentLength2}\r
100808
100812
  \r
100809
100813
  `, "latin1");
100810
100814
  socket.write(buffer2);
@@ -100819,8 +100823,8 @@ upgrade: ${upgrade}\r
100819
100823
  abort(err);
100820
100824
  }
100821
100825
  }
100822
- async function writeIterable(abort, body2, client2, request2, socket, contentLength, header, expectsPayload) {
100823
- assert2(contentLength !== 0 || client2[kRunning] === 0, "iterator body cannot be pipelined");
100826
+ async function writeIterable(abort, body2, client2, request2, socket, contentLength2, header, expectsPayload) {
100827
+ assert2(contentLength2 !== 0 || client2[kRunning] === 0, "iterator body cannot be pipelined");
100824
100828
  let callback = null;
100825
100829
  function onDrain() {
100826
100830
  if (callback) {
@@ -100838,7 +100842,7 @@ upgrade: ${upgrade}\r
100838
100842
  }
100839
100843
  });
100840
100844
  socket.on("close", onDrain).on("drain", onDrain);
100841
- const writer = new AsyncWriter({ abort, socket, request: request2, contentLength, client: client2, expectsPayload, header });
100845
+ const writer = new AsyncWriter({ abort, socket, request: request2, contentLength: contentLength2, client: client2, expectsPayload, header });
100842
100846
  try {
100843
100847
  for await (const chunk of body2) {
100844
100848
  if (socket[kError]) {
@@ -100867,10 +100871,10 @@ upgrade: ${upgrade}\r
100867
100871
  * @param {boolean} arg.expectsPayload
100868
100872
  * @param {string} arg.header
100869
100873
  */
100870
- constructor({ abort, socket, request: request2, contentLength, client: client2, expectsPayload, header }) {
100874
+ constructor({ abort, socket, request: request2, contentLength: contentLength2, client: client2, expectsPayload, header }) {
100871
100875
  this.socket = socket;
100872
100876
  this.request = request2;
100873
- this.contentLength = contentLength;
100877
+ this.contentLength = contentLength2;
100874
100878
  this.client = client2;
100875
100879
  this.bytesWritten = 0;
100876
100880
  this.expectsPayload = expectsPayload;
@@ -100883,7 +100887,7 @@ upgrade: ${upgrade}\r
100883
100887
  * @returns
100884
100888
  */
100885
100889
  write(chunk) {
100886
- const { socket, request: request2, contentLength, client: client2, bytesWritten, expectsPayload, header } = this;
100890
+ const { socket, request: request2, contentLength: contentLength2, client: client2, bytesWritten, expectsPayload, header } = this;
100887
100891
  if (socket[kError]) {
100888
100892
  throw socket[kError];
100889
100893
  }
@@ -100894,7 +100898,7 @@ upgrade: ${upgrade}\r
100894
100898
  if (!len) {
100895
100899
  return true;
100896
100900
  }
100897
- if (contentLength !== null && bytesWritten + len > contentLength) {
100901
+ if (contentLength2 !== null && bytesWritten + len > contentLength2) {
100898
100902
  if (client2[kStrictContentLength]) {
100899
100903
  throw new RequestContentLengthMismatchError();
100900
100904
  }
@@ -100905,16 +100909,16 @@ upgrade: ${upgrade}\r
100905
100909
  if (!expectsPayload && request2.reset !== false) {
100906
100910
  socket[kReset] = true;
100907
100911
  }
100908
- if (contentLength === null) {
100912
+ if (contentLength2 === null) {
100909
100913
  socket.write(`${header}transfer-encoding: chunked\r
100910
100914
  `, "latin1");
100911
100915
  } else {
100912
- socket.write(`${header}content-length: ${contentLength}\r
100916
+ socket.write(`${header}content-length: ${contentLength2}\r
100913
100917
  \r
100914
100918
  `, "latin1");
100915
100919
  }
100916
100920
  }
100917
- if (contentLength === null) {
100921
+ if (contentLength2 === null) {
100918
100922
  socket.write(`\r
100919
100923
  ${len.toString(16)}\r
100920
100924
  `, "latin1");
@@ -100936,7 +100940,7 @@ ${len.toString(16)}\r
100936
100940
  * @returns {void}
100937
100941
  */
100938
100942
  end() {
100939
- const { socket, contentLength, client: client2, bytesWritten, expectsPayload, header, request: request2 } = this;
100943
+ const { socket, contentLength: contentLength2, client: client2, bytesWritten, expectsPayload, header, request: request2 } = this;
100940
100944
  request2.onRequestSent();
100941
100945
  socket[kWriting] = false;
100942
100946
  if (socket[kError]) {
@@ -100954,10 +100958,10 @@ ${len.toString(16)}\r
100954
100958
  socket.write(`${header}\r
100955
100959
  `, "latin1");
100956
100960
  }
100957
- } else if (contentLength === null) {
100961
+ } else if (contentLength2 === null) {
100958
100962
  socket.write("\r\n0\r\n\r\n", "latin1");
100959
100963
  }
100960
- if (contentLength !== null && bytesWritten !== contentLength) {
100964
+ if (contentLength2 !== null && bytesWritten !== contentLength2) {
100961
100965
  if (client2[kStrictContentLength]) {
100962
100966
  throw new RequestContentLengthMismatchError();
100963
100967
  } else {
@@ -101410,30 +101414,30 @@ function requireClientH2() {
101410
101414
  if (body2 && typeof body2.read === "function") {
101411
101415
  body2.read(0);
101412
101416
  }
101413
- let contentLength = util2.bodyLength(body2);
101417
+ let contentLength2 = util2.bodyLength(body2);
101414
101418
  if (util2.isFormDataLike(body2)) {
101415
101419
  extractBody ?? (extractBody = requireBody().extractBody);
101416
101420
  const [bodyStream, contentType] = extractBody(body2);
101417
101421
  headers2["content-type"] = contentType;
101418
101422
  body2 = bodyStream.stream;
101419
- contentLength = bodyStream.length;
101423
+ contentLength2 = bodyStream.length;
101420
101424
  }
101421
- if (contentLength == null) {
101422
- contentLength = request2.contentLength;
101425
+ if (contentLength2 == null) {
101426
+ contentLength2 = request2.contentLength;
101423
101427
  }
101424
101428
  if (!expectsPayload) {
101425
- contentLength = null;
101429
+ contentLength2 = null;
101426
101430
  }
101427
- if (shouldSendContentLength(method) && contentLength > 0 && request2.contentLength != null && request2.contentLength !== contentLength) {
101431
+ if (shouldSendContentLength(method) && contentLength2 > 0 && request2.contentLength != null && request2.contentLength !== contentLength2) {
101428
101432
  if (client2[kStrictContentLength]) {
101429
101433
  util2.errorRequest(client2, request2, new RequestContentLengthMismatchError());
101430
101434
  return false;
101431
101435
  }
101432
101436
  process.emitWarning(new RequestContentLengthMismatchError());
101433
101437
  }
101434
- if (contentLength != null) {
101435
- assert2(body2 || contentLength === 0, "no body must not have content length");
101436
- headers2[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`;
101438
+ if (contentLength2 != null) {
101439
+ assert2(body2 || contentLength2 === 0, "no body must not have content length");
101440
+ headers2[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength2}`;
101437
101441
  }
101438
101442
  session.ref();
101439
101443
  if (channels.sendHeaders.hasSubscribers) {
@@ -101532,7 +101536,7 @@ function requireClientH2() {
101532
101536
  });
101533
101537
  return true;
101534
101538
  function writeBodyH2() {
101535
- if (!body2 || contentLength === 0) {
101539
+ if (!body2 || contentLength2 === 0) {
101536
101540
  writeBuffer2(
101537
101541
  abort,
101538
101542
  stream,
@@ -101540,7 +101544,7 @@ function requireClientH2() {
101540
101544
  client2,
101541
101545
  request2,
101542
101546
  client2[kSocket],
101543
- contentLength,
101547
+ contentLength2,
101544
101548
  expectsPayload
101545
101549
  );
101546
101550
  } else if (util2.isBuffer(body2)) {
@@ -101551,7 +101555,7 @@ function requireClientH2() {
101551
101555
  client2,
101552
101556
  request2,
101553
101557
  client2[kSocket],
101554
- contentLength,
101558
+ contentLength2,
101555
101559
  expectsPayload
101556
101560
  );
101557
101561
  } else if (util2.isBlobLike(body2)) {
@@ -101563,7 +101567,7 @@ function requireClientH2() {
101563
101567
  client2,
101564
101568
  request2,
101565
101569
  client2[kSocket],
101566
- contentLength,
101570
+ contentLength2,
101567
101571
  expectsPayload
101568
101572
  );
101569
101573
  } else {
@@ -101574,7 +101578,7 @@ function requireClientH2() {
101574
101578
  client2,
101575
101579
  request2,
101576
101580
  client2[kSocket],
101577
- contentLength,
101581
+ contentLength2,
101578
101582
  expectsPayload
101579
101583
  );
101580
101584
  }
@@ -101587,7 +101591,7 @@ function requireClientH2() {
101587
101591
  body2,
101588
101592
  client2,
101589
101593
  request2,
101590
- contentLength
101594
+ contentLength2
101591
101595
  );
101592
101596
  } else if (util2.isIterable(body2)) {
101593
101597
  writeIterable(
@@ -101597,7 +101601,7 @@ function requireClientH2() {
101597
101601
  client2,
101598
101602
  request2,
101599
101603
  client2[kSocket],
101600
- contentLength,
101604
+ contentLength2,
101601
101605
  expectsPayload
101602
101606
  );
101603
101607
  } else {
@@ -101605,10 +101609,10 @@ function requireClientH2() {
101605
101609
  }
101606
101610
  }
101607
101611
  }
101608
- function writeBuffer2(abort, h2stream, body2, client2, request2, socket, contentLength, expectsPayload) {
101612
+ function writeBuffer2(abort, h2stream, body2, client2, request2, socket, contentLength2, expectsPayload) {
101609
101613
  try {
101610
101614
  if (body2 != null && util2.isBuffer(body2)) {
101611
- assert2(contentLength === body2.byteLength, "buffer body must have content length");
101615
+ assert2(contentLength2 === body2.byteLength, "buffer body must have content length");
101612
101616
  h2stream.cork();
101613
101617
  h2stream.write(body2);
101614
101618
  h2stream.uncork();
@@ -101624,8 +101628,8 @@ function requireClientH2() {
101624
101628
  abort(error2);
101625
101629
  }
101626
101630
  }
101627
- function writeStream(abort, socket, expectsPayload, h2stream, body2, client2, request2, contentLength) {
101628
- assert2(contentLength !== 0 || client2[kRunning] === 0, "stream body cannot be pipelined");
101631
+ function writeStream(abort, socket, expectsPayload, h2stream, body2, client2, request2, contentLength2) {
101632
+ assert2(contentLength2 !== 0 || client2[kRunning] === 0, "stream body cannot be pipelined");
101629
101633
  const pipe2 = pipeline(
101630
101634
  body2,
101631
101635
  h2stream,
@@ -101648,10 +101652,10 @@ function requireClientH2() {
101648
101652
  request2.onBodySent(chunk);
101649
101653
  }
101650
101654
  }
101651
- async function writeBlob(abort, h2stream, body2, client2, request2, socket, contentLength, expectsPayload) {
101652
- assert2(contentLength === body2.size, "blob body must have content length");
101655
+ async function writeBlob(abort, h2stream, body2, client2, request2, socket, contentLength2, expectsPayload) {
101656
+ assert2(contentLength2 === body2.size, "blob body must have content length");
101653
101657
  try {
101654
- if (contentLength != null && contentLength !== body2.size) {
101658
+ if (contentLength2 != null && contentLength2 !== body2.size) {
101655
101659
  throw new RequestContentLengthMismatchError();
101656
101660
  }
101657
101661
  const buffer2 = Buffer.from(await body2.arrayBuffer());
@@ -101669,8 +101673,8 @@ function requireClientH2() {
101669
101673
  abort(err);
101670
101674
  }
101671
101675
  }
101672
- async function writeIterable(abort, h2stream, body2, client2, request2, socket, contentLength, expectsPayload) {
101673
- assert2(contentLength !== 0 || client2[kRunning] === 0, "iterator body cannot be pipelined");
101676
+ async function writeIterable(abort, h2stream, body2, client2, request2, socket, contentLength2, expectsPayload) {
101677
+ assert2(contentLength2 !== 0 || client2[kRunning] === 0, "iterator body cannot be pipelined");
101674
101678
  let callback = null;
101675
101679
  function onDrain() {
101676
101680
  if (callback) {
@@ -104310,8 +104314,8 @@ function requireRetryHandler() {
104310
104314
  this.end = end;
104311
104315
  }
104312
104316
  if (this.end == null) {
104313
- const contentLength = headers2["content-length"];
104314
- this.end = contentLength != null ? Number(contentLength) - 1 : null;
104317
+ const contentLength2 = headers2["content-length"];
104318
+ this.end = contentLength2 != null ? Number(contentLength2) - 1 : null;
104315
104319
  }
104316
104320
  assert2(Number.isFinite(this.start));
104317
104321
  assert2(
@@ -104527,7 +104531,7 @@ function requireReadable() {
104527
104531
  resume,
104528
104532
  abort,
104529
104533
  contentType = "",
104530
- contentLength,
104534
+ contentLength: contentLength2,
104531
104535
  highWaterMark = 64 * 1024
104532
104536
  // Same as nodejs fs streams.
104533
104537
  }) {
@@ -104543,7 +104547,7 @@ function requireReadable() {
104543
104547
  this[kBody] = null;
104544
104548
  this[kUsed] = false;
104545
104549
  this[kContentType] = contentType;
104546
- this[kContentLength] = Number.isFinite(contentLength) ? contentLength : null;
104550
+ this[kContentLength] = Number.isFinite(contentLength2) ? contentLength2 : null;
104547
104551
  this[kReading] = false;
104548
104552
  }
104549
104553
  /**
@@ -104983,12 +104987,12 @@ function requireApiRequest() {
104983
104987
  }
104984
104988
  const parsedHeaders = responseHeaders === "raw" ? util2.parseHeaders(rawHeaders) : headers2;
104985
104989
  const contentType = parsedHeaders["content-type"];
104986
- const contentLength = parsedHeaders["content-length"];
104990
+ const contentLength2 = parsedHeaders["content-length"];
104987
104991
  const res = new Readable({
104988
104992
  resume,
104989
104993
  abort,
104990
104994
  contentType,
104991
- contentLength: this.method !== "HEAD" && contentLength ? Number(contentLength) : null,
104995
+ contentLength: this.method !== "HEAD" && contentLength2 ? Number(contentLength2) : null,
104992
104996
  highWaterMark
104993
104997
  });
104994
104998
  if (this.removeAbortListener) {
@@ -106208,8 +106212,8 @@ function requireMockInterceptor() {
106208
106212
  }
106209
106213
  createMockScopeDispatchData({ statusCode, data, responseOptions }) {
106210
106214
  const responseData = getResponseData(data);
106211
- const contentLength = this[kContentLength] ? { "content-length": responseData.length } : {};
106212
- const headers2 = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers };
106215
+ const contentLength2 = this[kContentLength] ? { "content-length": responseData.length } : {};
106216
+ const headers2 = { ...this[kDefaultHeaders], ...contentLength2, ...responseOptions.headers };
106213
106217
  const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers };
106214
106218
  return { statusCode, data, headers: headers2, trailers };
106215
106219
  }
@@ -108052,10 +108056,10 @@ function requireDump() {
108052
108056
  return super.onRequestStart(controller, context);
108053
108057
  }
108054
108058
  onResponseStart(controller, statusCode, headers2, statusMessage) {
108055
- const contentLength = headers2["content-length"];
108056
- if (contentLength != null && contentLength > __privateGet(this, _maxSize2)) {
108059
+ const contentLength2 = headers2["content-length"];
108060
+ if (contentLength2 != null && contentLength2 > __privateGet(this, _maxSize2)) {
108057
108061
  throw new RequestAbortedError(
108058
- `Response size (${contentLength}) larger than maxSize (${__privateGet(this, _maxSize2)})`
108062
+ `Response size (${contentLength2}) larger than maxSize (${__privateGet(this, _maxSize2)})`
108059
108063
  );
108060
108064
  }
108061
108065
  if (this.aborted === true) {
@@ -113874,18 +113878,18 @@ function requireFetch() {
113874
113878
  httpFetchParams.request = httpRequest;
113875
113879
  }
113876
113880
  const includeCredentials = request2.credentials === "include" || request2.credentials === "same-origin" && request2.responseTainting === "basic";
113877
- const contentLength = httpRequest.body ? httpRequest.body.length : null;
113881
+ const contentLength2 = httpRequest.body ? httpRequest.body.length : null;
113878
113882
  let contentLengthHeaderValue = null;
113879
113883
  if (httpRequest.body == null && ["POST", "PUT"].includes(httpRequest.method)) {
113880
113884
  contentLengthHeaderValue = "0";
113881
113885
  }
113882
- if (contentLength != null) {
113883
- contentLengthHeaderValue = isomorphicEncode(`${contentLength}`);
113886
+ if (contentLength2 != null) {
113887
+ contentLengthHeaderValue = isomorphicEncode(`${contentLength2}`);
113884
113888
  }
113885
113889
  if (contentLengthHeaderValue != null && !httpRequest.headersList.contains("content-length", true)) {
113886
113890
  httpRequest.headersList.append("content-length", contentLengthHeaderValue, true);
113887
113891
  }
113888
- if (contentLength != null && httpRequest.keepalive) ;
113892
+ if (contentLength2 != null && httpRequest.keepalive) ;
113889
113893
  if (webidl.is.URL(httpRequest.referrer)) {
113890
113894
  httpRequest.headersList.append("referer", isomorphicEncode(httpRequest.referrer.href), true);
113891
113895
  }
@@ -119017,6 +119021,12 @@ async function handleLegacyEvent(basedir, runId, data, currentRun, params) {
119017
119021
  throw new Error(`Event type '${data.eventType}' not supported for legacy runs (specVersion: ${currentRun.specVersion || "undefined"}). Please upgrade 'workflow' package.`);
119018
119022
  }
119019
119023
  }
119024
+ const DEFAULT_MAX_EVENTS_PER_RUN = 25e3;
119025
+ function getMaxEventsPerRun() {
119026
+ const raw2 = process.env.WORKFLOW_MAX_EVENTS;
119027
+ const parsed = raw2 !== void 0 ? Number(raw2) : Number.NaN;
119028
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_MAX_EVENTS_PER_RUN;
119029
+ }
119020
119030
  const HookTokenClaimSchema = object$1({
119021
119031
  // The token-claim writer below has always persisted `hookId`, but
119022
119032
  // this read schema previously omitted it, which is the bug fixed
@@ -119248,7 +119258,8 @@ function createEventsStorage(basedir, tag) {
119248
119258
  const resolveData2 = (params == null ? void 0 : params.resolveData) ?? DEFAULT_RESOLVE_DATA_OPTION$1;
119249
119259
  return {
119250
119260
  event: stripEventDataRefs(event2, resolveData2),
119251
- run: currentRun
119261
+ run: currentRun,
119262
+ ...currentRun ? { maxEvents: getMaxEventsPerRun() } : {}
119252
119263
  };
119253
119264
  }
119254
119265
  if (data.eventType === "run_started") {
@@ -119331,7 +119342,7 @@ function createEventsStorage(basedir, tag) {
119331
119342
  } else if (data.eventType === "run_started") {
119332
119343
  if (currentRun) {
119333
119344
  if (currentRun.status === "running") {
119334
- return { run: currentRun };
119345
+ return { run: currentRun, maxEvents: getMaxEventsPerRun() };
119335
119346
  }
119336
119347
  run2 = {
119337
119348
  runId: currentRun.runId,
@@ -119714,7 +119725,9 @@ function createEventsStorage(basedir, tag) {
119714
119725
  wait: wait2,
119715
119726
  events: events2,
119716
119727
  cursor,
119717
- hasMore
119728
+ hasMore,
119729
+ // Per-run event ceiling (mirrors the Vercel World).
119730
+ ...run2 ? { maxEvents: getMaxEventsPerRun() } : {}
119718
119731
  };
119719
119732
  }
119720
119733
  },
@@ -120303,7 +120316,7 @@ function createLocalWorld(args) {
120303
120316
  const basedir = mergedConfig.dataDir;
120304
120317
  const hooksDir = path$3.join(basedir, "hooks");
120305
120318
  const taggedHookFiles = await listTaggedFiles(hooksDir, tag);
120306
- const { HookSchema: HookSchema2 } = await import("./index-D86iFXiQ.js");
120319
+ const { HookSchema: HookSchema2 } = await import("./index-BS2bBoaA.js");
120307
120320
  await Promise.all(taggedHookFiles.map(async (hookFile) => {
120308
120321
  const hook = await readJSON(path$3.join(hooksDir, hookFile), HookSchema2);
120309
120322
  if (hook == null ? void 0 : hook.token) {
@@ -120338,6 +120351,254 @@ function createLocalWorld(args) {
120338
120351
  }
120339
120352
  };
120340
120353
  }
120354
+ let _dispatcher;
120355
+ let _streamDispatcher;
120356
+ let _streamCloseDispatcher;
120357
+ const DEFAULT_HEADERS_TIMEOUT_MS = 3e4;
120358
+ const DEFAULT_BODY_TIMEOUT_MS = 3e4;
120359
+ function envTimeoutMs(name2, fallback) {
120360
+ const raw2 = process.env[name2];
120361
+ if (raw2 === void 0 || raw2 === "")
120362
+ return fallback;
120363
+ const parsed = Number.parseInt(raw2, 10);
120364
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
120365
+ }
120366
+ const RETRY_ERROR_CODES = [
120367
+ "ECONNRESET",
120368
+ "ECONNREFUSED",
120369
+ "ENOTFOUND",
120370
+ "ENETDOWN",
120371
+ "ENETUNREACH",
120372
+ "EHOSTDOWN",
120373
+ "EHOSTUNREACH",
120374
+ "EPIPE",
120375
+ "UND_ERR_SOCKET",
120376
+ "UND_ERR_HEADERS_TIMEOUT",
120377
+ "UND_ERR_BODY_TIMEOUT"
120378
+ ];
120379
+ const MAX_RETRIES = 2;
120380
+ function getBaseAgentOptions() {
120381
+ return {
120382
+ connections: 8,
120383
+ keepAliveTimeout: 1e4,
120384
+ headersTimeout: envTimeoutMs("WORKFLOW_VERCEL_HEADERS_TIMEOUT_MS", DEFAULT_HEADERS_TIMEOUT_MS),
120385
+ bodyTimeout: envTimeoutMs("WORKFLOW_VERCEL_BODY_TIMEOUT_MS", DEFAULT_BODY_TIMEOUT_MS)
120386
+ };
120387
+ }
120388
+ const H2_MAX_IN_FLIGHT_STREAMS = 100;
120389
+ const H2_STREAM_WINDOW_BYTES = 4 * 1024 * 1024;
120390
+ const H2_CONNECTION_WINDOW_BYTES = 16 * 1024 * 1024;
120391
+ function getAgentOptions() {
120392
+ return {
120393
+ ...getBaseAgentOptions(),
120394
+ allowH2: false,
120395
+ // HTTP/1.1 pipelining is disabled (pipelining: 1) because it causes
120396
+ // head-of-line blocking that deadlocks the webhook respondWith mechanism.
120397
+ pipelining: 1
120398
+ };
120399
+ }
120400
+ function getEventsAgentOptions() {
120401
+ return {
120402
+ ...getBaseAgentOptions(),
120403
+ allowH2: true,
120404
+ pipelining: H2_MAX_IN_FLIGHT_STREAMS,
120405
+ initialWindowSize: H2_STREAM_WINDOW_BYTES,
120406
+ connectionWindowSize: H2_CONNECTION_WINDOW_BYTES
120407
+ };
120408
+ }
120409
+ function getEventsAgentOptionsNoH2() {
120410
+ return {
120411
+ ...getBaseAgentOptions(),
120412
+ allowH2: false,
120413
+ pipelining: 1
120414
+ };
120415
+ }
120416
+ function getStreamAgentOptions() {
120417
+ return {
120418
+ ...getBaseAgentOptions(),
120419
+ allowH2: true,
120420
+ pipelining: 1
120421
+ };
120422
+ }
120423
+ function getRetryAgentOptions() {
120424
+ return {
120425
+ // Observe Retry-After header if received
120426
+ retryAfter: true,
120427
+ // Retry 5xx in-process (genuine transient blips recover fast), but NOT
120428
+ // 429. The Vercel firewall issues a challenge as a 429: our
120429
+ // server-to-server client cannot solve a challenge, so in-process
120430
+ // retries just re-trigger it ~5× per request and amplify load against
120431
+ // an already-overloaded firewall during an incident. Letting 429 pass
120432
+ // through surfaces it immediately to makeRequest — which maps it to a
120433
+ // ThrottleError carrying the `x-vercel-mitigated` / `x-vercel-id`
120434
+ // headers — and the queue does the (backed-off) retry instead.
120435
+ // (undici default is [500, 502, 503, 504, 429].)
120436
+ statusCodes: [500, 502, 503, 504],
120437
+ errorCodes: RETRY_ERROR_CODES,
120438
+ maxRetries: MAX_RETRIES
120439
+ };
120440
+ }
120441
+ const STREAM_RETRY_OPTIONS = {
120442
+ retryAfter: true,
120443
+ methods: ["PUT"],
120444
+ statusCodes: [429]
120445
+ };
120446
+ const STREAM_CLOSE_RETRY_OPTIONS = {
120447
+ retryAfter: true,
120448
+ methods: ["PUT"],
120449
+ statusCodes: [429, 500, 502, 503, 504]
120450
+ };
120451
+ const H2_REBUFFER_MAX_BYTES = 1 << 20;
120452
+ function h2EventsEnabled() {
120453
+ return process.env.WORKFLOW_H2_MULTIPLEX !== "0";
120454
+ }
120455
+ function contentLength(headers2) {
120456
+ if (!headers2 || typeof headers2 !== "object" || Array.isArray(headers2)) {
120457
+ return Number.NaN;
120458
+ }
120459
+ const record2 = headers2;
120460
+ const raw2 = record2["content-length"] ?? record2["Content-Length"];
120461
+ return typeof raw2 === "string" || typeof raw2 === "number" ? Number(raw2) : Number.NaN;
120462
+ }
120463
+ function h2MultiplexInterceptor(dispatch2) {
120464
+ return (opts, handler) => {
120465
+ const body2 = opts.body;
120466
+ const isAsyncIterable = !!body2 && typeof body2 !== "string" && !Buffer.isBuffer(body2) && typeof body2[Symbol.asyncIterator] === "function";
120467
+ const length = contentLength(opts.headers);
120468
+ if (!isAsyncIterable || !(length >= 0) || length > H2_REBUFFER_MAX_BYTES) {
120469
+ return dispatch2({ ...opts, idempotent: true }, handler);
120470
+ }
120471
+ void (async () => {
120472
+ var _a3;
120473
+ try {
120474
+ const chunks = [];
120475
+ for await (const chunk of body2) {
120476
+ chunks.push(Buffer.from(chunk));
120477
+ }
120478
+ dispatch2({ ...opts, body: Buffer.concat(chunks), idempotent: true }, handler);
120479
+ } catch (error2) {
120480
+ (_a3 = handler.onError) == null ? void 0 : _a3.call(handler, error2);
120481
+ }
120482
+ })();
120483
+ return true;
120484
+ };
120485
+ }
120486
+ const EVENTS_RECYCLE_AFTER_CONSECUTIVE_FAILURES = 3;
120487
+ const RECYCLE_MIN_INTERVAL_MS = 5e3;
120488
+ const RETIRED_CLOSE_DELAY_MS = 5e3;
120489
+ const RETIRED_DESTROY_DELAY_MS = 6e4;
120490
+ const RECYCLABLE_ERROR_CODES = /* @__PURE__ */ new Set([
120491
+ // Covers H2 stream timeout, frameError and GOAWAY (undici InformationalError).
120492
+ "UND_ERR_INFO",
120493
+ "UND_ERR_HEADERS_TIMEOUT",
120494
+ "UND_ERR_BODY_TIMEOUT"
120495
+ ]);
120496
+ const MAX_CAUSE_DEPTH = 8;
120497
+ function isRecyclableTransportError(error2) {
120498
+ let current = error2;
120499
+ for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {
120500
+ const code2 = current.code;
120501
+ if (typeof code2 === "string" && RECYCLABLE_ERROR_CODES.has(code2)) {
120502
+ return true;
120503
+ }
120504
+ current = current.cause;
120505
+ }
120506
+ return false;
120507
+ }
120508
+ function createDispatcherRecycler(factory, label) {
120509
+ let current;
120510
+ let consecutiveFailures = 0;
120511
+ let lastRecycledAt = 0;
120512
+ function retire(stale) {
120513
+ var _a3, _b2;
120514
+ const closeTimer = setTimeout(() => {
120515
+ var _a4;
120516
+ void Promise.resolve((_a4 = stale.close) == null ? void 0 : _a4.call(stale)).catch(() => void 0);
120517
+ }, RETIRED_CLOSE_DELAY_MS);
120518
+ const destroyTimer = setTimeout(() => {
120519
+ var _a4;
120520
+ void Promise.resolve((_a4 = stale.destroy) == null ? void 0 : _a4.call(stale)).catch(() => void 0);
120521
+ }, RETIRED_DESTROY_DELAY_MS);
120522
+ (_a3 = closeTimer.unref) == null ? void 0 : _a3.call(closeTimer);
120523
+ (_b2 = destroyTimer.unref) == null ? void 0 : _b2.call(destroyTimer);
120524
+ }
120525
+ return {
120526
+ get() {
120527
+ current ?? (current = factory());
120528
+ return current;
120529
+ },
120530
+ note(dispatcher2, error2) {
120531
+ if (!current || dispatcher2 !== current)
120532
+ return;
120533
+ if (error2 === void 0) {
120534
+ consecutiveFailures = 0;
120535
+ return;
120536
+ }
120537
+ if (!isRecyclableTransportError(error2))
120538
+ return;
120539
+ consecutiveFailures++;
120540
+ if (consecutiveFailures < EVENTS_RECYCLE_AFTER_CONSECUTIVE_FAILURES) {
120541
+ return;
120542
+ }
120543
+ const now2 = Date.now();
120544
+ if (now2 - lastRecycledAt < RECYCLE_MIN_INTERVAL_MS)
120545
+ return;
120546
+ lastRecycledAt = now2;
120547
+ consecutiveFailures = 0;
120548
+ const stale = current;
120549
+ current = void 0;
120550
+ console.warn(`[workflow] ${label}: rebuilding connection pool after ${EVENTS_RECYCLE_AFTER_CONSECUTIVE_FAILURES} consecutive transport failures`);
120551
+ retire(stale);
120552
+ }
120553
+ };
120554
+ }
120555
+ const eventsRecycler = createDispatcherRecycler(() => createEventsDispatcher(), "events transport");
120556
+ function noteEventsTransportOutcome(dispatcher2, error2) {
120557
+ eventsRecycler.note(dispatcher2, error2);
120558
+ }
120559
+ function getDispatcher(config2) {
120560
+ return (config2 == null ? void 0 : config2.dispatcher) ?? getDefaultDispatcher();
120561
+ }
120562
+ function getEventsDispatcher(config2) {
120563
+ return (config2 == null ? void 0 : config2.dispatcher) ?? eventsRecycler.get();
120564
+ }
120565
+ function getStreamDispatcher(config2) {
120566
+ return (config2 == null ? void 0 : config2.dispatcher) ?? getDefaultStreamDispatcher();
120567
+ }
120568
+ function getStreamCloseDispatcher(config2) {
120569
+ return (config2 == null ? void 0 : config2.dispatcher) ?? getDefaultStreamCloseDispatcher();
120570
+ }
120571
+ function createEventsDispatcher(agentOverrides) {
120572
+ const h2 = h2EventsEnabled();
120573
+ const agent2 = new undiciExports.RetryAgent(new undiciExports.Agent({
120574
+ ...h2 ? getEventsAgentOptions() : getEventsAgentOptionsNoH2(),
120575
+ ...agentOverrides
120576
+ }), getRetryAgentOptions());
120577
+ if (!h2) {
120578
+ return agent2;
120579
+ }
120580
+ return withBoundLifecycle(agent2, agent2.compose(h2MultiplexInterceptor));
120581
+ }
120582
+ function withBoundLifecycle(agent2, composed) {
120583
+ return new Proxy(composed, {
120584
+ get: (target2, key) => key === "close" || key === "destroy" ? agent2[key].bind(agent2) : target2[key]
120585
+ });
120586
+ }
120587
+ function createStreamDispatcher(retryOptions, agentOverrides) {
120588
+ return new undiciExports.RetryAgent(new undiciExports.Agent({ ...getStreamAgentOptions(), ...agentOverrides }), retryOptions);
120589
+ }
120590
+ function getDefaultDispatcher() {
120591
+ _dispatcher ?? (_dispatcher = new undiciExports.RetryAgent(new undiciExports.Agent(getAgentOptions()), getRetryAgentOptions()));
120592
+ return _dispatcher;
120593
+ }
120594
+ function getDefaultStreamDispatcher() {
120595
+ _streamDispatcher ?? (_streamDispatcher = createStreamDispatcher(STREAM_RETRY_OPTIONS));
120596
+ return _streamDispatcher;
120597
+ }
120598
+ function getDefaultStreamCloseDispatcher() {
120599
+ _streamCloseDispatcher ?? (_streamCloseDispatcher = createStreamDispatcher(STREAM_CLOSE_RETRY_OPTIONS));
120600
+ return _streamCloseDispatcher;
120601
+ }
120341
120602
  var getContext_1;
120342
120603
  var hasRequiredGetContext;
120343
120604
  function requireGetContext() {
@@ -120456,8 +120717,8 @@ function requireGetVercelOidcToken() {
120456
120717
  }
120457
120718
  try {
120458
120719
  const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
120459
- await import("./token-util-BCX_82dS.js").then((n) => n.t),
120460
- await import("./token-wXB5G-Q6.js").then((n) => n.t)
120720
+ await import("./token-util-CjU-0VfE.js").then((n) => n.t),
120721
+ await import("./token--5hm9Tcb.js").then((n) => n.t)
120461
120722
  ]);
120462
120723
  if (!token || isExpired(getTokenPayload(token), options == null ? void 0 : options.expirationBufferMs)) {
120463
120724
  await refreshToken(options);
@@ -121020,69 +121281,222 @@ function requireDist() {
121020
121281
  return dist;
121021
121282
  }
121022
121283
  var distExports = requireDist();
121023
- let _dispatcher;
121024
- const DEFAULT_HEADERS_TIMEOUT_MS = 3e4;
121025
- const DEFAULT_BODY_TIMEOUT_MS = 3e4;
121026
- function envTimeoutMs(name2, fallback) {
121027
- const raw2 = process.env[name2];
121028
- if (raw2 === void 0 || raw2 === "")
121029
- return fallback;
121030
- const parsed = Number.parseInt(raw2, 10);
121031
- return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
121284
+ let otelApiPromise = null;
121285
+ async function getOtelApi() {
121286
+ if (!otelApiPromise) {
121287
+ otelApiPromise = import("./index-hBO56emR.js").catch(() => null);
121288
+ }
121289
+ return otelApiPromise;
121032
121290
  }
121033
- const RETRY_ERROR_CODES = [
121034
- "ECONNRESET",
121035
- "ECONNREFUSED",
121036
- "ENOTFOUND",
121037
- "ENETDOWN",
121038
- "ENETUNREACH",
121039
- "EHOSTDOWN",
121040
- "EHOSTUNREACH",
121041
- "EPIPE",
121042
- "UND_ERR_SOCKET",
121043
- "UND_ERR_HEADERS_TIMEOUT",
121044
- "UND_ERR_BODY_TIMEOUT"
121291
+ let tracerPromise = null;
121292
+ async function getTracer() {
121293
+ if (!tracerPromise) {
121294
+ tracerPromise = getOtelApi().then((otel) => otel ? otel.trace.getTracer("workflow") : null);
121295
+ }
121296
+ return tracerPromise;
121297
+ }
121298
+ async function trace(spanName2, ...args) {
121299
+ const [tracer, otel] = await Promise.all([getTracer(), getOtelApi()]);
121300
+ const { fn: fn2, opts } = typeof args[0] === "function" ? { fn: args[0], opts: {} } : { fn: args[1], opts: args[0] };
121301
+ if (!fn2)
121302
+ throw new Error("Function to trace must be provided");
121303
+ if (!tracer || !otel) {
121304
+ return await fn2();
121305
+ }
121306
+ return tracer.startActiveSpan(spanName2, opts, async (span) => {
121307
+ try {
121308
+ const result = await fn2(span);
121309
+ span.setStatus({ code: otel.SpanStatusCode.OK });
121310
+ return result;
121311
+ } catch (e) {
121312
+ span.setStatus({
121313
+ code: otel.SpanStatusCode.ERROR,
121314
+ message: e.message
121315
+ });
121316
+ throw e;
121317
+ } finally {
121318
+ span.end();
121319
+ }
121320
+ });
121321
+ }
121322
+ async function getSpanKind(field) {
121323
+ const otel = await getOtelApi();
121324
+ if (!otel)
121325
+ return void 0;
121326
+ return otel.SpanKind[field];
121327
+ }
121328
+ async function injectTraceContextIntoHeaders(headers2) {
121329
+ const otel = await getOtelApi();
121330
+ if (!otel)
121331
+ return;
121332
+ const carrier = {};
121333
+ otel.propagation.inject(otel.context.active(), carrier);
121334
+ for (const [key, value] of Object.entries(carrier)) {
121335
+ headers2.set(key, value);
121336
+ }
121337
+ }
121338
+ function SemanticConvention(...names) {
121339
+ return (value) => Object.fromEntries(names.map((name2) => [name2, value]));
121340
+ }
121341
+ const HttpRequestMethod = SemanticConvention("http.request.method");
121342
+ const UrlFull = SemanticConvention("url.full");
121343
+ const ServerAddress = SemanticConvention("server.address");
121344
+ const ServerPort = SemanticConvention("server.port");
121345
+ const HttpResponseStatusCode = SemanticConvention("http.response.status_code");
121346
+ const ErrorType = SemanticConvention("error.type");
121347
+ const WorldParseFormat = SemanticConvention("workflow.world.parse.format");
121348
+ const PeerService = SemanticConvention("peer.service");
121349
+ const RpcSystem = SemanticConvention("rpc.system");
121350
+ const RpcService = SemanticConvention("rpc.service");
121351
+ const RpcMethod = SemanticConvention("rpc.method");
121352
+ const WorkflowRunId = SemanticConvention("workflow.run.id");
121353
+ const StepId = SemanticConvention("step.id");
121354
+ const REQUEST_TIMEOUT_MS = 6e4;
121355
+ const HTTP_DEBUG_ENABLED = typeof process !== "undefined" && typeof process.env.DEBUG === "string" && (process.env.DEBUG.includes("workflow:") || process.env.DEBUG === "*");
121356
+ const DIAGNOSTIC_HEADERS = [
121357
+ "x-vercel-id",
121358
+ "x-vercel-error",
121359
+ "x-vercel-mitigated"
121045
121360
  ];
121046
- const MAX_RETRIES = 2;
121047
- function getAgentOptions() {
121048
- return {
121049
- connections: 8,
121050
- keepAliveTimeout: 1e4,
121051
- // H2 is specifically incompatible with SvelteKit on Vercel prod. Everything else
121052
- // runs fine.
121053
- // TODO: Investigate/fix the failure on SvelteKit so we can re-enable H2.
121054
- allowH2: false,
121055
- // HTTP/1.1 pipelining is disabled (pipelining: 1) because it causes
121056
- // head-of-line blocking that deadlocks the webhook respondWith mechanism.
121057
- pipelining: 1,
121058
- headersTimeout: envTimeoutMs("WORKFLOW_VERCEL_HEADERS_TIMEOUT_MS", DEFAULT_HEADERS_TIMEOUT_MS),
121059
- bodyTimeout: envTimeoutMs("WORKFLOW_VERCEL_BODY_TIMEOUT_MS", DEFAULT_BODY_TIMEOUT_MS)
121060
- };
121361
+ function getVercelDiagnostics(headers2) {
121362
+ return DIAGNOSTIC_HEADERS.flatMap((header) => {
121363
+ const value = headers2.get(header);
121364
+ return value ? [`${header}=${value}`] : [];
121365
+ });
121061
121366
  }
121062
- function getDispatcher(config2) {
121063
- return (config2 == null ? void 0 : config2.dispatcher) ?? getDefaultDispatcher();
121367
+ function formatVercelDiagnostics(headers2) {
121368
+ const diagnostics2 = getVercelDiagnostics(headers2);
121369
+ return diagnostics2.length > 0 ? ` (${diagnostics2.join("; ")})` : "";
121064
121370
  }
121065
- function getDefaultDispatcher() {
121066
- if (!_dispatcher) {
121067
- const retryOptions = {
121068
- // Observe Retry-After header if received
121069
- retryAfter: true,
121070
- // Retry 5xx in-process (genuine transient blips recover fast), but NOT
121071
- // 429. The Vercel firewall issues a challenge as a 429: our
121072
- // server-to-server client cannot solve a challenge, so in-process
121073
- // retries just re-trigger it ~5× per request and amplify load against
121074
- // an already-overloaded firewall during an incident. Letting 429 pass
121075
- // through surfaces it immediately to makeRequest which maps it to a
121076
- // ThrottleError carrying the `x-vercel-mitigated` / `x-vercel-id`
121077
- // headers and the queue does the (backed-off) retry instead.
121078
- // (undici default is [500, 502, 503, 504, 429].)
121079
- statusCodes: [500, 502, 503, 504],
121080
- errorCodes: RETRY_ERROR_CODES,
121081
- maxRetries: MAX_RETRIES
121371
+ function httpLog(method, label, response2, ms2) {
121372
+ if (!HTTP_DEBUG_ENABLED)
121373
+ return;
121374
+ const diagnostics2 = getVercelDiagnostics(response2.headers);
121375
+ const suffix = diagnostics2.length > 0 ? `; ${diagnostics2.join("; ")}` : "";
121376
+ console.debug(`[workflow:world-vercel:http] ${method} ${label} -> ${response2.status} (${ms2}ms${suffix})`);
121377
+ }
121378
+ function logCurlRepro(method, url2, headers2) {
121379
+ if (!process.env.DEBUG)
121380
+ return;
121381
+ const stringifiedHeaders = Array.from(headers2.entries()).filter(([key]) => key.toLowerCase() !== "authorization").map(([key, value]) => `-H "${key}: ${value}"`).join(" ");
121382
+ console.error(`Failed to fetch, reproduce with:
121383
+ curl -X ${method} ${stringifiedHeaders} "${url2}"`);
121384
+ }
121385
+ function parseRetryAfter(value) {
121386
+ if (!value)
121387
+ return void 0;
121388
+ const parsed = parseInt(value, 10);
121389
+ return Number.isNaN(parsed) ? void 0 : parsed;
121390
+ }
121391
+ function errorForResponse(status, message2, opts = {}) {
121392
+ const { retryAfter, code: code2, url: url2, mitigated } = opts;
121393
+ if (status === 409)
121394
+ return new EntityConflictError(message2);
121395
+ if (status === 410)
121396
+ return new RunExpiredError(message2);
121397
+ if (status === 412)
121398
+ return new PreconditionFailedError(message2, { retryAfter });
121399
+ if (status === 425)
121400
+ return new TooEarlyError(message2, { retryAfter });
121401
+ if (status === 429) {
121402
+ if (isFirewallChallenge429(status, mitigated)) {
121403
+ return new WorkflowWorldError(`${message2} (x-vercel-mitigated=challenge)`, {
121404
+ url: url2,
121405
+ status,
121406
+ code: "TRANSPORT",
121407
+ retryAfter
121408
+ });
121409
+ }
121410
+ return new ThrottleError(message2, { retryAfter });
121411
+ }
121412
+ return new WorkflowWorldError(message2, { url: url2, status, code: code2, retryAfter });
121413
+ }
121414
+ function isFirewallChallenge429(status, mitigated) {
121415
+ return status === 429 && mitigated === "challenge";
121416
+ }
121417
+ async function resolveVercelApiToken(opts) {
121418
+ return (opts == null ? void 0 : opts.token) ?? process.env.VERCEL_TOKEN ?? await distExports.getVercelOidcToken().catch(() => null);
121419
+ }
121420
+ function parseServer(url2) {
121421
+ try {
121422
+ const parsed = new URL(url2);
121423
+ return {
121424
+ serverAddress: parsed.hostname,
121425
+ serverPort: parsed.port ? parseInt(parsed.port, 10) : parsed.protocol === "https:" ? 443 : 80
121082
121426
  };
121083
- _dispatcher = new undiciExports.RetryAgent(new undiciExports.Agent(getAgentOptions()), retryOptions);
121427
+ } catch {
121428
+ return {};
121084
121429
  }
121085
- return _dispatcher;
121430
+ }
121431
+ function httpClientSpanAttributes(args) {
121432
+ const { method, url: url2, peerService } = args;
121433
+ const { serverAddress, serverPort } = parseServer(url2);
121434
+ return {
121435
+ ...HttpRequestMethod(method),
121436
+ ...UrlFull(url2),
121437
+ ...serverAddress ? ServerAddress(serverAddress) : {},
121438
+ ...serverPort ? ServerPort(serverPort) : {},
121439
+ ...PeerService(peerService),
121440
+ ...RpcSystem("http"),
121441
+ ...RpcService(peerService)
121442
+ };
121443
+ }
121444
+ async function instrumentedFetch(opts) {
121445
+ 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 } = opts;
121446
+ const label = logLabel ?? url2;
121447
+ return trace(`http ${method}`, { kind: await getSpanKind("CLIENT") }, async (span) => {
121448
+ var _a3, _b2, _c;
121449
+ span == null ? void 0 : span.setAttributes(httpClientSpanAttributes({ method, url: url2, peerService }));
121450
+ if (injectTraceContext)
121451
+ await injectTraceContextIntoHeaders(headers2);
121452
+ if (cacheBust)
121453
+ headers2.set("X-Request-Time", Date.now().toString());
121454
+ const timeoutSignal = timeoutMs != null ? AbortSignal.timeout(timeoutMs) : void 0;
121455
+ const signal = callerSignal && timeoutSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : callerSignal ?? timeoutSignal;
121456
+ const start2 = Date.now();
121457
+ let response2;
121458
+ try {
121459
+ response2 = await fetch(url2, {
121460
+ method,
121461
+ headers: headers2,
121462
+ body: body2,
121463
+ signal,
121464
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- undici dispatcher type doesn't match @types/node's RequestInit
121465
+ dispatcher: dispatcher2
121466
+ });
121467
+ } catch (error2) {
121468
+ const elapsed = Date.now() - start2;
121469
+ onTransportOutcome == null ? void 0 : onTransportOutcome(error2);
121470
+ if (error2 instanceof Error && (error2.name === "TimeoutError" || error2.name === "AbortError")) {
121471
+ const timeoutError = new WorkflowWorldError(`${method} ${label} timed out after ${elapsed}ms`, { url: url2, cause: error2 });
121472
+ span == null ? void 0 : span.setAttributes({ ...ErrorType("TIMEOUT") });
121473
+ (_a3 = span == null ? void 0 : span.recordException) == null ? void 0 : _a3.call(span, timeoutError);
121474
+ throw timeoutError;
121475
+ }
121476
+ throw error2;
121477
+ }
121478
+ const ms2 = Date.now() - start2;
121479
+ onTransportOutcome == null ? void 0 : onTransportOutcome();
121480
+ httpLog(method, label, response2, ms2);
121481
+ span == null ? void 0 : span.setAttributes({ ...HttpResponseStatusCode(response2.status) });
121482
+ if (!response2.ok) {
121483
+ span == null ? void 0 : span.setAttributes({ ...ErrorType(`HTTP ${response2.status}`) });
121484
+ logCurlRepro(method, url2, headers2);
121485
+ if (buildError) {
121486
+ const error3 = await buildError(response2);
121487
+ (_b2 = span == null ? void 0 : span.recordException) == null ? void 0 : _b2.call(span, error3);
121488
+ throw error3;
121489
+ }
121490
+ const text2 = await response2.text().catch(() => "");
121491
+ const error2 = errorForResponse(response2.status, `${method} ${label} -> HTTP ${response2.status}: ${response2.statusText}${text2 ? ` ${text2}` : ""}${formatVercelDiagnostics(response2.headers)}`, {
121492
+ url: url2,
121493
+ retryAfter: parseRetryAfter(response2.headers.get("Retry-After"))
121494
+ });
121495
+ (_c = span == null ? void 0 : span.recordException) == null ? void 0 : _c.call(span, error2);
121496
+ throw error2;
121497
+ }
121498
+ return response2;
121499
+ });
121086
121500
  }
121087
121501
  const KEY_BYTES = 32;
121088
121502
  async function deriveRunKey(deploymentKey, projectId, runId) {
@@ -121108,7 +121522,7 @@ async function deriveRunKey(deploymentKey, projectId, runId) {
121108
121522
  return new Uint8Array(derivedBits);
121109
121523
  }
121110
121524
  async function fetchRunKey(deploymentId, projectId, runId, options) {
121111
- const token = (options == null ? void 0 : options.token) ?? process.env.VERCEL_TOKEN ?? await distExports.getVercelOidcToken().catch(() => null);
121525
+ const token = await resolveVercelApiToken({ token: options == null ? void 0 : options.token });
121112
121526
  if (!token) {
121113
121527
  throw new Error("Cannot fetch run key: no OIDC token or VERCEL_TOKEN available");
121114
121528
  }
@@ -121116,23 +121530,25 @@ async function fetchRunKey(deploymentId, projectId, runId, options) {
121116
121530
  if (options == null ? void 0 : options.teamId) {
121117
121531
  params.set("teamId", options.teamId);
121118
121532
  }
121119
- const response2 = await fetch(`https://api.vercel.com/v1/workflow/run-key/${deploymentId}?${params}`, {
121533
+ const response2 = await instrumentedFetch({
121120
121534
  method: "GET",
121121
- headers: {
121122
- Authorization: `Bearer ${token}`
121123
- },
121124
- // @ts-expect-error -- undici dispatcher is accepted by Node.js fetch but not in @types/node's RequestInit
121125
- dispatcher: getDispatcher({ dispatcher: options == null ? void 0 : options.dispatcher })
121126
- });
121127
- if (!response2.ok) {
121128
- let body2;
121129
- try {
121130
- body2 = await response2.text();
121131
- } catch {
121132
- body2 = "<unable to read response body>";
121535
+ url: `https://api.vercel.com/v1/workflow/run-key/${deploymentId}?${params}`,
121536
+ headers: new Headers({ Authorization: `Bearer ${token}` }),
121537
+ dispatcher: getDispatcher({ dispatcher: options == null ? void 0 : options.dispatcher }),
121538
+ peerService: "vercel-api",
121539
+ // Preserve the prior no-timeout behavior for this Vercel-API call; the
121540
+ // shared RetryAgent still handles transient/5xx retries.
121541
+ timeoutMs: null,
121542
+ buildError: async (res) => {
121543
+ let body2;
121544
+ try {
121545
+ body2 = await res.text();
121546
+ } catch {
121547
+ body2 = "<unable to read response body>";
121548
+ }
121549
+ return new Error(`Failed to fetch run key for ${runId} (deployment ${deploymentId}): HTTP ${res.status} ${res.statusText}${body2 ? ` — ${body2}` : ""}`);
121133
121550
  }
121134
- throw new Error(`Failed to fetch run key for ${runId} (deployment ${deploymentId}): HTTP ${response2.status} ${response2.statusText}${body2 ? ` — ${body2}` : ""}`);
121135
- }
121551
+ });
121136
121552
  const data = await response2.json();
121137
121553
  const result = object$1({ key: string$3().nullable() }).safeParse(data);
121138
121554
  if (!result.success) {
@@ -121177,66 +121593,6 @@ function createGetEncryptionKeyForRun(projectId, teamId, token, dispatcher2) {
121177
121593
  });
121178
121594
  };
121179
121595
  }
121180
- let otelApiPromise = null;
121181
- async function getOtelApi() {
121182
- if (!otelApiPromise) {
121183
- otelApiPromise = import("./index-meg9qk8y.js").catch(() => null);
121184
- }
121185
- return otelApiPromise;
121186
- }
121187
- let tracerPromise = null;
121188
- async function getTracer() {
121189
- if (!tracerPromise) {
121190
- tracerPromise = getOtelApi().then((otel) => otel ? otel.trace.getTracer("workflow") : null);
121191
- }
121192
- return tracerPromise;
121193
- }
121194
- async function trace(spanName2, ...args) {
121195
- const [tracer, otel] = await Promise.all([getTracer(), getOtelApi()]);
121196
- const { fn: fn2, opts } = typeof args[0] === "function" ? { fn: args[0], opts: {} } : { fn: args[1], opts: args[0] };
121197
- if (!fn2)
121198
- throw new Error("Function to trace must be provided");
121199
- if (!tracer || !otel) {
121200
- return await fn2();
121201
- }
121202
- return tracer.startActiveSpan(spanName2, opts, async (span) => {
121203
- try {
121204
- const result = await fn2(span);
121205
- span.setStatus({ code: otel.SpanStatusCode.OK });
121206
- return result;
121207
- } catch (e) {
121208
- span.setStatus({
121209
- code: otel.SpanStatusCode.ERROR,
121210
- message: e.message
121211
- });
121212
- throw e;
121213
- } finally {
121214
- span.end();
121215
- }
121216
- });
121217
- }
121218
- async function getSpanKind(field) {
121219
- const otel = await getOtelApi();
121220
- if (!otel)
121221
- return void 0;
121222
- return otel.SpanKind[field];
121223
- }
121224
- function SemanticConvention(...names) {
121225
- return (value) => Object.fromEntries(names.map((name2) => [name2, value]));
121226
- }
121227
- const HttpRequestMethod = SemanticConvention("http.request.method");
121228
- const UrlFull = SemanticConvention("url.full");
121229
- const ServerAddress = SemanticConvention("server.address");
121230
- const ServerPort = SemanticConvention("server.port");
121231
- const HttpResponseStatusCode = SemanticConvention("http.response.status_code");
121232
- const ErrorType = SemanticConvention("error.type");
121233
- const WorldParseFormat = SemanticConvention("workflow.world.parse.format");
121234
- const PeerService = SemanticConvention("peer.service");
121235
- const RpcSystem = SemanticConvention("rpc.system");
121236
- const RpcService = SemanticConvention("rpc.service");
121237
- const RpcMethod = SemanticConvention("rpc.method");
121238
- const WorkflowRunId = SemanticConvention("workflow.run.id");
121239
- const StepId = SemanticConvention("step.id");
121240
121596
  const WORKFLOW_SERVER_SERVICE = {
121241
121597
  peerService: "workflow-server",
121242
121598
  rpcSystem: "http",
@@ -125833,26 +126189,7 @@ var QueueClient = class {
125833
126189
  setApi(this, new ApiClient({ ...options, region }));
125834
126190
  }
125835
126191
  };
125836
- const version = "4.6.0";
125837
- const HTTP_DEBUG_ENABLED = typeof process !== "undefined" && typeof process.env.DEBUG === "string" && (process.env.DEBUG.includes("workflow:") || process.env.DEBUG === "*");
125838
- function httpLog(method, endpoint, response2, ms2) {
125839
- if (HTTP_DEBUG_ENABLED) {
125840
- const responseContext = getResponseDiagnosticHeaders(response2);
125841
- const diagnosticSuffix = responseContext.length > 0 ? `; ${responseContext.join("; ")}` : "";
125842
- console.debug(`[workflow:world-vercel:http] ${method} ${endpoint} -> ${response2.status} (${ms2}ms${diagnosticSuffix})`);
125843
- }
125844
- }
125845
- function getResponseDiagnosticHeaders(response2) {
125846
- return ["x-vercel-id", "x-vercel-error", "x-vercel-mitigated"].flatMap((header) => {
125847
- const value = response2.headers.get(header);
125848
- return value ? [`${header}=${value}`] : [];
125849
- });
125850
- }
125851
- function formatResponseDiagnostics(response2) {
125852
- const headers2 = getResponseDiagnosticHeaders(response2);
125853
- return headers2.length > 0 ? ` (${headers2.join("; ")})` : "";
125854
- }
125855
- const REQUEST_TIMEOUT_MS = 6e4;
126192
+ const version = "4.6.2";
125856
126193
  const IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
125857
126194
  const MAX_BODY_PARSE_RETRIES = 2;
125858
126195
  const BODY_PARSE_RETRY_BASE_MS = 100;
@@ -125990,27 +126327,15 @@ async function makeRequest({ endpoint, options = {}, config: config2 = {}, schem
125990
126327
  const method = options.method || "GET";
125991
126328
  const { baseUrl, headers: headers2 } = await getHttpConfig(config2);
125992
126329
  const url2 = `${baseUrl}${endpoint}`;
125993
- let serverAddress;
125994
- let serverPort;
125995
- try {
125996
- const parsedUrl = new URL(url2);
125997
- serverAddress = parsedUrl.hostname;
125998
- serverPort = parsedUrl.port ? parseInt(parsedUrl.port, 10) : parsedUrl.protocol === "https:" ? 443 : 80;
125999
- } catch {
126000
- }
126001
126330
  return trace(`http ${method}`, { kind: await getSpanKind("CLIENT") }, async (span) => {
126002
- var _a3, _b2;
126003
- span == null ? void 0 : span.setAttributes({
126004
- ...HttpRequestMethod(method),
126005
- ...UrlFull(url2),
126006
- ...serverAddress && ServerAddress(serverAddress),
126007
- ...serverPort && ServerPort(serverPort),
126008
- // Peer service for Datadog service maps
126009
- ...PeerService("workflow-server"),
126010
- ...RpcSystem("http"),
126011
- ...RpcService("workflow-server")
126012
- });
126331
+ var _a3, _b2, _c;
126332
+ span == null ? void 0 : span.setAttributes(httpClientSpanAttributes({
126333
+ method,
126334
+ url: url2,
126335
+ peerService: "workflow-server"
126336
+ }));
126013
126337
  headers2.set("Accept", "application/cbor");
126338
+ await injectTraceContextIntoHeaders(headers2);
126014
126339
  let body2;
126015
126340
  if (data !== void 0) {
126016
126341
  headers2.set("Content-Type", "application/cbor");
@@ -126057,64 +126382,27 @@ async function makeRequest({ endpoint, options = {}, config: config2 = {}, schem
126057
126382
  throw error2;
126058
126383
  }
126059
126384
  const fetchMs = Date.now() - fetchStart;
126060
- responseDiagnostics = formatResponseDiagnostics(response2);
126385
+ responseDiagnostics = formatVercelDiagnostics(response2.headers);
126061
126386
  httpLog(method, endpoint, response2, fetchMs);
126062
126387
  span == null ? void 0 : span.setAttributes({
126063
126388
  ...HttpResponseStatusCode(response2.status)
126064
126389
  });
126065
126390
  if (!response2.ok) {
126066
126391
  const errorData = await parseResponseBody(response2).then((r2) => r2.data).catch(() => ({}));
126067
- if (process.env.DEBUG) {
126068
- const stringifiedHeaders = Array.from(headers2.entries()).filter(([key]) => key.toLowerCase() !== "authorization").map(([key, value]) => `-H "${key}: ${value}"`).join(" ");
126069
- console.error(`Failed to fetch, reproduce with:
126070
- curl -X ${request2.method} ${stringifiedHeaders} "${url2}"`);
126071
- }
126072
- let retryAfter;
126073
- const retryAfterHeader = response2.headers.get("Retry-After");
126074
- if (retryAfterHeader) {
126075
- const parsed = parseInt(retryAfterHeader, 10);
126076
- if (!Number.isNaN(parsed)) {
126077
- retryAfter = parsed;
126078
- }
126079
- }
126392
+ logCurlRepro(request2.method, url2, headers2);
126393
+ const retryAfter = parseRetryAfter(response2.headers.get("Retry-After"));
126080
126394
  const defaultMessage = (errorData.message || `${request2.method} ${endpoint} -> HTTP ${response2.status}: ${response2.statusText}`) + responseDiagnostics;
126081
- const throwWithTrace = (error2) => {
126082
- var _a4;
126083
- span == null ? void 0 : span.setAttributes({
126084
- ...ErrorType(errorData.code || `HTTP ${response2.status}`)
126085
- });
126086
- (_a4 = span == null ? void 0 : span.recordException) == null ? void 0 : _a4.call(span, error2);
126087
- throw error2;
126088
- };
126089
- if (response2.status === 409) {
126090
- throwWithTrace(new EntityConflictError(defaultMessage));
126091
- }
126092
- if (response2.status === 410) {
126093
- throwWithTrace(new RunExpiredError(defaultMessage));
126094
- }
126095
- if (response2.status === 412) {
126096
- throwWithTrace(new PreconditionFailedError(defaultMessage, { retryAfter }));
126097
- }
126098
- if (response2.status === 425) {
126099
- throwWithTrace(new TooEarlyError(defaultMessage, { retryAfter }));
126100
- }
126101
- if (response2.status === 429) {
126102
- if (response2.headers.get("x-vercel-mitigated") === "challenge") {
126103
- throwWithTrace(new WorkflowWorldError(`${defaultMessage} (x-vercel-mitigated=challenge)`, {
126104
- url: url2,
126105
- status: response2.status,
126106
- code: "TRANSPORT",
126107
- retryAfter
126108
- }));
126109
- }
126110
- throwWithTrace(new ThrottleError(defaultMessage, { retryAfter }));
126111
- }
126112
- throwWithTrace(new WorkflowWorldError(defaultMessage, {
126395
+ const error2 = errorForResponse(response2.status, defaultMessage, {
126113
126396
  url: url2,
126114
- status: response2.status,
126115
126397
  code: errorData.code,
126116
- retryAfter
126117
- }));
126398
+ retryAfter,
126399
+ mitigated: response2.headers.get("x-vercel-mitigated")
126400
+ });
126401
+ span == null ? void 0 : span.setAttributes({
126402
+ ...ErrorType(errorData.code || `HTTP ${response2.status}`)
126403
+ });
126404
+ (_c = span == null ? void 0 : span.recordException) == null ? void 0 : _c.call(span, error2);
126405
+ throw error2;
126118
126406
  }
126119
126407
  onResponse == null ? void 0 : onResponse(response2);
126120
126408
  try {
@@ -126399,28 +126687,30 @@ function createResolveLatestDeploymentId(config2) {
126399
126687
  if (!currentDeploymentId) {
126400
126688
  throw new Error("Cannot resolve latest deployment: VERCEL_DEPLOYMENT_ID environment variable is not set");
126401
126689
  }
126402
- const token = (config2 == null ? void 0 : config2.token) ?? process.env.VERCEL_TOKEN ?? await distExports.getVercelOidcToken().catch(() => null);
126690
+ const token = await resolveVercelApiToken(config2);
126403
126691
  if (!token) {
126404
126692
  throw new Error("Cannot resolve latest deployment: no OIDC token or VERCEL_TOKEN available");
126405
126693
  }
126406
126694
  const url2 = `https://api.vercel.com/v1/workflow/resolve-latest-deployment/${encodeURIComponent(currentDeploymentId)}`;
126407
- const response2 = await fetch(url2, {
126695
+ const response2 = await instrumentedFetch({
126408
126696
  method: "GET",
126409
- headers: {
126410
- Authorization: `Bearer ${token}`
126411
- },
126412
- // @ts-expect-error -- undici dispatcher is accepted by Node.js fetch but not in @types/node's RequestInit
126413
- dispatcher: getDispatcher(config2)
126414
- });
126415
- if (!response2.ok) {
126416
- let body2;
126417
- try {
126418
- body2 = await response2.text();
126419
- } catch {
126420
- body2 = "<unable to read response body>";
126697
+ url: url2,
126698
+ headers: new Headers({ Authorization: `Bearer ${token}` }),
126699
+ dispatcher: getDispatcher(config2),
126700
+ peerService: "vercel-api",
126701
+ // Preserve the prior no-timeout behavior for this Vercel-API call; the
126702
+ // shared RetryAgent still handles transient/5xx retries.
126703
+ timeoutMs: null,
126704
+ buildError: async (res) => {
126705
+ let body2;
126706
+ try {
126707
+ body2 = await res.text();
126708
+ } catch {
126709
+ body2 = "<unable to read response body>";
126710
+ }
126711
+ return new Error(`Failed to resolve latest deployment for ${currentDeploymentId}: HTTP ${res.status} ${res.statusText}${body2 ? ` — ${body2}` : ""}`);
126421
126712
  }
126422
- throw new Error(`Failed to resolve latest deployment for ${currentDeploymentId}: HTTP ${response2.status} ${response2.statusText}${body2 ? ` — ${body2}` : ""}`);
126423
- }
126713
+ });
126424
126714
  const data = await response2.json();
126425
126715
  const result = ResolveLatestDeploymentResponseSchema.safeParse(data);
126426
126716
  if (!result.success) {
@@ -126632,42 +126922,81 @@ async function* decodeFrames(source) {
126632
126922
  buffer2 = buffer2.subarray(n);
126633
126923
  return out;
126634
126924
  };
126635
- while (true) {
126636
- if (!await refill(4))
126637
- return;
126638
- const metaLen = new DataView(buffer2.buffer, buffer2.byteOffset, 4).getUint32(0, false);
126639
- take(4);
126640
- if (!await refill(metaLen)) {
126641
- throw new Error("decodeFrames: truncated meta block");
126642
- }
126643
- const meta2 = decode(take(metaLen));
126644
- if (!await refill(4)) {
126645
- throw new Error("decodeFrames: truncated body length");
126646
- }
126647
- const bodyLen = new DataView(buffer2.buffer, buffer2.byteOffset, 4).getUint32(0, false);
126648
- take(4);
126649
- if (bodyLen > 0) {
126650
- if (!await refill(bodyLen)) {
126925
+ try {
126926
+ while (true) {
126927
+ if (!await refill(4))
126928
+ return;
126929
+ const metaLen = new DataView(buffer2.buffer, buffer2.byteOffset, 4).getUint32(0, false);
126930
+ take(4);
126931
+ if (!await refill(metaLen)) {
126932
+ throw new Error("decodeFrames: truncated meta block");
126933
+ }
126934
+ const meta2 = decode(take(metaLen));
126935
+ if (!await refill(4)) {
126936
+ throw new Error("decodeFrames: truncated body length");
126937
+ }
126938
+ const bodyLen = new DataView(buffer2.buffer, buffer2.byteOffset, 4).getUint32(0, false);
126939
+ take(4);
126940
+ if (bodyLen > 0 && !await refill(bodyLen)) {
126651
126941
  throw new Error("decodeFrames: truncated body bytes");
126652
126942
  }
126653
126943
  yield { meta: meta2, body: buffer2.slice(0, bodyLen) };
126654
126944
  take(bodyLen);
126655
- } else {
126656
- yield { meta: meta2, body: new Uint8Array(0) };
126945
+ if (meta2._end === 1)
126946
+ return;
126657
126947
  }
126658
- if (meta2._end === 1)
126659
- return;
126948
+ } finally {
126949
+ closeQuietly(() => {
126950
+ var _a3;
126951
+ return (_a3 = chunks.return) == null ? void 0 : _a3.call(chunks);
126952
+ });
126953
+ }
126954
+ }
126955
+ function closeQuietly(close) {
126956
+ try {
126957
+ void Promise.resolve(close()).catch(() => {
126958
+ });
126959
+ } catch {
126660
126960
  }
126661
126961
  }
126662
126962
  async function* readerToIterator(reader) {
126663
- while (true) {
126664
- const { done, value } = await reader.read();
126665
- if (done)
126666
- return;
126667
- if (value)
126668
- yield value;
126963
+ try {
126964
+ while (true) {
126965
+ const { done, value } = await reader.read();
126966
+ if (done)
126967
+ return;
126968
+ if (value)
126969
+ yield value;
126970
+ }
126971
+ } finally {
126972
+ closeQuietly(() => reader.cancel());
126669
126973
  }
126670
126974
  }
126975
+ async function fetchV4(url2, init2, config2, opName) {
126976
+ const dispatcher2 = getEventsDispatcher(config2);
126977
+ return instrumentedFetch({
126978
+ method: init2.method,
126979
+ url: url2,
126980
+ headers: init2.headers,
126981
+ body: init2.body,
126982
+ dispatcher: dispatcher2,
126983
+ // Repeated transport failures retire the shared events pool and the next
126984
+ // request builds a fresh one. undici keeps a black-holed HTTP/2 session in
126985
+ // service indefinitely, so without this every request routed onto it fails
126986
+ // until the compute instance is recycled — see noteEventsTransportOutcome.
126987
+ onTransportOutcome: (error2) => noteEventsTransportOutcome(dispatcher2, error2),
126988
+ timeoutMs: null,
126989
+ logLabel: opName,
126990
+ buildError: async (response2) => errorFromV4Response(response2.status, headersToRecord(response2.headers), await response2.text(), opName, url2)
126991
+ });
126992
+ }
126993
+ function headersToRecord(headers2) {
126994
+ const out = {};
126995
+ headers2.forEach((value, key) => {
126996
+ out[key] = value;
126997
+ });
126998
+ return out;
126999
+ }
126671
127000
  const V4_RESPONSE_HEADERS = {
126672
127001
  eventId: "x-wf-event-id",
126673
127002
  runId: "x-wf-run-id",
@@ -126718,7 +127047,7 @@ function buildPostFrameMeta(input) {
126718
127047
  }
126719
127048
  return meta2;
126720
127049
  }
126721
- function throwForErrorResponse(statusCode, responseHeaders, errorBody, opName, url2) {
127050
+ function errorFromV4Response(statusCode, responseHeaders, errorBody, opName, url2) {
126722
127051
  let message2 = `v4 ${opName} failed: HTTP ${statusCode}`;
126723
127052
  let code2;
126724
127053
  try {
@@ -126731,37 +127060,12 @@ function throwForErrorResponse(statusCode, responseHeaders, errorBody, opName, u
126731
127060
  if (errorBody)
126732
127061
  message2 += ` ${errorBody}`;
126733
127062
  }
126734
- let retryAfter;
126735
- const retryAfterHeader = readHeader(responseHeaders, "retry-after");
126736
- if (retryAfterHeader) {
126737
- const parsed = parseInt(retryAfterHeader, 10);
126738
- if (!Number.isNaN(parsed))
126739
- retryAfter = parsed;
126740
- }
126741
- if (statusCode === 409)
126742
- throw new EntityConflictError(message2);
126743
- if (statusCode === 410)
126744
- throw new RunExpiredError(message2);
126745
- if (statusCode === 412)
126746
- throw new PreconditionFailedError(message2, { retryAfter });
126747
- if (statusCode === 425)
126748
- throw new TooEarlyError(message2, { retryAfter });
126749
- if (statusCode === 429) {
126750
- if (readHeader(responseHeaders, "x-vercel-mitigated") === "challenge") {
126751
- throw new WorkflowWorldError(`${message2} (x-vercel-mitigated=challenge)`, {
126752
- status: statusCode,
126753
- code: "TRANSPORT",
126754
- url: url2,
126755
- retryAfter
126756
- });
126757
- }
126758
- throw new ThrottleError(message2, { retryAfter });
126759
- }
126760
- throw new WorkflowWorldError(message2, {
126761
- status: statusCode,
127063
+ const retryAfter = parseRetryAfter(readHeader(responseHeaders, "retry-after"));
127064
+ return errorForResponse(statusCode, message2, {
127065
+ retryAfter,
126762
127066
  code: code2,
126763
127067
  url: url2,
126764
- retryAfter
127068
+ mitigated: readHeader(responseHeaders, "x-vercel-mitigated")
126765
127069
  });
126766
127070
  }
126767
127071
  async function createWorkflowRunEventV4(input, config2) {
@@ -126770,26 +127074,14 @@ async function createWorkflowRunEventV4(input, config2) {
126770
127074
  headers2.set("Content-Type", "application/octet-stream");
126771
127075
  const frame2 = encodeFrame(buildPostFrameMeta(input), input.payload ?? new Uint8Array(0));
126772
127076
  const url2 = `${baseUrl}/v4/runs/${encodeURIComponent(input.runId)}/events/${encodeURIComponent(input.eventType)}`;
126773
- const response2 = await undiciExports.request(url2, {
126774
- method: "POST",
126775
- headers: Object.fromEntries(headers2.entries()),
126776
- body: frame2,
126777
- // getDispatcher() is typed `unknown` (undici's Dispatcher type is
126778
- // version-specific across @types/node majors); cast to the undici
126779
- // Dispatcher this module's own `request` expects.
126780
- dispatcher: getDispatcher(config2)
126781
- });
126782
- if (response2.statusCode < 200 || response2.statusCode >= 300) {
126783
- const errorBody = await response2.body.text();
126784
- throwForErrorResponse(response2.statusCode, response2.headers, errorBody, "createEvent", url2);
126785
- }
126786
- const eventId = response2.headers[V4_RESPONSE_HEADERS.eventId];
126787
- const runId = response2.headers[V4_RESPONSE_HEADERS.runId];
126788
- const createdAt = response2.headers[V4_RESPONSE_HEADERS.createdAt];
127077
+ const response2 = await fetchV4(url2, { method: "POST", headers: headers2, body: frame2 }, config2, "createEvent");
127078
+ const eventId = response2.headers.get(V4_RESPONSE_HEADERS.eventId);
127079
+ const runId = response2.headers.get(V4_RESPONSE_HEADERS.runId);
127080
+ const createdAt = response2.headers.get(V4_RESPONSE_HEADERS.createdAt);
126789
127081
  if (typeof eventId !== "string" || typeof runId !== "string" || typeof createdAt !== "string") {
126790
127082
  throw new Error("v4 createEvent: response missing required x-wf-* headers");
126791
127083
  }
126792
- const bodyBytes = new Uint8Array(await response2.body.arrayBuffer());
127084
+ const bodyBytes = new Uint8Array(await response2.arrayBuffer());
126793
127085
  const body2 = bodyBytes.byteLength > 0 ? decode(bodyBytes) : {};
126794
127086
  return { eventId, runId, createdAt, body: body2 };
126795
127087
  }
@@ -126804,19 +127096,8 @@ function readHeader(responseHeaders, name2) {
126804
127096
  async function getEventV4(runId, eventId, config2) {
126805
127097
  const { baseUrl, headers: headers2 } = await getHttpConfig(config2);
126806
127098
  const url2 = `${baseUrl}/v4/runs/${encodeURIComponent(runId)}/events/${encodeURIComponent(eventId)}`;
126807
- const response2 = await undiciExports.request(url2, {
126808
- method: "GET",
126809
- headers: Object.fromEntries(headers2.entries()),
126810
- // getDispatcher() is typed `unknown` (undici's Dispatcher type is
126811
- // version-specific across @types/node majors); cast to the undici
126812
- // Dispatcher this module's own `request` expects.
126813
- dispatcher: getDispatcher(config2)
126814
- });
126815
- if (response2.statusCode < 200 || response2.statusCode >= 300) {
126816
- const errorBody = await response2.body.text();
126817
- throwForErrorResponse(response2.statusCode, response2.headers, errorBody, "getEvent", url2);
126818
- }
126819
- const contentType = readHeader(response2.headers, "content-type");
127099
+ const response2 = await fetchV4(url2, { method: "GET", headers: headers2 }, config2, "getEvent");
127100
+ const contentType = response2.headers.get("content-type");
126820
127101
  if (!(contentType == null ? void 0 : contentType.startsWith(V4_FRAME_CONTENT_TYPE))) {
126821
127102
  throw new Error(`v4 getEvent: expected ${V4_FRAME_CONTENT_TYPE}, got ${contentType ?? "(none)"}`);
126822
127103
  }
@@ -126827,19 +127108,8 @@ async function getEventV4(runId, eventId, config2) {
126827
127108
  throw new Error(`v4 getEvent: empty frame stream for ${eventId}`);
126828
127109
  }
126829
127110
  async function consumeListFrameStream(url2, headers2, config2, opName) {
126830
- const response2 = await undiciExports.request(url2, {
126831
- method: "GET",
126832
- headers: Object.fromEntries(headers2.entries()),
126833
- // getDispatcher() is typed `unknown` (undici's Dispatcher type is
126834
- // version-specific across @types/node majors); cast to the undici
126835
- // Dispatcher this module's own `request` expects.
126836
- dispatcher: getDispatcher(config2)
126837
- });
126838
- if (response2.statusCode < 200 || response2.statusCode >= 300) {
126839
- const errorBody = await response2.body.text();
126840
- throwForErrorResponse(response2.statusCode, response2.headers, errorBody, opName, url2);
126841
- }
126842
- const contentType = readHeader(response2.headers, "content-type");
127111
+ const response2 = await fetchV4(url2, { method: "GET", headers: headers2 }, config2, opName);
127112
+ const contentType = response2.headers.get("content-type");
126843
127113
  if (!(contentType == null ? void 0 : contentType.startsWith(V4_FRAME_CONTENT_TYPE))) {
126844
127114
  throw new Error(`v4 ${opName}: expected ${V4_FRAME_CONTENT_TYPE}, got ${contentType ?? "(none)"}`);
126845
127115
  }
@@ -127347,7 +127617,9 @@ async function createWorkflowRunEventInner(id2, data, params, config2) {
127347
127617
  wait: body2.wait,
127348
127618
  events: body2.events ? body2.events.map(coerceEventDates) : void 0,
127349
127619
  cursor: body2.cursor ?? void 0,
127350
- hasMore: body2.hasMore
127620
+ hasMore: body2.hasMore,
127621
+ // Server-supplied per-run event ceiling; absent from older servers.
127622
+ ...typeof body2.maxEvents === "number" ? { maxEvents: body2.maxEvents } : {}
127351
127623
  };
127352
127624
  }
127353
127625
  function filterHookData(hook, resolveData) {
@@ -127461,30 +127733,28 @@ function getStreamMutationTimeoutMs() {
127461
127733
  }
127462
127734
  return DEFAULT_STREAM_MUTATION_TIMEOUT_MS;
127463
127735
  }
127464
- async function fetchStreamMutation(url2, init2, operation) {
127465
- const timeoutMs = getStreamMutationTimeoutMs();
127466
- try {
127467
- return await fetch(url2, {
127468
- ...init2,
127469
- signal: AbortSignal.timeout(timeoutMs)
127470
- });
127471
- } catch (err) {
127472
- if (err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError")) {
127473
- throw new Error(`Stream ${operation} timed out after ${timeoutMs}ms`, {
127474
- cause: err
127475
- });
127476
- }
127477
- throw err;
127478
- }
127736
+ async function fetchStreamMutation(url2, init2, operation, config2) {
127737
+ const response2 = await instrumentedFetch({
127738
+ method: init2.method,
127739
+ url: url2.toString(),
127740
+ headers: init2.headers,
127741
+ body: init2.body,
127742
+ // Stream mutations go through the dedicated H2 stream dispatchers rather
127743
+ // than the global agent — see the note at the top of this file. Close is
127744
+ // idempotent (unlike chunk appends), so it gets the dispatcher that
127745
+ // retries 5xx, which the server's close-barrier protocol depends on.
127746
+ dispatcher: operation === "close" ? getStreamCloseDispatcher(config2) : getStreamDispatcher(config2),
127747
+ timeoutMs: getStreamMutationTimeoutMs(),
127748
+ logLabel: url2.pathname,
127749
+ buildError: async (res) => createStreamRequestError(operation, url2, res, await res.text())
127750
+ });
127751
+ await response2.text();
127479
127752
  }
127480
127753
  function createStreamRequestError(operation, url2, response2, text2) {
127481
- const context = [`PUT ${url2.origin}${url2.pathname}`];
127482
- for (const header of ["x-vercel-id", "x-vercel-error"]) {
127483
- const value = response2.headers.get(header);
127484
- if (value) {
127485
- context.push(`${header}=${value}`);
127486
- }
127487
- }
127754
+ const context = [
127755
+ `PUT ${url2.origin}${url2.pathname}`,
127756
+ ...getVercelDiagnostics(response2.headers)
127757
+ ];
127488
127758
  return new Error(`Stream ${operation} failed: HTTP ${response2.status} (${context.join("; ")}): ${text2}`);
127489
127759
  }
127490
127760
  function encodeMultiChunks(chunks) {
@@ -127526,15 +127796,11 @@ function createStreamer(config2) {
127526
127796
  const resolvedRunId = await runId;
127527
127797
  const httpConfig = await getHttpConfig(config2);
127528
127798
  const url2 = getStreamUrl(name2, resolvedRunId, httpConfig);
127529
- const response2 = await fetchStreamMutation(url2, {
127799
+ await fetchStreamMutation(url2, {
127530
127800
  method: "PUT",
127531
127801
  body: chunk,
127532
127802
  headers: httpConfig.headers
127533
- }, "write");
127534
- const text2 = await response2.text();
127535
- if (!response2.ok) {
127536
- throw createStreamRequestError("write", url2, response2, text2);
127537
- }
127803
+ }, "write", config2);
127538
127804
  },
127539
127805
  async writeToStreamMulti(name2, runId, chunks) {
127540
127806
  if (chunks.length === 0)
@@ -127546,15 +127812,11 @@ function createStreamer(config2) {
127546
127812
  const batch = chunks.slice(i, i + MAX_CHUNKS_PER_REQUEST);
127547
127813
  const body2 = encodeMultiChunks(batch);
127548
127814
  const url2 = getStreamUrl(name2, resolvedRunId, httpConfig);
127549
- const response2 = await fetchStreamMutation(url2, {
127815
+ await fetchStreamMutation(url2, {
127550
127816
  method: "PUT",
127551
127817
  body: body2,
127552
127818
  headers: httpConfig.headers
127553
- }, "write");
127554
- const text2 = await response2.text();
127555
- if (!response2.ok) {
127556
- throw createStreamRequestError("write", url2, response2, text2);
127557
- }
127819
+ }, "write", config2);
127558
127820
  }
127559
127821
  },
127560
127822
  async closeStream(name2, runId) {
@@ -127562,14 +127824,10 @@ function createStreamer(config2) {
127562
127824
  const httpConfig = await getHttpConfig(config2);
127563
127825
  httpConfig.headers.set("X-Stream-Done", "true");
127564
127826
  const url2 = getStreamUrl(name2, resolvedRunId, httpConfig);
127565
- const response2 = await fetchStreamMutation(url2, {
127827
+ await fetchStreamMutation(url2, {
127566
127828
  method: "PUT",
127567
127829
  headers: httpConfig.headers
127568
- }, "close");
127569
- const text2 = await response2.text();
127570
- if (!response2.ok) {
127571
- throw createStreamRequestError("close", url2, response2, text2);
127572
- }
127830
+ }, "close", config2);
127573
127831
  },
127574
127832
  async readFromStream(name2, startIndex) {
127575
127833
  const httpConfig = await getHttpConfig(config2);
@@ -127578,13 +127836,16 @@ function createStreamer(config2) {
127578
127836
  url2.searchParams.set("startIndex", String(startIndex));
127579
127837
  }
127580
127838
  const abortController = new AbortController();
127581
- const response2 = await fetch(url2, {
127839
+ const response2 = await instrumentedFetch({
127840
+ method: "GET",
127841
+ url: url2.toString(),
127582
127842
  headers: httpConfig.headers,
127583
- signal: abortController.signal
127843
+ dispatcher: void 0,
127844
+ timeoutMs: null,
127845
+ signal: abortController.signal,
127846
+ logLabel: url2.pathname,
127847
+ buildError: (res) => new Error(`Failed to fetch stream: ${res.status}`)
127584
127848
  });
127585
- if (!response2.ok) {
127586
- throw new Error(`Failed to fetch stream: ${response2.status}`);
127587
- }
127588
127849
  if (!response2.body) {
127589
127850
  throw new Error("No response body for stream");
127590
127851
  }
@@ -127640,12 +127901,15 @@ function createStreamer(config2) {
127640
127901
  async listStreamsByRunId(runId) {
127641
127902
  const httpConfig = await getHttpConfig(config2);
127642
127903
  const url2 = new URL(`${httpConfig.baseUrl}/v2/runs/${encodeURIComponent(runId)}/streams`);
127643
- const response2 = await fetch(url2, {
127644
- headers: httpConfig.headers
127904
+ const response2 = await instrumentedFetch({
127905
+ method: "GET",
127906
+ url: url2.toString(),
127907
+ headers: httpConfig.headers,
127908
+ dispatcher: void 0,
127909
+ timeoutMs: null,
127910
+ logLabel: url2.pathname,
127911
+ buildError: (res) => new Error(`Failed to list streams: ${res.status}`)
127645
127912
  });
127646
- if (!response2.ok) {
127647
- throw new Error(`Failed to list streams: ${response2.status}`);
127648
- }
127649
127913
  return await response2.json();
127650
127914
  }
127651
127915
  };
@@ -132172,7 +132436,7 @@ function getRunCapabilities(workflowCoreVersion) {
132172
132436
  return result;
132173
132437
  }
132174
132438
  function waitUntil(promise2) {
132175
- void import("./index-B8YoYr9f.js").then((n) => n.i).then(({ waitUntil: waitUntil2 }) => {
132439
+ void import("./index-CMfOrLiJ.js").then((n) => n.i).then(({ waitUntil: waitUntil2 }) => {
132176
132440
  waitUntil2(promise2);
132177
132441
  });
132178
132442
  }