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