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/run.js ADDED
@@ -0,0 +1,2247 @@
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 TimeoutError = class extends (/* @__PURE__ */ TaggedError("TimeoutError", {
180
+ slug: "runtime-step-timeout",
181
+ hint: "Increase the step's timeout option, or check why the upstream operation is slow.",
182
+ message: (p) => p.operation ? `TimeoutError: ${p.operation} timed out after ${p.ms}ms` : `TimeoutError: Operation timed out after ${p.ms}ms`
183
+ })) {
184
+ };
185
+ var UnexpectedError = class extends (/* @__PURE__ */ TaggedError("UnexpectedError", {
186
+ slug: "runtime-unexpected",
187
+ hint: "An unexpected exception escaped a step. Inspect cause; consider returning a typed Result instead of throwing.",
188
+ message: (p) => `UnexpectedError: ${p.cause instanceof Error ? p.cause.message : String(p.cause ?? "unknown")}`
189
+ })) {
190
+ };
191
+
192
+ // src/result/index.ts
193
+ function ok(value) {
194
+ return { ok: true, value };
195
+ }
196
+ function err(error, options) {
197
+ const cause = options?.cause;
198
+ return { ok: false, error, ...cause !== void 0 ? { cause } : {} };
199
+ }
200
+
201
+ // src/core/bound-steps.ts
202
+ var isDepResultShaped = (value) => typeof value === "object" && value !== null && "ok" in value && typeof value.ok === "boolean" && (value.ok ? "value" in value : "error" in value);
203
+ var bindSteps = (deps, step) => {
204
+ const steps = {};
205
+ const invocationCounts = /* @__PURE__ */ new Map();
206
+ for (const key of Object.keys(deps)) {
207
+ const dep = deps[key];
208
+ if (typeof dep !== "function") continue;
209
+ steps[key] = (...args) => {
210
+ const count = (invocationCounts.get(key) ?? 0) + 1;
211
+ invocationCounts.set(key, count);
212
+ const stepKey = count === 1 ? key : `${key}#${count}`;
213
+ return step(stepKey, async () => {
214
+ const value = await dep(...args);
215
+ return isDepResultShaped(value) ? value : ok(value);
216
+ });
217
+ };
218
+ }
219
+ return steps;
220
+ };
221
+
222
+ // src/duration.ts
223
+ function toMillis(duration) {
224
+ return duration.millis;
225
+ }
226
+
227
+ // src/core/policies.ts
228
+ var toMs = (d) => typeof d === "number" ? d : toMillis(d);
229
+ var attemptCall = async (fn, args) => {
230
+ try {
231
+ const value = await fn(...args);
232
+ if (isDepResultShaped(value)) {
233
+ return value.ok ? { kind: "ok", value: value.value } : { kind: "err", error: value.error, result: value };
234
+ }
235
+ return { kind: "ok", value };
236
+ } catch (thrown) {
237
+ return { kind: "threw", thrown };
238
+ }
239
+ };
240
+ var named = (wrapped, source) => {
241
+ const name = source.name;
242
+ if (name) {
243
+ Object.defineProperty(wrapped, "name", { value: name, configurable: true });
244
+ }
245
+ return wrapped;
246
+ };
247
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
248
+ function retry(fn, options) {
249
+ const attempts = Math.max(1, Math.trunc(options.attempts));
250
+ const baseDelay = options.delay === void 0 ? 0 : toMs(options.delay);
251
+ const maxDelay = options.maxDelay === void 0 ? Infinity : toMs(options.maxDelay);
252
+ const backoff = options.backoff ?? "fixed";
253
+ const delayFor = (attempt) => {
254
+ const raw = backoff === "exponential" ? baseDelay * 2 ** (attempt - 1) : backoff === "linear" ? baseDelay * attempt : baseDelay;
255
+ return Math.min(raw, maxDelay);
256
+ };
257
+ const wrapped = async (...args) => {
258
+ let last = { kind: "threw", thrown: void 0 };
259
+ for (let attempt = 1; attempt <= attempts; attempt++) {
260
+ last = await attemptCall(fn, args);
261
+ if (last.kind === "ok") return ok(last.value);
262
+ const failure = last.kind === "err" ? last.error : last.thrown;
263
+ if (options.retryIf && !options.retryIf(failure)) break;
264
+ if (attempt < attempts) {
265
+ options.onRetry?.({ attempt, failure });
266
+ const ms = delayFor(attempt);
267
+ if (ms > 0) await sleep(ms);
268
+ }
269
+ }
270
+ if (last.kind === "err") return last.result;
271
+ throw last.thrown;
272
+ };
273
+ return named(wrapped, fn);
274
+ }
275
+ function timeout(fn, after) {
276
+ const ms = toMs(after);
277
+ const TIMED_OUT = /* @__PURE__ */ Symbol("timed-out");
278
+ const wrapped = async (...args) => {
279
+ let timer;
280
+ try {
281
+ const outcome = await Promise.race([
282
+ attemptCall(fn, args),
283
+ new Promise((resolve) => {
284
+ timer = setTimeout(() => resolve(TIMED_OUT), ms);
285
+ })
286
+ ]);
287
+ if (outcome === TIMED_OUT) {
288
+ return err(new TimeoutError({ operation: fn.name || void 0, ms }));
289
+ }
290
+ if (outcome.kind === "ok") return ok(outcome.value);
291
+ if (outcome.kind === "err") return outcome.result;
292
+ throw outcome.thrown;
293
+ } finally {
294
+ if (timer !== void 0) clearTimeout(timer);
295
+ }
296
+ };
297
+ return named(wrapped, fn);
298
+ }
299
+ function fallback(fn, onFailure) {
300
+ const wrapped = async (...args) => {
301
+ const outcome = await attemptCall(fn, args);
302
+ if (outcome.kind === "ok") return ok(outcome.value);
303
+ const failure = outcome.kind === "err" ? outcome.error : new UnexpectedError({ cause: outcome.thrown });
304
+ const recovered = await attemptCall(onFailure, [failure, ...args]);
305
+ if (recovered.kind === "ok") return ok(recovered.value);
306
+ if (recovered.kind === "err") return recovered.result;
307
+ throw recovered.thrown;
308
+ };
309
+ return named(wrapped, fn);
310
+ }
311
+
312
+ // src/core/index.ts
313
+ function parseDurationString(input) {
314
+ const match = input.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);
315
+ if (!match) return void 0;
316
+ const value = parseFloat(match[1]);
317
+ const unit = match[2].toLowerCase();
318
+ const multipliers = { ms: 1, s: 1e3, m: 6e4, h: 36e5, d: 864e5 };
319
+ return { _tag: "Duration", millis: value * (multipliers[unit] ?? 1) };
320
+ }
321
+ function defaultCatchUnexpected(cause) {
322
+ return new UnexpectedError({ cause });
323
+ }
324
+ function ok2(value) {
325
+ return { ok: true, value };
326
+ }
327
+ function err2(error, options) {
328
+ const cause = options?.cause;
329
+ return { ok: false, error, ...cause !== void 0 ? { cause } : {} };
330
+ }
331
+ function extractErrorTag(error) {
332
+ if (error == null) return "unknown";
333
+ if (typeof error === "string") return error.trim() || "unknown";
334
+ if (typeof error === "object") {
335
+ const tagged = error;
336
+ if (typeof tagged._tag === "string") {
337
+ const trimmed = tagged._tag.trim();
338
+ if (trimmed) return trimmed;
339
+ }
340
+ if (typeof tagged.tag === "string") {
341
+ const trimmed = tagged.tag.trim();
342
+ if (trimmed) return trimmed;
343
+ }
344
+ if (typeof tagged.code === "string") {
345
+ const trimmed = tagged.code.trim();
346
+ if (trimmed) return trimmed;
347
+ } else if (typeof tagged.code === "number") {
348
+ return String(tagged.code);
349
+ }
350
+ if (error instanceof Error && error.name) {
351
+ const trimmed = error.name.trim();
352
+ if (trimmed) return trimmed;
353
+ }
354
+ }
355
+ return "unknown";
356
+ }
357
+ function lookupErrorClassification(tag, errorMeta) {
358
+ if (!errorMeta || !tag) return void 0;
359
+ return errorMeta[tag];
360
+ }
361
+ function extractStepMetadata(options) {
362
+ const { intent, domain, owner, tags, stateChanges, emits, calls } = options;
363
+ if (!intent && !domain && !owner && !tags?.length && !stateChanges?.length && !emits?.length && !calls?.length) {
364
+ return void 0;
365
+ }
366
+ const metadata = {};
367
+ if (intent) metadata.intent = intent;
368
+ if (domain) metadata.domain = domain;
369
+ if (owner) metadata.owner = owner;
370
+ if (tags?.length) metadata.tags = tags;
371
+ if (stateChanges?.length) metadata.stateChanges = stateChanges;
372
+ if (emits?.length) metadata.emits = emits;
373
+ if (calls?.length) metadata.calls = calls;
374
+ return metadata;
375
+ }
376
+ function buildStepErrorPayload(error, errorMeta, origin, attempt, cumulativeDurationMs) {
377
+ const tag = extractErrorTag(error);
378
+ const classification = lookupErrorClassification(tag, errorMeta);
379
+ const diagnostics = { tag, origin };
380
+ if (classification !== void 0) diagnostics.classification = classification;
381
+ if (attempt !== void 0) diagnostics.attempt = attempt;
382
+ if (cumulativeDurationMs !== void 0) diagnostics.cumulativeDurationMs = cumulativeDurationMs;
383
+ return diagnostics;
384
+ }
385
+ var STEP_TIMEOUT_MARKER = /* @__PURE__ */ Symbol.for("step_timeout_marker");
386
+ function isStepTimeoutError(e) {
387
+ if (typeof e !== "object" || e === null) {
388
+ return false;
389
+ }
390
+ if (e.type === "STEP_TIMEOUT") {
391
+ return true;
392
+ }
393
+ return STEP_TIMEOUT_MARKER in e;
394
+ }
395
+ function getStepTimeoutMeta(e) {
396
+ if (typeof e !== "object" || e === null) {
397
+ return void 0;
398
+ }
399
+ if (e.type === "STEP_TIMEOUT") {
400
+ const err3 = e;
401
+ return {
402
+ timeoutMs: err3.timeoutMs,
403
+ stepName: err3.stepName,
404
+ stepKey: err3.stepKey,
405
+ attempt: err3.attempt
406
+ };
407
+ }
408
+ if (STEP_TIMEOUT_MARKER in e) {
409
+ return e[STEP_TIMEOUT_MARKER];
410
+ }
411
+ return void 0;
412
+ }
413
+ var EARLY_EXIT_SYMBOL = /* @__PURE__ */ Symbol("early-exit");
414
+ function createEarlyExit(error, meta) {
415
+ return {
416
+ [EARLY_EXIT_SYMBOL]: true,
417
+ error,
418
+ meta
419
+ };
420
+ }
421
+ function isEarlyExit(e) {
422
+ return typeof e === "object" && e !== null && e[EARLY_EXIT_SYMBOL] === true;
423
+ }
424
+ var MAPPER_EXCEPTION_SYMBOL = /* @__PURE__ */ Symbol("mapper-exception");
425
+ function createMapperException(thrown) {
426
+ return { [MAPPER_EXCEPTION_SYMBOL]: true, thrown };
427
+ }
428
+ function isMapperException(e) {
429
+ return typeof e === "object" && e !== null && e[MAPPER_EXCEPTION_SYMBOL] === true;
430
+ }
431
+ function calculateRetryDelay(attempt, options) {
432
+ const { backoff, initialDelay, maxDelay, jitter } = options;
433
+ let delay;
434
+ switch (backoff) {
435
+ case "fixed":
436
+ delay = initialDelay;
437
+ break;
438
+ case "linear":
439
+ delay = initialDelay * attempt;
440
+ break;
441
+ case "exponential":
442
+ delay = initialDelay * Math.pow(2, attempt - 1);
443
+ break;
444
+ }
445
+ delay = Math.min(delay, maxDelay);
446
+ if (jitter) {
447
+ const jitterAmount = delay * 0.25 * Math.random();
448
+ delay = delay + jitterAmount;
449
+ }
450
+ return Math.floor(delay);
451
+ }
452
+ function sleep2(ms) {
453
+ return new Promise((resolve) => setTimeout(resolve, ms));
454
+ }
455
+ var TIMEOUT_SYMBOL = /* @__PURE__ */ Symbol("timeout");
456
+ var TIMEOUT_OPTION_SYMBOL = /* @__PURE__ */ Symbol("timeout-option");
457
+ function isTimeoutOptionMarker(value) {
458
+ return typeof value === "object" && value !== null && value[TIMEOUT_OPTION_SYMBOL] === true;
459
+ }
460
+ async function executeWithTimeout(operation, options, stepInfo, externalSignal) {
461
+ const controller = new AbortController();
462
+ const behavior = options.onTimeout ?? "error";
463
+ const createTimeoutError = () => {
464
+ if (typeof behavior === "function") {
465
+ return behavior({
466
+ name: stepInfo.name,
467
+ key: stepInfo.key,
468
+ ms: options.ms
469
+ });
470
+ }
471
+ return options.error ?? {
472
+ type: "STEP_TIMEOUT",
473
+ stepName: stepInfo.name,
474
+ stepKey: stepInfo.key,
475
+ timeoutMs: options.ms,
476
+ attempt: stepInfo.attempt
477
+ };
478
+ };
479
+ let timeoutId;
480
+ if (externalSignal?.aborted) {
481
+ controller.abort(externalSignal.reason);
482
+ }
483
+ let externalAbortHandler;
484
+ if (externalSignal && !externalSignal.aborted) {
485
+ externalAbortHandler = () => controller.abort(externalSignal.reason);
486
+ externalSignal.addEventListener("abort", externalAbortHandler, { once: true });
487
+ }
488
+ const timeoutPromise = new Promise((_, reject) => {
489
+ timeoutId = setTimeout(() => {
490
+ if (behavior !== "disconnect") {
491
+ controller.abort();
492
+ }
493
+ if (behavior === "option") {
494
+ reject({ [TIMEOUT_OPTION_SYMBOL]: true, ms: options.ms });
495
+ return;
496
+ }
497
+ reject({ [TIMEOUT_SYMBOL]: true, error: createTimeoutError() });
498
+ }, options.ms);
499
+ });
500
+ let operationPromise;
501
+ if (options.signal) {
502
+ operationPromise = Promise.resolve(
503
+ operation(controller.signal)
504
+ );
505
+ } else {
506
+ operationPromise = Promise.resolve(operation());
507
+ }
508
+ try {
509
+ const result = await Promise.race([operationPromise, timeoutPromise]);
510
+ return result;
511
+ } catch (error) {
512
+ if (typeof error === "object" && error !== null && error[TIMEOUT_OPTION_SYMBOL] === true) {
513
+ throw { [TIMEOUT_OPTION_SYMBOL]: true, ms: options.ms };
514
+ }
515
+ if (typeof error === "object" && error !== null && error[TIMEOUT_SYMBOL] === true) {
516
+ if (behavior === "disconnect") {
517
+ operationPromise.catch(() => {
518
+ });
519
+ }
520
+ const errorToThrow = error.error;
521
+ if (typeof errorToThrow === "object" && errorToThrow !== null && errorToThrow.type !== "STEP_TIMEOUT") {
522
+ const meta = {
523
+ timeoutMs: options.ms,
524
+ stepName: stepInfo.name,
525
+ stepKey: stepInfo.key,
526
+ attempt: stepInfo.attempt
527
+ };
528
+ if (STEP_TIMEOUT_MARKER in errorToThrow) {
529
+ errorToThrow[STEP_TIMEOUT_MARKER] = meta;
530
+ } else {
531
+ Object.defineProperty(errorToThrow, STEP_TIMEOUT_MARKER, {
532
+ value: meta,
533
+ enumerable: false,
534
+ writable: true,
535
+ configurable: false
536
+ });
537
+ }
538
+ }
539
+ throw errorToThrow;
540
+ }
541
+ throw error;
542
+ } finally {
543
+ clearTimeout(timeoutId);
544
+ if (externalAbortHandler && externalSignal) {
545
+ externalSignal.removeEventListener("abort", externalAbortHandler);
546
+ }
547
+ }
548
+ }
549
+ var DEFAULT_RETRY_CONFIG = {
550
+ backoff: "exponential",
551
+ initialDelay: 100,
552
+ maxDelay: 3e4,
553
+ jitter: true,
554
+ shouldRetry: () => true,
555
+ onRetry: () => {
556
+ }
557
+ };
558
+ async function runFn(fnOrDeps, optionsOrFn, maybeOptions) {
559
+ if (typeof fnOrDeps !== "function") {
560
+ const deps = fnOrDeps;
561
+ const boundFn = optionsOrFn;
562
+ if (typeof boundFn !== "function") {
563
+ throw new TypeError(
564
+ "[awaitly] run(deps, fn) requires a callback as the second argument. Example: run({ getUser }, async (s) => s.getUser(id))"
565
+ );
566
+ }
567
+ const classicRun = runFn;
568
+ return classicRun(
569
+ ({ step }) => boundFn(bindSteps(deps, step), { step }),
570
+ maybeOptions
571
+ );
572
+ }
573
+ const fn = fnOrDeps;
574
+ const options = optionsOrFn;
575
+ const {
576
+ onError,
577
+ onEvent,
578
+ catchUnexpected,
579
+ workflowId: providedWorkflowId,
580
+ workflowName,
581
+ context,
582
+ graph,
583
+ _workflowSignal
584
+ } = options && typeof options === "object" ? options : {};
585
+ const workflowId = providedWorkflowId ?? crypto.randomUUID();
586
+ const declaredIds = graph ? new Set(
587
+ Array.isArray(graph) ? graph : graph.states.map((state) => state.semanticId ?? state.id)
588
+ ) : void 0;
589
+ const declaredPatterns = declaredIds ? [...declaredIds].filter((id) => id.includes("{")).map(
590
+ (id) => new RegExp(
591
+ `^${id.replaceAll(/[.*+?^$()[\]\\|]/g, String.raw`\$&`).replaceAll(/\{[^}]*\}/g, ".+")}$`
592
+ )
593
+ ) : void 0;
594
+ const assertDeclared = (id, kind) => {
595
+ if (!declaredIds || declaredIds.has(id)) return;
596
+ if (declaredPatterns?.some((re) => re.test(id))) return;
597
+ throw new Error(
598
+ `[awaitly] ${kind} id "${id}" is not in the declared workflow graph. Declared ids: ${[...declaredIds].join(", ")}. Either add it to the graph or remove the graph option.`
599
+ );
600
+ };
601
+ const effectiveCatchUnexpected = catchUnexpected ?? defaultCatchUnexpected;
602
+ const activeScopeStack = [];
603
+ let stepIdCounter = 0;
604
+ const generateStepId = (stepKey) => {
605
+ return stepKey ?? `step_${++stepIdCounter}`;
606
+ };
607
+ const emitEvent = (event) => {
608
+ const eventWithContext = event.context !== void 0 || context === void 0 ? event : { ...event, context };
609
+ const eventWithName = workflowName !== void 0 && eventWithContext.workflowName === void 0 ? { ...eventWithContext, workflowName } : eventWithContext;
610
+ if (eventWithName.type === "step_success") {
611
+ const stepId = eventWithName.stepId;
612
+ for (let i = activeScopeStack.length - 1; i >= 0; i--) {
613
+ const scope = activeScopeStack[i];
614
+ if (scope.type === "race" && !scope.winnerId) {
615
+ scope.winnerId = stepId;
616
+ break;
617
+ }
618
+ }
619
+ }
620
+ onEvent?.(eventWithName, context);
621
+ };
622
+ const earlyExit = createEarlyExit;
623
+ const isEarlyExitE = (e) => isEarlyExit(e);
624
+ const wrapForStep = (error, _meta) => {
625
+ return error;
626
+ };
627
+ const isResultLike = (value) => {
628
+ if (typeof value === "function") return false;
629
+ if (value && typeof value === "object" && "ok" in value) return true;
630
+ if (value && typeof value === "object" && "then" in value && typeof value.then === "function") return true;
631
+ return false;
632
+ };
633
+ try {
634
+ let normalizeParallelOperations2 = function(rawOperations) {
635
+ const out = {};
636
+ for (const [key, value2] of Object.entries(rawOperations)) {
637
+ if (typeof value2 === "function") {
638
+ out[key] = value2;
639
+ } else if (value2 && typeof value2 === "object" && "fn" in value2) {
640
+ out[key] = value2.fn;
641
+ } else {
642
+ throw new TypeError(`step.all: operation "${key}" must be a function or { fn, errors? } object`);
643
+ }
644
+ }
645
+ return out;
646
+ }, executeParallelArray2 = function(name, operation) {
647
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
648
+ return (async () => {
649
+ const startTime = performance.now();
650
+ let scopeEnded = false;
651
+ activeScopeStack.push({ scopeId, type: "parallel" });
652
+ const emitScopeEnd = () => {
653
+ if (scopeEnded) return;
654
+ scopeEnded = true;
655
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
656
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
657
+ emitEvent({
658
+ type: "scope_end",
659
+ workflowId,
660
+ scopeId,
661
+ ts: Date.now(),
662
+ durationMs: performance.now() - startTime
663
+ });
664
+ };
665
+ emitEvent({
666
+ type: "scope_start",
667
+ workflowId,
668
+ scopeId,
669
+ scopeType: "parallel",
670
+ name,
671
+ ts: Date.now()
672
+ });
673
+ try {
674
+ const result = await operation();
675
+ emitScopeEnd();
676
+ if (!result.ok) {
677
+ onError?.(result.error, name, context);
678
+ throw earlyExit(result.error, {
679
+ origin: "result",
680
+ resultCause: result.cause
681
+ });
682
+ }
683
+ return result.value;
684
+ } catch (error) {
685
+ emitScopeEnd();
686
+ throw error;
687
+ }
688
+ })();
689
+ }, executeParallelNamed2 = function(operations, options2) {
690
+ const keys = Object.keys(operations);
691
+ const name = options2.name ?? `Parallel(${keys.join(", ")})`;
692
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
693
+ return (async () => {
694
+ const startTime = performance.now();
695
+ let scopeEnded = false;
696
+ activeScopeStack.push({ scopeId, type: "parallel" });
697
+ const emitScopeEnd = () => {
698
+ if (scopeEnded) return;
699
+ scopeEnded = true;
700
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
701
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
702
+ emitEvent({
703
+ type: "scope_end",
704
+ workflowId,
705
+ scopeId,
706
+ ts: Date.now(),
707
+ durationMs: performance.now() - startTime
708
+ });
709
+ };
710
+ emitEvent({
711
+ type: "scope_start",
712
+ workflowId,
713
+ scopeId,
714
+ scopeType: "parallel",
715
+ name,
716
+ ts: Date.now()
717
+ });
718
+ try {
719
+ const results = await new Promise((resolve) => {
720
+ if (keys.length === 0) {
721
+ resolve([]);
722
+ return;
723
+ }
724
+ let settled = false;
725
+ let pendingCount = keys.length;
726
+ const resultArray = new Array(keys.length);
727
+ for (let i = 0; i < keys.length; i++) {
728
+ const key = keys[i];
729
+ const index = i;
730
+ Promise.resolve(operations[key]()).catch((reason) => err2(
731
+ { type: "PROMISE_REJECTED", cause: reason },
732
+ { cause: { type: "PROMISE_REJECTION", reason } }
733
+ )).then((result) => {
734
+ if (settled) return;
735
+ if (!result.ok) {
736
+ settled = true;
737
+ resolve([{ key, result }]);
738
+ return;
739
+ }
740
+ resultArray[index] = { key, result };
741
+ pendingCount--;
742
+ if (pendingCount === 0) {
743
+ resolve(resultArray);
744
+ }
745
+ });
746
+ }
747
+ });
748
+ emitScopeEnd();
749
+ const output = {};
750
+ for (const { key, result } of results) {
751
+ if (!result.ok) {
752
+ onError?.(result.error, key, context);
753
+ throw earlyExit(result.error, {
754
+ origin: "result",
755
+ resultCause: result.cause
756
+ });
757
+ }
758
+ output[key] = result.value;
759
+ }
760
+ return output;
761
+ } catch (error) {
762
+ emitScopeEnd();
763
+ throw error;
764
+ }
765
+ })();
766
+ };
767
+ var normalizeParallelOperations = normalizeParallelOperations2, executeParallelArray = executeParallelArray2, executeParallelNamed = executeParallelNamed2;
768
+ const stepFn = (id, operationOrResult, stepOptions) => {
769
+ return (async () => {
770
+ if (typeof id !== "string" || id.length === 0) {
771
+ throw new Error(
772
+ '[awaitly] step() requires an explicit string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))'
773
+ );
774
+ }
775
+ assertDeclared(id, "step");
776
+ const parsedOptions = stepOptions ?? {};
777
+ const stepMetadata = extractStepMetadata(parsedOptions);
778
+ const stepName = id;
779
+ const stepKey = parsedOptions.key ?? id;
780
+ const explicitKey = parsedOptions.key ?? id;
781
+ const { description: stepDescription, retry: retryConfig, timeout: timeoutConfig } = parsedOptions;
782
+ const stepId = generateStepId(stepKey);
783
+ const hasEventListeners = onEvent;
784
+ const overallStartTime = hasEventListeners ? performance.now() : 0;
785
+ const isDirectResult = isResultLike(operationOrResult);
786
+ const operation = isDirectResult ? () => operationOrResult : operationOrResult;
787
+ const maxAttempts = Math.max(1, retryConfig?.attempts ?? 1);
788
+ const effectiveRetry = {
789
+ attempts: maxAttempts,
790
+ backoff: retryConfig?.backoff ?? DEFAULT_RETRY_CONFIG.backoff,
791
+ initialDelay: retryConfig?.initialDelay ?? DEFAULT_RETRY_CONFIG.initialDelay,
792
+ maxDelay: retryConfig?.maxDelay ?? DEFAULT_RETRY_CONFIG.maxDelay,
793
+ jitter: retryConfig?.jitter ?? DEFAULT_RETRY_CONFIG.jitter,
794
+ shouldRetry: retryConfig?.shouldRetry ?? DEFAULT_RETRY_CONFIG.shouldRetry,
795
+ onRetry: retryConfig?.onRetry ?? DEFAULT_RETRY_CONFIG.onRetry
796
+ };
797
+ if (onEvent) {
798
+ emitEvent({
799
+ type: "step_start",
800
+ workflowId,
801
+ stepId,
802
+ stepKey,
803
+ name: stepName,
804
+ description: stepDescription,
805
+ ts: Date.now(),
806
+ ...stepMetadata && { metadata: stepMetadata }
807
+ });
808
+ }
809
+ let lastResult;
810
+ for (let attempt = 1; attempt <= effectiveRetry.attempts; attempt++) {
811
+ const attemptStartTime = hasEventListeners ? performance.now() : 0;
812
+ try {
813
+ let result;
814
+ if (timeoutConfig) {
815
+ result = await executeWithTimeout(
816
+ operation,
817
+ timeoutConfig,
818
+ { name: stepName, key: stepKey, attempt },
819
+ _workflowSignal
820
+ );
821
+ } else {
822
+ result = await operation();
823
+ }
824
+ if (result.ok) {
825
+ const durationMs = performance.now() - overallStartTime;
826
+ emitEvent({
827
+ type: "step_success",
828
+ workflowId,
829
+ stepId,
830
+ stepKey,
831
+ name: stepName,
832
+ description: stepDescription,
833
+ ts: Date.now(),
834
+ durationMs,
835
+ ...stepMetadata && { metadata: stepMetadata }
836
+ });
837
+ if (explicitKey) {
838
+ emitEvent({
839
+ type: "step_complete",
840
+ workflowId,
841
+ stepKey: explicitKey,
842
+ name: stepName,
843
+ description: stepDescription,
844
+ ts: Date.now(),
845
+ durationMs,
846
+ result,
847
+ ...stepMetadata && { metadata: stepMetadata }
848
+ });
849
+ }
850
+ return result.value;
851
+ }
852
+ lastResult = result;
853
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(result.error, attempt)) {
854
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
855
+ emitEvent({
856
+ type: "step_retry",
857
+ workflowId,
858
+ stepId,
859
+ stepKey,
860
+ name: stepName,
861
+ ts: Date.now(),
862
+ attempt: attempt + 1,
863
+ maxAttempts: effectiveRetry.attempts,
864
+ delayMs: delay,
865
+ error: result.error,
866
+ ...stepMetadata && { metadata: stepMetadata },
867
+ diagnostics: buildStepErrorPayload(result.error, parsedOptions.errorMeta, "result", attempt, performance.now() - overallStartTime)
868
+ });
869
+ effectiveRetry.onRetry(result.error, attempt, delay);
870
+ await sleep2(delay);
871
+ continue;
872
+ }
873
+ if (effectiveRetry.attempts > 1) {
874
+ emitEvent({
875
+ type: "step_retries_exhausted",
876
+ workflowId,
877
+ stepId,
878
+ stepKey,
879
+ name: stepName,
880
+ ts: Date.now(),
881
+ durationMs: performance.now() - overallStartTime,
882
+ attempts: attempt,
883
+ lastError: result.error,
884
+ ...stepMetadata && { metadata: stepMetadata },
885
+ diagnostics: buildStepErrorPayload(result.error, parsedOptions.errorMeta, "result", attempt, performance.now() - overallStartTime)
886
+ });
887
+ }
888
+ break;
889
+ } catch (thrown) {
890
+ const durationMs = performance.now() - attemptStartTime;
891
+ if (isTimeoutOptionMarker(thrown)) {
892
+ const timeoutMs = thrown.ms;
893
+ emitEvent({
894
+ type: "step_timeout",
895
+ workflowId,
896
+ stepId,
897
+ stepKey,
898
+ name: stepName,
899
+ ts: Date.now(),
900
+ timeoutMs,
901
+ attempt,
902
+ ...stepMetadata && { metadata: stepMetadata },
903
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt)
904
+ });
905
+ emitEvent({
906
+ type: "step_success",
907
+ workflowId,
908
+ stepId,
909
+ stepKey,
910
+ name: stepName,
911
+ description: stepDescription,
912
+ ts: Date.now(),
913
+ durationMs: performance.now() - overallStartTime,
914
+ ...stepMetadata && { metadata: stepMetadata }
915
+ });
916
+ if (explicitKey) {
917
+ emitEvent({
918
+ type: "step_complete",
919
+ workflowId,
920
+ stepKey: explicitKey,
921
+ name: stepName,
922
+ description: stepDescription,
923
+ ts: Date.now(),
924
+ durationMs: performance.now() - overallStartTime,
925
+ result: ok2(void 0),
926
+ ...stepMetadata && { metadata: stepMetadata }
927
+ });
928
+ }
929
+ return void 0;
930
+ }
931
+ if (isEarlyExitE(thrown)) {
932
+ emitEvent({
933
+ type: "step_aborted",
934
+ workflowId,
935
+ stepId,
936
+ stepKey,
937
+ name: stepName,
938
+ description: stepDescription,
939
+ ts: Date.now(),
940
+ durationMs,
941
+ ...stepMetadata && { metadata: stepMetadata }
942
+ });
943
+ throw thrown;
944
+ }
945
+ if (isStepTimeoutError(thrown)) {
946
+ const timeoutMeta = getStepTimeoutMeta(thrown);
947
+ const timeoutMs = timeoutConfig?.ms ?? timeoutMeta?.timeoutMs ?? 0;
948
+ emitEvent({
949
+ type: "step_timeout",
950
+ workflowId,
951
+ stepId,
952
+ stepKey,
953
+ name: stepName,
954
+ ts: Date.now(),
955
+ timeoutMs,
956
+ attempt,
957
+ ...stepMetadata && { metadata: stepMetadata },
958
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt)
959
+ });
960
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(thrown, attempt)) {
961
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
962
+ emitEvent({
963
+ type: "step_retry",
964
+ workflowId,
965
+ stepId,
966
+ stepKey,
967
+ name: stepName,
968
+ ts: Date.now(),
969
+ attempt: attempt + 1,
970
+ maxAttempts: effectiveRetry.attempts,
971
+ delayMs: delay,
972
+ error: thrown,
973
+ ...stepMetadata && { metadata: stepMetadata },
974
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, performance.now() - overallStartTime)
975
+ });
976
+ effectiveRetry.onRetry(thrown, attempt, delay);
977
+ await sleep2(delay);
978
+ continue;
979
+ }
980
+ if (effectiveRetry.attempts > 1) {
981
+ emitEvent({
982
+ type: "step_retries_exhausted",
983
+ workflowId,
984
+ stepId,
985
+ stepKey,
986
+ name: stepName,
987
+ ts: Date.now(),
988
+ durationMs: performance.now() - overallStartTime,
989
+ attempts: attempt,
990
+ lastError: thrown,
991
+ ...stepMetadata && { metadata: stepMetadata },
992
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, performance.now() - overallStartTime)
993
+ });
994
+ }
995
+ const totalDurationMs3 = performance.now() - overallStartTime;
996
+ emitEvent({
997
+ type: "step_error",
998
+ workflowId,
999
+ stepId,
1000
+ stepKey,
1001
+ name: stepName,
1002
+ description: stepDescription,
1003
+ ts: Date.now(),
1004
+ durationMs: totalDurationMs3,
1005
+ error: thrown,
1006
+ ...stepMetadata && { metadata: stepMetadata },
1007
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, totalDurationMs3)
1008
+ });
1009
+ if (explicitKey) {
1010
+ emitEvent({
1011
+ type: "step_complete",
1012
+ workflowId,
1013
+ stepKey: explicitKey,
1014
+ name: stepName,
1015
+ description: stepDescription,
1016
+ ts: Date.now(),
1017
+ durationMs: totalDurationMs3,
1018
+ result: err2(thrown, { cause: thrown }),
1019
+ meta: { origin: "throw", thrown },
1020
+ ...stepMetadata && { metadata: stepMetadata }
1021
+ });
1022
+ }
1023
+ onError?.(thrown, stepName, context);
1024
+ throw earlyExit(thrown, { origin: "throw", thrown });
1025
+ }
1026
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(thrown, attempt)) {
1027
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
1028
+ emitEvent({
1029
+ type: "step_retry",
1030
+ workflowId,
1031
+ stepId,
1032
+ stepKey,
1033
+ name: stepName,
1034
+ ts: Date.now(),
1035
+ attempt: attempt + 1,
1036
+ maxAttempts: effectiveRetry.attempts,
1037
+ delayMs: delay,
1038
+ error: thrown,
1039
+ ...stepMetadata && { metadata: stepMetadata },
1040
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, performance.now() - overallStartTime)
1041
+ });
1042
+ effectiveRetry.onRetry(thrown, attempt, delay);
1043
+ await sleep2(delay);
1044
+ continue;
1045
+ }
1046
+ if (effectiveRetry.attempts > 1 && !isStepTimeoutError(thrown)) {
1047
+ emitEvent({
1048
+ type: "step_retries_exhausted",
1049
+ workflowId,
1050
+ stepId,
1051
+ stepKey,
1052
+ name: stepName,
1053
+ ts: Date.now(),
1054
+ durationMs: performance.now() - overallStartTime,
1055
+ attempts: attempt,
1056
+ lastError: thrown,
1057
+ ...stepMetadata && { metadata: stepMetadata },
1058
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, performance.now() - overallStartTime)
1059
+ });
1060
+ }
1061
+ const totalDurationMs2 = performance.now() - overallStartTime;
1062
+ let mappedError;
1063
+ try {
1064
+ mappedError = effectiveCatchUnexpected(thrown);
1065
+ } catch (mapperError) {
1066
+ throw createMapperException(mapperError);
1067
+ }
1068
+ emitEvent({
1069
+ type: "step_error",
1070
+ workflowId,
1071
+ stepId,
1072
+ stepKey,
1073
+ name: stepName,
1074
+ description: stepDescription,
1075
+ ts: Date.now(),
1076
+ durationMs: totalDurationMs2,
1077
+ error: mappedError,
1078
+ ...stepMetadata && { metadata: stepMetadata },
1079
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, totalDurationMs2)
1080
+ });
1081
+ if (explicitKey) {
1082
+ emitEvent({
1083
+ type: "step_complete",
1084
+ workflowId,
1085
+ stepKey: explicitKey,
1086
+ name: stepName,
1087
+ description: stepDescription,
1088
+ ts: Date.now(),
1089
+ durationMs: totalDurationMs2,
1090
+ result: err2(mappedError, { cause: thrown }),
1091
+ meta: { origin: "throw", thrown },
1092
+ ...stepMetadata && { metadata: stepMetadata }
1093
+ });
1094
+ }
1095
+ onError?.(mappedError, stepName, context);
1096
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1097
+ }
1098
+ }
1099
+ const errorResult = lastResult;
1100
+ const totalDurationMs = performance.now() - overallStartTime;
1101
+ const wrappedError = wrapForStep(errorResult.error, {
1102
+ origin: "result",
1103
+ resultCause: errorResult.cause
1104
+ });
1105
+ emitEvent({
1106
+ type: "step_error",
1107
+ workflowId,
1108
+ stepId,
1109
+ stepKey,
1110
+ name: stepName,
1111
+ description: stepDescription,
1112
+ ts: Date.now(),
1113
+ durationMs: totalDurationMs,
1114
+ error: wrappedError,
1115
+ ...stepMetadata && { metadata: stepMetadata },
1116
+ diagnostics: buildStepErrorPayload(errorResult.error, parsedOptions.errorMeta, "result", effectiveRetry.attempts, totalDurationMs)
1117
+ });
1118
+ if (explicitKey) {
1119
+ emitEvent({
1120
+ type: "step_complete",
1121
+ workflowId,
1122
+ stepKey: explicitKey,
1123
+ name: stepName,
1124
+ description: stepDescription,
1125
+ ts: Date.now(),
1126
+ durationMs: totalDurationMs,
1127
+ result: errorResult,
1128
+ meta: { origin: "result", resultCause: errorResult.cause },
1129
+ ...stepMetadata && { metadata: stepMetadata }
1130
+ });
1131
+ }
1132
+ onError?.(wrappedError, stepName, context);
1133
+ throw earlyExit(wrappedError, {
1134
+ origin: "result",
1135
+ resultCause: errorResult.cause
1136
+ });
1137
+ })();
1138
+ };
1139
+ stepFn.try = (id, operation, opts) => {
1140
+ if (typeof id !== "string" || id.length === 0) {
1141
+ throw new Error(
1142
+ '[awaitly] step.try() requires an explicit string ID as the first argument. Example: step.try("parse", () => JSON.parse(str), { error: "PARSE_ERROR" })'
1143
+ );
1144
+ }
1145
+ assertDeclared(id, "step");
1146
+ const mapToError = "error" in opts ? () => opts.error : opts.onError;
1147
+ if (opts.retry || opts.timeout) {
1148
+ return stepFn.retry(
1149
+ id,
1150
+ async () => {
1151
+ try {
1152
+ return ok2(await operation());
1153
+ } catch (cause) {
1154
+ return err2(mapToError(cause), { cause });
1155
+ }
1156
+ },
1157
+ {
1158
+ attempts: opts.retry?.attempts ?? 1,
1159
+ ...opts.retry ?? {},
1160
+ key: opts.key,
1161
+ timeout: opts.timeout
1162
+ }
1163
+ );
1164
+ }
1165
+ const stepKey = opts.key ?? id;
1166
+ const stepName = id;
1167
+ const stepId = id;
1168
+ const hasEventListeners = onEvent;
1169
+ return (async () => {
1170
+ const startTime = hasEventListeners ? performance.now() : 0;
1171
+ if (onEvent) {
1172
+ emitEvent({
1173
+ type: "step_start",
1174
+ workflowId,
1175
+ stepId,
1176
+ stepKey,
1177
+ name: stepName,
1178
+ ts: Date.now()
1179
+ });
1180
+ }
1181
+ try {
1182
+ const value2 = await operation();
1183
+ const durationMs = performance.now() - startTime;
1184
+ emitEvent({
1185
+ type: "step_success",
1186
+ workflowId,
1187
+ stepId,
1188
+ stepKey,
1189
+ name: stepName,
1190
+ ts: Date.now(),
1191
+ durationMs
1192
+ });
1193
+ if (stepKey) {
1194
+ emitEvent({
1195
+ type: "step_complete",
1196
+ workflowId,
1197
+ stepKey,
1198
+ name: stepName,
1199
+ ts: Date.now(),
1200
+ durationMs,
1201
+ result: ok2(value2)
1202
+ });
1203
+ }
1204
+ return value2;
1205
+ } catch (error) {
1206
+ const mapped = mapToError(error);
1207
+ const durationMs = performance.now() - startTime;
1208
+ const wrappedError = wrapForStep(mapped, { origin: "throw", thrown: error });
1209
+ emitEvent({
1210
+ type: "step_error",
1211
+ workflowId,
1212
+ stepId,
1213
+ stepKey,
1214
+ name: stepName,
1215
+ ts: Date.now(),
1216
+ durationMs,
1217
+ error: wrappedError
1218
+ });
1219
+ if (stepKey) {
1220
+ emitEvent({
1221
+ type: "step_complete",
1222
+ workflowId,
1223
+ stepKey,
1224
+ name: stepName,
1225
+ ts: Date.now(),
1226
+ durationMs,
1227
+ result: err2(mapped, { cause: error }),
1228
+ meta: { origin: "throw", thrown: error }
1229
+ });
1230
+ }
1231
+ onError?.(wrappedError, stepName, context);
1232
+ throw earlyExit(wrappedError, { origin: "throw", thrown: error });
1233
+ }
1234
+ })();
1235
+ };
1236
+ stepFn.fromResult = (id, operation, opts) => {
1237
+ if (typeof id !== "string" || id.length === 0) {
1238
+ throw new Error(
1239
+ '[awaitly] step.fromResult() requires an explicit string ID as the first argument. Example: step.fromResult("callProvider", () => callProvider(input), { onError: (e) => ({ type: "FAILED" }) })'
1240
+ );
1241
+ }
1242
+ assertDeclared(id, "step");
1243
+ const stepKey = opts.key ?? id;
1244
+ const stepName = id;
1245
+ const stepId = id;
1246
+ const mapToError = "error" in opts ? () => opts.error : opts.onError;
1247
+ const hasEventListeners = onEvent;
1248
+ return (async () => {
1249
+ const startTime = hasEventListeners ? performance.now() : 0;
1250
+ if (onEvent) {
1251
+ emitEvent({
1252
+ type: "step_start",
1253
+ workflowId,
1254
+ stepId,
1255
+ stepKey,
1256
+ name: stepName,
1257
+ ts: Date.now()
1258
+ });
1259
+ }
1260
+ const result = await operation();
1261
+ if (result.ok) {
1262
+ const durationMs = performance.now() - startTime;
1263
+ emitEvent({
1264
+ type: "step_success",
1265
+ workflowId,
1266
+ stepId,
1267
+ stepKey,
1268
+ name: stepName,
1269
+ ts: Date.now(),
1270
+ durationMs
1271
+ });
1272
+ if (stepKey) {
1273
+ emitEvent({
1274
+ type: "step_complete",
1275
+ workflowId,
1276
+ stepKey,
1277
+ name: stepName,
1278
+ ts: Date.now(),
1279
+ durationMs,
1280
+ result: ok2(result.value)
1281
+ });
1282
+ }
1283
+ return result.value;
1284
+ } else {
1285
+ const mapped = mapToError(result.error);
1286
+ const durationMs = performance.now() - startTime;
1287
+ const wrappedError = wrapForStep(mapped, {
1288
+ origin: "result",
1289
+ resultCause: result.error
1290
+ });
1291
+ emitEvent({
1292
+ type: "step_error",
1293
+ workflowId,
1294
+ stepId,
1295
+ stepKey,
1296
+ name: stepName,
1297
+ ts: Date.now(),
1298
+ durationMs,
1299
+ error: wrappedError
1300
+ });
1301
+ if (stepKey) {
1302
+ emitEvent({
1303
+ type: "step_complete",
1304
+ workflowId,
1305
+ stepKey,
1306
+ name: stepName,
1307
+ ts: Date.now(),
1308
+ durationMs,
1309
+ result: err2(mapped, { cause: result.error }),
1310
+ meta: { origin: "result", resultCause: result.error }
1311
+ });
1312
+ }
1313
+ onError?.(wrappedError, stepName, context);
1314
+ throw earlyExit(wrappedError, {
1315
+ origin: "result",
1316
+ resultCause: result.error
1317
+ });
1318
+ }
1319
+ })();
1320
+ };
1321
+ stepFn.fromNullable = (id, operation, onNull, options2) => {
1322
+ if (typeof id !== "string" || id.length === 0) {
1323
+ throw new Error(
1324
+ '[awaitly] step.fromNullable() requires an explicit string ID as the first argument. Example: step.fromNullable("getUser", () => db.find(id), () => ({ type: "NOT_FOUND" }))'
1325
+ );
1326
+ }
1327
+ return stepFn(
1328
+ id,
1329
+ async () => {
1330
+ const value2 = await operation();
1331
+ return value2 != null ? ok2(value2) : err2(onNull());
1332
+ },
1333
+ options2
1334
+ );
1335
+ };
1336
+ stepFn.retry = (id, operation, options2) => {
1337
+ if (typeof id !== "string" || id.length === 0) {
1338
+ throw new Error(
1339
+ '[awaitly] step.retry() requires an explicit string ID as the first argument. Example: step.retry("fetchData", () => fetchData(), { attempts: 3 })'
1340
+ );
1341
+ }
1342
+ return stepFn(id, operation, {
1343
+ key: options2.key ?? id,
1344
+ retry: {
1345
+ attempts: options2.attempts,
1346
+ backoff: options2.backoff,
1347
+ initialDelay: options2.initialDelay,
1348
+ maxDelay: options2.maxDelay,
1349
+ jitter: options2.jitter,
1350
+ shouldRetry: options2.shouldRetry,
1351
+ onRetry: options2.onRetry
1352
+ },
1353
+ timeout: options2.timeout
1354
+ });
1355
+ };
1356
+ stepFn.withTimeout = (id, operation, options2) => {
1357
+ if (typeof id !== "string" || id.length === 0) {
1358
+ throw new Error(
1359
+ '[awaitly] step.withTimeout() requires an explicit string ID as the first argument. Example: step.withTimeout("slowOp", () => slowOp(), { ms: 5000 })'
1360
+ );
1361
+ }
1362
+ return stepFn(
1363
+ id,
1364
+ operation,
1365
+ {
1366
+ key: options2.key ?? id,
1367
+ timeout: options2
1368
+ }
1369
+ );
1370
+ };
1371
+ stepFn.sleep = (id, duration, options2) => {
1372
+ if (typeof id !== "string" || id.length === 0) {
1373
+ throw new Error(
1374
+ '[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")'
1375
+ );
1376
+ }
1377
+ const d = typeof duration === "string" ? parseDurationString(duration) : duration;
1378
+ if (!d) {
1379
+ throw new Error(`step.sleep: invalid duration '${duration}'`);
1380
+ }
1381
+ const ms = d.millis;
1382
+ const userSignal = options2?.signal;
1383
+ return stepFn(
1384
+ id,
1385
+ async () => {
1386
+ if (_workflowSignal?.aborted || userSignal?.aborted) {
1387
+ const e = new Error("Sleep aborted");
1388
+ e.name = "AbortError";
1389
+ throw e;
1390
+ }
1391
+ return new Promise((resolve, reject) => {
1392
+ const state = { timeoutId: void 0 };
1393
+ const onAbort = () => {
1394
+ if (state.timeoutId) clearTimeout(state.timeoutId);
1395
+ const e = new Error("Sleep aborted");
1396
+ e.name = "AbortError";
1397
+ reject(e);
1398
+ };
1399
+ _workflowSignal?.addEventListener("abort", onAbort, { once: true });
1400
+ userSignal?.addEventListener("abort", onAbort, { once: true });
1401
+ state.timeoutId = setTimeout(() => {
1402
+ _workflowSignal?.removeEventListener("abort", onAbort);
1403
+ userSignal?.removeEventListener("abort", onAbort);
1404
+ resolve(ok2(void 0));
1405
+ }, ms);
1406
+ });
1407
+ },
1408
+ {
1409
+ key: options2?.key ?? id,
1410
+ description: options2?.description
1411
+ }
1412
+ );
1413
+ };
1414
+ stepFn.all = ((...args) => {
1415
+ if (typeof args[0] !== "string") {
1416
+ throw new TypeError(
1417
+ "step.all(name, ...): first argument must be a string (step name). Example: step.all('Fetch data', { user: () => fetchUser(), posts: () => fetchPosts() })"
1418
+ );
1419
+ }
1420
+ const name = args[0];
1421
+ const second = args[1];
1422
+ if (typeof second === "function") {
1423
+ return executeParallelArray2(name, second);
1424
+ }
1425
+ if (second && typeof second === "object" && !Array.isArray(second)) {
1426
+ const rawOperations = second;
1427
+ const normalizedOperations = normalizeParallelOperations2(rawOperations);
1428
+ return executeParallelNamed2(normalizedOperations, { name });
1429
+ }
1430
+ throw new TypeError(
1431
+ "step.all(name, ...): second argument must be a function (array form) or an object of operations (object form)."
1432
+ );
1433
+ });
1434
+ stepFn.race = (name, operation) => {
1435
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1436
+ return (async () => {
1437
+ const startTime = performance.now();
1438
+ let scopeEnded = false;
1439
+ const scopeEntry = { scopeId, type: "race", winnerId: void 0 };
1440
+ activeScopeStack.push(scopeEntry);
1441
+ const emitScopeEnd = () => {
1442
+ if (scopeEnded) return;
1443
+ scopeEnded = true;
1444
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
1445
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
1446
+ emitEvent({
1447
+ type: "scope_end",
1448
+ workflowId,
1449
+ scopeId,
1450
+ ts: Date.now(),
1451
+ durationMs: performance.now() - startTime,
1452
+ winnerId: scopeEntry.winnerId
1453
+ });
1454
+ };
1455
+ emitEvent({
1456
+ type: "scope_start",
1457
+ workflowId,
1458
+ scopeId,
1459
+ scopeType: "race",
1460
+ name,
1461
+ ts: Date.now()
1462
+ });
1463
+ try {
1464
+ const result = await operation();
1465
+ emitScopeEnd();
1466
+ if (!result.ok) {
1467
+ onError?.(result.error, name, context);
1468
+ throw earlyExit(result.error, {
1469
+ origin: "result",
1470
+ resultCause: result.cause
1471
+ });
1472
+ }
1473
+ return result.value;
1474
+ } catch (error) {
1475
+ emitScopeEnd();
1476
+ throw error;
1477
+ }
1478
+ })();
1479
+ };
1480
+ stepFn.if = (id, conditionLabel, condition) => {
1481
+ assertDeclared(id, "decision");
1482
+ const value2 = condition();
1483
+ emitEvent({
1484
+ type: "decision",
1485
+ workflowId,
1486
+ decisionId: id,
1487
+ label: conditionLabel,
1488
+ branch: value2 ? "then" : "else",
1489
+ value: value2,
1490
+ ts: Date.now()
1491
+ });
1492
+ return value2;
1493
+ };
1494
+ stepFn.label = stepFn.if;
1495
+ stepFn.branch = async (id, options2) => {
1496
+ const { condition, then: thenFn, else: elseFn } = options2;
1497
+ assertDeclared(id, "decision");
1498
+ const conditionResult = condition();
1499
+ const branch = conditionResult ? "then" : "else";
1500
+ const startTime = performance.now();
1501
+ emitEvent({
1502
+ type: "decision",
1503
+ workflowId,
1504
+ decisionId: id,
1505
+ label: options2.conditionLabel,
1506
+ branch,
1507
+ value: conditionResult,
1508
+ phase: "start",
1509
+ ts: Date.now()
1510
+ });
1511
+ const emitEnd = () => {
1512
+ emitEvent({
1513
+ type: "decision",
1514
+ workflowId,
1515
+ decisionId: id,
1516
+ label: options2.conditionLabel,
1517
+ branch,
1518
+ value: conditionResult,
1519
+ phase: "end",
1520
+ durationMs: performance.now() - startTime,
1521
+ ts: Date.now()
1522
+ });
1523
+ };
1524
+ try {
1525
+ if (conditionResult) {
1526
+ return await thenFn();
1527
+ } else if (elseFn) {
1528
+ return await elseFn();
1529
+ }
1530
+ return void 0;
1531
+ } finally {
1532
+ emitEnd();
1533
+ }
1534
+ };
1535
+ stepFn.arm = (fn2, errors) => {
1536
+ return { fn: fn2, errors };
1537
+ };
1538
+ stepFn.forEach = async (_id, items, options2) => {
1539
+ const results = [];
1540
+ const maxIterations = options2.maxIterations;
1541
+ let index = 0;
1542
+ const isRunForm = "run" in options2;
1543
+ const asyncItems = Symbol.asyncIterator in items ? items : (async function* () {
1544
+ yield* items;
1545
+ })();
1546
+ for await (const item of asyncItems) {
1547
+ if (maxIterations !== void 0 && index >= maxIterations) {
1548
+ break;
1549
+ }
1550
+ let result;
1551
+ if (isRunForm) {
1552
+ const runOptions = options2;
1553
+ result = await runOptions.run(item, index);
1554
+ } else {
1555
+ const itemOptions = options2;
1556
+ result = await itemOptions.item.handler(item, index, stepFn);
1557
+ }
1558
+ results.push(result);
1559
+ index++;
1560
+ }
1561
+ return results;
1562
+ };
1563
+ stepFn.item = (handler) => {
1564
+ return {
1565
+ __forEachItemHandler: true,
1566
+ handler
1567
+ };
1568
+ };
1569
+ stepFn.dep = (_name, fn2) => {
1570
+ return fn2;
1571
+ };
1572
+ stepFn.workflow = (id, getter, options2) => {
1573
+ return stepFn(id, getter, options2);
1574
+ };
1575
+ stepFn.map = async (id, items, mapper, options2) => {
1576
+ const concurrency = options2?.concurrency ?? items.length;
1577
+ return stepFn(
1578
+ id,
1579
+ () => {
1580
+ if (concurrency >= items.length) {
1581
+ return allAsync(items.map((item, index) => mapper(item, index)));
1582
+ } else {
1583
+ return (async () => {
1584
+ const results = [];
1585
+ for (let i = 0; i < items.length; i += concurrency) {
1586
+ const batch = items.slice(i, i + concurrency);
1587
+ const batchResult = await allAsync(
1588
+ batch.map((item, batchIndex) => mapper(item, i + batchIndex))
1589
+ );
1590
+ if (!batchResult.ok) {
1591
+ return batchResult;
1592
+ }
1593
+ results.push(...batchResult.value);
1594
+ }
1595
+ return ok2(results);
1596
+ })();
1597
+ }
1598
+ },
1599
+ { key: options2?.key }
1600
+ );
1601
+ };
1602
+ stepFn.withFallback = (id, operation, options2) => {
1603
+ if (typeof id !== "string" || id.length === 0) {
1604
+ throw new Error(
1605
+ '[awaitly] step.withFallback() requires an explicit string ID as the first argument. Example: step.withFallback("getUser", () => fetchUser(id), { fallback: () => fetchFromCache(id) })'
1606
+ );
1607
+ }
1608
+ assertDeclared(id, "step");
1609
+ const stepKey = options2.key ?? id;
1610
+ const stepName = id;
1611
+ const stepId = generateStepId(stepKey);
1612
+ const hasEventListeners = onEvent;
1613
+ return (async () => {
1614
+ const startTime = hasEventListeners ? performance.now() : 0;
1615
+ if (onEvent) {
1616
+ emitEvent({
1617
+ type: "step_start",
1618
+ workflowId,
1619
+ stepId,
1620
+ stepKey,
1621
+ name: stepName,
1622
+ ts: Date.now()
1623
+ });
1624
+ }
1625
+ let primaryResult;
1626
+ try {
1627
+ primaryResult = await operation();
1628
+ } catch (thrown) {
1629
+ if (isEarlyExitE(thrown)) {
1630
+ emitEvent({
1631
+ type: "step_aborted",
1632
+ workflowId,
1633
+ stepId,
1634
+ stepKey,
1635
+ name: stepName,
1636
+ ts: Date.now(),
1637
+ durationMs: performance.now() - startTime
1638
+ });
1639
+ throw thrown;
1640
+ }
1641
+ let mappedError;
1642
+ try {
1643
+ mappedError = effectiveCatchUnexpected(thrown);
1644
+ } catch (mapperError) {
1645
+ throw createMapperException(mapperError);
1646
+ }
1647
+ if (options2.on !== void 0 && options2.on !== mappedError) {
1648
+ const durationMs2 = performance.now() - startTime;
1649
+ emitEvent({
1650
+ type: "step_error",
1651
+ workflowId,
1652
+ stepId,
1653
+ stepKey,
1654
+ name: stepName,
1655
+ ts: Date.now(),
1656
+ durationMs: durationMs2,
1657
+ error: mappedError
1658
+ });
1659
+ if (stepKey) {
1660
+ emitEvent({
1661
+ type: "step_complete",
1662
+ workflowId,
1663
+ stepKey,
1664
+ name: stepName,
1665
+ ts: Date.now(),
1666
+ durationMs: durationMs2,
1667
+ result: err2(mappedError, { cause: thrown }),
1668
+ meta: { origin: "throw", thrown }
1669
+ });
1670
+ }
1671
+ onError?.(mappedError, stepName, context);
1672
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1673
+ }
1674
+ let fallbackResultFromThrow;
1675
+ try {
1676
+ fallbackResultFromThrow = await options2.fallback();
1677
+ } catch (fallbackThrown) {
1678
+ if (isEarlyExitE(fallbackThrown)) {
1679
+ emitEvent({
1680
+ type: "step_aborted",
1681
+ workflowId,
1682
+ stepId,
1683
+ stepKey,
1684
+ name: stepName,
1685
+ ts: Date.now(),
1686
+ durationMs: performance.now() - startTime
1687
+ });
1688
+ throw fallbackThrown;
1689
+ }
1690
+ let fallbackMappedError;
1691
+ try {
1692
+ fallbackMappedError = effectiveCatchUnexpected(fallbackThrown);
1693
+ } catch (mapperError) {
1694
+ throw createMapperException(mapperError);
1695
+ }
1696
+ const durationMs2 = performance.now() - startTime;
1697
+ emitEvent({
1698
+ type: "step_error",
1699
+ workflowId,
1700
+ stepId,
1701
+ stepKey,
1702
+ name: stepName,
1703
+ ts: Date.now(),
1704
+ durationMs: durationMs2,
1705
+ error: fallbackMappedError
1706
+ });
1707
+ if (stepKey) {
1708
+ emitEvent({
1709
+ type: "step_complete",
1710
+ workflowId,
1711
+ stepKey,
1712
+ name: stepName,
1713
+ ts: Date.now(),
1714
+ durationMs: durationMs2,
1715
+ result: err2(fallbackMappedError, { cause: fallbackThrown }),
1716
+ meta: { origin: "throw", thrown: fallbackThrown }
1717
+ });
1718
+ }
1719
+ onError?.(fallbackMappedError, stepName, context);
1720
+ throw earlyExit(fallbackMappedError, { origin: "throw", thrown: fallbackThrown });
1721
+ }
1722
+ if (fallbackResultFromThrow.ok) {
1723
+ const durationMs2 = performance.now() - startTime;
1724
+ emitEvent({
1725
+ type: "step_success",
1726
+ workflowId,
1727
+ stepId,
1728
+ stepKey,
1729
+ name: stepName,
1730
+ ts: Date.now(),
1731
+ durationMs: durationMs2
1732
+ });
1733
+ if (stepKey) {
1734
+ emitEvent({
1735
+ type: "step_complete",
1736
+ workflowId,
1737
+ stepKey,
1738
+ name: stepName,
1739
+ ts: Date.now(),
1740
+ durationMs: durationMs2,
1741
+ result: fallbackResultFromThrow,
1742
+ meta: { origin: "fallback", fallbackUsed: true, fallbackReason: String(mappedError) }
1743
+ });
1744
+ }
1745
+ return fallbackResultFromThrow.value;
1746
+ } else {
1747
+ const durationMs2 = performance.now() - startTime;
1748
+ const wrappedError2 = wrapForStep(fallbackResultFromThrow.error, {
1749
+ origin: "result",
1750
+ resultCause: fallbackResultFromThrow.cause
1751
+ });
1752
+ emitEvent({
1753
+ type: "step_error",
1754
+ workflowId,
1755
+ stepId,
1756
+ stepKey,
1757
+ name: stepName,
1758
+ ts: Date.now(),
1759
+ durationMs: durationMs2,
1760
+ error: wrappedError2
1761
+ });
1762
+ if (stepKey) {
1763
+ emitEvent({
1764
+ type: "step_complete",
1765
+ workflowId,
1766
+ stepKey,
1767
+ name: stepName,
1768
+ ts: Date.now(),
1769
+ durationMs: durationMs2,
1770
+ result: fallbackResultFromThrow,
1771
+ meta: { origin: "result", resultCause: fallbackResultFromThrow.cause }
1772
+ });
1773
+ }
1774
+ onError?.(wrappedError2, stepName, context);
1775
+ throw earlyExit(wrappedError2, {
1776
+ origin: "result",
1777
+ resultCause: fallbackResultFromThrow.cause
1778
+ });
1779
+ }
1780
+ }
1781
+ if (primaryResult.ok) {
1782
+ const durationMs2 = performance.now() - startTime;
1783
+ emitEvent({
1784
+ type: "step_success",
1785
+ workflowId,
1786
+ stepId,
1787
+ stepKey,
1788
+ name: stepName,
1789
+ ts: Date.now(),
1790
+ durationMs: durationMs2
1791
+ });
1792
+ if (stepKey) {
1793
+ emitEvent({
1794
+ type: "step_complete",
1795
+ workflowId,
1796
+ stepKey,
1797
+ name: stepName,
1798
+ ts: Date.now(),
1799
+ durationMs: durationMs2,
1800
+ result: primaryResult
1801
+ });
1802
+ }
1803
+ return primaryResult.value;
1804
+ }
1805
+ const primaryError = primaryResult.error;
1806
+ if (options2.on !== void 0 && options2.on !== primaryError) {
1807
+ const durationMs2 = performance.now() - startTime;
1808
+ const wrappedError2 = wrapForStep(primaryError, {
1809
+ origin: "result",
1810
+ resultCause: primaryResult.cause
1811
+ });
1812
+ emitEvent({
1813
+ type: "step_error",
1814
+ workflowId,
1815
+ stepId,
1816
+ stepKey,
1817
+ name: stepName,
1818
+ ts: Date.now(),
1819
+ durationMs: durationMs2,
1820
+ error: wrappedError2
1821
+ });
1822
+ if (stepKey) {
1823
+ emitEvent({
1824
+ type: "step_complete",
1825
+ workflowId,
1826
+ stepKey,
1827
+ name: stepName,
1828
+ ts: Date.now(),
1829
+ durationMs: durationMs2,
1830
+ result: primaryResult,
1831
+ meta: { origin: "result", resultCause: primaryResult.cause }
1832
+ });
1833
+ }
1834
+ onError?.(wrappedError2, stepName, context);
1835
+ throw earlyExit(wrappedError2, {
1836
+ origin: "result",
1837
+ resultCause: primaryResult.cause
1838
+ });
1839
+ }
1840
+ let fallbackResult;
1841
+ try {
1842
+ fallbackResult = await options2.fallback();
1843
+ } catch (thrown) {
1844
+ if (isEarlyExitE(thrown)) {
1845
+ emitEvent({
1846
+ type: "step_aborted",
1847
+ workflowId,
1848
+ stepId,
1849
+ stepKey,
1850
+ name: stepName,
1851
+ ts: Date.now(),
1852
+ durationMs: performance.now() - startTime
1853
+ });
1854
+ throw thrown;
1855
+ }
1856
+ let mappedError;
1857
+ try {
1858
+ mappedError = effectiveCatchUnexpected(thrown);
1859
+ } catch (mapperError) {
1860
+ throw createMapperException(mapperError);
1861
+ }
1862
+ const durationMs2 = performance.now() - startTime;
1863
+ emitEvent({
1864
+ type: "step_error",
1865
+ workflowId,
1866
+ stepId,
1867
+ stepKey,
1868
+ name: stepName,
1869
+ ts: Date.now(),
1870
+ durationMs: durationMs2,
1871
+ error: mappedError
1872
+ });
1873
+ if (stepKey) {
1874
+ emitEvent({
1875
+ type: "step_complete",
1876
+ workflowId,
1877
+ stepKey,
1878
+ name: stepName,
1879
+ ts: Date.now(),
1880
+ durationMs: durationMs2,
1881
+ result: err2(mappedError, { cause: thrown }),
1882
+ meta: { origin: "throw", thrown }
1883
+ });
1884
+ }
1885
+ onError?.(mappedError, stepName, context);
1886
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1887
+ }
1888
+ if (fallbackResult.ok) {
1889
+ const durationMs2 = performance.now() - startTime;
1890
+ emitEvent({
1891
+ type: "step_success",
1892
+ workflowId,
1893
+ stepId,
1894
+ stepKey,
1895
+ name: stepName,
1896
+ ts: Date.now(),
1897
+ durationMs: durationMs2
1898
+ });
1899
+ if (stepKey) {
1900
+ emitEvent({
1901
+ type: "step_complete",
1902
+ workflowId,
1903
+ stepKey,
1904
+ name: stepName,
1905
+ ts: Date.now(),
1906
+ durationMs: durationMs2,
1907
+ result: fallbackResult,
1908
+ meta: { origin: "fallback", fallbackUsed: true, fallbackReason: String(primaryError) }
1909
+ });
1910
+ }
1911
+ return fallbackResult.value;
1912
+ }
1913
+ const durationMs = performance.now() - startTime;
1914
+ const wrappedError = wrapForStep(fallbackResult.error, {
1915
+ origin: "result",
1916
+ resultCause: fallbackResult.cause
1917
+ });
1918
+ emitEvent({
1919
+ type: "step_error",
1920
+ workflowId,
1921
+ stepId,
1922
+ stepKey,
1923
+ name: stepName,
1924
+ ts: Date.now(),
1925
+ durationMs,
1926
+ error: wrappedError
1927
+ });
1928
+ if (stepKey) {
1929
+ emitEvent({
1930
+ type: "step_complete",
1931
+ workflowId,
1932
+ stepKey,
1933
+ name: stepName,
1934
+ ts: Date.now(),
1935
+ durationMs,
1936
+ result: fallbackResult,
1937
+ meta: { origin: "result", resultCause: fallbackResult.cause }
1938
+ });
1939
+ }
1940
+ onError?.(wrappedError, stepName, context);
1941
+ throw earlyExit(wrappedError, {
1942
+ origin: "result",
1943
+ resultCause: fallbackResult.cause
1944
+ });
1945
+ })();
1946
+ };
1947
+ stepFn.withResource = (id, options2) => {
1948
+ if (typeof id !== "string" || id.length === 0) {
1949
+ throw new Error(
1950
+ '[awaitly] step.withResource() requires an explicit string ID as the first argument. Example: step.withResource("useDb", { acquire: () => connect(), use: (db) => query(db), release: (db) => db.close() })'
1951
+ );
1952
+ }
1953
+ assertDeclared(id, "step");
1954
+ const stepKey = id;
1955
+ const stepName = id;
1956
+ const stepId = generateStepId(stepKey);
1957
+ const hasEventListeners = onEvent;
1958
+ return (async () => {
1959
+ const startTime = hasEventListeners ? performance.now() : 0;
1960
+ if (onEvent) {
1961
+ emitEvent({
1962
+ type: "step_start",
1963
+ workflowId,
1964
+ stepId,
1965
+ stepKey,
1966
+ name: stepName,
1967
+ ts: Date.now()
1968
+ });
1969
+ }
1970
+ let acquireResult;
1971
+ try {
1972
+ acquireResult = await options2.acquire();
1973
+ } catch (thrown) {
1974
+ if (isEarlyExitE(thrown)) {
1975
+ emitEvent({
1976
+ type: "step_aborted",
1977
+ workflowId,
1978
+ stepId,
1979
+ stepKey,
1980
+ name: stepName,
1981
+ ts: Date.now(),
1982
+ durationMs: performance.now() - startTime
1983
+ });
1984
+ throw thrown;
1985
+ }
1986
+ let mappedError;
1987
+ try {
1988
+ mappedError = effectiveCatchUnexpected(thrown);
1989
+ } catch (mapperError) {
1990
+ throw createMapperException(mapperError);
1991
+ }
1992
+ const durationMs2 = performance.now() - startTime;
1993
+ emitEvent({
1994
+ type: "step_error",
1995
+ workflowId,
1996
+ stepId,
1997
+ stepKey,
1998
+ name: stepName,
1999
+ ts: Date.now(),
2000
+ durationMs: durationMs2,
2001
+ error: mappedError
2002
+ });
2003
+ if (stepKey) {
2004
+ emitEvent({
2005
+ type: "step_complete",
2006
+ workflowId,
2007
+ stepKey,
2008
+ name: stepName,
2009
+ ts: Date.now(),
2010
+ durationMs: durationMs2,
2011
+ result: err2(mappedError, { cause: thrown }),
2012
+ meta: { origin: "throw", thrown }
2013
+ });
2014
+ }
2015
+ onError?.(mappedError, stepName, context);
2016
+ throw earlyExit(mappedError, { origin: "throw", thrown });
2017
+ }
2018
+ if (!acquireResult.ok) {
2019
+ const durationMs2 = performance.now() - startTime;
2020
+ const wrappedError2 = wrapForStep(acquireResult.error, {
2021
+ origin: "result",
2022
+ resultCause: acquireResult.cause
2023
+ });
2024
+ emitEvent({
2025
+ type: "step_error",
2026
+ workflowId,
2027
+ stepId,
2028
+ stepKey,
2029
+ name: stepName,
2030
+ ts: Date.now(),
2031
+ durationMs: durationMs2,
2032
+ error: wrappedError2
2033
+ });
2034
+ if (stepKey) {
2035
+ emitEvent({
2036
+ type: "step_complete",
2037
+ workflowId,
2038
+ stepKey,
2039
+ name: stepName,
2040
+ ts: Date.now(),
2041
+ durationMs: durationMs2,
2042
+ result: acquireResult,
2043
+ meta: { origin: "result", resultCause: acquireResult.cause }
2044
+ });
2045
+ }
2046
+ onError?.(wrappedError2, stepName, context);
2047
+ throw earlyExit(wrappedError2, {
2048
+ origin: "result",
2049
+ resultCause: acquireResult.cause
2050
+ });
2051
+ }
2052
+ const resource = acquireResult.value;
2053
+ let useResult;
2054
+ let useThrown;
2055
+ let useThrewNonResult = false;
2056
+ try {
2057
+ useResult = await options2.use(resource);
2058
+ } catch (thrown) {
2059
+ if (isEarlyExitE(thrown)) {
2060
+ try {
2061
+ await options2.release(resource);
2062
+ } catch (releaseErr) {
2063
+ console.warn(
2064
+ `[awaitly] step.withResource("${id}"): release threw after earlyExit:`,
2065
+ releaseErr
2066
+ );
2067
+ }
2068
+ throw thrown;
2069
+ }
2070
+ useThrown = thrown;
2071
+ useThrewNonResult = true;
2072
+ }
2073
+ try {
2074
+ await options2.release(resource);
2075
+ } catch (releaseErr) {
2076
+ console.warn(
2077
+ `[awaitly] step.withResource("${id}"): release threw:`,
2078
+ releaseErr
2079
+ );
2080
+ }
2081
+ if (useThrewNonResult) {
2082
+ let mappedError;
2083
+ try {
2084
+ mappedError = effectiveCatchUnexpected(useThrown);
2085
+ } catch (mapperError) {
2086
+ throw createMapperException(mapperError);
2087
+ }
2088
+ const durationMs2 = performance.now() - startTime;
2089
+ emitEvent({
2090
+ type: "step_error",
2091
+ workflowId,
2092
+ stepId,
2093
+ stepKey,
2094
+ name: stepName,
2095
+ ts: Date.now(),
2096
+ durationMs: durationMs2,
2097
+ error: mappedError
2098
+ });
2099
+ if (stepKey) {
2100
+ emitEvent({
2101
+ type: "step_complete",
2102
+ workflowId,
2103
+ stepKey,
2104
+ name: stepName,
2105
+ ts: Date.now(),
2106
+ durationMs: durationMs2,
2107
+ result: err2(mappedError, { cause: useThrown }),
2108
+ meta: { origin: "throw", thrown: useThrown }
2109
+ });
2110
+ }
2111
+ onError?.(mappedError, stepName, context);
2112
+ throw earlyExit(mappedError, { origin: "throw", thrown: useThrown });
2113
+ }
2114
+ const result = useResult;
2115
+ if (result.ok) {
2116
+ const durationMs2 = performance.now() - startTime;
2117
+ emitEvent({
2118
+ type: "step_success",
2119
+ workflowId,
2120
+ stepId,
2121
+ stepKey,
2122
+ name: stepName,
2123
+ ts: Date.now(),
2124
+ durationMs: durationMs2
2125
+ });
2126
+ if (stepKey) {
2127
+ emitEvent({
2128
+ type: "step_complete",
2129
+ workflowId,
2130
+ stepKey,
2131
+ name: stepName,
2132
+ ts: Date.now(),
2133
+ durationMs: durationMs2,
2134
+ result
2135
+ });
2136
+ }
2137
+ return result.value;
2138
+ }
2139
+ const durationMs = performance.now() - startTime;
2140
+ const wrappedError = wrapForStep(result.error, {
2141
+ origin: "result",
2142
+ resultCause: result.cause
2143
+ });
2144
+ emitEvent({
2145
+ type: "step_error",
2146
+ workflowId,
2147
+ stepId,
2148
+ stepKey,
2149
+ name: stepName,
2150
+ ts: Date.now(),
2151
+ durationMs,
2152
+ error: wrappedError
2153
+ });
2154
+ if (stepKey) {
2155
+ emitEvent({
2156
+ type: "step_complete",
2157
+ workflowId,
2158
+ stepKey,
2159
+ name: stepName,
2160
+ ts: Date.now(),
2161
+ durationMs,
2162
+ result,
2163
+ meta: { origin: "result", resultCause: result.cause }
2164
+ });
2165
+ }
2166
+ onError?.(wrappedError, stepName, context);
2167
+ throw earlyExit(wrappedError, {
2168
+ origin: "result",
2169
+ resultCause: result.cause
2170
+ });
2171
+ })();
2172
+ };
2173
+ const step = stepFn;
2174
+ const value = await fn({ step });
2175
+ if (process.env.NODE_ENV !== "production" && value !== null && typeof value === "object" && "ok" in value && typeof value.ok === "boolean") {
2176
+ const maybeResult = value;
2177
+ if (maybeResult.ok === true && "value" in maybeResult || maybeResult.ok === false && "error" in maybeResult) {
2178
+ console.warn(
2179
+ `awaitly: Workflow executor returned a Result-like object. Return raw values, not ok() or err().
2180
+
2181
+ Incorrect: return ok({ data });
2182
+ Correct: return { data };
2183
+
2184
+ See: https://jagreehal.github.io/awaitly/guides/troubleshooting/#returning-ok-from-workflow-executor-double-wrapping`
2185
+ );
2186
+ }
2187
+ }
2188
+ return ok2(value);
2189
+ } catch (error) {
2190
+ if (isMapperException(error)) {
2191
+ throw error.thrown;
2192
+ }
2193
+ if (isEarlyExitE(error)) {
2194
+ const originalCause = error.meta.origin === "throw" ? error.meta.thrown : error.meta.origin === "result" ? error.meta.resultCause : void 0;
2195
+ return err2(error.error, { cause: originalCause });
2196
+ }
2197
+ const mapped = effectiveCatchUnexpected(error);
2198
+ onError?.(mapped, "unexpected", context);
2199
+ return err2(mapped, { cause: error });
2200
+ }
2201
+ }
2202
+ var runStrict = (fn, options) => {
2203
+ return runFn(fn, options);
2204
+ };
2205
+ var run = /* @__PURE__ */ Object.assign(runFn, { strict: runStrict });
2206
+ async function allAsync(results) {
2207
+ if (results.length === 0) {
2208
+ return ok2([]);
2209
+ }
2210
+ return new Promise((resolve) => {
2211
+ let settled = false;
2212
+ let pendingCount = results.length;
2213
+ const values = new Array(results.length);
2214
+ for (let i = 0; i < results.length; i++) {
2215
+ const index = i;
2216
+ Promise.resolve(results[index]).catch((reason) => err2(
2217
+ { type: "PROMISE_REJECTED", cause: reason },
2218
+ { cause: { type: "PROMISE_REJECTION", reason } }
2219
+ )).then((result) => {
2220
+ if (settled) return;
2221
+ if (!result.ok) {
2222
+ settled = true;
2223
+ resolve(result);
2224
+ return;
2225
+ }
2226
+ values[index] = result.value;
2227
+ pendingCount--;
2228
+ if (pendingCount === 0) {
2229
+ resolve(ok2(values));
2230
+ }
2231
+ });
2232
+ }
2233
+ });
2234
+ }
2235
+ export {
2236
+ EARLY_EXIT_SYMBOL,
2237
+ STEP_TIMEOUT_MARKER,
2238
+ createEarlyExit,
2239
+ fallback,
2240
+ getStepTimeoutMeta,
2241
+ isEarlyExit,
2242
+ isStepTimeoutError,
2243
+ retry,
2244
+ run,
2245
+ timeout
2246
+ };
2247
+ //# sourceMappingURL=run.js.map