awaitly 2.0.0 → 3.0.0

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 (88) hide show
  1. package/dist/di-Biw_plBn.d.cts +15 -0
  2. package/dist/di-DxyH2N3i.d.ts +15 -0
  3. package/dist/durable.cjs +4670 -0
  4. package/dist/durable.cjs.map +1 -0
  5. package/dist/durable.d.cts +9 -0
  6. package/dist/durable.d.ts +9 -0
  7. package/dist/durable.js +4610 -0
  8. package/dist/durable.js.map +1 -0
  9. package/dist/{di-BbFFfO8y.d.ts → duration-BjVn3QpB.d.cts} +1 -15
  10. package/dist/{di-BDlT7InM.d.cts → duration-BjVn3QpB.d.ts} +1 -15
  11. package/dist/engine.cjs +4501 -0
  12. package/dist/engine.cjs.map +1 -0
  13. package/dist/engine.d.cts +113 -0
  14. package/dist/engine.d.ts +113 -0
  15. package/dist/engine.js +4474 -0
  16. package/dist/engine.js.map +1 -0
  17. package/dist/{errors-DtXvrCiO.d.cts → errors-sDSeaZBO.d.cts} +1 -1
  18. package/dist/{errors-DtXvrCiO.d.ts → errors-sDSeaZBO.d.ts} +1 -1
  19. package/dist/guards-CwQZro1F.d.ts +72 -0
  20. package/dist/guards-DhhOJZda.d.cts +72 -0
  21. package/dist/hitl-BnnnLzh2.d.cts +468 -0
  22. package/dist/hitl-pYfkQMv_.d.ts +468 -0
  23. package/dist/hitl.cjs +646 -0
  24. package/dist/hitl.cjs.map +1 -0
  25. package/dist/hitl.d.cts +440 -0
  26. package/dist/hitl.d.ts +440 -0
  27. package/dist/hitl.js +605 -0
  28. package/dist/hitl.js.map +1 -0
  29. package/dist/index-Bew12SZ8.d.ts +417 -0
  30. package/dist/index-Bwt-iz50.d.cts +417 -0
  31. package/dist/{types-B8NfNRGX.d.ts → index-Cv4K_3sZ.d.ts} +2 -1162
  32. package/dist/{types-BZ2f4MRR.d.cts → index-ICmfQi08.d.cts} +2 -1162
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.cts +11 -1527
  35. package/dist/index.d.ts +11 -1527
  36. package/dist/persistence.cjs +552 -0
  37. package/dist/persistence.cjs.map +1 -0
  38. package/dist/persistence.d.cts +254 -0
  39. package/dist/persistence.d.ts +254 -0
  40. package/dist/persistence.js +499 -0
  41. package/dist/persistence.js.map +1 -0
  42. package/dist/reliability.cjs +1651 -0
  43. package/dist/reliability.cjs.map +1 -0
  44. package/dist/reliability.d.cts +1442 -0
  45. package/dist/reliability.d.ts +1442 -0
  46. package/dist/reliability.js +1589 -0
  47. package/dist/reliability.js.map +1 -0
  48. package/dist/result.d.cts +1 -1
  49. package/dist/result.d.ts +1 -1
  50. package/dist/run.cjs +2283 -0
  51. package/dist/run.cjs.map +1 -0
  52. package/dist/run.d.cts +90 -0
  53. package/dist/run.d.ts +90 -0
  54. package/dist/run.js +2247 -0
  55. package/dist/run.js.map +1 -0
  56. package/dist/saga.cjs +3699 -0
  57. package/dist/saga.cjs.map +1 -0
  58. package/dist/saga.d.cts +162 -0
  59. package/dist/saga.d.ts +162 -0
  60. package/dist/saga.js +3670 -0
  61. package/dist/saga.js.map +1 -0
  62. package/dist/store-contract-BI98VYmX.d.ts +66 -0
  63. package/dist/store-contract-C2HyR_o6.d.cts +66 -0
  64. package/dist/streaming.cjs +895 -0
  65. package/dist/streaming.cjs.map +1 -0
  66. package/dist/streaming.d.cts +594 -0
  67. package/dist/streaming.d.ts +594 -0
  68. package/dist/streaming.js +832 -0
  69. package/dist/streaming.js.map +1 -0
  70. package/dist/testing.d.cts +4 -2
  71. package/dist/testing.d.ts +4 -2
  72. package/dist/types-BDTxgKKc.d.ts +845 -0
  73. package/dist/types-C9Y71dua.d.cts +845 -0
  74. package/dist/types-d8q8iQlk.d.cts +323 -0
  75. package/dist/types-sObbY4mX.d.ts +323 -0
  76. package/dist/webhook.cjs +461 -0
  77. package/dist/webhook.cjs.map +1 -0
  78. package/dist/webhook.d.cts +497 -0
  79. package/dist/webhook.d.ts +497 -0
  80. package/dist/webhook.js +422 -0
  81. package/dist/webhook.js.map +1 -0
  82. package/dist/workflow.cjs +2 -2614
  83. package/dist/workflow.cjs.map +1 -1
  84. package/dist/workflow.d.cts +12 -3023
  85. package/dist/workflow.d.ts +12 -3023
  86. package/dist/workflow.js +2 -2535
  87. package/dist/workflow.js.map +1 -1
  88. package/package.json +46 -1
@@ -0,0 +1,4501 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/engine-entry.ts
21
+ var engine_entry_exports = {};
22
+ __export(engine_entry_exports, {
23
+ createEngine: () => createEngine
24
+ });
25
+ module.exports = __toCommonJS(engine_entry_exports);
26
+
27
+ // src/engine/index.ts
28
+ var import_node_crypto = require("crypto");
29
+
30
+ // src/slugs.ts
31
+ var AWAITLY_SLUGS = {
32
+ // --- step-* ---
33
+ "step-require-id": "step-require-id",
34
+ "step-no-immediate-execution": "step-no-immediate-execution",
35
+ "step-require-thunk-for-key": "step-require-thunk-for-key",
36
+ "step-no-bare-await": "step-no-bare-await",
37
+ "step-no-try-catch-wrap": "step-no-try-catch-wrap",
38
+ "step-stable-cache-keys": "step-stable-cache-keys",
39
+ // --- workflow-* ---
40
+ "workflow-no-floating": "workflow-no-floating",
41
+ "workflow-options-position": "workflow-options-position",
42
+ "workflow-callback-shape": "workflow-callback-shape",
43
+ "workflow-no-callable-form": "workflow-no-callable-form",
44
+ "workflow-no-dynamic-import": "workflow-no-dynamic-import",
45
+ "workflow-prefer-step-if": "workflow-prefer-step-if",
46
+ "workflow-prefer-step-foreach": "workflow-prefer-step-foreach",
47
+ // --- result-* ---
48
+ "result-no-floating": "result-no-floating",
49
+ "result-require-handling": "result-require-handling",
50
+ "result-no-double-wrap": "result-no-double-wrap",
51
+ "result-no-manual-propagation": "result-no-manual-propagation",
52
+ "result-no-direct-ok-err": "result-no-direct-ok-err",
53
+ // --- error-* ---
54
+ "error-check-unexpected-first": "error-check-unexpected-first",
55
+ "error-access-cause": "error-access-cause",
56
+ "error-normalize": "error-normalize",
57
+ "error-no-throw-in-deps": "error-no-throw-in-deps",
58
+ // --- concurrency-* ---
59
+ "concurrency-no-promise-all": "concurrency-no-promise-all",
60
+ "concurrency-no-promise-race": "concurrency-no-promise-race",
61
+ "concurrency-no-promise-allsettled": "concurrency-no-promise-allsettled",
62
+ // --- runtime-* ---
63
+ "runtime-step-timeout": "runtime-step-timeout",
64
+ "runtime-step-aborted": "runtime-step-aborted",
65
+ "runtime-retry-exhausted": "runtime-retry-exhausted",
66
+ "runtime-rate-limit": "runtime-rate-limit",
67
+ "runtime-circuit-open": "runtime-circuit-open",
68
+ "runtime-unexpected": "runtime-unexpected",
69
+ "runtime-resolver-not-found": "runtime-resolver-not-found",
70
+ "runtime-saga-compensation": "runtime-saga-compensation"
71
+ };
72
+ function slugDocsUrl(slug) {
73
+ return `https://jagreehal.github.io/awaitly/rules/#${slug}`;
74
+ }
75
+ var ALL_SLUGS = Object.keys(
76
+ AWAITLY_SLUGS
77
+ );
78
+
79
+ // src/tagged-error.ts
80
+ var InternalTaggedErrorBase = class extends Error {
81
+ type;
82
+ /** @deprecated Use `type`. */
83
+ _tag;
84
+ };
85
+ function TaggedError(tag, options) {
86
+ return class extends InternalTaggedErrorBase {
87
+ type = tag;
88
+ /** @deprecated Use `type`. */
89
+ _tag = tag;
90
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
91
+ constructor(props, errorOptions) {
92
+ const message = options?.message ? options.message(props ?? {}) : tag;
93
+ super(message);
94
+ this.name = tag;
95
+ if (options?.slug !== void 0) {
96
+ if (!options.hint) {
97
+ throw new TypeError(
98
+ `TaggedError: 'hint' is required when 'slug' is set (slug: "${options.slug}")`
99
+ );
100
+ }
101
+ Object.defineProperty(this, "code", {
102
+ value: options.slug,
103
+ enumerable: true,
104
+ writable: false,
105
+ configurable: false
106
+ });
107
+ Object.defineProperty(this, "hint", {
108
+ value: options.hint,
109
+ enumerable: true,
110
+ writable: false,
111
+ configurable: false
112
+ });
113
+ Object.defineProperty(this, "docsUrl", {
114
+ value: slugDocsUrl(options.slug),
115
+ enumerable: true,
116
+ writable: false,
117
+ configurable: false
118
+ });
119
+ }
120
+ Object.setPrototypeOf(this, new.target.prototype);
121
+ if (props && typeof props === "object") {
122
+ let safeProps;
123
+ if (options?.slug !== void 0) {
124
+ const {
125
+ _tag: _,
126
+ type: _t,
127
+ name: _n,
128
+ message: _m,
129
+ stack: _s,
130
+ code: _c,
131
+ hint: _h,
132
+ docsUrl: _d,
133
+ ...rest
134
+ } = props;
135
+ safeProps = rest;
136
+ } else {
137
+ const {
138
+ _tag: _,
139
+ type: _t,
140
+ name: _n,
141
+ message: _m,
142
+ stack: _s,
143
+ ...rest
144
+ } = props;
145
+ safeProps = rest;
146
+ }
147
+ const hasUserCause = Object.prototype.hasOwnProperty.call(
148
+ safeProps,
149
+ "cause"
150
+ );
151
+ const userCause = hasUserCause ? safeProps.cause : void 0;
152
+ if (hasUserCause) {
153
+ delete safeProps.cause;
154
+ }
155
+ const hasOptionsCause = errorOptions?.cause !== void 0;
156
+ if (hasUserCause && hasOptionsCause) {
157
+ throw new TypeError(
158
+ "TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause"
159
+ );
160
+ }
161
+ Object.assign(this, safeProps);
162
+ if (hasUserCause) {
163
+ this.cause = userCause;
164
+ }
165
+ if (hasOptionsCause) {
166
+ this.cause = errorOptions?.cause;
167
+ }
168
+ } else if (errorOptions?.cause !== void 0) {
169
+ this.cause = errorOptions.cause;
170
+ }
171
+ }
172
+ };
173
+ }
174
+ Object.defineProperty(TaggedError, Symbol.hasInstance, {
175
+ value: (instance) => instance instanceof InternalTaggedErrorBase
176
+ });
177
+ ((TaggedError2) => {
178
+ function isError(value) {
179
+ return value instanceof Error;
180
+ }
181
+ TaggedError2.isError = isError;
182
+ function isTaggedError(value) {
183
+ return value instanceof InternalTaggedErrorBase;
184
+ }
185
+ TaggedError2.isTaggedError = isTaggedError;
186
+ function match(error, handlers) {
187
+ const tag = error._tag;
188
+ const handler = handlers[tag];
189
+ return handler(
190
+ error
191
+ );
192
+ }
193
+ TaggedError2.match = match;
194
+ function matchPartial(error, handlers, otherwise) {
195
+ const tag = error._tag;
196
+ const handler = handlers[tag];
197
+ if (handler) {
198
+ return handler(
199
+ error
200
+ );
201
+ }
202
+ return otherwise(error);
203
+ }
204
+ TaggedError2.matchPartial = matchPartial;
205
+ })(TaggedError || (TaggedError = {}));
206
+
207
+ // src/errors.ts
208
+ var UnexpectedError = class extends (/* @__PURE__ */ TaggedError("UnexpectedError", {
209
+ slug: "runtime-unexpected",
210
+ hint: "An unexpected exception escaped a step. Inspect cause; consider returning a typed Result instead of throwing.",
211
+ message: (p) => `UnexpectedError: ${p.cause instanceof Error ? p.cause.message : String(p.cause ?? "unknown")}`
212
+ })) {
213
+ };
214
+
215
+ // src/result/index.ts
216
+ function ok(value) {
217
+ return { ok: true, value };
218
+ }
219
+
220
+ // src/core/bound-steps.ts
221
+ var isDepResultShaped = (value) => typeof value === "object" && value !== null && "ok" in value && typeof value.ok === "boolean" && (value.ok ? "value" in value : "error" in value);
222
+ var bindSteps = (deps, step) => {
223
+ const steps = {};
224
+ const invocationCounts = /* @__PURE__ */ new Map();
225
+ for (const key of Object.keys(deps)) {
226
+ const dep = deps[key];
227
+ if (typeof dep !== "function") continue;
228
+ steps[key] = (...args) => {
229
+ const count = (invocationCounts.get(key) ?? 0) + 1;
230
+ invocationCounts.set(key, count);
231
+ const stepKey = count === 1 ? key : `${key}#${count}`;
232
+ return step(stepKey, async () => {
233
+ const value = await dep(...args);
234
+ return isDepResultShaped(value) ? value : ok(value);
235
+ });
236
+ };
237
+ }
238
+ return steps;
239
+ };
240
+
241
+ // src/duration.ts
242
+ function millis(ms) {
243
+ return { _tag: "Duration", millis: ms };
244
+ }
245
+ function seconds(s) {
246
+ return { _tag: "Duration", millis: s * 1e3 };
247
+ }
248
+ function minutes(m) {
249
+ return { _tag: "Duration", millis: m * 60 * 1e3 };
250
+ }
251
+ function hours(h) {
252
+ return { _tag: "Duration", millis: h * 60 * 60 * 1e3 };
253
+ }
254
+ function days(d) {
255
+ return { _tag: "Duration", millis: d * 24 * 60 * 60 * 1e3 };
256
+ }
257
+ function toMillis(duration) {
258
+ return duration.millis;
259
+ }
260
+ function parse(input) {
261
+ const match = input.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);
262
+ if (!match) return void 0;
263
+ const value = parseFloat(match[1]);
264
+ const unit = match[2].toLowerCase();
265
+ switch (unit) {
266
+ case "ms":
267
+ return millis(value);
268
+ case "s":
269
+ return seconds(value);
270
+ case "m":
271
+ return minutes(value);
272
+ case "h":
273
+ return hours(value);
274
+ case "d":
275
+ return days(value);
276
+ default:
277
+ return void 0;
278
+ }
279
+ }
280
+
281
+ // src/core/index.ts
282
+ function parseDurationString(input) {
283
+ const match = input.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);
284
+ if (!match) return void 0;
285
+ const value = parseFloat(match[1]);
286
+ const unit = match[2].toLowerCase();
287
+ const multipliers = { ms: 1, s: 1e3, m: 6e4, h: 36e5, d: 864e5 };
288
+ return { _tag: "Duration", millis: value * (multipliers[unit] ?? 1) };
289
+ }
290
+ function defaultCatchUnexpected(cause) {
291
+ return new UnexpectedError({ cause });
292
+ }
293
+ function ok2(value) {
294
+ return { ok: true, value };
295
+ }
296
+ function err(error, options) {
297
+ const cause = options?.cause;
298
+ return { ok: false, error, ...cause !== void 0 ? { cause } : {} };
299
+ }
300
+ var isUnexpectedError = (e) => e instanceof UnexpectedError || typeof e === "object" && e !== null && "_tag" in e && e._tag === "UnexpectedError";
301
+ function extractErrorTag(error) {
302
+ if (error == null) return "unknown";
303
+ if (typeof error === "string") return error.trim() || "unknown";
304
+ if (typeof error === "object") {
305
+ const tagged = error;
306
+ if (typeof tagged._tag === "string") {
307
+ const trimmed = tagged._tag.trim();
308
+ if (trimmed) return trimmed;
309
+ }
310
+ if (typeof tagged.tag === "string") {
311
+ const trimmed = tagged.tag.trim();
312
+ if (trimmed) return trimmed;
313
+ }
314
+ if (typeof tagged.code === "string") {
315
+ const trimmed = tagged.code.trim();
316
+ if (trimmed) return trimmed;
317
+ } else if (typeof tagged.code === "number") {
318
+ return String(tagged.code);
319
+ }
320
+ if (error instanceof Error && error.name) {
321
+ const trimmed = error.name.trim();
322
+ if (trimmed) return trimmed;
323
+ }
324
+ }
325
+ return "unknown";
326
+ }
327
+ function lookupErrorClassification(tag, errorMeta) {
328
+ if (!errorMeta || !tag) return void 0;
329
+ return errorMeta[tag];
330
+ }
331
+ function extractStepMetadata(options) {
332
+ const { intent, domain, owner, tags, stateChanges, emits, calls } = options;
333
+ if (!intent && !domain && !owner && !tags?.length && !stateChanges?.length && !emits?.length && !calls?.length) {
334
+ return void 0;
335
+ }
336
+ const metadata = {};
337
+ if (intent) metadata.intent = intent;
338
+ if (domain) metadata.domain = domain;
339
+ if (owner) metadata.owner = owner;
340
+ if (tags?.length) metadata.tags = tags;
341
+ if (stateChanges?.length) metadata.stateChanges = stateChanges;
342
+ if (emits?.length) metadata.emits = emits;
343
+ if (calls?.length) metadata.calls = calls;
344
+ return metadata;
345
+ }
346
+ function buildStepErrorPayload(error, errorMeta, origin, attempt, cumulativeDurationMs) {
347
+ const tag = extractErrorTag(error);
348
+ const classification = lookupErrorClassification(tag, errorMeta);
349
+ const diagnostics = { tag, origin };
350
+ if (classification !== void 0) diagnostics.classification = classification;
351
+ if (attempt !== void 0) diagnostics.attempt = attempt;
352
+ if (cumulativeDurationMs !== void 0) diagnostics.cumulativeDurationMs = cumulativeDurationMs;
353
+ return diagnostics;
354
+ }
355
+ var STEP_TIMEOUT_MARKER = /* @__PURE__ */ Symbol.for("step_timeout_marker");
356
+ function isStepTimeoutError(e) {
357
+ if (typeof e !== "object" || e === null) {
358
+ return false;
359
+ }
360
+ if (e.type === "STEP_TIMEOUT") {
361
+ return true;
362
+ }
363
+ return STEP_TIMEOUT_MARKER in e;
364
+ }
365
+ function getStepTimeoutMeta(e) {
366
+ if (typeof e !== "object" || e === null) {
367
+ return void 0;
368
+ }
369
+ if (e.type === "STEP_TIMEOUT") {
370
+ const err2 = e;
371
+ return {
372
+ timeoutMs: err2.timeoutMs,
373
+ stepName: err2.stepName,
374
+ stepKey: err2.stepKey,
375
+ attempt: err2.attempt
376
+ };
377
+ }
378
+ if (STEP_TIMEOUT_MARKER in e) {
379
+ return e[STEP_TIMEOUT_MARKER];
380
+ }
381
+ return void 0;
382
+ }
383
+ var EARLY_EXIT_SYMBOL = /* @__PURE__ */ Symbol("early-exit");
384
+ function createEarlyExit(error, meta) {
385
+ return {
386
+ [EARLY_EXIT_SYMBOL]: true,
387
+ error,
388
+ meta
389
+ };
390
+ }
391
+ function isEarlyExit(e) {
392
+ return typeof e === "object" && e !== null && e[EARLY_EXIT_SYMBOL] === true;
393
+ }
394
+ var MAPPER_EXCEPTION_SYMBOL = /* @__PURE__ */ Symbol("mapper-exception");
395
+ function createMapperException(thrown) {
396
+ return { [MAPPER_EXCEPTION_SYMBOL]: true, thrown };
397
+ }
398
+ function isMapperException(e) {
399
+ return typeof e === "object" && e !== null && e[MAPPER_EXCEPTION_SYMBOL] === true;
400
+ }
401
+ function calculateRetryDelay(attempt, options) {
402
+ const { backoff, initialDelay, maxDelay, jitter } = options;
403
+ let delay;
404
+ switch (backoff) {
405
+ case "fixed":
406
+ delay = initialDelay;
407
+ break;
408
+ case "linear":
409
+ delay = initialDelay * attempt;
410
+ break;
411
+ case "exponential":
412
+ delay = initialDelay * Math.pow(2, attempt - 1);
413
+ break;
414
+ }
415
+ delay = Math.min(delay, maxDelay);
416
+ if (jitter) {
417
+ const jitterAmount = delay * 0.25 * Math.random();
418
+ delay = delay + jitterAmount;
419
+ }
420
+ return Math.floor(delay);
421
+ }
422
+ function sleep(ms) {
423
+ return new Promise((resolve) => setTimeout(resolve, ms));
424
+ }
425
+ var TIMEOUT_SYMBOL = /* @__PURE__ */ Symbol("timeout");
426
+ var TIMEOUT_OPTION_SYMBOL = /* @__PURE__ */ Symbol("timeout-option");
427
+ function isTimeoutOptionMarker(value) {
428
+ return typeof value === "object" && value !== null && value[TIMEOUT_OPTION_SYMBOL] === true;
429
+ }
430
+ async function executeWithTimeout(operation, options, stepInfo, externalSignal) {
431
+ const controller = new AbortController();
432
+ const behavior = options.onTimeout ?? "error";
433
+ const createTimeoutError = () => {
434
+ if (typeof behavior === "function") {
435
+ return behavior({
436
+ name: stepInfo.name,
437
+ key: stepInfo.key,
438
+ ms: options.ms
439
+ });
440
+ }
441
+ return options.error ?? {
442
+ type: "STEP_TIMEOUT",
443
+ stepName: stepInfo.name,
444
+ stepKey: stepInfo.key,
445
+ timeoutMs: options.ms,
446
+ attempt: stepInfo.attempt
447
+ };
448
+ };
449
+ let timeoutId;
450
+ if (externalSignal?.aborted) {
451
+ controller.abort(externalSignal.reason);
452
+ }
453
+ let externalAbortHandler;
454
+ if (externalSignal && !externalSignal.aborted) {
455
+ externalAbortHandler = () => controller.abort(externalSignal.reason);
456
+ externalSignal.addEventListener("abort", externalAbortHandler, { once: true });
457
+ }
458
+ const timeoutPromise = new Promise((_, reject) => {
459
+ timeoutId = setTimeout(() => {
460
+ if (behavior !== "disconnect") {
461
+ controller.abort();
462
+ }
463
+ if (behavior === "option") {
464
+ reject({ [TIMEOUT_OPTION_SYMBOL]: true, ms: options.ms });
465
+ return;
466
+ }
467
+ reject({ [TIMEOUT_SYMBOL]: true, error: createTimeoutError() });
468
+ }, options.ms);
469
+ });
470
+ let operationPromise;
471
+ if (options.signal) {
472
+ operationPromise = Promise.resolve(
473
+ operation(controller.signal)
474
+ );
475
+ } else {
476
+ operationPromise = Promise.resolve(operation());
477
+ }
478
+ try {
479
+ const result = await Promise.race([operationPromise, timeoutPromise]);
480
+ return result;
481
+ } catch (error) {
482
+ if (typeof error === "object" && error !== null && error[TIMEOUT_OPTION_SYMBOL] === true) {
483
+ throw { [TIMEOUT_OPTION_SYMBOL]: true, ms: options.ms };
484
+ }
485
+ if (typeof error === "object" && error !== null && error[TIMEOUT_SYMBOL] === true) {
486
+ if (behavior === "disconnect") {
487
+ operationPromise.catch(() => {
488
+ });
489
+ }
490
+ const errorToThrow = error.error;
491
+ if (typeof errorToThrow === "object" && errorToThrow !== null && errorToThrow.type !== "STEP_TIMEOUT") {
492
+ const meta = {
493
+ timeoutMs: options.ms,
494
+ stepName: stepInfo.name,
495
+ stepKey: stepInfo.key,
496
+ attempt: stepInfo.attempt
497
+ };
498
+ if (STEP_TIMEOUT_MARKER in errorToThrow) {
499
+ errorToThrow[STEP_TIMEOUT_MARKER] = meta;
500
+ } else {
501
+ Object.defineProperty(errorToThrow, STEP_TIMEOUT_MARKER, {
502
+ value: meta,
503
+ enumerable: false,
504
+ writable: true,
505
+ configurable: false
506
+ });
507
+ }
508
+ }
509
+ throw errorToThrow;
510
+ }
511
+ throw error;
512
+ } finally {
513
+ clearTimeout(timeoutId);
514
+ if (externalAbortHandler && externalSignal) {
515
+ externalSignal.removeEventListener("abort", externalAbortHandler);
516
+ }
517
+ }
518
+ }
519
+ var DEFAULT_RETRY_CONFIG = {
520
+ backoff: "exponential",
521
+ initialDelay: 100,
522
+ maxDelay: 3e4,
523
+ jitter: true,
524
+ shouldRetry: () => true,
525
+ onRetry: () => {
526
+ }
527
+ };
528
+ async function runFn(fnOrDeps, optionsOrFn, maybeOptions) {
529
+ if (typeof fnOrDeps !== "function") {
530
+ const deps = fnOrDeps;
531
+ const boundFn = optionsOrFn;
532
+ if (typeof boundFn !== "function") {
533
+ throw new TypeError(
534
+ "[awaitly] run(deps, fn) requires a callback as the second argument. Example: run({ getUser }, async (s) => s.getUser(id))"
535
+ );
536
+ }
537
+ const classicRun = runFn;
538
+ return classicRun(
539
+ ({ step }) => boundFn(bindSteps(deps, step), { step }),
540
+ maybeOptions
541
+ );
542
+ }
543
+ const fn = fnOrDeps;
544
+ const options = optionsOrFn;
545
+ const {
546
+ onError,
547
+ onEvent,
548
+ catchUnexpected,
549
+ workflowId: providedWorkflowId,
550
+ workflowName,
551
+ context,
552
+ graph,
553
+ _workflowSignal
554
+ } = options && typeof options === "object" ? options : {};
555
+ const workflowId = providedWorkflowId ?? crypto.randomUUID();
556
+ const declaredIds = graph ? new Set(
557
+ Array.isArray(graph) ? graph : graph.states.map((state) => state.semanticId ?? state.id)
558
+ ) : void 0;
559
+ const declaredPatterns = declaredIds ? [...declaredIds].filter((id) => id.includes("{")).map(
560
+ (id) => new RegExp(
561
+ `^${id.replaceAll(/[.*+?^$()[\]\\|]/g, String.raw`\$&`).replaceAll(/\{[^}]*\}/g, ".+")}$`
562
+ )
563
+ ) : void 0;
564
+ const assertDeclared = (id, kind) => {
565
+ if (!declaredIds || declaredIds.has(id)) return;
566
+ if (declaredPatterns?.some((re) => re.test(id))) return;
567
+ throw new Error(
568
+ `[awaitly] ${kind} id "${id}" is not in the declared workflow graph. Declared ids: ${[...declaredIds].join(", ")}. Either add it to the graph or remove the graph option.`
569
+ );
570
+ };
571
+ const effectiveCatchUnexpected = catchUnexpected ?? defaultCatchUnexpected;
572
+ const activeScopeStack = [];
573
+ let stepIdCounter = 0;
574
+ const generateStepId = (stepKey) => {
575
+ return stepKey ?? `step_${++stepIdCounter}`;
576
+ };
577
+ const emitEvent = (event) => {
578
+ const eventWithContext = event.context !== void 0 || context === void 0 ? event : { ...event, context };
579
+ const eventWithName = workflowName !== void 0 && eventWithContext.workflowName === void 0 ? { ...eventWithContext, workflowName } : eventWithContext;
580
+ if (eventWithName.type === "step_success") {
581
+ const stepId = eventWithName.stepId;
582
+ for (let i = activeScopeStack.length - 1; i >= 0; i--) {
583
+ const scope = activeScopeStack[i];
584
+ if (scope.type === "race" && !scope.winnerId) {
585
+ scope.winnerId = stepId;
586
+ break;
587
+ }
588
+ }
589
+ }
590
+ onEvent?.(eventWithName, context);
591
+ };
592
+ const earlyExit = createEarlyExit;
593
+ const isEarlyExitE = (e) => isEarlyExit(e);
594
+ const wrapForStep = (error, _meta) => {
595
+ return error;
596
+ };
597
+ const isResultLike = (value) => {
598
+ if (typeof value === "function") return false;
599
+ if (value && typeof value === "object" && "ok" in value) return true;
600
+ if (value && typeof value === "object" && "then" in value && typeof value.then === "function") return true;
601
+ return false;
602
+ };
603
+ try {
604
+ let normalizeParallelOperations2 = function(rawOperations) {
605
+ const out = {};
606
+ for (const [key, value2] of Object.entries(rawOperations)) {
607
+ if (typeof value2 === "function") {
608
+ out[key] = value2;
609
+ } else if (value2 && typeof value2 === "object" && "fn" in value2) {
610
+ out[key] = value2.fn;
611
+ } else {
612
+ throw new TypeError(`step.all: operation "${key}" must be a function or { fn, errors? } object`);
613
+ }
614
+ }
615
+ return out;
616
+ }, executeParallelArray2 = function(name, operation) {
617
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
618
+ return (async () => {
619
+ const startTime = performance.now();
620
+ let scopeEnded = false;
621
+ activeScopeStack.push({ scopeId, type: "parallel" });
622
+ const emitScopeEnd = () => {
623
+ if (scopeEnded) return;
624
+ scopeEnded = true;
625
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
626
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
627
+ emitEvent({
628
+ type: "scope_end",
629
+ workflowId,
630
+ scopeId,
631
+ ts: Date.now(),
632
+ durationMs: performance.now() - startTime
633
+ });
634
+ };
635
+ emitEvent({
636
+ type: "scope_start",
637
+ workflowId,
638
+ scopeId,
639
+ scopeType: "parallel",
640
+ name,
641
+ ts: Date.now()
642
+ });
643
+ try {
644
+ const result = await operation();
645
+ emitScopeEnd();
646
+ if (!result.ok) {
647
+ onError?.(result.error, name, context);
648
+ throw earlyExit(result.error, {
649
+ origin: "result",
650
+ resultCause: result.cause
651
+ });
652
+ }
653
+ return result.value;
654
+ } catch (error) {
655
+ emitScopeEnd();
656
+ throw error;
657
+ }
658
+ })();
659
+ }, executeParallelNamed2 = function(operations, options2) {
660
+ const keys = Object.keys(operations);
661
+ const name = options2.name ?? `Parallel(${keys.join(", ")})`;
662
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
663
+ return (async () => {
664
+ const startTime = performance.now();
665
+ let scopeEnded = false;
666
+ activeScopeStack.push({ scopeId, type: "parallel" });
667
+ const emitScopeEnd = () => {
668
+ if (scopeEnded) return;
669
+ scopeEnded = true;
670
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
671
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
672
+ emitEvent({
673
+ type: "scope_end",
674
+ workflowId,
675
+ scopeId,
676
+ ts: Date.now(),
677
+ durationMs: performance.now() - startTime
678
+ });
679
+ };
680
+ emitEvent({
681
+ type: "scope_start",
682
+ workflowId,
683
+ scopeId,
684
+ scopeType: "parallel",
685
+ name,
686
+ ts: Date.now()
687
+ });
688
+ try {
689
+ const results = await new Promise((resolve) => {
690
+ if (keys.length === 0) {
691
+ resolve([]);
692
+ return;
693
+ }
694
+ let settled = false;
695
+ let pendingCount = keys.length;
696
+ const resultArray = new Array(keys.length);
697
+ for (let i = 0; i < keys.length; i++) {
698
+ const key = keys[i];
699
+ const index = i;
700
+ Promise.resolve(operations[key]()).catch((reason) => err(
701
+ { type: "PROMISE_REJECTED", cause: reason },
702
+ { cause: { type: "PROMISE_REJECTION", reason } }
703
+ )).then((result) => {
704
+ if (settled) return;
705
+ if (!result.ok) {
706
+ settled = true;
707
+ resolve([{ key, result }]);
708
+ return;
709
+ }
710
+ resultArray[index] = { key, result };
711
+ pendingCount--;
712
+ if (pendingCount === 0) {
713
+ resolve(resultArray);
714
+ }
715
+ });
716
+ }
717
+ });
718
+ emitScopeEnd();
719
+ const output = {};
720
+ for (const { key, result } of results) {
721
+ if (!result.ok) {
722
+ onError?.(result.error, key, context);
723
+ throw earlyExit(result.error, {
724
+ origin: "result",
725
+ resultCause: result.cause
726
+ });
727
+ }
728
+ output[key] = result.value;
729
+ }
730
+ return output;
731
+ } catch (error) {
732
+ emitScopeEnd();
733
+ throw error;
734
+ }
735
+ })();
736
+ };
737
+ var normalizeParallelOperations = normalizeParallelOperations2, executeParallelArray = executeParallelArray2, executeParallelNamed = executeParallelNamed2;
738
+ const stepFn = (id, operationOrResult, stepOptions) => {
739
+ return (async () => {
740
+ if (typeof id !== "string" || id.length === 0) {
741
+ throw new Error(
742
+ '[awaitly] step() requires an explicit string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))'
743
+ );
744
+ }
745
+ assertDeclared(id, "step");
746
+ const parsedOptions = stepOptions ?? {};
747
+ const stepMetadata = extractStepMetadata(parsedOptions);
748
+ const stepName = id;
749
+ const stepKey = parsedOptions.key ?? id;
750
+ const explicitKey = parsedOptions.key ?? id;
751
+ const { description: stepDescription, retry: retryConfig, timeout: timeoutConfig } = parsedOptions;
752
+ const stepId = generateStepId(stepKey);
753
+ const hasEventListeners = onEvent;
754
+ const overallStartTime = hasEventListeners ? performance.now() : 0;
755
+ const isDirectResult = isResultLike(operationOrResult);
756
+ const operation = isDirectResult ? () => operationOrResult : operationOrResult;
757
+ const maxAttempts = Math.max(1, retryConfig?.attempts ?? 1);
758
+ const effectiveRetry = {
759
+ attempts: maxAttempts,
760
+ backoff: retryConfig?.backoff ?? DEFAULT_RETRY_CONFIG.backoff,
761
+ initialDelay: retryConfig?.initialDelay ?? DEFAULT_RETRY_CONFIG.initialDelay,
762
+ maxDelay: retryConfig?.maxDelay ?? DEFAULT_RETRY_CONFIG.maxDelay,
763
+ jitter: retryConfig?.jitter ?? DEFAULT_RETRY_CONFIG.jitter,
764
+ shouldRetry: retryConfig?.shouldRetry ?? DEFAULT_RETRY_CONFIG.shouldRetry,
765
+ onRetry: retryConfig?.onRetry ?? DEFAULT_RETRY_CONFIG.onRetry
766
+ };
767
+ if (onEvent) {
768
+ emitEvent({
769
+ type: "step_start",
770
+ workflowId,
771
+ stepId,
772
+ stepKey,
773
+ name: stepName,
774
+ description: stepDescription,
775
+ ts: Date.now(),
776
+ ...stepMetadata && { metadata: stepMetadata }
777
+ });
778
+ }
779
+ let lastResult;
780
+ for (let attempt = 1; attempt <= effectiveRetry.attempts; attempt++) {
781
+ const attemptStartTime = hasEventListeners ? performance.now() : 0;
782
+ try {
783
+ let result;
784
+ if (timeoutConfig) {
785
+ result = await executeWithTimeout(
786
+ operation,
787
+ timeoutConfig,
788
+ { name: stepName, key: stepKey, attempt },
789
+ _workflowSignal
790
+ );
791
+ } else {
792
+ result = await operation();
793
+ }
794
+ if (result.ok) {
795
+ const durationMs = performance.now() - overallStartTime;
796
+ emitEvent({
797
+ type: "step_success",
798
+ workflowId,
799
+ stepId,
800
+ stepKey,
801
+ name: stepName,
802
+ description: stepDescription,
803
+ ts: Date.now(),
804
+ durationMs,
805
+ ...stepMetadata && { metadata: stepMetadata }
806
+ });
807
+ if (explicitKey) {
808
+ emitEvent({
809
+ type: "step_complete",
810
+ workflowId,
811
+ stepKey: explicitKey,
812
+ name: stepName,
813
+ description: stepDescription,
814
+ ts: Date.now(),
815
+ durationMs,
816
+ result,
817
+ ...stepMetadata && { metadata: stepMetadata }
818
+ });
819
+ }
820
+ return result.value;
821
+ }
822
+ lastResult = result;
823
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(result.error, attempt)) {
824
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
825
+ emitEvent({
826
+ type: "step_retry",
827
+ workflowId,
828
+ stepId,
829
+ stepKey,
830
+ name: stepName,
831
+ ts: Date.now(),
832
+ attempt: attempt + 1,
833
+ maxAttempts: effectiveRetry.attempts,
834
+ delayMs: delay,
835
+ error: result.error,
836
+ ...stepMetadata && { metadata: stepMetadata },
837
+ diagnostics: buildStepErrorPayload(result.error, parsedOptions.errorMeta, "result", attempt, performance.now() - overallStartTime)
838
+ });
839
+ effectiveRetry.onRetry(result.error, attempt, delay);
840
+ await sleep(delay);
841
+ continue;
842
+ }
843
+ if (effectiveRetry.attempts > 1) {
844
+ emitEvent({
845
+ type: "step_retries_exhausted",
846
+ workflowId,
847
+ stepId,
848
+ stepKey,
849
+ name: stepName,
850
+ ts: Date.now(),
851
+ durationMs: performance.now() - overallStartTime,
852
+ attempts: attempt,
853
+ lastError: result.error,
854
+ ...stepMetadata && { metadata: stepMetadata },
855
+ diagnostics: buildStepErrorPayload(result.error, parsedOptions.errorMeta, "result", attempt, performance.now() - overallStartTime)
856
+ });
857
+ }
858
+ break;
859
+ } catch (thrown) {
860
+ const durationMs = performance.now() - attemptStartTime;
861
+ if (isTimeoutOptionMarker(thrown)) {
862
+ const timeoutMs = thrown.ms;
863
+ emitEvent({
864
+ type: "step_timeout",
865
+ workflowId,
866
+ stepId,
867
+ stepKey,
868
+ name: stepName,
869
+ ts: Date.now(),
870
+ timeoutMs,
871
+ attempt,
872
+ ...stepMetadata && { metadata: stepMetadata },
873
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt)
874
+ });
875
+ emitEvent({
876
+ type: "step_success",
877
+ workflowId,
878
+ stepId,
879
+ stepKey,
880
+ name: stepName,
881
+ description: stepDescription,
882
+ ts: Date.now(),
883
+ durationMs: performance.now() - overallStartTime,
884
+ ...stepMetadata && { metadata: stepMetadata }
885
+ });
886
+ if (explicitKey) {
887
+ emitEvent({
888
+ type: "step_complete",
889
+ workflowId,
890
+ stepKey: explicitKey,
891
+ name: stepName,
892
+ description: stepDescription,
893
+ ts: Date.now(),
894
+ durationMs: performance.now() - overallStartTime,
895
+ result: ok2(void 0),
896
+ ...stepMetadata && { metadata: stepMetadata }
897
+ });
898
+ }
899
+ return void 0;
900
+ }
901
+ if (isEarlyExitE(thrown)) {
902
+ emitEvent({
903
+ type: "step_aborted",
904
+ workflowId,
905
+ stepId,
906
+ stepKey,
907
+ name: stepName,
908
+ description: stepDescription,
909
+ ts: Date.now(),
910
+ durationMs,
911
+ ...stepMetadata && { metadata: stepMetadata }
912
+ });
913
+ throw thrown;
914
+ }
915
+ if (isStepTimeoutError(thrown)) {
916
+ const timeoutMeta = getStepTimeoutMeta(thrown);
917
+ const timeoutMs = timeoutConfig?.ms ?? timeoutMeta?.timeoutMs ?? 0;
918
+ emitEvent({
919
+ type: "step_timeout",
920
+ workflowId,
921
+ stepId,
922
+ stepKey,
923
+ name: stepName,
924
+ ts: Date.now(),
925
+ timeoutMs,
926
+ attempt,
927
+ ...stepMetadata && { metadata: stepMetadata },
928
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt)
929
+ });
930
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(thrown, attempt)) {
931
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
932
+ emitEvent({
933
+ type: "step_retry",
934
+ workflowId,
935
+ stepId,
936
+ stepKey,
937
+ name: stepName,
938
+ ts: Date.now(),
939
+ attempt: attempt + 1,
940
+ maxAttempts: effectiveRetry.attempts,
941
+ delayMs: delay,
942
+ error: thrown,
943
+ ...stepMetadata && { metadata: stepMetadata },
944
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, performance.now() - overallStartTime)
945
+ });
946
+ effectiveRetry.onRetry(thrown, attempt, delay);
947
+ await sleep(delay);
948
+ continue;
949
+ }
950
+ if (effectiveRetry.attempts > 1) {
951
+ emitEvent({
952
+ type: "step_retries_exhausted",
953
+ workflowId,
954
+ stepId,
955
+ stepKey,
956
+ name: stepName,
957
+ ts: Date.now(),
958
+ durationMs: performance.now() - overallStartTime,
959
+ attempts: attempt,
960
+ lastError: thrown,
961
+ ...stepMetadata && { metadata: stepMetadata },
962
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, performance.now() - overallStartTime)
963
+ });
964
+ }
965
+ const totalDurationMs3 = performance.now() - overallStartTime;
966
+ emitEvent({
967
+ type: "step_error",
968
+ workflowId,
969
+ stepId,
970
+ stepKey,
971
+ name: stepName,
972
+ description: stepDescription,
973
+ ts: Date.now(),
974
+ durationMs: totalDurationMs3,
975
+ error: thrown,
976
+ ...stepMetadata && { metadata: stepMetadata },
977
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, totalDurationMs3)
978
+ });
979
+ if (explicitKey) {
980
+ emitEvent({
981
+ type: "step_complete",
982
+ workflowId,
983
+ stepKey: explicitKey,
984
+ name: stepName,
985
+ description: stepDescription,
986
+ ts: Date.now(),
987
+ durationMs: totalDurationMs3,
988
+ result: err(thrown, { cause: thrown }),
989
+ meta: { origin: "throw", thrown },
990
+ ...stepMetadata && { metadata: stepMetadata }
991
+ });
992
+ }
993
+ onError?.(thrown, stepName, context);
994
+ throw earlyExit(thrown, { origin: "throw", thrown });
995
+ }
996
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(thrown, attempt)) {
997
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
998
+ emitEvent({
999
+ type: "step_retry",
1000
+ workflowId,
1001
+ stepId,
1002
+ stepKey,
1003
+ name: stepName,
1004
+ ts: Date.now(),
1005
+ attempt: attempt + 1,
1006
+ maxAttempts: effectiveRetry.attempts,
1007
+ delayMs: delay,
1008
+ error: thrown,
1009
+ ...stepMetadata && { metadata: stepMetadata },
1010
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, performance.now() - overallStartTime)
1011
+ });
1012
+ effectiveRetry.onRetry(thrown, attempt, delay);
1013
+ await sleep(delay);
1014
+ continue;
1015
+ }
1016
+ if (effectiveRetry.attempts > 1 && !isStepTimeoutError(thrown)) {
1017
+ emitEvent({
1018
+ type: "step_retries_exhausted",
1019
+ workflowId,
1020
+ stepId,
1021
+ stepKey,
1022
+ name: stepName,
1023
+ ts: Date.now(),
1024
+ durationMs: performance.now() - overallStartTime,
1025
+ attempts: attempt,
1026
+ lastError: thrown,
1027
+ ...stepMetadata && { metadata: stepMetadata },
1028
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, performance.now() - overallStartTime)
1029
+ });
1030
+ }
1031
+ const totalDurationMs2 = performance.now() - overallStartTime;
1032
+ let mappedError;
1033
+ try {
1034
+ mappedError = effectiveCatchUnexpected(thrown);
1035
+ } catch (mapperError) {
1036
+ throw createMapperException(mapperError);
1037
+ }
1038
+ emitEvent({
1039
+ type: "step_error",
1040
+ workflowId,
1041
+ stepId,
1042
+ stepKey,
1043
+ name: stepName,
1044
+ description: stepDescription,
1045
+ ts: Date.now(),
1046
+ durationMs: totalDurationMs2,
1047
+ error: mappedError,
1048
+ ...stepMetadata && { metadata: stepMetadata },
1049
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, totalDurationMs2)
1050
+ });
1051
+ if (explicitKey) {
1052
+ emitEvent({
1053
+ type: "step_complete",
1054
+ workflowId,
1055
+ stepKey: explicitKey,
1056
+ name: stepName,
1057
+ description: stepDescription,
1058
+ ts: Date.now(),
1059
+ durationMs: totalDurationMs2,
1060
+ result: err(mappedError, { cause: thrown }),
1061
+ meta: { origin: "throw", thrown },
1062
+ ...stepMetadata && { metadata: stepMetadata }
1063
+ });
1064
+ }
1065
+ onError?.(mappedError, stepName, context);
1066
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1067
+ }
1068
+ }
1069
+ const errorResult = lastResult;
1070
+ const totalDurationMs = performance.now() - overallStartTime;
1071
+ const wrappedError = wrapForStep(errorResult.error, {
1072
+ origin: "result",
1073
+ resultCause: errorResult.cause
1074
+ });
1075
+ emitEvent({
1076
+ type: "step_error",
1077
+ workflowId,
1078
+ stepId,
1079
+ stepKey,
1080
+ name: stepName,
1081
+ description: stepDescription,
1082
+ ts: Date.now(),
1083
+ durationMs: totalDurationMs,
1084
+ error: wrappedError,
1085
+ ...stepMetadata && { metadata: stepMetadata },
1086
+ diagnostics: buildStepErrorPayload(errorResult.error, parsedOptions.errorMeta, "result", effectiveRetry.attempts, totalDurationMs)
1087
+ });
1088
+ if (explicitKey) {
1089
+ emitEvent({
1090
+ type: "step_complete",
1091
+ workflowId,
1092
+ stepKey: explicitKey,
1093
+ name: stepName,
1094
+ description: stepDescription,
1095
+ ts: Date.now(),
1096
+ durationMs: totalDurationMs,
1097
+ result: errorResult,
1098
+ meta: { origin: "result", resultCause: errorResult.cause },
1099
+ ...stepMetadata && { metadata: stepMetadata }
1100
+ });
1101
+ }
1102
+ onError?.(wrappedError, stepName, context);
1103
+ throw earlyExit(wrappedError, {
1104
+ origin: "result",
1105
+ resultCause: errorResult.cause
1106
+ });
1107
+ })();
1108
+ };
1109
+ stepFn.try = (id, operation, opts) => {
1110
+ if (typeof id !== "string" || id.length === 0) {
1111
+ throw new Error(
1112
+ '[awaitly] step.try() requires an explicit string ID as the first argument. Example: step.try("parse", () => JSON.parse(str), { error: "PARSE_ERROR" })'
1113
+ );
1114
+ }
1115
+ assertDeclared(id, "step");
1116
+ const mapToError = "error" in opts ? () => opts.error : opts.onError;
1117
+ if (opts.retry || opts.timeout) {
1118
+ return stepFn.retry(
1119
+ id,
1120
+ async () => {
1121
+ try {
1122
+ return ok2(await operation());
1123
+ } catch (cause) {
1124
+ return err(mapToError(cause), { cause });
1125
+ }
1126
+ },
1127
+ {
1128
+ attempts: opts.retry?.attempts ?? 1,
1129
+ ...opts.retry ?? {},
1130
+ key: opts.key,
1131
+ timeout: opts.timeout
1132
+ }
1133
+ );
1134
+ }
1135
+ const stepKey = opts.key ?? id;
1136
+ const stepName = id;
1137
+ const stepId = id;
1138
+ const hasEventListeners = onEvent;
1139
+ return (async () => {
1140
+ const startTime = hasEventListeners ? performance.now() : 0;
1141
+ if (onEvent) {
1142
+ emitEvent({
1143
+ type: "step_start",
1144
+ workflowId,
1145
+ stepId,
1146
+ stepKey,
1147
+ name: stepName,
1148
+ ts: Date.now()
1149
+ });
1150
+ }
1151
+ try {
1152
+ const value2 = await operation();
1153
+ const durationMs = performance.now() - startTime;
1154
+ emitEvent({
1155
+ type: "step_success",
1156
+ workflowId,
1157
+ stepId,
1158
+ stepKey,
1159
+ name: stepName,
1160
+ ts: Date.now(),
1161
+ durationMs
1162
+ });
1163
+ if (stepKey) {
1164
+ emitEvent({
1165
+ type: "step_complete",
1166
+ workflowId,
1167
+ stepKey,
1168
+ name: stepName,
1169
+ ts: Date.now(),
1170
+ durationMs,
1171
+ result: ok2(value2)
1172
+ });
1173
+ }
1174
+ return value2;
1175
+ } catch (error) {
1176
+ const mapped = mapToError(error);
1177
+ const durationMs = performance.now() - startTime;
1178
+ const wrappedError = wrapForStep(mapped, { origin: "throw", thrown: error });
1179
+ emitEvent({
1180
+ type: "step_error",
1181
+ workflowId,
1182
+ stepId,
1183
+ stepKey,
1184
+ name: stepName,
1185
+ ts: Date.now(),
1186
+ durationMs,
1187
+ error: wrappedError
1188
+ });
1189
+ if (stepKey) {
1190
+ emitEvent({
1191
+ type: "step_complete",
1192
+ workflowId,
1193
+ stepKey,
1194
+ name: stepName,
1195
+ ts: Date.now(),
1196
+ durationMs,
1197
+ result: err(mapped, { cause: error }),
1198
+ meta: { origin: "throw", thrown: error }
1199
+ });
1200
+ }
1201
+ onError?.(wrappedError, stepName, context);
1202
+ throw earlyExit(wrappedError, { origin: "throw", thrown: error });
1203
+ }
1204
+ })();
1205
+ };
1206
+ stepFn.fromResult = (id, operation, opts) => {
1207
+ if (typeof id !== "string" || id.length === 0) {
1208
+ throw new Error(
1209
+ '[awaitly] step.fromResult() requires an explicit string ID as the first argument. Example: step.fromResult("callProvider", () => callProvider(input), { onError: (e) => ({ type: "FAILED" }) })'
1210
+ );
1211
+ }
1212
+ assertDeclared(id, "step");
1213
+ const stepKey = opts.key ?? id;
1214
+ const stepName = id;
1215
+ const stepId = id;
1216
+ const mapToError = "error" in opts ? () => opts.error : opts.onError;
1217
+ const hasEventListeners = onEvent;
1218
+ return (async () => {
1219
+ const startTime = hasEventListeners ? performance.now() : 0;
1220
+ if (onEvent) {
1221
+ emitEvent({
1222
+ type: "step_start",
1223
+ workflowId,
1224
+ stepId,
1225
+ stepKey,
1226
+ name: stepName,
1227
+ ts: Date.now()
1228
+ });
1229
+ }
1230
+ const result = await operation();
1231
+ if (result.ok) {
1232
+ const durationMs = performance.now() - startTime;
1233
+ emitEvent({
1234
+ type: "step_success",
1235
+ workflowId,
1236
+ stepId,
1237
+ stepKey,
1238
+ name: stepName,
1239
+ ts: Date.now(),
1240
+ durationMs
1241
+ });
1242
+ if (stepKey) {
1243
+ emitEvent({
1244
+ type: "step_complete",
1245
+ workflowId,
1246
+ stepKey,
1247
+ name: stepName,
1248
+ ts: Date.now(),
1249
+ durationMs,
1250
+ result: ok2(result.value)
1251
+ });
1252
+ }
1253
+ return result.value;
1254
+ } else {
1255
+ const mapped = mapToError(result.error);
1256
+ const durationMs = performance.now() - startTime;
1257
+ const wrappedError = wrapForStep(mapped, {
1258
+ origin: "result",
1259
+ resultCause: result.error
1260
+ });
1261
+ emitEvent({
1262
+ type: "step_error",
1263
+ workflowId,
1264
+ stepId,
1265
+ stepKey,
1266
+ name: stepName,
1267
+ ts: Date.now(),
1268
+ durationMs,
1269
+ error: wrappedError
1270
+ });
1271
+ if (stepKey) {
1272
+ emitEvent({
1273
+ type: "step_complete",
1274
+ workflowId,
1275
+ stepKey,
1276
+ name: stepName,
1277
+ ts: Date.now(),
1278
+ durationMs,
1279
+ result: err(mapped, { cause: result.error }),
1280
+ meta: { origin: "result", resultCause: result.error }
1281
+ });
1282
+ }
1283
+ onError?.(wrappedError, stepName, context);
1284
+ throw earlyExit(wrappedError, {
1285
+ origin: "result",
1286
+ resultCause: result.error
1287
+ });
1288
+ }
1289
+ })();
1290
+ };
1291
+ stepFn.fromNullable = (id, operation, onNull, options2) => {
1292
+ if (typeof id !== "string" || id.length === 0) {
1293
+ throw new Error(
1294
+ '[awaitly] step.fromNullable() requires an explicit string ID as the first argument. Example: step.fromNullable("getUser", () => db.find(id), () => ({ type: "NOT_FOUND" }))'
1295
+ );
1296
+ }
1297
+ return stepFn(
1298
+ id,
1299
+ async () => {
1300
+ const value2 = await operation();
1301
+ return value2 != null ? ok2(value2) : err(onNull());
1302
+ },
1303
+ options2
1304
+ );
1305
+ };
1306
+ stepFn.retry = (id, operation, options2) => {
1307
+ if (typeof id !== "string" || id.length === 0) {
1308
+ throw new Error(
1309
+ '[awaitly] step.retry() requires an explicit string ID as the first argument. Example: step.retry("fetchData", () => fetchData(), { attempts: 3 })'
1310
+ );
1311
+ }
1312
+ return stepFn(id, operation, {
1313
+ key: options2.key ?? id,
1314
+ retry: {
1315
+ attempts: options2.attempts,
1316
+ backoff: options2.backoff,
1317
+ initialDelay: options2.initialDelay,
1318
+ maxDelay: options2.maxDelay,
1319
+ jitter: options2.jitter,
1320
+ shouldRetry: options2.shouldRetry,
1321
+ onRetry: options2.onRetry
1322
+ },
1323
+ timeout: options2.timeout
1324
+ });
1325
+ };
1326
+ stepFn.withTimeout = (id, operation, options2) => {
1327
+ if (typeof id !== "string" || id.length === 0) {
1328
+ throw new Error(
1329
+ '[awaitly] step.withTimeout() requires an explicit string ID as the first argument. Example: step.withTimeout("slowOp", () => slowOp(), { ms: 5000 })'
1330
+ );
1331
+ }
1332
+ return stepFn(
1333
+ id,
1334
+ operation,
1335
+ {
1336
+ key: options2.key ?? id,
1337
+ timeout: options2
1338
+ }
1339
+ );
1340
+ };
1341
+ stepFn.sleep = (id, duration, options2) => {
1342
+ if (typeof id !== "string" || id.length === 0) {
1343
+ throw new Error(
1344
+ '[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")'
1345
+ );
1346
+ }
1347
+ const d = typeof duration === "string" ? parseDurationString(duration) : duration;
1348
+ if (!d) {
1349
+ throw new Error(`step.sleep: invalid duration '${duration}'`);
1350
+ }
1351
+ const ms = d.millis;
1352
+ const userSignal = options2?.signal;
1353
+ return stepFn(
1354
+ id,
1355
+ async () => {
1356
+ if (_workflowSignal?.aborted || userSignal?.aborted) {
1357
+ const e = new Error("Sleep aborted");
1358
+ e.name = "AbortError";
1359
+ throw e;
1360
+ }
1361
+ return new Promise((resolve, reject) => {
1362
+ const state = { timeoutId: void 0 };
1363
+ const onAbort = () => {
1364
+ if (state.timeoutId) clearTimeout(state.timeoutId);
1365
+ const e = new Error("Sleep aborted");
1366
+ e.name = "AbortError";
1367
+ reject(e);
1368
+ };
1369
+ _workflowSignal?.addEventListener("abort", onAbort, { once: true });
1370
+ userSignal?.addEventListener("abort", onAbort, { once: true });
1371
+ state.timeoutId = setTimeout(() => {
1372
+ _workflowSignal?.removeEventListener("abort", onAbort);
1373
+ userSignal?.removeEventListener("abort", onAbort);
1374
+ resolve(ok2(void 0));
1375
+ }, ms);
1376
+ });
1377
+ },
1378
+ {
1379
+ key: options2?.key ?? id,
1380
+ description: options2?.description
1381
+ }
1382
+ );
1383
+ };
1384
+ stepFn.all = ((...args) => {
1385
+ if (typeof args[0] !== "string") {
1386
+ throw new TypeError(
1387
+ "step.all(name, ...): first argument must be a string (step name). Example: step.all('Fetch data', { user: () => fetchUser(), posts: () => fetchPosts() })"
1388
+ );
1389
+ }
1390
+ const name = args[0];
1391
+ const second = args[1];
1392
+ if (typeof second === "function") {
1393
+ return executeParallelArray2(name, second);
1394
+ }
1395
+ if (second && typeof second === "object" && !Array.isArray(second)) {
1396
+ const rawOperations = second;
1397
+ const normalizedOperations = normalizeParallelOperations2(rawOperations);
1398
+ return executeParallelNamed2(normalizedOperations, { name });
1399
+ }
1400
+ throw new TypeError(
1401
+ "step.all(name, ...): second argument must be a function (array form) or an object of operations (object form)."
1402
+ );
1403
+ });
1404
+ stepFn.race = (name, operation) => {
1405
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1406
+ return (async () => {
1407
+ const startTime = performance.now();
1408
+ let scopeEnded = false;
1409
+ const scopeEntry = { scopeId, type: "race", winnerId: void 0 };
1410
+ activeScopeStack.push(scopeEntry);
1411
+ const emitScopeEnd = () => {
1412
+ if (scopeEnded) return;
1413
+ scopeEnded = true;
1414
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
1415
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
1416
+ emitEvent({
1417
+ type: "scope_end",
1418
+ workflowId,
1419
+ scopeId,
1420
+ ts: Date.now(),
1421
+ durationMs: performance.now() - startTime,
1422
+ winnerId: scopeEntry.winnerId
1423
+ });
1424
+ };
1425
+ emitEvent({
1426
+ type: "scope_start",
1427
+ workflowId,
1428
+ scopeId,
1429
+ scopeType: "race",
1430
+ name,
1431
+ ts: Date.now()
1432
+ });
1433
+ try {
1434
+ const result = await operation();
1435
+ emitScopeEnd();
1436
+ if (!result.ok) {
1437
+ onError?.(result.error, name, context);
1438
+ throw earlyExit(result.error, {
1439
+ origin: "result",
1440
+ resultCause: result.cause
1441
+ });
1442
+ }
1443
+ return result.value;
1444
+ } catch (error) {
1445
+ emitScopeEnd();
1446
+ throw error;
1447
+ }
1448
+ })();
1449
+ };
1450
+ stepFn.if = (id, conditionLabel, condition) => {
1451
+ assertDeclared(id, "decision");
1452
+ const value2 = condition();
1453
+ emitEvent({
1454
+ type: "decision",
1455
+ workflowId,
1456
+ decisionId: id,
1457
+ label: conditionLabel,
1458
+ branch: value2 ? "then" : "else",
1459
+ value: value2,
1460
+ ts: Date.now()
1461
+ });
1462
+ return value2;
1463
+ };
1464
+ stepFn.label = stepFn.if;
1465
+ stepFn.branch = async (id, options2) => {
1466
+ const { condition, then: thenFn, else: elseFn } = options2;
1467
+ assertDeclared(id, "decision");
1468
+ const conditionResult = condition();
1469
+ const branch = conditionResult ? "then" : "else";
1470
+ const startTime = performance.now();
1471
+ emitEvent({
1472
+ type: "decision",
1473
+ workflowId,
1474
+ decisionId: id,
1475
+ label: options2.conditionLabel,
1476
+ branch,
1477
+ value: conditionResult,
1478
+ phase: "start",
1479
+ ts: Date.now()
1480
+ });
1481
+ const emitEnd = () => {
1482
+ emitEvent({
1483
+ type: "decision",
1484
+ workflowId,
1485
+ decisionId: id,
1486
+ label: options2.conditionLabel,
1487
+ branch,
1488
+ value: conditionResult,
1489
+ phase: "end",
1490
+ durationMs: performance.now() - startTime,
1491
+ ts: Date.now()
1492
+ });
1493
+ };
1494
+ try {
1495
+ if (conditionResult) {
1496
+ return await thenFn();
1497
+ } else if (elseFn) {
1498
+ return await elseFn();
1499
+ }
1500
+ return void 0;
1501
+ } finally {
1502
+ emitEnd();
1503
+ }
1504
+ };
1505
+ stepFn.arm = (fn2, errors) => {
1506
+ return { fn: fn2, errors };
1507
+ };
1508
+ stepFn.forEach = async (_id, items, options2) => {
1509
+ const results = [];
1510
+ const maxIterations = options2.maxIterations;
1511
+ let index = 0;
1512
+ const isRunForm = "run" in options2;
1513
+ const asyncItems = Symbol.asyncIterator in items ? items : (async function* () {
1514
+ yield* items;
1515
+ })();
1516
+ for await (const item of asyncItems) {
1517
+ if (maxIterations !== void 0 && index >= maxIterations) {
1518
+ break;
1519
+ }
1520
+ let result;
1521
+ if (isRunForm) {
1522
+ const runOptions = options2;
1523
+ result = await runOptions.run(item, index);
1524
+ } else {
1525
+ const itemOptions = options2;
1526
+ result = await itemOptions.item.handler(item, index, stepFn);
1527
+ }
1528
+ results.push(result);
1529
+ index++;
1530
+ }
1531
+ return results;
1532
+ };
1533
+ stepFn.item = (handler) => {
1534
+ return {
1535
+ __forEachItemHandler: true,
1536
+ handler
1537
+ };
1538
+ };
1539
+ stepFn.dep = (_name, fn2) => {
1540
+ return fn2;
1541
+ };
1542
+ stepFn.workflow = (id, getter, options2) => {
1543
+ return stepFn(id, getter, options2);
1544
+ };
1545
+ stepFn.map = async (id, items, mapper, options2) => {
1546
+ const concurrency = options2?.concurrency ?? items.length;
1547
+ return stepFn(
1548
+ id,
1549
+ () => {
1550
+ if (concurrency >= items.length) {
1551
+ return allAsync(items.map((item, index) => mapper(item, index)));
1552
+ } else {
1553
+ return (async () => {
1554
+ const results = [];
1555
+ for (let i = 0; i < items.length; i += concurrency) {
1556
+ const batch = items.slice(i, i + concurrency);
1557
+ const batchResult = await allAsync(
1558
+ batch.map((item, batchIndex) => mapper(item, i + batchIndex))
1559
+ );
1560
+ if (!batchResult.ok) {
1561
+ return batchResult;
1562
+ }
1563
+ results.push(...batchResult.value);
1564
+ }
1565
+ return ok2(results);
1566
+ })();
1567
+ }
1568
+ },
1569
+ { key: options2?.key }
1570
+ );
1571
+ };
1572
+ stepFn.withFallback = (id, operation, options2) => {
1573
+ if (typeof id !== "string" || id.length === 0) {
1574
+ throw new Error(
1575
+ '[awaitly] step.withFallback() requires an explicit string ID as the first argument. Example: step.withFallback("getUser", () => fetchUser(id), { fallback: () => fetchFromCache(id) })'
1576
+ );
1577
+ }
1578
+ assertDeclared(id, "step");
1579
+ const stepKey = options2.key ?? id;
1580
+ const stepName = id;
1581
+ const stepId = generateStepId(stepKey);
1582
+ const hasEventListeners = onEvent;
1583
+ return (async () => {
1584
+ const startTime = hasEventListeners ? performance.now() : 0;
1585
+ if (onEvent) {
1586
+ emitEvent({
1587
+ type: "step_start",
1588
+ workflowId,
1589
+ stepId,
1590
+ stepKey,
1591
+ name: stepName,
1592
+ ts: Date.now()
1593
+ });
1594
+ }
1595
+ let primaryResult;
1596
+ try {
1597
+ primaryResult = await operation();
1598
+ } catch (thrown) {
1599
+ if (isEarlyExitE(thrown)) {
1600
+ emitEvent({
1601
+ type: "step_aborted",
1602
+ workflowId,
1603
+ stepId,
1604
+ stepKey,
1605
+ name: stepName,
1606
+ ts: Date.now(),
1607
+ durationMs: performance.now() - startTime
1608
+ });
1609
+ throw thrown;
1610
+ }
1611
+ let mappedError;
1612
+ try {
1613
+ mappedError = effectiveCatchUnexpected(thrown);
1614
+ } catch (mapperError) {
1615
+ throw createMapperException(mapperError);
1616
+ }
1617
+ if (options2.on !== void 0 && options2.on !== mappedError) {
1618
+ const durationMs2 = performance.now() - startTime;
1619
+ emitEvent({
1620
+ type: "step_error",
1621
+ workflowId,
1622
+ stepId,
1623
+ stepKey,
1624
+ name: stepName,
1625
+ ts: Date.now(),
1626
+ durationMs: durationMs2,
1627
+ error: mappedError
1628
+ });
1629
+ if (stepKey) {
1630
+ emitEvent({
1631
+ type: "step_complete",
1632
+ workflowId,
1633
+ stepKey,
1634
+ name: stepName,
1635
+ ts: Date.now(),
1636
+ durationMs: durationMs2,
1637
+ result: err(mappedError, { cause: thrown }),
1638
+ meta: { origin: "throw", thrown }
1639
+ });
1640
+ }
1641
+ onError?.(mappedError, stepName, context);
1642
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1643
+ }
1644
+ let fallbackResultFromThrow;
1645
+ try {
1646
+ fallbackResultFromThrow = await options2.fallback();
1647
+ } catch (fallbackThrown) {
1648
+ if (isEarlyExitE(fallbackThrown)) {
1649
+ emitEvent({
1650
+ type: "step_aborted",
1651
+ workflowId,
1652
+ stepId,
1653
+ stepKey,
1654
+ name: stepName,
1655
+ ts: Date.now(),
1656
+ durationMs: performance.now() - startTime
1657
+ });
1658
+ throw fallbackThrown;
1659
+ }
1660
+ let fallbackMappedError;
1661
+ try {
1662
+ fallbackMappedError = effectiveCatchUnexpected(fallbackThrown);
1663
+ } catch (mapperError) {
1664
+ throw createMapperException(mapperError);
1665
+ }
1666
+ const durationMs2 = performance.now() - startTime;
1667
+ emitEvent({
1668
+ type: "step_error",
1669
+ workflowId,
1670
+ stepId,
1671
+ stepKey,
1672
+ name: stepName,
1673
+ ts: Date.now(),
1674
+ durationMs: durationMs2,
1675
+ error: fallbackMappedError
1676
+ });
1677
+ if (stepKey) {
1678
+ emitEvent({
1679
+ type: "step_complete",
1680
+ workflowId,
1681
+ stepKey,
1682
+ name: stepName,
1683
+ ts: Date.now(),
1684
+ durationMs: durationMs2,
1685
+ result: err(fallbackMappedError, { cause: fallbackThrown }),
1686
+ meta: { origin: "throw", thrown: fallbackThrown }
1687
+ });
1688
+ }
1689
+ onError?.(fallbackMappedError, stepName, context);
1690
+ throw earlyExit(fallbackMappedError, { origin: "throw", thrown: fallbackThrown });
1691
+ }
1692
+ if (fallbackResultFromThrow.ok) {
1693
+ const durationMs2 = performance.now() - startTime;
1694
+ emitEvent({
1695
+ type: "step_success",
1696
+ workflowId,
1697
+ stepId,
1698
+ stepKey,
1699
+ name: stepName,
1700
+ ts: Date.now(),
1701
+ durationMs: durationMs2
1702
+ });
1703
+ if (stepKey) {
1704
+ emitEvent({
1705
+ type: "step_complete",
1706
+ workflowId,
1707
+ stepKey,
1708
+ name: stepName,
1709
+ ts: Date.now(),
1710
+ durationMs: durationMs2,
1711
+ result: fallbackResultFromThrow,
1712
+ meta: { origin: "fallback", fallbackUsed: true, fallbackReason: String(mappedError) }
1713
+ });
1714
+ }
1715
+ return fallbackResultFromThrow.value;
1716
+ } else {
1717
+ const durationMs2 = performance.now() - startTime;
1718
+ const wrappedError2 = wrapForStep(fallbackResultFromThrow.error, {
1719
+ origin: "result",
1720
+ resultCause: fallbackResultFromThrow.cause
1721
+ });
1722
+ emitEvent({
1723
+ type: "step_error",
1724
+ workflowId,
1725
+ stepId,
1726
+ stepKey,
1727
+ name: stepName,
1728
+ ts: Date.now(),
1729
+ durationMs: durationMs2,
1730
+ error: wrappedError2
1731
+ });
1732
+ if (stepKey) {
1733
+ emitEvent({
1734
+ type: "step_complete",
1735
+ workflowId,
1736
+ stepKey,
1737
+ name: stepName,
1738
+ ts: Date.now(),
1739
+ durationMs: durationMs2,
1740
+ result: fallbackResultFromThrow,
1741
+ meta: { origin: "result", resultCause: fallbackResultFromThrow.cause }
1742
+ });
1743
+ }
1744
+ onError?.(wrappedError2, stepName, context);
1745
+ throw earlyExit(wrappedError2, {
1746
+ origin: "result",
1747
+ resultCause: fallbackResultFromThrow.cause
1748
+ });
1749
+ }
1750
+ }
1751
+ if (primaryResult.ok) {
1752
+ const durationMs2 = performance.now() - startTime;
1753
+ emitEvent({
1754
+ type: "step_success",
1755
+ workflowId,
1756
+ stepId,
1757
+ stepKey,
1758
+ name: stepName,
1759
+ ts: Date.now(),
1760
+ durationMs: durationMs2
1761
+ });
1762
+ if (stepKey) {
1763
+ emitEvent({
1764
+ type: "step_complete",
1765
+ workflowId,
1766
+ stepKey,
1767
+ name: stepName,
1768
+ ts: Date.now(),
1769
+ durationMs: durationMs2,
1770
+ result: primaryResult
1771
+ });
1772
+ }
1773
+ return primaryResult.value;
1774
+ }
1775
+ const primaryError = primaryResult.error;
1776
+ if (options2.on !== void 0 && options2.on !== primaryError) {
1777
+ const durationMs2 = performance.now() - startTime;
1778
+ const wrappedError2 = wrapForStep(primaryError, {
1779
+ origin: "result",
1780
+ resultCause: primaryResult.cause
1781
+ });
1782
+ emitEvent({
1783
+ type: "step_error",
1784
+ workflowId,
1785
+ stepId,
1786
+ stepKey,
1787
+ name: stepName,
1788
+ ts: Date.now(),
1789
+ durationMs: durationMs2,
1790
+ error: wrappedError2
1791
+ });
1792
+ if (stepKey) {
1793
+ emitEvent({
1794
+ type: "step_complete",
1795
+ workflowId,
1796
+ stepKey,
1797
+ name: stepName,
1798
+ ts: Date.now(),
1799
+ durationMs: durationMs2,
1800
+ result: primaryResult,
1801
+ meta: { origin: "result", resultCause: primaryResult.cause }
1802
+ });
1803
+ }
1804
+ onError?.(wrappedError2, stepName, context);
1805
+ throw earlyExit(wrappedError2, {
1806
+ origin: "result",
1807
+ resultCause: primaryResult.cause
1808
+ });
1809
+ }
1810
+ let fallbackResult;
1811
+ try {
1812
+ fallbackResult = await options2.fallback();
1813
+ } catch (thrown) {
1814
+ if (isEarlyExitE(thrown)) {
1815
+ emitEvent({
1816
+ type: "step_aborted",
1817
+ workflowId,
1818
+ stepId,
1819
+ stepKey,
1820
+ name: stepName,
1821
+ ts: Date.now(),
1822
+ durationMs: performance.now() - startTime
1823
+ });
1824
+ throw thrown;
1825
+ }
1826
+ let mappedError;
1827
+ try {
1828
+ mappedError = effectiveCatchUnexpected(thrown);
1829
+ } catch (mapperError) {
1830
+ throw createMapperException(mapperError);
1831
+ }
1832
+ const durationMs2 = performance.now() - startTime;
1833
+ emitEvent({
1834
+ type: "step_error",
1835
+ workflowId,
1836
+ stepId,
1837
+ stepKey,
1838
+ name: stepName,
1839
+ ts: Date.now(),
1840
+ durationMs: durationMs2,
1841
+ error: mappedError
1842
+ });
1843
+ if (stepKey) {
1844
+ emitEvent({
1845
+ type: "step_complete",
1846
+ workflowId,
1847
+ stepKey,
1848
+ name: stepName,
1849
+ ts: Date.now(),
1850
+ durationMs: durationMs2,
1851
+ result: err(mappedError, { cause: thrown }),
1852
+ meta: { origin: "throw", thrown }
1853
+ });
1854
+ }
1855
+ onError?.(mappedError, stepName, context);
1856
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1857
+ }
1858
+ if (fallbackResult.ok) {
1859
+ const durationMs2 = performance.now() - startTime;
1860
+ emitEvent({
1861
+ type: "step_success",
1862
+ workflowId,
1863
+ stepId,
1864
+ stepKey,
1865
+ name: stepName,
1866
+ ts: Date.now(),
1867
+ durationMs: durationMs2
1868
+ });
1869
+ if (stepKey) {
1870
+ emitEvent({
1871
+ type: "step_complete",
1872
+ workflowId,
1873
+ stepKey,
1874
+ name: stepName,
1875
+ ts: Date.now(),
1876
+ durationMs: durationMs2,
1877
+ result: fallbackResult,
1878
+ meta: { origin: "fallback", fallbackUsed: true, fallbackReason: String(primaryError) }
1879
+ });
1880
+ }
1881
+ return fallbackResult.value;
1882
+ }
1883
+ const durationMs = performance.now() - startTime;
1884
+ const wrappedError = wrapForStep(fallbackResult.error, {
1885
+ origin: "result",
1886
+ resultCause: fallbackResult.cause
1887
+ });
1888
+ emitEvent({
1889
+ type: "step_error",
1890
+ workflowId,
1891
+ stepId,
1892
+ stepKey,
1893
+ name: stepName,
1894
+ ts: Date.now(),
1895
+ durationMs,
1896
+ error: wrappedError
1897
+ });
1898
+ if (stepKey) {
1899
+ emitEvent({
1900
+ type: "step_complete",
1901
+ workflowId,
1902
+ stepKey,
1903
+ name: stepName,
1904
+ ts: Date.now(),
1905
+ durationMs,
1906
+ result: fallbackResult,
1907
+ meta: { origin: "result", resultCause: fallbackResult.cause }
1908
+ });
1909
+ }
1910
+ onError?.(wrappedError, stepName, context);
1911
+ throw earlyExit(wrappedError, {
1912
+ origin: "result",
1913
+ resultCause: fallbackResult.cause
1914
+ });
1915
+ })();
1916
+ };
1917
+ stepFn.withResource = (id, options2) => {
1918
+ if (typeof id !== "string" || id.length === 0) {
1919
+ throw new Error(
1920
+ '[awaitly] step.withResource() requires an explicit string ID as the first argument. Example: step.withResource("useDb", { acquire: () => connect(), use: (db) => query(db), release: (db) => db.close() })'
1921
+ );
1922
+ }
1923
+ assertDeclared(id, "step");
1924
+ const stepKey = id;
1925
+ const stepName = id;
1926
+ const stepId = generateStepId(stepKey);
1927
+ const hasEventListeners = onEvent;
1928
+ return (async () => {
1929
+ const startTime = hasEventListeners ? performance.now() : 0;
1930
+ if (onEvent) {
1931
+ emitEvent({
1932
+ type: "step_start",
1933
+ workflowId,
1934
+ stepId,
1935
+ stepKey,
1936
+ name: stepName,
1937
+ ts: Date.now()
1938
+ });
1939
+ }
1940
+ let acquireResult;
1941
+ try {
1942
+ acquireResult = await options2.acquire();
1943
+ } catch (thrown) {
1944
+ if (isEarlyExitE(thrown)) {
1945
+ emitEvent({
1946
+ type: "step_aborted",
1947
+ workflowId,
1948
+ stepId,
1949
+ stepKey,
1950
+ name: stepName,
1951
+ ts: Date.now(),
1952
+ durationMs: performance.now() - startTime
1953
+ });
1954
+ throw thrown;
1955
+ }
1956
+ let mappedError;
1957
+ try {
1958
+ mappedError = effectiveCatchUnexpected(thrown);
1959
+ } catch (mapperError) {
1960
+ throw createMapperException(mapperError);
1961
+ }
1962
+ const durationMs2 = performance.now() - startTime;
1963
+ emitEvent({
1964
+ type: "step_error",
1965
+ workflowId,
1966
+ stepId,
1967
+ stepKey,
1968
+ name: stepName,
1969
+ ts: Date.now(),
1970
+ durationMs: durationMs2,
1971
+ error: mappedError
1972
+ });
1973
+ if (stepKey) {
1974
+ emitEvent({
1975
+ type: "step_complete",
1976
+ workflowId,
1977
+ stepKey,
1978
+ name: stepName,
1979
+ ts: Date.now(),
1980
+ durationMs: durationMs2,
1981
+ result: err(mappedError, { cause: thrown }),
1982
+ meta: { origin: "throw", thrown }
1983
+ });
1984
+ }
1985
+ onError?.(mappedError, stepName, context);
1986
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1987
+ }
1988
+ if (!acquireResult.ok) {
1989
+ const durationMs2 = performance.now() - startTime;
1990
+ const wrappedError2 = wrapForStep(acquireResult.error, {
1991
+ origin: "result",
1992
+ resultCause: acquireResult.cause
1993
+ });
1994
+ emitEvent({
1995
+ type: "step_error",
1996
+ workflowId,
1997
+ stepId,
1998
+ stepKey,
1999
+ name: stepName,
2000
+ ts: Date.now(),
2001
+ durationMs: durationMs2,
2002
+ error: wrappedError2
2003
+ });
2004
+ if (stepKey) {
2005
+ emitEvent({
2006
+ type: "step_complete",
2007
+ workflowId,
2008
+ stepKey,
2009
+ name: stepName,
2010
+ ts: Date.now(),
2011
+ durationMs: durationMs2,
2012
+ result: acquireResult,
2013
+ meta: { origin: "result", resultCause: acquireResult.cause }
2014
+ });
2015
+ }
2016
+ onError?.(wrappedError2, stepName, context);
2017
+ throw earlyExit(wrappedError2, {
2018
+ origin: "result",
2019
+ resultCause: acquireResult.cause
2020
+ });
2021
+ }
2022
+ const resource = acquireResult.value;
2023
+ let useResult;
2024
+ let useThrown;
2025
+ let useThrewNonResult = false;
2026
+ try {
2027
+ useResult = await options2.use(resource);
2028
+ } catch (thrown) {
2029
+ if (isEarlyExitE(thrown)) {
2030
+ try {
2031
+ await options2.release(resource);
2032
+ } catch (releaseErr) {
2033
+ console.warn(
2034
+ `[awaitly] step.withResource("${id}"): release threw after earlyExit:`,
2035
+ releaseErr
2036
+ );
2037
+ }
2038
+ throw thrown;
2039
+ }
2040
+ useThrown = thrown;
2041
+ useThrewNonResult = true;
2042
+ }
2043
+ try {
2044
+ await options2.release(resource);
2045
+ } catch (releaseErr) {
2046
+ console.warn(
2047
+ `[awaitly] step.withResource("${id}"): release threw:`,
2048
+ releaseErr
2049
+ );
2050
+ }
2051
+ if (useThrewNonResult) {
2052
+ let mappedError;
2053
+ try {
2054
+ mappedError = effectiveCatchUnexpected(useThrown);
2055
+ } catch (mapperError) {
2056
+ throw createMapperException(mapperError);
2057
+ }
2058
+ const durationMs2 = performance.now() - startTime;
2059
+ emitEvent({
2060
+ type: "step_error",
2061
+ workflowId,
2062
+ stepId,
2063
+ stepKey,
2064
+ name: stepName,
2065
+ ts: Date.now(),
2066
+ durationMs: durationMs2,
2067
+ error: mappedError
2068
+ });
2069
+ if (stepKey) {
2070
+ emitEvent({
2071
+ type: "step_complete",
2072
+ workflowId,
2073
+ stepKey,
2074
+ name: stepName,
2075
+ ts: Date.now(),
2076
+ durationMs: durationMs2,
2077
+ result: err(mappedError, { cause: useThrown }),
2078
+ meta: { origin: "throw", thrown: useThrown }
2079
+ });
2080
+ }
2081
+ onError?.(mappedError, stepName, context);
2082
+ throw earlyExit(mappedError, { origin: "throw", thrown: useThrown });
2083
+ }
2084
+ const result = useResult;
2085
+ if (result.ok) {
2086
+ const durationMs2 = performance.now() - startTime;
2087
+ emitEvent({
2088
+ type: "step_success",
2089
+ workflowId,
2090
+ stepId,
2091
+ stepKey,
2092
+ name: stepName,
2093
+ ts: Date.now(),
2094
+ durationMs: durationMs2
2095
+ });
2096
+ if (stepKey) {
2097
+ emitEvent({
2098
+ type: "step_complete",
2099
+ workflowId,
2100
+ stepKey,
2101
+ name: stepName,
2102
+ ts: Date.now(),
2103
+ durationMs: durationMs2,
2104
+ result
2105
+ });
2106
+ }
2107
+ return result.value;
2108
+ }
2109
+ const durationMs = performance.now() - startTime;
2110
+ const wrappedError = wrapForStep(result.error, {
2111
+ origin: "result",
2112
+ resultCause: result.cause
2113
+ });
2114
+ emitEvent({
2115
+ type: "step_error",
2116
+ workflowId,
2117
+ stepId,
2118
+ stepKey,
2119
+ name: stepName,
2120
+ ts: Date.now(),
2121
+ durationMs,
2122
+ error: wrappedError
2123
+ });
2124
+ if (stepKey) {
2125
+ emitEvent({
2126
+ type: "step_complete",
2127
+ workflowId,
2128
+ stepKey,
2129
+ name: stepName,
2130
+ ts: Date.now(),
2131
+ durationMs,
2132
+ result,
2133
+ meta: { origin: "result", resultCause: result.cause }
2134
+ });
2135
+ }
2136
+ onError?.(wrappedError, stepName, context);
2137
+ throw earlyExit(wrappedError, {
2138
+ origin: "result",
2139
+ resultCause: result.cause
2140
+ });
2141
+ })();
2142
+ };
2143
+ const step = stepFn;
2144
+ const value = await fn({ step });
2145
+ if (process.env.NODE_ENV !== "production" && value !== null && typeof value === "object" && "ok" in value && typeof value.ok === "boolean") {
2146
+ const maybeResult = value;
2147
+ if (maybeResult.ok === true && "value" in maybeResult || maybeResult.ok === false && "error" in maybeResult) {
2148
+ console.warn(
2149
+ `awaitly: Workflow executor returned a Result-like object. Return raw values, not ok() or err().
2150
+
2151
+ Incorrect: return ok({ data });
2152
+ Correct: return { data };
2153
+
2154
+ See: https://jagreehal.github.io/awaitly/guides/troubleshooting/#returning-ok-from-workflow-executor-double-wrapping`
2155
+ );
2156
+ }
2157
+ }
2158
+ return ok2(value);
2159
+ } catch (error) {
2160
+ if (isMapperException(error)) {
2161
+ throw error.thrown;
2162
+ }
2163
+ if (isEarlyExitE(error)) {
2164
+ const originalCause = error.meta.origin === "throw" ? error.meta.thrown : error.meta.origin === "result" ? error.meta.resultCause : void 0;
2165
+ return err(error.error, { cause: originalCause });
2166
+ }
2167
+ const mapped = effectiveCatchUnexpected(error);
2168
+ onError?.(mapped, "unexpected", context);
2169
+ return err(mapped, { cause: error });
2170
+ }
2171
+ }
2172
+ var runStrict = (fn, options) => {
2173
+ return runFn(fn, options);
2174
+ };
2175
+ var run = /* @__PURE__ */ Object.assign(runFn, { strict: runStrict });
2176
+ async function allAsync(results) {
2177
+ if (results.length === 0) {
2178
+ return ok2([]);
2179
+ }
2180
+ return new Promise((resolve) => {
2181
+ let settled = false;
2182
+ let pendingCount = results.length;
2183
+ const values = new Array(results.length);
2184
+ for (let i = 0; i < results.length; i++) {
2185
+ const index = i;
2186
+ Promise.resolve(results[index]).catch((reason) => err(
2187
+ { type: "PROMISE_REJECTED", cause: reason },
2188
+ { cause: { type: "PROMISE_REJECTION", reason } }
2189
+ )).then((result) => {
2190
+ if (settled) return;
2191
+ if (!result.ok) {
2192
+ settled = true;
2193
+ resolve(result);
2194
+ return;
2195
+ }
2196
+ values[index] = result.value;
2197
+ pendingCount--;
2198
+ if (pendingCount === 0) {
2199
+ resolve(ok2(values));
2200
+ }
2201
+ });
2202
+ }
2203
+ });
2204
+ }
2205
+
2206
+ // src/workflow/guards.ts
2207
+ function isStepComplete(event) {
2208
+ return event.type === "step_complete";
2209
+ }
2210
+ function isWorkflowCancelled(error) {
2211
+ return typeof error === "object" && error !== null && error.type === "WORKFLOW_CANCELLED";
2212
+ }
2213
+
2214
+ // src/persistence.ts
2215
+ var SnapshotFormatError = class extends Error {
2216
+ constructor(message, errors = []) {
2217
+ super(message);
2218
+ this.errors = errors;
2219
+ this.name = "SnapshotFormatError";
2220
+ }
2221
+ errors;
2222
+ };
2223
+ var SnapshotDecodeError = class extends Error {
2224
+ constructor(message, stepId, originalError) {
2225
+ super(message);
2226
+ this.stepId = stepId;
2227
+ this.originalError = originalError;
2228
+ this.name = "SnapshotDecodeError";
2229
+ }
2230
+ stepId;
2231
+ originalError;
2232
+ };
2233
+ function validateSnapshot(obj) {
2234
+ const errors = [];
2235
+ if (typeof obj !== "object" || obj === null) {
2236
+ return { valid: false, errors: ["Snapshot must be an object"] };
2237
+ }
2238
+ const snapshot = obj;
2239
+ if (!("formatVersion" in snapshot)) {
2240
+ errors.push("Missing required field: formatVersion");
2241
+ } else if (snapshot.formatVersion !== 1) {
2242
+ errors.push(`Invalid formatVersion: expected 1, got ${snapshot.formatVersion}`);
2243
+ }
2244
+ if (!("steps" in snapshot)) {
2245
+ errors.push("Missing required field: steps");
2246
+ } else if (typeof snapshot.steps !== "object" || snapshot.steps === null) {
2247
+ errors.push("steps must be an object");
2248
+ } else {
2249
+ const steps = snapshot.steps;
2250
+ for (const [stepId, stepResult] of Object.entries(steps)) {
2251
+ if (typeof stepResult !== "object" || stepResult === null) {
2252
+ errors.push(`steps["${stepId}"] must be an object`);
2253
+ continue;
2254
+ }
2255
+ const step = stepResult;
2256
+ if (!("ok" in step)) {
2257
+ errors.push(`steps["${stepId}"] missing required field: ok`);
2258
+ } else if (typeof step.ok !== "boolean") {
2259
+ errors.push(`steps["${stepId}"].ok must be a boolean`);
2260
+ } else if (step.ok === false) {
2261
+ if (!("error" in step)) {
2262
+ errors.push(`steps["${stepId}"] is error result but missing error field`);
2263
+ }
2264
+ if (!("cause" in step)) {
2265
+ errors.push(`steps["${stepId}"] is error result but missing cause field`);
2266
+ }
2267
+ }
2268
+ }
2269
+ }
2270
+ if (!("execution" in snapshot)) {
2271
+ errors.push("Missing required field: execution");
2272
+ } else if (typeof snapshot.execution !== "object" || snapshot.execution === null) {
2273
+ errors.push("execution must be an object");
2274
+ } else {
2275
+ const execution = snapshot.execution;
2276
+ if (!("status" in execution)) {
2277
+ errors.push("execution missing required field: status");
2278
+ } else if (!["running", "completed", "failed"].includes(execution.status)) {
2279
+ errors.push(`execution.status must be one of: running, completed, failed`);
2280
+ }
2281
+ if (!("lastUpdated" in execution)) {
2282
+ errors.push("execution missing required field: lastUpdated");
2283
+ } else if (typeof execution.lastUpdated !== "string") {
2284
+ errors.push("execution.lastUpdated must be a string (ISO timestamp)");
2285
+ }
2286
+ }
2287
+ if (errors.length > 0) {
2288
+ return { valid: false, errors };
2289
+ }
2290
+ return { valid: true, snapshot: obj };
2291
+ }
2292
+ function assertValidSnapshot(obj) {
2293
+ const result = validateSnapshot(obj);
2294
+ if (!result.valid) {
2295
+ throw new SnapshotFormatError(`Invalid snapshot format: ${result.errors[0]}`, result.errors);
2296
+ }
2297
+ return result.snapshot;
2298
+ }
2299
+ function mergeSnapshots(base, delta) {
2300
+ const mergedSteps = /* @__PURE__ */ Object.create(null);
2301
+ for (const [key, value] of Object.entries(base.steps)) {
2302
+ if (Object.prototype.hasOwnProperty.call(base.steps, key)) {
2303
+ mergedSteps[key] = value;
2304
+ }
2305
+ }
2306
+ for (const [key, value] of Object.entries(delta.steps)) {
2307
+ if (Object.prototype.hasOwnProperty.call(delta.steps, key)) {
2308
+ mergedSteps[key] = value;
2309
+ }
2310
+ }
2311
+ const mergedMetadata = base.metadata || delta.metadata ? { ...base.metadata, ...delta.metadata } : void 0;
2312
+ const baseWarnings = (base.warnings || []).filter(
2313
+ (w) => !Object.prototype.hasOwnProperty.call(delta.steps, w.stepId)
2314
+ );
2315
+ const mergedWarnings = [...baseWarnings, ...delta.warnings || []];
2316
+ return {
2317
+ formatVersion: 1,
2318
+ steps: mergedSteps,
2319
+ execution: { ...delta.execution },
2320
+ metadata: mergedMetadata,
2321
+ warnings: mergedWarnings.length > 0 ? mergedWarnings : void 0
2322
+ };
2323
+ }
2324
+ var MAX_STRING_REPRESENTATION_LENGTH = 1e3;
2325
+ function serializeError(error) {
2326
+ const serialized = {
2327
+ type: "error",
2328
+ name: error.name,
2329
+ message: error.message
2330
+ };
2331
+ if (error.stack) {
2332
+ serialized.stack = error.stack;
2333
+ }
2334
+ const errorWithCause = error;
2335
+ if (errorWithCause.cause !== void 0) {
2336
+ if (errorWithCause.cause instanceof Error) {
2337
+ serialized.cause = serializeError(errorWithCause.cause);
2338
+ } else {
2339
+ serialized.cause = serializeThrown(errorWithCause.cause);
2340
+ }
2341
+ }
2342
+ return serialized;
2343
+ }
2344
+ function serializeThrown(value) {
2345
+ let stringRepresentation;
2346
+ let truncated = false;
2347
+ try {
2348
+ stringRepresentation = String(value);
2349
+ if (stringRepresentation.length > MAX_STRING_REPRESENTATION_LENGTH) {
2350
+ stringRepresentation = stringRepresentation.slice(0, MAX_STRING_REPRESENTATION_LENGTH);
2351
+ truncated = true;
2352
+ }
2353
+ } catch {
2354
+ stringRepresentation = "[unable to convert to string]";
2355
+ }
2356
+ const originalType = value === null ? "null" : typeof value === "object" ? value.constructor?.name ?? "Object" : typeof value;
2357
+ let jsonValue;
2358
+ try {
2359
+ const serialized = JSON.stringify(value);
2360
+ if (serialized !== void 0) {
2361
+ jsonValue = JSON.parse(serialized);
2362
+ }
2363
+ } catch {
2364
+ }
2365
+ const result = {
2366
+ type: "thrown",
2367
+ originalType,
2368
+ stringRepresentation
2369
+ };
2370
+ if (jsonValue !== void 0) {
2371
+ result.value = jsonValue;
2372
+ }
2373
+ if (truncated) {
2374
+ result.truncated = true;
2375
+ }
2376
+ return result;
2377
+ }
2378
+ function deserializeCauseNew(serialized) {
2379
+ if (serialized.type === "error") {
2380
+ const error = new Error(serialized.message);
2381
+ error.name = serialized.name;
2382
+ if (serialized.stack) {
2383
+ error.stack = serialized.stack;
2384
+ }
2385
+ if (serialized.cause) {
2386
+ error.cause = deserializeCauseNew(serialized.cause);
2387
+ }
2388
+ return error;
2389
+ }
2390
+ return serialized.value !== void 0 ? serialized.value : serialized.stringRepresentation;
2391
+ }
2392
+
2393
+ // src/workflow/cache-encoding.ts
2394
+ function isCachedErrorCause(cause) {
2395
+ return typeof cause === "object" && cause !== null && cause.__cachedMeta === true;
2396
+ }
2397
+ function encodeCachedError(error, meta, originalCause) {
2398
+ return err(error, {
2399
+ cause: { __cachedMeta: true, originalCause, meta }
2400
+ });
2401
+ }
2402
+ function decodeCachedMeta(cause) {
2403
+ if (isCachedErrorCause(cause)) {
2404
+ return cause.meta;
2405
+ }
2406
+ return { origin: "result", resultCause: cause };
2407
+ }
2408
+
2409
+ // src/workflow/resume-state.ts
2410
+ function createResumeStateCollector() {
2411
+ const steps = /* @__PURE__ */ new Map();
2412
+ return {
2413
+ handleEvent: (event) => {
2414
+ if (isStepComplete(event)) {
2415
+ steps.set(event.stepKey, { result: event.result, meta: event.meta });
2416
+ }
2417
+ },
2418
+ getResumeState: () => ({ steps: new Map(steps) }),
2419
+ clear: () => steps.clear()
2420
+ };
2421
+ }
2422
+
2423
+ // src/streaming/types.ts
2424
+ var STREAM_WRITE_ERROR = "STREAM_WRITE_ERROR";
2425
+ var STREAM_READ_ERROR = "STREAM_READ_ERROR";
2426
+ var STREAM_CLOSE_ERROR = "STREAM_CLOSE_ERROR";
2427
+ var STREAM_ENDED = "STREAM_ENDED";
2428
+ function streamWriteError(reason, message, cause) {
2429
+ return {
2430
+ type: STREAM_WRITE_ERROR,
2431
+ reason,
2432
+ message,
2433
+ ...cause !== void 0 ? { cause } : {}
2434
+ };
2435
+ }
2436
+ function streamReadError(reason, message, cause) {
2437
+ return {
2438
+ type: STREAM_READ_ERROR,
2439
+ reason,
2440
+ message,
2441
+ ...cause !== void 0 ? { cause } : {}
2442
+ };
2443
+ }
2444
+ function streamCloseError(reason, message, cause) {
2445
+ return {
2446
+ type: STREAM_CLOSE_ERROR,
2447
+ reason,
2448
+ message,
2449
+ ...cause !== void 0 ? { cause } : {}
2450
+ };
2451
+ }
2452
+ function streamEnded(finalPosition) {
2453
+ return {
2454
+ type: STREAM_ENDED,
2455
+ finalPosition
2456
+ };
2457
+ }
2458
+
2459
+ // src/streaming/backpressure.ts
2460
+ function createBackpressureController(options = {}) {
2461
+ const highWaterMark = options.highWaterMark ?? 16;
2462
+ const lowWaterMark = options.lowWaterMark ?? Math.floor(highWaterMark / 2);
2463
+ const onStateChange = options.onStateChange;
2464
+ let state = "flowing";
2465
+ let bufferedCount = 0;
2466
+ let drainResolvers = [];
2467
+ function updateState(newState) {
2468
+ if (state !== newState) {
2469
+ state = newState;
2470
+ onStateChange?.(newState);
2471
+ if (newState === "flowing" && drainResolvers.length > 0) {
2472
+ const resolvers = drainResolvers;
2473
+ drainResolvers = [];
2474
+ for (const resolve of resolvers) {
2475
+ resolve();
2476
+ }
2477
+ }
2478
+ }
2479
+ }
2480
+ function checkState() {
2481
+ if (state === "flowing" && bufferedCount >= highWaterMark) {
2482
+ updateState("paused");
2483
+ } else if (state === "paused" && bufferedCount <= lowWaterMark) {
2484
+ updateState("flowing");
2485
+ }
2486
+ }
2487
+ return {
2488
+ get state() {
2489
+ return state;
2490
+ },
2491
+ get bufferedCount() {
2492
+ return bufferedCount;
2493
+ },
2494
+ get highWaterMark() {
2495
+ return highWaterMark;
2496
+ },
2497
+ get lowWaterMark() {
2498
+ return lowWaterMark;
2499
+ },
2500
+ increment() {
2501
+ bufferedCount++;
2502
+ checkState();
2503
+ },
2504
+ decrement() {
2505
+ if (bufferedCount > 0) {
2506
+ bufferedCount--;
2507
+ checkState();
2508
+ }
2509
+ },
2510
+ setCount(count) {
2511
+ bufferedCount = Math.max(0, count);
2512
+ checkState();
2513
+ },
2514
+ waitForDrain() {
2515
+ if (state === "flowing") {
2516
+ return Promise.resolve();
2517
+ }
2518
+ return new Promise((resolve) => {
2519
+ drainResolvers.push(resolve);
2520
+ });
2521
+ },
2522
+ reset() {
2523
+ bufferedCount = 0;
2524
+ drainResolvers = [];
2525
+ updateState("flowing");
2526
+ }
2527
+ };
2528
+ }
2529
+
2530
+ // src/workflow/validation.ts
2531
+ async function validateInput(schema, input) {
2532
+ const result = schema["~standard"].validate(input);
2533
+ const resolved = result instanceof Promise ? await result : result;
2534
+ if (resolved.issues) {
2535
+ return err({
2536
+ type: "INPUT_VALIDATION_ERROR",
2537
+ issues: resolved.issues.map((i) => ({
2538
+ message: i.message,
2539
+ path: i.path?.map(
2540
+ (p) => typeof p === "object" ? p.key : p
2541
+ )
2542
+ })),
2543
+ message: `Input validation failed: ${resolved.issues.map((i) => i.message).join(", ")}`
2544
+ });
2545
+ }
2546
+ return ok2(resolved.value);
2547
+ }
2548
+
2549
+ // src/di.ts
2550
+ function withDeps(workflow, overrides) {
2551
+ const forward = (method) => ((...args) => {
2552
+ const last = args.at(-1);
2553
+ const hasConfig = args.length > 0 && typeof last === "object" && last !== null && !Array.isArray(last) && typeof last !== "function";
2554
+ const config = hasConfig ? last : void 0;
2555
+ const head = hasConfig ? args.slice(0, -1) : args;
2556
+ const mergedDeps = { ...overrides, ...config?.deps ?? {} };
2557
+ const mergedConfig = config ? { ...config, deps: mergedDeps } : { deps: mergedDeps };
2558
+ return workflow[method](...head, mergedConfig);
2559
+ });
2560
+ return {
2561
+ run: forward("run"),
2562
+ runWithState: forward("runWithState"),
2563
+ withDeps(nextOverrides) {
2564
+ return withDeps(workflow, { ...overrides, ...nextOverrides });
2565
+ }
2566
+ };
2567
+ }
2568
+
2569
+ // src/workflow/execute.ts
2570
+ function createWorkflow(workflowName, deps, options) {
2571
+ if (typeof workflowName !== "string" || workflowName.length === 0) {
2572
+ throw new TypeError(
2573
+ "createWorkflow(workflowName, deps, options?): first argument must be a non-empty string. Example: createWorkflow('checkout', { chargeCard, sendEmail })"
2574
+ );
2575
+ }
2576
+ const depsActual = deps ?? {};
2577
+ const optionsActual = options;
2578
+ async function internalExecute(runName, userFn, config) {
2579
+ const workflowId = runName ?? crypto.randomUUID();
2580
+ const effectiveDeps = config?.deps ? { ...depsActual, ...config.deps } : depsActual;
2581
+ const compensations = [];
2582
+ const createContextFn = config?.createContext ?? optionsActual?.createContext;
2583
+ const context = createContextFn ? await createContextFn() : void 0;
2584
+ const workflowSignal = config?.signal ?? optionsActual?.signal;
2585
+ const onEventHandler = config?.onEvent ?? optionsActual?.onEvent;
2586
+ const onErrorHandler = config?.onError ?? optionsActual?.onError;
2587
+ const shouldRunHook = config?.shouldRun ?? optionsActual?.shouldRun;
2588
+ const onBeforeStartHook = config?.onBeforeStart ?? optionsActual?.onBeforeStart;
2589
+ const onAfterStepHook = config?.onAfterStep ?? optionsActual?.onAfterStep;
2590
+ const resumeStateOption = config?.resumeState ?? optionsActual?.resumeState;
2591
+ const catchUnexpected = optionsActual?.catchUnexpected ?? defaultCatchUnexpected;
2592
+ const declaredGraph = config?.graph ?? optionsActual?.graph;
2593
+ const workflowData = {};
2594
+ const devWarnings = (config?.devWarnings ?? optionsActual?.devWarnings) === true && process.env.NODE_ENV !== "production";
2595
+ const ctxSetWarned = /* @__PURE__ */ new Set();
2596
+ const ctxGetWarned = /* @__PURE__ */ new Set();
2597
+ const workflowContext = {
2598
+ workflowId,
2599
+ onEvent: onEventHandler,
2600
+ context: context !== void 0 ? context : void 0,
2601
+ signal: workflowSignal,
2602
+ // Data store for static analysis
2603
+ input: {},
2604
+ ref: (key) => workflowData[key],
2605
+ set: (key, value) => {
2606
+ if (devWarnings && !ctxSetWarned.has(key)) {
2607
+ ctxSetWarned.add(key);
2608
+ console.warn(
2609
+ `awaitly: ctx.set('${key}', ...) is deprecated for static analysis. Use step('id', fn, { out: '${key}' }) instead.`
2610
+ );
2611
+ }
2612
+ workflowData[key] = value;
2613
+ },
2614
+ get: (key) => {
2615
+ if (devWarnings && !ctxGetWarned.has(key)) {
2616
+ ctxGetWarned.add(key);
2617
+ console.warn(
2618
+ `awaitly: ctx.get('${key}') is deprecated for static analysis. Use ctx.ref('${key}') instead for tracked dependencies.`
2619
+ );
2620
+ }
2621
+ return workflowData[key];
2622
+ }
2623
+ };
2624
+ const emitEvent = (event) => {
2625
+ const eventWithContext = event.context !== void 0 || context === void 0 ? event : { ...event, context };
2626
+ const eventWithName = eventWithContext.workflowName === void 0 ? { ...eventWithContext, workflowName } : eventWithContext;
2627
+ onEventHandler?.(eventWithName, context);
2628
+ };
2629
+ const createCancelledResult = (reason, lastStepKey2) => {
2630
+ const cancelledError = {
2631
+ type: "WORKFLOW_CANCELLED",
2632
+ reason,
2633
+ lastStepKey: lastStepKey2
2634
+ };
2635
+ return err(catchUnexpected(cancelledError), { cause: cancelledError });
2636
+ };
2637
+ if (workflowSignal?.aborted) {
2638
+ const reason = typeof workflowSignal.reason === "string" ? workflowSignal.reason : workflowSignal.reason instanceof Error ? workflowSignal.reason.message : void 0;
2639
+ emitEvent({
2640
+ type: "workflow_cancelled",
2641
+ workflowId,
2642
+ ts: Date.now(),
2643
+ durationMs: 0,
2644
+ reason
2645
+ });
2646
+ return createCancelledResult(reason);
2647
+ }
2648
+ if (shouldRunHook) {
2649
+ const hookStartTime = performance.now();
2650
+ try {
2651
+ const shouldRunResult = await shouldRunHook(workflowId, context);
2652
+ const hookDuration = performance.now() - hookStartTime;
2653
+ emitEvent({
2654
+ type: "hook_should_run",
2655
+ workflowId,
2656
+ ts: Date.now(),
2657
+ durationMs: hookDuration,
2658
+ result: shouldRunResult,
2659
+ skipped: !shouldRunResult
2660
+ });
2661
+ if (!shouldRunResult) {
2662
+ const skipCause = new Error("Workflow skipped by shouldRun hook");
2663
+ return err(catchUnexpected(skipCause), { cause: skipCause });
2664
+ }
2665
+ } catch (thrown) {
2666
+ const hookDuration = performance.now() - hookStartTime;
2667
+ emitEvent({
2668
+ type: "hook_should_run_error",
2669
+ workflowId,
2670
+ ts: Date.now(),
2671
+ durationMs: hookDuration,
2672
+ error: thrown
2673
+ });
2674
+ return err(catchUnexpected(thrown), { cause: thrown });
2675
+ }
2676
+ }
2677
+ if (onBeforeStartHook) {
2678
+ const hookStartTime = performance.now();
2679
+ try {
2680
+ const beforeStartResult = await onBeforeStartHook(workflowId, context);
2681
+ const hookDuration = performance.now() - hookStartTime;
2682
+ emitEvent({
2683
+ type: "hook_before_start",
2684
+ workflowId,
2685
+ ts: Date.now(),
2686
+ durationMs: hookDuration,
2687
+ result: beforeStartResult,
2688
+ skipped: !beforeStartResult
2689
+ });
2690
+ if (!beforeStartResult) {
2691
+ const skipCause = new Error("Workflow skipped by onBeforeStart hook");
2692
+ return err(catchUnexpected(skipCause), { cause: skipCause });
2693
+ }
2694
+ } catch (thrown) {
2695
+ const hookDuration = performance.now() - hookStartTime;
2696
+ emitEvent({
2697
+ type: "hook_before_start_error",
2698
+ workflowId,
2699
+ ts: Date.now(),
2700
+ durationMs: hookDuration,
2701
+ error: thrown
2702
+ });
2703
+ return err(catchUnexpected(thrown), { cause: thrown });
2704
+ }
2705
+ }
2706
+ const inputSchema = optionsActual?.inputSchema;
2707
+ const inputValue = optionsActual?.input;
2708
+ if (inputSchema) {
2709
+ const validationResult = await validateInput(inputSchema, inputValue);
2710
+ if (!validationResult.ok) {
2711
+ return err(validationResult.error);
2712
+ }
2713
+ workflowContext.input = validationResult.value;
2714
+ } else if (inputValue !== void 0) {
2715
+ workflowContext.input = inputValue;
2716
+ }
2717
+ const startTs = Date.now();
2718
+ const startTime = performance.now();
2719
+ emitEvent({
2720
+ type: "workflow_start",
2721
+ workflowId,
2722
+ ts: startTs
2723
+ });
2724
+ let cache = config?.cache ?? optionsActual?.cache;
2725
+ const streamStore = config?.streamStore ?? optionsActual?.streamStore;
2726
+ if (resumeStateOption && !cache) {
2727
+ cache = /* @__PURE__ */ new Map();
2728
+ }
2729
+ if (resumeStateOption && cache) {
2730
+ const resumeState = typeof resumeStateOption === "function" ? await resumeStateOption() : resumeStateOption;
2731
+ if (!(resumeState.steps instanceof Map)) {
2732
+ console.warn(
2733
+ `awaitly: resumeState.steps is not a Map (got ${typeof resumeState.steps}). This usually happens when state is serialized with JSON.stringify() directly.
2734
+ Use serializeResumeState() and deserializeResumeState() from 'awaitly/workflow' instead:
2735
+ import { serializeResumeState, deserializeResumeState } from 'awaitly/workflow';
2736
+ const json = JSON.stringify(serializeResumeState(state)); // Save this
2737
+ const restored = deserializeResumeState(JSON.parse(json)); // Load this`
2738
+ );
2739
+ if (typeof resumeState.steps === "object" && resumeState.steps !== null) {
2740
+ resumeState.steps = new Map(Object.entries(resumeState.steps));
2741
+ }
2742
+ }
2743
+ for (const [key, entry] of resumeState.steps) {
2744
+ const { result: result2, meta } = entry;
2745
+ if (result2.ok) {
2746
+ cache.set(key, result2);
2747
+ } else {
2748
+ const effectiveMeta = meta ?? { origin: "result", resultCause: result2.cause };
2749
+ cache.set(key, encodeCachedError(result2.error, effectiveMeta, result2.cause));
2750
+ }
2751
+ }
2752
+ }
2753
+ const snapshotOption = config?.snapshot ?? optionsActual?.snapshot;
2754
+ const snapshotSerialization = optionsActual?.serialization;
2755
+ if (snapshotOption && !resumeStateOption) {
2756
+ if (!cache) {
2757
+ cache = /* @__PURE__ */ new Map();
2758
+ }
2759
+ const snapshot = snapshotOption;
2760
+ const decode = snapshotSerialization?.decode;
2761
+ for (const [stepId, stepResult] of Object.entries(snapshot.steps)) {
2762
+ if (!Object.prototype.hasOwnProperty.call(snapshot.steps, stepId)) {
2763
+ continue;
2764
+ }
2765
+ try {
2766
+ if (stepResult.ok) {
2767
+ const value = decode ? decode(stepResult.value) : stepResult.value;
2768
+ cache.set(stepId, ok2(value));
2769
+ } else {
2770
+ const errorValue = decode ? decode(stepResult.error) : stepResult.error;
2771
+ const deserializedCause = deserializeCauseNew(stepResult.cause);
2772
+ const meta = stepResult.meta?.origin === "throw" ? { origin: "throw", thrown: deserializedCause } : { origin: "result", resultCause: deserializedCause };
2773
+ cache.set(stepId, encodeCachedError(errorValue, meta, deserializedCause));
2774
+ }
2775
+ } catch (e) {
2776
+ throw new SnapshotDecodeError(
2777
+ `Failed to decode step "${stepId}": ${e instanceof Error ? e.message : String(e)}`,
2778
+ stepId,
2779
+ e instanceof Error ? e : void 0
2780
+ );
2781
+ }
2782
+ }
2783
+ }
2784
+ let abortedDuringExecution = false;
2785
+ let abortReason;
2786
+ let lastStepKey;
2787
+ const abortHandler = () => {
2788
+ abortedDuringExecution = true;
2789
+ abortReason = typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0;
2790
+ };
2791
+ if (workflowSignal && !workflowSignal.aborted) {
2792
+ workflowSignal.addEventListener("abort", abortHandler, { once: true });
2793
+ }
2794
+ const checkCancellation = () => {
2795
+ if (abortedDuringExecution || workflowSignal?.aborted) {
2796
+ const reason = abortReason ?? (typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0);
2797
+ const cancelledError = {
2798
+ type: "WORKFLOW_CANCELLED",
2799
+ reason,
2800
+ lastStepKey
2801
+ };
2802
+ throw cancelledError;
2803
+ }
2804
+ };
2805
+ const callOnAfterStepHook = async (stepKey, result2, _meta) => {
2806
+ if (!onAfterStepHook) return;
2807
+ const hookStartTime = performance.now();
2808
+ try {
2809
+ await onAfterStepHook(stepKey, result2, workflowId, context);
2810
+ const hookDuration = performance.now() - hookStartTime;
2811
+ emitEvent({
2812
+ type: "hook_after_step",
2813
+ workflowId,
2814
+ stepKey,
2815
+ ts: Date.now(),
2816
+ durationMs: hookDuration
2817
+ });
2818
+ } catch (thrown) {
2819
+ const hookDuration = performance.now() - hookStartTime;
2820
+ emitEvent({
2821
+ type: "hook_after_step_error",
2822
+ workflowId,
2823
+ stepKey,
2824
+ ts: Date.now(),
2825
+ durationMs: hookDuration,
2826
+ error: thrown
2827
+ });
2828
+ throw thrown;
2829
+ }
2830
+ };
2831
+ const createCachedStep = (realStep) => {
2832
+ const cachedStepFn = async (idOrOperationOrResult, operationOrOptions, stepOptions) => {
2833
+ if (typeof idOrOperationOrResult !== "string") {
2834
+ throw new Error(
2835
+ '[awaitly] step() requires a string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))'
2836
+ );
2837
+ }
2838
+ const id = idOrOperationOrResult;
2839
+ const opts = stepOptions ?? {};
2840
+ const name = id;
2841
+ const key = Object.prototype.hasOwnProperty.call(opts, "key") ? opts.key : id;
2842
+ const { ttl, out } = opts;
2843
+ checkCancellation();
2844
+ const stepMetadata = extractStepMetadata(opts);
2845
+ if (key && cache && cache.has(key)) {
2846
+ emitEvent({
2847
+ type: "step_cache_hit",
2848
+ workflowId,
2849
+ stepKey: key,
2850
+ name,
2851
+ ts: Date.now(),
2852
+ ...stepMetadata && { metadata: stepMetadata }
2853
+ });
2854
+ const cached = cache.get(key);
2855
+ if (cached.ok) {
2856
+ lastStepKey = key;
2857
+ if (out) {
2858
+ workflowData[out] = cached.value;
2859
+ }
2860
+ return cached.value;
2861
+ }
2862
+ const meta = decodeCachedMeta(cached.cause);
2863
+ throw createEarlyExit(cached.error, meta);
2864
+ }
2865
+ if (key && cache) {
2866
+ emitEvent({
2867
+ type: "step_cache_miss",
2868
+ workflowId,
2869
+ stepKey: key,
2870
+ name,
2871
+ ts: Date.now(),
2872
+ ...stepMetadata && { metadata: stepMetadata }
2873
+ });
2874
+ }
2875
+ try {
2876
+ const value = await realStep(
2877
+ id,
2878
+ operationOrOptions,
2879
+ opts
2880
+ );
2881
+ if (out) {
2882
+ workflowData[out] = value;
2883
+ }
2884
+ if (opts.compensate) {
2885
+ compensations.push({
2886
+ stepName: name,
2887
+ value,
2888
+ compensate: opts.compensate
2889
+ });
2890
+ }
2891
+ if (key) {
2892
+ lastStepKey = key;
2893
+ if (cache) {
2894
+ cache.set(key, ok2(value), ttl ? { ttl } : void 0);
2895
+ }
2896
+ await callOnAfterStepHook(key, ok2(value));
2897
+ }
2898
+ return value;
2899
+ } catch (thrown) {
2900
+ if (key && isEarlyExit(thrown)) {
2901
+ const exit = thrown;
2902
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
2903
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
2904
+ if (cache) {
2905
+ cache.set(key, errorResult, ttl ? { ttl } : void 0);
2906
+ }
2907
+ await callOnAfterStepHook(key, errorResult, exit.meta);
2908
+ }
2909
+ throw thrown;
2910
+ }
2911
+ };
2912
+ cachedStepFn.try = async (id, operation, opts) => {
2913
+ const { ttl } = opts;
2914
+ const key = opts.key ?? id;
2915
+ const name = id;
2916
+ if (cache && cache.has(key)) {
2917
+ emitEvent({
2918
+ type: "step_cache_hit",
2919
+ workflowId,
2920
+ stepKey: key,
2921
+ name,
2922
+ ts: Date.now()
2923
+ });
2924
+ const cached = cache.get(key);
2925
+ if (cached.ok) {
2926
+ return cached.value;
2927
+ }
2928
+ const meta = decodeCachedMeta(cached.cause);
2929
+ throw createEarlyExit(cached.error, meta);
2930
+ }
2931
+ if (cache) {
2932
+ emitEvent({
2933
+ type: "step_cache_miss",
2934
+ workflowId,
2935
+ stepKey: key,
2936
+ name,
2937
+ ts: Date.now()
2938
+ });
2939
+ }
2940
+ try {
2941
+ const value = await realStep.try(id, operation, { ...opts, key });
2942
+ if (opts.compensate) {
2943
+ compensations.push({
2944
+ stepName: name,
2945
+ value,
2946
+ compensate: opts.compensate
2947
+ });
2948
+ }
2949
+ if (cache) {
2950
+ cache.set(key, ok2(value), ttl ? { ttl } : void 0);
2951
+ }
2952
+ await callOnAfterStepHook(key, ok2(value));
2953
+ return value;
2954
+ } catch (thrown) {
2955
+ if (isEarlyExit(thrown)) {
2956
+ const exit = thrown;
2957
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
2958
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
2959
+ if (cache) {
2960
+ cache.set(key, errorResult, ttl ? { ttl } : void 0);
2961
+ }
2962
+ await callOnAfterStepHook(key, errorResult, exit.meta);
2963
+ }
2964
+ throw thrown;
2965
+ }
2966
+ };
2967
+ cachedStepFn.fromResult = async (id, operation, opts) => {
2968
+ const { ttl } = opts;
2969
+ const key = opts.key ?? id;
2970
+ const name = id;
2971
+ if (cache && cache.has(key)) {
2972
+ emitEvent({
2973
+ type: "step_cache_hit",
2974
+ workflowId,
2975
+ stepKey: key,
2976
+ name,
2977
+ ts: Date.now()
2978
+ });
2979
+ const cached = cache.get(key);
2980
+ if (cached.ok) {
2981
+ return cached.value;
2982
+ }
2983
+ const meta = decodeCachedMeta(cached.cause);
2984
+ throw createEarlyExit(cached.error, meta);
2985
+ }
2986
+ if (cache) {
2987
+ emitEvent({
2988
+ type: "step_cache_miss",
2989
+ workflowId,
2990
+ stepKey: key,
2991
+ name,
2992
+ ts: Date.now()
2993
+ });
2994
+ }
2995
+ try {
2996
+ const value = await realStep.fromResult(id, operation, { ...opts, key });
2997
+ if (cache) {
2998
+ cache.set(key, ok2(value), ttl ? { ttl } : void 0);
2999
+ }
3000
+ await callOnAfterStepHook(key, ok2(value));
3001
+ return value;
3002
+ } catch (thrown) {
3003
+ if (isEarlyExit(thrown)) {
3004
+ const exit = thrown;
3005
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
3006
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
3007
+ if (cache) {
3008
+ cache.set(key, errorResult, ttl ? { ttl } : void 0);
3009
+ }
3010
+ await callOnAfterStepHook(key, errorResult, exit.meta);
3011
+ }
3012
+ throw thrown;
3013
+ }
3014
+ };
3015
+ cachedStepFn.race = realStep.race;
3016
+ cachedStepFn.withFallback = async (id, operation, options2) => {
3017
+ const key = options2.key ?? id;
3018
+ const name = id;
3019
+ if (cache && cache.has(key)) {
3020
+ emitEvent({
3021
+ type: "step_cache_hit",
3022
+ workflowId,
3023
+ stepKey: key,
3024
+ name,
3025
+ ts: Date.now()
3026
+ });
3027
+ const cached = cache.get(key);
3028
+ if (cached.ok) {
3029
+ return cached.value;
3030
+ }
3031
+ const meta = decodeCachedMeta(cached.cause);
3032
+ throw createEarlyExit(cached.error, meta);
3033
+ }
3034
+ if (cache) {
3035
+ emitEvent({
3036
+ type: "step_cache_miss",
3037
+ workflowId,
3038
+ stepKey: key,
3039
+ name,
3040
+ ts: Date.now()
3041
+ });
3042
+ }
3043
+ try {
3044
+ const value = await realStep.withFallback(
3045
+ id,
3046
+ operation,
3047
+ options2
3048
+ );
3049
+ if (cache) {
3050
+ cache.set(key, ok2(value));
3051
+ }
3052
+ await callOnAfterStepHook(key, ok2(value));
3053
+ return value;
3054
+ } catch (thrown) {
3055
+ if (isEarlyExit(thrown)) {
3056
+ const exit = thrown;
3057
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
3058
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
3059
+ if (cache) {
3060
+ cache.set(key, errorResult);
3061
+ }
3062
+ await callOnAfterStepHook(key, errorResult, exit.meta);
3063
+ }
3064
+ throw thrown;
3065
+ }
3066
+ };
3067
+ cachedStepFn.withResource = async (id, options2) => {
3068
+ const key = id;
3069
+ try {
3070
+ const value = await realStep.withResource(id, options2);
3071
+ await callOnAfterStepHook(key, ok2(value));
3072
+ return value;
3073
+ } catch (thrown) {
3074
+ if (isEarlyExit(thrown)) {
3075
+ const exit = thrown;
3076
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
3077
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
3078
+ await callOnAfterStepHook(key, errorResult, exit.meta);
3079
+ }
3080
+ throw thrown;
3081
+ }
3082
+ };
3083
+ cachedStepFn.retry = (id, operation, options2) => {
3084
+ const stepOptions = {
3085
+ key: options2.key,
3086
+ // explicitly pass so undefined = don't cache
3087
+ retry: {
3088
+ attempts: options2.attempts,
3089
+ backoff: options2.backoff,
3090
+ initialDelay: options2.initialDelay,
3091
+ maxDelay: options2.maxDelay,
3092
+ jitter: options2.jitter,
3093
+ shouldRetry: options2.shouldRetry,
3094
+ onRetry: options2.onRetry
3095
+ },
3096
+ timeout: options2.timeout,
3097
+ ttl: options2.ttl
3098
+ };
3099
+ return cachedStepFn(id, operation, stepOptions);
3100
+ };
3101
+ cachedStepFn.withTimeout = (id, operation, options2) => {
3102
+ const stepOptions = {
3103
+ key: options2.key,
3104
+ timeout: options2,
3105
+ ttl: options2.ttl
3106
+ };
3107
+ return cachedStepFn(
3108
+ id,
3109
+ operation,
3110
+ stepOptions
3111
+ );
3112
+ };
3113
+ cachedStepFn.sleep = (id, duration, options2) => {
3114
+ if (typeof id !== "string" || id.length === 0) {
3115
+ throw new Error(
3116
+ '[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")'
3117
+ );
3118
+ }
3119
+ const d = typeof duration === "string" ? parse(duration) : duration;
3120
+ if (!d) {
3121
+ throw new Error(`step.sleep: invalid duration '${duration}'`);
3122
+ }
3123
+ const ms = toMillis(d);
3124
+ const userSignal = options2?.signal;
3125
+ const sleepOperation = async () => {
3126
+ if (workflowSignal?.aborted || userSignal?.aborted) {
3127
+ const e = new Error("Sleep aborted");
3128
+ e.name = "AbortError";
3129
+ throw e;
3130
+ }
3131
+ return new Promise((resolve, reject) => {
3132
+ const state = {
3133
+ timeoutId: void 0
3134
+ };
3135
+ const onAbort = () => {
3136
+ if (state.timeoutId) clearTimeout(state.timeoutId);
3137
+ const e = new Error("Sleep aborted");
3138
+ e.name = "AbortError";
3139
+ reject(e);
3140
+ };
3141
+ workflowSignal?.addEventListener("abort", onAbort, { once: true });
3142
+ userSignal?.addEventListener("abort", onAbort, { once: true });
3143
+ state.timeoutId = setTimeout(() => {
3144
+ workflowSignal?.removeEventListener("abort", onAbort);
3145
+ userSignal?.removeEventListener("abort", onAbort);
3146
+ resolve(ok2(void 0));
3147
+ }, ms);
3148
+ });
3149
+ };
3150
+ return cachedStepFn(id, sleepOperation, {
3151
+ key: options2?.key,
3152
+ ttl: options2?.ttl,
3153
+ description: options2?.description
3154
+ });
3155
+ };
3156
+ const activeWriters = /* @__PURE__ */ new Map();
3157
+ const activeReaders = /* @__PURE__ */ new Map();
3158
+ cachedStepFn.getWritable = (options2) => {
3159
+ const namespace = options2?.namespace ?? "default";
3160
+ const highWaterMark = options2?.highWaterMark ?? 16;
3161
+ if (!streamStore) {
3162
+ throw new Error(
3163
+ "streamStore is required to use getWritable(). Pass a streamStore to createWorkflow options."
3164
+ );
3165
+ }
3166
+ const existingKey = `${workflowId}:${namespace}`;
3167
+ const existing = activeWriters.get(existingKey);
3168
+ if (existing && !existing.closed && !existing.aborted) {
3169
+ return existing.writer;
3170
+ }
3171
+ const backpressure = createBackpressureController({
3172
+ highWaterMark,
3173
+ onStateChange: (state) => {
3174
+ emitEvent({
3175
+ type: "stream_backpressure",
3176
+ workflowId,
3177
+ namespace,
3178
+ bufferedCount: backpressure.bufferedCount,
3179
+ state,
3180
+ ts: Date.now()
3181
+ });
3182
+ }
3183
+ });
3184
+ let position = 0;
3185
+ let writable = true;
3186
+ let aborted = false;
3187
+ let closed = false;
3188
+ emitEvent({
3189
+ type: "stream_created",
3190
+ workflowId,
3191
+ namespace,
3192
+ ts: Date.now()
3193
+ });
3194
+ const writer = {
3195
+ async write(value) {
3196
+ if (closed) {
3197
+ return err(streamWriteError("closed", "Stream is closed"));
3198
+ }
3199
+ if (aborted) {
3200
+ return err(streamWriteError("aborted", "Stream was aborted"));
3201
+ }
3202
+ if (backpressure.state === "paused") {
3203
+ await backpressure.waitForDrain();
3204
+ }
3205
+ const item = {
3206
+ value,
3207
+ position,
3208
+ ts: Date.now()
3209
+ };
3210
+ const result2 = await streamStore.append(workflowId, namespace, item);
3211
+ if (!result2.ok) {
3212
+ emitEvent({
3213
+ type: "stream_error",
3214
+ workflowId,
3215
+ namespace,
3216
+ error: result2.error,
3217
+ position,
3218
+ ts: Date.now()
3219
+ });
3220
+ return err(streamWriteError("store_error", result2.error.message, result2.error));
3221
+ }
3222
+ emitEvent({
3223
+ type: "stream_write",
3224
+ workflowId,
3225
+ namespace,
3226
+ position,
3227
+ ts: Date.now()
3228
+ });
3229
+ position++;
3230
+ backpressure.increment();
3231
+ return ok2(void 0);
3232
+ },
3233
+ async close() {
3234
+ if (closed) {
3235
+ return err(streamCloseError("already_closed", "Stream is already closed"));
3236
+ }
3237
+ const result2 = await streamStore.closeStream(workflowId, namespace);
3238
+ if (!result2.ok) {
3239
+ return err(streamCloseError("store_error", result2.error.message, result2.error));
3240
+ }
3241
+ closed = true;
3242
+ writable = false;
3243
+ emitEvent({
3244
+ type: "stream_close",
3245
+ workflowId,
3246
+ namespace,
3247
+ finalPosition: position,
3248
+ ts: Date.now()
3249
+ });
3250
+ activeWriters.delete(existingKey);
3251
+ return ok2(void 0);
3252
+ },
3253
+ abort(reason) {
3254
+ aborted = true;
3255
+ writable = false;
3256
+ closed = true;
3257
+ emitEvent({
3258
+ type: "stream_error",
3259
+ workflowId,
3260
+ namespace,
3261
+ error: reason,
3262
+ position,
3263
+ ts: Date.now()
3264
+ });
3265
+ activeWriters.delete(existingKey);
3266
+ },
3267
+ get writable() {
3268
+ return writable;
3269
+ },
3270
+ get position() {
3271
+ return position;
3272
+ },
3273
+ get namespace() {
3274
+ return namespace;
3275
+ }
3276
+ };
3277
+ activeWriters.set(existingKey, {
3278
+ writer,
3279
+ backpressure,
3280
+ aborted,
3281
+ closed
3282
+ });
3283
+ return writer;
3284
+ };
3285
+ cachedStepFn.getReadable = (options2) => {
3286
+ const namespace = options2?.namespace ?? "default";
3287
+ const startIndex = options2?.startIndex ?? 0;
3288
+ const pollInterval = options2?.pollInterval ?? 10;
3289
+ const pollTimeout = options2?.pollTimeout ?? 3e4;
3290
+ if (!streamStore) {
3291
+ throw new Error(
3292
+ "streamStore is required to use getReadable(). Pass a streamStore to createWorkflow options."
3293
+ );
3294
+ }
3295
+ const existingKey = `${workflowId}:${namespace}:${startIndex}`;
3296
+ const existing = activeReaders.get(existingKey);
3297
+ if (existing && !existing.closed) {
3298
+ return existing.reader;
3299
+ }
3300
+ const decrementBackpressure = () => {
3301
+ const writerKey = `${workflowId}:${namespace}`;
3302
+ const activeWriter = activeWriters.get(writerKey);
3303
+ if (activeWriter) {
3304
+ activeWriter.backpressure.decrement();
3305
+ }
3306
+ };
3307
+ let position = startIndex;
3308
+ let readable = true;
3309
+ let closed = false;
3310
+ let bufferedItems = [];
3311
+ let bufferIndex = 0;
3312
+ const reader = {
3313
+ async read() {
3314
+ if (closed) {
3315
+ return err(streamReadError("closed", "Reader is closed"));
3316
+ }
3317
+ if (bufferIndex < bufferedItems.length) {
3318
+ const item = bufferedItems[bufferIndex++];
3319
+ position = item.position + 1;
3320
+ decrementBackpressure();
3321
+ emitEvent({
3322
+ type: "stream_read",
3323
+ workflowId,
3324
+ namespace,
3325
+ position: item.position,
3326
+ ts: Date.now()
3327
+ });
3328
+ return ok2(item.value);
3329
+ }
3330
+ const writerKey = `${workflowId}:${namespace}`;
3331
+ const pollStart = Date.now();
3332
+ let hasSeenWriter = activeWriters.has(writerKey);
3333
+ const initialMetaResult = await streamStore.getMetadata(workflowId, namespace);
3334
+ let hasSeenMetadata = initialMetaResult.ok && initialMetaResult.value !== void 0;
3335
+ while (Date.now() - pollStart < pollTimeout) {
3336
+ const result2 = await streamStore.read(workflowId, namespace, position, 100);
3337
+ if (!result2.ok) {
3338
+ return err(streamReadError("store_error", result2.error.message, result2.error));
3339
+ }
3340
+ const items = result2.value;
3341
+ if (items.length > 0) {
3342
+ bufferedItems = items;
3343
+ bufferIndex = 1;
3344
+ const item = items[0];
3345
+ position = item.position + 1;
3346
+ decrementBackpressure();
3347
+ emitEvent({
3348
+ type: "stream_read",
3349
+ workflowId,
3350
+ namespace,
3351
+ position: item.position,
3352
+ ts: Date.now()
3353
+ });
3354
+ return ok2(item.value);
3355
+ }
3356
+ const writerActive = activeWriters.has(writerKey);
3357
+ const metaResult = await streamStore.getMetadata(workflowId, namespace);
3358
+ const metadataExists = metaResult.ok && metaResult.value !== void 0;
3359
+ if (writerActive) hasSeenWriter = true;
3360
+ if (metadataExists) hasSeenMetadata = true;
3361
+ if (metaResult.ok && metaResult.value?.closed) {
3362
+ readable = false;
3363
+ return err(streamEnded(position));
3364
+ }
3365
+ if (hasSeenWriter && !writerActive && !metadataExists) {
3366
+ readable = false;
3367
+ return err(streamEnded(position));
3368
+ }
3369
+ if (hasSeenMetadata && !writerActive && metaResult.ok && !metaResult.value?.closed) {
3370
+ }
3371
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
3372
+ }
3373
+ readable = false;
3374
+ return err(streamEnded(position));
3375
+ },
3376
+ close() {
3377
+ closed = true;
3378
+ readable = false;
3379
+ bufferedItems = [];
3380
+ activeReaders.delete(existingKey);
3381
+ },
3382
+ get readable() {
3383
+ return readable;
3384
+ },
3385
+ get position() {
3386
+ return position;
3387
+ },
3388
+ get namespace() {
3389
+ return namespace;
3390
+ }
3391
+ };
3392
+ activeReaders.set(existingKey, {
3393
+ reader,
3394
+ position,
3395
+ closed
3396
+ });
3397
+ return reader;
3398
+ };
3399
+ cachedStepFn.streamForEach = async (source, processor, options2) => {
3400
+ const checkpointInterval = options2?.checkpointInterval ?? 1;
3401
+ const concurrency = options2?.concurrency ?? 1;
3402
+ const results = [];
3403
+ let processedCount = 0;
3404
+ let lastPosition = -1;
3405
+ const isStreamReader = (s) => {
3406
+ return typeof s === "object" && s !== null && "read" in s && typeof s.read === "function";
3407
+ };
3408
+ const processItem = async (item, itemIndex, itemPosition, namespace) => {
3409
+ const shouldCheckpoint = checkpointInterval > 0 && itemIndex % checkpointInterval === 0;
3410
+ const stepKey = shouldCheckpoint ? `stream-foreach:${namespace}:pos-${itemPosition}` : void 0;
3411
+ const stepId = stepKey ?? `stream-item-${itemPosition}`;
3412
+ const stepResult = await cachedStepFn(
3413
+ stepId,
3414
+ () => processor(item, itemIndex),
3415
+ { key: stepKey }
3416
+ );
3417
+ return { index: itemIndex, position: itemPosition, result: stepResult };
3418
+ };
3419
+ if (isStreamReader(source)) {
3420
+ if (concurrency <= 1) {
3421
+ let itemPosition = source.position;
3422
+ let readResult = await source.read();
3423
+ while (readResult.ok) {
3424
+ const item = readResult.value;
3425
+ const { result: result2 } = await processItem(item, processedCount, itemPosition, source.namespace);
3426
+ results.push(result2);
3427
+ lastPosition = itemPosition;
3428
+ processedCount++;
3429
+ itemPosition = source.position;
3430
+ readResult = await source.read();
3431
+ }
3432
+ } else {
3433
+ const resultsMap = /* @__PURE__ */ new Map();
3434
+ let itemIndex = 0;
3435
+ let totalItems = 0;
3436
+ const slots = new Array(concurrency).fill(null);
3437
+ const getSlot = async () => {
3438
+ for (let i = 0; i < slots.length; i++) {
3439
+ if (slots[i] === null) return i;
3440
+ }
3441
+ const activePromises = slots.filter((s) => s !== null);
3442
+ const completed = await Promise.race(activePromises);
3443
+ resultsMap.set(completed.index, { position: completed.position, result: completed.result });
3444
+ slots[completed.slotIndex] = null;
3445
+ return completed.slotIndex;
3446
+ };
3447
+ let itemPosition = source.position;
3448
+ let readResult = await source.read();
3449
+ while (readResult.ok) {
3450
+ const slotIndex = await getSlot();
3451
+ const currentIndex = itemIndex;
3452
+ const currentPosition = itemPosition;
3453
+ const currentItem = readResult.value;
3454
+ const currentSlot = slotIndex;
3455
+ slots[slotIndex] = processItem(currentItem, currentIndex, currentPosition, source.namespace).then((r) => ({ slotIndex: currentSlot, ...r }));
3456
+ totalItems++;
3457
+ itemIndex++;
3458
+ itemPosition = source.position;
3459
+ readResult = await source.read();
3460
+ }
3461
+ for (let i = 0; i < slots.length; i++) {
3462
+ if (slots[i] !== null) {
3463
+ const result2 = await slots[i];
3464
+ resultsMap.set(result2.index, { position: result2.position, result: result2.result });
3465
+ }
3466
+ }
3467
+ for (let i = 0; i < totalItems; i++) {
3468
+ const entry = resultsMap.get(i);
3469
+ if (entry) {
3470
+ results.push(entry.result);
3471
+ lastPosition = entry.position;
3472
+ processedCount++;
3473
+ }
3474
+ }
3475
+ }
3476
+ } else {
3477
+ if (concurrency <= 1) {
3478
+ let index = 0;
3479
+ for await (const item of source) {
3480
+ const { result: result2 } = await processItem(item, index, index, "async-iterable");
3481
+ results.push(result2);
3482
+ lastPosition = index;
3483
+ processedCount++;
3484
+ index++;
3485
+ }
3486
+ } else {
3487
+ const resultsMap = /* @__PURE__ */ new Map();
3488
+ let itemIndex = 0;
3489
+ let totalItems = 0;
3490
+ const slots = new Array(concurrency).fill(null);
3491
+ const getSlot = async () => {
3492
+ for (let i = 0; i < slots.length; i++) {
3493
+ if (slots[i] === null) return i;
3494
+ }
3495
+ const activePromises = slots.filter((s) => s !== null);
3496
+ const completed = await Promise.race(activePromises);
3497
+ resultsMap.set(completed.index, completed.result);
3498
+ slots[completed.slotIndex] = null;
3499
+ return completed.slotIndex;
3500
+ };
3501
+ for await (const item of source) {
3502
+ const slotIndex = await getSlot();
3503
+ const currentIndex = itemIndex;
3504
+ const currentSlot = slotIndex;
3505
+ slots[slotIndex] = processItem(item, currentIndex, currentIndex, "async-iterable").then((r) => ({ slotIndex: currentSlot, ...r }));
3506
+ totalItems++;
3507
+ itemIndex++;
3508
+ }
3509
+ for (let i = 0; i < slots.length; i++) {
3510
+ if (slots[i] !== null) {
3511
+ const result2 = await slots[i];
3512
+ resultsMap.set(result2.index, result2.result);
3513
+ }
3514
+ }
3515
+ for (let i = 0; i < totalItems; i++) {
3516
+ if (resultsMap.has(i)) {
3517
+ results.push(resultsMap.get(i));
3518
+ lastPosition = i;
3519
+ processedCount++;
3520
+ }
3521
+ }
3522
+ }
3523
+ }
3524
+ return {
3525
+ results,
3526
+ processedCount,
3527
+ lastPosition
3528
+ };
3529
+ };
3530
+ cachedStepFn.if = realStep.if;
3531
+ cachedStepFn.label = realStep.label;
3532
+ cachedStepFn.branch = realStep.branch;
3533
+ cachedStepFn.arm = realStep.arm;
3534
+ cachedStepFn.forEach = realStep.forEach;
3535
+ cachedStepFn.item = realStep.item;
3536
+ cachedStepFn.dep = realStep.dep;
3537
+ cachedStepFn.workflow = (id, getter, options2) => cachedStepFn(id, getter, options2);
3538
+ cachedStepFn.all = (id, shape, options2) => {
3539
+ const opts = options2 !== void 0 && Object.prototype.hasOwnProperty.call(options2, "key") ? options2 : { ...options2, key: void 0 };
3540
+ return cachedStepFn(id, async () => ok2(await realStep.all(id, shape)), opts);
3541
+ };
3542
+ cachedStepFn.map = (id, items, mapper, options2) => {
3543
+ const opts = options2 !== void 0 && Object.prototype.hasOwnProperty.call(options2, "key") ? options2 : { ...options2, key: void 0 };
3544
+ return cachedStepFn(id, async () => ok2(await realStep.map(id, items, mapper, options2)), opts);
3545
+ };
3546
+ return cachedStepFn;
3547
+ };
3548
+ const wrappedFn = ({ step }) => {
3549
+ const cachedStep = createCachedStep(step);
3550
+ return userFn({
3551
+ step: cachedStep,
3552
+ steps: bindSteps(effectiveDeps ?? {}, cachedStep),
3553
+ deps: effectiveDeps,
3554
+ ctx: workflowContext
3555
+ });
3556
+ };
3557
+ let result;
3558
+ try {
3559
+ result = await run(wrappedFn, {
3560
+ onError: onErrorHandler,
3561
+ onEvent: onEventHandler,
3562
+ catchUnexpected,
3563
+ workflowId,
3564
+ workflowName,
3565
+ context,
3566
+ graph: declaredGraph,
3567
+ _workflowSignal: workflowSignal
3568
+ });
3569
+ } finally {
3570
+ if (workflowSignal) {
3571
+ workflowSignal.removeEventListener("abort", abortHandler);
3572
+ }
3573
+ }
3574
+ if (!result.ok && compensations.length > 0) {
3575
+ const compensationErrors = [];
3576
+ for (let i = compensations.length - 1; i >= 0; i--) {
3577
+ const comp = compensations[i];
3578
+ try {
3579
+ await comp.compensate(comp.value);
3580
+ } catch (compErr) {
3581
+ compensationErrors.push({ stepName: comp.stepName, error: compErr });
3582
+ }
3583
+ }
3584
+ if (compensationErrors.length > 0) {
3585
+ const sagaError = {
3586
+ type: "SAGA_COMPENSATION_ERROR",
3587
+ originalError: result.error,
3588
+ compensationErrors
3589
+ };
3590
+ result = err(sagaError, { cause: result.cause });
3591
+ }
3592
+ }
3593
+ const durationMs = performance.now() - startTime;
3594
+ if (!result.ok) {
3595
+ let cancelledError;
3596
+ if (isWorkflowCancelled(result.cause)) {
3597
+ cancelledError = result.cause;
3598
+ }
3599
+ if (!cancelledError && abortedDuringExecution && isUnexpectedError(result.error)) {
3600
+ const thrown = result.cause;
3601
+ const isAbortError = thrown != null && typeof thrown === "object" && "name" in thrown && thrown.name === "AbortError";
3602
+ if (isAbortError) {
3603
+ const reason = abortReason ?? (typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0);
3604
+ cancelledError = {
3605
+ type: "WORKFLOW_CANCELLED",
3606
+ reason,
3607
+ lastStepKey
3608
+ };
3609
+ }
3610
+ }
3611
+ if (cancelledError) {
3612
+ emitEvent({
3613
+ type: "workflow_cancelled",
3614
+ workflowId,
3615
+ ts: Date.now(),
3616
+ durationMs,
3617
+ reason: cancelledError.reason,
3618
+ lastStepKey: cancelledError.lastStepKey
3619
+ });
3620
+ if (cancelledError && !isWorkflowCancelled(result.cause)) {
3621
+ return err(result.error, { cause: cancelledError });
3622
+ }
3623
+ return result;
3624
+ }
3625
+ }
3626
+ if (result.ok && abortedDuringExecution) {
3627
+ const reason = abortReason ?? (typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0);
3628
+ emitEvent({
3629
+ type: "workflow_cancelled",
3630
+ workflowId,
3631
+ ts: Date.now(),
3632
+ durationMs,
3633
+ reason,
3634
+ lastStepKey
3635
+ });
3636
+ const cancelledError = {
3637
+ type: "WORKFLOW_CANCELLED",
3638
+ reason,
3639
+ lastStepKey
3640
+ };
3641
+ return err(catchUnexpected(cancelledError), { cause: cancelledError });
3642
+ }
3643
+ if (result.ok) {
3644
+ emitEvent({
3645
+ type: "workflow_success",
3646
+ workflowId,
3647
+ ts: Date.now(),
3648
+ durationMs
3649
+ });
3650
+ } else {
3651
+ emitEvent({
3652
+ type: "workflow_error",
3653
+ workflowId,
3654
+ ts: Date.now(),
3655
+ durationMs,
3656
+ error: result.error
3657
+ });
3658
+ }
3659
+ return result;
3660
+ }
3661
+ function runMethod(fnOrName, maybeFnOrConfig, maybeConfig) {
3662
+ let runName;
3663
+ let fn;
3664
+ let config;
3665
+ if (typeof fnOrName === "string") {
3666
+ runName = fnOrName;
3667
+ fn = maybeFnOrConfig;
3668
+ config = maybeConfig;
3669
+ } else {
3670
+ fn = fnOrName;
3671
+ config = maybeFnOrConfig;
3672
+ }
3673
+ return internalExecute(runName, fn, config);
3674
+ }
3675
+ async function runWithStateMethod(fnOrName, maybeFnOrConfig, maybeConfig) {
3676
+ let runName;
3677
+ let fn;
3678
+ let config;
3679
+ if (typeof fnOrName === "string") {
3680
+ runName = fnOrName;
3681
+ fn = maybeFnOrConfig;
3682
+ config = maybeConfig;
3683
+ } else {
3684
+ fn = fnOrName;
3685
+ config = maybeFnOrConfig;
3686
+ }
3687
+ const collector = createResumeStateCollector();
3688
+ const userOnEvent = config?.onEvent;
3689
+ const mergedOnEvent = (event, ctx) => {
3690
+ collector.handleEvent(event);
3691
+ try {
3692
+ userOnEvent?.(event, ctx);
3693
+ } catch {
3694
+ }
3695
+ };
3696
+ const mergedConfig = {
3697
+ ...config,
3698
+ onEvent: mergedOnEvent
3699
+ };
3700
+ let result;
3701
+ let resumeState;
3702
+ try {
3703
+ result = await internalExecute(runName, fn, mergedConfig);
3704
+ } catch (thrown) {
3705
+ const catchUnexpected = optionsActual?.catchUnexpected ?? defaultCatchUnexpected;
3706
+ result = err(catchUnexpected(thrown), { cause: thrown });
3707
+ } finally {
3708
+ resumeState = collector.getResumeState();
3709
+ }
3710
+ return { result, resumeState };
3711
+ }
3712
+ const workflow = {
3713
+ withDeps: (overrides) => withDeps(workflow, overrides),
3714
+ run: runMethod,
3715
+ runWithState: runWithStateMethod
3716
+ };
3717
+ return workflow;
3718
+ }
3719
+
3720
+ // src/durable/index.ts
3721
+ var defaultStore;
3722
+ function createMemorySnapshotStore() {
3723
+ const store = /* @__PURE__ */ new Map();
3724
+ return {
3725
+ async save(id, snapshot) {
3726
+ store.set(id, { snapshot, updatedAt: /* @__PURE__ */ new Date() });
3727
+ },
3728
+ async load(id) {
3729
+ const entry = store.get(id);
3730
+ return entry?.snapshot ?? null;
3731
+ },
3732
+ async delete(id) {
3733
+ store.delete(id);
3734
+ },
3735
+ async list(options) {
3736
+ const prefix = options?.prefix ?? "";
3737
+ const limit = options?.limit ?? 100;
3738
+ const results = [];
3739
+ for (const [id, entry] of store.entries()) {
3740
+ if (prefix && !id.startsWith(prefix)) continue;
3741
+ results.push({ id, updatedAt: entry.updatedAt.toISOString() });
3742
+ if (results.length >= limit) break;
3743
+ }
3744
+ results.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
3745
+ return results;
3746
+ },
3747
+ async close() {
3748
+ }
3749
+ };
3750
+ }
3751
+ function getDefaultStore() {
3752
+ if (defaultStore === void 0) {
3753
+ defaultStore = createMemorySnapshotStore();
3754
+ }
3755
+ return defaultStore;
3756
+ }
3757
+ function hasWorkflowLock(store) {
3758
+ return typeof store.tryAcquire === "function" && typeof store.release === "function";
3759
+ }
3760
+ var activeWorkflows = /* @__PURE__ */ new Set();
3761
+ var pendingIdempotencyRuns = /* @__PURE__ */ new Map();
3762
+ var durable = {
3763
+ /**
3764
+ * Execute a workflow with automatic state persistence.
3765
+ *
3766
+ * Features:
3767
+ * - **Automatic checkpointing**: State is saved after each keyed step
3768
+ * - **Crash recovery**: Resume from the last completed step on restart
3769
+ * - **Version checking**: Reject resume if workflow logic version changed
3770
+ * - **Concurrency control**: Prevent duplicate executions of the same workflow ID
3771
+ * - **Cancellation support**: Integrates with AbortSignal for graceful shutdown
3772
+ *
3773
+ * ## How It Works
3774
+ *
3775
+ * 1. On start: Load existing state from store (if any)
3776
+ * 2. Check version compatibility (reject if mismatch)
3777
+ * 3. Pre-populate cache from loaded state (skip completed steps)
3778
+ * 4. Execute workflow, persisting state after each keyed step
3779
+ * 5. On completion: Delete stored state (clean up)
3780
+ * 6. On error/cancellation: State remains for future resume
3781
+ *
3782
+ * ## Important Notes
3783
+ *
3784
+ * - **Only keyed steps are durable**: Use `{ key: 'step-name' }` option
3785
+ * - **Steps should be idempotent**: They may be retried on resume
3786
+ * - **Serialization**: State is JSON-serialized; complex objects may lose fidelity
3787
+ *
3788
+ * @param deps - Workflow dependencies (Result-returning functions)
3789
+ * @param fn - Workflow function receiving ({ step, deps, ctx })
3790
+ * @param options - Durable execution options
3791
+ * @returns AsyncResult with workflow result or error
3792
+ *
3793
+ * @example
3794
+ * ```typescript
3795
+ * import { durable } from 'awaitly/durable';
3796
+ *
3797
+ * // Zero-config: uses in-memory store (per process)
3798
+ * const result = await durable.run(
3799
+ * { fetchUser, createOrder, sendEmail },
3800
+ * async ({ step, deps: { fetchUser, createOrder, sendEmail } }) => {
3801
+ * const user = await step(() => fetchUser('123'), { key: 'fetch-user' });
3802
+ * const order = await step(() => createOrder(user), { key: 'create-order' });
3803
+ * await step(() => sendEmail(order), { key: 'send-email' });
3804
+ * return order;
3805
+ * },
3806
+ * { id: 'checkout-123' }
3807
+ * );
3808
+ *
3809
+ * // Persistence across restarts: pass a store adapter
3810
+ * import { postgres } from 'awaitly-postgres'; // or awaitly-mongo, awaitly-libsql
3811
+ * const store = postgres(process.env.DATABASE_URL);
3812
+ * await durable.run(deps, fn, { id: 'checkout-123', store });
3813
+ *
3814
+ * if (result.ok) {
3815
+ * console.log('Order completed:', result.value);
3816
+ * } else if (isWorkflowCancelled(result.error)) {
3817
+ * console.log('Workflow cancelled at:', result.error.lastStepKey);
3818
+ * }
3819
+ * ```
3820
+ */
3821
+ async run(deps, fn, options) {
3822
+ const {
3823
+ id,
3824
+ store: storeOption,
3825
+ version = 1,
3826
+ allowConcurrent = false,
3827
+ lockTtlMs = 6e4,
3828
+ heartbeatIntervalMs,
3829
+ abortOnLeaseLoss,
3830
+ metadata,
3831
+ signal,
3832
+ createContext,
3833
+ onEvent,
3834
+ onError,
3835
+ onVersionMismatch,
3836
+ idempotencyKey,
3837
+ input
3838
+ } = options;
3839
+ const effectiveStore = storeOption ?? getDefaultStore();
3840
+ let resolveIdempotencyRun;
3841
+ if (idempotencyKey) {
3842
+ const idemId = `idem:${idempotencyKey}`;
3843
+ const pending = pendingIdempotencyRuns.get(idemId);
3844
+ if (pending) {
3845
+ return await pending;
3846
+ }
3847
+ pendingIdempotencyRuns.set(idemId, new Promise((r) => {
3848
+ resolveIdempotencyRun = r;
3849
+ }));
3850
+ try {
3851
+ const idemSnapshot = await effectiveStore.load(idemId);
3852
+ if (idemSnapshot) {
3853
+ if (input !== void 0 && idemSnapshot.metadata?.input !== void 0) {
3854
+ const storedInput = JSON.stringify(idemSnapshot.metadata.input);
3855
+ const currentInput = JSON.stringify(input);
3856
+ if (storedInput !== currentInput) {
3857
+ const result = err({
3858
+ type: "IDEMPOTENCY_CONFLICT",
3859
+ idempotencyKey,
3860
+ workflowId: id,
3861
+ message: `Idempotency key '${idempotencyKey}' already used with different input for workflow '${id}'.`
3862
+ });
3863
+ resolveIdempotencyRun(result);
3864
+ pendingIdempotencyRuns.delete(idemId);
3865
+ resolveIdempotencyRun = void 0;
3866
+ return result;
3867
+ }
3868
+ }
3869
+ if (idemSnapshot.execution.status === "completed" && idemSnapshot.metadata?.finalResult !== void 0) {
3870
+ const result = idemSnapshot.metadata.finalResult;
3871
+ resolveIdempotencyRun(result);
3872
+ pendingIdempotencyRuns.delete(idemId);
3873
+ resolveIdempotencyRun = void 0;
3874
+ return result;
3875
+ }
3876
+ if (idemSnapshot.execution.status === "running") {
3877
+ const result = err({
3878
+ type: "CONCURRENT_EXECUTION",
3879
+ workflowId: id,
3880
+ message: `Workflow '${id}' with idempotency key '${idempotencyKey}' is already running.`,
3881
+ reason: "cross-process"
3882
+ });
3883
+ resolveIdempotencyRun(result);
3884
+ pendingIdempotencyRuns.delete(idemId);
3885
+ resolveIdempotencyRun = void 0;
3886
+ return result;
3887
+ }
3888
+ }
3889
+ } catch {
3890
+ }
3891
+ try {
3892
+ await effectiveStore.save(idemId, {
3893
+ formatVersion: 1,
3894
+ steps: {},
3895
+ execution: {
3896
+ status: "running",
3897
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
3898
+ },
3899
+ metadata: {
3900
+ workflowId: id,
3901
+ idempotencyKey,
3902
+ input
3903
+ }
3904
+ });
3905
+ } catch {
3906
+ }
3907
+ }
3908
+ if (!allowConcurrent && activeWorkflows.has(id)) {
3909
+ const error = {
3910
+ type: "CONCURRENT_EXECUTION",
3911
+ workflowId: id,
3912
+ message: `Workflow '${id}' is already running. Set allowConcurrent: true to allow parallel executions.`,
3913
+ reason: "in-process"
3914
+ };
3915
+ return err(error);
3916
+ }
3917
+ let leaseOwnerToken = null;
3918
+ if (!allowConcurrent && hasWorkflowLock(effectiveStore)) {
3919
+ let lease;
3920
+ try {
3921
+ lease = await effectiveStore.tryAcquire(id, { ttlMs: lockTtlMs });
3922
+ } catch (lockError) {
3923
+ const error = {
3924
+ type: "PERSISTENCE_ERROR",
3925
+ operation: "load",
3926
+ workflowId: id,
3927
+ cause: lockError,
3928
+ message: `Failed to acquire lock for workflow '${id}': ${lockError instanceof Error ? lockError.message : String(lockError)}`
3929
+ };
3930
+ return err(error);
3931
+ }
3932
+ if (lease === null) {
3933
+ const error = {
3934
+ type: "CONCURRENT_EXECUTION",
3935
+ workflowId: id,
3936
+ message: `Workflow '${id}' is already running (lease held by another process). Set allowConcurrent: true to allow parallel executions.`,
3937
+ reason: "cross-process"
3938
+ };
3939
+ return err(error);
3940
+ }
3941
+ leaseOwnerToken = lease.ownerToken;
3942
+ }
3943
+ let heartbeatTimer;
3944
+ let leaseAbortController;
3945
+ const lockStore = effectiveStore;
3946
+ if (leaseOwnerToken && typeof lockStore.renew === "function") {
3947
+ const heartbeatMs = heartbeatIntervalMs ?? Math.floor(lockTtlMs / 3);
3948
+ leaseAbortController = new AbortController();
3949
+ heartbeatTimer = setInterval(async () => {
3950
+ try {
3951
+ const renewed = await lockStore.renew(id, leaseOwnerToken, { ttlMs: lockTtlMs });
3952
+ if (!renewed) {
3953
+ leaseAbortController.abort(new Error("Lease expired"));
3954
+ }
3955
+ } catch {
3956
+ leaseAbortController.abort(new Error("Lease renewal failed"));
3957
+ }
3958
+ }, heartbeatMs);
3959
+ }
3960
+ activeWorkflows.add(id);
3961
+ let durableResult;
3962
+ try {
3963
+ let existingSnapshot = null;
3964
+ try {
3965
+ existingSnapshot = await effectiveStore.load(id);
3966
+ } catch (loadError) {
3967
+ const error = {
3968
+ type: "PERSISTENCE_ERROR",
3969
+ operation: "load",
3970
+ workflowId: id,
3971
+ cause: loadError,
3972
+ message: `Failed to load state for workflow '${id}': ${loadError instanceof Error ? loadError.message : String(loadError)}`
3973
+ };
3974
+ durableResult = err(error);
3975
+ return err(error);
3976
+ }
3977
+ if (existingSnapshot) {
3978
+ try {
3979
+ assertValidSnapshot(existingSnapshot);
3980
+ } catch (validationError) {
3981
+ if (validationError instanceof SnapshotFormatError) {
3982
+ const error = {
3983
+ type: "PERSISTENCE_ERROR",
3984
+ operation: "load",
3985
+ workflowId: id,
3986
+ cause: validationError,
3987
+ message: `Invalid snapshot format for workflow '${id}': ${validationError.message}`
3988
+ };
3989
+ durableResult = err(error);
3990
+ return err(error);
3991
+ }
3992
+ throw validationError;
3993
+ }
3994
+ }
3995
+ if (existingSnapshot) {
3996
+ const storedVersion = typeof existingSnapshot.metadata?.version === "number" ? existingSnapshot.metadata.version : 1;
3997
+ if (storedVersion !== version) {
3998
+ const error = {
3999
+ type: "VERSION_MISMATCH",
4000
+ workflowId: id,
4001
+ storedVersion,
4002
+ requestedVersion: version,
4003
+ currentVersion: version,
4004
+ message: `Workflow '${id}' has stored state at version ${storedVersion} but this run requested version ${version}. Migrate the stored state to the new version, or clear state for this id (e.g. durable.deleteState(store, '${id}')) and re-run.`
4005
+ };
4006
+ if (!onVersionMismatch) {
4007
+ durableResult = err(error);
4008
+ return err(error);
4009
+ }
4010
+ const resolution = await Promise.resolve(
4011
+ onVersionMismatch({ id, storedVersion, requestedVersion: version })
4012
+ );
4013
+ if (resolution === "throw") {
4014
+ durableResult = err(error);
4015
+ return err(error);
4016
+ }
4017
+ if (resolution === "clear") {
4018
+ try {
4019
+ await effectiveStore.delete(id);
4020
+ } catch {
4021
+ }
4022
+ existingSnapshot = null;
4023
+ } else {
4024
+ existingSnapshot = resolution.migratedSnapshot;
4025
+ }
4026
+ }
4027
+ }
4028
+ const emitDurableEvent = (event, ctx) => {
4029
+ if (onEvent) {
4030
+ onEvent(event, ctx);
4031
+ }
4032
+ };
4033
+ const resumeCollector = createResumeStateCollector();
4034
+ const workflowOptions = {
4035
+ // Restore from existing snapshot
4036
+ snapshot: existingSnapshot,
4037
+ // Persist after each keyed step
4038
+ onAfterStep: async (stepKey, result2, wfId, ctx) => {
4039
+ try {
4040
+ const collectedState = resumeCollector.getResumeState();
4041
+ const steps = {};
4042
+ for (const [key, entry] of collectedState.steps) {
4043
+ if (entry.result.ok) {
4044
+ steps[key] = { ok: true, value: entry.result.value };
4045
+ } else {
4046
+ const cause = entry.result.cause;
4047
+ const serializedCause = cause instanceof Error ? serializeError(cause) : serializeThrown(cause);
4048
+ const origin = entry.meta?.origin === "throw" ? "throw" : "result";
4049
+ steps[key] = {
4050
+ ok: false,
4051
+ error: entry.result.error,
4052
+ cause: serializedCause,
4053
+ meta: { origin }
4054
+ };
4055
+ }
4056
+ }
4057
+ const currentSnapshot = {
4058
+ formatVersion: 1,
4059
+ workflowName: id,
4060
+ steps,
4061
+ execution: {
4062
+ status: "running",
4063
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
4064
+ currentStepId: stepKey
4065
+ },
4066
+ metadata: {
4067
+ ...existingSnapshot?.metadata ?? {},
4068
+ ...metadata,
4069
+ version,
4070
+ lastStepKey: stepKey
4071
+ }
4072
+ };
4073
+ let snapshotToSave = existingSnapshot ? mergeSnapshots(existingSnapshot, currentSnapshot) : currentSnapshot;
4074
+ if (snapshotToSave.warnings && snapshotToSave.warnings.length > 0) {
4075
+ const currentStepKeys = new Set(Object.keys(currentSnapshot.steps));
4076
+ const filtered = snapshotToSave.warnings.filter(
4077
+ (w) => !currentStepKeys.has(w.stepId)
4078
+ );
4079
+ snapshotToSave = {
4080
+ ...snapshotToSave,
4081
+ warnings: filtered.length > 0 ? filtered : void 0
4082
+ };
4083
+ }
4084
+ await effectiveStore.save(id, snapshotToSave);
4085
+ emitDurableEvent(
4086
+ {
4087
+ type: "persist_success",
4088
+ workflowId: wfId,
4089
+ stepKey,
4090
+ ts: Date.now(),
4091
+ context: ctx
4092
+ },
4093
+ ctx
4094
+ );
4095
+ } catch (persistError) {
4096
+ emitDurableEvent(
4097
+ {
4098
+ type: "persist_error",
4099
+ workflowId: wfId,
4100
+ stepKey,
4101
+ error: persistError,
4102
+ ts: Date.now(),
4103
+ context: ctx
4104
+ },
4105
+ ctx
4106
+ );
4107
+ }
4108
+ },
4109
+ // Forward events and collect step results for snapshot building
4110
+ onEvent: (event, ctx) => {
4111
+ resumeCollector.handleEvent(event);
4112
+ emitDurableEvent(event, ctx);
4113
+ },
4114
+ onError,
4115
+ signal: leaseAbortController && signal ? AbortSignal.any([signal, leaseAbortController.signal]) : leaseAbortController?.signal ?? signal,
4116
+ createContext
4117
+ };
4118
+ let workflowInstance;
4119
+ try {
4120
+ workflowInstance = createWorkflow(id, deps, workflowOptions);
4121
+ } catch (createError) {
4122
+ if (createError instanceof SnapshotFormatError) {
4123
+ const error = {
4124
+ type: "PERSISTENCE_ERROR",
4125
+ operation: "load",
4126
+ workflowId: id,
4127
+ cause: createError,
4128
+ message: `Invalid snapshot format for workflow '${id}': ${createError.message}`
4129
+ };
4130
+ durableResult = err(error);
4131
+ return err(error);
4132
+ }
4133
+ throw createError;
4134
+ }
4135
+ let result;
4136
+ try {
4137
+ result = await workflowInstance.run(fn);
4138
+ } catch (runError) {
4139
+ if (runError instanceof SnapshotFormatError || runError instanceof SnapshotDecodeError) {
4140
+ const error = {
4141
+ type: "PERSISTENCE_ERROR",
4142
+ operation: "load",
4143
+ workflowId: id,
4144
+ cause: runError,
4145
+ message: `Invalid snapshot format for workflow '${id}': ${runError.message}`
4146
+ };
4147
+ durableResult = err(error);
4148
+ return err(error);
4149
+ }
4150
+ throw runError;
4151
+ }
4152
+ if (abortOnLeaseLoss !== false && leaseAbortController?.signal.aborted) {
4153
+ const leaseErr = err({
4154
+ type: "LEASE_EXPIRED",
4155
+ workflowId: id,
4156
+ message: `Lease expired for workflow '${id}' during execution. The workflow may have been reclaimed by another process.`
4157
+ });
4158
+ durableResult = leaseErr;
4159
+ return leaseErr;
4160
+ }
4161
+ if (result.ok) {
4162
+ try {
4163
+ await effectiveStore.delete(id);
4164
+ } catch (deleteError) {
4165
+ const error = {
4166
+ type: "PERSISTENCE_ERROR",
4167
+ operation: "delete",
4168
+ workflowId: id,
4169
+ cause: deleteError,
4170
+ message: `Failed to delete state for workflow '${id}': ${deleteError instanceof Error ? deleteError.message : String(deleteError)}`
4171
+ };
4172
+ durableResult = err(error);
4173
+ return err(error);
4174
+ }
4175
+ if (idempotencyKey) {
4176
+ const idemId = `idem:${idempotencyKey}`;
4177
+ try {
4178
+ await effectiveStore.save(idemId, {
4179
+ formatVersion: 1,
4180
+ steps: {},
4181
+ execution: {
4182
+ status: "completed",
4183
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
4184
+ completedAt: (/* @__PURE__ */ new Date()).toISOString()
4185
+ },
4186
+ metadata: {
4187
+ workflowId: id,
4188
+ idempotencyKey,
4189
+ input,
4190
+ finalResult: result
4191
+ }
4192
+ });
4193
+ } catch {
4194
+ }
4195
+ }
4196
+ }
4197
+ durableResult = result;
4198
+ return result;
4199
+ } finally {
4200
+ activeWorkflows.delete(id);
4201
+ if (resolveIdempotencyRun) {
4202
+ resolveIdempotencyRun(durableResult);
4203
+ pendingIdempotencyRuns.delete(`idem:${idempotencyKey}`);
4204
+ }
4205
+ if (heartbeatTimer) {
4206
+ clearInterval(heartbeatTimer);
4207
+ }
4208
+ if (leaseOwnerToken !== null && hasWorkflowLock(effectiveStore)) {
4209
+ try {
4210
+ await effectiveStore.release(id, leaseOwnerToken);
4211
+ } catch {
4212
+ }
4213
+ }
4214
+ }
4215
+ },
4216
+ /**
4217
+ * Clear all persisted workflow state from the store.
4218
+ * Use for admin/testing. If the store implements `clear()`, that is used;
4219
+ * otherwise clears by listing and deleting in pages.
4220
+ *
4221
+ * @param store - Snapshot store
4222
+ */
4223
+ async clearState(store) {
4224
+ const storeWithClear = store;
4225
+ if (typeof storeWithClear.clear === "function") {
4226
+ await storeWithClear.clear();
4227
+ return;
4228
+ }
4229
+ const limit = 100;
4230
+ for (; ; ) {
4231
+ const entries = await store.list({ limit });
4232
+ if (entries.length === 0) break;
4233
+ const ids = entries.map((e) => e.id);
4234
+ await this.deleteStates(store, ids, { continueOnError: true });
4235
+ if (entries.length < limit) break;
4236
+ }
4237
+ },
4238
+ /**
4239
+ * Check if a workflow ID has persisted state (can be resumed).
4240
+ *
4241
+ * @param store - Snapshot store
4242
+ * @param id - Workflow execution ID
4243
+ * @returns `true` if state exists, `false` otherwise (including on store errors)
4244
+ */
4245
+ async hasState(store, id) {
4246
+ try {
4247
+ const snapshot = await store.load(id);
4248
+ return snapshot !== null;
4249
+ } catch {
4250
+ return false;
4251
+ }
4252
+ },
4253
+ /**
4254
+ * Delete persisted state for a workflow (cancel resume capability).
4255
+ * Deleting is effectively an ack/reset: the workflow can no longer resume from that state.
4256
+ * If you delete while a run is in flight, the run continues; on success it may delete again (no-op) or save (recreating state).
4257
+ * For multi-worker safety, prefer deleting only when the workflow is not running or when you hold the lock.
4258
+ *
4259
+ * @param store - Snapshot store
4260
+ * @param id - Workflow execution ID
4261
+ * @returns `true` on success, `false` on store errors
4262
+ */
4263
+ async deleteState(store, id) {
4264
+ try {
4265
+ await store.delete(id);
4266
+ return true;
4267
+ } catch {
4268
+ return false;
4269
+ }
4270
+ },
4271
+ /**
4272
+ * Bulk delete persisted state for multiple workflow IDs (best-effort).
4273
+ * Use for admin/cleanup. Deletes in a loop with optional concurrency.
4274
+ *
4275
+ * @param store - Snapshot store
4276
+ * @param ids - Workflow execution IDs to delete
4277
+ * @param options - Optional concurrency and error handling
4278
+ * @returns Count of deleted entries and any errors when continueOnError is true
4279
+ */
4280
+ async deleteStates(store, ids, options = {}) {
4281
+ const { concurrency = 10, continueOnError = true } = options;
4282
+ if (ids.length === 0) {
4283
+ return { deleted: 0 };
4284
+ }
4285
+ const errors = [];
4286
+ let deleted = 0;
4287
+ const run2 = async (id) => {
4288
+ try {
4289
+ await store.delete(id);
4290
+ deleted++;
4291
+ } catch (error) {
4292
+ if (continueOnError) errors.push({ id, error });
4293
+ else throw error;
4294
+ }
4295
+ };
4296
+ const limit = Math.max(1, concurrency);
4297
+ for (let i = 0; i < ids.length; i += limit) {
4298
+ const batch = ids.slice(i, i + limit);
4299
+ await Promise.all(batch.map((id) => run2(id)));
4300
+ }
4301
+ return errors.length > 0 ? { deleted, errors } : { deleted };
4302
+ },
4303
+ /**
4304
+ * List workflow IDs with persisted state.
4305
+ *
4306
+ * @param store - Snapshot store
4307
+ * @param options - Optional prefix and limit
4308
+ * @returns Array of { id, updatedAt } entries
4309
+ */
4310
+ async listPending(store, options) {
4311
+ try {
4312
+ return await store.list(options);
4313
+ } catch {
4314
+ return [];
4315
+ }
4316
+ }
4317
+ };
4318
+
4319
+ // src/engine/index.ts
4320
+ function createEngine(options) {
4321
+ const {
4322
+ store,
4323
+ workflows,
4324
+ concurrency = 5,
4325
+ onEvent,
4326
+ onError
4327
+ } = options;
4328
+ const schedules = /* @__PURE__ */ new Map();
4329
+ let pollTimer;
4330
+ let running = false;
4331
+ let tickInFlight = false;
4332
+ function emit(event) {
4333
+ try {
4334
+ onEvent?.(event);
4335
+ } catch {
4336
+ }
4337
+ }
4338
+ async function enqueue(name, opts) {
4339
+ const wf = workflows[name];
4340
+ if (!wf) {
4341
+ throw new Error(`Unknown workflow: '${name}'. Registered: ${Object.keys(workflows).join(", ")}`);
4342
+ }
4343
+ const id = opts?.id ?? `${name}:${(0, import_node_crypto.randomUUID)()}`;
4344
+ const snapshot = {
4345
+ formatVersion: 1,
4346
+ workflowName: name,
4347
+ steps: {},
4348
+ execution: {
4349
+ status: "running",
4350
+ // "running" so durable.run can resume it
4351
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
4352
+ },
4353
+ metadata: {
4354
+ engineState: "queued",
4355
+ workflowName: name,
4356
+ input: opts?.input ?? null,
4357
+ idempotencyKey: opts?.idempotencyKey,
4358
+ enqueuedAt: (/* @__PURE__ */ new Date()).toISOString(),
4359
+ ...opts?.metadata
4360
+ }
4361
+ };
4362
+ await store.save(id, snapshot);
4363
+ emit({ type: "workflow_enqueued", workflowName: name, id, ts: Date.now() });
4364
+ return id;
4365
+ }
4366
+ async function tick() {
4367
+ if (tickInFlight) return 0;
4368
+ tickInFlight = true;
4369
+ try {
4370
+ const entries = await store.list({ limit: concurrency * 2 });
4371
+ let processed = 0;
4372
+ const queued = [];
4373
+ for (const entry of entries) {
4374
+ if (queued.length >= concurrency) break;
4375
+ const snapshot = await store.load(entry.id);
4376
+ if (snapshot && snapshot.metadata?.engineState === "queued" && typeof snapshot.metadata?.workflowName === "string") {
4377
+ queued.push({ id: entry.id, workflowName: snapshot.metadata.workflowName, snapshot });
4378
+ }
4379
+ }
4380
+ const results = await Promise.allSettled(
4381
+ queued.map(async ({ id, workflowName, snapshot }) => {
4382
+ const wf = workflows[workflowName];
4383
+ if (!wf) return;
4384
+ const processingSnapshot = {
4385
+ ...snapshot,
4386
+ metadata: {
4387
+ ...snapshot.metadata,
4388
+ engineState: "processing"
4389
+ }
4390
+ };
4391
+ await store.save(id, processingSnapshot);
4392
+ emit({ type: "workflow_started", workflowName, id, ts: Date.now() });
4393
+ const result = await durable.run(wf.deps, wf.fn, {
4394
+ id,
4395
+ store,
4396
+ idempotencyKey: snapshot.metadata?.idempotencyKey,
4397
+ input: snapshot.metadata?.input,
4398
+ ...wf.durableDefaults
4399
+ });
4400
+ if (result.ok) {
4401
+ emit({ type: "workflow_completed", workflowName, id, ts: Date.now() });
4402
+ } else {
4403
+ emit({ type: "workflow_failed", workflowName, id, error: result.error, ts: Date.now() });
4404
+ }
4405
+ processed++;
4406
+ })
4407
+ );
4408
+ for (const r of results) {
4409
+ if (r.status === "rejected") {
4410
+ try {
4411
+ onError?.(r.reason);
4412
+ } catch {
4413
+ }
4414
+ }
4415
+ }
4416
+ emit({ type: "engine_tick", ts: Date.now(), processed });
4417
+ return processed;
4418
+ } finally {
4419
+ tickInFlight = false;
4420
+ }
4421
+ }
4422
+ function schedule(name, opts) {
4423
+ const scheduleId = opts?.id ? `schedule:${opts.id}` : `schedule:${(0, import_node_crypto.randomUUID)()}`;
4424
+ if (opts.immediate) {
4425
+ void enqueue(name, opts).catch((e) => {
4426
+ try {
4427
+ onError?.(e);
4428
+ } catch {
4429
+ }
4430
+ });
4431
+ }
4432
+ const interval = setInterval(() => {
4433
+ void enqueue(name, opts).catch((e) => {
4434
+ try {
4435
+ onError?.(e);
4436
+ } catch {
4437
+ }
4438
+ });
4439
+ }, opts.intervalMs);
4440
+ schedules.set(scheduleId, interval);
4441
+ emit({ type: "schedule_created", workflowName: name, scheduleId, intervalMs: opts.intervalMs, ts: Date.now() });
4442
+ return scheduleId;
4443
+ }
4444
+ function unschedule(scheduleId) {
4445
+ const interval = schedules.get(scheduleId);
4446
+ if (!interval) return false;
4447
+ clearInterval(interval);
4448
+ schedules.delete(scheduleId);
4449
+ emit({ type: "schedule_removed", scheduleId, ts: Date.now() });
4450
+ return true;
4451
+ }
4452
+ function start(pollIntervalMs = 1e3) {
4453
+ if (running) return;
4454
+ running = true;
4455
+ emit({ type: "engine_start", ts: Date.now() });
4456
+ void tick().catch((e) => {
4457
+ try {
4458
+ onError?.(e);
4459
+ } catch {
4460
+ }
4461
+ });
4462
+ pollTimer = setInterval(() => {
4463
+ void tick().catch((e) => {
4464
+ try {
4465
+ onError?.(e);
4466
+ } catch {
4467
+ }
4468
+ });
4469
+ }, pollIntervalMs);
4470
+ }
4471
+ async function stop() {
4472
+ if (!running) return;
4473
+ running = false;
4474
+ if (pollTimer) {
4475
+ clearInterval(pollTimer);
4476
+ pollTimer = void 0;
4477
+ }
4478
+ for (const [id, interval] of schedules) {
4479
+ clearInterval(interval);
4480
+ schedules.delete(id);
4481
+ }
4482
+ while (tickInFlight) {
4483
+ await new Promise((resolve) => setTimeout(resolve, 50));
4484
+ }
4485
+ emit({ type: "engine_stop", ts: Date.now() });
4486
+ }
4487
+ return {
4488
+ enqueue,
4489
+ schedule,
4490
+ unschedule,
4491
+ start,
4492
+ stop,
4493
+ tick,
4494
+ status: () => ({ running, pendingSchedules: schedules.size })
4495
+ };
4496
+ }
4497
+ // Annotate the CommonJS export names for ESM import in node:
4498
+ 0 && (module.exports = {
4499
+ createEngine
4500
+ });
4501
+ //# sourceMappingURL=engine.cjs.map