@workflow/world-testing 4.0.1-beta.32 → 4.0.1-beta.34

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,19 +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/noop.ts
24515
- var count = 0;
24516
- async function noop(_i) {
24517
- count++;
24518
- return count;
24519
- }
24520
- __name(noop, "noop");
24521
- async function brokenWf() {
24522
- throw new Error("You attempted to execute workflow brokenWf function directly. To start a workflow, use start(brokenWf) from workflow/api");
24523
- }
24524
- __name(brokenWf, "brokenWf");
24525
- brokenWf.workflowId = "workflow//workflows/noop.ts//brokenWf";
24526
- registerStepFunction("step//workflows/noop.ts//noop", noop);
24527
24514
  // workflows/null-byte.ts
24528
24515
  async function nullByteStep() {
24529
24516
  return "null byte \0";
@@ -25209,6 +25196,169 @@ function stringify_primitive(thing) {
25209
25196
  return String(thing);
25210
25197
  }
25211
25198
  __name(stringify_primitive, "stringify_primitive");
25199
+ // ../../node_modules/.pnpm/ulid@3.0.1/node_modules/ulid/dist/node/index.js
25200
+ var import_node_crypto = __toESM(require("node:crypto"), 1);
25201
+ var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
25202
+ var ENCODING_LEN = 32;
25203
+ var RANDOM_LEN = 16;
25204
+ var TIME_LEN = 10;
25205
+ var TIME_MAX = 281474976710655;
25206
+ var ULIDErrorCode;
25207
+ (function (ULIDErrorCode2) {
25208
+ ULIDErrorCode2["Base32IncorrectEncoding"] = "B32_ENC_INVALID";
25209
+ ULIDErrorCode2["DecodeTimeInvalidCharacter"] = "DEC_TIME_CHAR";
25210
+ ULIDErrorCode2["DecodeTimeValueMalformed"] = "DEC_TIME_MALFORMED";
25211
+ ULIDErrorCode2["EncodeTimeNegative"] = "ENC_TIME_NEG";
25212
+ ULIDErrorCode2["EncodeTimeSizeExceeded"] = "ENC_TIME_SIZE_EXCEED";
25213
+ ULIDErrorCode2["EncodeTimeValueMalformed"] = "ENC_TIME_MALFORMED";
25214
+ ULIDErrorCode2["PRNGDetectFailure"] = "PRNG_DETECT";
25215
+ ULIDErrorCode2["ULIDInvalid"] = "ULID_INVALID";
25216
+ ULIDErrorCode2["Unexpected"] = "UNEXPECTED";
25217
+ ULIDErrorCode2["UUIDInvalid"] = "UUID_INVALID";
25218
+ })(ULIDErrorCode || (ULIDErrorCode = {}));
25219
+ var ULIDError = class extends Error {
25220
+ static {
25221
+ __name(this, "ULIDError");
25222
+ }
25223
+ constructor(errorCode, message) {
25224
+ super(`${message} (${errorCode})`);
25225
+ this.name = "ULIDError";
25226
+ this.code = errorCode;
25227
+ }
25228
+ };
25229
+ function randomChar(prng) {
25230
+ const randomPosition = Math.floor(prng() * ENCODING_LEN) % ENCODING_LEN;
25231
+ return ENCODING.charAt(randomPosition);
25232
+ }
25233
+ __name(randomChar, "randomChar");
25234
+ function replaceCharAt(str, index, char) {
25235
+ if (index > str.length - 1) {
25236
+ return str;
25237
+ }
25238
+ return str.substr(0, index) + char + str.substr(index + 1);
25239
+ }
25240
+ __name(replaceCharAt, "replaceCharAt");
25241
+ function incrementBase32(str) {
25242
+ let done = void 0, index = str.length, char, charIndex, output = str;
25243
+ const maxCharIndex = ENCODING_LEN - 1;
25244
+ while (!done && index-- >= 0) {
25245
+ char = output[index];
25246
+ charIndex = ENCODING.indexOf(char);
25247
+ if (charIndex === -1) {
25248
+ throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Incorrectly encoded string");
25249
+ }
25250
+ if (charIndex === maxCharIndex) {
25251
+ output = replaceCharAt(output, index, ENCODING[0]);
25252
+ continue;
25253
+ }
25254
+ done = replaceCharAt(output, index, ENCODING[charIndex + 1]);
25255
+ }
25256
+ if (typeof done === "string") {
25257
+ return done;
25258
+ }
25259
+ throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Failed incrementing string");
25260
+ }
25261
+ __name(incrementBase32, "incrementBase32");
25262
+ function decodeTime(id) {
25263
+ if (id.length !== TIME_LEN + RANDOM_LEN) {
25264
+ throw new ULIDError(ULIDErrorCode.DecodeTimeValueMalformed, "Malformed ULID");
25265
+ }
25266
+ const time3 = id.substr(0, TIME_LEN).toUpperCase().split("").reverse().reduce((carry, char, index) => {
25267
+ const encodingIndex = ENCODING.indexOf(char);
25268
+ if (encodingIndex === -1) {
25269
+ throw new ULIDError(ULIDErrorCode.DecodeTimeInvalidCharacter, `Time decode error: Invalid character: ${char}`);
25270
+ }
25271
+ return carry += encodingIndex * Math.pow(ENCODING_LEN, index);
25272
+ }, 0);
25273
+ if (time3 > TIME_MAX) {
25274
+ throw new ULIDError(ULIDErrorCode.DecodeTimeValueMalformed, `Malformed ULID: timestamp too large: ${time3}`);
25275
+ }
25276
+ return time3;
25277
+ }
25278
+ __name(decodeTime, "decodeTime");
25279
+ function detectPRNG(root) {
25280
+ const rootLookup = detectRoot();
25281
+ const globalCrypto = rootLookup && (rootLookup.crypto || rootLookup.msCrypto) || (typeof import_node_crypto.default !== "undefined" ? import_node_crypto.default : null);
25282
+ if (typeof globalCrypto?.getRandomValues === "function") {
25283
+ return () => {
25284
+ const buffer = new Uint8Array(1);
25285
+ globalCrypto.getRandomValues(buffer);
25286
+ return buffer[0] / 255;
25287
+ };
25288
+ }
25289
+ else if (typeof globalCrypto?.randomBytes === "function") {
25290
+ return () => globalCrypto.randomBytes(1).readUInt8() / 255;
25291
+ }
25292
+ else if (import_node_crypto.default?.randomBytes) {
25293
+ return () => import_node_crypto.default.randomBytes(1).readUInt8() / 255;
25294
+ }
25295
+ throw new ULIDError(ULIDErrorCode.PRNGDetectFailure, "Failed to find a reliable PRNG");
25296
+ }
25297
+ __name(detectPRNG, "detectPRNG");
25298
+ function detectRoot() {
25299
+ if (inWebWorker())
25300
+ return self;
25301
+ if (typeof window !== "undefined") {
25302
+ return window;
25303
+ }
25304
+ if (typeof global !== "undefined") {
25305
+ return global;
25306
+ }
25307
+ if (typeof globalThis !== "undefined") {
25308
+ return globalThis;
25309
+ }
25310
+ return null;
25311
+ }
25312
+ __name(detectRoot, "detectRoot");
25313
+ function encodeRandom(len, prng) {
25314
+ let str = "";
25315
+ for (; len > 0; len--) {
25316
+ str = randomChar(prng) + str;
25317
+ }
25318
+ return str;
25319
+ }
25320
+ __name(encodeRandom, "encodeRandom");
25321
+ function encodeTime(now, len = TIME_LEN) {
25322
+ if (isNaN(now)) {
25323
+ throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be a number: ${now}`);
25324
+ }
25325
+ else if (now > TIME_MAX) {
25326
+ throw new ULIDError(ULIDErrorCode.EncodeTimeSizeExceeded, `Cannot encode a time larger than ${TIME_MAX}: ${now}`);
25327
+ }
25328
+ else if (now < 0) {
25329
+ throw new ULIDError(ULIDErrorCode.EncodeTimeNegative, `Time must be positive: ${now}`);
25330
+ }
25331
+ else if (Number.isInteger(now) === false) {
25332
+ throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be an integer: ${now}`);
25333
+ }
25334
+ let mod, str = "";
25335
+ for (let currentLen = len; currentLen > 0; currentLen--) {
25336
+ mod = now % ENCODING_LEN;
25337
+ str = ENCODING.charAt(mod) + str;
25338
+ now = (now - mod) / ENCODING_LEN;
25339
+ }
25340
+ return str;
25341
+ }
25342
+ __name(encodeTime, "encodeTime");
25343
+ function inWebWorker() {
25344
+ return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
25345
+ }
25346
+ __name(inWebWorker, "inWebWorker");
25347
+ function monotonicFactory(prng) {
25348
+ const currentPRNG = prng || detectPRNG();
25349
+ let lastTime = 0, lastRandom;
25350
+ return /* @__PURE__ */ __name(function _ulid2(seedTime) {
25351
+ const seed = !seedTime || isNaN(seedTime) ? Date.now() : seedTime;
25352
+ if (seed <= lastTime) {
25353
+ const incrementedRandom = lastRandom = incrementBase32(lastRandom);
25354
+ return encodeTime(lastTime, TIME_LEN) + incrementedRandom;
25355
+ }
25356
+ lastTime = seed;
25357
+ const newRandom = lastRandom = encodeRandom(RANDOM_LEN, currentPRNG);
25358
+ return encodeTime(seed, TIME_LEN) + newRandom;
25359
+ }, "_ulid");
25360
+ }
25361
+ __name(monotonicFactory, "monotonicFactory");
25212
25362
  // ../core/dist/runtime/world.js
25213
25363
  var import_node_module = require("node:module");
25214
25364
  var import_node_path4 = require("node:path");
@@ -25396,8 +25546,8 @@ async function getPort() {
25396
25546
  return ports[0];
25397
25547
  }
25398
25548
  __name(getPort, "getPort");
25399
- var PROBE_TIMEOUT_MS = 1e3;
25400
- var PROBE_ENDPOINT = "/.well-known/workflow/v1/flow";
25549
+ var PROBE_TIMEOUT_MS = 500;
25550
+ var PROBE_ENDPOINT = "/.well-known/workflow/v1/flow?__health";
25401
25551
  async function probePort(port, options = {}) {
25402
25552
  const { endpoint = PROBE_ENDPOINT, timeout = PROBE_TIMEOUT_MS } = options;
25403
25553
  const controller = new AbortController();
@@ -25407,7 +25557,7 @@ async function probePort(port, options = {}) {
25407
25557
  method: "HEAD",
25408
25558
  signal: controller.signal
25409
25559
  });
25410
- return response.status !== 404;
25560
+ return response.status === 200;
25411
25561
  }
25412
25562
  catch {
25413
25563
  return false;
@@ -41182,170 +41332,6 @@ var StepSchema = external_exports.object({
41182
41332
  });
41183
41333
  // ../world-local/dist/queue.js
41184
41334
  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
41335
  var import_undici = __toESM(require_undici(), 1);
41350
41336
  var LOCAL_QUEUE_MAX_VISIBILITY = parseInt(process.env.WORKFLOW_LOCAL_QUEUE_MAX_VISIBILITY ?? "0", 10) || Infinity;
41351
41337
  var DEFAULT_CONCURRENCY_LIMIT = 100;
@@ -41657,12 +41643,7 @@ async function paginatedFileSystemQuery(config3) {
41657
41643
  return sortOrder === "desc" ? fileTime < cursorTime : fileTime > cursorTime;
41658
41644
  }
41659
41645
  }
41660
- return false;
41661
- });
41662
- }
41663
- else {
41664
- candidateFileIds = relevantFileIds.filter((fileId) => {
41665
- return getCreatedAt(`${fileId}.json`) !== null;
41646
+ return true;
41666
41647
  });
41667
41648
  }
41668
41649
  const validItems = [];
@@ -41766,9 +41747,7 @@ var getObjectCreatedAt = /* @__PURE__ */ __name((idPrefix) => (filename) => {
41766
41747
  return ulidToDate(ulid5);
41767
41748
  }
41768
41749
  if (idPrefix === "step") {
41769
- const runId = filename.substring(0, dashIndex);
41770
- const ulid5 = runId.replace(/^wrun_/, "");
41771
- return ulidToDate(ulid5);
41750
+ return null;
41772
41751
  }
41773
41752
  const id = filename.substring(dashIndex + 1).replace(/\.json$/, "");
41774
41753
  const ulid4 = id.replace(replaceRegex, "");
@@ -42184,6 +42163,9 @@ __name(createStorage, "createStorage");
42184
42163
  var import_node_events = require("node:events");
42185
42164
  var import_node_path3 = __toESM(require("node:path"), 1);
42186
42165
  var monotonicUlid2 = monotonicFactory(() => Math.random());
42166
+ var RunStreamsSchema = external_exports.object({
42167
+ streams: external_exports.array(external_exports.string())
42168
+ });
42187
42169
  function serializeChunk(chunk) {
42188
42170
  const eofByte = Buffer.from([
42189
42171
  chunk.eof ? 1 : 0
@@ -42205,10 +42187,31 @@ function deserializeChunk(serialized) {
42205
42187
  __name(deserializeChunk, "deserializeChunk");
42206
42188
  function createStreamer(basedir) {
42207
42189
  const streamEmitter = new import_node_events.EventEmitter();
42190
+ const registeredStreams = /* @__PURE__ */ new Set();
42191
+ async function registerStreamForRun(runId, streamName) {
42192
+ const cacheKey = `${runId}:${streamName}`;
42193
+ if (registeredStreams.has(cacheKey)) {
42194
+ return;
42195
+ }
42196
+ const runStreamsPath = import_node_path3.default.join(basedir, "streams", "runs", `${runId}.json`);
42197
+ const existing = await readJSON(runStreamsPath, RunStreamsSchema);
42198
+ const streams = existing?.streams ?? [];
42199
+ if (!streams.includes(streamName)) {
42200
+ streams.push(streamName);
42201
+ await writeJSON(runStreamsPath, {
42202
+ streams
42203
+ }, {
42204
+ overwrite: true
42205
+ });
42206
+ }
42207
+ registeredStreams.add(cacheKey);
42208
+ }
42209
+ __name(registerStreamForRun, "registerStreamForRun");
42208
42210
  return {
42209
42211
  async writeToStream(name, _runId, chunk) {
42210
- await _runId;
42211
- const chunkId = `strm_${monotonicUlid2()}`;
42212
+ const runId = await _runId;
42213
+ await registerStreamForRun(runId, name);
42214
+ const chunkId = `chnk_${monotonicUlid2()}`;
42212
42215
  let chunkBuffer;
42213
42216
  if (typeof chunk === "string") {
42214
42217
  chunkBuffer = Buffer.from(new TextEncoder().encode(chunk));
@@ -42233,8 +42236,9 @@ function createStreamer(basedir) {
42233
42236
  });
42234
42237
  },
42235
42238
  async closeStream(name, _runId) {
42236
- await _runId;
42237
- const chunkId = `strm_${monotonicUlid2()}`;
42239
+ const runId = await _runId;
42240
+ await registerStreamForRun(runId, name);
42241
+ const chunkId = `chnk_${monotonicUlid2()}`;
42238
42242
  const chunkPath = import_node_path3.default.join(basedir, "streams", "chunks", `${name}-${chunkId}.json`);
42239
42243
  await write(chunkPath, serializeChunk({
42240
42244
  chunk: Buffer.from([]),
@@ -42245,30 +42249,9 @@ function createStreamer(basedir) {
42245
42249
  });
42246
42250
  },
42247
42251
  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);
42252
+ const runStreamsPath = import_node_path3.default.join(basedir, "streams", "runs", `${runId}.json`);
42253
+ const data = await readJSON(runStreamsPath, RunStreamsSchema);
42254
+ return data?.streams ?? [];
42272
42255
  },
42273
42256
  async readFromStream(name, startIndex = 0) {
42274
42257
  const chunksDir = import_node_path3.default.join(basedir, "streams", "chunks");
@@ -42365,7 +42348,7 @@ __name(createLocalWorld, "createLocalWorld");
42365
42348
  var import_node_os = __toESM(require("node:os"), 1);
42366
42349
  var import_oidc2 = __toESM(require_dist(), 1);
42367
42350
  // ../world-vercel/dist/version.js
42368
- var version2 = "4.0.1-beta.19";
42351
+ var version2 = "4.0.1-beta.21";
42369
42352
  // ../world-vercel/dist/utils.js
42370
42353
  var DEFAULT_RESOLVE_DATA_OPTION2 = "all";
42371
42354
  function dateToStringReplacer(_key, value) {
@@ -42423,7 +42406,12 @@ var getHttpUrl = /* @__PURE__ */ __name((config3) => {
42423
42406
  const projectConfig = config3?.projectConfig;
42424
42407
  const defaultUrl = "https://vercel-workflow.com/api";
42425
42408
  const defaultProxyUrl = "https://api.vercel.com/v1/workflow";
42426
- const usingProxy = Boolean(config3?.baseUrl || projectConfig?.projectId && projectConfig?.teamId);
42409
+ const usingProxy = (
42410
+ // Skipping proxy is specifically used for e2e testing. Normally, we assume calls from
42411
+ // CLI and web UI are not running inside the Vercel runtime environment, and so need to
42412
+ // use the proxy for authentication. However, during e2e tests, this is not the case,
42413
+ // so we allow skipping the proxy.
42414
+ !config3?.skipProxy && Boolean(config3?.baseUrl || projectConfig?.projectId && projectConfig?.teamId));
42427
42415
  const baseUrl = config3?.baseUrl || (usingProxy ? defaultProxyUrl : defaultUrl);
42428
42416
  return {
42429
42417
  baseUrl,
@@ -42462,6 +42450,7 @@ __name(getHttpConfig, "getHttpConfig");
42462
42450
  async function makeRequest({ endpoint, options = {}, config: config3 = {}, schema }) {
42463
42451
  const { baseUrl, headers } = await getHttpConfig(config3);
42464
42452
  headers.set("Content-Type", "application/json");
42453
+ headers.set("X-Request-Time", Date.now().toString());
42465
42454
  const url2 = `${baseUrl}${endpoint}`;
42466
42455
  const response = await fetch(url2, {
42467
42456
  ...options,
@@ -43149,7 +43138,8 @@ var createWorld = /* @__PURE__ */ __name(() => {
43149
43138
  const targetWorld = process.env.WORKFLOW_TARGET_WORLD || defaultWorld();
43150
43139
  if (targetWorld === "vercel") {
43151
43140
  return createVercelWorld({
43152
- baseUrl: process.env.WORKFLOW_VERCEL_PROXY_URL,
43141
+ baseUrl: process.env.WORKFLOW_VERCEL_BACKEND_URL,
43142
+ skipProxy: process.env.WORKFLOW_VERCEL_SKIP_PROXY === "true",
43153
43143
  token: process.env.WORKFLOW_VERCEL_AUTH_TOKEN,
43154
43144
  projectConfig: {
43155
43145
  environment: process.env.WORKFLOW_VERCEL_ENV,
@@ -43198,11 +43188,13 @@ var WORKFLOW_CREATE_HOOK = Symbol.for("WORKFLOW_CREATE_HOOK");
43198
43188
  var WORKFLOW_SLEEP = Symbol.for("WORKFLOW_SLEEP");
43199
43189
  var WORKFLOW_CONTEXT = Symbol.for("WORKFLOW_CONTEXT");
43200
43190
  var WORKFLOW_GET_STREAM_ID = Symbol.for("WORKFLOW_GET_STREAM_ID");
43191
+ var STABLE_ULID = Symbol.for("WORKFLOW_STABLE_ULID");
43201
43192
  var STREAM_NAME_SYMBOL = Symbol.for("WORKFLOW_STREAM_NAME");
43202
43193
  var STREAM_TYPE_SYMBOL = Symbol.for("WORKFLOW_STREAM_TYPE");
43203
43194
  var BODY_INIT_SYMBOL = Symbol.for("BODY_INIT");
43204
43195
  var WEBHOOK_RESPONSE_WRITABLE = Symbol.for("WEBHOOK_RESPONSE_WRITABLE");
43205
43196
  // ../core/dist/serialization.js
43197
+ var defaultUlid = monotonicFactory();
43206
43198
  function formatSerializationError(context, error45) {
43207
43199
  const verb = context.includes("return value") ? "returning" : "passing";
43208
43200
  let message = `Failed to serialize ${context}`;
@@ -43459,7 +43451,8 @@ function getStepReducers(global2 = globalThis, ops, runId) {
43459
43451
  if (!runId) {
43460
43452
  throw new Error("ReadableStream cannot be serialized without a valid runId");
43461
43453
  }
43462
- name = global2.crypto.randomUUID();
43454
+ const streamId = (global2[STABLE_ULID] || defaultUlid)();
43455
+ name = `strm_${streamId}`;
43463
43456
  type = getStreamType(value);
43464
43457
  const writable = new WorkflowServerWritableStream(name, runId);
43465
43458
  if (type === "bytes") {
@@ -43484,7 +43477,8 @@ function getStepReducers(global2 = globalThis, ops, runId) {
43484
43477
  if (!runId) {
43485
43478
  throw new Error("WritableStream cannot be serialized without a valid runId");
43486
43479
  }
43487
- name = global2.crypto.randomUUID();
43480
+ const streamId = (global2[STABLE_ULID] || defaultUlid)();
43481
+ name = `strm_${streamId}`;
43488
43482
  ops.push(new WorkflowServerReadableStream(name).pipeThrough(getDeserializeStream(getStepRevivers(global2, ops, runId))).pipeTo(value));
43489
43483
  }
43490
43484
  return {
@@ -43697,6 +43691,8 @@ var WorkflowTracePropagated = SemanticConvention("workflow.trace.propagated");
43697
43691
  var WorkflowErrorName = SemanticConvention("workflow.error.name");
43698
43692
  var WorkflowErrorMessage = SemanticConvention("workflow.error.message");
43699
43693
  var WorkflowStepsCreated = SemanticConvention("workflow.steps.created");
43694
+ var WorkflowHooksCreated = SemanticConvention("workflow.hooks.created");
43695
+ var WorkflowWaitsCreated = SemanticConvention("workflow.waits.created");
43700
43696
  var StepName = SemanticConvention("step.name");
43701
43697
  var StepId = SemanticConvention("step.id");
43702
43698
  var StepAttempt = SemanticConvention("step.attempt");
@@ -44039,6 +44035,43 @@ async function fetch2(...args) {
44039
44035
  }
44040
44036
  __name(fetch2, "fetch");
44041
44037
  registerStepFunction("step//workflow/dist/stdlib.js//fetch", fetch2);
44038
+ // workflows/hooks.ts
44039
+ var Hook = defineHook({
44040
+ schema: object({
44041
+ data: string2(),
44042
+ done: boolean2().optional(),
44043
+ metadata: unknown()
44044
+ })
44045
+ });
44046
+ async function collectWithHook(token, customData) {
44047
+ throw new Error("You attempted to execute workflow collectWithHook function directly. To start a workflow, use start(collectWithHook) from workflow/api");
44048
+ }
44049
+ __name(collectWithHook, "collectWithHook");
44050
+ collectWithHook.workflowId = "workflow//workflows/hooks.ts//collectWithHook";
44051
+ async function writeEvent(writable, event, payload) {
44052
+ console.log("writing event", event, payload);
44053
+ const writer = writable.getWriter();
44054
+ await writer.write(new TextEncoder().encode(`${JSON.stringify({
44055
+ event,
44056
+ payload
44057
+ })}\r
44058
+ `));
44059
+ }
44060
+ __name(writeEvent, "writeEvent");
44061
+ registerStepFunction("step//workflows/hooks.ts//writeEvent", writeEvent);
44062
+ // workflows/noop.ts
44063
+ var count = 0;
44064
+ async function noop(_i) {
44065
+ count++;
44066
+ return count;
44067
+ }
44068
+ __name(noop, "noop");
44069
+ async function brokenWf() {
44070
+ throw new Error("You attempted to execute workflow brokenWf function directly. To start a workflow, use start(brokenWf) from workflow/api");
44071
+ }
44072
+ __name(brokenWf, "brokenWf");
44073
+ brokenWf.workflowId = "workflow//workflows/noop.ts//brokenWf";
44074
+ registerStepFunction("step//workflows/noop.ts//noop", noop);
44042
44075
  // workflows/retriable-and-fatal.ts
44043
44076
  async function retryableAndFatalErrorWorkflow() {
44044
44077
  throw new Error("You attempted to execute workflow retryableAndFatalErrorWorkflow function directly. To start a workflow, use start(retryableAndFatalErrorWorkflow) from workflow/api");
@@ -44077,32 +44110,6 @@ async function addition(num, num2) {
44077
44110
  __name(addition, "addition");
44078
44111
  addition.workflowId = "workflow//workflows/addition.ts//addition";
44079
44112
  registerStepFunction("step//workflows/addition.ts//add", add);
44080
- // workflows/hooks.ts
44081
- var Hook = defineHook({
44082
- schema: object({
44083
- data: string2(),
44084
- done: boolean2().optional(),
44085
- metadata: unknown()
44086
- })
44087
- });
44088
- async function collectWithHook(token, customData) {
44089
- throw new Error("You attempted to execute workflow collectWithHook function directly. To start a workflow, use start(collectWithHook) from workflow/api");
44090
- }
44091
- __name(collectWithHook, "collectWithHook");
44092
- collectWithHook.workflowId = "workflow//workflows/hooks.ts//collectWithHook";
44093
- async function writeEvent(writable, event, payload) {
44094
- console.log("writing event", event, payload);
44095
- const writer = writable.getWriter();
44096
- await writer.write(new TextEncoder().encode(`${JSON.stringify({
44097
- event,
44098
- payload
44099
- })}\r
44100
- `));
44101
- }
44102
- __name(writeEvent, "writeEvent");
44103
- registerStepFunction("step//workflows/hooks.ts//writeEvent", writeEvent);
44104
- // ../core/dist/runtime.js
44105
- var import_functions4 = __toESM(require_functions(), 1);
44106
44113
  // ../core/dist/logger.js
44107
44114
  var import_debug = __toESM(require_src2(), 1);
44108
44115
  function createLogger(namespace) {
@@ -44135,6 +44142,47 @@ var runtimeLogger = createLogger("runtime");
44135
44142
  var webhookLogger = createLogger("webhook");
44136
44143
  var eventsLogger = createLogger("events");
44137
44144
  var adapterLogger = createLogger("adapter");
44145
+ // ../core/dist/runtime/helpers.js
44146
+ function withHealthCheck(handler) {
44147
+ return async (req) => {
44148
+ const url2 = new URL(req.url);
44149
+ const isHealthCheck = url2.searchParams.has("__health");
44150
+ if (isHealthCheck) {
44151
+ return new Response(`Workflow DevKit "${url2.pathname}" endpoint is healthy`, {
44152
+ status: 200,
44153
+ headers: {
44154
+ "Content-Type": "text/plain"
44155
+ }
44156
+ });
44157
+ }
44158
+ return await handler(req);
44159
+ };
44160
+ }
44161
+ __name(withHealthCheck, "withHealthCheck");
44162
+ async function queueMessage(world, ...args) {
44163
+ const queueName = args[0];
44164
+ await trace("queueMessage", {
44165
+ attributes: QueueName(queueName),
44166
+ kind: await getSpanKind("PRODUCER")
44167
+ }, async (span) => {
44168
+ const { messageId } = await world.queue(...args);
44169
+ span?.setAttributes(QueueMessageId(messageId));
44170
+ });
44171
+ }
44172
+ __name(queueMessage, "queueMessage");
44173
+ function getQueueOverhead(message) {
44174
+ if (!message.requestedAt)
44175
+ return;
44176
+ try {
44177
+ return QueueOverheadMs(Date.now() - message.requestedAt.getTime());
44178
+ }
44179
+ catch {
44180
+ return;
44181
+ }
44182
+ }
44183
+ __name(getQueueOverhead, "getQueueOverhead");
44184
+ // ../core/dist/runtime/suspension-handler.js
44185
+ var import_functions3 = __toESM(require_functions(), 1);
44138
44186
  // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
44139
44187
  var comma = ",".charCodeAt(0);
44140
44188
  var semicolon = ";".charCodeAt(0);
@@ -44173,10 +44221,11 @@ var EventConsumerResult;
44173
44221
  // ../core/dist/vm/index.js
44174
44222
  var import_seedrandom = __toESM(require_seedrandom2(), 1);
44175
44223
  // ../core/dist/runtime/start.js
44176
- var import_functions3 = __toESM(require_functions(), 1);
44177
- // ../core/dist/runtime.js
44224
+ var import_functions4 = __toESM(require_functions(), 1);
44225
+ // ../core/dist/runtime/step-handler.js
44226
+ var import_functions5 = __toESM(require_functions(), 1);
44178
44227
  var DEFAULT_STEP_MAX_RETRIES = 3;
44179
- var stepEntrypoint = /* @__PURE__ */ getWorldHandlers().createQueueHandler("__wkf_step_", async (message_, metadata) => {
44228
+ var stepHandler = getWorldHandlers().createQueueHandler("__wkf_step_", async (message_, metadata) => {
44180
44229
  const { workflowName, workflowRunId, workflowStartedAt, stepId, traceCarrier: traceContext, requestedAt } = StepInvokePayloadSchema.parse(message_);
44181
44230
  const spanLinks = await linkToCurrentContext();
44182
44231
  return await withTraceContext(traceContext, async () => {
@@ -44326,7 +44375,7 @@ var stepEntrypoint = /* @__PURE__ */ getWorldHandlers().createQueueHandler("__wk
44326
44375
  closureVars: hydratedInput.closureVars
44327
44376
  }, () => stepFn.apply(null, args));
44328
44377
  result = dehydrateStepReturnValue(result, ops, workflowRunId);
44329
- (0, import_functions4.waitUntil)(Promise.all(ops).catch((err) => {
44378
+ (0, import_functions5.waitUntil)(Promise.all(ops).catch((err) => {
44330
44379
  const isAbortError = err?.name === "AbortError" || err?.name === "ResponseAborted";
44331
44380
  if (!isAbortError)
44332
44381
  throw err;
@@ -44469,28 +44518,7 @@ Bubbling up error to parent workflow`);
44469
44518
  });
44470
44519
  });
44471
44520
  });
44472
- async function queueMessage(world, ...args) {
44473
- const queueName = args[0];
44474
- await trace("queueMessage", {
44475
- attributes: QueueName(queueName),
44476
- kind: await getSpanKind("PRODUCER")
44477
- }, async (span) => {
44478
- const { messageId } = await world.queue(...args);
44479
- span?.setAttributes(QueueMessageId(messageId));
44480
- });
44481
- }
44482
- __name(queueMessage, "queueMessage");
44483
- function getQueueOverhead(message) {
44484
- if (!message.requestedAt)
44485
- return;
44486
- try {
44487
- return QueueOverheadMs(Date.now() - message.requestedAt.getTime());
44488
- }
44489
- catch {
44490
- return;
44491
- }
44492
- }
44493
- __name(getQueueOverhead, "getQueueOverhead");
44521
+ var stepEntrypoint = /* @__PURE__ */ withHealthCheck(stepHandler);
44494
44522
  // Annotate the CommonJS export names for ESM import in node:
44495
44523
  0 && (module.exports = {
44496
44524
  POST