@workflow/web 4.1.0-beta.37 → 4.1.0-beta.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (20) hide show
  1. package/build/client/assets/{highlighted-body-B3W2YXNL-BO6bNJzI.js → highlighted-body-B3W2YXNL-BlI_3W94.js} +1 -1
  2. package/build/client/assets/{home-bWDrLREI.js → home-B4MMr7LP.js} +1 -1
  3. package/build/client/assets/manifest-ef94afe1.js +1 -0
  4. package/build/client/assets/{mermaid-3ZIDBTTL-CJ6mkUFN.js → mermaid-3ZIDBTTL-BhkyG8Sq.js} +7 -7
  5. package/build/client/assets/{root-Ckv-c9_b.js → root-B2fanH6r.js} +1 -1
  6. package/build/client/assets/run-detail-D40YBNgh.js +41 -0
  7. package/build/client/assets/{use-workflow-graph-JKiMb5g6.js → use-workflow-graph-D6xsvBGu.js} +1 -1
  8. package/build/server/assets/{app-CatvtWxS.js → app-YwmyVuwT.js} +1 -1
  9. package/build/server/assets/{highlighted-body-B3W2YXNL-DoOhy3wX.js → highlighted-body-B3W2YXNL-Dqsnck2u.js} +3 -3
  10. package/build/server/assets/{mermaid-3ZIDBTTL-uuxw6-ur.js → mermaid-3ZIDBTTL-mfJ74Epj.js} +3 -3
  11. package/build/server/assets/{server-build-XXW48t5z.js → server-build-B3ijdJBL.js} +370 -340
  12. package/build/server/assets/{token-C58qysN7.js → token-CWWXwMh8.js} +3 -3
  13. package/build/server/assets/{token-CLFHo1Az.js → token-DJXheGCg.js} +2 -2
  14. package/build/server/assets/{token-util-C6iVpF77.js → token-util-CvLiUUQD.js} +2 -2
  15. package/build/server/assets/{token-util-CbxhzlWz.js → token-util-REQ15piK.js} +1 -1
  16. package/build/server/assets/{token-util-CcopqG1U.js → token-util-l0RNhdPG.js} +2 -2
  17. package/build/server/index.js +1 -1
  18. package/package.json +6 -6
  19. package/build/client/assets/manifest-daa82ff1.js +0 -1
  20. package/build/client/assets/run-detail-EcdnCjQk.js +0 -41
@@ -14,7 +14,7 @@ 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, _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, M as Meta, L as Links, d as ScrollRestoration, e as Scripts, O as Outlet, u as useNavigate, f as useSearchParams, h as Link$1, i as useLocation, j as useParams } from "./app-CatvtWxS.js";
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, M as Meta, L as Links, d as ScrollRestoration, e as Scripts, O as Outlet, u as useNavigate, f as useSearchParams, h as Link$1, i as useLocation, j as useParams } from "./app-YwmyVuwT.js";
18
18
  import require$$0$4, { PassThrough } from "node:stream";
19
19
  import require$$0 from "util";
20
20
  import require$$1$1 from "crypto";
@@ -24,10 +24,10 @@ import minproc from "node:process";
24
24
  import path$2, { join as join$1, resolve, dirname, isAbsolute, sep } from "node:path";
25
25
  import { fileURLToPath } from "node:url";
26
26
  import { createRequire } from "module";
27
- import require$$0$8, { readdir, readlink, readFile, mkdir, access, constants as constants$5, writeFile, unlink } from "node:fs/promises";
27
+ import require$$0$8, { readdir, readlink, readFile, mkdir, access, constants as constants$5, writeFile, unlink, rm } from "node:fs/promises";
28
+ import crypto, { webcrypto } from "node:crypto";
28
29
  import require$$1$2 from "tty";
29
30
  import require$$0$1 from "os";
30
- import crypto, { webcrypto } from "node:crypto";
31
31
  import { createRequire as createRequire$1 } from "node:module";
32
32
  import { execFile } from "node:child_process";
33
33
  import require$$3, { promisify, inspect, types as types$2 } from "node:util";
@@ -64424,7 +64424,7 @@ var tn = f("block", "before:content-[counter(line)]", "before:inline-block", "be
64424
64424
  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 });
64425
64425
  var Se = reactExports.createContext({ code: "" }), de$1 = () => reactExports.useContext(Se);
64426
64426
  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 }) });
64427
- var cn$1 = /\n+$/, dn = reactExports.lazy(() => import("./highlighted-body-B3W2YXNL-DoOhy3wX.js").then((e) => ({ default: e.HighlightedCodeBlockBody }))), rt = ({ code: e, language: t, className: o, children: n, isIncomplete: s2 = false, ...r2 }) => {
64427
+ var cn$1 = /\n+$/, dn = reactExports.lazy(() => import("./highlighted-body-B3W2YXNL-Dqsnck2u.js").then((e) => ({ default: e.HighlightedCodeBlockBody }))), rt = ({ code: e, language: t, className: o, children: n, isIncomplete: s2 = false, ...r2 }) => {
64428
64428
  let i = reactExports.useMemo(() => e.replace(cn$1, ""), [e]), c = reactExports.useMemo(() => ({ bg: "transparent", fg: "inherit", tokens: i.split(`
64429
64429
  `).map((a2) => [{ content: a2, color: "inherit", bgColor: "transparent", htmlStyle: {}, offset: 0 }]) }), [i]);
64430
64430
  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 }) })] }) });
@@ -64746,7 +64746,7 @@ var Dt = ({ children: e, className: t, onDownload: o, onError: n }) => {
64746
64746
  }, []), 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] });
64747
64747
  };
64748
64748
  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 }) })] });
64749
- var Jn = reactExports.lazy(() => import("./mermaid-3ZIDBTTL-uuxw6-ur.js").then((e) => ({ default: e.Mermaid }))), Kn = /language-([^\s]+)/;
64749
+ var Jn = reactExports.lazy(() => import("./mermaid-3ZIDBTTL-mfJ74Epj.js").then((e) => ({ default: e.Mermaid }))), Kn = /language-([^\s]+)/;
64750
64750
  function ke(e, t) {
64751
64751
  if (!(e != null && e.position || t != null && t.position)) return true;
64752
64752
  if (!(e != null && e.position && (t != null && t.position))) return false;
@@ -72712,6 +72712,9 @@ async function fetchStep$1(worldEnv, runId, stepId, resolveData = "all") {
72712
72712
  async function fetchEvents$1(worldEnv, runId, params) {
72713
72713
  return rpc("fetchEvents", { worldEnv, runId, params });
72714
72714
  }
72715
+ async function fetchEvent$1(worldEnv, runId, eventId, resolveData = "all") {
72716
+ return rpc("fetchEvent", { worldEnv, runId, eventId, resolveData });
72717
+ }
72715
72718
  async function fetchEventsByCorrelationId$1(worldEnv, correlationId, params) {
72716
72719
  return rpc("fetchEventsByCorrelationId", { worldEnv, correlationId, params });
72717
72720
  }
@@ -87334,6 +87337,174 @@ const WaitSchema = object$1({
87334
87337
  updatedAt: date$2(),
87335
87338
  specVersion: number$1().optional()
87336
87339
  });
87340
+ const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
87341
+ const ENCODING_LEN = 32;
87342
+ const RANDOM_LEN = 16;
87343
+ const TIME_LEN = 10;
87344
+ const TIME_MAX = 281474976710655;
87345
+ var ULIDErrorCode;
87346
+ (function(ULIDErrorCode2) {
87347
+ ULIDErrorCode2["Base32IncorrectEncoding"] = "B32_ENC_INVALID";
87348
+ ULIDErrorCode2["DecodeTimeInvalidCharacter"] = "DEC_TIME_CHAR";
87349
+ ULIDErrorCode2["DecodeTimeValueMalformed"] = "DEC_TIME_MALFORMED";
87350
+ ULIDErrorCode2["EncodeTimeNegative"] = "ENC_TIME_NEG";
87351
+ ULIDErrorCode2["EncodeTimeSizeExceeded"] = "ENC_TIME_SIZE_EXCEED";
87352
+ ULIDErrorCode2["EncodeTimeValueMalformed"] = "ENC_TIME_MALFORMED";
87353
+ ULIDErrorCode2["PRNGDetectFailure"] = "PRNG_DETECT";
87354
+ ULIDErrorCode2["ULIDInvalid"] = "ULID_INVALID";
87355
+ ULIDErrorCode2["Unexpected"] = "UNEXPECTED";
87356
+ ULIDErrorCode2["UUIDInvalid"] = "UUID_INVALID";
87357
+ })(ULIDErrorCode || (ULIDErrorCode = {}));
87358
+ class ULIDError extends Error {
87359
+ constructor(errorCode, message2) {
87360
+ super(`${message2} (${errorCode})`);
87361
+ this.name = "ULIDError";
87362
+ this.code = errorCode;
87363
+ }
87364
+ }
87365
+ function randomChar(prng) {
87366
+ const randomPosition = Math.floor(prng() * ENCODING_LEN) % ENCODING_LEN;
87367
+ return ENCODING.charAt(randomPosition);
87368
+ }
87369
+ function replaceCharAt(str, index2, char) {
87370
+ if (index2 > str.length - 1) {
87371
+ return str;
87372
+ }
87373
+ return str.substr(0, index2) + char + str.substr(index2 + 1);
87374
+ }
87375
+ function incrementBase32(str) {
87376
+ let done = void 0, index2 = str.length, char, charIndex, output = str;
87377
+ const maxCharIndex = ENCODING_LEN - 1;
87378
+ while (!done && index2-- >= 0) {
87379
+ char = output[index2];
87380
+ charIndex = ENCODING.indexOf(char);
87381
+ if (charIndex === -1) {
87382
+ throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Incorrectly encoded string");
87383
+ }
87384
+ if (charIndex === maxCharIndex) {
87385
+ output = replaceCharAt(output, index2, ENCODING[0]);
87386
+ continue;
87387
+ }
87388
+ done = replaceCharAt(output, index2, ENCODING[charIndex + 1]);
87389
+ }
87390
+ if (typeof done === "string") {
87391
+ return done;
87392
+ }
87393
+ throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Failed incrementing string");
87394
+ }
87395
+ function decodeTime(id2) {
87396
+ if (id2.length !== TIME_LEN + RANDOM_LEN) {
87397
+ throw new ULIDError(ULIDErrorCode.DecodeTimeValueMalformed, "Malformed ULID");
87398
+ }
87399
+ const time2 = id2.substr(0, TIME_LEN).toUpperCase().split("").reverse().reduce((carry, char, index2) => {
87400
+ const encodingIndex = ENCODING.indexOf(char);
87401
+ if (encodingIndex === -1) {
87402
+ throw new ULIDError(ULIDErrorCode.DecodeTimeInvalidCharacter, `Time decode error: Invalid character: ${char}`);
87403
+ }
87404
+ return carry += encodingIndex * Math.pow(ENCODING_LEN, index2);
87405
+ }, 0);
87406
+ if (time2 > TIME_MAX) {
87407
+ throw new ULIDError(ULIDErrorCode.DecodeTimeValueMalformed, `Malformed ULID: timestamp too large: ${time2}`);
87408
+ }
87409
+ return time2;
87410
+ }
87411
+ function detectPRNG(root2) {
87412
+ var _a3;
87413
+ const rootLookup = detectRoot();
87414
+ const globalCrypto = rootLookup && (rootLookup.crypto || rootLookup.msCrypto) || (typeof crypto !== "undefined" ? crypto : null);
87415
+ if (typeof (globalCrypto == null ? void 0 : globalCrypto.getRandomValues) === "function") {
87416
+ return () => {
87417
+ const buffer = new Uint8Array(1);
87418
+ globalCrypto.getRandomValues(buffer);
87419
+ return buffer[0] / 255;
87420
+ };
87421
+ } else if (typeof (globalCrypto == null ? void 0 : globalCrypto.randomBytes) === "function") {
87422
+ return () => globalCrypto.randomBytes(1).readUInt8() / 255;
87423
+ } else if ((_a3 = crypto) == null ? void 0 : _a3.randomBytes) {
87424
+ return () => crypto.randomBytes(1).readUInt8() / 255;
87425
+ }
87426
+ throw new ULIDError(ULIDErrorCode.PRNGDetectFailure, "Failed to find a reliable PRNG");
87427
+ }
87428
+ function detectRoot() {
87429
+ if (inWebWorker())
87430
+ return self;
87431
+ if (typeof window !== "undefined") {
87432
+ return window;
87433
+ }
87434
+ if (typeof global !== "undefined") {
87435
+ return global;
87436
+ }
87437
+ if (typeof globalThis !== "undefined") {
87438
+ return globalThis;
87439
+ }
87440
+ return null;
87441
+ }
87442
+ function encodeRandom(len, prng) {
87443
+ let str = "";
87444
+ for (; len > 0; len--) {
87445
+ str = randomChar(prng) + str;
87446
+ }
87447
+ return str;
87448
+ }
87449
+ function encodeTime(now2, len = TIME_LEN) {
87450
+ if (isNaN(now2)) {
87451
+ throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be a number: ${now2}`);
87452
+ } else if (now2 > TIME_MAX) {
87453
+ throw new ULIDError(ULIDErrorCode.EncodeTimeSizeExceeded, `Cannot encode a time larger than ${TIME_MAX}: ${now2}`);
87454
+ } else if (now2 < 0) {
87455
+ throw new ULIDError(ULIDErrorCode.EncodeTimeNegative, `Time must be positive: ${now2}`);
87456
+ } else if (Number.isInteger(now2) === false) {
87457
+ throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be an integer: ${now2}`);
87458
+ }
87459
+ let mod, str = "";
87460
+ for (let currentLen = len; currentLen > 0; currentLen--) {
87461
+ mod = now2 % ENCODING_LEN;
87462
+ str = ENCODING.charAt(mod) + str;
87463
+ now2 = (now2 - mod) / ENCODING_LEN;
87464
+ }
87465
+ return str;
87466
+ }
87467
+ function inWebWorker() {
87468
+ return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
87469
+ }
87470
+ function monotonicFactory(prng) {
87471
+ const currentPRNG = prng || detectPRNG();
87472
+ let lastTime = 0, lastRandom;
87473
+ return function _ulid2(seedTime) {
87474
+ const seed = !seedTime || isNaN(seedTime) ? Date.now() : seedTime;
87475
+ if (seed <= lastTime) {
87476
+ const incrementedRandom = lastRandom = incrementBase32(lastRandom);
87477
+ return encodeTime(lastTime, TIME_LEN) + incrementedRandom;
87478
+ }
87479
+ lastTime = seed;
87480
+ const newRandom = lastRandom = encodeRandom(RANDOM_LEN, currentPRNG);
87481
+ return encodeTime(seed, TIME_LEN) + newRandom;
87482
+ };
87483
+ }
87484
+ const UlidSchema = string$1().ulid();
87485
+ const DEFAULT_TIMESTAMP_THRESHOLD_MS = 5 * 60 * 1e3;
87486
+ function ulidToDate(maybeUlid) {
87487
+ const ulid2 = UlidSchema.safeParse(maybeUlid);
87488
+ if (!ulid2.success) {
87489
+ return null;
87490
+ }
87491
+ return new Date(decodeTime(ulid2.data));
87492
+ }
87493
+ function validateUlidTimestamp(prefixedUlid, prefix, thresholdMs = DEFAULT_TIMESTAMP_THRESHOLD_MS) {
87494
+ const raw2 = prefixedUlid.startsWith(prefix) ? prefixedUlid.slice(prefix.length) : prefixedUlid;
87495
+ const ulidTimestamp = ulidToDate(raw2);
87496
+ if (!ulidTimestamp) {
87497
+ return `Invalid runId: "${prefixedUlid}" is not a valid ULID`;
87498
+ }
87499
+ const serverTimestamp = /* @__PURE__ */ new Date();
87500
+ const driftMs = Math.abs(serverTimestamp.getTime() - ulidTimestamp.getTime());
87501
+ if (driftMs <= thresholdMs) {
87502
+ return null;
87503
+ }
87504
+ const driftSeconds = Math.round(driftMs / 1e3);
87505
+ const thresholdSeconds = Math.round(thresholdMs / 1e3);
87506
+ return `Invalid runId timestamp: embedded timestamp differs from server time by ${driftSeconds}s (threshold: ${thresholdSeconds}s)`;
87507
+ }
87337
87508
  const NONCE_LENGTH = 12;
87338
87509
  const TAG_LENGTH = 128;
87339
87510
  const KEY_LENGTH = 32;
@@ -88293,150 +88464,6 @@ const runtimeLogger = createLogger("runtime");
88293
88464
  createLogger("webhook");
88294
88465
  createLogger("events");
88295
88466
  createLogger("adapter");
88296
- const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
88297
- const ENCODING_LEN = 32;
88298
- const RANDOM_LEN = 16;
88299
- const TIME_LEN = 10;
88300
- const TIME_MAX = 281474976710655;
88301
- var ULIDErrorCode;
88302
- (function(ULIDErrorCode2) {
88303
- ULIDErrorCode2["Base32IncorrectEncoding"] = "B32_ENC_INVALID";
88304
- ULIDErrorCode2["DecodeTimeInvalidCharacter"] = "DEC_TIME_CHAR";
88305
- ULIDErrorCode2["DecodeTimeValueMalformed"] = "DEC_TIME_MALFORMED";
88306
- ULIDErrorCode2["EncodeTimeNegative"] = "ENC_TIME_NEG";
88307
- ULIDErrorCode2["EncodeTimeSizeExceeded"] = "ENC_TIME_SIZE_EXCEED";
88308
- ULIDErrorCode2["EncodeTimeValueMalformed"] = "ENC_TIME_MALFORMED";
88309
- ULIDErrorCode2["PRNGDetectFailure"] = "PRNG_DETECT";
88310
- ULIDErrorCode2["ULIDInvalid"] = "ULID_INVALID";
88311
- ULIDErrorCode2["Unexpected"] = "UNEXPECTED";
88312
- ULIDErrorCode2["UUIDInvalid"] = "UUID_INVALID";
88313
- })(ULIDErrorCode || (ULIDErrorCode = {}));
88314
- class ULIDError extends Error {
88315
- constructor(errorCode, message2) {
88316
- super(`${message2} (${errorCode})`);
88317
- this.name = "ULIDError";
88318
- this.code = errorCode;
88319
- }
88320
- }
88321
- function randomChar(prng) {
88322
- const randomPosition = Math.floor(prng() * ENCODING_LEN) % ENCODING_LEN;
88323
- return ENCODING.charAt(randomPosition);
88324
- }
88325
- function replaceCharAt(str, index2, char) {
88326
- if (index2 > str.length - 1) {
88327
- return str;
88328
- }
88329
- return str.substr(0, index2) + char + str.substr(index2 + 1);
88330
- }
88331
- function incrementBase32(str) {
88332
- let done = void 0, index2 = str.length, char, charIndex, output = str;
88333
- const maxCharIndex = ENCODING_LEN - 1;
88334
- while (!done && index2-- >= 0) {
88335
- char = output[index2];
88336
- charIndex = ENCODING.indexOf(char);
88337
- if (charIndex === -1) {
88338
- throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Incorrectly encoded string");
88339
- }
88340
- if (charIndex === maxCharIndex) {
88341
- output = replaceCharAt(output, index2, ENCODING[0]);
88342
- continue;
88343
- }
88344
- done = replaceCharAt(output, index2, ENCODING[charIndex + 1]);
88345
- }
88346
- if (typeof done === "string") {
88347
- return done;
88348
- }
88349
- throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Failed incrementing string");
88350
- }
88351
- function decodeTime(id2) {
88352
- if (id2.length !== TIME_LEN + RANDOM_LEN) {
88353
- throw new ULIDError(ULIDErrorCode.DecodeTimeValueMalformed, "Malformed ULID");
88354
- }
88355
- const time2 = id2.substr(0, TIME_LEN).toUpperCase().split("").reverse().reduce((carry, char, index2) => {
88356
- const encodingIndex = ENCODING.indexOf(char);
88357
- if (encodingIndex === -1) {
88358
- throw new ULIDError(ULIDErrorCode.DecodeTimeInvalidCharacter, `Time decode error: Invalid character: ${char}`);
88359
- }
88360
- return carry += encodingIndex * Math.pow(ENCODING_LEN, index2);
88361
- }, 0);
88362
- if (time2 > TIME_MAX) {
88363
- throw new ULIDError(ULIDErrorCode.DecodeTimeValueMalformed, `Malformed ULID: timestamp too large: ${time2}`);
88364
- }
88365
- return time2;
88366
- }
88367
- function detectPRNG(root2) {
88368
- var _a3;
88369
- const rootLookup = detectRoot();
88370
- const globalCrypto = rootLookup && (rootLookup.crypto || rootLookup.msCrypto) || (typeof crypto !== "undefined" ? crypto : null);
88371
- if (typeof (globalCrypto == null ? void 0 : globalCrypto.getRandomValues) === "function") {
88372
- return () => {
88373
- const buffer = new Uint8Array(1);
88374
- globalCrypto.getRandomValues(buffer);
88375
- return buffer[0] / 255;
88376
- };
88377
- } else if (typeof (globalCrypto == null ? void 0 : globalCrypto.randomBytes) === "function") {
88378
- return () => globalCrypto.randomBytes(1).readUInt8() / 255;
88379
- } else if ((_a3 = crypto) == null ? void 0 : _a3.randomBytes) {
88380
- return () => crypto.randomBytes(1).readUInt8() / 255;
88381
- }
88382
- throw new ULIDError(ULIDErrorCode.PRNGDetectFailure, "Failed to find a reliable PRNG");
88383
- }
88384
- function detectRoot() {
88385
- if (inWebWorker())
88386
- return self;
88387
- if (typeof window !== "undefined") {
88388
- return window;
88389
- }
88390
- if (typeof global !== "undefined") {
88391
- return global;
88392
- }
88393
- if (typeof globalThis !== "undefined") {
88394
- return globalThis;
88395
- }
88396
- return null;
88397
- }
88398
- function encodeRandom(len, prng) {
88399
- let str = "";
88400
- for (; len > 0; len--) {
88401
- str = randomChar(prng) + str;
88402
- }
88403
- return str;
88404
- }
88405
- function encodeTime(now2, len = TIME_LEN) {
88406
- if (isNaN(now2)) {
88407
- throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be a number: ${now2}`);
88408
- } else if (now2 > TIME_MAX) {
88409
- throw new ULIDError(ULIDErrorCode.EncodeTimeSizeExceeded, `Cannot encode a time larger than ${TIME_MAX}: ${now2}`);
88410
- } else if (now2 < 0) {
88411
- throw new ULIDError(ULIDErrorCode.EncodeTimeNegative, `Time must be positive: ${now2}`);
88412
- } else if (Number.isInteger(now2) === false) {
88413
- throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be an integer: ${now2}`);
88414
- }
88415
- let mod, str = "";
88416
- for (let currentLen = len; currentLen > 0; currentLen--) {
88417
- mod = now2 % ENCODING_LEN;
88418
- str = ENCODING.charAt(mod) + str;
88419
- now2 = (now2 - mod) / ENCODING_LEN;
88420
- }
88421
- return str;
88422
- }
88423
- function inWebWorker() {
88424
- return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
88425
- }
88426
- function monotonicFactory(prng) {
88427
- const currentPRNG = prng || detectPRNG();
88428
- let lastTime = 0, lastRandom;
88429
- return function _ulid2(seedTime) {
88430
- const seed = !seedTime || isNaN(seedTime) ? Date.now() : seedTime;
88431
- if (seed <= lastTime) {
88432
- const incrementedRandom = lastRandom = incrementBase32(lastRandom);
88433
- return encodeTime(lastTime, TIME_LEN) + incrementedRandom;
88434
- }
88435
- lastTime = seed;
88436
- const newRandom = lastRandom = encodeRandom(RANDOM_LEN, currentPRNG);
88437
- return encodeTime(seed, TIME_LEN) + newRandom;
88438
- };
88439
- }
88440
88467
  const execFileAsync = promisify(execFile);
88441
88468
  function parsePort$1(value, radix = 10) {
88442
88469
  const port = parseInt(value, radix);
@@ -89400,8 +89427,8 @@ function requireGetVercelOidcToken$1() {
89400
89427
  }
89401
89428
  try {
89402
89429
  const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
89403
- await import("./token-util-C6iVpF77.js").then((n) => n.t),
89404
- await import("./token-C58qysN7.js").then((n) => n.t)
89430
+ await import("./token-util-CvLiUUQD.js").then((n) => n.t),
89431
+ await import("./token-CWWXwMh8.js").then((n) => n.t)
89405
89432
  ]);
89406
89433
  if (!token || isExpired(getTokenPayload(token))) {
89407
89434
  await refreshToken();
@@ -115521,6 +115548,7 @@ function createQueue$2(config2) {
115521
115548
  const generateId2 = monotonicFactory();
115522
115549
  const semaphore = new libExports.Sema(WORKFLOW_LOCAL_QUEUE_CONCURRENCY);
115523
115550
  const inflightMessages = /* @__PURE__ */ new Map();
115551
+ const directHandlers = /* @__PURE__ */ new Map();
115524
115552
  const queue = async (queueName, message2, opts) => {
115525
115553
  const cleanup = [];
115526
115554
  if (opts == null ? void 0 : opts.idempotencyKey) {
@@ -115531,10 +115559,13 @@ function createQueue$2(config2) {
115531
115559
  }
115532
115560
  const body2 = transport.serialize(message2);
115533
115561
  let pathname;
115562
+ let prefix;
115534
115563
  if (queueName.startsWith("__wkf_step_")) {
115535
115564
  pathname = `step`;
115565
+ prefix = "__wkf_step_";
115536
115566
  } else if (queueName.startsWith("__wkf_workflow_")) {
115537
115567
  pathname = `flow`;
115568
+ prefix = "__wkf_workflow_";
115538
115569
  } else {
115539
115570
  throw new Error("Unknown queue name prefix");
115540
115571
  }
@@ -115554,22 +115585,34 @@ function createQueue$2(config2) {
115554
115585
  }
115555
115586
  try {
115556
115587
  let defaultRetriesLeft = 3;
115557
- const baseUrl = await resolveBaseUrl$1(config2);
115588
+ const directHandler = directHandlers.get(prefix);
115558
115589
  for (let attempt = 0; defaultRetriesLeft > 0; attempt++) {
115559
115590
  defaultRetriesLeft--;
115560
- const response2 = await fetch(`${baseUrl}/.well-known/workflow/v1/${pathname}`, {
115561
- method: "POST",
115562
- duplex: "half",
115563
- dispatcher: httpAgent,
115564
- headers: {
115565
- ...opts == null ? void 0 : opts.headers,
115566
- "content-type": "application/json",
115567
- "x-vqs-queue-name": queueName,
115568
- "x-vqs-message-id": messageId,
115569
- "x-vqs-message-attempt": String(attempt + 1)
115570
- },
115571
- body: body2
115572
- });
115591
+ let response2;
115592
+ const headers2 = {
115593
+ ...opts == null ? void 0 : opts.headers,
115594
+ "content-type": "application/json",
115595
+ "x-vqs-queue-name": queueName,
115596
+ "x-vqs-message-id": messageId,
115597
+ "x-vqs-message-attempt": String(attempt + 1)
115598
+ };
115599
+ if (directHandler) {
115600
+ const req = new Request("http://localhost/.well-known/workflow/v1/" + pathname, {
115601
+ method: "POST",
115602
+ headers: headers2,
115603
+ body: body2
115604
+ });
115605
+ response2 = await directHandler(req);
115606
+ } else {
115607
+ const baseUrl = await resolveBaseUrl$1(config2);
115608
+ response2 = await fetch(`${baseUrl}/.well-known/workflow/v1/${pathname}`, {
115609
+ method: "POST",
115610
+ duplex: "half",
115611
+ dispatcher: httpAgent,
115612
+ headers: headers2,
115613
+ body: body2
115614
+ });
115615
+ }
115573
115616
  if (response2.ok) {
115574
115617
  return;
115575
115618
  }
@@ -115634,7 +115677,7 @@ function createQueue$2(config2) {
115634
115677
  if (typeof (result == null ? void 0 : result.timeoutSeconds) === "number") {
115635
115678
  timeoutSeconds = Math.min(result.timeoutSeconds, LOCAL_QUEUE_MAX_VISIBILITY);
115636
115679
  }
115637
- if (timeoutSeconds) {
115680
+ if (timeoutSeconds != null) {
115638
115681
  return Response.json({ timeoutSeconds }, { status: 503 });
115639
115682
  }
115640
115683
  return Response.json({ ok: true });
@@ -115651,6 +115694,9 @@ function createQueue$2(config2) {
115651
115694
  queue,
115652
115695
  createQueueHandler,
115653
115696
  getDeploymentId,
115697
+ registerHandler(prefix, handler) {
115698
+ directHandlers.set(prefix, handler);
115699
+ },
115654
115700
  async close() {
115655
115701
  await httpAgent.close();
115656
115702
  }
@@ -115752,7 +115798,6 @@ function instrumentObject$1(prefix, o) {
115752
115798
  return handlers2;
115753
115799
  }
115754
115800
  const ulid$1 = monotonicFactory(() => Math.random());
115755
- const Ulid = string$1().ulid();
115756
115801
  const isWindows = process.platform === "win32";
115757
115802
  async function withWindowsRetry(fn2, maxRetries = 5) {
115758
115803
  if (!isWindows)
@@ -115773,13 +115818,6 @@ async function withWindowsRetry(fn2, maxRetries = 5) {
115773
115818
  throw new Error("Retry loop exited unexpectedly");
115774
115819
  }
115775
115820
  const createdFilesCache = /* @__PURE__ */ new Set();
115776
- function ulidToDate(maybeUlid) {
115777
- const ulid2 = Ulid.safeParse(maybeUlid);
115778
- if (!ulid2.success) {
115779
- return null;
115780
- }
115781
- return new Date(decodeTime(ulid2.data));
115782
- }
115783
115821
  async function ensureDir(dirPath) {
115784
115822
  try {
115785
115823
  await promises.mkdir(dirPath, { recursive: true });
@@ -116155,6 +116193,12 @@ function createEventsStorage(basedir) {
116155
116193
  } else {
116156
116194
  effectiveRunId = runId;
116157
116195
  }
116196
+ if (data.eventType === "run_created" && runId && runId !== "") {
116197
+ const validationError = validateUlidTimestamp(effectiveRunId, "wrun_");
116198
+ if (validationError) {
116199
+ throw new WorkflowAPIError(validationError, { status: 400 });
116200
+ }
116201
+ }
116158
116202
  const effectiveSpecVersion = data.specVersion ?? SPEC_VERSION_CURRENT;
116159
116203
  const isRunTerminal = (status) => ["completed", "failed", "cancelled"].includes(status);
116160
116204
  const isStepTerminal = (status) => ["completed", "failed"].includes(status);
@@ -116578,6 +116622,16 @@ function createEventsStorage(basedir) {
116578
116622
  wait
116579
116623
  };
116580
116624
  },
116625
+ async get(runId, eventId, params) {
116626
+ const compositeKey = `${runId}-${eventId}`;
116627
+ const eventPath = path$2.join(basedir, "events", `${compositeKey}.json`);
116628
+ const event = await readJSON(eventPath, EventSchema);
116629
+ if (!event) {
116630
+ throw new Error(`Event ${eventId} in run ${runId} not found`);
116631
+ }
116632
+ const resolveData = (params == null ? void 0 : params.resolveData) ?? DEFAULT_RESOLVE_DATA_OPTION$1;
116633
+ return filterEventData$1(event, resolveData);
116634
+ },
116581
116635
  async list(params) {
116582
116636
  var _a3, _b, _c;
116583
116637
  const { runId } = params;
@@ -116950,6 +117004,10 @@ function createLocalWorld(args) {
116950
117004
  },
116951
117005
  async close() {
116952
117006
  await queue.close();
117007
+ },
117008
+ async clear() {
117009
+ await rm(mergedConfig.dataDir, { recursive: true, force: true });
117010
+ await initDataDir(mergedConfig.dataDir);
116953
117011
  }
116954
117012
  };
116955
117013
  }
@@ -117071,8 +117129,8 @@ function requireGetVercelOidcToken() {
117071
117129
  }
117072
117130
  try {
117073
117131
  const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
117074
- await import("./token-util-CcopqG1U.js").then((n) => n.t),
117075
- await import("./token-CLFHo1Az.js").then((n) => n.t)
117132
+ await import("./token-util-l0RNhdPG.js").then((n) => n.t),
117133
+ await import("./token-DJXheGCg.js").then((n) => n.t)
117076
117134
  ]);
117077
117135
  if (!token || isExpired(getTokenPayload(token), options == null ? void 0 : options.expirationBufferMs)) {
117078
117136
  await refreshToken(options);
@@ -117791,7 +117849,7 @@ const PeerService = SemanticConvention("peer.service");
117791
117849
  const RpcSystem = SemanticConvention("rpc.system");
117792
117850
  const RpcService = SemanticConvention("rpc.service");
117793
117851
  const RpcMethod = SemanticConvention("rpc.method");
117794
- const version$1 = "4.1.0-beta.38";
117852
+ const version$1 = "4.1.0-beta.41";
117795
117853
  const DEFAULT_RESOLVE_DATA_OPTION = "all";
117796
117854
  function deserializeError(obj) {
117797
117855
  const { error: error2, ...rest } = obj;
@@ -118090,7 +118148,7 @@ function createQueue$1(config2) {
118090
118148
  attempt: metadata.deliveryCount
118091
118149
  });
118092
118150
  if (typeof (result == null ? void 0 : result.timeoutSeconds) === "number") {
118093
- const delaySeconds = Math.min(result.timeoutSeconds, MAX_DELAY_SECONDS);
118151
+ const delaySeconds = result.timeoutSeconds > 0 ? Math.min(result.timeoutSeconds, MAX_DELAY_SECONDS) : void 0;
118094
118152
  await queue(queueName, payload, { deploymentId, delaySeconds });
118095
118153
  }
118096
118154
  });
@@ -118531,6 +118589,21 @@ async function hydrateEventRefs(events2, config2, refResolveConcurrency) {
118531
118589
  return result;
118532
118590
  });
118533
118591
  }
118592
+ async function getEvent(runId, eventId, params, config2) {
118593
+ const resolveData = (params == null ? void 0 : params.resolveData) ?? DEFAULT_RESOLVE_DATA_OPTION;
118594
+ const remoteRefBehavior = resolveData === "none" ? "lazy" : "resolve";
118595
+ const searchParams = new URLSearchParams();
118596
+ searchParams.set("remoteRefBehavior", remoteRefBehavior);
118597
+ const queryString = searchParams.toString();
118598
+ const endpoint = `/v2/runs/${runId}/events/${eventId}${queryString ? `?${queryString}` : ""}`;
118599
+ const event = await makeRequest({
118600
+ endpoint,
118601
+ options: { method: "GET" },
118602
+ config: config2,
118603
+ schema: resolveData === "none" ? EventWithRefsSchema : EventSchema
118604
+ });
118605
+ return filterEventData(event, resolveData);
118606
+ }
118534
118607
  async function getWorkflowRunEvents(params, config2) {
118535
118608
  const searchParams = new URLSearchParams();
118536
118609
  const { pagination, resolveData = DEFAULT_RESOLVE_DATA_OPTION } = params;
@@ -118614,6 +118687,12 @@ async function createWorkflowRunEvent(id2, data, params, config2) {
118614
118687
  });
118615
118688
  return { event: wireResult2 };
118616
118689
  }
118690
+ if (data.eventType === "run_created" && id2) {
118691
+ const validationError = validateUlidTimestamp(id2, "wrun_");
118692
+ if (validationError) {
118693
+ throw new WorkflowAPIError(validationError, { status: 400 });
118694
+ }
118695
+ }
118617
118696
  const runIdPath = id2 === null ? "null" : id2;
118618
118697
  const remoteRefBehavior = eventsNeedingResolve.has(data.eventType) ? "resolve" : "lazy";
118619
118698
  if (remoteRefBehavior === "resolve") {
@@ -118768,6 +118847,7 @@ function createStorage(config2) {
118768
118847
  },
118769
118848
  events: {
118770
118849
  create: (runId, data, params) => createWorkflowRunEvent(runId, data, params, config2),
118850
+ get: (runId, eventId, params) => getEvent(runId, eventId, params, config2),
118771
118851
  list: (params) => getWorkflowRunEvents(params, config2),
118772
118852
  listByCorrelationId: (params) => getWorkflowRunEvents(params, config2)
118773
118853
  },
@@ -120473,7 +120553,7 @@ function getStreamType(stream) {
120473
120553
  } catch {
120474
120554
  }
120475
120555
  }
120476
- const FRAME_HEADER_SIZE = 4;
120556
+ const FRAME_HEADER_SIZE$1 = 4;
120477
120557
  function getSerializeStream(reducers, cryptoKey) {
120478
120558
  const encoder = new TextEncoder();
120479
120559
  const keyState = { resolved: false, key: void 0 };
@@ -120491,9 +120571,9 @@ function getSerializeStream(reducers, cryptoKey) {
120491
120571
  const encrypted = await encrypt(keyState.key, prefixed);
120492
120572
  prefixed = encodeWithFormatPrefix(SerializationFormat.ENCRYPTED, encrypted);
120493
120573
  }
120494
- const frame2 = new Uint8Array(FRAME_HEADER_SIZE + prefixed.length);
120574
+ const frame2 = new Uint8Array(FRAME_HEADER_SIZE$1 + prefixed.length);
120495
120575
  new DataView(frame2.buffer).setUint32(0, prefixed.length, false);
120496
- frame2.set(prefixed, FRAME_HEADER_SIZE);
120576
+ frame2.set(prefixed, FRAME_HEADER_SIZE$1);
120497
120577
  controller.enqueue(frame2);
120498
120578
  } catch (error2) {
120499
120579
  controller.error(new WorkflowRuntimeError(formatSerializationError("stream chunk", error2), { slug: "serialization-failed", cause: error2 }));
@@ -120517,13 +120597,13 @@ function getDeserializeStream(revivers, cryptoKey) {
120517
120597
  keyState.key = await cryptoKey;
120518
120598
  keyState.resolved = true;
120519
120599
  }
120520
- while (buffer.length >= FRAME_HEADER_SIZE) {
120600
+ while (buffer.length >= FRAME_HEADER_SIZE$1) {
120521
120601
  const frameLength = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength).getUint32(0, false);
120522
- if (buffer.length < FRAME_HEADER_SIZE + frameLength) {
120602
+ if (buffer.length < FRAME_HEADER_SIZE$1 + frameLength) {
120523
120603
  break;
120524
120604
  }
120525
- const frameData = buffer.slice(FRAME_HEADER_SIZE, FRAME_HEADER_SIZE + frameLength);
120526
- buffer = buffer.slice(FRAME_HEADER_SIZE + frameLength);
120605
+ const frameData = buffer.slice(FRAME_HEADER_SIZE$1, FRAME_HEADER_SIZE$1 + frameLength);
120606
+ buffer = buffer.slice(FRAME_HEADER_SIZE$1 + frameLength);
120527
120607
  let { format: format2, payload } = decodeFormatPrefix(frameData);
120528
120608
  if (format2 === SerializationFormat.ENCRYPTED) {
120529
120609
  if (!keyState.key) {
@@ -120541,7 +120621,7 @@ function getDeserializeStream(revivers, cryptoKey) {
120541
120621
  }
120542
120622
  const stream = new TransformStream({
120543
120623
  async transform(chunk, controller) {
120544
- if (buffer.length === 0 && chunk.length >= FRAME_HEADER_SIZE) {
120624
+ if (buffer.length === 0 && chunk.length >= FRAME_HEADER_SIZE$1) {
120545
120625
  const possibleLength = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength).getUint32(0, false);
120546
120626
  if (possibleLength > 0 && possibleLength < 1e8) {
120547
120627
  appendToBuffer(chunk);
@@ -122131,7 +122211,7 @@ async function resumeHook$2(tokenOrHook, payload, encryptionKeyOverride) {
122131
122211
  });
122132
122212
  });
122133
122213
  }
122134
- const version = "4.2.0-beta.64";
122214
+ const version = "4.2.0-beta.67";
122135
122215
  const ulid = monotonicFactory();
122136
122216
  async function start$1(workflow, argsOrOptions, options) {
122137
122217
  return await waitedUntil(() => {
@@ -122472,8 +122552,9 @@ getWorldHandlers().createQueueHandler("__wkf_step_", async (message_, metadata)
122472
122552
  return await withTraceContext(traceContext, async () => {
122473
122553
  const stepName = metadata.queueName.slice("__wkf_step_".length);
122474
122554
  const world = getWorld();
122555
+ const isVercel = process.env.VERCEL_URL !== void 0;
122475
122556
  const [port, spanKind] = await Promise.all([
122476
- getPort(),
122557
+ isVercel ? void 0 : getPort(),
122477
122558
  getSpanKind$2("CONSUMER")
122478
122559
  ]);
122479
122560
  return trace$2(`STEP ${stepName}`, { kind: spanKind, links: spanLinks }, async (span) => {
@@ -122650,16 +122731,18 @@ getWorldHandlers().createQueueHandler("__wkf_step_", async (message_, metadata)
122650
122731
  result = await trace$2("step.execute", {}, async () => {
122651
122732
  return await contextStorage.run({
122652
122733
  stepMetadata: {
122734
+ stepName,
122653
122735
  stepId,
122654
122736
  stepStartedAt: /* @__PURE__ */ new Date(+stepStartedAt),
122655
122737
  attempt
122656
122738
  },
122657
122739
  workflowMetadata: {
122740
+ workflowName,
122658
122741
  workflowRunId,
122659
122742
  workflowStartedAt: /* @__PURE__ */ new Date(+workflowStartedAt),
122660
122743
  // TODO: there should be a getUrl method on the world interface itself. This
122661
122744
  // solution only works for vercel + local worlds.
122662
- url: process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : `http://localhost:${port ?? 3e3}`
122745
+ url: isVercel ? `https://${process.env.VERCEL_URL}` : `http://localhost:${port ?? 3e3}`
122663
122746
  },
122664
122747
  ops,
122665
122748
  closureVars: hydratedInput.closureVars,
@@ -123410,6 +123493,19 @@ async function fetchEvents(worldEnv, runId, params) {
123410
123493
  );
123411
123494
  }
123412
123495
  }
123496
+ async function fetchEvent(worldEnv, runId, eventId, resolveData = "all") {
123497
+ try {
123498
+ const world = await getWorldFromEnv(worldEnv);
123499
+ const event = await world.events.get(runId, eventId, { resolveData });
123500
+ return createResponse(event);
123501
+ } catch (error2) {
123502
+ return createServerActionError(error2, "world.events.get", {
123503
+ runId,
123504
+ eventId,
123505
+ resolveData
123506
+ });
123507
+ }
123508
+ }
123413
123509
  async function fetchEventsByCorrelationId(worldEnv, correlationId, params) {
123414
123510
  const { cursor, sortOrder = "asc", limit = 1e3, withData = false } = params;
123415
123511
  try {
@@ -123533,10 +123629,7 @@ async function resumeHook$1(worldEnv, token, payload) {
123533
123629
  async function readStreamServerAction(env2, streamId, startIndex) {
123534
123630
  try {
123535
123631
  const world = await getWorldFromEnv(env2);
123536
- const stream = await world.readFromStream(streamId, startIndex);
123537
- const revivers = getExternalRevivers(globalThis, [], "", void 0);
123538
- const transform2 = getDeserializeStream(revivers, void 0);
123539
- return stream.pipeThrough(transform2);
123632
+ return await world.readFromStream(streamId, startIndex);
123540
123633
  } catch (error2) {
123541
123634
  const actionError = createServerActionError(error2, "world.readFromStream", {
123542
123635
  streamId,
@@ -129614,7 +129707,7 @@ function useWorkflowTraceViewerData(env2, runId, options = {}) {
129614
129707
  setAuxiliaryDataLoading(true);
129615
129708
  setError(null);
129616
129709
  const [runResult, stepsResult, hooksResult, eventsResult] = await Promise.all([
129617
- unwrapServerActionResult(fetchRun$1(env2, runId)),
129710
+ unwrapServerActionResult(fetchRun$1(env2, runId, "none")),
129618
129711
  unwrapServerActionResult(
129619
129712
  fetchSteps$1(env2, runId, {
129620
129713
  sortOrder: "asc",
@@ -129789,12 +129882,13 @@ function useWorkflowTraceViewerData(env2, runId, options = {}) {
129789
129882
  return false;
129790
129883
  }
129791
129884
  const { error: error22, result } = await unwrapServerActionResult(
129792
- fetchRun$1(env2, runId)
129885
+ fetchRun$1(env2, runId, "none")
129793
129886
  );
129794
129887
  if (error22) {
129795
129888
  setError(error22);
129796
129889
  return false;
129797
129890
  }
129891
+ setError(null);
129798
129892
  setRun(hydrateResourceIO(result));
129799
129893
  return true;
129800
129894
  }, [env2, runId, run == null ? void 0 : run.completedAt]);
@@ -145837,7 +145931,8 @@ function mapRunToExecution(run, steps, events2, graph) {
145837
145931
  });
145838
145932
  return result;
145839
145933
  }
145840
- function useStreamReader(env2, streamId) {
145934
+ const FRAME_HEADER_SIZE = 4;
145935
+ function useStreamReader(env2, streamId, runId, encryptionKey) {
145841
145936
  const [chunks, setChunks] = reactExports.useState([]);
145842
145937
  const [isLive, setIsLive] = reactExports.useState(false);
145843
145938
  const [error2, setError] = reactExports.useState(null);
@@ -145856,83 +145951,82 @@ function useStreamReader(env2, streamId) {
145856
145951
  abortControllerRef.current = abortController;
145857
145952
  setIsLive(true);
145858
145953
  const revivers = getWebRevivers();
145859
- const handleStreamEnd = () => {
145860
- if (mounted) {
145861
- setIsLive(false);
145862
- }
145863
- };
145864
- const handleStreamError = (err) => {
145865
- if (mounted) {
145866
- setError(err instanceof Error ? err.message : String(err));
145867
- setIsLive(false);
145868
- }
145869
- };
145870
- const addChunk = (value) => {
145871
- if (mounted && value !== void 0 && value !== null) {
145872
- const chunkId = chunkIdRef.current++;
145873
- let hydrated;
145874
- try {
145875
- hydrated = hydrateData(value, revivers);
145876
- } catch {
145877
- hydrated = value;
145878
- }
145879
- const text2 = typeof hydrated === "string" ? hydrated : JSON.stringify(hydrated, null, 2);
145880
- setChunks((prev) => [...prev, { id: chunkId, text: text2 }]);
145881
- }
145882
- };
145883
- const processFramedStream = async (reader) => {
145884
- var _a3;
145885
- let buffer = new Uint8Array(0);
145886
- const appendToBuffer = (data) => {
145887
- const newBuffer = new Uint8Array(buffer.length + data.length);
145888
- newBuffer.set(buffer, 0);
145889
- newBuffer.set(data, buffer.length);
145890
- buffer = newBuffer;
145891
- };
145892
- for (; ; ) {
145893
- if ((_a3 = abortControllerRef.current) == null ? void 0 : _a3.signal.aborted) break;
145894
- const { value, done } = await reader.read();
145895
- if (done) {
145896
- handleStreamEnd();
145897
- break;
145898
- }
145899
- appendToBuffer(value);
145900
- while (buffer.length >= 4) {
145901
- const view = new DataView(
145902
- buffer.buffer,
145903
- buffer.byteOffset,
145904
- buffer.byteLength
145905
- );
145906
- const frameLength = view.getUint32(0, false);
145907
- if (buffer.length < 4 + frameLength) {
145908
- break;
145909
- }
145910
- const frameData = buffer.slice(4, 4 + frameLength);
145911
- buffer = buffer.slice(4 + frameLength);
145912
- try {
145913
- const rawChunk = decode$2(frameData);
145914
- addChunk(rawChunk);
145915
- } catch (err) {
145916
- console.error("Failed to decode stream chunk:", err);
145917
- }
145918
- }
145919
- }
145920
- };
145921
145954
  const readStreamData = async () => {
145922
145955
  try {
145923
- const stream = await readStream(
145956
+ const rawStream = await readStream(
145924
145957
  env2,
145925
145958
  streamId,
145926
145959
  void 0,
145927
145960
  abortController.signal
145928
145961
  );
145929
- const reader = stream.getReader();
145930
- await processFramedStream(reader);
145962
+ const cryptoKey = encryptionKey ? await importKey(encryptionKey) : void 0;
145963
+ const reader = rawStream.getReader();
145964
+ let buffer = new Uint8Array(0);
145965
+ const appendToBuffer = (data) => {
145966
+ const newBuffer = new Uint8Array(buffer.length + data.length);
145967
+ newBuffer.set(buffer, 0);
145968
+ newBuffer.set(data, buffer.length);
145969
+ buffer = newBuffer;
145970
+ };
145971
+ for (; ; ) {
145972
+ if (abortController.signal.aborted) break;
145973
+ const { value, done } = await reader.read();
145974
+ if (done) {
145975
+ if (mounted) setIsLive(false);
145976
+ break;
145977
+ }
145978
+ appendToBuffer(value);
145979
+ while (buffer.length >= FRAME_HEADER_SIZE) {
145980
+ const view = new DataView(
145981
+ buffer.buffer,
145982
+ buffer.byteOffset,
145983
+ buffer.byteLength
145984
+ );
145985
+ const frameLength = view.getUint32(0, false);
145986
+ if (buffer.length < FRAME_HEADER_SIZE + frameLength) {
145987
+ break;
145988
+ }
145989
+ const frameData = buffer.slice(
145990
+ FRAME_HEADER_SIZE,
145991
+ FRAME_HEADER_SIZE + frameLength
145992
+ );
145993
+ buffer = buffer.slice(FRAME_HEADER_SIZE + frameLength);
145994
+ try {
145995
+ const { format: format2, payload } = decodeFormatPrefix$1(frameData);
145996
+ let dataToHydrate;
145997
+ if (format2 === SerializationFormat$1.ENCRYPTED) {
145998
+ if (!cryptoKey) {
145999
+ if (mounted) {
146000
+ setError(
146001
+ "This stream is encrypted. Click Decrypt to view."
146002
+ );
146003
+ setIsLive(false);
146004
+ }
146005
+ reader.cancel().catch(() => {
146006
+ });
146007
+ return;
146008
+ }
146009
+ dataToHydrate = await decrypt(cryptoKey, payload);
146010
+ } else {
146011
+ dataToHydrate = frameData;
146012
+ }
146013
+ const hydrated = hydrateData(dataToHydrate, revivers);
146014
+ if (mounted && hydrated !== void 0 && hydrated !== null) {
146015
+ const chunkId = chunkIdRef.current++;
146016
+ const text2 = typeof hydrated === "string" ? hydrated : JSON.stringify(hydrated, null, 2);
146017
+ setChunks((prev) => [...prev, { id: chunkId, text: text2 }]);
146018
+ }
146019
+ } catch (err) {
146020
+ console.error("Failed to process stream frame:", err);
146021
+ }
146022
+ }
146023
+ }
145931
146024
  } catch (err) {
145932
- if (abortController.signal.aborted) {
145933
- return;
146025
+ if (abortController.signal.aborted) return;
146026
+ if (mounted) {
146027
+ setError(err instanceof Error ? err.message : String(err));
146028
+ setIsLive(false);
145934
146029
  }
145935
- handleStreamError(err);
145936
146030
  }
145937
146031
  };
145938
146032
  void readStreamData();
@@ -145942,12 +146036,8 @@ function useStreamReader(env2, streamId) {
145942
146036
  abortControllerRef.current.abort();
145943
146037
  }
145944
146038
  };
145945
- }, [env2, streamId]);
145946
- return {
145947
- chunks,
145948
- isLive,
145949
- error: error2
145950
- };
146039
+ }, [env2, streamId, runId, encryptionKey]);
146040
+ return { chunks, isLive, error: error2 };
145951
146041
  }
145952
146042
  function LiveStatus({ hasError, errorMessage }) {
145953
146043
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center gap-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Tooltip, { children: [
@@ -146852,13 +146942,6 @@ function GraphTabContent({
146852
146942
  }
146853
146943
  );
146854
146944
  }
146855
- const RUN_LEVEL_EVENT_TYPES = /* @__PURE__ */ new Set([
146856
- "run_created",
146857
- "run_started",
146858
- "run_completed",
146859
- "run_failed",
146860
- "run_cancelled"
146861
- ]);
146862
146945
  function RunDetailView({
146863
146946
  runId,
146864
146947
  // TODO: This should open the right sidebar within the trace viewer
@@ -146926,52 +147009,13 @@ function RunDetailView({
146926
147009
  );
146927
147010
  const handleLoadEventData = reactExports.useCallback(
146928
147011
  async (event) => {
146929
- const isRunLevelEvent = RUN_LEVEL_EVENT_TYPES.has(event.eventType);
146930
- if (!isRunLevelEvent && event.correlationId) {
146931
- const { error: error3, result: result2 } = await unwrapServerActionResult(
146932
- fetchEventsByCorrelationId$1(env2, event.correlationId, {
146933
- sortOrder: "asc",
146934
- limit: 100,
146935
- withData: true
146936
- })
146937
- );
146938
- if (error3) {
146939
- throw error3;
146940
- }
146941
- const rawEvent2 = result2.data.find((e) => e.eventId === event.eventId);
146942
- if (!rawEvent2) return null;
146943
- const fullEvent2 = encryptionKeyRef.current ? await hydrateResourceIOWithKey(rawEvent2, encryptionKeyRef.current) : hydrateResourceIO(rawEvent2);
146944
- if ("eventData" in fullEvent2) {
146945
- return fullEvent2.eventData;
146946
- }
146947
- return null;
146948
- }
146949
147012
  const { error: error22, result } = await unwrapServerActionResult(
146950
- fetchEvents$1(env2, event.runId, {
146951
- sortOrder: "desc",
146952
- limit: 1e3,
146953
- withData: true
146954
- })
147013
+ fetchEvent$1(env2, event.runId, event.eventId, "all")
146955
147014
  );
146956
147015
  if (error22) {
146957
147016
  throw error22;
146958
147017
  }
146959
- let rawEvent = result.data.find((e) => e.eventId === event.eventId);
146960
- if (!rawEvent) {
146961
- const { error: ascError, result: ascResult } = await unwrapServerActionResult(
146962
- fetchEvents$1(env2, event.runId, {
146963
- sortOrder: "asc",
146964
- limit: 1e3,
146965
- withData: true
146966
- })
146967
- );
146968
- if (ascError) {
146969
- throw ascError;
146970
- }
146971
- rawEvent = ascResult.data.find((e) => e.eventId === event.eventId);
146972
- }
146973
- if (!rawEvent) return null;
146974
- const fullEvent = encryptionKeyRef.current ? await hydrateResourceIOWithKey(rawEvent, encryptionKeyRef.current) : hydrateResourceIO(rawEvent);
147018
+ const fullEvent = encryptionKeyRef.current ? await hydrateResourceIOWithKey(result, encryptionKeyRef.current) : hydrateResourceIO(result);
146975
147019
  if ("eventData" in fullEvent) {
146976
147020
  return fullEvent.eventData;
146977
147021
  }
@@ -146980,26 +147024,20 @@ function RunDetailView({
146980
147024
  [env2]
146981
147025
  );
146982
147026
  const handleLoadSidebarEventData = reactExports.useCallback(
146983
- async (correlationId, eventId) => {
147027
+ async (_correlationId, eventId) => {
146984
147028
  const { error: error22, result } = await unwrapServerActionResult(
146985
- fetchEventsByCorrelationId$1(env2, correlationId, {
146986
- sortOrder: "asc",
146987
- limit: 100,
146988
- withData: true
146989
- })
147029
+ fetchEvent$1(env2, runId, eventId, "all")
146990
147030
  );
146991
147031
  if (error22) {
146992
147032
  throw error22;
146993
147033
  }
146994
- const rawEvent = result.data.find((e) => e.eventId === eventId);
146995
- if (!rawEvent) return null;
146996
- const fullEvent = encryptionKeyRef.current ? await hydrateResourceIOWithKey(rawEvent, encryptionKeyRef.current) : hydrateResourceIO(rawEvent);
147034
+ const fullEvent = encryptionKeyRef.current ? await hydrateResourceIOWithKey(result, encryptionKeyRef.current) : hydrateResourceIO(result);
146997
147035
  if ("eventData" in fullEvent) {
146998
147036
  return fullEvent.eventData;
146999
147037
  }
147000
147038
  return null;
147001
147039
  },
147002
- [env2]
147040
+ [env2, runId]
147003
147041
  );
147004
147042
  const isLocalBackend = serverConfig.backendId === "local" || serverConfig.backendId === "@workflow/world-local";
147005
147043
  const {
@@ -147066,7 +147104,7 @@ function RunDetailView({
147066
147104
  chunks: streamChunks,
147067
147105
  isLive: streamIsLive,
147068
147106
  error: streamError
147069
- } = useStreamReader(env2, selectedStreamId);
147107
+ } = useStreamReader(env2, selectedStreamId, runId, encryptionKey);
147070
147108
  const handleCancelClick = () => {
147071
147109
  setShowCancelDialog(true);
147072
147110
  };
@@ -147426,6 +147464,7 @@ const handlers = {
147426
147464
  fetchSteps: (p2) => fetchSteps(p2.worldEnv ?? {}, p2.runId, p2.params ?? {}),
147427
147465
  fetchStep: (p2) => fetchStep(p2.worldEnv ?? {}, p2.runId, p2.stepId, p2.resolveData),
147428
147466
  fetchEvents: (p2) => fetchEvents(p2.worldEnv ?? {}, p2.runId, p2.params ?? {}),
147467
+ fetchEvent: (p2) => fetchEvent(p2.worldEnv ?? {}, p2.runId, p2.eventId, p2.resolveData),
147429
147468
  fetchEventsByCorrelationId: (p2) => fetchEventsByCorrelationId(p2.worldEnv ?? {}, p2.correlationId, p2.params ?? {}),
147430
147469
  fetchHooks: (p2) => fetchHooks(p2.worldEnv ?? {}, p2.params ?? {}),
147431
147470
  fetchHook: (p2) => fetchHook(p2.worldEnv ?? {}, p2.hookId, p2.resolveData),
@@ -147550,16 +147589,7 @@ async function loader({
147550
147589
  status: 500
147551
147590
  });
147552
147591
  }
147553
- const cborStream = stream.pipeThrough(new TransformStream({
147554
- transform(chunk, controller) {
147555
- const encoded = encode$2(chunk);
147556
- const length = new DataView(new ArrayBuffer(4));
147557
- length.setUint32(0, encoded.byteLength, false);
147558
- controller.enqueue(new Uint8Array(length.buffer));
147559
- controller.enqueue(new Uint8Array(encoded));
147560
- }
147561
- }));
147562
- return new Response(cborStream, {
147592
+ return new Response(stream, {
147563
147593
  headers: {
147564
147594
  "Content-Type": "application/octet-stream"
147565
147595
  }
@@ -147578,7 +147608,7 @@ const route4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProper
147578
147608
  __proto__: null,
147579
147609
  loader
147580
147610
  }, Symbol.toStringTag, { value: "Module" }));
147581
- const serverManifest = { "entry": { "module": "/assets/entry.client-BjpmGyLC.js", "imports": ["/assets/index-DklpUtP3.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": false, "module": "/assets/root-Ckv-c9_b.js", "imports": ["/assets/index-DklpUtP3.js", "/assets/mermaid-3ZIDBTTL-CJ6mkUFN.js"], "css": ["/assets/root-Dr_TuMgh.css", "/assets/mermaid-3ZIDBTTL-DKxHcEOp.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-bWDrLREI.js", "imports": ["/assets/index-DklpUtP3.js", "/assets/use-workflow-graph-JKiMb5g6.js", "/assets/mermaid-3ZIDBTTL-CJ6mkUFN.js"], "css": ["/assets/use-workflow-graph-yls6qlc0.css", "/assets/mermaid-3ZIDBTTL-DKxHcEOp.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-EcdnCjQk.js", "imports": ["/assets/index-DklpUtP3.js", "/assets/use-workflow-graph-JKiMb5g6.js", "/assets/mermaid-3ZIDBTTL-CJ6mkUFN.js"], "css": ["/assets/use-workflow-graph-yls6qlc0.css", "/assets/mermaid-3ZIDBTTL-DKxHcEOp.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-daa82ff1.js", "version": "daa82ff1", "sri": void 0 };
147611
+ const serverManifest = { "entry": { "module": "/assets/entry.client-BjpmGyLC.js", "imports": ["/assets/index-DklpUtP3.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": false, "module": "/assets/root-B2fanH6r.js", "imports": ["/assets/index-DklpUtP3.js", "/assets/mermaid-3ZIDBTTL-BhkyG8Sq.js"], "css": ["/assets/root-Dr_TuMgh.css", "/assets/mermaid-3ZIDBTTL-DKxHcEOp.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-B4MMr7LP.js", "imports": ["/assets/index-DklpUtP3.js", "/assets/use-workflow-graph-D6xsvBGu.js", "/assets/mermaid-3ZIDBTTL-BhkyG8Sq.js"], "css": ["/assets/use-workflow-graph-yls6qlc0.css", "/assets/mermaid-3ZIDBTTL-DKxHcEOp.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-D40YBNgh.js", "imports": ["/assets/index-DklpUtP3.js", "/assets/use-workflow-graph-D6xsvBGu.js", "/assets/mermaid-3ZIDBTTL-BhkyG8Sq.js", "/assets/encryption-8OvC6eoJ.js"], "css": ["/assets/use-workflow-graph-yls6qlc0.css", "/assets/mermaid-3ZIDBTTL-DKxHcEOp.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-ef94afe1.js", "version": "ef94afe1", "sri": void 0 };
147582
147612
  const assetsBuildDirectory = "build/client";
147583
147613
  const basename = "/";
147584
147614
  const future = { "unstable_optimizeDeps": false, "unstable_subResourceIntegrity": false, "unstable_trailingSlashAwareDataRequests": false, "unstable_previewServerPrerendering": false, "v8_middleware": false, "v8_splitRouteModules": false, "v8_viteEnvironmentApi": false };