@workflow/web 4.1.19 → 4.1.21

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.
@@ -18,8 +18,8 @@ import { createRequire as __wkfCreateRequire } from "node:module";
18
18
  if (typeof globalThis.require === "undefined") {
19
19
  globalThis.require = __wkfCreateRequire(import.meta.url);
20
20
  }
21
- import { a as requireReact, S as ServerRouter, c as createReadableStreamFromReadable, r as reactExports, g as getDefaultExportFromCjs, R as React, b as ReactExports, w as withComponentProps, d as withErrorBoundaryProps, M as Meta, L as Links, e as ScrollRestoration, f as Scripts, O as Outlet, u as useNavigate, h as useSearchParams, i as Link$1, j as useRouteError, k as isRouteErrorResponse, l as useLocation, m as useParams } from "./app-aFdZLlgg.js";
22
- import require$$0$5, { PassThrough } from "node:stream";
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-eQjjf4RE.js";
22
+ import require$$0$5, { PassThrough, Transform as Transform$1 } from "node:stream";
23
23
  import require$$0 from "util";
24
24
  import require$$1 from "crypto";
25
25
  import require$$2 from "async_hooks";
@@ -37,23 +37,24 @@ import { promises } from "node:fs";
37
37
  import { execFile } from "node:child_process";
38
38
  import require$$3, { promisify, inspect, types as types$3 } from "node:util";
39
39
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
40
+ import require$$0$7, { Buffer as Buffer$2 } from "node:buffer";
41
+ import http from "node:http";
42
+ import https from "node:https";
43
+ import zlib from "node:zlib";
40
44
  import require$$0$2 from "events";
41
45
  import require$$0$4 from "node:assert";
42
46
  import require$$1$2 from "node:net";
43
- import require$$2$1 from "node:http";
44
47
  import require$$5$1 from "node:querystring";
45
48
  import require$$0$3, { EventEmitter } from "node:events";
46
49
  import require$$0$6 from "node:diagnostics_channel";
47
50
  import require$$4 from "node:tls";
48
- import require$$0$7 from "node:buffer";
49
- import require$$3$1 from "node:zlib";
50
51
  import require$$5$2 from "node:perf_hooks";
51
52
  import require$$8 from "node:util/types";
52
53
  import require$$1$3 from "node:sqlite";
53
- import require$$2$2 from "node:worker_threads";
54
+ import require$$2$1 from "node:worker_threads";
54
55
  import require$$1$4, { AsyncLocalStorage } from "node:async_hooks";
55
56
  import require$$1$5 from "node:console";
56
- import require$$2$3 from "node:timers";
57
+ import require$$2$2 from "node:timers";
57
58
  import require$$1$6 from "node:dns";
58
59
  import * as path$2 from "path";
59
60
  import path__default from "path";
@@ -610,7 +611,7 @@ function requireReactDom_development() {
610
611
  function getValueDescriptorExpectingEnumForWarning(thing) {
611
612
  return null === thing ? "`null`" : void 0 === thing ? "`undefined`" : "" === thing ? "an empty string" : "string" === typeof thing ? JSON.stringify(thing) : "number" === typeof thing ? "`" + thing + "`" : 'something with type "' + typeof thing + '"';
612
613
  }
613
- function resolveDispatcher() {
614
+ function resolveDispatcher2() {
614
615
  var dispatcher2 = ReactSharedInternals.H;
615
616
  null === dispatcher2 && console.error(
616
617
  "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
@@ -802,10 +803,10 @@ function requireReactDom_development() {
802
803
  return fn2(a2);
803
804
  };
804
805
  reactDom_development.useFormState = function(action2, initialState2, permalink) {
805
- return resolveDispatcher().useFormState(action2, initialState2, permalink);
806
+ return resolveDispatcher2().useFormState(action2, initialState2, permalink);
806
807
  };
807
808
  reactDom_development.useFormStatus = function() {
808
- return resolveDispatcher().useHostTransitionStatus();
809
+ return resolveDispatcher2().useHostTransitionStatus();
809
810
  };
810
811
  reactDom_development.version = "19.1.0";
811
812
  "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
@@ -34866,6 +34867,25 @@ const serializationFormat = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object
34866
34867
  serializedStepFunctionToString,
34867
34868
  streamToStreamRef
34868
34869
  }, Symbol.toStringTag, { value: "Module" }));
34870
+ const warnedEnvValues = /* @__PURE__ */ new Set();
34871
+ function warnOnce(key, message2) {
34872
+ if (warnedEnvValues.has(key))
34873
+ return;
34874
+ warnedEnvValues.add(key);
34875
+ console.warn(`[workflow] ${message2}`);
34876
+ }
34877
+ function envFlag(name2, fallback, env2 = process.env) {
34878
+ const raw2 = env2[name2];
34879
+ if (raw2 === void 0 || raw2 === "")
34880
+ return fallback;
34881
+ const normalized = raw2.toLowerCase();
34882
+ if (normalized === "0" || normalized === "false")
34883
+ return false;
34884
+ if (normalized === "1" || normalized === "true")
34885
+ return true;
34886
+ warnOnce(`${name2}=${raw2}`, `Ignoring ${name2}: expected 0/1/true/false; using default ${fallback}`);
34887
+ return fallback;
34888
+ }
34869
34889
  const NEVER = Object.freeze({
34870
34890
  status: "aborted"
34871
34891
  });
@@ -48800,6 +48820,11 @@ const HookSchema = object$1({
48800
48820
  specVersion: number$3().optional(),
48801
48821
  isWebhook: boolean$3().optional()
48802
48822
  });
48823
+ const NODE_HTTP_ENV_VAR = "WORKFLOW_NODE_HTTP";
48824
+ const NODE_HTTP_DEFAULT = false;
48825
+ function isNodeHttpEnabled(env2 = process.env) {
48826
+ return envFlag(NODE_HTTP_ENV_VAR, NODE_HTTP_DEFAULT, env2);
48827
+ }
48803
48828
  const QueuePrefix = string$3().regex(/^__(?:[a-z][a-z0-9]*_)?wkf_(?:workflow|step)_$/, "Must match __wkf_{workflow|step}_ or __{namespace}_wkf_{workflow|step}_");
48804
48829
  const ValidQueueName = string$3().regex(/^__(?:[a-z][a-z0-9]*_)?wkf_(?:workflow|step)_.+$/, "Must be a valid queue name with a recognized prefix");
48805
48830
  const QueueNamespace = string$3().regex(/^[a-z][a-z0-9]*$/, "Must be lowercase alphanumeric, starting with a letter");
@@ -48864,7 +48889,8 @@ const QueuePayloadSchema = union([
48864
48889
  StepInvokePayloadSchema,
48865
48890
  HealthCheckPayloadSchema
48866
48891
  ]);
48867
- async function reenqueueActiveRuns(runs, enqueue, label) {
48892
+ async function reenqueueActiveRuns(runs, enqueue, label, namespace2) {
48893
+ const workflowQueuePrefix = getQueueTopicPrefix("workflow", resolveQueueNamespace(namespace2));
48868
48894
  let reenqueued = 0;
48869
48895
  for (const status of ["pending", "running"]) {
48870
48896
  let cursor;
@@ -48877,7 +48903,7 @@ async function reenqueueActiveRuns(runs, enqueue, label) {
48877
48903
  });
48878
48904
  for (const run2 of page.data) {
48879
48905
  try {
48880
- const queueName = `__wkf_workflow_${run2.workflowName}`;
48906
+ const queueName = `${workflowQueuePrefix}${run2.workflowName}`;
48881
48907
  await enqueue(queueName, { runId: run2.runId });
48882
48908
  reenqueued++;
48883
48909
  } catch (err) {
@@ -81832,7 +81858,7 @@ var tn = f("block", "before:content-[counter(line)]", "before:inline-block", "be
81832
81858
  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 });
81833
81859
  var Se = reactExports.createContext({ code: "" }), de = () => reactExports.useContext(Se);
81834
81860
  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 }) });
81835
- var cn$1 = /\n+$/, dn = reactExports.lazy(() => import("./highlighted-body-B3W2YXNL--Q6LYe80.js").then((e) => ({ default: e.HighlightedCodeBlockBody }))), rt = ({ code: e, language: t, className: o, children: n, isIncomplete: s2 = false, ...r2 }) => {
81861
+ var cn$1 = /\n+$/, dn = reactExports.lazy(() => import("./highlighted-body-B3W2YXNL-DkTToHdM.js").then((e) => ({ default: e.HighlightedCodeBlockBody }))), rt = ({ code: e, language: t, className: o, children: n, isIncomplete: s2 = false, ...r2 }) => {
81836
81862
  let i = reactExports.useMemo(() => e.replace(cn$1, ""), [e]), c = reactExports.useMemo(() => ({ bg: "transparent", fg: "inherit", tokens: i.split(`
81837
81863
  `).map((a2) => [{ content: a2, color: "inherit", bgColor: "transparent", htmlStyle: {}, offset: 0 }]) }), [i]);
81838
81864
  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 }) })] }) });
@@ -82154,7 +82180,7 @@ var Dt = ({ children: e, className: t, onDownload: o, onError: n }) => {
82154
82180
  }, []), 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] });
82155
82181
  };
82156
82182
  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 }) })] });
82157
- var Jn = reactExports.lazy(() => import("./mermaid-3ZIDBTTL-DrVDu1xg.js").then((e) => ({ default: e.Mermaid }))), Kn = /language-([^\s]+)/;
82183
+ var Jn = reactExports.lazy(() => import("./mermaid-3ZIDBTTL-DvwsvCUy.js").then((e) => ({ default: e.Mermaid }))), Kn = /language-([^\s]+)/;
82158
82184
  function ke(e, t) {
82159
82185
  if (!(e != null && e.position || t != null && t.position)) return true;
82160
82186
  if (!(e != null && e.position && (t != null && t.position))) return false;
@@ -92046,7 +92072,7 @@ createLogger("build", {
92046
92072
  debugNamespace: "workflow:build"
92047
92073
  });
92048
92074
  const MAX_QUEUE_DELIVERIES = 48;
92049
- const version$1 = "4.8.3";
92075
+ const version$1 = "4.8.5";
92050
92076
  const execFileAsync = promisify(execFile);
92051
92077
  function parsePort$1(value, radix = 10) {
92052
92078
  const port = parseInt(value, radix);
@@ -92295,6 +92321,18 @@ const config = once(() => {
92295
92321
  const baseUrl = getBaseUrlFromEnv();
92296
92322
  return { dataDir, baseUrl };
92297
92323
  });
92324
+ function resolveRecoverActiveRuns(config2) {
92325
+ var _a3;
92326
+ if (config2.recoverActiveRuns !== void 0) {
92327
+ return config2.recoverActiveRuns;
92328
+ }
92329
+ const raw2 = (_a3 = process.env.WORKFLOW_LOCAL_RECOVER_ACTIVE_RUNS) == null ? void 0 : _a3.toLowerCase();
92330
+ if (raw2 === "0" || raw2 === "false")
92331
+ return false;
92332
+ if (raw2 === "1" || raw2 === "true")
92333
+ return true;
92334
+ return true;
92335
+ }
92298
92336
  function resolveDirectBaseUrl(config2) {
92299
92337
  return config2.baseUrl ?? process.env.WORKFLOW_LOCAL_BASE_URL ?? createWorkflowBaseUrl("http://localhost");
92300
92338
  }
@@ -92367,8 +92405,10 @@ async function withWindowsRetry(fn2, maxRetries = 5) {
92367
92405
  throw new Error("Retry loop exited unexpectedly");
92368
92406
  }
92369
92407
  const createdFilesCache = /* @__PURE__ */ new Set();
92408
+ const createdDirectoriesCache = /* @__PURE__ */ new Set();
92370
92409
  function clearCreatedFilesCache() {
92371
92410
  createdFilesCache.clear();
92411
+ createdDirectoriesCache.clear();
92372
92412
  }
92373
92413
  const TAG_PATTERN = /\.[a-zA-Z][a-zA-Z0-9-]*$/;
92374
92414
  function stripTag(fileId) {
@@ -92421,11 +92461,29 @@ async function listTaggedFilesByExtension(dirPath, tag, extension2) {
92421
92461
  }
92422
92462
  }
92423
92463
  async function ensureDir(dirPath) {
92464
+ const resolvedPath = path$3.resolve(dirPath);
92465
+ if (createdDirectoriesCache.has(resolvedPath)) {
92466
+ return;
92467
+ }
92424
92468
  try {
92425
- await promises.mkdir(dirPath, { recursive: true });
92469
+ await promises.mkdir(resolvedPath, { recursive: true });
92470
+ createdDirectoriesCache.add(resolvedPath);
92426
92471
  } catch (_error) {
92427
92472
  }
92428
92473
  }
92474
+ async function withEnsuredDirectory(dirPath, operation) {
92475
+ await ensureDir(dirPath);
92476
+ try {
92477
+ return await operation();
92478
+ } catch (error2) {
92479
+ if (error2.code !== "ENOENT") {
92480
+ throw error2;
92481
+ }
92482
+ createdDirectoriesCache.delete(path$3.resolve(dirPath));
92483
+ await ensureDir(dirPath);
92484
+ return operation();
92485
+ }
92486
+ }
92429
92487
  function jsonReplacer(_key, value) {
92430
92488
  if (value instanceof Uint8Array) {
92431
92489
  return {
@@ -92462,10 +92520,11 @@ async function write(filePath, data, opts) {
92462
92520
  const tempPath = `${filePath}.tmp.${ulid$1()}`;
92463
92521
  let tempFileCreated = false;
92464
92522
  try {
92465
- await ensureDir(path$3.dirname(filePath));
92466
- await promises.writeFile(tempPath, data);
92467
- tempFileCreated = true;
92468
- await withWindowsRetry(() => promises.rename(tempPath, filePath));
92523
+ await withEnsuredDirectory(path$3.dirname(filePath), async () => {
92524
+ await promises.writeFile(tempPath, data);
92525
+ tempFileCreated = true;
92526
+ await withWindowsRetry(() => promises.rename(tempPath, filePath));
92527
+ });
92469
92528
  createdFilesCache.add(filePath);
92470
92529
  } catch (error2) {
92471
92530
  if (tempFileCreated) {
@@ -92508,21 +92567,22 @@ async function deleteJSON(filePath) {
92508
92567
  }
92509
92568
  }
92510
92569
  async function writeExclusive(filePath, data) {
92511
- await ensureDir(path$3.dirname(filePath));
92512
92570
  const tempPath = `${filePath}.tmp.${ulid$1()}`;
92513
92571
  let tempFileCreated = false;
92514
92572
  try {
92515
- await promises.writeFile(tempPath, data, { flag: "wx" });
92516
- tempFileCreated = true;
92517
- try {
92518
- await withWindowsRetry(() => promises.link(tempPath, filePath));
92519
- return true;
92520
- } catch (error2) {
92521
- if (error2.code === "EEXIST") {
92522
- return false;
92573
+ return await withEnsuredDirectory(path$3.dirname(filePath), async () => {
92574
+ await promises.writeFile(tempPath, data, { flag: "wx" });
92575
+ tempFileCreated = true;
92576
+ try {
92577
+ await withWindowsRetry(() => promises.link(tempPath, filePath));
92578
+ return true;
92579
+ } catch (error2) {
92580
+ if (error2.code === "EEXIST") {
92581
+ return false;
92582
+ }
92583
+ throw error2;
92523
92584
  }
92524
- throw error2;
92525
- }
92585
+ });
92526
92586
  } finally {
92527
92587
  if (tempFileCreated) {
92528
92588
  await withWindowsRetry(() => promises.unlink(tempPath), 3).catch(() => {
@@ -92556,11 +92616,12 @@ function createCursor(timestamp, id2) {
92556
92616
  return id2 ? `${timestamp.toISOString()}|${id2}` : timestamp.toISOString();
92557
92617
  }
92558
92618
  async function paginatedFileSystemQuery(config2) {
92559
- const { directory, schema, filePrefix, fileIdFilter, filter: filter2, sortOrder = "desc", limit = 20, cursor, getCreatedAt, getId } = config2;
92619
+ const { directory, schema, cachedItems, filePrefix, fileIdFilter, filter: filter2, sortOrder = "desc", limit = 20, cursor, getCreatedAt, getId } = config2;
92560
92620
  if (filePrefix !== void 0) {
92561
92621
  assertSafeEntityId("filePrefix", filePrefix);
92562
92622
  }
92563
- const fileIds = await listJSONFiles(directory);
92623
+ const resolvedDirectory = path$3.resolve(directory);
92624
+ const fileIds = await listJSONFiles(resolvedDirectory);
92564
92625
  const relevantFileIds = filePrefix ? fileIds.filter((fileId) => fileId.startsWith(filePrefix)) : fileIds;
92565
92626
  const filteredFileIds = fileIdFilter ? relevantFileIds.filter(fileIdFilter) : relevantFileIds;
92566
92627
  const parsedCursor = parseCursor(cursor);
@@ -92582,10 +92643,11 @@ async function paginatedFileSystemQuery(config2) {
92582
92643
  }
92583
92644
  const validItems = [];
92584
92645
  for (const fileId of candidateFileIds) {
92585
- const filePath = path$3.join(directory, `${fileId}.json`);
92646
+ const filePath = path$3.join(resolvedDirectory, `${fileId}.json`);
92586
92647
  let item = null;
92587
92648
  try {
92588
- item = await readJSON(filePath, schema);
92649
+ const cachedItem = cachedItems == null ? void 0 : cachedItems.get(filePath);
92650
+ item = cachedItem === void 0 ? await readJSON(filePath, schema) : structuredClone(cachedItem);
92589
92651
  } catch (error2) {
92590
92652
  if (error2 instanceof ZodError) {
92591
92653
  console.warn(`Skipping item ${fileId} due to malformed JSON: ${error2.message}`);
@@ -92962,6 +93024,263 @@ function instrumentObject$1(prefix, o) {
92962
93024
  }
92963
93025
  return handlers2;
92964
93026
  }
93027
+ function createNodeHttpAgents(options) {
93028
+ const shared2 = {
93029
+ keepAlive: true,
93030
+ keepAliveMsecs: options.keepAliveMs,
93031
+ maxSockets: options.maxSockets
93032
+ };
93033
+ return { http: new http.Agent(shared2), https: new https.Agent(shared2) };
93034
+ }
93035
+ function destroyNodeHttpAgents(agents) {
93036
+ agents.http.destroy();
93037
+ agents.https.destroy();
93038
+ }
93039
+ const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([204, 205, 304]);
93040
+ const ACCEPTED_ENCODINGS = "gzip, deflate, br";
93041
+ const TIMEOUT_CODE = "ETIMEDOUT";
93042
+ function transportError(message2, code2) {
93043
+ return Object.assign(new Error(message2), { code: code2 });
93044
+ }
93045
+ function toOutgoingHeaders(headers2) {
93046
+ const outgoing = {};
93047
+ headers2 == null ? void 0 : headers2.forEach((value, name2) => {
93048
+ outgoing[name2] = value;
93049
+ });
93050
+ return outgoing;
93051
+ }
93052
+ function toResponseHeaders(message2) {
93053
+ const headers2 = new Headers();
93054
+ for (const [name2, value] of Object.entries(message2.headers)) {
93055
+ if (value === void 0)
93056
+ continue;
93057
+ if (Array.isArray(value)) {
93058
+ for (const entry2 of value)
93059
+ headers2.append(name2, entry2);
93060
+ } else {
93061
+ headers2.append(name2, value);
93062
+ }
93063
+ }
93064
+ return headers2;
93065
+ }
93066
+ const ZLIB_OPTIONS = {
93067
+ flush: zlib.constants.Z_SYNC_FLUSH,
93068
+ finishFlush: zlib.constants.Z_SYNC_FLUSH
93069
+ };
93070
+ const BROTLI_OPTIONS = {
93071
+ flush: zlib.constants.BROTLI_OPERATION_FLUSH,
93072
+ finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
93073
+ };
93074
+ class InflateAuto extends Transform$1 {
93075
+ constructor() {
93076
+ super(...arguments);
93077
+ __publicField(this, "inner");
93078
+ }
93079
+ _transform(chunk, _encoding, callback) {
93080
+ if (!this.inner) {
93081
+ if (chunk.length === 0) {
93082
+ callback();
93083
+ return;
93084
+ }
93085
+ const inner = (chunk[0] & 15) === 8 ? zlib.createInflate(ZLIB_OPTIONS) : zlib.createInflateRaw(ZLIB_OPTIONS);
93086
+ inner.on("data", (decoded) => this.push(decoded));
93087
+ inner.on("end", () => this.push(null));
93088
+ inner.on("error", (error2) => this.destroy(error2));
93089
+ this.inner = inner;
93090
+ }
93091
+ this.inner.write(chunk, callback);
93092
+ }
93093
+ /**
93094
+ * Overriding `_final` keeps the readable side open past the end of the
93095
+ * writable one, so the last inflated bytes still reach the consumer. It is
93096
+ * closed by the inner stream's `end`, or here when there was no body at all.
93097
+ */
93098
+ _final(callback) {
93099
+ if (this.inner) {
93100
+ this.inner.end();
93101
+ } else {
93102
+ this.push(null);
93103
+ }
93104
+ callback();
93105
+ }
93106
+ _destroy(error2, callback) {
93107
+ var _a3;
93108
+ (_a3 = this.inner) == null ? void 0 : _a3.destroy();
93109
+ callback(error2);
93110
+ }
93111
+ }
93112
+ function decodeBody(message2) {
93113
+ var _a3;
93114
+ const encoding2 = (_a3 = message2.headers["content-encoding"]) == null ? void 0 : _a3.toLowerCase().trim();
93115
+ if (!encoding2 || encoding2 === "identity")
93116
+ return message2;
93117
+ let decoder2;
93118
+ if (encoding2 === "gzip" || encoding2 === "x-gzip") {
93119
+ decoder2 = zlib.createGunzip(ZLIB_OPTIONS);
93120
+ } else if (encoding2 === "deflate") {
93121
+ decoder2 = new InflateAuto();
93122
+ } else if (encoding2 === "br") {
93123
+ decoder2 = zlib.createBrotliDecompress(BROTLI_OPTIONS);
93124
+ } else {
93125
+ return message2;
93126
+ }
93127
+ message2.on("error", (error2) => decoder2.destroy(error2));
93128
+ message2.on("close", () => {
93129
+ if (message2.complete)
93130
+ return;
93131
+ decoder2.destroy(transportError("socket hang up", "ECONNRESET"));
93132
+ });
93133
+ decoder2.on("close", () => {
93134
+ if (!message2.complete)
93135
+ message2.destroy();
93136
+ });
93137
+ return message2.pipe(decoder2);
93138
+ }
93139
+ function toWebStream(source, hooks) {
93140
+ let closed = false;
93141
+ const finish = (fn2) => {
93142
+ if (closed)
93143
+ return;
93144
+ closed = true;
93145
+ hooks.done();
93146
+ fn2();
93147
+ };
93148
+ return new ReadableStream({
93149
+ start(controller) {
93150
+ source.on("data", (chunk) => {
93151
+ hooks.progress();
93152
+ controller.enqueue(new Uint8Array(chunk));
93153
+ if ((controller.desiredSize ?? 1) <= 0)
93154
+ source.pause();
93155
+ });
93156
+ source.on("end", () => finish(() => controller.close()));
93157
+ source.on("error", (error2) => finish(() => controller.error(hooks.failure(error2))));
93158
+ source.on("close", () => finish(() => controller.error(hooks.failure())));
93159
+ },
93160
+ pull() {
93161
+ source.resume();
93162
+ },
93163
+ cancel(reason) {
93164
+ var _a3;
93165
+ finish(() => {
93166
+ });
93167
+ (_a3 = source.destroy) == null ? void 0 : _a3.call(source, reason instanceof Error ? reason : void 0);
93168
+ }
93169
+ });
93170
+ }
93171
+ function nodeHttpFetch(url2, init2 = {}) {
93172
+ const { method = "GET", headers: headers2, body: body2, signal, agents, headersTimeoutMs, bodyTimeoutMs } = init2;
93173
+ const target2 = new URL(url2);
93174
+ const secure = target2.protocol === "https:";
93175
+ if (!secure && target2.protocol !== "http:") {
93176
+ return Promise.reject(new TypeError(`node:http transport cannot request ${target2.protocol}// URLs`));
93177
+ }
93178
+ const outgoing = toOutgoingHeaders(headers2);
93179
+ const payload = body2 == null ? void 0 : typeof body2 === "string" ? Buffer$2.from(body2, "utf8") : Buffer$2.from(body2.buffer, body2.byteOffset, body2.byteLength);
93180
+ if (payload)
93181
+ outgoing["content-length"] = String(payload.byteLength);
93182
+ if (!("accept-encoding" in outgoing)) {
93183
+ outgoing["accept-encoding"] = ACCEPTED_ENCODINGS;
93184
+ }
93185
+ return new Promise((resolve2, reject) => {
93186
+ if (signal == null ? void 0 : signal.aborted) {
93187
+ reject(signal.reason);
93188
+ return;
93189
+ }
93190
+ let settled = false;
93191
+ let headersTimer;
93192
+ let bodyTimer;
93193
+ let teardownReason;
93194
+ const clearTimers = () => {
93195
+ clearTimeout(headersTimer);
93196
+ clearTimeout(bodyTimer);
93197
+ headersTimer = void 0;
93198
+ bodyTimer = void 0;
93199
+ };
93200
+ const request2 = (secure ? https : http).request(target2, {
93201
+ method,
93202
+ headers: outgoing,
93203
+ agent: agents ? secure ? agents.https : agents.http : void 0
93204
+ });
93205
+ const abort = () => {
93206
+ if ((signal == null ? void 0 : signal.reason) instanceof Error)
93207
+ teardownReason = signal.reason;
93208
+ request2.destroy(signal == null ? void 0 : signal.reason);
93209
+ };
93210
+ signal == null ? void 0 : signal.addEventListener("abort", abort, { once: true });
93211
+ const detach = () => {
93212
+ signal == null ? void 0 : signal.removeEventListener("abort", abort);
93213
+ };
93214
+ const fail = (error2) => {
93215
+ clearTimers();
93216
+ detach();
93217
+ if (settled)
93218
+ return;
93219
+ settled = true;
93220
+ reject(error2);
93221
+ };
93222
+ if (headersTimeoutMs) {
93223
+ request2.on("socket", () => {
93224
+ headersTimer = setTimeout(() => {
93225
+ request2.destroy(transportError(`no response headers within ${headersTimeoutMs}ms`, TIMEOUT_CODE));
93226
+ }, headersTimeoutMs);
93227
+ });
93228
+ }
93229
+ request2.on("error", fail);
93230
+ request2.on("response", (message2) => {
93231
+ clearTimeout(headersTimer);
93232
+ headersTimer = void 0;
93233
+ const status = message2.statusCode ?? 0;
93234
+ if (status < 200 || status > 599) {
93235
+ request2.destroy();
93236
+ fail(transportError(`origin returned an unusable status line (${status})`, "UNSUPPORTED_STATUS"));
93237
+ return;
93238
+ }
93239
+ const responseHeaders = toResponseHeaders(message2);
93240
+ const statusText = message2.statusMessage ?? "";
93241
+ const bodiless = NULL_BODY_STATUSES.has(status) || method.toUpperCase() === "HEAD";
93242
+ if (bodiless) {
93243
+ message2.resume();
93244
+ clearTimers();
93245
+ detach();
93246
+ settled = true;
93247
+ resolve2(new Response(null, { status, statusText, headers: responseHeaders }));
93248
+ return;
93249
+ }
93250
+ const armBodyTimer = () => {
93251
+ if (!bodyTimeoutMs)
93252
+ return;
93253
+ clearTimeout(bodyTimer);
93254
+ bodyTimer = setTimeout(() => {
93255
+ teardownReason = transportError(`no response body progress for ${bodyTimeoutMs}ms`, TIMEOUT_CODE);
93256
+ request2.destroy(teardownReason);
93257
+ }, bodyTimeoutMs);
93258
+ };
93259
+ armBodyTimer();
93260
+ const decoded = decodeBody(message2);
93261
+ if (decoded !== message2) {
93262
+ responseHeaders.delete("content-encoding");
93263
+ responseHeaders.delete("content-length");
93264
+ }
93265
+ const stream = toWebStream(decoded, {
93266
+ progress: armBodyTimer,
93267
+ done: () => {
93268
+ clearTimers();
93269
+ detach();
93270
+ },
93271
+ // A deliberate teardown (body deadline, caller abort) reaches the
93272
+ // socket as a plain reset, so the reason we tore it down for wins over
93273
+ // whatever the socket reported.
93274
+ failure: (cause) => teardownReason ?? cause ?? transportError("socket hang up", "ECONNRESET")
93275
+ });
93276
+ settled = true;
93277
+ resolve2(new Response(stream, { status, statusText, headers: responseHeaders }));
93278
+ });
93279
+ if (payload)
93280
+ request2.write(payload);
93281
+ request2.end();
93282
+ });
93283
+ }
92965
93284
  var lib = {};
92966
93285
  var hasRequiredLib;
92967
93286
  function requireLib() {
@@ -94130,7 +94449,7 @@ function requireUtil$5() {
94130
94449
  hasRequiredUtil$5 = 1;
94131
94450
  const assert2 = require$$0$4;
94132
94451
  const { kDestroyed, kBodyUsed, kListeners, kBody } = requireSymbols();
94133
- const { IncomingMessage } = require$$2$1;
94452
+ const { IncomingMessage } = http;
94134
94453
  const stream = require$$0$5;
94135
94454
  const net2 = require$$1$2;
94136
94455
  const { stringify: stringify2 } = require$$5$1;
@@ -97450,8 +97769,8 @@ function requireRuntimeFeatures() {
97450
97769
  __proto__: null,
97451
97770
  "node:crypto": () => crypto,
97452
97771
  "node:sqlite": () => require$$1$3,
97453
- "node:worker_threads": () => require$$2$2,
97454
- "node:zlib": () => require$$3$1
97772
+ "node:worker_threads": () => require$$2$1,
97773
+ "node:zlib": () => zlib
97455
97774
  };
97456
97775
  function detectRuntimeFeatureByNodeModule(moduleName) {
97457
97776
  try {
@@ -97675,7 +97994,7 @@ function requireWebidl() {
97675
97994
  return "Object";
97676
97995
  }
97677
97996
  };
97678
- webidl.util.markAsUncloneable = runtimeFeatures2.has("markAsUncloneable") ? require$$2$2.markAsUncloneable : () => {
97997
+ webidl.util.markAsUncloneable = runtimeFeatures2.has("markAsUncloneable") ? require$$2$1.markAsUncloneable : () => {
97679
97998
  };
97680
97999
  webidl.util.ConvertToInt = function(V2, bitLength, signedness, flags) {
97681
98000
  let upperBound;
@@ -98158,7 +98477,7 @@ function requireUtil$4() {
98158
98477
  if (hasRequiredUtil$4) return util$4;
98159
98478
  hasRequiredUtil$4 = 1;
98160
98479
  const { Transform: Transform2 } = require$$0$5;
98161
- const zlib = require$$3$1;
98480
+ const zlib$1 = zlib;
98162
98481
  const { redirectStatusSet, referrerPolicyTokens, badPortsSet } = requireConstants$3();
98163
98482
  const { getGlobalOrigin } = requireGlobal$1();
98164
98483
  const { collectAnHTTPQuotedString, parseMIMEType } = requireDataUrl();
@@ -98766,7 +99085,7 @@ function requireUtil$4() {
98766
99085
  callback();
98767
99086
  return;
98768
99087
  }
98769
- this._inflateStream = (chunk[0] & 15) === 8 ? zlib.createInflate(__privateGet(this, _zlibOptions)) : zlib.createInflateRaw(__privateGet(this, _zlibOptions));
99088
+ this._inflateStream = (chunk[0] & 15) === 8 ? zlib$1.createInflate(__privateGet(this, _zlibOptions)) : zlib$1.createInflateRaw(__privateGet(this, _zlibOptions));
98770
99089
  this._inflateStream.on("data", this.push.bind(this));
98771
99090
  this._inflateStream.on("end", () => this.push(null));
98772
99091
  this._inflateStream.on("error", (err) => this.destroy(err));
@@ -101725,7 +102044,7 @@ function requireClient() {
101725
102044
  hasRequiredClient = 1;
101726
102045
  const assert2 = require$$0$4;
101727
102046
  const net2 = require$$1$2;
101728
- const http = require$$2$1;
102047
+ const http$1 = http;
101729
102048
  const util2 = requireUtil$5();
101730
102049
  const { ClientStats } = requireStats();
101731
102050
  const { channels } = requireDiagnostics();
@@ -101783,7 +102102,7 @@ function requireClient() {
101783
102102
  const connectH1 = requireClientH1();
101784
102103
  const connectH2 = requireClientH2();
101785
102104
  const kClosedResolve = Symbol("kClosedResolve");
101786
- const getDefaultNodeMaxHeaderSize = http && http.maxHeaderSize && Number.isInteger(http.maxHeaderSize) && http.maxHeaderSize > 0 ? () => http.maxHeaderSize : () => {
102105
+ const getDefaultNodeMaxHeaderSize = http$1 && http$1.maxHeaderSize && Number.isInteger(http$1.maxHeaderSize) && http$1.maxHeaderSize > 0 ? () => http$1.maxHeaderSize : () => {
101787
102106
  throw new InvalidArgumentError("http module not available or http.maxHeaderSize invalid");
101788
102107
  };
101789
102108
  const noop3 = () => {
@@ -105768,7 +106087,7 @@ function requireMockUtils() {
105768
106087
  kTotalDispatchCount
105769
106088
  } = requireMockSymbols();
105770
106089
  const { serializePathWithQuery } = requireUtil$5();
105771
- const { STATUS_CODES } = require$$2$1;
106090
+ const { STATUS_CODES } = http;
105772
106091
  const {
105773
106092
  types: {
105774
106093
  isPromise
@@ -106939,7 +107258,7 @@ function requireSnapshotRecorder() {
106939
107258
  hasRequiredSnapshotRecorder = 1;
106940
107259
  const { writeFile: writeFile2, readFile: readFile2, mkdir: mkdir2 } = fs$1;
106941
107260
  const { dirname: dirname2, resolve: resolve2 } = path$3;
106942
- const { setTimeout: setTimeout2, clearTimeout: clearTimeout2 } = require$$2$3;
107261
+ const { setTimeout: setTimeout2, clearTimeout: clearTimeout2 } = require$$2$2;
106943
107262
  const { InvalidArgumentError, UndiciError } = requireErrors();
106944
107263
  const { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = requireSnapshotUtils();
106945
107264
  function formatRequestKey(opts, headerFilters, matchOptions = {}) {
@@ -110375,7 +110694,7 @@ function requireDecompress() {
110375
110694
  var _decompressors, _skipStatusCodes, _skipErrorResponses, _DecompressHandler_instances, shouldSkipDecompression_fn, createDecompressionChain_fn, setupDecompressorEvents_fn, setupSingleDecompressor_fn, setupMultipleDecompressors_fn, cleanupDecompressors_fn;
110376
110695
  if (hasRequiredDecompress) return decompress;
110377
110696
  hasRequiredDecompress = 1;
110378
- const { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = require$$3$1;
110697
+ const { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = zlib;
110379
110698
  const { pipeline } = require$$0$5;
110380
110699
  const DecoratorHandler = requireDecoratorHandler();
110381
110700
  const { runtimeFeatures: runtimeFeatures2 } = requireRuntimeFeatures();
@@ -113231,7 +113550,7 @@ function requireFetch() {
113231
113550
  } = requireResponse();
113232
113551
  const { HeadersList } = requireHeaders();
113233
113552
  const { Request: Request2, cloneRequest, getRequestDispatcher, getRequestState } = requireRequest();
113234
- const zlib = require$$3$1;
113553
+ const zlib$1 = zlib;
113235
113554
  const {
113236
113555
  makePolicyContainer,
113237
113556
  clonePolicyContainer,
@@ -113281,7 +113600,7 @@ function requireFetch() {
113281
113600
  const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = requireDataUrl();
113282
113601
  const { getGlobalDispatcher } = requireGlobal();
113283
113602
  const { webidl } = requireWebidl();
113284
- const { STATUS_CODES } = require$$2$1;
113603
+ const { STATUS_CODES } = http;
113285
113604
  const { bytesMatch } = requireSubresourceIntegrity();
113286
113605
  const { createDeferredPromise } = requirePromise();
113287
113606
  const { isomorphicEncode } = requireInfra();
@@ -114225,28 +114544,28 @@ function requireFetch() {
114225
114544
  for (let i = codings.length - 1; i >= 0; --i) {
114226
114545
  const coding = codings[i].trim();
114227
114546
  if (coding === "x-gzip" || coding === "gzip") {
114228
- decoders.push(zlib.createGunzip({
114547
+ decoders.push(zlib$1.createGunzip({
114229
114548
  // Be less strict when decoding compressed responses, since sometimes
114230
114549
  // servers send slightly invalid responses that are still accepted
114231
114550
  // by common browsers.
114232
114551
  // Always using Z_SYNC_FLUSH is what cURL does.
114233
- flush: zlib.constants.Z_SYNC_FLUSH,
114234
- finishFlush: zlib.constants.Z_SYNC_FLUSH
114552
+ flush: zlib$1.constants.Z_SYNC_FLUSH,
114553
+ finishFlush: zlib$1.constants.Z_SYNC_FLUSH
114235
114554
  }));
114236
114555
  } else if (coding === "deflate") {
114237
114556
  decoders.push(createInflate({
114238
- flush: zlib.constants.Z_SYNC_FLUSH,
114239
- finishFlush: zlib.constants.Z_SYNC_FLUSH
114557
+ flush: zlib$1.constants.Z_SYNC_FLUSH,
114558
+ finishFlush: zlib$1.constants.Z_SYNC_FLUSH
114240
114559
  }));
114241
114560
  } else if (coding === "br") {
114242
- decoders.push(zlib.createBrotliDecompress({
114243
- flush: zlib.constants.BROTLI_OPERATION_FLUSH,
114244
- finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
114561
+ decoders.push(zlib$1.createBrotliDecompress({
114562
+ flush: zlib$1.constants.BROTLI_OPERATION_FLUSH,
114563
+ finishFlush: zlib$1.constants.BROTLI_OPERATION_FLUSH
114245
114564
  }));
114246
114565
  } else if (coding === "zstd" && hasZstd) {
114247
- decoders.push(zlib.createZstdDecompress({
114248
- flush: zlib.constants.ZSTD_e_continue,
114249
- finishFlush: zlib.constants.ZSTD_e_end
114566
+ decoders.push(zlib$1.createZstdDecompress({
114567
+ flush: zlib$1.constants.ZSTD_e_continue,
114568
+ finishFlush: zlib$1.constants.ZSTD_e_end
114250
114569
  }));
114251
114570
  } else {
114252
114571
  decoders.length = 0;
@@ -116287,7 +116606,7 @@ function requirePermessageDeflate() {
116287
116606
  var _inflate, _options2, _maxPayloadSize;
116288
116607
  if (hasRequiredPermessageDeflate) return permessageDeflate;
116289
116608
  hasRequiredPermessageDeflate = 1;
116290
- const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = require$$3$1;
116609
+ const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = zlib;
116291
116610
  const { isValidClientWindowBits } = requireUtil$1();
116292
116611
  const { MessageSizeExceededError } = requireErrors();
116293
116612
  const tail = Buffer.from([0, 0, 255, 255]);
@@ -118574,11 +118893,17 @@ function getQueueRoute(queueName) {
118574
118893
  };
118575
118894
  }
118576
118895
  function createQueue$2(config2) {
118577
- const httpAgent = new undiciExports.Agent({
118896
+ const agentOptions = {
118578
118897
  headersTimeout: 0,
118579
118898
  connections: 1e3,
118580
- keepAliveTimeout: 3e4
118581
- });
118899
+ keepAliveTimeout: 3e4,
118900
+ bodyTimeout: 3e5
118901
+ };
118902
+ const nodeHttpAgents = isNodeHttpEnabled() ? createNodeHttpAgents({
118903
+ maxSockets: agentOptions.connections,
118904
+ keepAliveMs: agentOptions.keepAliveTimeout
118905
+ }) : void 0;
118906
+ const httpAgent = nodeHttpAgents ? void 0 : new undiciExports.Agent(agentOptions);
118582
118907
  const transport = new TypedJsonTransport();
118583
118908
  const generateId2 = monotonicFactory();
118584
118909
  const semaphore = new libExports.Sema(WORKFLOW_LOCAL_QUEUE_CONCURRENCY);
@@ -118634,13 +118959,24 @@ function createQueue$2(config2) {
118634
118959
  response2 = await directHandler(req);
118635
118960
  } else {
118636
118961
  const baseUrl = await resolveBaseUrl$1(config2);
118637
- response2 = await fetch(createWorkflowUrl(baseUrl, { type: pathname }), {
118962
+ const url2 = createWorkflowUrl(baseUrl, { type: pathname });
118963
+ response2 = nodeHttpAgents ? await nodeHttpFetch(url2, {
118638
118964
  method: "POST",
118639
- duplex: "half",
118640
- dispatcher: httpAgent,
118641
- headers: headers2,
118642
- body: body2
118643
- });
118965
+ headers: new Headers(headers2),
118966
+ body: body2,
118967
+ agents: nodeHttpAgents,
118968
+ headersTimeoutMs: agentOptions.headersTimeout,
118969
+ bodyTimeoutMs: agentOptions.bodyTimeout
118970
+ }) : (
118971
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- undici v7 dispatcher types don't match @types/node's RequestInit
118972
+ await fetch(url2, {
118973
+ method: "POST",
118974
+ duplex: "half",
118975
+ dispatcher: httpAgent,
118976
+ headers: headers2,
118977
+ body: body2
118978
+ })
118979
+ );
118644
118980
  }
118645
118981
  const text2 = await response2.text();
118646
118982
  if (response2.ok) {
@@ -118744,7 +119080,9 @@ function createQueue$2(config2) {
118744
119080
  directHandlers.set(prefix, handler);
118745
119081
  },
118746
119082
  async close() {
118747
- await httpAgent.close();
119083
+ if (nodeHttpAgents)
119084
+ destroyNodeHttpAgents(nodeHttpAgents);
119085
+ await (httpAgent == null ? void 0 : httpAgent.close());
118748
119086
  }
118749
119087
  };
118750
119088
  }
@@ -119150,8 +119488,75 @@ async function deleteAllWaitsForRun(basedir, runId) {
119150
119488
  }
119151
119489
  }
119152
119490
  function createEventsStorage(basedir, tag) {
119491
+ const maxCachedEventBytes = 4 * 1024 * 1024;
119492
+ const maxCachedEventEntries = 1e3;
119493
+ const eventCache = /* @__PURE__ */ new Map();
119494
+ const cachedEventBytes = /* @__PURE__ */ new Map();
119495
+ const cachedPathsByRunId = /* @__PURE__ */ new Map();
119496
+ let totalCachedEventBytes = 0;
119497
+ function deleteCachedEvent(eventPath) {
119498
+ const event = eventCache.get(eventPath);
119499
+ if (!event) {
119500
+ return;
119501
+ }
119502
+ eventCache.delete(eventPath);
119503
+ totalCachedEventBytes -= cachedEventBytes.get(eventPath) ?? 0;
119504
+ cachedEventBytes.delete(eventPath);
119505
+ const cachedPaths = cachedPathsByRunId.get(event.runId);
119506
+ cachedPaths == null ? void 0 : cachedPaths.delete(eventPath);
119507
+ if ((cachedPaths == null ? void 0 : cachedPaths.size) === 0) {
119508
+ cachedPathsByRunId.delete(event.runId);
119509
+ }
119510
+ }
119511
+ function clearRunCache(runId) {
119512
+ for (const cachedPath of cachedPathsByRunId.get(runId) ?? []) {
119513
+ deleteCachedEvent(cachedPath);
119514
+ }
119515
+ }
119516
+ function clearCache() {
119517
+ eventCache.clear();
119518
+ cachedEventBytes.clear();
119519
+ cachedPathsByRunId.clear();
119520
+ totalCachedEventBytes = 0;
119521
+ }
119522
+ function cacheEvent(eventPath, cachedEvent, serializedBytes) {
119523
+ if (serializedBytes > maxCachedEventBytes) {
119524
+ return;
119525
+ }
119526
+ while (eventCache.size > 0 && (eventCache.size >= maxCachedEventEntries || totalCachedEventBytes + serializedBytes > maxCachedEventBytes)) {
119527
+ const oldestPath = eventCache.keys().next().value;
119528
+ deleteCachedEvent(oldestPath);
119529
+ }
119530
+ eventCache.set(eventPath, cachedEvent);
119531
+ cachedEventBytes.set(eventPath, serializedBytes);
119532
+ totalCachedEventBytes += serializedBytes;
119533
+ const cachedPaths = cachedPathsByRunId.get(cachedEvent.runId) ?? /* @__PURE__ */ new Set();
119534
+ cachedPaths.add(eventPath);
119535
+ cachedPathsByRunId.set(cachedEvent.runId, cachedPaths);
119536
+ }
119537
+ function rememberStoredEvent(event, eventPath, serializedEvent) {
119538
+ if (event.eventType === "run_completed" || event.eventType === "run_failed" || event.eventType === "run_cancelled") {
119539
+ clearRunCache(event.runId);
119540
+ return;
119541
+ }
119542
+ const serializedBytes = Buffer.byteLength(serializedEvent);
119543
+ if (serializedBytes > maxCachedEventBytes) {
119544
+ return;
119545
+ }
119546
+ const cachedEvent = EventSchema.safeParse(JSON.parse(serializedEvent, jsonReviver));
119547
+ if (cachedEvent.success) {
119548
+ cacheEvent(eventPath, cachedEvent.data, serializedBytes);
119549
+ }
119550
+ }
119551
+ async function storeEvent(event) {
119552
+ const eventPath = taggedPath(basedir, "events", `${event.runId}-${event.eventId}`, tag);
119553
+ const serializedEvent = JSON.stringify(event, jsonReplacer, 2);
119554
+ await write(eventPath, serializedEvent);
119555
+ rememberStoredEvent(event, eventPath, serializedEvent);
119556
+ }
119153
119557
  const hookLocks = /* @__PURE__ */ new Map();
119154
119558
  return {
119559
+ clearCache,
119155
119560
  async create(runId, data, params) {
119156
119561
  if (runId != null && runId !== "") {
119157
119562
  assertSafeEntityId("runId", runId);
@@ -119222,8 +119627,7 @@ function createEventsStorage(basedir, tag) {
119222
119627
  executionContext: runInputData.executionContext
119223
119628
  }
119224
119629
  };
119225
- const createdCompositeKey = `${effectiveRunId}-${runCreatedEventId}`;
119226
- await writeJSON(taggedPath(basedir, "events", createdCompositeKey, tag), runCreatedEvent);
119630
+ await storeEvent(runCreatedEvent);
119227
119631
  currentRun = createdRun;
119228
119632
  } else {
119229
119633
  currentRun = await readJSONWithFallback(basedir, "runs", effectiveRunId, WorkflowRunSchema, tag);
@@ -119253,8 +119657,7 @@ function createEventsStorage(basedir, tag) {
119253
119657
  createdAt: now2,
119254
119658
  specVersion: effectiveSpecVersion
119255
119659
  };
119256
- const compositeKey2 = `${effectiveRunId}-${eventId}`;
119257
- await writeJSON(taggedPath(basedir, "events", compositeKey2, tag), event2);
119660
+ await storeEvent(event2);
119258
119661
  const resolveData2 = (params == null ? void 0 : params.resolveData) ?? DEFAULT_RESOLVE_DATA_OPTION$1;
119259
119662
  return {
119260
119663
  event: stripEventDataRefs(event2, resolveData2),
@@ -119603,8 +120006,7 @@ function createEventsStorage(basedir, tag) {
119603
120006
  createdAt: now2,
119604
120007
  specVersion: effectiveSpecVersion
119605
120008
  };
119606
- const compositeKey2 = `${effectiveRunId}-${eventId}`;
119607
- await writeJSON(taggedPath(basedir, "events", compositeKey2, tag), conflictEvent);
120009
+ await storeEvent(conflictEvent);
119608
120010
  const resolveData2 = (params == null ? void 0 : params.resolveData) ?? DEFAULT_RESOLVE_DATA_OPTION$1;
119609
120011
  const filteredEvent2 = stripEventDataRefs(conflictEvent, resolveData2);
119610
120012
  return {
@@ -119688,13 +120090,16 @@ function createEventsStorage(basedir, tag) {
119688
120090
  await writeJSON(taggedPath(basedir, "waits", waitCompositeKey, tag), wait2, { overwrite: true });
119689
120091
  }
119690
120092
  const compositeKey = `${effectiveRunId}-${eventId}`;
119691
- const eventPublished = await writeExclusive(taggedPath(basedir, "events", compositeKey, tag), JSON.stringify(event, jsonReplacer, 2));
120093
+ const eventPath = taggedPath(basedir, "events", compositeKey, tag);
120094
+ const serializedEvent = JSON.stringify(event, jsonReplacer, 2);
120095
+ const eventPublished = await writeExclusive(eventPath, serializedEvent);
119692
120096
  if (!eventPublished) {
119693
120097
  if (data.eventType === "hook_created" && data.correlationId) {
119694
120098
  await repairHookEntityFromPersistedEvent(basedir, effectiveRunId, data.correlationId, eventId, tag);
119695
120099
  }
119696
120100
  throw new EntityConflictError(`Event "${eventId}" already exists for run "${effectiveRunId}"`);
119697
120101
  }
120102
+ rememberStoredEvent(event, eventPath, serializedEvent);
119698
120103
  if (hook && data.eventType === "hook_created") {
119699
120104
  await writeJSON(taggedPath(basedir, "hooks", hook.hookId, tag), hook, hookEntityWriteOptions);
119700
120105
  }
@@ -119707,6 +120112,7 @@ function createEventsStorage(basedir, tag) {
119707
120112
  const allEvents = await paginatedFileSystemQuery({
119708
120113
  directory: path$3.join(basedir, "events"),
119709
120114
  schema: EventSchema,
120115
+ cachedItems: eventCache,
119710
120116
  filePrefix: `${effectiveRunId}-`,
119711
120117
  sortOrder: "asc",
119712
120118
  limit: 1e3,
@@ -119750,6 +120156,7 @@ function createEventsStorage(basedir, tag) {
119750
120156
  const result = await paginatedFileSystemQuery({
119751
120157
  directory: path$3.join(basedir, "events"),
119752
120158
  schema: EventSchema,
120159
+ cachedItems: eventCache,
119753
120160
  filePrefix: `${runId}-`,
119754
120161
  // Events in chronological order (oldest first) by default,
119755
120162
  // different from the default for other list calls.
@@ -119775,8 +120182,9 @@ function createEventsStorage(basedir, tag) {
119775
120182
  const result = await paginatedFileSystemQuery({
119776
120183
  directory: path$3.join(basedir, "events"),
119777
120184
  schema: EventSchema,
120185
+ cachedItems: eventCache,
119778
120186
  // No filePrefix - search all events
119779
- filter: (event) => event.correlationId === correlationId,
120187
+ filter: (event) => event.correlationId === correlationId && (params.runId === void 0 || event.runId === params.runId),
119780
120188
  // Events in chronological order (oldest first) by default,
119781
120189
  // different from the default for other list calls.
119782
120190
  sortOrder: ((_a3 = params.pagination) == null ? void 0 : _a3.sortOrder) ?? "asc",
@@ -119901,7 +120309,8 @@ function createStorage$1(basedir, tag) {
119901
120309
  runs: instrumentObject$1("world.runs", runs),
119902
120310
  steps: instrumentObject$1("world.steps", steps),
119903
120311
  events: instrumentObject$1("world.events", events2),
119904
- hooks: instrumentObject$1("world.hooks", hooks)
120312
+ hooks: instrumentObject$1("world.hooks", hooks),
120313
+ clearCache: () => events2.clearCache()
119905
120314
  };
119906
120315
  }
119907
120316
  const monotonicUlid = monotonicFactory(() => Math.random());
@@ -120281,8 +120690,8 @@ function createLocalWorld(args) {
120281
120690
  const mergedConfig = { ...config.value, ...definedArgs };
120282
120691
  const tag = mergedConfig.tag;
120283
120692
  const queue = createQueue$2(mergedConfig);
120284
- const storage = createStorage$1(mergedConfig.dataDir, tag);
120285
- const recoverActiveRuns = mergedConfig.recoverActiveRuns ?? true;
120693
+ const { clearCache: clearStorageCache, ...storage } = createStorage$1(mergedConfig.dataDir, tag);
120694
+ const recoverActiveRuns = resolveRecoverActiveRuns(mergedConfig);
120286
120695
  return {
120287
120696
  specVersion: SPEC_VERSION_CURRENT,
120288
120697
  ...queue,
@@ -120309,14 +120718,16 @@ function createLocalWorld(args) {
120309
120718
  await reenqueueActiveRuns(recoveryRuns, queue.queue, "world-local");
120310
120719
  },
120311
120720
  async close() {
120721
+ clearStorageCache();
120312
120722
  await queue.close();
120313
120723
  },
120314
120724
  async clear() {
120725
+ clearStorageCache();
120315
120726
  if (tag) {
120316
120727
  const basedir = mergedConfig.dataDir;
120317
120728
  const hooksDir = path$3.join(basedir, "hooks");
120318
120729
  const taggedHookFiles = await listTaggedFiles(hooksDir, tag);
120319
- const { HookSchema: HookSchema2 } = await import("./index-Bq9UALYe.js");
120730
+ const { HookSchema: HookSchema2 } = await import("./index-Ctx7nEpR.js");
120320
120731
  await Promise.all(taggedHookFiles.map(async (hookFile) => {
120321
120732
  const hook = await readJSON(path$3.join(hooksDir, hookFile), HookSchema2);
120322
120733
  if (hook == null ? void 0 : hook.token) {
@@ -120345,6 +120756,7 @@ function createLocalWorld(args) {
120345
120756
  })));
120346
120757
  clearCreatedFilesCache();
120347
120758
  } else {
120759
+ clearCreatedFilesCache();
120348
120760
  await rm(mergedConfig.dataDir, { recursive: true, force: true });
120349
120761
  await initDataDir(mergedConfig.dataDir);
120350
120762
  }
@@ -120354,6 +120766,7 @@ function createLocalWorld(args) {
120354
120766
  let _dispatcher;
120355
120767
  let _streamDispatcher;
120356
120768
  let _streamCloseDispatcher;
120769
+ let _nodeHttpAgents;
120357
120770
  const DEFAULT_HEADERS_TIMEOUT_MS = 3e4;
120358
120771
  const DEFAULT_BODY_TIMEOUT_MS = 3e4;
120359
120772
  function envTimeoutMs(name2, fallback) {
@@ -120385,6 +120798,10 @@ function getBaseAgentOptions() {
120385
120798
  bodyTimeout: envTimeoutMs("WORKFLOW_VERCEL_BODY_TIMEOUT_MS", DEFAULT_BODY_TIMEOUT_MS)
120386
120799
  };
120387
120800
  }
120801
+ function getNodeHttpPhaseTimeouts() {
120802
+ const { headersTimeout, bodyTimeout } = getBaseAgentOptions();
120803
+ return { headersTimeoutMs: headersTimeout, bodyTimeoutMs: bodyTimeout };
120804
+ }
120388
120805
  const H2_MAX_IN_FLIGHT_STREAMS = 100;
120389
120806
  const H2_STREAM_WINDOW_BYTES = 4 * 1024 * 1024;
120390
120807
  const H2_CONNECTION_WINDOW_BYTES = 16 * 1024 * 1024;
@@ -120556,17 +120973,37 @@ const eventsRecycler = createDispatcherRecycler(() => createEventsDispatcher(),
120556
120973
  function noteEventsTransportOutcome(dispatcher2, error2) {
120557
120974
  eventsRecycler.note(dispatcher2, error2);
120558
120975
  }
120976
+ function resolveDispatcher(config2, buildDefault) {
120977
+ if (config2 == null ? void 0 : config2.dispatcher)
120978
+ return config2.dispatcher;
120979
+ return isNodeHttpEnabled() ? void 0 : buildDefault();
120980
+ }
120981
+ function getNodeHttpAgents(config2) {
120982
+ if (config2 == null ? void 0 : config2.dispatcher)
120983
+ return void 0;
120984
+ if (!isNodeHttpEnabled())
120985
+ return void 0;
120986
+ const baseOptions = getBaseAgentOptions();
120987
+ _nodeHttpAgents ?? (_nodeHttpAgents = createNodeHttpAgents({
120988
+ maxSockets: baseOptions.connections,
120989
+ keepAliveMs: baseOptions.keepAliveTimeout
120990
+ }));
120991
+ return _nodeHttpAgents;
120992
+ }
120559
120993
  function getDispatcher(config2) {
120994
+ return resolveDispatcher(config2, getDefaultDispatcher);
120995
+ }
120996
+ function getQueueDispatcher(config2) {
120560
120997
  return (config2 == null ? void 0 : config2.dispatcher) ?? getDefaultDispatcher();
120561
120998
  }
120562
120999
  function getEventsDispatcher(config2) {
120563
- return (config2 == null ? void 0 : config2.dispatcher) ?? eventsRecycler.get();
121000
+ return resolveDispatcher(config2, () => eventsRecycler.get());
120564
121001
  }
120565
121002
  function getStreamDispatcher(config2) {
120566
- return (config2 == null ? void 0 : config2.dispatcher) ?? getDefaultStreamDispatcher();
121003
+ return resolveDispatcher(config2, getDefaultStreamDispatcher);
120567
121004
  }
120568
121005
  function getStreamCloseDispatcher(config2) {
120569
- return (config2 == null ? void 0 : config2.dispatcher) ?? getDefaultStreamCloseDispatcher();
121006
+ return resolveDispatcher(config2, getDefaultStreamCloseDispatcher);
120570
121007
  }
120571
121008
  function createEventsDispatcher(agentOverrides) {
120572
121009
  const h2 = h2EventsEnabled();
@@ -120717,8 +121154,8 @@ function requireGetVercelOidcToken() {
120717
121154
  }
120718
121155
  try {
120719
121156
  const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
120720
- await import("./token-util-CEKv99vM.js").then((n) => n.t),
120721
- await import("./token-BSJJ1ZPx.js").then((n) => n.t)
121157
+ await import("./token-util-u3-O6-cJ.js").then((n) => n.t),
121158
+ await import("./token-B9AfalZB.js").then((n) => n.t)
120722
121159
  ]);
120723
121160
  if (!token || isExpired(getTokenPayload(token), options == null ? void 0 : options.expirationBufferMs)) {
120724
121161
  await refreshToken(options);
@@ -121351,6 +121788,7 @@ const RpcService = SemanticConvention("rpc.service");
121351
121788
  const RpcMethod = SemanticConvention("rpc.method");
121352
121789
  const WorkflowRunId = SemanticConvention("workflow.run.id");
121353
121790
  const StepId = SemanticConvention("step.id");
121791
+ const WorkflowHttpTransport = SemanticConvention("workflow.http.transport");
121354
121792
  const REQUEST_TIMEOUT_MS = 6e4;
121355
121793
  const HTTP_DEBUG_ENABLED = typeof process !== "undefined" && typeof process.env.DEBUG === "string" && (process.env.DEBUG.includes("workflow:") || process.env.DEBUG === "*");
121356
121794
  const DIAGNOSTIC_HEADERS = [
@@ -121456,7 +121894,22 @@ async function instrumentedFetch(opts) {
121456
121894
  const start2 = Date.now();
121457
121895
  let response2;
121458
121896
  try {
121459
- response2 = await fetch(url2, {
121897
+ const nodeAgents = dispatcher2 ? void 0 : getNodeHttpAgents();
121898
+ span == null ? void 0 : span.setAttributes({
121899
+ ...WorkflowHttpTransport(nodeAgents ? "node-http" : "undici")
121900
+ });
121901
+ response2 = nodeAgents ? await nodeHttpFetch(url2, {
121902
+ method,
121903
+ headers: headers2,
121904
+ body: body2,
121905
+ signal,
121906
+ agents: nodeAgents,
121907
+ // Same per-phase deadlines the undici agents are configured
121908
+ // with: without these the node:http path arms no stalled-socket
121909
+ // deadline, and a `timeoutMs: null` caller would have no deadline
121910
+ // at all.
121911
+ ...getNodeHttpPhaseTimeouts()
121912
+ }) : await fetch(url2, {
121460
121913
  method,
121461
121914
  headers: headers2,
121462
121915
  body: body2,
@@ -126189,7 +126642,7 @@ var QueueClient = class {
126189
126642
  setApi(this, new ApiClient({ ...options, region }));
126190
126643
  }
126191
126644
  };
126192
- const version = "4.6.2";
126645
+ const version = "4.7.1";
126193
126646
  const IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
126194
126647
  const MAX_BODY_PARSE_RETRIES = 2;
126195
126648
  const BODY_PARSE_RETRY_BASE_MS = 100;
@@ -126205,7 +126658,8 @@ const TRANSIENT_TRANSPORT_ERROR_CODES = /* @__PURE__ */ new Set([
126205
126658
  "ECONNREFUSED",
126206
126659
  "ENOTFOUND",
126207
126660
  "EAI_AGAIN",
126208
- "EPIPE"
126661
+ "EPIPE",
126662
+ "ETIMEDOUT"
126209
126663
  ]);
126210
126664
  function getTransientTransportCode(error2) {
126211
126665
  let current = error2;
@@ -126324,7 +126778,7 @@ async function getHttpConfig(config2) {
126324
126778
  return { baseUrl, headers: headers2, usingProxy };
126325
126779
  }
126326
126780
  async function makeRequest({ endpoint, options = {}, config: config2 = {}, schema, data, onResponse, retryConnectTimeout = false }) {
126327
- const method = options.method || "GET";
126781
+ const method = (options.method || "GET").toUpperCase();
126328
126782
  const { baseUrl, headers: headers2 } = await getHttpConfig(config2);
126329
126783
  const url2 = `${baseUrl}${endpoint}`;
126330
126784
  return trace(`http ${method}`, { kind: await getSpanKind("CLIENT") }, async (span) => {
@@ -126341,23 +126795,32 @@ async function makeRequest({ endpoint, options = {}, config: config2 = {}, schem
126341
126795
  headers2.set("Content-Type", "application/cbor");
126342
126796
  body2 = encode(data);
126343
126797
  }
126344
- const canRetryRead = IDEMPOTENT_METHODS.has(method.toUpperCase());
126798
+ const canRetryRead = IDEMPOTENT_METHODS.has(method);
126345
126799
  let parseResult;
126346
126800
  let responseDiagnostics = "";
126347
126801
  for (let attempt = 0; ; attempt++) {
126348
126802
  headers2.set("X-Request-Time", Date.now().toString());
126349
126803
  const timeoutSignal = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
126350
126804
  const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;
126351
- const request2 = new Request(url2, {
126352
- ...options,
126353
- body: body2,
126354
- headers: headers2,
126355
- signal
126356
- });
126357
126805
  const fetchStart = Date.now();
126358
126806
  let response2;
126359
126807
  try {
126360
- response2 = await fetch(request2, {
126808
+ const nodeAgents = getNodeHttpAgents(config2);
126809
+ span == null ? void 0 : span.setAttributes({
126810
+ ...WorkflowHttpTransport(nodeAgents ? "node-http" : "undici")
126811
+ });
126812
+ response2 = nodeAgents ? await nodeHttpFetch(url2, {
126813
+ method,
126814
+ headers: headers2,
126815
+ body: body2,
126816
+ signal,
126817
+ agents: nodeAgents,
126818
+ // Same per-phase deadlines the undici agents are configured
126819
+ // with: without these the node:http path arms no stalled-socket
126820
+ // deadline.
126821
+ ...getNodeHttpPhaseTimeouts()
126822
+ }) : await fetch(new Request(url2, { ...options, body: body2, headers: headers2, signal }), {
126823
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- undici v7 dispatcher types don't match @types/node's RequestInit
126361
126824
  dispatcher: getDispatcher(config2)
126362
126825
  });
126363
126826
  } catch (error2) {
@@ -126374,10 +126837,10 @@ async function makeRequest({ endpoint, options = {}, config: config2 = {}, schem
126374
126837
  await new Promise((resolve2) => setTimeout(resolve2, BODY_PARSE_RETRY_BASE_MS));
126375
126838
  continue;
126376
126839
  }
126377
- const transportError = new WorkflowWorldError(`${method} ${endpoint} transport failure after ${elapsed}ms (${transportCode})`, { url: url2, code: "TRANSPORT", cause: error2 });
126840
+ const transportError2 = new WorkflowWorldError(`${method} ${endpoint} transport failure after ${elapsed}ms (${transportCode})`, { url: url2, code: "TRANSPORT", cause: error2 });
126378
126841
  span == null ? void 0 : span.setAttributes({ ...ErrorType("TRANSPORT") });
126379
- (_b2 = span == null ? void 0 : span.recordException) == null ? void 0 : _b2.call(span, transportError);
126380
- throw transportError;
126842
+ (_b2 = span == null ? void 0 : span.recordException) == null ? void 0 : _b2.call(span, transportError2);
126843
+ throw transportError2;
126381
126844
  }
126382
126845
  throw error2;
126383
126846
  }
@@ -126389,9 +126852,9 @@ async function makeRequest({ endpoint, options = {}, config: config2 = {}, schem
126389
126852
  });
126390
126853
  if (!response2.ok) {
126391
126854
  const errorData = await parseResponseBody(response2).then((r2) => r2.data).catch(() => ({}));
126392
- logCurlRepro(request2.method, url2, headers2);
126855
+ logCurlRepro(method, url2, headers2);
126393
126856
  const retryAfter = parseRetryAfter(response2.headers.get("Retry-After"));
126394
- const defaultMessage = (errorData.message || `${request2.method} ${endpoint} -> HTTP ${response2.status}: ${response2.statusText}`) + responseDiagnostics;
126857
+ const defaultMessage = (errorData.message || `${method} ${endpoint} -> HTTP ${response2.status}: ${response2.statusText}`) + responseDiagnostics;
126395
126858
  const error2 = errorForResponse(response2.status, defaultMessage, {
126396
126859
  url: url2,
126397
126860
  code: errorData.code,
@@ -126580,7 +127043,7 @@ function createQueue$1(config2) {
126580
127043
  const dualTransport = new DualTransport();
126581
127044
  const clientOptions = {
126582
127045
  region,
126583
- dispatcher: getDispatcher(config2),
127046
+ dispatcher: getQueueDispatcher(config2),
126584
127047
  transport: dualTransport,
126585
127048
  ...usingProxy && {
126586
127049
  // final path will be /queues-proxy/api/v3/topic/...
@@ -127156,10 +127619,12 @@ async function getWorkflowRunEventsV4(runId, params = {}, config2) {
127156
127619
  const url2 = `${baseUrl}/v4/runs/${encodeURIComponent(runId)}/events` + paginationToQuery(params);
127157
127620
  return consumeListFrameStream(url2, headers2, config2, "listEvents");
127158
127621
  }
127159
- async function getEventsByCorrelationIdV4(correlationId, params = {}, config2) {
127622
+ async function getEventsByCorrelationIdV4(correlationId, params = {}, config2, runId) {
127160
127623
  const { baseUrl, headers: headers2 } = await getHttpConfig(config2);
127161
127624
  const sp = new URLSearchParams();
127162
127625
  sp.set("correlationId", correlationId);
127626
+ if (runId !== void 0)
127627
+ sp.set("runId", runId);
127163
127628
  appendListParams(sp, params);
127164
127629
  const url2 = `${baseUrl}/v4/events?${sp.toString()}`;
127165
127630
  return consumeListFrameStream(url2, headers2, config2, "listEventsByCorrelationId");
@@ -127544,10 +128009,13 @@ async function getWorkflowRunEvents(params, config2) {
127544
128009
  sortOrder: pagination == null ? void 0 : pagination.sortOrder,
127545
128010
  remoteRefBehavior: resolveData === "none" ? "lazy" : "resolve"
127546
128011
  };
127547
- const result = await ("correlationId" in params ? getEventsByCorrelationIdV4(params.correlationId, wirePagination, config2) : getWorkflowRunEventsV4(params.runId, wirePagination, config2));
128012
+ const runId = "correlationId" in params ? params.runId : void 0;
128013
+ const result = await ("correlationId" in params ? getEventsByCorrelationIdV4(params.correlationId, wirePagination, config2, runId) : getWorkflowRunEventsV4(params.runId, wirePagination, config2));
127548
128014
  const events2 = result.events.map((listed) => buildEventFromV4(listed.event, listed.body, resolveData));
127549
128015
  return {
127550
- data: events2,
128016
+ // Older servers may ignore the runId query parameter. Keep the client
128017
+ // filter as a compatibility guard until every server honors it.
128018
+ data: runId !== void 0 ? events2.filter((event) => event.runId === runId) : events2,
127551
128019
  cursor: result.next ?? null,
127552
128020
  hasMore: Boolean(result.next)
127553
128021
  };
@@ -128696,7 +129164,7 @@ class WorkflowServerReadableStream extends ReadableStream {
128696
129164
  _reader = new WeakMap();
128697
129165
  const FRAMED_STREAM_MAX_RECONNECTS = 50;
128698
129166
  const FRAMED_STREAM_MAX_TOTAL_RECONNECTS = 1e3;
128699
- function createReconnectingFramedStream(name2, startIndex) {
129167
+ function createReconnectingFramedStream(runId, name2, startIndex) {
128700
129168
  const reconnectSupported = startIndex === void 0 || startIndex >= 0;
128701
129169
  let currentStartIndex = startIndex ?? 0;
128702
129170
  let consumedFrames = 0;
@@ -128710,6 +129178,15 @@ function createReconnectingFramedStream(name2, startIndex) {
128710
129178
  const stream = await world.readFromStream(name2, effectiveStartIndex);
128711
129179
  reader = stream.getReader();
128712
129180
  }
129181
+ async function isVerifiedComplete() {
129182
+ try {
129183
+ const world = getWorld();
129184
+ const info = await world.getStreamInfo(name2, runId);
129185
+ return info.done && currentStartIndex + consumedFrames > info.tailIndex;
129186
+ } catch {
129187
+ return true;
129188
+ }
129189
+ }
128713
129190
  async function reconnect() {
128714
129191
  if (reader) {
128715
129192
  await reader.cancel().catch(() => {
@@ -128764,6 +129241,15 @@ function createReconnectingFramedStream(name2, startIndex) {
128764
129241
  }
128765
129242
  if (result.done || !result.value) {
128766
129243
  reader = void 0;
129244
+ if (reconnectSupported && !await isVerifiedComplete()) {
129245
+ try {
129246
+ await reconnect();
129247
+ } catch (reconnectErr) {
129248
+ controller.error(reconnectErr);
129249
+ return;
129250
+ }
129251
+ continue;
129252
+ }
128767
129253
  controller.close();
128768
129254
  return;
128769
129255
  }
@@ -129291,7 +129777,7 @@ function getExternalRevivers(global2 = globalThis, ops, runId, cryptoKey) {
129291
129777
  pollReadableLock(userReadable, state);
129292
129778
  return userReadable;
129293
129779
  } else {
129294
- const readable2 = createReconnectingFramedStream(value.name, value.startIndex);
129780
+ const readable2 = createReconnectingFramedStream(runId, value.name, value.startIndex);
129295
129781
  const transform2 = getDeserializeStream(getExternalRevivers(global2, ops, runId, cryptoKey), cryptoKey);
129296
129782
  const state = createFlushableState();
129297
129783
  ops.push(state.promise);
@@ -129678,6 +130164,10 @@ async function dehydrateStepReturnValue(value, runId, key, ops = [], global2 = g
129678
130164
  throw new WorkflowRuntimeError(formatSerializationError("step return value", error2), { slug: "serialization-failed", cause: error2 });
129679
130165
  }
129680
130166
  }
130167
+ const UNSERIALIZABLE_FLAG = "__workflowUnserializableStepInput";
130168
+ function isUnserializableStepInputPlaceholder(hydratedInput) {
130169
+ return typeof hydratedInput === "object" && hydratedInput !== null && hydratedInput[UNSERIALIZABLE_FLAG] === true;
130170
+ }
129681
130171
  var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
129682
130172
  var intToChar = new Uint8Array(64);
129683
130173
  var charToInt = new Uint8Array(128);
@@ -133292,6 +133782,9 @@ createQueueHandler(stepPrefix, async (message_, metadata) => {
133292
133782
  let userCodeFailed = false;
133293
133783
  const executionStartTime = Date.now();
133294
133784
  try {
133785
+ if (isUnserializableStepInputPlaceholder(hydratedInput)) {
133786
+ throw new FatalError(formatSerializationError("step arguments", void 0));
133787
+ }
133295
133788
  result = await trace$2("step.execute", {}, async () => {
133296
133789
  return await contextStorage.run({
133297
133790
  stepMetadata: {
@@ -134079,11 +134572,18 @@ async function fetchEvent(worldEnv, runId, eventId, resolveData = "all") {
134079
134572
  }
134080
134573
  }
134081
134574
  async function fetchEventsByCorrelationId(worldEnv, correlationId, params) {
134082
- const { cursor, sortOrder = "asc", limit = 100, withData = false } = params;
134575
+ const {
134576
+ runId,
134577
+ cursor,
134578
+ sortOrder = "asc",
134579
+ limit = 100,
134580
+ withData = false
134581
+ } = params;
134083
134582
  try {
134084
134583
  const world = await getWorldFromEnv(worldEnv);
134085
134584
  const result = await world.events.listByCorrelationId({
134086
134585
  correlationId,
134586
+ runId,
134087
134587
  pagination: { cursor, limit, sortOrder },
134088
134588
  resolveData: withData ? "all" : "none"
134089
134589
  });
@@ -154541,6 +155041,7 @@ function useEventsListData(env2, runId, options = {}) {
154541
155041
  }
154542
155042
  const { error: fetchError, result } = await unwrapServerActionResult(
154543
155043
  fetchEventsByCorrelationId$1(env2, id2, {
155044
+ runId,
154544
155045
  cursor: nextCursor,
154545
155046
  sortOrder,
154546
155047
  limit: 100,
@@ -155297,7 +155798,7 @@ const route4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProper
155297
155798
  __proto__: null,
155298
155799
  loader
155299
155800
  }, Symbol.toStringTag, { value: "Module" }));
155300
- const serverManifest = { "entry": { "module": "/assets/entry.client-C_C46bD6.js", "imports": ["/assets/index-BsV8i_Jn.js"], "css": [] }, "routes": { "root": { "id": "root", "parentId": void 0, "path": "", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": true, "module": "/assets/root-BxnaECGo.js", "imports": ["/assets/index-BsV8i_Jn.js", "/assets/mermaid-3ZIDBTTL-Bp6ZST9_.js"], "css": ["/assets/root-BOS11TzD.css", "/assets/mermaid-3ZIDBTTL-yyHEMZs4.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/home": { "id": "routes/home", "parentId": "root", "path": void 0, "index": true, "caseSensitive": void 0, "hasAction": false, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": false, "module": "/assets/home-Blj6TeEE.js", "imports": ["/assets/index-BsV8i_Jn.js", "/assets/workflow-graph-viewer-C6PWoIIU.js", "/assets/mermaid-3ZIDBTTL-Bp6ZST9_.js", "/assets/index-DZSXezpI.js"], "css": ["/assets/workflow-graph-viewer-yls6qlc0.css", "/assets/mermaid-3ZIDBTTL-yyHEMZs4.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/run-detail": { "id": "routes/run-detail", "parentId": "root", "path": "run/:runId", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": false, "module": "/assets/run-detail-Cbuf5qtv.js", "imports": ["/assets/index-BsV8i_Jn.js", "/assets/workflow-graph-viewer-C6PWoIIU.js", "/assets/mermaid-3ZIDBTTL-Bp6ZST9_.js", "/assets/encryption-BRhjWsZh.js", "/assets/index-DZSXezpI.js"], "css": ["/assets/workflow-graph-viewer-yls6qlc0.css", "/assets/mermaid-3ZIDBTTL-yyHEMZs4.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/api.rpc": { "id": "routes/api.rpc", "parentId": "root", "path": "api/rpc", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": false, "hasErrorBoundary": false, "module": "/assets/api.rpc-l0sNRNKZ.js", "imports": [], "css": [], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/api.stream.$streamId": { "id": "routes/api.stream.$streamId", "parentId": "root", "path": "api/stream/:streamId", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": false, "hasErrorBoundary": false, "module": "/assets/api.stream._streamId-l0sNRNKZ.js", "imports": [], "css": [], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 } }, "url": "/assets/manifest-0285e96f.js", "version": "0285e96f", "sri": void 0 };
155801
+ const serverManifest = { "entry": { "module": "/assets/entry.client-C_C46bD6.js", "imports": ["/assets/index-BsV8i_Jn.js"], "css": [] }, "routes": { "root": { "id": "root", "parentId": void 0, "path": "", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": true, "module": "/assets/root-BxnaECGo.js", "imports": ["/assets/index-BsV8i_Jn.js", "/assets/mermaid-3ZIDBTTL-Bp6ZST9_.js"], "css": ["/assets/root-BOS11TzD.css", "/assets/mermaid-3ZIDBTTL-yyHEMZs4.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/home": { "id": "routes/home", "parentId": "root", "path": void 0, "index": true, "caseSensitive": void 0, "hasAction": false, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": false, "module": "/assets/home-Blj6TeEE.js", "imports": ["/assets/index-BsV8i_Jn.js", "/assets/workflow-graph-viewer-C6PWoIIU.js", "/assets/mermaid-3ZIDBTTL-Bp6ZST9_.js", "/assets/index-DZSXezpI.js"], "css": ["/assets/workflow-graph-viewer-yls6qlc0.css", "/assets/mermaid-3ZIDBTTL-yyHEMZs4.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/run-detail": { "id": "routes/run-detail", "parentId": "root", "path": "run/:runId", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": false, "module": "/assets/run-detail-1KdCfmI4.js", "imports": ["/assets/index-BsV8i_Jn.js", "/assets/workflow-graph-viewer-C6PWoIIU.js", "/assets/mermaid-3ZIDBTTL-Bp6ZST9_.js", "/assets/encryption-BRhjWsZh.js", "/assets/index-DZSXezpI.js"], "css": ["/assets/workflow-graph-viewer-yls6qlc0.css", "/assets/mermaid-3ZIDBTTL-yyHEMZs4.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/api.rpc": { "id": "routes/api.rpc", "parentId": "root", "path": "api/rpc", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": false, "hasErrorBoundary": false, "module": "/assets/api.rpc-l0sNRNKZ.js", "imports": [], "css": [], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/api.stream.$streamId": { "id": "routes/api.stream.$streamId", "parentId": "root", "path": "api/stream/:streamId", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": false, "hasErrorBoundary": false, "module": "/assets/api.stream._streamId-l0sNRNKZ.js", "imports": [], "css": [], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 } }, "url": "/assets/manifest-d91343fe.js", "version": "d91343fe", "sri": void 0 };
155301
155802
  const assetsBuildDirectory = "build/client";
155302
155803
  const basename = "/";
155303
155804
  const future = { "unstable_optimizeDeps": false, "unstable_subResourceIntegrity": false, "unstable_trailingSlashAwareDataRequests": false, "unstable_previewServerPrerendering": false, "v8_middleware": false, "v8_splitRouteModules": false, "v8_viteEnvironmentApi": false };
@@ -155366,61 +155867,65 @@ const serverBuild = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineP
155366
155867
  ssr
155367
155868
  }, Symbol.toStringTag, { value: "Module" }));
155368
155869
  export {
155369
- Qe as $,
155370
- isTerminalRunEventType as A,
155870
+ validateUlidTimestamp as $,
155871
+ envFlag as A,
155371
155872
  BaseEventSchema as B,
155372
- isTerminalStepStatus as C,
155873
+ getQueueTopicPrefix as C,
155373
155874
  DEFAULT_TIMESTAMP_THRESHOLD_FUTURE_MS as D,
155374
155875
  EVENT_DATA_REF_FIELDS as E,
155375
- isTerminalWorkflowRunStatus as F,
155376
- parseQueueName as G,
155876
+ isLegacySpecVersion as F,
155877
+ isNodeHttpEnabled as G,
155377
155878
  HookSchema as H,
155378
- reenqueueActiveRuns as I,
155379
- requiresNewerWorld as J,
155380
- resolveQueueNamespace as K,
155879
+ isTerminalRunEventType as I,
155880
+ isTerminalStepStatus as J,
155881
+ isTerminalWorkflowRunStatus as K,
155381
155882
  LegacySerializedDataSchemaV1 as L,
155382
155883
  MessageId as M,
155383
155884
  Nt as N,
155384
- stripEventDataRefs as O,
155885
+ parseQueueName as O,
155385
155886
  PaginatedResponseSchema as P,
155386
155887
  QueuePayloadSchema as Q,
155387
155888
  RunInputSchema as R,
155388
155889
  SPEC_VERSION_CURRENT as S,
155389
155890
  TERMINAL_RUN_EVENT_TYPES as T,
155390
- ulidToDate as U,
155891
+ reenqueueActiveRuns as U,
155391
155892
  ValidQueueName as V,
155392
155893
  WaitSchema as W,
155393
- validateUlidTimestamp as X,
155394
- R as Y,
155395
- Ks as Z,
155396
- jsxRuntimeExports as _,
155894
+ requiresNewerWorld as X,
155895
+ resolveQueueNamespace as Y,
155896
+ stripEventDataRefs as Z,
155897
+ ulidToDate as _,
155397
155898
  DEFAULT_TIMESTAMP_THRESHOLD_PAST_MS as a,
155398
- requireTokenUtil as a0,
155399
- requireTokenError as a1,
155400
- serverBuild as a2,
155899
+ R as a0,
155900
+ Ks as a1,
155901
+ jsxRuntimeExports as a2,
155902
+ Qe as a3,
155903
+ requireTokenUtil as a4,
155904
+ requireTokenError as a5,
155905
+ serverBuild as a6,
155401
155906
  EventSchema as b,
155402
155907
  EventTypeSchema as c,
155403
155908
  HealthCheckPayloadSchema as d,
155404
155909
  HookCreatedEventSchema as e,
155405
- QueuePrefix as f,
155406
- SPEC_VERSION_LEGACY as g,
155407
- SPEC_VERSION_SUPPORTS_CBOR_QUEUE_TRANSPORT as h,
155408
- SPEC_VERSION_SUPPORTS_EVENT_SOURCING as i,
155409
- SerializedDataSchema as j,
155410
- StepInvokePayloadSchema as k,
155411
- StepSchema as l,
155412
- StepStatusSchema as m,
155413
- StructuredErrorSchema as n,
155414
- TERMINAL_STEP_STATUSES as o,
155415
- TERMINAL_WORKFLOW_RUN_STATUSES as p,
155416
- TerminalRunEventTypeSchema as q,
155417
- TerminalStepStatusSchema as r,
155418
- TerminalWorkflowRunStatusSchema as s,
155419
- WaitStatusSchema as t,
155420
- WorkflowInvokePayloadSchema as u,
155421
- WorkflowRunBaseSchema as v,
155422
- WorkflowRunSchema as w,
155423
- WorkflowRunStatusSchema as x,
155424
- getQueueTopicPrefix as y,
155425
- isLegacySpecVersion as z
155910
+ NODE_HTTP_DEFAULT as f,
155911
+ NODE_HTTP_ENV_VAR as g,
155912
+ QueuePrefix as h,
155913
+ SPEC_VERSION_LEGACY as i,
155914
+ SPEC_VERSION_SUPPORTS_CBOR_QUEUE_TRANSPORT as j,
155915
+ SPEC_VERSION_SUPPORTS_EVENT_SOURCING as k,
155916
+ SerializedDataSchema as l,
155917
+ StepInvokePayloadSchema as m,
155918
+ StepSchema as n,
155919
+ StepStatusSchema as o,
155920
+ StructuredErrorSchema as p,
155921
+ TERMINAL_STEP_STATUSES as q,
155922
+ TERMINAL_WORKFLOW_RUN_STATUSES as r,
155923
+ TerminalRunEventTypeSchema as s,
155924
+ TerminalStepStatusSchema as t,
155925
+ TerminalWorkflowRunStatusSchema as u,
155926
+ WaitStatusSchema as v,
155927
+ WorkflowInvokePayloadSchema as w,
155928
+ WorkflowRunBaseSchema as x,
155929
+ WorkflowRunSchema as y,
155930
+ WorkflowRunStatusSchema as z
155426
155931
  };