@workflow/world-testing 4.0.1-beta.33 → 4.0.1-beta.35

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.
@@ -488,11 +488,11 @@ var require_wait_until = __commonJS({
488
488
  }), mod), "__toCommonJS");
489
489
  var wait_until_exports = {};
490
490
  __export2(wait_until_exports, {
491
- waitUntil: /* @__PURE__ */ __name(() => waitUntil6, "waitUntil")
491
+ waitUntil: /* @__PURE__ */ __name(() => waitUntil7, "waitUntil")
492
492
  });
493
493
  module2.exports = __toCommonJS2(wait_until_exports);
494
494
  var import_get_context = require_get_context();
495
- var waitUntil6 = /* @__PURE__ */ __name((promise2) => {
495
+ var waitUntil7 = /* @__PURE__ */ __name((promise2) => {
496
496
  if (promise2 === null || typeof promise2 !== "object" || typeof promise2.then !== "function") {
497
497
  throw new TypeError(`waitUntil can only be called with a Promise, got ${typeof promise2}`);
498
498
  }
@@ -24511,30 +24511,6 @@ __name(__builtin_response_text, "__builtin_response_text");
24511
24511
  registerStepFunction("__builtin_response_array_buffer", __builtin_response_array_buffer);
24512
24512
  registerStepFunction("__builtin_response_json", __builtin_response_json);
24513
24513
  registerStepFunction("__builtin_response_text", __builtin_response_text);
24514
- // workflows/addition.ts
24515
- async function add(num, num2) {
24516
- return num + num2;
24517
- }
24518
- __name(add, "add");
24519
- async function addition(num, num2) {
24520
- throw new Error("You attempted to execute workflow addition function directly. To start a workflow, use start(addition) from workflow/api");
24521
- }
24522
- __name(addition, "addition");
24523
- addition.workflowId = "workflow//workflows/addition.ts//addition";
24524
- registerStepFunction("step//workflows/addition.ts//add", add);
24525
- // workflows/noop.ts
24526
- var count = 0;
24527
- async function noop(_i) {
24528
- count++;
24529
- return count;
24530
- }
24531
- __name(noop, "noop");
24532
- async function brokenWf() {
24533
- throw new Error("You attempted to execute workflow brokenWf function directly. To start a workflow, use start(brokenWf) from workflow/api");
24534
- }
24535
- __name(brokenWf, "brokenWf");
24536
- brokenWf.workflowId = "workflow//workflows/noop.ts//brokenWf";
24537
- registerStepFunction("step//workflows/noop.ts//noop", noop);
24538
24514
  // ../utils/dist/index.js
24539
24515
  var import_ms = __toESM(require_ms(), 1);
24540
24516
  function once(fn) {
@@ -25209,6 +25185,169 @@ function stringify_primitive(thing) {
25209
25185
  return String(thing);
25210
25186
  }
25211
25187
  __name(stringify_primitive, "stringify_primitive");
25188
+ // ../../node_modules/.pnpm/ulid@3.0.1/node_modules/ulid/dist/node/index.js
25189
+ var import_node_crypto = __toESM(require("node:crypto"), 1);
25190
+ var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
25191
+ var ENCODING_LEN = 32;
25192
+ var RANDOM_LEN = 16;
25193
+ var TIME_LEN = 10;
25194
+ var TIME_MAX = 281474976710655;
25195
+ var ULIDErrorCode;
25196
+ (function (ULIDErrorCode2) {
25197
+ ULIDErrorCode2["Base32IncorrectEncoding"] = "B32_ENC_INVALID";
25198
+ ULIDErrorCode2["DecodeTimeInvalidCharacter"] = "DEC_TIME_CHAR";
25199
+ ULIDErrorCode2["DecodeTimeValueMalformed"] = "DEC_TIME_MALFORMED";
25200
+ ULIDErrorCode2["EncodeTimeNegative"] = "ENC_TIME_NEG";
25201
+ ULIDErrorCode2["EncodeTimeSizeExceeded"] = "ENC_TIME_SIZE_EXCEED";
25202
+ ULIDErrorCode2["EncodeTimeValueMalformed"] = "ENC_TIME_MALFORMED";
25203
+ ULIDErrorCode2["PRNGDetectFailure"] = "PRNG_DETECT";
25204
+ ULIDErrorCode2["ULIDInvalid"] = "ULID_INVALID";
25205
+ ULIDErrorCode2["Unexpected"] = "UNEXPECTED";
25206
+ ULIDErrorCode2["UUIDInvalid"] = "UUID_INVALID";
25207
+ })(ULIDErrorCode || (ULIDErrorCode = {}));
25208
+ var ULIDError = class extends Error {
25209
+ static {
25210
+ __name(this, "ULIDError");
25211
+ }
25212
+ constructor(errorCode, message) {
25213
+ super(`${message} (${errorCode})`);
25214
+ this.name = "ULIDError";
25215
+ this.code = errorCode;
25216
+ }
25217
+ };
25218
+ function randomChar(prng) {
25219
+ const randomPosition = Math.floor(prng() * ENCODING_LEN) % ENCODING_LEN;
25220
+ return ENCODING.charAt(randomPosition);
25221
+ }
25222
+ __name(randomChar, "randomChar");
25223
+ function replaceCharAt(str, index, char) {
25224
+ if (index > str.length - 1) {
25225
+ return str;
25226
+ }
25227
+ return str.substr(0, index) + char + str.substr(index + 1);
25228
+ }
25229
+ __name(replaceCharAt, "replaceCharAt");
25230
+ function incrementBase32(str) {
25231
+ let done = void 0, index = str.length, char, charIndex, output = str;
25232
+ const maxCharIndex = ENCODING_LEN - 1;
25233
+ while (!done && index-- >= 0) {
25234
+ char = output[index];
25235
+ charIndex = ENCODING.indexOf(char);
25236
+ if (charIndex === -1) {
25237
+ throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Incorrectly encoded string");
25238
+ }
25239
+ if (charIndex === maxCharIndex) {
25240
+ output = replaceCharAt(output, index, ENCODING[0]);
25241
+ continue;
25242
+ }
25243
+ done = replaceCharAt(output, index, ENCODING[charIndex + 1]);
25244
+ }
25245
+ if (typeof done === "string") {
25246
+ return done;
25247
+ }
25248
+ throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Failed incrementing string");
25249
+ }
25250
+ __name(incrementBase32, "incrementBase32");
25251
+ function decodeTime(id) {
25252
+ if (id.length !== TIME_LEN + RANDOM_LEN) {
25253
+ throw new ULIDError(ULIDErrorCode.DecodeTimeValueMalformed, "Malformed ULID");
25254
+ }
25255
+ const time3 = id.substr(0, TIME_LEN).toUpperCase().split("").reverse().reduce((carry, char, index) => {
25256
+ const encodingIndex = ENCODING.indexOf(char);
25257
+ if (encodingIndex === -1) {
25258
+ throw new ULIDError(ULIDErrorCode.DecodeTimeInvalidCharacter, `Time decode error: Invalid character: ${char}`);
25259
+ }
25260
+ return carry += encodingIndex * Math.pow(ENCODING_LEN, index);
25261
+ }, 0);
25262
+ if (time3 > TIME_MAX) {
25263
+ throw new ULIDError(ULIDErrorCode.DecodeTimeValueMalformed, `Malformed ULID: timestamp too large: ${time3}`);
25264
+ }
25265
+ return time3;
25266
+ }
25267
+ __name(decodeTime, "decodeTime");
25268
+ function detectPRNG(root) {
25269
+ const rootLookup = detectRoot();
25270
+ const globalCrypto = rootLookup && (rootLookup.crypto || rootLookup.msCrypto) || (typeof import_node_crypto.default !== "undefined" ? import_node_crypto.default : null);
25271
+ if (typeof globalCrypto?.getRandomValues === "function") {
25272
+ return () => {
25273
+ const buffer = new Uint8Array(1);
25274
+ globalCrypto.getRandomValues(buffer);
25275
+ return buffer[0] / 255;
25276
+ };
25277
+ }
25278
+ else if (typeof globalCrypto?.randomBytes === "function") {
25279
+ return () => globalCrypto.randomBytes(1).readUInt8() / 255;
25280
+ }
25281
+ else if (import_node_crypto.default?.randomBytes) {
25282
+ return () => import_node_crypto.default.randomBytes(1).readUInt8() / 255;
25283
+ }
25284
+ throw new ULIDError(ULIDErrorCode.PRNGDetectFailure, "Failed to find a reliable PRNG");
25285
+ }
25286
+ __name(detectPRNG, "detectPRNG");
25287
+ function detectRoot() {
25288
+ if (inWebWorker())
25289
+ return self;
25290
+ if (typeof window !== "undefined") {
25291
+ return window;
25292
+ }
25293
+ if (typeof global !== "undefined") {
25294
+ return global;
25295
+ }
25296
+ if (typeof globalThis !== "undefined") {
25297
+ return globalThis;
25298
+ }
25299
+ return null;
25300
+ }
25301
+ __name(detectRoot, "detectRoot");
25302
+ function encodeRandom(len, prng) {
25303
+ let str = "";
25304
+ for (; len > 0; len--) {
25305
+ str = randomChar(prng) + str;
25306
+ }
25307
+ return str;
25308
+ }
25309
+ __name(encodeRandom, "encodeRandom");
25310
+ function encodeTime(now, len = TIME_LEN) {
25311
+ if (isNaN(now)) {
25312
+ throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be a number: ${now}`);
25313
+ }
25314
+ else if (now > TIME_MAX) {
25315
+ throw new ULIDError(ULIDErrorCode.EncodeTimeSizeExceeded, `Cannot encode a time larger than ${TIME_MAX}: ${now}`);
25316
+ }
25317
+ else if (now < 0) {
25318
+ throw new ULIDError(ULIDErrorCode.EncodeTimeNegative, `Time must be positive: ${now}`);
25319
+ }
25320
+ else if (Number.isInteger(now) === false) {
25321
+ throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be an integer: ${now}`);
25322
+ }
25323
+ let mod, str = "";
25324
+ for (let currentLen = len; currentLen > 0; currentLen--) {
25325
+ mod = now % ENCODING_LEN;
25326
+ str = ENCODING.charAt(mod) + str;
25327
+ now = (now - mod) / ENCODING_LEN;
25328
+ }
25329
+ return str;
25330
+ }
25331
+ __name(encodeTime, "encodeTime");
25332
+ function inWebWorker() {
25333
+ return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
25334
+ }
25335
+ __name(inWebWorker, "inWebWorker");
25336
+ function monotonicFactory(prng) {
25337
+ const currentPRNG = prng || detectPRNG();
25338
+ let lastTime = 0, lastRandom;
25339
+ return /* @__PURE__ */ __name(function _ulid2(seedTime) {
25340
+ const seed = !seedTime || isNaN(seedTime) ? Date.now() : seedTime;
25341
+ if (seed <= lastTime) {
25342
+ const incrementedRandom = lastRandom = incrementBase32(lastRandom);
25343
+ return encodeTime(lastTime, TIME_LEN) + incrementedRandom;
25344
+ }
25345
+ lastTime = seed;
25346
+ const newRandom = lastRandom = encodeRandom(RANDOM_LEN, currentPRNG);
25347
+ return encodeTime(seed, TIME_LEN) + newRandom;
25348
+ }, "_ulid");
25349
+ }
25350
+ __name(monotonicFactory, "monotonicFactory");
25212
25351
  // ../core/dist/runtime/world.js
25213
25352
  var import_node_module = require("node:module");
25214
25353
  var import_node_path4 = require("node:path");
@@ -41182,170 +41321,6 @@ var StepSchema = external_exports.object({
41182
41321
  });
41183
41322
  // ../world-local/dist/queue.js
41184
41323
  var import_async_sema = __toESM(require_lib(), 1);
41185
- // ../../node_modules/.pnpm/ulid@3.0.1/node_modules/ulid/dist/node/index.js
41186
- var import_node_crypto = __toESM(require("node:crypto"), 1);
41187
- var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
41188
- var ENCODING_LEN = 32;
41189
- var RANDOM_LEN = 16;
41190
- var TIME_LEN = 10;
41191
- var TIME_MAX = 281474976710655;
41192
- var ULIDErrorCode;
41193
- (function (ULIDErrorCode2) {
41194
- ULIDErrorCode2["Base32IncorrectEncoding"] = "B32_ENC_INVALID";
41195
- ULIDErrorCode2["DecodeTimeInvalidCharacter"] = "DEC_TIME_CHAR";
41196
- ULIDErrorCode2["DecodeTimeValueMalformed"] = "DEC_TIME_MALFORMED";
41197
- ULIDErrorCode2["EncodeTimeNegative"] = "ENC_TIME_NEG";
41198
- ULIDErrorCode2["EncodeTimeSizeExceeded"] = "ENC_TIME_SIZE_EXCEED";
41199
- ULIDErrorCode2["EncodeTimeValueMalformed"] = "ENC_TIME_MALFORMED";
41200
- ULIDErrorCode2["PRNGDetectFailure"] = "PRNG_DETECT";
41201
- ULIDErrorCode2["ULIDInvalid"] = "ULID_INVALID";
41202
- ULIDErrorCode2["Unexpected"] = "UNEXPECTED";
41203
- ULIDErrorCode2["UUIDInvalid"] = "UUID_INVALID";
41204
- })(ULIDErrorCode || (ULIDErrorCode = {}));
41205
- var ULIDError = class extends Error {
41206
- static {
41207
- __name(this, "ULIDError");
41208
- }
41209
- constructor(errorCode, message) {
41210
- super(`${message} (${errorCode})`);
41211
- this.name = "ULIDError";
41212
- this.code = errorCode;
41213
- }
41214
- };
41215
- function randomChar(prng) {
41216
- const randomPosition = Math.floor(prng() * ENCODING_LEN) % ENCODING_LEN;
41217
- return ENCODING.charAt(randomPosition);
41218
- }
41219
- __name(randomChar, "randomChar");
41220
- function replaceCharAt(str, index, char) {
41221
- if (index > str.length - 1) {
41222
- return str;
41223
- }
41224
- return str.substr(0, index) + char + str.substr(index + 1);
41225
- }
41226
- __name(replaceCharAt, "replaceCharAt");
41227
- function incrementBase32(str) {
41228
- let done = void 0, index = str.length, char, charIndex, output = str;
41229
- const maxCharIndex = ENCODING_LEN - 1;
41230
- while (!done && index-- >= 0) {
41231
- char = output[index];
41232
- charIndex = ENCODING.indexOf(char);
41233
- if (charIndex === -1) {
41234
- throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Incorrectly encoded string");
41235
- }
41236
- if (charIndex === maxCharIndex) {
41237
- output = replaceCharAt(output, index, ENCODING[0]);
41238
- continue;
41239
- }
41240
- done = replaceCharAt(output, index, ENCODING[charIndex + 1]);
41241
- }
41242
- if (typeof done === "string") {
41243
- return done;
41244
- }
41245
- throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Failed incrementing string");
41246
- }
41247
- __name(incrementBase32, "incrementBase32");
41248
- function decodeTime(id) {
41249
- if (id.length !== TIME_LEN + RANDOM_LEN) {
41250
- throw new ULIDError(ULIDErrorCode.DecodeTimeValueMalformed, "Malformed ULID");
41251
- }
41252
- const time3 = id.substr(0, TIME_LEN).toUpperCase().split("").reverse().reduce((carry, char, index) => {
41253
- const encodingIndex = ENCODING.indexOf(char);
41254
- if (encodingIndex === -1) {
41255
- throw new ULIDError(ULIDErrorCode.DecodeTimeInvalidCharacter, `Time decode error: Invalid character: ${char}`);
41256
- }
41257
- return carry += encodingIndex * Math.pow(ENCODING_LEN, index);
41258
- }, 0);
41259
- if (time3 > TIME_MAX) {
41260
- throw new ULIDError(ULIDErrorCode.DecodeTimeValueMalformed, `Malformed ULID: timestamp too large: ${time3}`);
41261
- }
41262
- return time3;
41263
- }
41264
- __name(decodeTime, "decodeTime");
41265
- function detectPRNG(root) {
41266
- const rootLookup = detectRoot();
41267
- const globalCrypto = rootLookup && (rootLookup.crypto || rootLookup.msCrypto) || (typeof import_node_crypto.default !== "undefined" ? import_node_crypto.default : null);
41268
- if (typeof globalCrypto?.getRandomValues === "function") {
41269
- return () => {
41270
- const buffer = new Uint8Array(1);
41271
- globalCrypto.getRandomValues(buffer);
41272
- return buffer[0] / 255;
41273
- };
41274
- }
41275
- else if (typeof globalCrypto?.randomBytes === "function") {
41276
- return () => globalCrypto.randomBytes(1).readUInt8() / 255;
41277
- }
41278
- else if (import_node_crypto.default?.randomBytes) {
41279
- return () => import_node_crypto.default.randomBytes(1).readUInt8() / 255;
41280
- }
41281
- throw new ULIDError(ULIDErrorCode.PRNGDetectFailure, "Failed to find a reliable PRNG");
41282
- }
41283
- __name(detectPRNG, "detectPRNG");
41284
- function detectRoot() {
41285
- if (inWebWorker())
41286
- return self;
41287
- if (typeof window !== "undefined") {
41288
- return window;
41289
- }
41290
- if (typeof global !== "undefined") {
41291
- return global;
41292
- }
41293
- if (typeof globalThis !== "undefined") {
41294
- return globalThis;
41295
- }
41296
- return null;
41297
- }
41298
- __name(detectRoot, "detectRoot");
41299
- function encodeRandom(len, prng) {
41300
- let str = "";
41301
- for (; len > 0; len--) {
41302
- str = randomChar(prng) + str;
41303
- }
41304
- return str;
41305
- }
41306
- __name(encodeRandom, "encodeRandom");
41307
- function encodeTime(now, len = TIME_LEN) {
41308
- if (isNaN(now)) {
41309
- throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be a number: ${now}`);
41310
- }
41311
- else if (now > TIME_MAX) {
41312
- throw new ULIDError(ULIDErrorCode.EncodeTimeSizeExceeded, `Cannot encode a time larger than ${TIME_MAX}: ${now}`);
41313
- }
41314
- else if (now < 0) {
41315
- throw new ULIDError(ULIDErrorCode.EncodeTimeNegative, `Time must be positive: ${now}`);
41316
- }
41317
- else if (Number.isInteger(now) === false) {
41318
- throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be an integer: ${now}`);
41319
- }
41320
- let mod, str = "";
41321
- for (let currentLen = len; currentLen > 0; currentLen--) {
41322
- mod = now % ENCODING_LEN;
41323
- str = ENCODING.charAt(mod) + str;
41324
- now = (now - mod) / ENCODING_LEN;
41325
- }
41326
- return str;
41327
- }
41328
- __name(encodeTime, "encodeTime");
41329
- function inWebWorker() {
41330
- return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
41331
- }
41332
- __name(inWebWorker, "inWebWorker");
41333
- function monotonicFactory(prng) {
41334
- const currentPRNG = prng || detectPRNG();
41335
- let lastTime = 0, lastRandom;
41336
- return /* @__PURE__ */ __name(function _ulid2(seedTime) {
41337
- const seed = !seedTime || isNaN(seedTime) ? Date.now() : seedTime;
41338
- if (seed <= lastTime) {
41339
- const incrementedRandom = lastRandom = incrementBase32(lastRandom);
41340
- return encodeTime(lastTime, TIME_LEN) + incrementedRandom;
41341
- }
41342
- lastTime = seed;
41343
- const newRandom = lastRandom = encodeRandom(RANDOM_LEN, currentPRNG);
41344
- return encodeTime(seed, TIME_LEN) + newRandom;
41345
- }, "_ulid");
41346
- }
41347
- __name(monotonicFactory, "monotonicFactory");
41348
- // ../world-local/dist/queue.js
41349
41324
  var import_undici = __toESM(require_undici(), 1);
41350
41325
  var LOCAL_QUEUE_MAX_VISIBILITY = parseInt(process.env.WORKFLOW_LOCAL_QUEUE_MAX_VISIBILITY ?? "0", 10) || Infinity;
41351
41326
  var DEFAULT_CONCURRENCY_LIMIT = 100;
@@ -41657,12 +41632,7 @@ async function paginatedFileSystemQuery(config3) {
41657
41632
  return sortOrder === "desc" ? fileTime < cursorTime : fileTime > cursorTime;
41658
41633
  }
41659
41634
  }
41660
- return false;
41661
- });
41662
- }
41663
- else {
41664
- candidateFileIds = relevantFileIds.filter((fileId) => {
41665
- return getCreatedAt(`${fileId}.json`) !== null;
41635
+ return true;
41666
41636
  });
41667
41637
  }
41668
41638
  const validItems = [];
@@ -41766,9 +41736,7 @@ var getObjectCreatedAt = /* @__PURE__ */ __name((idPrefix) => (filename) => {
41766
41736
  return ulidToDate(ulid5);
41767
41737
  }
41768
41738
  if (idPrefix === "step") {
41769
- const runId = filename.substring(0, dashIndex);
41770
- const ulid5 = runId.replace(/^wrun_/, "");
41771
- return ulidToDate(ulid5);
41739
+ return null;
41772
41740
  }
41773
41741
  const id = filename.substring(dashIndex + 1).replace(/\.json$/, "");
41774
41742
  const ulid4 = id.replace(replaceRegex, "");
@@ -42184,6 +42152,9 @@ __name(createStorage, "createStorage");
42184
42152
  var import_node_events = require("node:events");
42185
42153
  var import_node_path3 = __toESM(require("node:path"), 1);
42186
42154
  var monotonicUlid2 = monotonicFactory(() => Math.random());
42155
+ var RunStreamsSchema = external_exports.object({
42156
+ streams: external_exports.array(external_exports.string())
42157
+ });
42187
42158
  function serializeChunk(chunk) {
42188
42159
  const eofByte = Buffer.from([
42189
42160
  chunk.eof ? 1 : 0
@@ -42205,10 +42176,31 @@ function deserializeChunk(serialized) {
42205
42176
  __name(deserializeChunk, "deserializeChunk");
42206
42177
  function createStreamer(basedir) {
42207
42178
  const streamEmitter = new import_node_events.EventEmitter();
42179
+ const registeredStreams = /* @__PURE__ */ new Set();
42180
+ async function registerStreamForRun(runId, streamName) {
42181
+ const cacheKey = `${runId}:${streamName}`;
42182
+ if (registeredStreams.has(cacheKey)) {
42183
+ return;
42184
+ }
42185
+ const runStreamsPath = import_node_path3.default.join(basedir, "streams", "runs", `${runId}.json`);
42186
+ const existing = await readJSON(runStreamsPath, RunStreamsSchema);
42187
+ const streams = existing?.streams ?? [];
42188
+ if (!streams.includes(streamName)) {
42189
+ streams.push(streamName);
42190
+ await writeJSON(runStreamsPath, {
42191
+ streams
42192
+ }, {
42193
+ overwrite: true
42194
+ });
42195
+ }
42196
+ registeredStreams.add(cacheKey);
42197
+ }
42198
+ __name(registerStreamForRun, "registerStreamForRun");
42208
42199
  return {
42209
42200
  async writeToStream(name, _runId, chunk) {
42210
- await _runId;
42211
- const chunkId = `strm_${monotonicUlid2()}`;
42201
+ const runId = await _runId;
42202
+ await registerStreamForRun(runId, name);
42203
+ const chunkId = `chnk_${monotonicUlid2()}`;
42212
42204
  let chunkBuffer;
42213
42205
  if (typeof chunk === "string") {
42214
42206
  chunkBuffer = Buffer.from(new TextEncoder().encode(chunk));
@@ -42233,8 +42225,9 @@ function createStreamer(basedir) {
42233
42225
  });
42234
42226
  },
42235
42227
  async closeStream(name, _runId) {
42236
- await _runId;
42237
- const chunkId = `strm_${monotonicUlid2()}`;
42228
+ const runId = await _runId;
42229
+ await registerStreamForRun(runId, name);
42230
+ const chunkId = `chnk_${monotonicUlid2()}`;
42238
42231
  const chunkPath = import_node_path3.default.join(basedir, "streams", "chunks", `${name}-${chunkId}.json`);
42239
42232
  await write(chunkPath, serializeChunk({
42240
42233
  chunk: Buffer.from([]),
@@ -42245,30 +42238,9 @@ function createStreamer(basedir) {
42245
42238
  });
42246
42239
  },
42247
42240
  async listStreamsByRunId(runId) {
42248
- const chunksDir = import_node_path3.default.join(basedir, "streams", "chunks");
42249
- const files = await listJSONFiles(chunksDir);
42250
- const streamPrefix = runId.replace("wrun_", "strm_") + "_user";
42251
- const streamNames = /* @__PURE__ */ new Set();
42252
- for (const file2 of files) {
42253
- const lastDashIndex = file2.lastIndexOf("-strm_");
42254
- if (lastDashIndex === -1) {
42255
- const parts = file2.split("-");
42256
- if (parts.length >= 2) {
42257
- parts.pop();
42258
- const streamName = parts.join("-");
42259
- if (streamName.startsWith(streamPrefix)) {
42260
- streamNames.add(streamName);
42261
- }
42262
- }
42263
- }
42264
- else {
42265
- const streamName = file2.substring(0, lastDashIndex);
42266
- if (streamName.startsWith(streamPrefix)) {
42267
- streamNames.add(streamName);
42268
- }
42269
- }
42270
- }
42271
- return Array.from(streamNames);
42241
+ const runStreamsPath = import_node_path3.default.join(basedir, "streams", "runs", `${runId}.json`);
42242
+ const data = await readJSON(runStreamsPath, RunStreamsSchema);
42243
+ return data?.streams ?? [];
42272
42244
  },
42273
42245
  async readFromStream(name, startIndex = 0) {
42274
42246
  const chunksDir = import_node_path3.default.join(basedir, "streams", "chunks");
@@ -42365,7 +42337,7 @@ __name(createLocalWorld, "createLocalWorld");
42365
42337
  var import_node_os = __toESM(require("node:os"), 1);
42366
42338
  var import_oidc2 = __toESM(require_dist(), 1);
42367
42339
  // ../world-vercel/dist/version.js
42368
- var version2 = "4.0.1-beta.20";
42340
+ var version2 = "4.0.1-beta.22";
42369
42341
  // ../world-vercel/dist/utils.js
42370
42342
  var DEFAULT_RESOLVE_DATA_OPTION2 = "all";
42371
42343
  function dateToStringReplacer(_key, value) {
@@ -42467,36 +42439,36 @@ __name(getHttpConfig, "getHttpConfig");
42467
42439
  async function makeRequest({ endpoint, options = {}, config: config3 = {}, schema }) {
42468
42440
  const { baseUrl, headers } = await getHttpConfig(config3);
42469
42441
  headers.set("Content-Type", "application/json");
42442
+ headers.set("X-Request-Time", Date.now().toString());
42470
42443
  const url2 = `${baseUrl}${endpoint}`;
42471
- const response = await fetch(url2, {
42444
+ const request = new Request(url2, {
42472
42445
  ...options,
42473
42446
  headers
42474
42447
  });
42448
+ const response = await fetch(request);
42475
42449
  if (!response.ok) {
42476
42450
  const errorData = await response.json().catch(() => ({}));
42477
42451
  if (process.env.DEBUG === "1") {
42478
42452
  const stringifiedHeaders = Array.from(headers.entries()).map(([key, value]) => `-H "${key}: ${value}"`).join(" ");
42479
42453
  console.error(`Failed to fetch, reproduce with:
42480
- curl -X ${options.method} ${stringifiedHeaders} "${url2}"`);
42454
+ curl -X ${request.method} ${stringifiedHeaders} "${url2}"`);
42481
42455
  }
42482
- throw new WorkflowAPIError(errorData.message || `${options.method ?? "GET"} ${endpoint} -> HTTP ${response.status}: ${response.statusText}`, {
42456
+ throw new WorkflowAPIError(errorData.message || `${request.method} ${endpoint} -> HTTP ${response.status}: ${response.statusText}`, {
42483
42457
  url: url2,
42484
42458
  status: response.status,
42485
42459
  code: errorData.code
42486
42460
  });
42487
42461
  }
42462
+ const text = await response.text();
42488
42463
  try {
42489
- const text = await response.text();
42490
42464
  return schema.parse(JSON.parse(text));
42491
42465
  }
42492
42466
  catch (error45) {
42493
- if (error45 instanceof ZodError) {
42494
- throw new WorkflowAPIError(`Failed to parse server response for ${options.method ?? "GET"} ${endpoint}: ${error45.message}`, {
42495
- url: url2,
42496
- cause: error45
42497
- });
42498
- }
42499
- throw new WorkflowAPIError(`Failed to parse server response for ${options.method ?? "GET"} ${endpoint}`, {
42467
+ throw new WorkflowAPIError(`Failed to parse server response for ${request.method} ${endpoint}:
42468
+
42469
+ ${error45}
42470
+
42471
+ Response body: ${text}`, {
42500
42472
  url: url2,
42501
42473
  cause: error45
42502
42474
  });
@@ -42506,9 +42478,19 @@ __name(makeRequest, "makeRequest");
42506
42478
  // ../world-vercel/dist/queue.js
42507
42479
  var MessageWrapper = object({
42508
42480
  payload: QueuePayloadSchema,
42509
- queueName: ValidQueueName
42510
- });
42511
- var VERCEL_QUEUE_MAX_VISIBILITY = 39600;
42481
+ queueName: ValidQueueName,
42482
+ /**
42483
+ * The deployment ID to use when re-enqueueing the message.
42484
+ * This ensures the message is processed by the same deployment.
42485
+ */
42486
+ deploymentId: string2().optional()
42487
+ });
42488
+ var VERCEL_QUEUE_MESSAGE_LIFETIME = Number(process.env.VERCEL_QUEUE_MESSAGE_LIFETIME || 86400
42489
+ // 24 hours in seconds
42490
+ );
42491
+ var MESSAGE_LIFETIME_BUFFER = Number(process.env.VERCEL_QUEUE_MESSAGE_LIFETIME_BUFFER || 3600
42492
+ // 1 hour buffer before lifetime expires
42493
+ );
42512
42494
  function createQueue2(config3) {
42513
42495
  const { baseUrl, usingProxy } = getHttpUrl(config3);
42514
42496
  const headers = getHeaders(config3);
@@ -42518,15 +42500,17 @@ function createQueue2(config3) {
42518
42500
  token: usingProxy ? config3?.token : void 0,
42519
42501
  headers: Object.fromEntries(headers.entries())
42520
42502
  });
42521
- const queue = /* @__PURE__ */ __name(async (queueName, x, opts) => {
42503
+ const queue = /* @__PURE__ */ __name(async (queueName, payload, opts) => {
42522
42504
  const hasEncoder = typeof MessageWrapper.encode === "function";
42523
42505
  if (!hasEncoder) {
42524
42506
  console.warn("Using zod v3 compatibility mode for queue() calls - this may not work as expected");
42525
42507
  }
42526
42508
  const encoder = hasEncoder ? MessageWrapper.encode : (data) => data;
42527
42509
  const encoded = encoder({
42528
- payload: x,
42529
- queueName
42510
+ payload,
42511
+ queueName,
42512
+ // Store deploymentId in the message so it can be preserved when re-enqueueing
42513
+ deploymentId: opts?.deploymentId
42530
42514
  });
42531
42515
  const sanitizedQueueName = queueName.replace(/[^A-Za-z0-9-_]/g, "-");
42532
42516
  const { messageId } = await queueClient.send(sanitizedQueueName, encoded, opts);
@@ -42538,16 +42522,24 @@ function createQueue2(config3) {
42538
42522
  return queueClient.handleCallback({
42539
42523
  [`${prefix}*`]: {
42540
42524
  default: /* @__PURE__ */ __name(async (body, meta) => {
42541
- const { payload, queueName } = MessageWrapper.parse(body);
42525
+ const { payload, queueName, deploymentId } = MessageWrapper.parse(body);
42542
42526
  const result = await handler(payload, {
42543
42527
  queueName,
42544
42528
  messageId: MessageId.parse(meta.messageId),
42545
42529
  attempt: meta.deliveryCount
42546
42530
  });
42547
42531
  if (typeof result?.timeoutSeconds === "number") {
42548
- const adjustedTimeoutSeconds = Math.min(result.timeoutSeconds, VERCEL_QUEUE_MAX_VISIBILITY);
42549
- if (adjustedTimeoutSeconds !== result.timeoutSeconds) {
42550
- result.timeoutSeconds = adjustedTimeoutSeconds;
42532
+ const now = Date.now();
42533
+ const messageAge = (now - meta.createdAt.getTime()) / 1e3;
42534
+ const maxAllowedTimeout = VERCEL_QUEUE_MESSAGE_LIFETIME - MESSAGE_LIFETIME_BUFFER - messageAge;
42535
+ if (maxAllowedTimeout <= 0) {
42536
+ await queue(queueName, payload, {
42537
+ deploymentId
42538
+ });
42539
+ return void 0;
42540
+ }
42541
+ else if (result.timeoutSeconds > maxAllowedTimeout) {
42542
+ result.timeoutSeconds = maxAllowedTimeout;
42551
42543
  }
42552
42544
  }
42553
42545
  return result;
@@ -43204,11 +43196,13 @@ var WORKFLOW_CREATE_HOOK = Symbol.for("WORKFLOW_CREATE_HOOK");
43204
43196
  var WORKFLOW_SLEEP = Symbol.for("WORKFLOW_SLEEP");
43205
43197
  var WORKFLOW_CONTEXT = Symbol.for("WORKFLOW_CONTEXT");
43206
43198
  var WORKFLOW_GET_STREAM_ID = Symbol.for("WORKFLOW_GET_STREAM_ID");
43199
+ var STABLE_ULID = Symbol.for("WORKFLOW_STABLE_ULID");
43207
43200
  var STREAM_NAME_SYMBOL = Symbol.for("WORKFLOW_STREAM_NAME");
43208
43201
  var STREAM_TYPE_SYMBOL = Symbol.for("WORKFLOW_STREAM_TYPE");
43209
43202
  var BODY_INIT_SYMBOL = Symbol.for("BODY_INIT");
43210
43203
  var WEBHOOK_RESPONSE_WRITABLE = Symbol.for("WEBHOOK_RESPONSE_WRITABLE");
43211
43204
  // ../core/dist/serialization.js
43205
+ var defaultUlid = monotonicFactory();
43212
43206
  function formatSerializationError(context, error45) {
43213
43207
  const verb = context.includes("return value") ? "returning" : "passing";
43214
43208
  let message = `Failed to serialize ${context}`;
@@ -43465,7 +43459,8 @@ function getStepReducers(global2 = globalThis, ops, runId) {
43465
43459
  if (!runId) {
43466
43460
  throw new Error("ReadableStream cannot be serialized without a valid runId");
43467
43461
  }
43468
- name = global2.crypto.randomUUID();
43462
+ const streamId = (global2[STABLE_ULID] || defaultUlid)();
43463
+ name = `strm_${streamId}`;
43469
43464
  type = getStreamType(value);
43470
43465
  const writable = new WorkflowServerWritableStream(name, runId);
43471
43466
  if (type === "bytes") {
@@ -43490,7 +43485,8 @@ function getStepReducers(global2 = globalThis, ops, runId) {
43490
43485
  if (!runId) {
43491
43486
  throw new Error("WritableStream cannot be serialized without a valid runId");
43492
43487
  }
43493
- name = global2.crypto.randomUUID();
43488
+ const streamId = (global2[STABLE_ULID] || defaultUlid)();
43489
+ name = `strm_${streamId}`;
43494
43490
  ops.push(new WorkflowServerReadableStream(name).pipeThrough(getDeserializeStream(getStepRevivers(global2, ops, runId))).pipeTo(value));
43495
43491
  }
43496
43492
  return {
@@ -43703,6 +43699,8 @@ var WorkflowTracePropagated = SemanticConvention("workflow.trace.propagated");
43703
43699
  var WorkflowErrorName = SemanticConvention("workflow.error.name");
43704
43700
  var WorkflowErrorMessage = SemanticConvention("workflow.error.message");
43705
43701
  var WorkflowStepsCreated = SemanticConvention("workflow.steps.created");
43702
+ var WorkflowHooksCreated = SemanticConvention("workflow.hooks.created");
43703
+ var WorkflowWaitsCreated = SemanticConvention("workflow.waits.created");
43706
43704
  var StepName = SemanticConvention("step.name");
43707
43705
  var StepId = SemanticConvention("step.id");
43708
43706
  var StepAttempt = SemanticConvention("step.attempt");
@@ -44069,6 +44067,41 @@ async function writeEvent(writable, event, payload) {
44069
44067
  }
44070
44068
  __name(writeEvent, "writeEvent");
44071
44069
  registerStepFunction("step//workflows/hooks.ts//writeEvent", writeEvent);
44070
+ // workflows/addition.ts
44071
+ async function add(num, num2) {
44072
+ return num + num2;
44073
+ }
44074
+ __name(add, "add");
44075
+ async function addition(num, num2) {
44076
+ throw new Error("You attempted to execute workflow addition function directly. To start a workflow, use start(addition) from workflow/api");
44077
+ }
44078
+ __name(addition, "addition");
44079
+ addition.workflowId = "workflow//workflows/addition.ts//addition";
44080
+ registerStepFunction("step//workflows/addition.ts//add", add);
44081
+ // workflows/noop.ts
44082
+ var count = 0;
44083
+ async function noop(_i) {
44084
+ count++;
44085
+ return count;
44086
+ }
44087
+ __name(noop, "noop");
44088
+ async function brokenWf() {
44089
+ throw new Error("You attempted to execute workflow brokenWf function directly. To start a workflow, use start(brokenWf) from workflow/api");
44090
+ }
44091
+ __name(brokenWf, "brokenWf");
44092
+ brokenWf.workflowId = "workflow//workflows/noop.ts//brokenWf";
44093
+ registerStepFunction("step//workflows/noop.ts//noop", noop);
44094
+ // workflows/null-byte.ts
44095
+ async function nullByteStep() {
44096
+ return "null byte \0";
44097
+ }
44098
+ __name(nullByteStep, "nullByteStep");
44099
+ async function nullByteWorkflow() {
44100
+ throw new Error("You attempted to execute workflow nullByteWorkflow function directly. To start a workflow, use start(nullByteWorkflow) from workflow/api");
44101
+ }
44102
+ __name(nullByteWorkflow, "nullByteWorkflow");
44103
+ nullByteWorkflow.workflowId = "workflow//workflows/null-byte.ts//nullByteWorkflow";
44104
+ registerStepFunction("step//workflows/null-byte.ts//nullByteStep", nullByteStep);
44072
44105
  // workflows/retriable-and-fatal.ts
44073
44106
  async function retryableAndFatalErrorWorkflow() {
44074
44107
  throw new Error("You attempted to execute workflow retryableAndFatalErrorWorkflow function directly. To start a workflow, use start(retryableAndFatalErrorWorkflow) from workflow/api");
@@ -44096,19 +44129,6 @@ async function stepThatFails() {
44096
44129
  __name(stepThatFails, "stepThatFails");
44097
44130
  registerStepFunction("step//workflows/retriable-and-fatal.ts//stepThatThrowsRetryableError", stepThatThrowsRetryableError);
44098
44131
  registerStepFunction("step//workflows/retriable-and-fatal.ts//stepThatFails", stepThatFails);
44099
- // workflows/null-byte.ts
44100
- async function nullByteStep() {
44101
- return "null byte \0";
44102
- }
44103
- __name(nullByteStep, "nullByteStep");
44104
- async function nullByteWorkflow() {
44105
- throw new Error("You attempted to execute workflow nullByteWorkflow function directly. To start a workflow, use start(nullByteWorkflow) from workflow/api");
44106
- }
44107
- __name(nullByteWorkflow, "nullByteWorkflow");
44108
- nullByteWorkflow.workflowId = "workflow//workflows/null-byte.ts//nullByteWorkflow";
44109
- registerStepFunction("step//workflows/null-byte.ts//nullByteStep", nullByteStep);
44110
- // ../core/dist/runtime.js
44111
- var import_functions4 = __toESM(require_functions(), 1);
44112
44132
  // ../core/dist/logger.js
44113
44133
  var import_debug = __toESM(require_src2(), 1);
44114
44134
  function createLogger(namespace) {
@@ -44141,6 +44161,47 @@ var runtimeLogger = createLogger("runtime");
44141
44161
  var webhookLogger = createLogger("webhook");
44142
44162
  var eventsLogger = createLogger("events");
44143
44163
  var adapterLogger = createLogger("adapter");
44164
+ // ../core/dist/runtime/helpers.js
44165
+ function withHealthCheck(handler) {
44166
+ return async (req) => {
44167
+ const url2 = new URL(req.url);
44168
+ const isHealthCheck = url2.searchParams.has("__health");
44169
+ if (isHealthCheck) {
44170
+ return new Response(`Workflow DevKit "${url2.pathname}" endpoint is healthy`, {
44171
+ status: 200,
44172
+ headers: {
44173
+ "Content-Type": "text/plain"
44174
+ }
44175
+ });
44176
+ }
44177
+ return await handler(req);
44178
+ };
44179
+ }
44180
+ __name(withHealthCheck, "withHealthCheck");
44181
+ async function queueMessage(world, ...args) {
44182
+ const queueName = args[0];
44183
+ await trace("queueMessage", {
44184
+ attributes: QueueName(queueName),
44185
+ kind: await getSpanKind("PRODUCER")
44186
+ }, async (span) => {
44187
+ const { messageId } = await world.queue(...args);
44188
+ span?.setAttributes(QueueMessageId(messageId));
44189
+ });
44190
+ }
44191
+ __name(queueMessage, "queueMessage");
44192
+ function getQueueOverhead(message) {
44193
+ if (!message.requestedAt)
44194
+ return;
44195
+ try {
44196
+ return QueueOverheadMs(Date.now() - message.requestedAt.getTime());
44197
+ }
44198
+ catch {
44199
+ return;
44200
+ }
44201
+ }
44202
+ __name(getQueueOverhead, "getQueueOverhead");
44203
+ // ../core/dist/runtime/suspension-handler.js
44204
+ var import_functions3 = __toESM(require_functions(), 1);
44144
44205
  // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
44145
44206
  var comma = ",".charCodeAt(0);
44146
44207
  var semicolon = ";".charCodeAt(0);
@@ -44179,25 +44240,10 @@ var EventConsumerResult;
44179
44240
  // ../core/dist/vm/index.js
44180
44241
  var import_seedrandom = __toESM(require_seedrandom2(), 1);
44181
44242
  // ../core/dist/runtime/start.js
44182
- var import_functions3 = __toESM(require_functions(), 1);
44183
- // ../core/dist/runtime.js
44243
+ var import_functions4 = __toESM(require_functions(), 1);
44244
+ // ../core/dist/runtime/step-handler.js
44245
+ var import_functions5 = __toESM(require_functions(), 1);
44184
44246
  var DEFAULT_STEP_MAX_RETRIES = 3;
44185
- function withHealthCheck(handler) {
44186
- return async (req) => {
44187
- const url2 = new URL(req.url);
44188
- const isHealthCheck = url2.searchParams.has("__health");
44189
- if (isHealthCheck) {
44190
- return new Response(`Workflow DevKit "${url2.pathname}" endpoint is healthy`, {
44191
- status: 200,
44192
- headers: {
44193
- "Content-Type": "text/plain"
44194
- }
44195
- });
44196
- }
44197
- return await handler(req);
44198
- };
44199
- }
44200
- __name(withHealthCheck, "withHealthCheck");
44201
44247
  var stepHandler = getWorldHandlers().createQueueHandler("__wkf_step_", async (message_, metadata) => {
44202
44248
  const { workflowName, workflowRunId, workflowStartedAt, stepId, traceCarrier: traceContext, requestedAt } = StepInvokePayloadSchema.parse(message_);
44203
44249
  const spanLinks = await linkToCurrentContext();
@@ -44348,7 +44394,7 @@ var stepHandler = getWorldHandlers().createQueueHandler("__wkf_step_", async (me
44348
44394
  closureVars: hydratedInput.closureVars
44349
44395
  }, () => stepFn.apply(null, args));
44350
44396
  result = dehydrateStepReturnValue(result, ops, workflowRunId);
44351
- (0, import_functions4.waitUntil)(Promise.all(ops).catch((err) => {
44397
+ (0, import_functions5.waitUntil)(Promise.all(ops).catch((err) => {
44352
44398
  const isAbortError = err?.name === "AbortError" || err?.name === "ResponseAborted";
44353
44399
  if (!isAbortError)
44354
44400
  throw err;
@@ -44492,28 +44538,6 @@ Bubbling up error to parent workflow`);
44492
44538
  });
44493
44539
  });
44494
44540
  var stepEntrypoint = /* @__PURE__ */ withHealthCheck(stepHandler);
44495
- async function queueMessage(world, ...args) {
44496
- const queueName = args[0];
44497
- await trace("queueMessage", {
44498
- attributes: QueueName(queueName),
44499
- kind: await getSpanKind("PRODUCER")
44500
- }, async (span) => {
44501
- const { messageId } = await world.queue(...args);
44502
- span?.setAttributes(QueueMessageId(messageId));
44503
- });
44504
- }
44505
- __name(queueMessage, "queueMessage");
44506
- function getQueueOverhead(message) {
44507
- if (!message.requestedAt)
44508
- return;
44509
- try {
44510
- return QueueOverheadMs(Date.now() - message.requestedAt.getTime());
44511
- }
44512
- catch {
44513
- return;
44514
- }
44515
- }
44516
- __name(getQueueOverhead, "getQueueOverhead");
44517
44541
  // Annotate the CommonJS export names for ESM import in node:
44518
44542
  0 && (module.exports = {
44519
44543
  POST