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
package/dist/saga.js ADDED
@@ -0,0 +1,3670 @@
1
+ // src/slugs.ts
2
+ var AWAITLY_SLUGS = {
3
+ // --- step-* ---
4
+ "step-require-id": "step-require-id",
5
+ "step-no-immediate-execution": "step-no-immediate-execution",
6
+ "step-require-thunk-for-key": "step-require-thunk-for-key",
7
+ "step-no-bare-await": "step-no-bare-await",
8
+ "step-no-try-catch-wrap": "step-no-try-catch-wrap",
9
+ "step-stable-cache-keys": "step-stable-cache-keys",
10
+ // --- workflow-* ---
11
+ "workflow-no-floating": "workflow-no-floating",
12
+ "workflow-options-position": "workflow-options-position",
13
+ "workflow-callback-shape": "workflow-callback-shape",
14
+ "workflow-no-callable-form": "workflow-no-callable-form",
15
+ "workflow-no-dynamic-import": "workflow-no-dynamic-import",
16
+ "workflow-prefer-step-if": "workflow-prefer-step-if",
17
+ "workflow-prefer-step-foreach": "workflow-prefer-step-foreach",
18
+ // --- result-* ---
19
+ "result-no-floating": "result-no-floating",
20
+ "result-require-handling": "result-require-handling",
21
+ "result-no-double-wrap": "result-no-double-wrap",
22
+ "result-no-manual-propagation": "result-no-manual-propagation",
23
+ "result-no-direct-ok-err": "result-no-direct-ok-err",
24
+ // --- error-* ---
25
+ "error-check-unexpected-first": "error-check-unexpected-first",
26
+ "error-access-cause": "error-access-cause",
27
+ "error-normalize": "error-normalize",
28
+ "error-no-throw-in-deps": "error-no-throw-in-deps",
29
+ // --- concurrency-* ---
30
+ "concurrency-no-promise-all": "concurrency-no-promise-all",
31
+ "concurrency-no-promise-race": "concurrency-no-promise-race",
32
+ "concurrency-no-promise-allsettled": "concurrency-no-promise-allsettled",
33
+ // --- runtime-* ---
34
+ "runtime-step-timeout": "runtime-step-timeout",
35
+ "runtime-step-aborted": "runtime-step-aborted",
36
+ "runtime-retry-exhausted": "runtime-retry-exhausted",
37
+ "runtime-rate-limit": "runtime-rate-limit",
38
+ "runtime-circuit-open": "runtime-circuit-open",
39
+ "runtime-unexpected": "runtime-unexpected",
40
+ "runtime-resolver-not-found": "runtime-resolver-not-found",
41
+ "runtime-saga-compensation": "runtime-saga-compensation"
42
+ };
43
+ function slugDocsUrl(slug) {
44
+ return `https://jagreehal.github.io/awaitly/rules/#${slug}`;
45
+ }
46
+ var ALL_SLUGS = Object.keys(
47
+ AWAITLY_SLUGS
48
+ );
49
+
50
+ // src/tagged-error.ts
51
+ var InternalTaggedErrorBase = class extends Error {
52
+ type;
53
+ /** @deprecated Use `type`. */
54
+ _tag;
55
+ };
56
+ function TaggedError(tag, options) {
57
+ return class extends InternalTaggedErrorBase {
58
+ type = tag;
59
+ /** @deprecated Use `type`. */
60
+ _tag = tag;
61
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
62
+ constructor(props, errorOptions) {
63
+ const message = options?.message ? options.message(props ?? {}) : tag;
64
+ super(message);
65
+ this.name = tag;
66
+ if (options?.slug !== void 0) {
67
+ if (!options.hint) {
68
+ throw new TypeError(
69
+ `TaggedError: 'hint' is required when 'slug' is set (slug: "${options.slug}")`
70
+ );
71
+ }
72
+ Object.defineProperty(this, "code", {
73
+ value: options.slug,
74
+ enumerable: true,
75
+ writable: false,
76
+ configurable: false
77
+ });
78
+ Object.defineProperty(this, "hint", {
79
+ value: options.hint,
80
+ enumerable: true,
81
+ writable: false,
82
+ configurable: false
83
+ });
84
+ Object.defineProperty(this, "docsUrl", {
85
+ value: slugDocsUrl(options.slug),
86
+ enumerable: true,
87
+ writable: false,
88
+ configurable: false
89
+ });
90
+ }
91
+ Object.setPrototypeOf(this, new.target.prototype);
92
+ if (props && typeof props === "object") {
93
+ let safeProps;
94
+ if (options?.slug !== void 0) {
95
+ const {
96
+ _tag: _,
97
+ type: _t,
98
+ name: _n,
99
+ message: _m,
100
+ stack: _s,
101
+ code: _c,
102
+ hint: _h,
103
+ docsUrl: _d,
104
+ ...rest
105
+ } = props;
106
+ safeProps = rest;
107
+ } else {
108
+ const {
109
+ _tag: _,
110
+ type: _t,
111
+ name: _n,
112
+ message: _m,
113
+ stack: _s,
114
+ ...rest
115
+ } = props;
116
+ safeProps = rest;
117
+ }
118
+ const hasUserCause = Object.prototype.hasOwnProperty.call(
119
+ safeProps,
120
+ "cause"
121
+ );
122
+ const userCause = hasUserCause ? safeProps.cause : void 0;
123
+ if (hasUserCause) {
124
+ delete safeProps.cause;
125
+ }
126
+ const hasOptionsCause = errorOptions?.cause !== void 0;
127
+ if (hasUserCause && hasOptionsCause) {
128
+ throw new TypeError(
129
+ "TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause"
130
+ );
131
+ }
132
+ Object.assign(this, safeProps);
133
+ if (hasUserCause) {
134
+ this.cause = userCause;
135
+ }
136
+ if (hasOptionsCause) {
137
+ this.cause = errorOptions?.cause;
138
+ }
139
+ } else if (errorOptions?.cause !== void 0) {
140
+ this.cause = errorOptions.cause;
141
+ }
142
+ }
143
+ };
144
+ }
145
+ Object.defineProperty(TaggedError, Symbol.hasInstance, {
146
+ value: (instance) => instance instanceof InternalTaggedErrorBase
147
+ });
148
+ ((TaggedError2) => {
149
+ function isError(value) {
150
+ return value instanceof Error;
151
+ }
152
+ TaggedError2.isError = isError;
153
+ function isTaggedError(value) {
154
+ return value instanceof InternalTaggedErrorBase;
155
+ }
156
+ TaggedError2.isTaggedError = isTaggedError;
157
+ function match(error, handlers) {
158
+ const tag = error._tag;
159
+ const handler = handlers[tag];
160
+ return handler(
161
+ error
162
+ );
163
+ }
164
+ TaggedError2.match = match;
165
+ function matchPartial(error, handlers, otherwise) {
166
+ const tag = error._tag;
167
+ const handler = handlers[tag];
168
+ if (handler) {
169
+ return handler(
170
+ error
171
+ );
172
+ }
173
+ return otherwise(error);
174
+ }
175
+ TaggedError2.matchPartial = matchPartial;
176
+ })(TaggedError || (TaggedError = {}));
177
+
178
+ // src/errors.ts
179
+ var UnexpectedError = class extends (/* @__PURE__ */ TaggedError("UnexpectedError", {
180
+ slug: "runtime-unexpected",
181
+ hint: "An unexpected exception escaped a step. Inspect cause; consider returning a typed Result instead of throwing.",
182
+ message: (p) => `UnexpectedError: ${p.cause instanceof Error ? p.cause.message : String(p.cause ?? "unknown")}`
183
+ })) {
184
+ };
185
+
186
+ // src/result/index.ts
187
+ function ok(value) {
188
+ return { ok: true, value };
189
+ }
190
+
191
+ // src/core/bound-steps.ts
192
+ var isDepResultShaped = (value) => typeof value === "object" && value !== null && "ok" in value && typeof value.ok === "boolean" && (value.ok ? "value" in value : "error" in value);
193
+ var bindSteps = (deps, step) => {
194
+ const steps = {};
195
+ const invocationCounts = /* @__PURE__ */ new Map();
196
+ for (const key of Object.keys(deps)) {
197
+ const dep = deps[key];
198
+ if (typeof dep !== "function") continue;
199
+ steps[key] = (...args) => {
200
+ const count = (invocationCounts.get(key) ?? 0) + 1;
201
+ invocationCounts.set(key, count);
202
+ const stepKey = count === 1 ? key : `${key}#${count}`;
203
+ return step(stepKey, async () => {
204
+ const value = await dep(...args);
205
+ return isDepResultShaped(value) ? value : ok(value);
206
+ });
207
+ };
208
+ }
209
+ return steps;
210
+ };
211
+
212
+ // src/duration.ts
213
+ function millis(ms) {
214
+ return { _tag: "Duration", millis: ms };
215
+ }
216
+ function seconds(s) {
217
+ return { _tag: "Duration", millis: s * 1e3 };
218
+ }
219
+ function minutes(m) {
220
+ return { _tag: "Duration", millis: m * 60 * 1e3 };
221
+ }
222
+ function hours(h) {
223
+ return { _tag: "Duration", millis: h * 60 * 60 * 1e3 };
224
+ }
225
+ function days(d) {
226
+ return { _tag: "Duration", millis: d * 24 * 60 * 60 * 1e3 };
227
+ }
228
+ function toMillis(duration) {
229
+ return duration.millis;
230
+ }
231
+ function parse(input) {
232
+ const match = input.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);
233
+ if (!match) return void 0;
234
+ const value = parseFloat(match[1]);
235
+ const unit = match[2].toLowerCase();
236
+ switch (unit) {
237
+ case "ms":
238
+ return millis(value);
239
+ case "s":
240
+ return seconds(value);
241
+ case "m":
242
+ return minutes(value);
243
+ case "h":
244
+ return hours(value);
245
+ case "d":
246
+ return days(value);
247
+ default:
248
+ return void 0;
249
+ }
250
+ }
251
+
252
+ // src/core/index.ts
253
+ function parseDurationString(input) {
254
+ const match = input.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);
255
+ if (!match) return void 0;
256
+ const value = parseFloat(match[1]);
257
+ const unit = match[2].toLowerCase();
258
+ const multipliers = { ms: 1, s: 1e3, m: 6e4, h: 36e5, d: 864e5 };
259
+ return { _tag: "Duration", millis: value * (multipliers[unit] ?? 1) };
260
+ }
261
+ function defaultCatchUnexpected(cause) {
262
+ return new UnexpectedError({ cause });
263
+ }
264
+ function ok2(value) {
265
+ return { ok: true, value };
266
+ }
267
+ function err(error, options) {
268
+ const cause = options?.cause;
269
+ return { ok: false, error, ...cause !== void 0 ? { cause } : {} };
270
+ }
271
+ var isUnexpectedError = (e) => e instanceof UnexpectedError || typeof e === "object" && e !== null && "_tag" in e && e._tag === "UnexpectedError";
272
+ function extractErrorTag(error) {
273
+ if (error == null) return "unknown";
274
+ if (typeof error === "string") return error.trim() || "unknown";
275
+ if (typeof error === "object") {
276
+ const tagged = error;
277
+ if (typeof tagged._tag === "string") {
278
+ const trimmed = tagged._tag.trim();
279
+ if (trimmed) return trimmed;
280
+ }
281
+ if (typeof tagged.tag === "string") {
282
+ const trimmed = tagged.tag.trim();
283
+ if (trimmed) return trimmed;
284
+ }
285
+ if (typeof tagged.code === "string") {
286
+ const trimmed = tagged.code.trim();
287
+ if (trimmed) return trimmed;
288
+ } else if (typeof tagged.code === "number") {
289
+ return String(tagged.code);
290
+ }
291
+ if (error instanceof Error && error.name) {
292
+ const trimmed = error.name.trim();
293
+ if (trimmed) return trimmed;
294
+ }
295
+ }
296
+ return "unknown";
297
+ }
298
+ function lookupErrorClassification(tag, errorMeta) {
299
+ if (!errorMeta || !tag) return void 0;
300
+ return errorMeta[tag];
301
+ }
302
+ function extractStepMetadata(options) {
303
+ const { intent, domain, owner, tags, stateChanges, emits, calls } = options;
304
+ if (!intent && !domain && !owner && !tags?.length && !stateChanges?.length && !emits?.length && !calls?.length) {
305
+ return void 0;
306
+ }
307
+ const metadata = {};
308
+ if (intent) metadata.intent = intent;
309
+ if (domain) metadata.domain = domain;
310
+ if (owner) metadata.owner = owner;
311
+ if (tags?.length) metadata.tags = tags;
312
+ if (stateChanges?.length) metadata.stateChanges = stateChanges;
313
+ if (emits?.length) metadata.emits = emits;
314
+ if (calls?.length) metadata.calls = calls;
315
+ return metadata;
316
+ }
317
+ function buildStepErrorPayload(error, errorMeta, origin, attempt, cumulativeDurationMs) {
318
+ const tag = extractErrorTag(error);
319
+ const classification = lookupErrorClassification(tag, errorMeta);
320
+ const diagnostics = { tag, origin };
321
+ if (classification !== void 0) diagnostics.classification = classification;
322
+ if (attempt !== void 0) diagnostics.attempt = attempt;
323
+ if (cumulativeDurationMs !== void 0) diagnostics.cumulativeDurationMs = cumulativeDurationMs;
324
+ return diagnostics;
325
+ }
326
+ var STEP_TIMEOUT_MARKER = /* @__PURE__ */ Symbol.for("step_timeout_marker");
327
+ function isStepTimeoutError(e) {
328
+ if (typeof e !== "object" || e === null) {
329
+ return false;
330
+ }
331
+ if (e.type === "STEP_TIMEOUT") {
332
+ return true;
333
+ }
334
+ return STEP_TIMEOUT_MARKER in e;
335
+ }
336
+ function getStepTimeoutMeta(e) {
337
+ if (typeof e !== "object" || e === null) {
338
+ return void 0;
339
+ }
340
+ if (e.type === "STEP_TIMEOUT") {
341
+ const err2 = e;
342
+ return {
343
+ timeoutMs: err2.timeoutMs,
344
+ stepName: err2.stepName,
345
+ stepKey: err2.stepKey,
346
+ attempt: err2.attempt
347
+ };
348
+ }
349
+ if (STEP_TIMEOUT_MARKER in e) {
350
+ return e[STEP_TIMEOUT_MARKER];
351
+ }
352
+ return void 0;
353
+ }
354
+ var EARLY_EXIT_SYMBOL = /* @__PURE__ */ Symbol("early-exit");
355
+ function createEarlyExit(error, meta) {
356
+ return {
357
+ [EARLY_EXIT_SYMBOL]: true,
358
+ error,
359
+ meta
360
+ };
361
+ }
362
+ function isEarlyExit(e) {
363
+ return typeof e === "object" && e !== null && e[EARLY_EXIT_SYMBOL] === true;
364
+ }
365
+ var MAPPER_EXCEPTION_SYMBOL = /* @__PURE__ */ Symbol("mapper-exception");
366
+ function createMapperException(thrown) {
367
+ return { [MAPPER_EXCEPTION_SYMBOL]: true, thrown };
368
+ }
369
+ function isMapperException(e) {
370
+ return typeof e === "object" && e !== null && e[MAPPER_EXCEPTION_SYMBOL] === true;
371
+ }
372
+ function calculateRetryDelay(attempt, options) {
373
+ const { backoff, initialDelay, maxDelay, jitter } = options;
374
+ let delay;
375
+ switch (backoff) {
376
+ case "fixed":
377
+ delay = initialDelay;
378
+ break;
379
+ case "linear":
380
+ delay = initialDelay * attempt;
381
+ break;
382
+ case "exponential":
383
+ delay = initialDelay * Math.pow(2, attempt - 1);
384
+ break;
385
+ }
386
+ delay = Math.min(delay, maxDelay);
387
+ if (jitter) {
388
+ const jitterAmount = delay * 0.25 * Math.random();
389
+ delay = delay + jitterAmount;
390
+ }
391
+ return Math.floor(delay);
392
+ }
393
+ function sleep(ms) {
394
+ return new Promise((resolve) => setTimeout(resolve, ms));
395
+ }
396
+ var TIMEOUT_SYMBOL = /* @__PURE__ */ Symbol("timeout");
397
+ var TIMEOUT_OPTION_SYMBOL = /* @__PURE__ */ Symbol("timeout-option");
398
+ function isTimeoutOptionMarker(value) {
399
+ return typeof value === "object" && value !== null && value[TIMEOUT_OPTION_SYMBOL] === true;
400
+ }
401
+ async function executeWithTimeout(operation, options, stepInfo, externalSignal) {
402
+ const controller = new AbortController();
403
+ const behavior = options.onTimeout ?? "error";
404
+ const createTimeoutError = () => {
405
+ if (typeof behavior === "function") {
406
+ return behavior({
407
+ name: stepInfo.name,
408
+ key: stepInfo.key,
409
+ ms: options.ms
410
+ });
411
+ }
412
+ return options.error ?? {
413
+ type: "STEP_TIMEOUT",
414
+ stepName: stepInfo.name,
415
+ stepKey: stepInfo.key,
416
+ timeoutMs: options.ms,
417
+ attempt: stepInfo.attempt
418
+ };
419
+ };
420
+ let timeoutId;
421
+ if (externalSignal?.aborted) {
422
+ controller.abort(externalSignal.reason);
423
+ }
424
+ let externalAbortHandler;
425
+ if (externalSignal && !externalSignal.aborted) {
426
+ externalAbortHandler = () => controller.abort(externalSignal.reason);
427
+ externalSignal.addEventListener("abort", externalAbortHandler, { once: true });
428
+ }
429
+ const timeoutPromise = new Promise((_, reject) => {
430
+ timeoutId = setTimeout(() => {
431
+ if (behavior !== "disconnect") {
432
+ controller.abort();
433
+ }
434
+ if (behavior === "option") {
435
+ reject({ [TIMEOUT_OPTION_SYMBOL]: true, ms: options.ms });
436
+ return;
437
+ }
438
+ reject({ [TIMEOUT_SYMBOL]: true, error: createTimeoutError() });
439
+ }, options.ms);
440
+ });
441
+ let operationPromise;
442
+ if (options.signal) {
443
+ operationPromise = Promise.resolve(
444
+ operation(controller.signal)
445
+ );
446
+ } else {
447
+ operationPromise = Promise.resolve(operation());
448
+ }
449
+ try {
450
+ const result = await Promise.race([operationPromise, timeoutPromise]);
451
+ return result;
452
+ } catch (error) {
453
+ if (typeof error === "object" && error !== null && error[TIMEOUT_OPTION_SYMBOL] === true) {
454
+ throw { [TIMEOUT_OPTION_SYMBOL]: true, ms: options.ms };
455
+ }
456
+ if (typeof error === "object" && error !== null && error[TIMEOUT_SYMBOL] === true) {
457
+ if (behavior === "disconnect") {
458
+ operationPromise.catch(() => {
459
+ });
460
+ }
461
+ const errorToThrow = error.error;
462
+ if (typeof errorToThrow === "object" && errorToThrow !== null && errorToThrow.type !== "STEP_TIMEOUT") {
463
+ const meta = {
464
+ timeoutMs: options.ms,
465
+ stepName: stepInfo.name,
466
+ stepKey: stepInfo.key,
467
+ attempt: stepInfo.attempt
468
+ };
469
+ if (STEP_TIMEOUT_MARKER in errorToThrow) {
470
+ errorToThrow[STEP_TIMEOUT_MARKER] = meta;
471
+ } else {
472
+ Object.defineProperty(errorToThrow, STEP_TIMEOUT_MARKER, {
473
+ value: meta,
474
+ enumerable: false,
475
+ writable: true,
476
+ configurable: false
477
+ });
478
+ }
479
+ }
480
+ throw errorToThrow;
481
+ }
482
+ throw error;
483
+ } finally {
484
+ clearTimeout(timeoutId);
485
+ if (externalAbortHandler && externalSignal) {
486
+ externalSignal.removeEventListener("abort", externalAbortHandler);
487
+ }
488
+ }
489
+ }
490
+ var DEFAULT_RETRY_CONFIG = {
491
+ backoff: "exponential",
492
+ initialDelay: 100,
493
+ maxDelay: 3e4,
494
+ jitter: true,
495
+ shouldRetry: () => true,
496
+ onRetry: () => {
497
+ }
498
+ };
499
+ async function runFn(fnOrDeps, optionsOrFn, maybeOptions) {
500
+ if (typeof fnOrDeps !== "function") {
501
+ const deps = fnOrDeps;
502
+ const boundFn = optionsOrFn;
503
+ if (typeof boundFn !== "function") {
504
+ throw new TypeError(
505
+ "[awaitly] run(deps, fn) requires a callback as the second argument. Example: run({ getUser }, async (s) => s.getUser(id))"
506
+ );
507
+ }
508
+ const classicRun = runFn;
509
+ return classicRun(
510
+ ({ step }) => boundFn(bindSteps(deps, step), { step }),
511
+ maybeOptions
512
+ );
513
+ }
514
+ const fn = fnOrDeps;
515
+ const options = optionsOrFn;
516
+ const {
517
+ onError,
518
+ onEvent,
519
+ catchUnexpected,
520
+ workflowId: providedWorkflowId,
521
+ workflowName,
522
+ context,
523
+ graph,
524
+ _workflowSignal
525
+ } = options && typeof options === "object" ? options : {};
526
+ const workflowId = providedWorkflowId ?? crypto.randomUUID();
527
+ const declaredIds = graph ? new Set(
528
+ Array.isArray(graph) ? graph : graph.states.map((state) => state.semanticId ?? state.id)
529
+ ) : void 0;
530
+ const declaredPatterns = declaredIds ? [...declaredIds].filter((id) => id.includes("{")).map(
531
+ (id) => new RegExp(
532
+ `^${id.replaceAll(/[.*+?^$()[\]\\|]/g, String.raw`\$&`).replaceAll(/\{[^}]*\}/g, ".+")}$`
533
+ )
534
+ ) : void 0;
535
+ const assertDeclared = (id, kind) => {
536
+ if (!declaredIds || declaredIds.has(id)) return;
537
+ if (declaredPatterns?.some((re) => re.test(id))) return;
538
+ throw new Error(
539
+ `[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.`
540
+ );
541
+ };
542
+ const effectiveCatchUnexpected = catchUnexpected ?? defaultCatchUnexpected;
543
+ const activeScopeStack = [];
544
+ let stepIdCounter = 0;
545
+ const generateStepId = (stepKey) => {
546
+ return stepKey ?? `step_${++stepIdCounter}`;
547
+ };
548
+ const emitEvent = (event) => {
549
+ const eventWithContext = event.context !== void 0 || context === void 0 ? event : { ...event, context };
550
+ const eventWithName = workflowName !== void 0 && eventWithContext.workflowName === void 0 ? { ...eventWithContext, workflowName } : eventWithContext;
551
+ if (eventWithName.type === "step_success") {
552
+ const stepId = eventWithName.stepId;
553
+ for (let i = activeScopeStack.length - 1; i >= 0; i--) {
554
+ const scope = activeScopeStack[i];
555
+ if (scope.type === "race" && !scope.winnerId) {
556
+ scope.winnerId = stepId;
557
+ break;
558
+ }
559
+ }
560
+ }
561
+ onEvent?.(eventWithName, context);
562
+ };
563
+ const earlyExit = createEarlyExit;
564
+ const isEarlyExitE = (e) => isEarlyExit(e);
565
+ const wrapForStep = (error, _meta) => {
566
+ return error;
567
+ };
568
+ const isResultLike = (value) => {
569
+ if (typeof value === "function") return false;
570
+ if (value && typeof value === "object" && "ok" in value) return true;
571
+ if (value && typeof value === "object" && "then" in value && typeof value.then === "function") return true;
572
+ return false;
573
+ };
574
+ try {
575
+ let normalizeParallelOperations2 = function(rawOperations) {
576
+ const out = {};
577
+ for (const [key, value2] of Object.entries(rawOperations)) {
578
+ if (typeof value2 === "function") {
579
+ out[key] = value2;
580
+ } else if (value2 && typeof value2 === "object" && "fn" in value2) {
581
+ out[key] = value2.fn;
582
+ } else {
583
+ throw new TypeError(`step.all: operation "${key}" must be a function or { fn, errors? } object`);
584
+ }
585
+ }
586
+ return out;
587
+ }, executeParallelArray2 = function(name, operation) {
588
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
589
+ return (async () => {
590
+ const startTime = performance.now();
591
+ let scopeEnded = false;
592
+ activeScopeStack.push({ scopeId, type: "parallel" });
593
+ const emitScopeEnd = () => {
594
+ if (scopeEnded) return;
595
+ scopeEnded = true;
596
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
597
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
598
+ emitEvent({
599
+ type: "scope_end",
600
+ workflowId,
601
+ scopeId,
602
+ ts: Date.now(),
603
+ durationMs: performance.now() - startTime
604
+ });
605
+ };
606
+ emitEvent({
607
+ type: "scope_start",
608
+ workflowId,
609
+ scopeId,
610
+ scopeType: "parallel",
611
+ name,
612
+ ts: Date.now()
613
+ });
614
+ try {
615
+ const result = await operation();
616
+ emitScopeEnd();
617
+ if (!result.ok) {
618
+ onError?.(result.error, name, context);
619
+ throw earlyExit(result.error, {
620
+ origin: "result",
621
+ resultCause: result.cause
622
+ });
623
+ }
624
+ return result.value;
625
+ } catch (error) {
626
+ emitScopeEnd();
627
+ throw error;
628
+ }
629
+ })();
630
+ }, executeParallelNamed2 = function(operations, options2) {
631
+ const keys = Object.keys(operations);
632
+ const name = options2.name ?? `Parallel(${keys.join(", ")})`;
633
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
634
+ return (async () => {
635
+ const startTime = performance.now();
636
+ let scopeEnded = false;
637
+ activeScopeStack.push({ scopeId, type: "parallel" });
638
+ const emitScopeEnd = () => {
639
+ if (scopeEnded) return;
640
+ scopeEnded = true;
641
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
642
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
643
+ emitEvent({
644
+ type: "scope_end",
645
+ workflowId,
646
+ scopeId,
647
+ ts: Date.now(),
648
+ durationMs: performance.now() - startTime
649
+ });
650
+ };
651
+ emitEvent({
652
+ type: "scope_start",
653
+ workflowId,
654
+ scopeId,
655
+ scopeType: "parallel",
656
+ name,
657
+ ts: Date.now()
658
+ });
659
+ try {
660
+ const results = await new Promise((resolve) => {
661
+ if (keys.length === 0) {
662
+ resolve([]);
663
+ return;
664
+ }
665
+ let settled = false;
666
+ let pendingCount = keys.length;
667
+ const resultArray = new Array(keys.length);
668
+ for (let i = 0; i < keys.length; i++) {
669
+ const key = keys[i];
670
+ const index = i;
671
+ Promise.resolve(operations[key]()).catch((reason) => err(
672
+ { type: "PROMISE_REJECTED", cause: reason },
673
+ { cause: { type: "PROMISE_REJECTION", reason } }
674
+ )).then((result) => {
675
+ if (settled) return;
676
+ if (!result.ok) {
677
+ settled = true;
678
+ resolve([{ key, result }]);
679
+ return;
680
+ }
681
+ resultArray[index] = { key, result };
682
+ pendingCount--;
683
+ if (pendingCount === 0) {
684
+ resolve(resultArray);
685
+ }
686
+ });
687
+ }
688
+ });
689
+ emitScopeEnd();
690
+ const output = {};
691
+ for (const { key, result } of results) {
692
+ if (!result.ok) {
693
+ onError?.(result.error, key, context);
694
+ throw earlyExit(result.error, {
695
+ origin: "result",
696
+ resultCause: result.cause
697
+ });
698
+ }
699
+ output[key] = result.value;
700
+ }
701
+ return output;
702
+ } catch (error) {
703
+ emitScopeEnd();
704
+ throw error;
705
+ }
706
+ })();
707
+ };
708
+ var normalizeParallelOperations = normalizeParallelOperations2, executeParallelArray = executeParallelArray2, executeParallelNamed = executeParallelNamed2;
709
+ const stepFn = (id, operationOrResult, stepOptions) => {
710
+ return (async () => {
711
+ if (typeof id !== "string" || id.length === 0) {
712
+ throw new Error(
713
+ '[awaitly] step() requires an explicit string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))'
714
+ );
715
+ }
716
+ assertDeclared(id, "step");
717
+ const parsedOptions = stepOptions ?? {};
718
+ const stepMetadata = extractStepMetadata(parsedOptions);
719
+ const stepName = id;
720
+ const stepKey = parsedOptions.key ?? id;
721
+ const explicitKey = parsedOptions.key ?? id;
722
+ const { description: stepDescription, retry: retryConfig, timeout: timeoutConfig } = parsedOptions;
723
+ const stepId = generateStepId(stepKey);
724
+ const hasEventListeners = onEvent;
725
+ const overallStartTime = hasEventListeners ? performance.now() : 0;
726
+ const isDirectResult = isResultLike(operationOrResult);
727
+ const operation = isDirectResult ? () => operationOrResult : operationOrResult;
728
+ const maxAttempts = Math.max(1, retryConfig?.attempts ?? 1);
729
+ const effectiveRetry = {
730
+ attempts: maxAttempts,
731
+ backoff: retryConfig?.backoff ?? DEFAULT_RETRY_CONFIG.backoff,
732
+ initialDelay: retryConfig?.initialDelay ?? DEFAULT_RETRY_CONFIG.initialDelay,
733
+ maxDelay: retryConfig?.maxDelay ?? DEFAULT_RETRY_CONFIG.maxDelay,
734
+ jitter: retryConfig?.jitter ?? DEFAULT_RETRY_CONFIG.jitter,
735
+ shouldRetry: retryConfig?.shouldRetry ?? DEFAULT_RETRY_CONFIG.shouldRetry,
736
+ onRetry: retryConfig?.onRetry ?? DEFAULT_RETRY_CONFIG.onRetry
737
+ };
738
+ if (onEvent) {
739
+ emitEvent({
740
+ type: "step_start",
741
+ workflowId,
742
+ stepId,
743
+ stepKey,
744
+ name: stepName,
745
+ description: stepDescription,
746
+ ts: Date.now(),
747
+ ...stepMetadata && { metadata: stepMetadata }
748
+ });
749
+ }
750
+ let lastResult;
751
+ for (let attempt = 1; attempt <= effectiveRetry.attempts; attempt++) {
752
+ const attemptStartTime = hasEventListeners ? performance.now() : 0;
753
+ try {
754
+ let result;
755
+ if (timeoutConfig) {
756
+ result = await executeWithTimeout(
757
+ operation,
758
+ timeoutConfig,
759
+ { name: stepName, key: stepKey, attempt },
760
+ _workflowSignal
761
+ );
762
+ } else {
763
+ result = await operation();
764
+ }
765
+ if (result.ok) {
766
+ const durationMs = performance.now() - overallStartTime;
767
+ emitEvent({
768
+ type: "step_success",
769
+ workflowId,
770
+ stepId,
771
+ stepKey,
772
+ name: stepName,
773
+ description: stepDescription,
774
+ ts: Date.now(),
775
+ durationMs,
776
+ ...stepMetadata && { metadata: stepMetadata }
777
+ });
778
+ if (explicitKey) {
779
+ emitEvent({
780
+ type: "step_complete",
781
+ workflowId,
782
+ stepKey: explicitKey,
783
+ name: stepName,
784
+ description: stepDescription,
785
+ ts: Date.now(),
786
+ durationMs,
787
+ result,
788
+ ...stepMetadata && { metadata: stepMetadata }
789
+ });
790
+ }
791
+ return result.value;
792
+ }
793
+ lastResult = result;
794
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(result.error, attempt)) {
795
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
796
+ emitEvent({
797
+ type: "step_retry",
798
+ workflowId,
799
+ stepId,
800
+ stepKey,
801
+ name: stepName,
802
+ ts: Date.now(),
803
+ attempt: attempt + 1,
804
+ maxAttempts: effectiveRetry.attempts,
805
+ delayMs: delay,
806
+ error: result.error,
807
+ ...stepMetadata && { metadata: stepMetadata },
808
+ diagnostics: buildStepErrorPayload(result.error, parsedOptions.errorMeta, "result", attempt, performance.now() - overallStartTime)
809
+ });
810
+ effectiveRetry.onRetry(result.error, attempt, delay);
811
+ await sleep(delay);
812
+ continue;
813
+ }
814
+ if (effectiveRetry.attempts > 1) {
815
+ emitEvent({
816
+ type: "step_retries_exhausted",
817
+ workflowId,
818
+ stepId,
819
+ stepKey,
820
+ name: stepName,
821
+ ts: Date.now(),
822
+ durationMs: performance.now() - overallStartTime,
823
+ attempts: attempt,
824
+ lastError: result.error,
825
+ ...stepMetadata && { metadata: stepMetadata },
826
+ diagnostics: buildStepErrorPayload(result.error, parsedOptions.errorMeta, "result", attempt, performance.now() - overallStartTime)
827
+ });
828
+ }
829
+ break;
830
+ } catch (thrown) {
831
+ const durationMs = performance.now() - attemptStartTime;
832
+ if (isTimeoutOptionMarker(thrown)) {
833
+ const timeoutMs = thrown.ms;
834
+ emitEvent({
835
+ type: "step_timeout",
836
+ workflowId,
837
+ stepId,
838
+ stepKey,
839
+ name: stepName,
840
+ ts: Date.now(),
841
+ timeoutMs,
842
+ attempt,
843
+ ...stepMetadata && { metadata: stepMetadata },
844
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt)
845
+ });
846
+ emitEvent({
847
+ type: "step_success",
848
+ workflowId,
849
+ stepId,
850
+ stepKey,
851
+ name: stepName,
852
+ description: stepDescription,
853
+ ts: Date.now(),
854
+ durationMs: performance.now() - overallStartTime,
855
+ ...stepMetadata && { metadata: stepMetadata }
856
+ });
857
+ if (explicitKey) {
858
+ emitEvent({
859
+ type: "step_complete",
860
+ workflowId,
861
+ stepKey: explicitKey,
862
+ name: stepName,
863
+ description: stepDescription,
864
+ ts: Date.now(),
865
+ durationMs: performance.now() - overallStartTime,
866
+ result: ok2(void 0),
867
+ ...stepMetadata && { metadata: stepMetadata }
868
+ });
869
+ }
870
+ return void 0;
871
+ }
872
+ if (isEarlyExitE(thrown)) {
873
+ emitEvent({
874
+ type: "step_aborted",
875
+ workflowId,
876
+ stepId,
877
+ stepKey,
878
+ name: stepName,
879
+ description: stepDescription,
880
+ ts: Date.now(),
881
+ durationMs,
882
+ ...stepMetadata && { metadata: stepMetadata }
883
+ });
884
+ throw thrown;
885
+ }
886
+ if (isStepTimeoutError(thrown)) {
887
+ const timeoutMeta = getStepTimeoutMeta(thrown);
888
+ const timeoutMs = timeoutConfig?.ms ?? timeoutMeta?.timeoutMs ?? 0;
889
+ emitEvent({
890
+ type: "step_timeout",
891
+ workflowId,
892
+ stepId,
893
+ stepKey,
894
+ name: stepName,
895
+ ts: Date.now(),
896
+ timeoutMs,
897
+ attempt,
898
+ ...stepMetadata && { metadata: stepMetadata },
899
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt)
900
+ });
901
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(thrown, attempt)) {
902
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
903
+ emitEvent({
904
+ type: "step_retry",
905
+ workflowId,
906
+ stepId,
907
+ stepKey,
908
+ name: stepName,
909
+ ts: Date.now(),
910
+ attempt: attempt + 1,
911
+ maxAttempts: effectiveRetry.attempts,
912
+ delayMs: delay,
913
+ error: thrown,
914
+ ...stepMetadata && { metadata: stepMetadata },
915
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, performance.now() - overallStartTime)
916
+ });
917
+ effectiveRetry.onRetry(thrown, attempt, delay);
918
+ await sleep(delay);
919
+ continue;
920
+ }
921
+ if (effectiveRetry.attempts > 1) {
922
+ emitEvent({
923
+ type: "step_retries_exhausted",
924
+ workflowId,
925
+ stepId,
926
+ stepKey,
927
+ name: stepName,
928
+ ts: Date.now(),
929
+ durationMs: performance.now() - overallStartTime,
930
+ attempts: attempt,
931
+ lastError: thrown,
932
+ ...stepMetadata && { metadata: stepMetadata },
933
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, performance.now() - overallStartTime)
934
+ });
935
+ }
936
+ const totalDurationMs3 = performance.now() - overallStartTime;
937
+ emitEvent({
938
+ type: "step_error",
939
+ workflowId,
940
+ stepId,
941
+ stepKey,
942
+ name: stepName,
943
+ description: stepDescription,
944
+ ts: Date.now(),
945
+ durationMs: totalDurationMs3,
946
+ error: thrown,
947
+ ...stepMetadata && { metadata: stepMetadata },
948
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, totalDurationMs3)
949
+ });
950
+ if (explicitKey) {
951
+ emitEvent({
952
+ type: "step_complete",
953
+ workflowId,
954
+ stepKey: explicitKey,
955
+ name: stepName,
956
+ description: stepDescription,
957
+ ts: Date.now(),
958
+ durationMs: totalDurationMs3,
959
+ result: err(thrown, { cause: thrown }),
960
+ meta: { origin: "throw", thrown },
961
+ ...stepMetadata && { metadata: stepMetadata }
962
+ });
963
+ }
964
+ onError?.(thrown, stepName, context);
965
+ throw earlyExit(thrown, { origin: "throw", thrown });
966
+ }
967
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(thrown, attempt)) {
968
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
969
+ emitEvent({
970
+ type: "step_retry",
971
+ workflowId,
972
+ stepId,
973
+ stepKey,
974
+ name: stepName,
975
+ ts: Date.now(),
976
+ attempt: attempt + 1,
977
+ maxAttempts: effectiveRetry.attempts,
978
+ delayMs: delay,
979
+ error: thrown,
980
+ ...stepMetadata && { metadata: stepMetadata },
981
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, performance.now() - overallStartTime)
982
+ });
983
+ effectiveRetry.onRetry(thrown, attempt, delay);
984
+ await sleep(delay);
985
+ continue;
986
+ }
987
+ if (effectiveRetry.attempts > 1 && !isStepTimeoutError(thrown)) {
988
+ emitEvent({
989
+ type: "step_retries_exhausted",
990
+ workflowId,
991
+ stepId,
992
+ stepKey,
993
+ name: stepName,
994
+ ts: Date.now(),
995
+ durationMs: performance.now() - overallStartTime,
996
+ attempts: attempt,
997
+ lastError: thrown,
998
+ ...stepMetadata && { metadata: stepMetadata },
999
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, performance.now() - overallStartTime)
1000
+ });
1001
+ }
1002
+ const totalDurationMs2 = performance.now() - overallStartTime;
1003
+ let mappedError;
1004
+ try {
1005
+ mappedError = effectiveCatchUnexpected(thrown);
1006
+ } catch (mapperError) {
1007
+ throw createMapperException(mapperError);
1008
+ }
1009
+ emitEvent({
1010
+ type: "step_error",
1011
+ workflowId,
1012
+ stepId,
1013
+ stepKey,
1014
+ name: stepName,
1015
+ description: stepDescription,
1016
+ ts: Date.now(),
1017
+ durationMs: totalDurationMs2,
1018
+ error: mappedError,
1019
+ ...stepMetadata && { metadata: stepMetadata },
1020
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, totalDurationMs2)
1021
+ });
1022
+ if (explicitKey) {
1023
+ emitEvent({
1024
+ type: "step_complete",
1025
+ workflowId,
1026
+ stepKey: explicitKey,
1027
+ name: stepName,
1028
+ description: stepDescription,
1029
+ ts: Date.now(),
1030
+ durationMs: totalDurationMs2,
1031
+ result: err(mappedError, { cause: thrown }),
1032
+ meta: { origin: "throw", thrown },
1033
+ ...stepMetadata && { metadata: stepMetadata }
1034
+ });
1035
+ }
1036
+ onError?.(mappedError, stepName, context);
1037
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1038
+ }
1039
+ }
1040
+ const errorResult = lastResult;
1041
+ const totalDurationMs = performance.now() - overallStartTime;
1042
+ const wrappedError = wrapForStep(errorResult.error, {
1043
+ origin: "result",
1044
+ resultCause: errorResult.cause
1045
+ });
1046
+ emitEvent({
1047
+ type: "step_error",
1048
+ workflowId,
1049
+ stepId,
1050
+ stepKey,
1051
+ name: stepName,
1052
+ description: stepDescription,
1053
+ ts: Date.now(),
1054
+ durationMs: totalDurationMs,
1055
+ error: wrappedError,
1056
+ ...stepMetadata && { metadata: stepMetadata },
1057
+ diagnostics: buildStepErrorPayload(errorResult.error, parsedOptions.errorMeta, "result", effectiveRetry.attempts, totalDurationMs)
1058
+ });
1059
+ if (explicitKey) {
1060
+ emitEvent({
1061
+ type: "step_complete",
1062
+ workflowId,
1063
+ stepKey: explicitKey,
1064
+ name: stepName,
1065
+ description: stepDescription,
1066
+ ts: Date.now(),
1067
+ durationMs: totalDurationMs,
1068
+ result: errorResult,
1069
+ meta: { origin: "result", resultCause: errorResult.cause },
1070
+ ...stepMetadata && { metadata: stepMetadata }
1071
+ });
1072
+ }
1073
+ onError?.(wrappedError, stepName, context);
1074
+ throw earlyExit(wrappedError, {
1075
+ origin: "result",
1076
+ resultCause: errorResult.cause
1077
+ });
1078
+ })();
1079
+ };
1080
+ stepFn.try = (id, operation, opts) => {
1081
+ if (typeof id !== "string" || id.length === 0) {
1082
+ throw new Error(
1083
+ '[awaitly] step.try() requires an explicit string ID as the first argument. Example: step.try("parse", () => JSON.parse(str), { error: "PARSE_ERROR" })'
1084
+ );
1085
+ }
1086
+ assertDeclared(id, "step");
1087
+ const mapToError = "error" in opts ? () => opts.error : opts.onError;
1088
+ if (opts.retry || opts.timeout) {
1089
+ return stepFn.retry(
1090
+ id,
1091
+ async () => {
1092
+ try {
1093
+ return ok2(await operation());
1094
+ } catch (cause) {
1095
+ return err(mapToError(cause), { cause });
1096
+ }
1097
+ },
1098
+ {
1099
+ attempts: opts.retry?.attempts ?? 1,
1100
+ ...opts.retry ?? {},
1101
+ key: opts.key,
1102
+ timeout: opts.timeout
1103
+ }
1104
+ );
1105
+ }
1106
+ const stepKey = opts.key ?? id;
1107
+ const stepName = id;
1108
+ const stepId = id;
1109
+ const hasEventListeners = onEvent;
1110
+ return (async () => {
1111
+ const startTime = hasEventListeners ? performance.now() : 0;
1112
+ if (onEvent) {
1113
+ emitEvent({
1114
+ type: "step_start",
1115
+ workflowId,
1116
+ stepId,
1117
+ stepKey,
1118
+ name: stepName,
1119
+ ts: Date.now()
1120
+ });
1121
+ }
1122
+ try {
1123
+ const value2 = await operation();
1124
+ const durationMs = performance.now() - startTime;
1125
+ emitEvent({
1126
+ type: "step_success",
1127
+ workflowId,
1128
+ stepId,
1129
+ stepKey,
1130
+ name: stepName,
1131
+ ts: Date.now(),
1132
+ durationMs
1133
+ });
1134
+ if (stepKey) {
1135
+ emitEvent({
1136
+ type: "step_complete",
1137
+ workflowId,
1138
+ stepKey,
1139
+ name: stepName,
1140
+ ts: Date.now(),
1141
+ durationMs,
1142
+ result: ok2(value2)
1143
+ });
1144
+ }
1145
+ return value2;
1146
+ } catch (error) {
1147
+ const mapped = mapToError(error);
1148
+ const durationMs = performance.now() - startTime;
1149
+ const wrappedError = wrapForStep(mapped, { origin: "throw", thrown: error });
1150
+ emitEvent({
1151
+ type: "step_error",
1152
+ workflowId,
1153
+ stepId,
1154
+ stepKey,
1155
+ name: stepName,
1156
+ ts: Date.now(),
1157
+ durationMs,
1158
+ error: wrappedError
1159
+ });
1160
+ if (stepKey) {
1161
+ emitEvent({
1162
+ type: "step_complete",
1163
+ workflowId,
1164
+ stepKey,
1165
+ name: stepName,
1166
+ ts: Date.now(),
1167
+ durationMs,
1168
+ result: err(mapped, { cause: error }),
1169
+ meta: { origin: "throw", thrown: error }
1170
+ });
1171
+ }
1172
+ onError?.(wrappedError, stepName, context);
1173
+ throw earlyExit(wrappedError, { origin: "throw", thrown: error });
1174
+ }
1175
+ })();
1176
+ };
1177
+ stepFn.fromResult = (id, operation, opts) => {
1178
+ if (typeof id !== "string" || id.length === 0) {
1179
+ throw new Error(
1180
+ '[awaitly] step.fromResult() requires an explicit string ID as the first argument. Example: step.fromResult("callProvider", () => callProvider(input), { onError: (e) => ({ type: "FAILED" }) })'
1181
+ );
1182
+ }
1183
+ assertDeclared(id, "step");
1184
+ const stepKey = opts.key ?? id;
1185
+ const stepName = id;
1186
+ const stepId = id;
1187
+ const mapToError = "error" in opts ? () => opts.error : opts.onError;
1188
+ const hasEventListeners = onEvent;
1189
+ return (async () => {
1190
+ const startTime = hasEventListeners ? performance.now() : 0;
1191
+ if (onEvent) {
1192
+ emitEvent({
1193
+ type: "step_start",
1194
+ workflowId,
1195
+ stepId,
1196
+ stepKey,
1197
+ name: stepName,
1198
+ ts: Date.now()
1199
+ });
1200
+ }
1201
+ const result = await operation();
1202
+ if (result.ok) {
1203
+ const durationMs = performance.now() - startTime;
1204
+ emitEvent({
1205
+ type: "step_success",
1206
+ workflowId,
1207
+ stepId,
1208
+ stepKey,
1209
+ name: stepName,
1210
+ ts: Date.now(),
1211
+ durationMs
1212
+ });
1213
+ if (stepKey) {
1214
+ emitEvent({
1215
+ type: "step_complete",
1216
+ workflowId,
1217
+ stepKey,
1218
+ name: stepName,
1219
+ ts: Date.now(),
1220
+ durationMs,
1221
+ result: ok2(result.value)
1222
+ });
1223
+ }
1224
+ return result.value;
1225
+ } else {
1226
+ const mapped = mapToError(result.error);
1227
+ const durationMs = performance.now() - startTime;
1228
+ const wrappedError = wrapForStep(mapped, {
1229
+ origin: "result",
1230
+ resultCause: result.error
1231
+ });
1232
+ emitEvent({
1233
+ type: "step_error",
1234
+ workflowId,
1235
+ stepId,
1236
+ stepKey,
1237
+ name: stepName,
1238
+ ts: Date.now(),
1239
+ durationMs,
1240
+ error: wrappedError
1241
+ });
1242
+ if (stepKey) {
1243
+ emitEvent({
1244
+ type: "step_complete",
1245
+ workflowId,
1246
+ stepKey,
1247
+ name: stepName,
1248
+ ts: Date.now(),
1249
+ durationMs,
1250
+ result: err(mapped, { cause: result.error }),
1251
+ meta: { origin: "result", resultCause: result.error }
1252
+ });
1253
+ }
1254
+ onError?.(wrappedError, stepName, context);
1255
+ throw earlyExit(wrappedError, {
1256
+ origin: "result",
1257
+ resultCause: result.error
1258
+ });
1259
+ }
1260
+ })();
1261
+ };
1262
+ stepFn.fromNullable = (id, operation, onNull, options2) => {
1263
+ if (typeof id !== "string" || id.length === 0) {
1264
+ throw new Error(
1265
+ '[awaitly] step.fromNullable() requires an explicit string ID as the first argument. Example: step.fromNullable("getUser", () => db.find(id), () => ({ type: "NOT_FOUND" }))'
1266
+ );
1267
+ }
1268
+ return stepFn(
1269
+ id,
1270
+ async () => {
1271
+ const value2 = await operation();
1272
+ return value2 != null ? ok2(value2) : err(onNull());
1273
+ },
1274
+ options2
1275
+ );
1276
+ };
1277
+ stepFn.retry = (id, operation, options2) => {
1278
+ if (typeof id !== "string" || id.length === 0) {
1279
+ throw new Error(
1280
+ '[awaitly] step.retry() requires an explicit string ID as the first argument. Example: step.retry("fetchData", () => fetchData(), { attempts: 3 })'
1281
+ );
1282
+ }
1283
+ return stepFn(id, operation, {
1284
+ key: options2.key ?? id,
1285
+ retry: {
1286
+ attempts: options2.attempts,
1287
+ backoff: options2.backoff,
1288
+ initialDelay: options2.initialDelay,
1289
+ maxDelay: options2.maxDelay,
1290
+ jitter: options2.jitter,
1291
+ shouldRetry: options2.shouldRetry,
1292
+ onRetry: options2.onRetry
1293
+ },
1294
+ timeout: options2.timeout
1295
+ });
1296
+ };
1297
+ stepFn.withTimeout = (id, operation, options2) => {
1298
+ if (typeof id !== "string" || id.length === 0) {
1299
+ throw new Error(
1300
+ '[awaitly] step.withTimeout() requires an explicit string ID as the first argument. Example: step.withTimeout("slowOp", () => slowOp(), { ms: 5000 })'
1301
+ );
1302
+ }
1303
+ return stepFn(
1304
+ id,
1305
+ operation,
1306
+ {
1307
+ key: options2.key ?? id,
1308
+ timeout: options2
1309
+ }
1310
+ );
1311
+ };
1312
+ stepFn.sleep = (id, duration, options2) => {
1313
+ if (typeof id !== "string" || id.length === 0) {
1314
+ throw new Error(
1315
+ '[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")'
1316
+ );
1317
+ }
1318
+ const d = typeof duration === "string" ? parseDurationString(duration) : duration;
1319
+ if (!d) {
1320
+ throw new Error(`step.sleep: invalid duration '${duration}'`);
1321
+ }
1322
+ const ms = d.millis;
1323
+ const userSignal = options2?.signal;
1324
+ return stepFn(
1325
+ id,
1326
+ async () => {
1327
+ if (_workflowSignal?.aborted || userSignal?.aborted) {
1328
+ const e = new Error("Sleep aborted");
1329
+ e.name = "AbortError";
1330
+ throw e;
1331
+ }
1332
+ return new Promise((resolve, reject) => {
1333
+ const state = { timeoutId: void 0 };
1334
+ const onAbort = () => {
1335
+ if (state.timeoutId) clearTimeout(state.timeoutId);
1336
+ const e = new Error("Sleep aborted");
1337
+ e.name = "AbortError";
1338
+ reject(e);
1339
+ };
1340
+ _workflowSignal?.addEventListener("abort", onAbort, { once: true });
1341
+ userSignal?.addEventListener("abort", onAbort, { once: true });
1342
+ state.timeoutId = setTimeout(() => {
1343
+ _workflowSignal?.removeEventListener("abort", onAbort);
1344
+ userSignal?.removeEventListener("abort", onAbort);
1345
+ resolve(ok2(void 0));
1346
+ }, ms);
1347
+ });
1348
+ },
1349
+ {
1350
+ key: options2?.key ?? id,
1351
+ description: options2?.description
1352
+ }
1353
+ );
1354
+ };
1355
+ stepFn.all = ((...args) => {
1356
+ if (typeof args[0] !== "string") {
1357
+ throw new TypeError(
1358
+ "step.all(name, ...): first argument must be a string (step name). Example: step.all('Fetch data', { user: () => fetchUser(), posts: () => fetchPosts() })"
1359
+ );
1360
+ }
1361
+ const name = args[0];
1362
+ const second = args[1];
1363
+ if (typeof second === "function") {
1364
+ return executeParallelArray2(name, second);
1365
+ }
1366
+ if (second && typeof second === "object" && !Array.isArray(second)) {
1367
+ const rawOperations = second;
1368
+ const normalizedOperations = normalizeParallelOperations2(rawOperations);
1369
+ return executeParallelNamed2(normalizedOperations, { name });
1370
+ }
1371
+ throw new TypeError(
1372
+ "step.all(name, ...): second argument must be a function (array form) or an object of operations (object form)."
1373
+ );
1374
+ });
1375
+ stepFn.race = (name, operation) => {
1376
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1377
+ return (async () => {
1378
+ const startTime = performance.now();
1379
+ let scopeEnded = false;
1380
+ const scopeEntry = { scopeId, type: "race", winnerId: void 0 };
1381
+ activeScopeStack.push(scopeEntry);
1382
+ const emitScopeEnd = () => {
1383
+ if (scopeEnded) return;
1384
+ scopeEnded = true;
1385
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
1386
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
1387
+ emitEvent({
1388
+ type: "scope_end",
1389
+ workflowId,
1390
+ scopeId,
1391
+ ts: Date.now(),
1392
+ durationMs: performance.now() - startTime,
1393
+ winnerId: scopeEntry.winnerId
1394
+ });
1395
+ };
1396
+ emitEvent({
1397
+ type: "scope_start",
1398
+ workflowId,
1399
+ scopeId,
1400
+ scopeType: "race",
1401
+ name,
1402
+ ts: Date.now()
1403
+ });
1404
+ try {
1405
+ const result = await operation();
1406
+ emitScopeEnd();
1407
+ if (!result.ok) {
1408
+ onError?.(result.error, name, context);
1409
+ throw earlyExit(result.error, {
1410
+ origin: "result",
1411
+ resultCause: result.cause
1412
+ });
1413
+ }
1414
+ return result.value;
1415
+ } catch (error) {
1416
+ emitScopeEnd();
1417
+ throw error;
1418
+ }
1419
+ })();
1420
+ };
1421
+ stepFn.if = (id, conditionLabel, condition) => {
1422
+ assertDeclared(id, "decision");
1423
+ const value2 = condition();
1424
+ emitEvent({
1425
+ type: "decision",
1426
+ workflowId,
1427
+ decisionId: id,
1428
+ label: conditionLabel,
1429
+ branch: value2 ? "then" : "else",
1430
+ value: value2,
1431
+ ts: Date.now()
1432
+ });
1433
+ return value2;
1434
+ };
1435
+ stepFn.label = stepFn.if;
1436
+ stepFn.branch = async (id, options2) => {
1437
+ const { condition, then: thenFn, else: elseFn } = options2;
1438
+ assertDeclared(id, "decision");
1439
+ const conditionResult = condition();
1440
+ const branch = conditionResult ? "then" : "else";
1441
+ const startTime = performance.now();
1442
+ emitEvent({
1443
+ type: "decision",
1444
+ workflowId,
1445
+ decisionId: id,
1446
+ label: options2.conditionLabel,
1447
+ branch,
1448
+ value: conditionResult,
1449
+ phase: "start",
1450
+ ts: Date.now()
1451
+ });
1452
+ const emitEnd = () => {
1453
+ emitEvent({
1454
+ type: "decision",
1455
+ workflowId,
1456
+ decisionId: id,
1457
+ label: options2.conditionLabel,
1458
+ branch,
1459
+ value: conditionResult,
1460
+ phase: "end",
1461
+ durationMs: performance.now() - startTime,
1462
+ ts: Date.now()
1463
+ });
1464
+ };
1465
+ try {
1466
+ if (conditionResult) {
1467
+ return await thenFn();
1468
+ } else if (elseFn) {
1469
+ return await elseFn();
1470
+ }
1471
+ return void 0;
1472
+ } finally {
1473
+ emitEnd();
1474
+ }
1475
+ };
1476
+ stepFn.arm = (fn2, errors) => {
1477
+ return { fn: fn2, errors };
1478
+ };
1479
+ stepFn.forEach = async (_id, items, options2) => {
1480
+ const results = [];
1481
+ const maxIterations = options2.maxIterations;
1482
+ let index = 0;
1483
+ const isRunForm = "run" in options2;
1484
+ const asyncItems = Symbol.asyncIterator in items ? items : (async function* () {
1485
+ yield* items;
1486
+ })();
1487
+ for await (const item of asyncItems) {
1488
+ if (maxIterations !== void 0 && index >= maxIterations) {
1489
+ break;
1490
+ }
1491
+ let result;
1492
+ if (isRunForm) {
1493
+ const runOptions = options2;
1494
+ result = await runOptions.run(item, index);
1495
+ } else {
1496
+ const itemOptions = options2;
1497
+ result = await itemOptions.item.handler(item, index, stepFn);
1498
+ }
1499
+ results.push(result);
1500
+ index++;
1501
+ }
1502
+ return results;
1503
+ };
1504
+ stepFn.item = (handler) => {
1505
+ return {
1506
+ __forEachItemHandler: true,
1507
+ handler
1508
+ };
1509
+ };
1510
+ stepFn.dep = (_name, fn2) => {
1511
+ return fn2;
1512
+ };
1513
+ stepFn.workflow = (id, getter, options2) => {
1514
+ return stepFn(id, getter, options2);
1515
+ };
1516
+ stepFn.map = async (id, items, mapper, options2) => {
1517
+ const concurrency = options2?.concurrency ?? items.length;
1518
+ return stepFn(
1519
+ id,
1520
+ () => {
1521
+ if (concurrency >= items.length) {
1522
+ return allAsync(items.map((item, index) => mapper(item, index)));
1523
+ } else {
1524
+ return (async () => {
1525
+ const results = [];
1526
+ for (let i = 0; i < items.length; i += concurrency) {
1527
+ const batch = items.slice(i, i + concurrency);
1528
+ const batchResult = await allAsync(
1529
+ batch.map((item, batchIndex) => mapper(item, i + batchIndex))
1530
+ );
1531
+ if (!batchResult.ok) {
1532
+ return batchResult;
1533
+ }
1534
+ results.push(...batchResult.value);
1535
+ }
1536
+ return ok2(results);
1537
+ })();
1538
+ }
1539
+ },
1540
+ { key: options2?.key }
1541
+ );
1542
+ };
1543
+ stepFn.withFallback = (id, operation, options2) => {
1544
+ if (typeof id !== "string" || id.length === 0) {
1545
+ throw new Error(
1546
+ '[awaitly] step.withFallback() requires an explicit string ID as the first argument. Example: step.withFallback("getUser", () => fetchUser(id), { fallback: () => fetchFromCache(id) })'
1547
+ );
1548
+ }
1549
+ assertDeclared(id, "step");
1550
+ const stepKey = options2.key ?? id;
1551
+ const stepName = id;
1552
+ const stepId = generateStepId(stepKey);
1553
+ const hasEventListeners = onEvent;
1554
+ return (async () => {
1555
+ const startTime = hasEventListeners ? performance.now() : 0;
1556
+ if (onEvent) {
1557
+ emitEvent({
1558
+ type: "step_start",
1559
+ workflowId,
1560
+ stepId,
1561
+ stepKey,
1562
+ name: stepName,
1563
+ ts: Date.now()
1564
+ });
1565
+ }
1566
+ let primaryResult;
1567
+ try {
1568
+ primaryResult = await operation();
1569
+ } catch (thrown) {
1570
+ if (isEarlyExitE(thrown)) {
1571
+ emitEvent({
1572
+ type: "step_aborted",
1573
+ workflowId,
1574
+ stepId,
1575
+ stepKey,
1576
+ name: stepName,
1577
+ ts: Date.now(),
1578
+ durationMs: performance.now() - startTime
1579
+ });
1580
+ throw thrown;
1581
+ }
1582
+ let mappedError;
1583
+ try {
1584
+ mappedError = effectiveCatchUnexpected(thrown);
1585
+ } catch (mapperError) {
1586
+ throw createMapperException(mapperError);
1587
+ }
1588
+ if (options2.on !== void 0 && options2.on !== mappedError) {
1589
+ const durationMs2 = performance.now() - startTime;
1590
+ emitEvent({
1591
+ type: "step_error",
1592
+ workflowId,
1593
+ stepId,
1594
+ stepKey,
1595
+ name: stepName,
1596
+ ts: Date.now(),
1597
+ durationMs: durationMs2,
1598
+ error: mappedError
1599
+ });
1600
+ if (stepKey) {
1601
+ emitEvent({
1602
+ type: "step_complete",
1603
+ workflowId,
1604
+ stepKey,
1605
+ name: stepName,
1606
+ ts: Date.now(),
1607
+ durationMs: durationMs2,
1608
+ result: err(mappedError, { cause: thrown }),
1609
+ meta: { origin: "throw", thrown }
1610
+ });
1611
+ }
1612
+ onError?.(mappedError, stepName, context);
1613
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1614
+ }
1615
+ let fallbackResultFromThrow;
1616
+ try {
1617
+ fallbackResultFromThrow = await options2.fallback();
1618
+ } catch (fallbackThrown) {
1619
+ if (isEarlyExitE(fallbackThrown)) {
1620
+ emitEvent({
1621
+ type: "step_aborted",
1622
+ workflowId,
1623
+ stepId,
1624
+ stepKey,
1625
+ name: stepName,
1626
+ ts: Date.now(),
1627
+ durationMs: performance.now() - startTime
1628
+ });
1629
+ throw fallbackThrown;
1630
+ }
1631
+ let fallbackMappedError;
1632
+ try {
1633
+ fallbackMappedError = effectiveCatchUnexpected(fallbackThrown);
1634
+ } catch (mapperError) {
1635
+ throw createMapperException(mapperError);
1636
+ }
1637
+ const durationMs2 = performance.now() - startTime;
1638
+ emitEvent({
1639
+ type: "step_error",
1640
+ workflowId,
1641
+ stepId,
1642
+ stepKey,
1643
+ name: stepName,
1644
+ ts: Date.now(),
1645
+ durationMs: durationMs2,
1646
+ error: fallbackMappedError
1647
+ });
1648
+ if (stepKey) {
1649
+ emitEvent({
1650
+ type: "step_complete",
1651
+ workflowId,
1652
+ stepKey,
1653
+ name: stepName,
1654
+ ts: Date.now(),
1655
+ durationMs: durationMs2,
1656
+ result: err(fallbackMappedError, { cause: fallbackThrown }),
1657
+ meta: { origin: "throw", thrown: fallbackThrown }
1658
+ });
1659
+ }
1660
+ onError?.(fallbackMappedError, stepName, context);
1661
+ throw earlyExit(fallbackMappedError, { origin: "throw", thrown: fallbackThrown });
1662
+ }
1663
+ if (fallbackResultFromThrow.ok) {
1664
+ const durationMs2 = performance.now() - startTime;
1665
+ emitEvent({
1666
+ type: "step_success",
1667
+ workflowId,
1668
+ stepId,
1669
+ stepKey,
1670
+ name: stepName,
1671
+ ts: Date.now(),
1672
+ durationMs: durationMs2
1673
+ });
1674
+ if (stepKey) {
1675
+ emitEvent({
1676
+ type: "step_complete",
1677
+ workflowId,
1678
+ stepKey,
1679
+ name: stepName,
1680
+ ts: Date.now(),
1681
+ durationMs: durationMs2,
1682
+ result: fallbackResultFromThrow,
1683
+ meta: { origin: "fallback", fallbackUsed: true, fallbackReason: String(mappedError) }
1684
+ });
1685
+ }
1686
+ return fallbackResultFromThrow.value;
1687
+ } else {
1688
+ const durationMs2 = performance.now() - startTime;
1689
+ const wrappedError2 = wrapForStep(fallbackResultFromThrow.error, {
1690
+ origin: "result",
1691
+ resultCause: fallbackResultFromThrow.cause
1692
+ });
1693
+ emitEvent({
1694
+ type: "step_error",
1695
+ workflowId,
1696
+ stepId,
1697
+ stepKey,
1698
+ name: stepName,
1699
+ ts: Date.now(),
1700
+ durationMs: durationMs2,
1701
+ error: wrappedError2
1702
+ });
1703
+ if (stepKey) {
1704
+ emitEvent({
1705
+ type: "step_complete",
1706
+ workflowId,
1707
+ stepKey,
1708
+ name: stepName,
1709
+ ts: Date.now(),
1710
+ durationMs: durationMs2,
1711
+ result: fallbackResultFromThrow,
1712
+ meta: { origin: "result", resultCause: fallbackResultFromThrow.cause }
1713
+ });
1714
+ }
1715
+ onError?.(wrappedError2, stepName, context);
1716
+ throw earlyExit(wrappedError2, {
1717
+ origin: "result",
1718
+ resultCause: fallbackResultFromThrow.cause
1719
+ });
1720
+ }
1721
+ }
1722
+ if (primaryResult.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: primaryResult
1742
+ });
1743
+ }
1744
+ return primaryResult.value;
1745
+ }
1746
+ const primaryError = primaryResult.error;
1747
+ if (options2.on !== void 0 && options2.on !== primaryError) {
1748
+ const durationMs2 = performance.now() - startTime;
1749
+ const wrappedError2 = wrapForStep(primaryError, {
1750
+ origin: "result",
1751
+ resultCause: primaryResult.cause
1752
+ });
1753
+ emitEvent({
1754
+ type: "step_error",
1755
+ workflowId,
1756
+ stepId,
1757
+ stepKey,
1758
+ name: stepName,
1759
+ ts: Date.now(),
1760
+ durationMs: durationMs2,
1761
+ error: wrappedError2
1762
+ });
1763
+ if (stepKey) {
1764
+ emitEvent({
1765
+ type: "step_complete",
1766
+ workflowId,
1767
+ stepKey,
1768
+ name: stepName,
1769
+ ts: Date.now(),
1770
+ durationMs: durationMs2,
1771
+ result: primaryResult,
1772
+ meta: { origin: "result", resultCause: primaryResult.cause }
1773
+ });
1774
+ }
1775
+ onError?.(wrappedError2, stepName, context);
1776
+ throw earlyExit(wrappedError2, {
1777
+ origin: "result",
1778
+ resultCause: primaryResult.cause
1779
+ });
1780
+ }
1781
+ let fallbackResult;
1782
+ try {
1783
+ fallbackResult = await options2.fallback();
1784
+ } catch (thrown) {
1785
+ if (isEarlyExitE(thrown)) {
1786
+ emitEvent({
1787
+ type: "step_aborted",
1788
+ workflowId,
1789
+ stepId,
1790
+ stepKey,
1791
+ name: stepName,
1792
+ ts: Date.now(),
1793
+ durationMs: performance.now() - startTime
1794
+ });
1795
+ throw thrown;
1796
+ }
1797
+ let mappedError;
1798
+ try {
1799
+ mappedError = effectiveCatchUnexpected(thrown);
1800
+ } catch (mapperError) {
1801
+ throw createMapperException(mapperError);
1802
+ }
1803
+ const durationMs2 = performance.now() - startTime;
1804
+ emitEvent({
1805
+ type: "step_error",
1806
+ workflowId,
1807
+ stepId,
1808
+ stepKey,
1809
+ name: stepName,
1810
+ ts: Date.now(),
1811
+ durationMs: durationMs2,
1812
+ error: mappedError
1813
+ });
1814
+ if (stepKey) {
1815
+ emitEvent({
1816
+ type: "step_complete",
1817
+ workflowId,
1818
+ stepKey,
1819
+ name: stepName,
1820
+ ts: Date.now(),
1821
+ durationMs: durationMs2,
1822
+ result: err(mappedError, { cause: thrown }),
1823
+ meta: { origin: "throw", thrown }
1824
+ });
1825
+ }
1826
+ onError?.(mappedError, stepName, context);
1827
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1828
+ }
1829
+ if (fallbackResult.ok) {
1830
+ const durationMs2 = performance.now() - startTime;
1831
+ emitEvent({
1832
+ type: "step_success",
1833
+ workflowId,
1834
+ stepId,
1835
+ stepKey,
1836
+ name: stepName,
1837
+ ts: Date.now(),
1838
+ durationMs: durationMs2
1839
+ });
1840
+ if (stepKey) {
1841
+ emitEvent({
1842
+ type: "step_complete",
1843
+ workflowId,
1844
+ stepKey,
1845
+ name: stepName,
1846
+ ts: Date.now(),
1847
+ durationMs: durationMs2,
1848
+ result: fallbackResult,
1849
+ meta: { origin: "fallback", fallbackUsed: true, fallbackReason: String(primaryError) }
1850
+ });
1851
+ }
1852
+ return fallbackResult.value;
1853
+ }
1854
+ const durationMs = performance.now() - startTime;
1855
+ const wrappedError = wrapForStep(fallbackResult.error, {
1856
+ origin: "result",
1857
+ resultCause: fallbackResult.cause
1858
+ });
1859
+ emitEvent({
1860
+ type: "step_error",
1861
+ workflowId,
1862
+ stepId,
1863
+ stepKey,
1864
+ name: stepName,
1865
+ ts: Date.now(),
1866
+ durationMs,
1867
+ error: wrappedError
1868
+ });
1869
+ if (stepKey) {
1870
+ emitEvent({
1871
+ type: "step_complete",
1872
+ workflowId,
1873
+ stepKey,
1874
+ name: stepName,
1875
+ ts: Date.now(),
1876
+ durationMs,
1877
+ result: fallbackResult,
1878
+ meta: { origin: "result", resultCause: fallbackResult.cause }
1879
+ });
1880
+ }
1881
+ onError?.(wrappedError, stepName, context);
1882
+ throw earlyExit(wrappedError, {
1883
+ origin: "result",
1884
+ resultCause: fallbackResult.cause
1885
+ });
1886
+ })();
1887
+ };
1888
+ stepFn.withResource = (id, options2) => {
1889
+ if (typeof id !== "string" || id.length === 0) {
1890
+ throw new Error(
1891
+ '[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() })'
1892
+ );
1893
+ }
1894
+ assertDeclared(id, "step");
1895
+ const stepKey = id;
1896
+ const stepName = id;
1897
+ const stepId = generateStepId(stepKey);
1898
+ const hasEventListeners = onEvent;
1899
+ return (async () => {
1900
+ const startTime = hasEventListeners ? performance.now() : 0;
1901
+ if (onEvent) {
1902
+ emitEvent({
1903
+ type: "step_start",
1904
+ workflowId,
1905
+ stepId,
1906
+ stepKey,
1907
+ name: stepName,
1908
+ ts: Date.now()
1909
+ });
1910
+ }
1911
+ let acquireResult;
1912
+ try {
1913
+ acquireResult = await options2.acquire();
1914
+ } catch (thrown) {
1915
+ if (isEarlyExitE(thrown)) {
1916
+ emitEvent({
1917
+ type: "step_aborted",
1918
+ workflowId,
1919
+ stepId,
1920
+ stepKey,
1921
+ name: stepName,
1922
+ ts: Date.now(),
1923
+ durationMs: performance.now() - startTime
1924
+ });
1925
+ throw thrown;
1926
+ }
1927
+ let mappedError;
1928
+ try {
1929
+ mappedError = effectiveCatchUnexpected(thrown);
1930
+ } catch (mapperError) {
1931
+ throw createMapperException(mapperError);
1932
+ }
1933
+ const durationMs2 = performance.now() - startTime;
1934
+ emitEvent({
1935
+ type: "step_error",
1936
+ workflowId,
1937
+ stepId,
1938
+ stepKey,
1939
+ name: stepName,
1940
+ ts: Date.now(),
1941
+ durationMs: durationMs2,
1942
+ error: mappedError
1943
+ });
1944
+ if (stepKey) {
1945
+ emitEvent({
1946
+ type: "step_complete",
1947
+ workflowId,
1948
+ stepKey,
1949
+ name: stepName,
1950
+ ts: Date.now(),
1951
+ durationMs: durationMs2,
1952
+ result: err(mappedError, { cause: thrown }),
1953
+ meta: { origin: "throw", thrown }
1954
+ });
1955
+ }
1956
+ onError?.(mappedError, stepName, context);
1957
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1958
+ }
1959
+ if (!acquireResult.ok) {
1960
+ const durationMs2 = performance.now() - startTime;
1961
+ const wrappedError2 = wrapForStep(acquireResult.error, {
1962
+ origin: "result",
1963
+ resultCause: acquireResult.cause
1964
+ });
1965
+ emitEvent({
1966
+ type: "step_error",
1967
+ workflowId,
1968
+ stepId,
1969
+ stepKey,
1970
+ name: stepName,
1971
+ ts: Date.now(),
1972
+ durationMs: durationMs2,
1973
+ error: wrappedError2
1974
+ });
1975
+ if (stepKey) {
1976
+ emitEvent({
1977
+ type: "step_complete",
1978
+ workflowId,
1979
+ stepKey,
1980
+ name: stepName,
1981
+ ts: Date.now(),
1982
+ durationMs: durationMs2,
1983
+ result: acquireResult,
1984
+ meta: { origin: "result", resultCause: acquireResult.cause }
1985
+ });
1986
+ }
1987
+ onError?.(wrappedError2, stepName, context);
1988
+ throw earlyExit(wrappedError2, {
1989
+ origin: "result",
1990
+ resultCause: acquireResult.cause
1991
+ });
1992
+ }
1993
+ const resource = acquireResult.value;
1994
+ let useResult;
1995
+ let useThrown;
1996
+ let useThrewNonResult = false;
1997
+ try {
1998
+ useResult = await options2.use(resource);
1999
+ } catch (thrown) {
2000
+ if (isEarlyExitE(thrown)) {
2001
+ try {
2002
+ await options2.release(resource);
2003
+ } catch (releaseErr) {
2004
+ console.warn(
2005
+ `[awaitly] step.withResource("${id}"): release threw after earlyExit:`,
2006
+ releaseErr
2007
+ );
2008
+ }
2009
+ throw thrown;
2010
+ }
2011
+ useThrown = thrown;
2012
+ useThrewNonResult = true;
2013
+ }
2014
+ try {
2015
+ await options2.release(resource);
2016
+ } catch (releaseErr) {
2017
+ console.warn(
2018
+ `[awaitly] step.withResource("${id}"): release threw:`,
2019
+ releaseErr
2020
+ );
2021
+ }
2022
+ if (useThrewNonResult) {
2023
+ let mappedError;
2024
+ try {
2025
+ mappedError = effectiveCatchUnexpected(useThrown);
2026
+ } catch (mapperError) {
2027
+ throw createMapperException(mapperError);
2028
+ }
2029
+ const durationMs2 = performance.now() - startTime;
2030
+ emitEvent({
2031
+ type: "step_error",
2032
+ workflowId,
2033
+ stepId,
2034
+ stepKey,
2035
+ name: stepName,
2036
+ ts: Date.now(),
2037
+ durationMs: durationMs2,
2038
+ error: mappedError
2039
+ });
2040
+ if (stepKey) {
2041
+ emitEvent({
2042
+ type: "step_complete",
2043
+ workflowId,
2044
+ stepKey,
2045
+ name: stepName,
2046
+ ts: Date.now(),
2047
+ durationMs: durationMs2,
2048
+ result: err(mappedError, { cause: useThrown }),
2049
+ meta: { origin: "throw", thrown: useThrown }
2050
+ });
2051
+ }
2052
+ onError?.(mappedError, stepName, context);
2053
+ throw earlyExit(mappedError, { origin: "throw", thrown: useThrown });
2054
+ }
2055
+ const result = useResult;
2056
+ if (result.ok) {
2057
+ const durationMs2 = performance.now() - startTime;
2058
+ emitEvent({
2059
+ type: "step_success",
2060
+ workflowId,
2061
+ stepId,
2062
+ stepKey,
2063
+ name: stepName,
2064
+ ts: Date.now(),
2065
+ durationMs: durationMs2
2066
+ });
2067
+ if (stepKey) {
2068
+ emitEvent({
2069
+ type: "step_complete",
2070
+ workflowId,
2071
+ stepKey,
2072
+ name: stepName,
2073
+ ts: Date.now(),
2074
+ durationMs: durationMs2,
2075
+ result
2076
+ });
2077
+ }
2078
+ return result.value;
2079
+ }
2080
+ const durationMs = performance.now() - startTime;
2081
+ const wrappedError = wrapForStep(result.error, {
2082
+ origin: "result",
2083
+ resultCause: result.cause
2084
+ });
2085
+ emitEvent({
2086
+ type: "step_error",
2087
+ workflowId,
2088
+ stepId,
2089
+ stepKey,
2090
+ name: stepName,
2091
+ ts: Date.now(),
2092
+ durationMs,
2093
+ error: wrappedError
2094
+ });
2095
+ if (stepKey) {
2096
+ emitEvent({
2097
+ type: "step_complete",
2098
+ workflowId,
2099
+ stepKey,
2100
+ name: stepName,
2101
+ ts: Date.now(),
2102
+ durationMs,
2103
+ result,
2104
+ meta: { origin: "result", resultCause: result.cause }
2105
+ });
2106
+ }
2107
+ onError?.(wrappedError, stepName, context);
2108
+ throw earlyExit(wrappedError, {
2109
+ origin: "result",
2110
+ resultCause: result.cause
2111
+ });
2112
+ })();
2113
+ };
2114
+ const step = stepFn;
2115
+ const value = await fn({ step });
2116
+ if (process.env.NODE_ENV !== "production" && value !== null && typeof value === "object" && "ok" in value && typeof value.ok === "boolean") {
2117
+ const maybeResult = value;
2118
+ if (maybeResult.ok === true && "value" in maybeResult || maybeResult.ok === false && "error" in maybeResult) {
2119
+ console.warn(
2120
+ `awaitly: Workflow executor returned a Result-like object. Return raw values, not ok() or err().
2121
+
2122
+ Incorrect: return ok({ data });
2123
+ Correct: return { data };
2124
+
2125
+ See: https://jagreehal.github.io/awaitly/guides/troubleshooting/#returning-ok-from-workflow-executor-double-wrapping`
2126
+ );
2127
+ }
2128
+ }
2129
+ return ok2(value);
2130
+ } catch (error) {
2131
+ if (isMapperException(error)) {
2132
+ throw error.thrown;
2133
+ }
2134
+ if (isEarlyExitE(error)) {
2135
+ const originalCause = error.meta.origin === "throw" ? error.meta.thrown : error.meta.origin === "result" ? error.meta.resultCause : void 0;
2136
+ return err(error.error, { cause: originalCause });
2137
+ }
2138
+ const mapped = effectiveCatchUnexpected(error);
2139
+ onError?.(mapped, "unexpected", context);
2140
+ return err(mapped, { cause: error });
2141
+ }
2142
+ }
2143
+ var runStrict = (fn, options) => {
2144
+ return runFn(fn, options);
2145
+ };
2146
+ var run = /* @__PURE__ */ Object.assign(runFn, { strict: runStrict });
2147
+ async function allAsync(results) {
2148
+ if (results.length === 0) {
2149
+ return ok2([]);
2150
+ }
2151
+ return new Promise((resolve) => {
2152
+ let settled = false;
2153
+ let pendingCount = results.length;
2154
+ const values = new Array(results.length);
2155
+ for (let i = 0; i < results.length; i++) {
2156
+ const index = i;
2157
+ Promise.resolve(results[index]).catch((reason) => err(
2158
+ { type: "PROMISE_REJECTED", cause: reason },
2159
+ { cause: { type: "PROMISE_REJECTION", reason } }
2160
+ )).then((result) => {
2161
+ if (settled) return;
2162
+ if (!result.ok) {
2163
+ settled = true;
2164
+ resolve(result);
2165
+ return;
2166
+ }
2167
+ values[index] = result.value;
2168
+ pendingCount--;
2169
+ if (pendingCount === 0) {
2170
+ resolve(ok2(values));
2171
+ }
2172
+ });
2173
+ }
2174
+ });
2175
+ }
2176
+
2177
+ // src/streaming/types.ts
2178
+ var STREAM_WRITE_ERROR = "STREAM_WRITE_ERROR";
2179
+ var STREAM_READ_ERROR = "STREAM_READ_ERROR";
2180
+ var STREAM_CLOSE_ERROR = "STREAM_CLOSE_ERROR";
2181
+ var STREAM_ENDED = "STREAM_ENDED";
2182
+ function streamWriteError(reason, message, cause) {
2183
+ return {
2184
+ type: STREAM_WRITE_ERROR,
2185
+ reason,
2186
+ message,
2187
+ ...cause !== void 0 ? { cause } : {}
2188
+ };
2189
+ }
2190
+ function streamReadError(reason, message, cause) {
2191
+ return {
2192
+ type: STREAM_READ_ERROR,
2193
+ reason,
2194
+ message,
2195
+ ...cause !== void 0 ? { cause } : {}
2196
+ };
2197
+ }
2198
+ function streamCloseError(reason, message, cause) {
2199
+ return {
2200
+ type: STREAM_CLOSE_ERROR,
2201
+ reason,
2202
+ message,
2203
+ ...cause !== void 0 ? { cause } : {}
2204
+ };
2205
+ }
2206
+ function streamEnded(finalPosition) {
2207
+ return {
2208
+ type: STREAM_ENDED,
2209
+ finalPosition
2210
+ };
2211
+ }
2212
+
2213
+ // src/streaming/backpressure.ts
2214
+ function createBackpressureController(options = {}) {
2215
+ const highWaterMark = options.highWaterMark ?? 16;
2216
+ const lowWaterMark = options.lowWaterMark ?? Math.floor(highWaterMark / 2);
2217
+ const onStateChange = options.onStateChange;
2218
+ let state = "flowing";
2219
+ let bufferedCount = 0;
2220
+ let drainResolvers = [];
2221
+ function updateState(newState) {
2222
+ if (state !== newState) {
2223
+ state = newState;
2224
+ onStateChange?.(newState);
2225
+ if (newState === "flowing" && drainResolvers.length > 0) {
2226
+ const resolvers = drainResolvers;
2227
+ drainResolvers = [];
2228
+ for (const resolve of resolvers) {
2229
+ resolve();
2230
+ }
2231
+ }
2232
+ }
2233
+ }
2234
+ function checkState() {
2235
+ if (state === "flowing" && bufferedCount >= highWaterMark) {
2236
+ updateState("paused");
2237
+ } else if (state === "paused" && bufferedCount <= lowWaterMark) {
2238
+ updateState("flowing");
2239
+ }
2240
+ }
2241
+ return {
2242
+ get state() {
2243
+ return state;
2244
+ },
2245
+ get bufferedCount() {
2246
+ return bufferedCount;
2247
+ },
2248
+ get highWaterMark() {
2249
+ return highWaterMark;
2250
+ },
2251
+ get lowWaterMark() {
2252
+ return lowWaterMark;
2253
+ },
2254
+ increment() {
2255
+ bufferedCount++;
2256
+ checkState();
2257
+ },
2258
+ decrement() {
2259
+ if (bufferedCount > 0) {
2260
+ bufferedCount--;
2261
+ checkState();
2262
+ }
2263
+ },
2264
+ setCount(count) {
2265
+ bufferedCount = Math.max(0, count);
2266
+ checkState();
2267
+ },
2268
+ waitForDrain() {
2269
+ if (state === "flowing") {
2270
+ return Promise.resolve();
2271
+ }
2272
+ return new Promise((resolve) => {
2273
+ drainResolvers.push(resolve);
2274
+ });
2275
+ },
2276
+ reset() {
2277
+ bufferedCount = 0;
2278
+ drainResolvers = [];
2279
+ updateState("flowing");
2280
+ }
2281
+ };
2282
+ }
2283
+
2284
+ // src/workflow/guards.ts
2285
+ function isStepComplete(event) {
2286
+ return event.type === "step_complete";
2287
+ }
2288
+ function isWorkflowCancelled(error) {
2289
+ return typeof error === "object" && error !== null && error.type === "WORKFLOW_CANCELLED";
2290
+ }
2291
+
2292
+ // src/workflow/resume-state.ts
2293
+ function createResumeStateCollector() {
2294
+ const steps = /* @__PURE__ */ new Map();
2295
+ return {
2296
+ handleEvent: (event) => {
2297
+ if (isStepComplete(event)) {
2298
+ steps.set(event.stepKey, { result: event.result, meta: event.meta });
2299
+ }
2300
+ },
2301
+ getResumeState: () => ({ steps: new Map(steps) }),
2302
+ clear: () => steps.clear()
2303
+ };
2304
+ }
2305
+
2306
+ // src/workflow/cache-encoding.ts
2307
+ function isCachedErrorCause(cause) {
2308
+ return typeof cause === "object" && cause !== null && cause.__cachedMeta === true;
2309
+ }
2310
+ function encodeCachedError(error, meta, originalCause) {
2311
+ return err(error, {
2312
+ cause: { __cachedMeta: true, originalCause, meta }
2313
+ });
2314
+ }
2315
+ function decodeCachedMeta(cause) {
2316
+ if (isCachedErrorCause(cause)) {
2317
+ return cause.meta;
2318
+ }
2319
+ return { origin: "result", resultCause: cause };
2320
+ }
2321
+
2322
+ // src/workflow/validation.ts
2323
+ async function validateInput(schema, input) {
2324
+ const result = schema["~standard"].validate(input);
2325
+ const resolved = result instanceof Promise ? await result : result;
2326
+ if (resolved.issues) {
2327
+ return err({
2328
+ type: "INPUT_VALIDATION_ERROR",
2329
+ issues: resolved.issues.map((i) => ({
2330
+ message: i.message,
2331
+ path: i.path?.map(
2332
+ (p) => typeof p === "object" ? p.key : p
2333
+ )
2334
+ })),
2335
+ message: `Input validation failed: ${resolved.issues.map((i) => i.message).join(", ")}`
2336
+ });
2337
+ }
2338
+ return ok2(resolved.value);
2339
+ }
2340
+
2341
+ // src/di.ts
2342
+ function withDeps(workflow, overrides) {
2343
+ const forward = (method) => ((...args) => {
2344
+ const last = args.at(-1);
2345
+ const hasConfig = args.length > 0 && typeof last === "object" && last !== null && !Array.isArray(last) && typeof last !== "function";
2346
+ const config = hasConfig ? last : void 0;
2347
+ const head = hasConfig ? args.slice(0, -1) : args;
2348
+ const mergedDeps = { ...overrides, ...config?.deps ?? {} };
2349
+ const mergedConfig = config ? { ...config, deps: mergedDeps } : { deps: mergedDeps };
2350
+ return workflow[method](...head, mergedConfig);
2351
+ });
2352
+ return {
2353
+ run: forward("run"),
2354
+ runWithState: forward("runWithState"),
2355
+ withDeps(nextOverrides) {
2356
+ return withDeps(workflow, { ...overrides, ...nextOverrides });
2357
+ }
2358
+ };
2359
+ }
2360
+
2361
+ // src/persistence.ts
2362
+ var SnapshotDecodeError = class extends Error {
2363
+ constructor(message, stepId, originalError) {
2364
+ super(message);
2365
+ this.stepId = stepId;
2366
+ this.originalError = originalError;
2367
+ this.name = "SnapshotDecodeError";
2368
+ }
2369
+ stepId;
2370
+ originalError;
2371
+ };
2372
+ function deserializeCauseNew(serialized) {
2373
+ if (serialized.type === "error") {
2374
+ const error = new Error(serialized.message);
2375
+ error.name = serialized.name;
2376
+ if (serialized.stack) {
2377
+ error.stack = serialized.stack;
2378
+ }
2379
+ if (serialized.cause) {
2380
+ error.cause = deserializeCauseNew(serialized.cause);
2381
+ }
2382
+ return error;
2383
+ }
2384
+ return serialized.value !== void 0 ? serialized.value : serialized.stringRepresentation;
2385
+ }
2386
+
2387
+ // src/workflow/execute.ts
2388
+ function createWorkflow(workflowName, deps, options) {
2389
+ if (typeof workflowName !== "string" || workflowName.length === 0) {
2390
+ throw new TypeError(
2391
+ "createWorkflow(workflowName, deps, options?): first argument must be a non-empty string. Example: createWorkflow('checkout', { chargeCard, sendEmail })"
2392
+ );
2393
+ }
2394
+ const depsActual = deps ?? {};
2395
+ const optionsActual = options;
2396
+ async function internalExecute(runName, userFn, config) {
2397
+ const workflowId = runName ?? crypto.randomUUID();
2398
+ const effectiveDeps = config?.deps ? { ...depsActual, ...config.deps } : depsActual;
2399
+ const compensations = [];
2400
+ const createContextFn = config?.createContext ?? optionsActual?.createContext;
2401
+ const context = createContextFn ? await createContextFn() : void 0;
2402
+ const workflowSignal = config?.signal ?? optionsActual?.signal;
2403
+ const onEventHandler = config?.onEvent ?? optionsActual?.onEvent;
2404
+ const onErrorHandler = config?.onError ?? optionsActual?.onError;
2405
+ const shouldRunHook = config?.shouldRun ?? optionsActual?.shouldRun;
2406
+ const onBeforeStartHook = config?.onBeforeStart ?? optionsActual?.onBeforeStart;
2407
+ const onAfterStepHook = config?.onAfterStep ?? optionsActual?.onAfterStep;
2408
+ const resumeStateOption = config?.resumeState ?? optionsActual?.resumeState;
2409
+ const catchUnexpected = optionsActual?.catchUnexpected ?? defaultCatchUnexpected;
2410
+ const declaredGraph = config?.graph ?? optionsActual?.graph;
2411
+ const workflowData = {};
2412
+ const devWarnings = (config?.devWarnings ?? optionsActual?.devWarnings) === true && process.env.NODE_ENV !== "production";
2413
+ const ctxSetWarned = /* @__PURE__ */ new Set();
2414
+ const ctxGetWarned = /* @__PURE__ */ new Set();
2415
+ const workflowContext = {
2416
+ workflowId,
2417
+ onEvent: onEventHandler,
2418
+ context: context !== void 0 ? context : void 0,
2419
+ signal: workflowSignal,
2420
+ // Data store for static analysis
2421
+ input: {},
2422
+ ref: (key) => workflowData[key],
2423
+ set: (key, value) => {
2424
+ if (devWarnings && !ctxSetWarned.has(key)) {
2425
+ ctxSetWarned.add(key);
2426
+ console.warn(
2427
+ `awaitly: ctx.set('${key}', ...) is deprecated for static analysis. Use step('id', fn, { out: '${key}' }) instead.`
2428
+ );
2429
+ }
2430
+ workflowData[key] = value;
2431
+ },
2432
+ get: (key) => {
2433
+ if (devWarnings && !ctxGetWarned.has(key)) {
2434
+ ctxGetWarned.add(key);
2435
+ console.warn(
2436
+ `awaitly: ctx.get('${key}') is deprecated for static analysis. Use ctx.ref('${key}') instead for tracked dependencies.`
2437
+ );
2438
+ }
2439
+ return workflowData[key];
2440
+ }
2441
+ };
2442
+ const emitEvent = (event) => {
2443
+ const eventWithContext = event.context !== void 0 || context === void 0 ? event : { ...event, context };
2444
+ const eventWithName = eventWithContext.workflowName === void 0 ? { ...eventWithContext, workflowName } : eventWithContext;
2445
+ onEventHandler?.(eventWithName, context);
2446
+ };
2447
+ const createCancelledResult = (reason, lastStepKey2) => {
2448
+ const cancelledError = {
2449
+ type: "WORKFLOW_CANCELLED",
2450
+ reason,
2451
+ lastStepKey: lastStepKey2
2452
+ };
2453
+ return err(catchUnexpected(cancelledError), { cause: cancelledError });
2454
+ };
2455
+ if (workflowSignal?.aborted) {
2456
+ const reason = typeof workflowSignal.reason === "string" ? workflowSignal.reason : workflowSignal.reason instanceof Error ? workflowSignal.reason.message : void 0;
2457
+ emitEvent({
2458
+ type: "workflow_cancelled",
2459
+ workflowId,
2460
+ ts: Date.now(),
2461
+ durationMs: 0,
2462
+ reason
2463
+ });
2464
+ return createCancelledResult(reason);
2465
+ }
2466
+ if (shouldRunHook) {
2467
+ const hookStartTime = performance.now();
2468
+ try {
2469
+ const shouldRunResult = await shouldRunHook(workflowId, context);
2470
+ const hookDuration = performance.now() - hookStartTime;
2471
+ emitEvent({
2472
+ type: "hook_should_run",
2473
+ workflowId,
2474
+ ts: Date.now(),
2475
+ durationMs: hookDuration,
2476
+ result: shouldRunResult,
2477
+ skipped: !shouldRunResult
2478
+ });
2479
+ if (!shouldRunResult) {
2480
+ const skipCause = new Error("Workflow skipped by shouldRun hook");
2481
+ return err(catchUnexpected(skipCause), { cause: skipCause });
2482
+ }
2483
+ } catch (thrown) {
2484
+ const hookDuration = performance.now() - hookStartTime;
2485
+ emitEvent({
2486
+ type: "hook_should_run_error",
2487
+ workflowId,
2488
+ ts: Date.now(),
2489
+ durationMs: hookDuration,
2490
+ error: thrown
2491
+ });
2492
+ return err(catchUnexpected(thrown), { cause: thrown });
2493
+ }
2494
+ }
2495
+ if (onBeforeStartHook) {
2496
+ const hookStartTime = performance.now();
2497
+ try {
2498
+ const beforeStartResult = await onBeforeStartHook(workflowId, context);
2499
+ const hookDuration = performance.now() - hookStartTime;
2500
+ emitEvent({
2501
+ type: "hook_before_start",
2502
+ workflowId,
2503
+ ts: Date.now(),
2504
+ durationMs: hookDuration,
2505
+ result: beforeStartResult,
2506
+ skipped: !beforeStartResult
2507
+ });
2508
+ if (!beforeStartResult) {
2509
+ const skipCause = new Error("Workflow skipped by onBeforeStart hook");
2510
+ return err(catchUnexpected(skipCause), { cause: skipCause });
2511
+ }
2512
+ } catch (thrown) {
2513
+ const hookDuration = performance.now() - hookStartTime;
2514
+ emitEvent({
2515
+ type: "hook_before_start_error",
2516
+ workflowId,
2517
+ ts: Date.now(),
2518
+ durationMs: hookDuration,
2519
+ error: thrown
2520
+ });
2521
+ return err(catchUnexpected(thrown), { cause: thrown });
2522
+ }
2523
+ }
2524
+ const inputSchema = optionsActual?.inputSchema;
2525
+ const inputValue = optionsActual?.input;
2526
+ if (inputSchema) {
2527
+ const validationResult = await validateInput(inputSchema, inputValue);
2528
+ if (!validationResult.ok) {
2529
+ return err(validationResult.error);
2530
+ }
2531
+ workflowContext.input = validationResult.value;
2532
+ } else if (inputValue !== void 0) {
2533
+ workflowContext.input = inputValue;
2534
+ }
2535
+ const startTs = Date.now();
2536
+ const startTime = performance.now();
2537
+ emitEvent({
2538
+ type: "workflow_start",
2539
+ workflowId,
2540
+ ts: startTs
2541
+ });
2542
+ let cache = config?.cache ?? optionsActual?.cache;
2543
+ const streamStore = config?.streamStore ?? optionsActual?.streamStore;
2544
+ if (resumeStateOption && !cache) {
2545
+ cache = /* @__PURE__ */ new Map();
2546
+ }
2547
+ if (resumeStateOption && cache) {
2548
+ const resumeState = typeof resumeStateOption === "function" ? await resumeStateOption() : resumeStateOption;
2549
+ if (!(resumeState.steps instanceof Map)) {
2550
+ console.warn(
2551
+ `awaitly: resumeState.steps is not a Map (got ${typeof resumeState.steps}). This usually happens when state is serialized with JSON.stringify() directly.
2552
+ Use serializeResumeState() and deserializeResumeState() from 'awaitly/workflow' instead:
2553
+ import { serializeResumeState, deserializeResumeState } from 'awaitly/workflow';
2554
+ const json = JSON.stringify(serializeResumeState(state)); // Save this
2555
+ const restored = deserializeResumeState(JSON.parse(json)); // Load this`
2556
+ );
2557
+ if (typeof resumeState.steps === "object" && resumeState.steps !== null) {
2558
+ resumeState.steps = new Map(Object.entries(resumeState.steps));
2559
+ }
2560
+ }
2561
+ for (const [key, entry] of resumeState.steps) {
2562
+ const { result: result2, meta } = entry;
2563
+ if (result2.ok) {
2564
+ cache.set(key, result2);
2565
+ } else {
2566
+ const effectiveMeta = meta ?? { origin: "result", resultCause: result2.cause };
2567
+ cache.set(key, encodeCachedError(result2.error, effectiveMeta, result2.cause));
2568
+ }
2569
+ }
2570
+ }
2571
+ const snapshotOption = config?.snapshot ?? optionsActual?.snapshot;
2572
+ const snapshotSerialization = optionsActual?.serialization;
2573
+ if (snapshotOption && !resumeStateOption) {
2574
+ if (!cache) {
2575
+ cache = /* @__PURE__ */ new Map();
2576
+ }
2577
+ const snapshot = snapshotOption;
2578
+ const decode = snapshotSerialization?.decode;
2579
+ for (const [stepId, stepResult] of Object.entries(snapshot.steps)) {
2580
+ if (!Object.prototype.hasOwnProperty.call(snapshot.steps, stepId)) {
2581
+ continue;
2582
+ }
2583
+ try {
2584
+ if (stepResult.ok) {
2585
+ const value = decode ? decode(stepResult.value) : stepResult.value;
2586
+ cache.set(stepId, ok2(value));
2587
+ } else {
2588
+ const errorValue = decode ? decode(stepResult.error) : stepResult.error;
2589
+ const deserializedCause = deserializeCauseNew(stepResult.cause);
2590
+ const meta = stepResult.meta?.origin === "throw" ? { origin: "throw", thrown: deserializedCause } : { origin: "result", resultCause: deserializedCause };
2591
+ cache.set(stepId, encodeCachedError(errorValue, meta, deserializedCause));
2592
+ }
2593
+ } catch (e) {
2594
+ throw new SnapshotDecodeError(
2595
+ `Failed to decode step "${stepId}": ${e instanceof Error ? e.message : String(e)}`,
2596
+ stepId,
2597
+ e instanceof Error ? e : void 0
2598
+ );
2599
+ }
2600
+ }
2601
+ }
2602
+ let abortedDuringExecution = false;
2603
+ let abortReason;
2604
+ let lastStepKey;
2605
+ const abortHandler = () => {
2606
+ abortedDuringExecution = true;
2607
+ abortReason = typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0;
2608
+ };
2609
+ if (workflowSignal && !workflowSignal.aborted) {
2610
+ workflowSignal.addEventListener("abort", abortHandler, { once: true });
2611
+ }
2612
+ const checkCancellation = () => {
2613
+ if (abortedDuringExecution || workflowSignal?.aborted) {
2614
+ const reason = abortReason ?? (typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0);
2615
+ const cancelledError = {
2616
+ type: "WORKFLOW_CANCELLED",
2617
+ reason,
2618
+ lastStepKey
2619
+ };
2620
+ throw cancelledError;
2621
+ }
2622
+ };
2623
+ const callOnAfterStepHook = async (stepKey, result2, _meta) => {
2624
+ if (!onAfterStepHook) return;
2625
+ const hookStartTime = performance.now();
2626
+ try {
2627
+ await onAfterStepHook(stepKey, result2, workflowId, context);
2628
+ const hookDuration = performance.now() - hookStartTime;
2629
+ emitEvent({
2630
+ type: "hook_after_step",
2631
+ workflowId,
2632
+ stepKey,
2633
+ ts: Date.now(),
2634
+ durationMs: hookDuration
2635
+ });
2636
+ } catch (thrown) {
2637
+ const hookDuration = performance.now() - hookStartTime;
2638
+ emitEvent({
2639
+ type: "hook_after_step_error",
2640
+ workflowId,
2641
+ stepKey,
2642
+ ts: Date.now(),
2643
+ durationMs: hookDuration,
2644
+ error: thrown
2645
+ });
2646
+ throw thrown;
2647
+ }
2648
+ };
2649
+ const createCachedStep = (realStep) => {
2650
+ const cachedStepFn = async (idOrOperationOrResult, operationOrOptions, stepOptions) => {
2651
+ if (typeof idOrOperationOrResult !== "string") {
2652
+ throw new Error(
2653
+ '[awaitly] step() requires a string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))'
2654
+ );
2655
+ }
2656
+ const id = idOrOperationOrResult;
2657
+ const opts = stepOptions ?? {};
2658
+ const name = id;
2659
+ const key = Object.prototype.hasOwnProperty.call(opts, "key") ? opts.key : id;
2660
+ const { ttl, out } = opts;
2661
+ checkCancellation();
2662
+ const stepMetadata = extractStepMetadata(opts);
2663
+ if (key && cache && cache.has(key)) {
2664
+ emitEvent({
2665
+ type: "step_cache_hit",
2666
+ workflowId,
2667
+ stepKey: key,
2668
+ name,
2669
+ ts: Date.now(),
2670
+ ...stepMetadata && { metadata: stepMetadata }
2671
+ });
2672
+ const cached = cache.get(key);
2673
+ if (cached.ok) {
2674
+ lastStepKey = key;
2675
+ if (out) {
2676
+ workflowData[out] = cached.value;
2677
+ }
2678
+ return cached.value;
2679
+ }
2680
+ const meta = decodeCachedMeta(cached.cause);
2681
+ throw createEarlyExit(cached.error, meta);
2682
+ }
2683
+ if (key && cache) {
2684
+ emitEvent({
2685
+ type: "step_cache_miss",
2686
+ workflowId,
2687
+ stepKey: key,
2688
+ name,
2689
+ ts: Date.now(),
2690
+ ...stepMetadata && { metadata: stepMetadata }
2691
+ });
2692
+ }
2693
+ try {
2694
+ const value = await realStep(
2695
+ id,
2696
+ operationOrOptions,
2697
+ opts
2698
+ );
2699
+ if (out) {
2700
+ workflowData[out] = value;
2701
+ }
2702
+ if (opts.compensate) {
2703
+ compensations.push({
2704
+ stepName: name,
2705
+ value,
2706
+ compensate: opts.compensate
2707
+ });
2708
+ }
2709
+ if (key) {
2710
+ lastStepKey = key;
2711
+ if (cache) {
2712
+ cache.set(key, ok2(value), ttl ? { ttl } : void 0);
2713
+ }
2714
+ await callOnAfterStepHook(key, ok2(value));
2715
+ }
2716
+ return value;
2717
+ } catch (thrown) {
2718
+ if (key && isEarlyExit(thrown)) {
2719
+ const exit = thrown;
2720
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
2721
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
2722
+ if (cache) {
2723
+ cache.set(key, errorResult, ttl ? { ttl } : void 0);
2724
+ }
2725
+ await callOnAfterStepHook(key, errorResult, exit.meta);
2726
+ }
2727
+ throw thrown;
2728
+ }
2729
+ };
2730
+ cachedStepFn.try = async (id, operation, opts) => {
2731
+ const { ttl } = opts;
2732
+ const key = opts.key ?? id;
2733
+ const name = id;
2734
+ if (cache && cache.has(key)) {
2735
+ emitEvent({
2736
+ type: "step_cache_hit",
2737
+ workflowId,
2738
+ stepKey: key,
2739
+ name,
2740
+ ts: Date.now()
2741
+ });
2742
+ const cached = cache.get(key);
2743
+ if (cached.ok) {
2744
+ return cached.value;
2745
+ }
2746
+ const meta = decodeCachedMeta(cached.cause);
2747
+ throw createEarlyExit(cached.error, meta);
2748
+ }
2749
+ if (cache) {
2750
+ emitEvent({
2751
+ type: "step_cache_miss",
2752
+ workflowId,
2753
+ stepKey: key,
2754
+ name,
2755
+ ts: Date.now()
2756
+ });
2757
+ }
2758
+ try {
2759
+ const value = await realStep.try(id, operation, { ...opts, key });
2760
+ if (opts.compensate) {
2761
+ compensations.push({
2762
+ stepName: name,
2763
+ value,
2764
+ compensate: opts.compensate
2765
+ });
2766
+ }
2767
+ if (cache) {
2768
+ cache.set(key, ok2(value), ttl ? { ttl } : void 0);
2769
+ }
2770
+ await callOnAfterStepHook(key, ok2(value));
2771
+ return value;
2772
+ } catch (thrown) {
2773
+ if (isEarlyExit(thrown)) {
2774
+ const exit = thrown;
2775
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
2776
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
2777
+ if (cache) {
2778
+ cache.set(key, errorResult, ttl ? { ttl } : void 0);
2779
+ }
2780
+ await callOnAfterStepHook(key, errorResult, exit.meta);
2781
+ }
2782
+ throw thrown;
2783
+ }
2784
+ };
2785
+ cachedStepFn.fromResult = async (id, operation, opts) => {
2786
+ const { ttl } = opts;
2787
+ const key = opts.key ?? id;
2788
+ const name = id;
2789
+ if (cache && cache.has(key)) {
2790
+ emitEvent({
2791
+ type: "step_cache_hit",
2792
+ workflowId,
2793
+ stepKey: key,
2794
+ name,
2795
+ ts: Date.now()
2796
+ });
2797
+ const cached = cache.get(key);
2798
+ if (cached.ok) {
2799
+ return cached.value;
2800
+ }
2801
+ const meta = decodeCachedMeta(cached.cause);
2802
+ throw createEarlyExit(cached.error, meta);
2803
+ }
2804
+ if (cache) {
2805
+ emitEvent({
2806
+ type: "step_cache_miss",
2807
+ workflowId,
2808
+ stepKey: key,
2809
+ name,
2810
+ ts: Date.now()
2811
+ });
2812
+ }
2813
+ try {
2814
+ const value = await realStep.fromResult(id, operation, { ...opts, key });
2815
+ if (cache) {
2816
+ cache.set(key, ok2(value), ttl ? { ttl } : void 0);
2817
+ }
2818
+ await callOnAfterStepHook(key, ok2(value));
2819
+ return value;
2820
+ } catch (thrown) {
2821
+ if (isEarlyExit(thrown)) {
2822
+ const exit = thrown;
2823
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
2824
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
2825
+ if (cache) {
2826
+ cache.set(key, errorResult, ttl ? { ttl } : void 0);
2827
+ }
2828
+ await callOnAfterStepHook(key, errorResult, exit.meta);
2829
+ }
2830
+ throw thrown;
2831
+ }
2832
+ };
2833
+ cachedStepFn.race = realStep.race;
2834
+ cachedStepFn.withFallback = async (id, operation, options2) => {
2835
+ const key = options2.key ?? id;
2836
+ const name = id;
2837
+ if (cache && cache.has(key)) {
2838
+ emitEvent({
2839
+ type: "step_cache_hit",
2840
+ workflowId,
2841
+ stepKey: key,
2842
+ name,
2843
+ ts: Date.now()
2844
+ });
2845
+ const cached = cache.get(key);
2846
+ if (cached.ok) {
2847
+ return cached.value;
2848
+ }
2849
+ const meta = decodeCachedMeta(cached.cause);
2850
+ throw createEarlyExit(cached.error, meta);
2851
+ }
2852
+ if (cache) {
2853
+ emitEvent({
2854
+ type: "step_cache_miss",
2855
+ workflowId,
2856
+ stepKey: key,
2857
+ name,
2858
+ ts: Date.now()
2859
+ });
2860
+ }
2861
+ try {
2862
+ const value = await realStep.withFallback(
2863
+ id,
2864
+ operation,
2865
+ options2
2866
+ );
2867
+ if (cache) {
2868
+ cache.set(key, ok2(value));
2869
+ }
2870
+ await callOnAfterStepHook(key, ok2(value));
2871
+ return value;
2872
+ } catch (thrown) {
2873
+ if (isEarlyExit(thrown)) {
2874
+ const exit = thrown;
2875
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
2876
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
2877
+ if (cache) {
2878
+ cache.set(key, errorResult);
2879
+ }
2880
+ await callOnAfterStepHook(key, errorResult, exit.meta);
2881
+ }
2882
+ throw thrown;
2883
+ }
2884
+ };
2885
+ cachedStepFn.withResource = async (id, options2) => {
2886
+ const key = id;
2887
+ try {
2888
+ const value = await realStep.withResource(id, options2);
2889
+ await callOnAfterStepHook(key, ok2(value));
2890
+ return value;
2891
+ } catch (thrown) {
2892
+ if (isEarlyExit(thrown)) {
2893
+ const exit = thrown;
2894
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
2895
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
2896
+ await callOnAfterStepHook(key, errorResult, exit.meta);
2897
+ }
2898
+ throw thrown;
2899
+ }
2900
+ };
2901
+ cachedStepFn.retry = (id, operation, options2) => {
2902
+ const stepOptions = {
2903
+ key: options2.key,
2904
+ // explicitly pass so undefined = don't cache
2905
+ retry: {
2906
+ attempts: options2.attempts,
2907
+ backoff: options2.backoff,
2908
+ initialDelay: options2.initialDelay,
2909
+ maxDelay: options2.maxDelay,
2910
+ jitter: options2.jitter,
2911
+ shouldRetry: options2.shouldRetry,
2912
+ onRetry: options2.onRetry
2913
+ },
2914
+ timeout: options2.timeout,
2915
+ ttl: options2.ttl
2916
+ };
2917
+ return cachedStepFn(id, operation, stepOptions);
2918
+ };
2919
+ cachedStepFn.withTimeout = (id, operation, options2) => {
2920
+ const stepOptions = {
2921
+ key: options2.key,
2922
+ timeout: options2,
2923
+ ttl: options2.ttl
2924
+ };
2925
+ return cachedStepFn(
2926
+ id,
2927
+ operation,
2928
+ stepOptions
2929
+ );
2930
+ };
2931
+ cachedStepFn.sleep = (id, duration, options2) => {
2932
+ if (typeof id !== "string" || id.length === 0) {
2933
+ throw new Error(
2934
+ '[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")'
2935
+ );
2936
+ }
2937
+ const d = typeof duration === "string" ? parse(duration) : duration;
2938
+ if (!d) {
2939
+ throw new Error(`step.sleep: invalid duration '${duration}'`);
2940
+ }
2941
+ const ms = toMillis(d);
2942
+ const userSignal = options2?.signal;
2943
+ const sleepOperation = async () => {
2944
+ if (workflowSignal?.aborted || userSignal?.aborted) {
2945
+ const e = new Error("Sleep aborted");
2946
+ e.name = "AbortError";
2947
+ throw e;
2948
+ }
2949
+ return new Promise((resolve, reject) => {
2950
+ const state = {
2951
+ timeoutId: void 0
2952
+ };
2953
+ const onAbort = () => {
2954
+ if (state.timeoutId) clearTimeout(state.timeoutId);
2955
+ const e = new Error("Sleep aborted");
2956
+ e.name = "AbortError";
2957
+ reject(e);
2958
+ };
2959
+ workflowSignal?.addEventListener("abort", onAbort, { once: true });
2960
+ userSignal?.addEventListener("abort", onAbort, { once: true });
2961
+ state.timeoutId = setTimeout(() => {
2962
+ workflowSignal?.removeEventListener("abort", onAbort);
2963
+ userSignal?.removeEventListener("abort", onAbort);
2964
+ resolve(ok2(void 0));
2965
+ }, ms);
2966
+ });
2967
+ };
2968
+ return cachedStepFn(id, sleepOperation, {
2969
+ key: options2?.key,
2970
+ ttl: options2?.ttl,
2971
+ description: options2?.description
2972
+ });
2973
+ };
2974
+ const activeWriters = /* @__PURE__ */ new Map();
2975
+ const activeReaders = /* @__PURE__ */ new Map();
2976
+ cachedStepFn.getWritable = (options2) => {
2977
+ const namespace = options2?.namespace ?? "default";
2978
+ const highWaterMark = options2?.highWaterMark ?? 16;
2979
+ if (!streamStore) {
2980
+ throw new Error(
2981
+ "streamStore is required to use getWritable(). Pass a streamStore to createWorkflow options."
2982
+ );
2983
+ }
2984
+ const existingKey = `${workflowId}:${namespace}`;
2985
+ const existing = activeWriters.get(existingKey);
2986
+ if (existing && !existing.closed && !existing.aborted) {
2987
+ return existing.writer;
2988
+ }
2989
+ const backpressure = createBackpressureController({
2990
+ highWaterMark,
2991
+ onStateChange: (state) => {
2992
+ emitEvent({
2993
+ type: "stream_backpressure",
2994
+ workflowId,
2995
+ namespace,
2996
+ bufferedCount: backpressure.bufferedCount,
2997
+ state,
2998
+ ts: Date.now()
2999
+ });
3000
+ }
3001
+ });
3002
+ let position = 0;
3003
+ let writable = true;
3004
+ let aborted = false;
3005
+ let closed = false;
3006
+ emitEvent({
3007
+ type: "stream_created",
3008
+ workflowId,
3009
+ namespace,
3010
+ ts: Date.now()
3011
+ });
3012
+ const writer = {
3013
+ async write(value) {
3014
+ if (closed) {
3015
+ return err(streamWriteError("closed", "Stream is closed"));
3016
+ }
3017
+ if (aborted) {
3018
+ return err(streamWriteError("aborted", "Stream was aborted"));
3019
+ }
3020
+ if (backpressure.state === "paused") {
3021
+ await backpressure.waitForDrain();
3022
+ }
3023
+ const item = {
3024
+ value,
3025
+ position,
3026
+ ts: Date.now()
3027
+ };
3028
+ const result2 = await streamStore.append(workflowId, namespace, item);
3029
+ if (!result2.ok) {
3030
+ emitEvent({
3031
+ type: "stream_error",
3032
+ workflowId,
3033
+ namespace,
3034
+ error: result2.error,
3035
+ position,
3036
+ ts: Date.now()
3037
+ });
3038
+ return err(streamWriteError("store_error", result2.error.message, result2.error));
3039
+ }
3040
+ emitEvent({
3041
+ type: "stream_write",
3042
+ workflowId,
3043
+ namespace,
3044
+ position,
3045
+ ts: Date.now()
3046
+ });
3047
+ position++;
3048
+ backpressure.increment();
3049
+ return ok2(void 0);
3050
+ },
3051
+ async close() {
3052
+ if (closed) {
3053
+ return err(streamCloseError("already_closed", "Stream is already closed"));
3054
+ }
3055
+ const result2 = await streamStore.closeStream(workflowId, namespace);
3056
+ if (!result2.ok) {
3057
+ return err(streamCloseError("store_error", result2.error.message, result2.error));
3058
+ }
3059
+ closed = true;
3060
+ writable = false;
3061
+ emitEvent({
3062
+ type: "stream_close",
3063
+ workflowId,
3064
+ namespace,
3065
+ finalPosition: position,
3066
+ ts: Date.now()
3067
+ });
3068
+ activeWriters.delete(existingKey);
3069
+ return ok2(void 0);
3070
+ },
3071
+ abort(reason) {
3072
+ aborted = true;
3073
+ writable = false;
3074
+ closed = true;
3075
+ emitEvent({
3076
+ type: "stream_error",
3077
+ workflowId,
3078
+ namespace,
3079
+ error: reason,
3080
+ position,
3081
+ ts: Date.now()
3082
+ });
3083
+ activeWriters.delete(existingKey);
3084
+ },
3085
+ get writable() {
3086
+ return writable;
3087
+ },
3088
+ get position() {
3089
+ return position;
3090
+ },
3091
+ get namespace() {
3092
+ return namespace;
3093
+ }
3094
+ };
3095
+ activeWriters.set(existingKey, {
3096
+ writer,
3097
+ backpressure,
3098
+ aborted,
3099
+ closed
3100
+ });
3101
+ return writer;
3102
+ };
3103
+ cachedStepFn.getReadable = (options2) => {
3104
+ const namespace = options2?.namespace ?? "default";
3105
+ const startIndex = options2?.startIndex ?? 0;
3106
+ const pollInterval = options2?.pollInterval ?? 10;
3107
+ const pollTimeout = options2?.pollTimeout ?? 3e4;
3108
+ if (!streamStore) {
3109
+ throw new Error(
3110
+ "streamStore is required to use getReadable(). Pass a streamStore to createWorkflow options."
3111
+ );
3112
+ }
3113
+ const existingKey = `${workflowId}:${namespace}:${startIndex}`;
3114
+ const existing = activeReaders.get(existingKey);
3115
+ if (existing && !existing.closed) {
3116
+ return existing.reader;
3117
+ }
3118
+ const decrementBackpressure = () => {
3119
+ const writerKey = `${workflowId}:${namespace}`;
3120
+ const activeWriter = activeWriters.get(writerKey);
3121
+ if (activeWriter) {
3122
+ activeWriter.backpressure.decrement();
3123
+ }
3124
+ };
3125
+ let position = startIndex;
3126
+ let readable = true;
3127
+ let closed = false;
3128
+ let bufferedItems = [];
3129
+ let bufferIndex = 0;
3130
+ const reader = {
3131
+ async read() {
3132
+ if (closed) {
3133
+ return err(streamReadError("closed", "Reader is closed"));
3134
+ }
3135
+ if (bufferIndex < bufferedItems.length) {
3136
+ const item = bufferedItems[bufferIndex++];
3137
+ position = item.position + 1;
3138
+ decrementBackpressure();
3139
+ emitEvent({
3140
+ type: "stream_read",
3141
+ workflowId,
3142
+ namespace,
3143
+ position: item.position,
3144
+ ts: Date.now()
3145
+ });
3146
+ return ok2(item.value);
3147
+ }
3148
+ const writerKey = `${workflowId}:${namespace}`;
3149
+ const pollStart = Date.now();
3150
+ let hasSeenWriter = activeWriters.has(writerKey);
3151
+ const initialMetaResult = await streamStore.getMetadata(workflowId, namespace);
3152
+ let hasSeenMetadata = initialMetaResult.ok && initialMetaResult.value !== void 0;
3153
+ while (Date.now() - pollStart < pollTimeout) {
3154
+ const result2 = await streamStore.read(workflowId, namespace, position, 100);
3155
+ if (!result2.ok) {
3156
+ return err(streamReadError("store_error", result2.error.message, result2.error));
3157
+ }
3158
+ const items = result2.value;
3159
+ if (items.length > 0) {
3160
+ bufferedItems = items;
3161
+ bufferIndex = 1;
3162
+ const item = items[0];
3163
+ position = item.position + 1;
3164
+ decrementBackpressure();
3165
+ emitEvent({
3166
+ type: "stream_read",
3167
+ workflowId,
3168
+ namespace,
3169
+ position: item.position,
3170
+ ts: Date.now()
3171
+ });
3172
+ return ok2(item.value);
3173
+ }
3174
+ const writerActive = activeWriters.has(writerKey);
3175
+ const metaResult = await streamStore.getMetadata(workflowId, namespace);
3176
+ const metadataExists = metaResult.ok && metaResult.value !== void 0;
3177
+ if (writerActive) hasSeenWriter = true;
3178
+ if (metadataExists) hasSeenMetadata = true;
3179
+ if (metaResult.ok && metaResult.value?.closed) {
3180
+ readable = false;
3181
+ return err(streamEnded(position));
3182
+ }
3183
+ if (hasSeenWriter && !writerActive && !metadataExists) {
3184
+ readable = false;
3185
+ return err(streamEnded(position));
3186
+ }
3187
+ if (hasSeenMetadata && !writerActive && metaResult.ok && !metaResult.value?.closed) {
3188
+ }
3189
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
3190
+ }
3191
+ readable = false;
3192
+ return err(streamEnded(position));
3193
+ },
3194
+ close() {
3195
+ closed = true;
3196
+ readable = false;
3197
+ bufferedItems = [];
3198
+ activeReaders.delete(existingKey);
3199
+ },
3200
+ get readable() {
3201
+ return readable;
3202
+ },
3203
+ get position() {
3204
+ return position;
3205
+ },
3206
+ get namespace() {
3207
+ return namespace;
3208
+ }
3209
+ };
3210
+ activeReaders.set(existingKey, {
3211
+ reader,
3212
+ position,
3213
+ closed
3214
+ });
3215
+ return reader;
3216
+ };
3217
+ cachedStepFn.streamForEach = async (source, processor, options2) => {
3218
+ const checkpointInterval = options2?.checkpointInterval ?? 1;
3219
+ const concurrency = options2?.concurrency ?? 1;
3220
+ const results = [];
3221
+ let processedCount = 0;
3222
+ let lastPosition = -1;
3223
+ const isStreamReader = (s) => {
3224
+ return typeof s === "object" && s !== null && "read" in s && typeof s.read === "function";
3225
+ };
3226
+ const processItem = async (item, itemIndex, itemPosition, namespace) => {
3227
+ const shouldCheckpoint = checkpointInterval > 0 && itemIndex % checkpointInterval === 0;
3228
+ const stepKey = shouldCheckpoint ? `stream-foreach:${namespace}:pos-${itemPosition}` : void 0;
3229
+ const stepId = stepKey ?? `stream-item-${itemPosition}`;
3230
+ const stepResult = await cachedStepFn(
3231
+ stepId,
3232
+ () => processor(item, itemIndex),
3233
+ { key: stepKey }
3234
+ );
3235
+ return { index: itemIndex, position: itemPosition, result: stepResult };
3236
+ };
3237
+ if (isStreamReader(source)) {
3238
+ if (concurrency <= 1) {
3239
+ let itemPosition = source.position;
3240
+ let readResult = await source.read();
3241
+ while (readResult.ok) {
3242
+ const item = readResult.value;
3243
+ const { result: result2 } = await processItem(item, processedCount, itemPosition, source.namespace);
3244
+ results.push(result2);
3245
+ lastPosition = itemPosition;
3246
+ processedCount++;
3247
+ itemPosition = source.position;
3248
+ readResult = await source.read();
3249
+ }
3250
+ } else {
3251
+ const resultsMap = /* @__PURE__ */ new Map();
3252
+ let itemIndex = 0;
3253
+ let totalItems = 0;
3254
+ const slots = new Array(concurrency).fill(null);
3255
+ const getSlot = async () => {
3256
+ for (let i = 0; i < slots.length; i++) {
3257
+ if (slots[i] === null) return i;
3258
+ }
3259
+ const activePromises = slots.filter((s) => s !== null);
3260
+ const completed = await Promise.race(activePromises);
3261
+ resultsMap.set(completed.index, { position: completed.position, result: completed.result });
3262
+ slots[completed.slotIndex] = null;
3263
+ return completed.slotIndex;
3264
+ };
3265
+ let itemPosition = source.position;
3266
+ let readResult = await source.read();
3267
+ while (readResult.ok) {
3268
+ const slotIndex = await getSlot();
3269
+ const currentIndex = itemIndex;
3270
+ const currentPosition = itemPosition;
3271
+ const currentItem = readResult.value;
3272
+ const currentSlot = slotIndex;
3273
+ slots[slotIndex] = processItem(currentItem, currentIndex, currentPosition, source.namespace).then((r) => ({ slotIndex: currentSlot, ...r }));
3274
+ totalItems++;
3275
+ itemIndex++;
3276
+ itemPosition = source.position;
3277
+ readResult = await source.read();
3278
+ }
3279
+ for (let i = 0; i < slots.length; i++) {
3280
+ if (slots[i] !== null) {
3281
+ const result2 = await slots[i];
3282
+ resultsMap.set(result2.index, { position: result2.position, result: result2.result });
3283
+ }
3284
+ }
3285
+ for (let i = 0; i < totalItems; i++) {
3286
+ const entry = resultsMap.get(i);
3287
+ if (entry) {
3288
+ results.push(entry.result);
3289
+ lastPosition = entry.position;
3290
+ processedCount++;
3291
+ }
3292
+ }
3293
+ }
3294
+ } else {
3295
+ if (concurrency <= 1) {
3296
+ let index = 0;
3297
+ for await (const item of source) {
3298
+ const { result: result2 } = await processItem(item, index, index, "async-iterable");
3299
+ results.push(result2);
3300
+ lastPosition = index;
3301
+ processedCount++;
3302
+ index++;
3303
+ }
3304
+ } else {
3305
+ const resultsMap = /* @__PURE__ */ new Map();
3306
+ let itemIndex = 0;
3307
+ let totalItems = 0;
3308
+ const slots = new Array(concurrency).fill(null);
3309
+ const getSlot = async () => {
3310
+ for (let i = 0; i < slots.length; i++) {
3311
+ if (slots[i] === null) return i;
3312
+ }
3313
+ const activePromises = slots.filter((s) => s !== null);
3314
+ const completed = await Promise.race(activePromises);
3315
+ resultsMap.set(completed.index, completed.result);
3316
+ slots[completed.slotIndex] = null;
3317
+ return completed.slotIndex;
3318
+ };
3319
+ for await (const item of source) {
3320
+ const slotIndex = await getSlot();
3321
+ const currentIndex = itemIndex;
3322
+ const currentSlot = slotIndex;
3323
+ slots[slotIndex] = processItem(item, currentIndex, currentIndex, "async-iterable").then((r) => ({ slotIndex: currentSlot, ...r }));
3324
+ totalItems++;
3325
+ itemIndex++;
3326
+ }
3327
+ for (let i = 0; i < slots.length; i++) {
3328
+ if (slots[i] !== null) {
3329
+ const result2 = await slots[i];
3330
+ resultsMap.set(result2.index, result2.result);
3331
+ }
3332
+ }
3333
+ for (let i = 0; i < totalItems; i++) {
3334
+ if (resultsMap.has(i)) {
3335
+ results.push(resultsMap.get(i));
3336
+ lastPosition = i;
3337
+ processedCount++;
3338
+ }
3339
+ }
3340
+ }
3341
+ }
3342
+ return {
3343
+ results,
3344
+ processedCount,
3345
+ lastPosition
3346
+ };
3347
+ };
3348
+ cachedStepFn.if = realStep.if;
3349
+ cachedStepFn.label = realStep.label;
3350
+ cachedStepFn.branch = realStep.branch;
3351
+ cachedStepFn.arm = realStep.arm;
3352
+ cachedStepFn.forEach = realStep.forEach;
3353
+ cachedStepFn.item = realStep.item;
3354
+ cachedStepFn.dep = realStep.dep;
3355
+ cachedStepFn.workflow = (id, getter, options2) => cachedStepFn(id, getter, options2);
3356
+ cachedStepFn.all = (id, shape, options2) => {
3357
+ const opts = options2 !== void 0 && Object.prototype.hasOwnProperty.call(options2, "key") ? options2 : { ...options2, key: void 0 };
3358
+ return cachedStepFn(id, async () => ok2(await realStep.all(id, shape)), opts);
3359
+ };
3360
+ cachedStepFn.map = (id, items, mapper, options2) => {
3361
+ const opts = options2 !== void 0 && Object.prototype.hasOwnProperty.call(options2, "key") ? options2 : { ...options2, key: void 0 };
3362
+ return cachedStepFn(id, async () => ok2(await realStep.map(id, items, mapper, options2)), opts);
3363
+ };
3364
+ return cachedStepFn;
3365
+ };
3366
+ const wrappedFn = ({ step }) => {
3367
+ const cachedStep = createCachedStep(step);
3368
+ return userFn({
3369
+ step: cachedStep,
3370
+ steps: bindSteps(effectiveDeps ?? {}, cachedStep),
3371
+ deps: effectiveDeps,
3372
+ ctx: workflowContext
3373
+ });
3374
+ };
3375
+ let result;
3376
+ try {
3377
+ result = await run(wrappedFn, {
3378
+ onError: onErrorHandler,
3379
+ onEvent: onEventHandler,
3380
+ catchUnexpected,
3381
+ workflowId,
3382
+ workflowName,
3383
+ context,
3384
+ graph: declaredGraph,
3385
+ _workflowSignal: workflowSignal
3386
+ });
3387
+ } finally {
3388
+ if (workflowSignal) {
3389
+ workflowSignal.removeEventListener("abort", abortHandler);
3390
+ }
3391
+ }
3392
+ if (!result.ok && compensations.length > 0) {
3393
+ const compensationErrors = [];
3394
+ for (let i = compensations.length - 1; i >= 0; i--) {
3395
+ const comp = compensations[i];
3396
+ try {
3397
+ await comp.compensate(comp.value);
3398
+ } catch (compErr) {
3399
+ compensationErrors.push({ stepName: comp.stepName, error: compErr });
3400
+ }
3401
+ }
3402
+ if (compensationErrors.length > 0) {
3403
+ const sagaError = {
3404
+ type: "SAGA_COMPENSATION_ERROR",
3405
+ originalError: result.error,
3406
+ compensationErrors
3407
+ };
3408
+ result = err(sagaError, { cause: result.cause });
3409
+ }
3410
+ }
3411
+ const durationMs = performance.now() - startTime;
3412
+ if (!result.ok) {
3413
+ let cancelledError;
3414
+ if (isWorkflowCancelled(result.cause)) {
3415
+ cancelledError = result.cause;
3416
+ }
3417
+ if (!cancelledError && abortedDuringExecution && isUnexpectedError(result.error)) {
3418
+ const thrown = result.cause;
3419
+ const isAbortError = thrown != null && typeof thrown === "object" && "name" in thrown && thrown.name === "AbortError";
3420
+ if (isAbortError) {
3421
+ const reason = abortReason ?? (typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0);
3422
+ cancelledError = {
3423
+ type: "WORKFLOW_CANCELLED",
3424
+ reason,
3425
+ lastStepKey
3426
+ };
3427
+ }
3428
+ }
3429
+ if (cancelledError) {
3430
+ emitEvent({
3431
+ type: "workflow_cancelled",
3432
+ workflowId,
3433
+ ts: Date.now(),
3434
+ durationMs,
3435
+ reason: cancelledError.reason,
3436
+ lastStepKey: cancelledError.lastStepKey
3437
+ });
3438
+ if (cancelledError && !isWorkflowCancelled(result.cause)) {
3439
+ return err(result.error, { cause: cancelledError });
3440
+ }
3441
+ return result;
3442
+ }
3443
+ }
3444
+ if (result.ok && abortedDuringExecution) {
3445
+ const reason = abortReason ?? (typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0);
3446
+ emitEvent({
3447
+ type: "workflow_cancelled",
3448
+ workflowId,
3449
+ ts: Date.now(),
3450
+ durationMs,
3451
+ reason,
3452
+ lastStepKey
3453
+ });
3454
+ const cancelledError = {
3455
+ type: "WORKFLOW_CANCELLED",
3456
+ reason,
3457
+ lastStepKey
3458
+ };
3459
+ return err(catchUnexpected(cancelledError), { cause: cancelledError });
3460
+ }
3461
+ if (result.ok) {
3462
+ emitEvent({
3463
+ type: "workflow_success",
3464
+ workflowId,
3465
+ ts: Date.now(),
3466
+ durationMs
3467
+ });
3468
+ } else {
3469
+ emitEvent({
3470
+ type: "workflow_error",
3471
+ workflowId,
3472
+ ts: Date.now(),
3473
+ durationMs,
3474
+ error: result.error
3475
+ });
3476
+ }
3477
+ return result;
3478
+ }
3479
+ function runMethod(fnOrName, maybeFnOrConfig, maybeConfig) {
3480
+ let runName;
3481
+ let fn;
3482
+ let config;
3483
+ if (typeof fnOrName === "string") {
3484
+ runName = fnOrName;
3485
+ fn = maybeFnOrConfig;
3486
+ config = maybeConfig;
3487
+ } else {
3488
+ fn = fnOrName;
3489
+ config = maybeFnOrConfig;
3490
+ }
3491
+ return internalExecute(runName, fn, config);
3492
+ }
3493
+ async function runWithStateMethod(fnOrName, maybeFnOrConfig, maybeConfig) {
3494
+ let runName;
3495
+ let fn;
3496
+ let config;
3497
+ if (typeof fnOrName === "string") {
3498
+ runName = fnOrName;
3499
+ fn = maybeFnOrConfig;
3500
+ config = maybeConfig;
3501
+ } else {
3502
+ fn = fnOrName;
3503
+ config = maybeFnOrConfig;
3504
+ }
3505
+ const collector = createResumeStateCollector();
3506
+ const userOnEvent = config?.onEvent;
3507
+ const mergedOnEvent = (event, ctx) => {
3508
+ collector.handleEvent(event);
3509
+ try {
3510
+ userOnEvent?.(event, ctx);
3511
+ } catch {
3512
+ }
3513
+ };
3514
+ const mergedConfig = {
3515
+ ...config,
3516
+ onEvent: mergedOnEvent
3517
+ };
3518
+ let result;
3519
+ let resumeState;
3520
+ try {
3521
+ result = await internalExecute(runName, fn, mergedConfig);
3522
+ } catch (thrown) {
3523
+ const catchUnexpected = optionsActual?.catchUnexpected ?? defaultCatchUnexpected;
3524
+ result = err(catchUnexpected(thrown), { cause: thrown });
3525
+ } finally {
3526
+ resumeState = collector.getResumeState();
3527
+ }
3528
+ return { result, resumeState };
3529
+ }
3530
+ const workflow = {
3531
+ withDeps: (overrides) => withDeps(workflow, overrides),
3532
+ run: runMethod,
3533
+ runWithState: runWithStateMethod
3534
+ };
3535
+ return workflow;
3536
+ }
3537
+
3538
+ // src/saga.ts
3539
+ function isSagaCompensationError(error) {
3540
+ return typeof error === "object" && error !== null && error.type === "SAGA_COMPENSATION_ERROR";
3541
+ }
3542
+ function createSagaWorkflow(workflowName, deps, options) {
3543
+ return createWorkflow(workflowName, deps, options);
3544
+ }
3545
+ async function runSaga(fn, options) {
3546
+ const sagaId = crypto.randomUUID();
3547
+ const startTime = performance.now();
3548
+ const compensations = [];
3549
+ const emit = (e) => options?.onEvent?.(e);
3550
+ emit({ type: "saga_start", sagaId, ts: Date.now() });
3551
+ const stepFn = async (name, operation, stepOptions) => {
3552
+ if (typeof name !== "string" || name.length === 0) {
3553
+ throw new TypeError(
3554
+ "step(name, operation, options?): first argument must be a string."
3555
+ );
3556
+ }
3557
+ const result = await operation();
3558
+ if (result.ok) {
3559
+ if (stepOptions?.compensate) {
3560
+ compensations.push({
3561
+ name,
3562
+ value: result.value,
3563
+ compensate: stepOptions.compensate
3564
+ });
3565
+ }
3566
+ return result.value;
3567
+ }
3568
+ throw createEarlyExit(result.error, {
3569
+ origin: "result",
3570
+ resultCause: result.cause
3571
+ });
3572
+ };
3573
+ const stepTry = async (name, operation, opts) => {
3574
+ if (typeof name !== "string" || name.length === 0) {
3575
+ throw new TypeError(
3576
+ "step.try(name, operation, options): first argument must be a string."
3577
+ );
3578
+ }
3579
+ const mapToError = "error" in opts ? () => opts.error : opts.onError;
3580
+ try {
3581
+ const value = await operation();
3582
+ if (opts.compensate) {
3583
+ compensations.push({
3584
+ name,
3585
+ value,
3586
+ compensate: opts.compensate
3587
+ });
3588
+ }
3589
+ return value;
3590
+ } catch (thrown) {
3591
+ const mapped = mapToError(thrown);
3592
+ throw createEarlyExit(mapped, { origin: "throw", thrown });
3593
+ }
3594
+ };
3595
+ const step = Object.assign(stepFn, { try: stepTry });
3596
+ try {
3597
+ const value = await fn({ step });
3598
+ emit({
3599
+ type: "saga_success",
3600
+ sagaId,
3601
+ ts: Date.now(),
3602
+ durationMs: performance.now() - startTime
3603
+ });
3604
+ return ok2(value);
3605
+ } catch (thrown) {
3606
+ const durationMs = performance.now() - startTime;
3607
+ const originalError = isEarlyExit(thrown) ? thrown.error : thrown;
3608
+ emit({ type: "saga_error", sagaId, ts: Date.now(), durationMs, error: originalError });
3609
+ emit({
3610
+ type: "saga_compensation_start",
3611
+ sagaId,
3612
+ ts: Date.now(),
3613
+ stepCount: compensations.length
3614
+ });
3615
+ const compensationStart = performance.now();
3616
+ const compensationErrors = [];
3617
+ for (let i = compensations.length - 1; i >= 0; i--) {
3618
+ const comp = compensations[i];
3619
+ try {
3620
+ await comp.compensate(comp.value);
3621
+ emit({
3622
+ type: "saga_compensation_step",
3623
+ sagaId,
3624
+ stepName: comp.name,
3625
+ ts: Date.now(),
3626
+ success: true
3627
+ });
3628
+ } catch (error) {
3629
+ compensationErrors.push({ stepName: comp.name, error });
3630
+ emit({
3631
+ type: "saga_compensation_step",
3632
+ sagaId,
3633
+ stepName: comp.name,
3634
+ ts: Date.now(),
3635
+ success: false,
3636
+ error
3637
+ });
3638
+ }
3639
+ }
3640
+ emit({
3641
+ type: "saga_compensation_end",
3642
+ sagaId,
3643
+ ts: Date.now(),
3644
+ durationMs: performance.now() - compensationStart,
3645
+ success: compensationErrors.length === 0,
3646
+ failedCount: compensationErrors.length
3647
+ });
3648
+ if (compensationErrors.length > 0) {
3649
+ const sagaError = {
3650
+ type: "SAGA_COMPENSATION_ERROR",
3651
+ originalError,
3652
+ compensationErrors
3653
+ };
3654
+ options?.onError?.(sagaError);
3655
+ if (options?.throwOnCompensationFailure) throw sagaError;
3656
+ return err(sagaError);
3657
+ }
3658
+ options?.onError?.(originalError);
3659
+ if (!isEarlyExit(thrown)) {
3660
+ return err(new UnexpectedError({ cause: thrown }));
3661
+ }
3662
+ return err(originalError);
3663
+ }
3664
+ }
3665
+ export {
3666
+ createSagaWorkflow,
3667
+ isSagaCompensationError,
3668
+ runSaga
3669
+ };
3670
+ //# sourceMappingURL=saga.js.map