awaitly 1.34.0 → 2.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 (241) hide show
  1. package/dist/{duration.d.ts → di-BDlT7InM.d.cts} +15 -1
  2. package/dist/{duration.d.cts → di-BbFFfO8y.d.ts} +15 -1
  3. package/dist/errors-DtXvrCiO.d.cts +708 -0
  4. package/dist/errors-DtXvrCiO.d.ts +708 -0
  5. package/dist/index.cjs +4594 -1
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +1970 -141
  8. package/dist/index.d.ts +1970 -141
  9. package/dist/index.js +4398 -1
  10. package/dist/index.js.map +1 -1
  11. package/dist/result.cjs +641 -1
  12. package/dist/result.cjs.map +1 -1
  13. package/dist/result.d.cts +35 -5
  14. package/dist/result.d.ts +35 -5
  15. package/dist/result.js +561 -1
  16. package/dist/result.js.map +1 -1
  17. package/dist/testing.cjs +4202 -8
  18. package/dist/testing.cjs.map +1 -1
  19. package/dist/testing.d.cts +2 -6
  20. package/dist/testing.d.ts +2 -6
  21. package/dist/testing.js +4154 -8
  22. package/dist/testing.js.map +1 -1
  23. package/dist/{run-entry-D2MmJFj9.d.cts → types-B8NfNRGX.d.ts} +1152 -1499
  24. package/dist/{run-entry-Dduz-is2.d.ts → types-BZ2f4MRR.d.cts} +1152 -1499
  25. package/dist/workflow.cjs +7096 -6
  26. package/dist/workflow.cjs.map +1 -1
  27. package/dist/workflow.d.cts +3346 -22
  28. package/dist/workflow.d.ts +3346 -22
  29. package/dist/workflow.js +6929 -6
  30. package/dist/workflow.js.map +1 -1
  31. package/package.json +13 -178
  32. package/dist/adapters.cjs +0 -7
  33. package/dist/adapters.cjs.map +0 -1
  34. package/dist/adapters.d.cts +0 -179
  35. package/dist/adapters.d.ts +0 -179
  36. package/dist/adapters.js +0 -7
  37. package/dist/adapters.js.map +0 -1
  38. package/dist/batch.cjs +0 -7
  39. package/dist/batch.cjs.map +0 -1
  40. package/dist/batch.d.cts +0 -200
  41. package/dist/batch.d.ts +0 -200
  42. package/dist/batch.js +0 -7
  43. package/dist/batch.js.map +0 -1
  44. package/dist/bind-deps.cjs +0 -2
  45. package/dist/bind-deps.cjs.map +0 -1
  46. package/dist/bind-deps.d.cts +0 -28
  47. package/dist/bind-deps.d.ts +0 -28
  48. package/dist/bind-deps.js +0 -2
  49. package/dist/bind-deps.js.map +0 -1
  50. package/dist/cache.cjs +0 -2
  51. package/dist/cache.cjs.map +0 -1
  52. package/dist/cache.d.cts +0 -269
  53. package/dist/cache.d.ts +0 -269
  54. package/dist/cache.js +0 -2
  55. package/dist/cache.js.map +0 -1
  56. package/dist/circuit-breaker.cjs +0 -7
  57. package/dist/circuit-breaker.cjs.map +0 -1
  58. package/dist/circuit-breaker.d.cts +0 -211
  59. package/dist/circuit-breaker.d.ts +0 -211
  60. package/dist/circuit-breaker.js +0 -7
  61. package/dist/circuit-breaker.js.map +0 -1
  62. package/dist/conditional.cjs +0 -2
  63. package/dist/conditional.cjs.map +0 -1
  64. package/dist/conditional.d.cts +0 -252
  65. package/dist/conditional.d.ts +0 -252
  66. package/dist/conditional.js +0 -2
  67. package/dist/conditional.js.map +0 -1
  68. package/dist/core.cjs +0 -7
  69. package/dist/core.cjs.map +0 -1
  70. package/dist/core.d.cts +0 -5
  71. package/dist/core.d.ts +0 -5
  72. package/dist/core.js +0 -7
  73. package/dist/core.js.map +0 -1
  74. package/dist/di-COl5oFnR.d.cts +0 -15
  75. package/dist/di-CyDj_JyZ.d.ts +0 -15
  76. package/dist/diagnostics.cjs +0 -8
  77. package/dist/diagnostics.cjs.map +0 -1
  78. package/dist/diagnostics.d.cts +0 -68
  79. package/dist/diagnostics.d.ts +0 -68
  80. package/dist/diagnostics.js +0 -8
  81. package/dist/diagnostics.js.map +0 -1
  82. package/dist/durable.cjs +0 -11
  83. package/dist/durable.cjs.map +0 -1
  84. package/dist/durable.d.cts +0 -9
  85. package/dist/durable.d.ts +0 -9
  86. package/dist/durable.js +0 -11
  87. package/dist/durable.js.map +0 -1
  88. package/dist/duration.cjs +0 -2
  89. package/dist/duration.cjs.map +0 -1
  90. package/dist/duration.js +0 -2
  91. package/dist/duration.js.map +0 -1
  92. package/dist/engine.cjs +0 -11
  93. package/dist/engine.cjs.map +0 -1
  94. package/dist/engine.d.cts +0 -115
  95. package/dist/engine.d.ts +0 -115
  96. package/dist/engine.js +0 -11
  97. package/dist/engine.js.map +0 -1
  98. package/dist/errors.cjs +0 -2
  99. package/dist/errors.cjs.map +0 -1
  100. package/dist/errors.d.cts +0 -361
  101. package/dist/errors.d.ts +0 -361
  102. package/dist/errors.js +0 -2
  103. package/dist/errors.js.map +0 -1
  104. package/dist/fetch.cjs +0 -7
  105. package/dist/fetch.cjs.map +0 -1
  106. package/dist/fetch.d.cts +0 -86
  107. package/dist/fetch.d.ts +0 -86
  108. package/dist/fetch.js +0 -7
  109. package/dist/fetch.js.map +0 -1
  110. package/dist/flow.cjs +0 -7
  111. package/dist/flow.cjs.map +0 -1
  112. package/dist/flow.d.cts +0 -163
  113. package/dist/flow.d.ts +0 -163
  114. package/dist/flow.js +0 -7
  115. package/dist/flow.js.map +0 -1
  116. package/dist/functional.cjs +0 -2
  117. package/dist/functional.cjs.map +0 -1
  118. package/dist/functional.d.cts +0 -444
  119. package/dist/functional.d.ts +0 -444
  120. package/dist/functional.js +0 -2
  121. package/dist/functional.js.map +0 -1
  122. package/dist/guards-BodHXLzX.d.cts +0 -72
  123. package/dist/guards-CeWoQ8fn.d.ts +0 -72
  124. package/dist/hitl-BPE_1UiM.d.cts +0 -468
  125. package/dist/hitl-byp570uC.d.ts +0 -468
  126. package/dist/hitl.cjs +0 -7
  127. package/dist/hitl.cjs.map +0 -1
  128. package/dist/hitl.d.cts +0 -442
  129. package/dist/hitl.d.ts +0 -442
  130. package/dist/hitl.js +0 -7
  131. package/dist/hitl.js.map +0 -1
  132. package/dist/index-BYT3amEz.d.ts +0 -417
  133. package/dist/index-C_ak66jy.d.cts +0 -417
  134. package/dist/match-entry-DjI2bLpD.d.cts +0 -209
  135. package/dist/match-entry-DjI2bLpD.d.ts +0 -209
  136. package/dist/match.cjs +0 -2
  137. package/dist/match.cjs.map +0 -1
  138. package/dist/match.d.cts +0 -1
  139. package/dist/match.d.ts +0 -1
  140. package/dist/match.js +0 -2
  141. package/dist/match.js.map +0 -1
  142. package/dist/otel.cjs +0 -2
  143. package/dist/otel.cjs.map +0 -1
  144. package/dist/otel.d.cts +0 -188
  145. package/dist/otel.d.ts +0 -188
  146. package/dist/otel.js +0 -2
  147. package/dist/otel.js.map +0 -1
  148. package/dist/persistence-entry-DOMx3woy.d.ts +0 -822
  149. package/dist/persistence-entry-ymCA4iDu.d.cts +0 -822
  150. package/dist/persistence.cjs +0 -2
  151. package/dist/persistence.cjs.map +0 -1
  152. package/dist/persistence.d.cts +0 -7
  153. package/dist/persistence.d.ts +0 -7
  154. package/dist/persistence.js +0 -2
  155. package/dist/persistence.js.map +0 -1
  156. package/dist/policies.cjs +0 -2
  157. package/dist/policies.cjs.map +0 -1
  158. package/dist/policies.d.cts +0 -379
  159. package/dist/policies.d.ts +0 -379
  160. package/dist/policies.js +0 -2
  161. package/dist/policies.js.map +0 -1
  162. package/dist/ratelimit.cjs +0 -7
  163. package/dist/ratelimit.cjs.map +0 -1
  164. package/dist/ratelimit.d.cts +0 -458
  165. package/dist/ratelimit.d.ts +0 -458
  166. package/dist/ratelimit.js +0 -7
  167. package/dist/ratelimit.js.map +0 -1
  168. package/dist/reliability.cjs +0 -11
  169. package/dist/reliability.cjs.map +0 -1
  170. package/dist/reliability.d.cts +0 -11
  171. package/dist/reliability.d.ts +0 -11
  172. package/dist/reliability.js +0 -11
  173. package/dist/reliability.js.map +0 -1
  174. package/dist/resolver.cjs +0 -7
  175. package/dist/resolver.cjs.map +0 -1
  176. package/dist/resolver.d.cts +0 -68
  177. package/dist/resolver.d.ts +0 -68
  178. package/dist/resolver.js +0 -7
  179. package/dist/resolver.js.map +0 -1
  180. package/dist/resource.cjs +0 -7
  181. package/dist/resource.cjs.map +0 -1
  182. package/dist/resource.d.cts +0 -174
  183. package/dist/resource.d.ts +0 -174
  184. package/dist/resource.js +0 -7
  185. package/dist/resource.js.map +0 -1
  186. package/dist/result/retry.cjs +0 -2
  187. package/dist/result/retry.cjs.map +0 -1
  188. package/dist/result/retry.d.cts +0 -70
  189. package/dist/result/retry.d.ts +0 -70
  190. package/dist/result/retry.js +0 -2
  191. package/dist/result/retry.js.map +0 -1
  192. package/dist/retry.cjs +0 -2
  193. package/dist/retry.cjs.map +0 -1
  194. package/dist/retry.d.cts +0 -388
  195. package/dist/retry.d.ts +0 -388
  196. package/dist/retry.js +0 -2
  197. package/dist/retry.js.map +0 -1
  198. package/dist/run.cjs +0 -7
  199. package/dist/run.cjs.map +0 -1
  200. package/dist/run.d.cts +0 -4
  201. package/dist/run.d.ts +0 -4
  202. package/dist/run.js +0 -7
  203. package/dist/run.js.map +0 -1
  204. package/dist/saga.cjs +0 -11
  205. package/dist/saga.cjs.map +0 -1
  206. package/dist/saga.d.cts +0 -164
  207. package/dist/saga.d.ts +0 -164
  208. package/dist/saga.js +0 -11
  209. package/dist/saga.js.map +0 -1
  210. package/dist/singleflight.cjs +0 -2
  211. package/dist/singleflight.cjs.map +0 -1
  212. package/dist/singleflight.d.cts +0 -145
  213. package/dist/singleflight.d.ts +0 -145
  214. package/dist/singleflight.js +0 -2
  215. package/dist/singleflight.js.map +0 -1
  216. package/dist/slugs.cjs +0 -2
  217. package/dist/slugs.cjs.map +0 -1
  218. package/dist/slugs.d.cts +0 -67
  219. package/dist/slugs.d.ts +0 -67
  220. package/dist/slugs.js +0 -2
  221. package/dist/slugs.js.map +0 -1
  222. package/dist/streaming.cjs +0 -9
  223. package/dist/streaming.cjs.map +0 -1
  224. package/dist/streaming.d.cts +0 -596
  225. package/dist/streaming.d.ts +0 -596
  226. package/dist/streaming.js +0 -9
  227. package/dist/streaming.js.map +0 -1
  228. package/dist/tagged-error.cjs +0 -2
  229. package/dist/tagged-error.cjs.map +0 -1
  230. package/dist/tagged-error.d.cts +0 -275
  231. package/dist/tagged-error.d.ts +0 -275
  232. package/dist/tagged-error.js +0 -2
  233. package/dist/tagged-error.js.map +0 -1
  234. package/dist/types-DQmzO9f4.d.ts +0 -323
  235. package/dist/types-qBUOYi-4.d.cts +0 -323
  236. package/dist/webhook.cjs +0 -7
  237. package/dist/webhook.cjs.map +0 -1
  238. package/dist/webhook.d.cts +0 -499
  239. package/dist/webhook.d.ts +0 -499
  240. package/dist/webhook.js +0 -7
  241. package/dist/webhook.js.map +0 -1
package/dist/retry.d.ts DELETED
@@ -1,388 +0,0 @@
1
- import { Duration } from './duration.js';
2
- export { days, hours, isDuration, millis, minutes, seconds, toDays, toHours, toMillis, toMinutes, toSeconds } from './duration.js';
3
-
4
- /**
5
- * awaitly/schedule
6
- *
7
- * Composable scheduling primitives inspired by Effect's Schedule module.
8
- * Build complex retry and polling strategies by composing simple building blocks.
9
- *
10
- * @example
11
- * ```typescript
12
- * // "Exponential backoff with jitter, max 5 attempts, then poll every minute"
13
- * const schedule = Schedule.exponential(Duration.millis(100))
14
- * .pipe(Schedule.jittered(0.2))
15
- * .pipe(Schedule.upTo(5))
16
- * .pipe(Schedule.andThen(Schedule.spaced(Duration.minutes(1))))
17
- *
18
- * // Use with workflows
19
- * const result = await step('fetchData', () => fetchData(), { schedule })
20
- * ```
21
- */
22
-
23
- /**
24
- * The state maintained by a schedule during execution.
25
- */
26
- interface ScheduleState {
27
- /** Number of iterations completed */
28
- readonly iterations: number;
29
- /** Total elapsed time since schedule started */
30
- readonly elapsed: Duration;
31
- /** The last input received (if any) */
32
- readonly lastInput?: unknown;
33
- /** The last output produced (if any) */
34
- readonly lastOutput?: unknown;
35
- /** Combinator-specific metadata (used by andThen, union, intersect, etc.) */
36
- readonly meta?: unknown;
37
- }
38
- /**
39
- * Decision returned by a schedule step.
40
- * Combinators can optionally provide `nextState` to thread custom state through execution.
41
- */
42
- type ScheduleDecision<Out> = {
43
- readonly _tag: "Continue";
44
- readonly delay: Duration;
45
- readonly output: Out;
46
- readonly nextState?: ScheduleState;
47
- } | {
48
- readonly _tag: "Done";
49
- };
50
- /**
51
- * A schedule that repeats forever with no delay.
52
- */
53
- declare function forever<In = unknown>(): Schedule<In, number>;
54
- /**
55
- * A schedule that repeats exactly n times.
56
- *
57
- * @example
58
- * ```typescript
59
- * const thrice = Schedule.recurs(3)
60
- * ```
61
- */
62
- declare function recurs<In = unknown>(n: number): Schedule<In, number>;
63
- /**
64
- * A schedule that repeats once.
65
- */
66
- declare function once<In = unknown>(): Schedule<In, void>;
67
- /**
68
- * A schedule that always stops immediately.
69
- */
70
- declare function stop<In = unknown>(): Schedule<In, never>;
71
- /**
72
- * A schedule that waits a fixed duration between each iteration.
73
- *
74
- * @example
75
- * ```typescript
76
- * const pollEvery5s = Schedule.spaced(Duration.seconds(5))
77
- * ```
78
- */
79
- declare function spaced<In = unknown>(delay: Duration): Schedule<In, number>;
80
- /**
81
- * Alias for spaced - a fixed interval schedule.
82
- */
83
- declare const fixed: typeof spaced;
84
- /**
85
- * A schedule with exponentially increasing delays.
86
- * delay(n) = base * factor^n
87
- *
88
- * @example
89
- * ```typescript
90
- * // 100ms, 200ms, 400ms, 800ms, ...
91
- * const exponential = Schedule.exponential(Duration.millis(100))
92
- *
93
- * // With custom factor: 100ms, 300ms, 900ms, ...
94
- * const triple = Schedule.exponential(Duration.millis(100), 3)
95
- * ```
96
- */
97
- declare function exponential<In = unknown>(base: Duration, factor?: number): Schedule<In, Duration>;
98
- /**
99
- * A schedule with linearly increasing delays.
100
- * delay(n) = base * (n + 1)
101
- *
102
- * @example
103
- * ```typescript
104
- * // 100ms, 200ms, 300ms, 400ms, ...
105
- * const linear = Schedule.linear(Duration.millis(100))
106
- * ```
107
- */
108
- declare function linear<In = unknown>(base: Duration): Schedule<In, Duration>;
109
- /**
110
- * A schedule with fibonacci-sequence delays.
111
- * delay(n) follows fibonacci: base, base, 2*base, 3*base, 5*base, ...
112
- *
113
- * @example
114
- * ```typescript
115
- * // 100ms, 100ms, 200ms, 300ms, 500ms, 800ms, ...
116
- * const fib = Schedule.fibonacci(Duration.millis(100))
117
- * ```
118
- */
119
- declare function fibonacci<In = unknown>(base: Duration): Schedule<In, Duration>;
120
- /**
121
- * Limit a schedule to at most n iterations.
122
- *
123
- * @example
124
- * ```typescript
125
- * // Exponential backoff, max 5 attempts
126
- * const limited = Schedule.exponential(Duration.millis(100))
127
- * .pipe(Schedule.upTo(5))
128
- * ```
129
- */
130
- declare function upTo<In, Out>(n: number): (schedule: Schedule<In, Out>) => Schedule<In, Out>;
131
- /**
132
- * Limit a schedule by total elapsed time.
133
- *
134
- * @example
135
- * ```typescript
136
- * // Retry for at most 30 seconds
137
- * const timeLimited = Schedule.spaced(Duration.seconds(1))
138
- * .pipe(Schedule.upToElapsed(Duration.seconds(30)))
139
- * ```
140
- */
141
- declare function upToElapsed<In, Out>(maxElapsed: Duration): (schedule: Schedule<In, Out>) => Schedule<In, Out>;
142
- /**
143
- * Cap the maximum delay of a schedule.
144
- *
145
- * @example
146
- * ```typescript
147
- * // Exponential, but never more than 30 seconds
148
- * const capped = Schedule.exponential(Duration.millis(100))
149
- * .pipe(Schedule.maxDelay(Duration.seconds(30)))
150
- * ```
151
- */
152
- declare function maxDelay<In, Out>(max: Duration): (schedule: Schedule<In, Out>) => Schedule<In, Out>;
153
- /**
154
- * Set a minimum delay for a schedule.
155
- *
156
- * @example
157
- * ```typescript
158
- * const atLeast1s = schedule.pipe(Schedule.minDelay(Duration.seconds(1)))
159
- * ```
160
- */
161
- declare function minDelay<In, Out>(min: Duration): (schedule: Schedule<In, Out>) => Schedule<In, Out>;
162
- /**
163
- * Continue while a predicate on the input returns true.
164
- *
165
- * @example
166
- * ```typescript
167
- * // Retry while the error is transient
168
- * const retryTransient = Schedule.exponential(Duration.millis(100))
169
- * .pipe(Schedule.whileInput((err: Error) => err.message.includes("ECONNRESET")))
170
- * ```
171
- */
172
- declare function whileInput<In, Out>(predicate: (input: In) => boolean): (schedule: Schedule<In, Out>) => Schedule<In, Out>;
173
- /**
174
- * Continue while a predicate on the output returns true.
175
- *
176
- * @example
177
- * ```typescript
178
- * // Poll until status is "ready"
179
- * const untilReady = Schedule.spaced(Duration.seconds(1))
180
- * .pipe(Schedule.whileOutput((status: string) => status !== "ready"))
181
- * ```
182
- */
183
- declare function whileOutput<In, Out>(predicate: (output: Out) => boolean): (schedule: Schedule<In, Out>) => Schedule<In, Out>;
184
- /**
185
- * Continue until a predicate on the input returns true.
186
- * Opposite of whileInput.
187
- */
188
- declare function untilInput<In, Out>(predicate: (input: In) => boolean): (schedule: Schedule<In, Out>) => Schedule<In, Out>;
189
- /**
190
- * Continue until a predicate on the output returns true.
191
- * Opposite of whileOutput.
192
- */
193
- declare function untilOutput<In, Out>(predicate: (output: Out) => boolean): (schedule: Schedule<In, Out>) => Schedule<In, Out>;
194
- /**
195
- * Add random jitter to delays to prevent thundering herd.
196
- *
197
- * @param factor - Jitter factor (0.0 to 1.0). Delay will be multiplied by (1 - factor) to (1 + factor).
198
- *
199
- * @example
200
- * ```typescript
201
- * // ±20% jitter
202
- * const jittered = Schedule.exponential(Duration.millis(100))
203
- * .pipe(Schedule.jittered(0.2))
204
- * ```
205
- */
206
- declare function jittered<In, Out>(factor?: number): (schedule: Schedule<In, Out>) => Schedule<In, Out>;
207
- /**
208
- * Add a fixed random delay to each iteration.
209
- *
210
- * @example
211
- * ```typescript
212
- * // Add 0-500ms random delay
213
- * const randomized = schedule.pipe(Schedule.addDelay(Duration.millis(500)))
214
- * ```
215
- */
216
- declare function addDelay<In, Out>(maxExtra: Duration): (schedule: Schedule<In, Out>) => Schedule<In, Out>;
217
- /**
218
- * Chain two schedules: run the first until done, then run the second.
219
- * The second schedule starts with fresh state when it begins.
220
- *
221
- * @example
222
- * ```typescript
223
- * // 5 exponential retries, then poll every minute
224
- * const strategy = Schedule.exponential(Duration.millis(100))
225
- * .pipe(Schedule.upTo(5))
226
- * .pipe(Schedule.andThen(Schedule.spaced(Duration.minutes(1))))
227
- * ```
228
- */
229
- declare function andThen<In, Out1, Out2>(second: Schedule<In, Out2>): (first: Schedule<In, Out1>) => Schedule<In, Out1 | Out2>;
230
- /**
231
- * Run two schedules in parallel, using the shorter delay.
232
- * Both schedules advance their state independently.
233
- *
234
- * @example
235
- * ```typescript
236
- * // Use whichever delay is shorter
237
- * const union = Schedule.union(
238
- * Schedule.exponential(Duration.millis(100)),
239
- * Schedule.spaced(Duration.seconds(1))
240
- * )
241
- * ```
242
- */
243
- declare function union<In, Out1, Out2>(first: Schedule<In, Out1>, second: Schedule<In, Out2>): Schedule<In, [Out1, Out2]>;
244
- /**
245
- * Run two schedules in parallel, using the longer delay.
246
- * Both schedules advance their state independently. Stops when either schedule stops.
247
- *
248
- * @example
249
- * ```typescript
250
- * // Use whichever delay is longer
251
- * const intersect = Schedule.intersect(
252
- * Schedule.exponential(Duration.millis(100)),
253
- * Schedule.spaced(Duration.seconds(1))
254
- * )
255
- * ```
256
- */
257
- declare function intersect<In, Out1, Out2>(first: Schedule<In, Out1>, second: Schedule<In, Out2>): Schedule<In, [Out1, Out2]>;
258
- /**
259
- * Transform the output of a schedule.
260
- *
261
- * @example
262
- * ```typescript
263
- * const withIteration = Schedule.spaced(Duration.seconds(1))
264
- * .pipe(Schedule.map((n) => ({ attempt: n + 1 })))
265
- * ```
266
- */
267
- declare function map<In, Out, NewOut>(fn: (output: Out) => NewOut): (schedule: Schedule<In, Out>) => Schedule<In, NewOut>;
268
- /**
269
- * Perform a side effect on each iteration.
270
- *
271
- * @example
272
- * ```typescript
273
- * const logged = Schedule.exponential(Duration.millis(100))
274
- * .pipe(Schedule.tap((delay) => console.log(`Waiting ${delay}ms`)))
275
- * ```
276
- */
277
- declare function tap<In, Out>(fn: (output: Out, state: ScheduleState) => void): (schedule: Schedule<In, Out>) => Schedule<In, Out>;
278
- /**
279
- * Modify the delay of a schedule.
280
- *
281
- * @example
282
- * ```typescript
283
- * const doubled = schedule.pipe(Schedule.modifyDelay(d => Duration.multiply(d, 2)))
284
- * ```
285
- */
286
- declare function modifyDelay<In, Out>(fn: (delay: Duration, output: Out) => Duration): (schedule: Schedule<In, Out>) => Schedule<In, Out>;
287
- /**
288
- * Create an iterator for running a schedule step-by-step.
289
- *
290
- * @example
291
- * ```typescript
292
- * const runner = Schedule.run(mySchedule)
293
- *
294
- * while (true) {
295
- * const next = runner.next(lastResult)
296
- * if (next.done) break
297
- * await sleep(next.value.delay)
298
- * }
299
- * ```
300
- */
301
- declare function run<In, Out>(schedule: Schedule<In, Out>): {
302
- next: (input: In) => {
303
- done: false;
304
- value: {
305
- delay: Duration;
306
- output: Out;
307
- };
308
- } | {
309
- done: true;
310
- };
311
- };
312
- /**
313
- * Get all delays from a schedule (for testing/visualization).
314
- * Runs the schedule with undefined input until it completes or reaches maxIterations.
315
- */
316
- declare function delays<Out>(schedule: Schedule<undefined, Out>, maxIterations?: number): Duration[];
317
- /**
318
- * A schedule with pipe support for method chaining.
319
- */
320
- type PipedSchedule<In, Out> = Schedule<In, Out> & {
321
- pipe: <NewOut>(fn: (s: Schedule<In, Out>) => Schedule<In, NewOut>) => PipedSchedule<In, NewOut>;
322
- } & {
323
- pipe: <R>(fn: (s: Schedule<In, Out>) => R) => R;
324
- };
325
- /**
326
- * A Schedule defines a recurring pattern with delays and outputs.
327
- *
328
- * @typeParam In - The input type (from retry attempts, etc.)
329
- * @typeParam Out - The output type (often the delay or iteration count)
330
- */
331
- interface Schedule<In = unknown, Out = unknown> {
332
- readonly _tag: "Schedule";
333
- /** Compute the next step given input and current state */
334
- readonly step: (input: In, state: ScheduleState) => ScheduleDecision<Out>;
335
- /** Initial state for this schedule */
336
- readonly initial: ScheduleState;
337
- }
338
- /**
339
- * Schedule namespace for composable scheduling.
340
- *
341
- * @example
342
- * ```typescript
343
- * import { Schedule, Duration } from "awaitly";
344
- *
345
- * // Exponential backoff with jitter, max 5 attempts
346
- * const retry = Schedule.exponential(Duration.millis(100))
347
- * .pipe(Schedule.jittered(0.2))
348
- * .pipe(Schedule.upTo(5))
349
- * .pipe(Schedule.maxDelay(Duration.seconds(30)))
350
- *
351
- * // Then poll every minute forever
352
- * const poll = Schedule.spaced(Duration.minutes(1))
353
- *
354
- * // Chain them
355
- * const strategy = retry.pipe(Schedule.andThen(poll))
356
- * ```
357
- */
358
- declare const Schedule: {
359
- readonly forever: <In = unknown>() => PipedSchedule<In, number>;
360
- readonly once: <In = unknown>() => PipedSchedule<In, void>;
361
- readonly recurs: <In = unknown>(n: number) => PipedSchedule<In, number>;
362
- readonly stop: typeof stop;
363
- readonly spaced: <In = unknown>(delay: Duration) => PipedSchedule<In, number>;
364
- readonly fixed: <In = unknown>(delay: Duration) => PipedSchedule<In, number>;
365
- readonly exponential: <In = unknown>(base: Duration, factor?: number) => PipedSchedule<In, Duration>;
366
- readonly linear: <In = unknown>(base: Duration) => PipedSchedule<In, Duration>;
367
- readonly fibonacci: <In = unknown>(base: Duration) => PipedSchedule<In, Duration>;
368
- readonly upTo: typeof upTo;
369
- readonly upToElapsed: typeof upToElapsed;
370
- readonly maxDelay: typeof maxDelay;
371
- readonly minDelay: typeof minDelay;
372
- readonly whileInput: typeof whileInput;
373
- readonly whileOutput: typeof whileOutput;
374
- readonly untilInput: typeof untilInput;
375
- readonly untilOutput: typeof untilOutput;
376
- readonly jittered: typeof jittered;
377
- readonly addDelay: typeof addDelay;
378
- readonly andThen: typeof andThen;
379
- readonly union: <In, Out1, Out2>(first: Schedule<In, Out1>, second: Schedule<In, Out2>) => PipedSchedule<In, [Out1, Out2]>;
380
- readonly intersect: <In, Out1, Out2>(first: Schedule<In, Out1>, second: Schedule<In, Out2>) => PipedSchedule<In, [Out1, Out2]>;
381
- readonly map: typeof map;
382
- readonly tap: typeof tap;
383
- readonly modifyDelay: typeof modifyDelay;
384
- readonly run: typeof run;
385
- readonly delays: typeof delays;
386
- };
387
-
388
- export { Duration, Duration as DurationType, Schedule, type ScheduleDecision, type ScheduleState, Schedule as ScheduleType, addDelay, andThen, delays, exponential, fibonacci, fixed, forever, intersect, jittered, linear, map, maxDelay, minDelay, modifyDelay, once, recurs, run, spaced, stop, tap, union, untilInput, untilOutput, upTo, upToElapsed, whileInput, whileOutput };
package/dist/retry.js DELETED
@@ -1,2 +0,0 @@
1
- function D(t){return{_tag:"Duration",millis:t}}function w(t){return{_tag:"Duration",millis:t*1e3}}function T(t){return{_tag:"Duration",millis:t*60*1e3}}function k(t){return{_tag:"Duration",millis:t*60*60*1e3}}function M(t){return{_tag:"Duration",millis:t*24*60*60*1e3}}var R={_tag:"Duration",millis:0},H={_tag:"Duration",millis:1/0};function l(t){return t.millis}function P(t){return t.millis/1e3}function C(t){return t.millis/(60*1e3)}function W(t){return t.millis/(3600*1e3)}function N(t){return t.millis/(1440*60*1e3)}function _(t,e){return{_tag:"Duration",millis:t.millis+e.millis}}function L(t,e){return{_tag:"Duration",millis:Math.max(0,t.millis-e.millis)}}function x(t,e){return{_tag:"Duration",millis:t.millis*e}}function Z(t,e){return{_tag:"Duration",millis:t.millis/e}}function B(t,e){return t.millis<e.millis}function G(t,e){return t.millis<=e.millis}function J(t,e){return t.millis>e.millis}function K(t,e){return t.millis>=e.millis}function Q(t,e){return t.millis===e.millis}function j(t,e){return t.millis<=e.millis?t:e}function F(t,e){return t.millis>=e.millis?t:e}function U(t,e,n){return j(F(t,e),n)}function V(t){return t.millis===0}function X(t){return t.millis===1/0}function Y(t){return Number.isFinite(t.millis)&&t.millis>0}function $(t){return typeof t=="object"&&t!==null&&"_tag"in t&&t._tag==="Duration"&&"millis"in t&&typeof t.millis=="number"}function tt(t){let e=t.millis;if(e===1/0)return"\u221E";if(e===0)return"0ms";let n=Math.floor(e/(1440*60*1e3)),u=Math.floor(e%(1440*60*1e3)/(3600*1e3)),i=Math.floor(e%(3600*1e3)/(60*1e3)),o=Math.floor(e%(60*1e3)/1e3),r=e%1e3,a=[];return n>0&&a.push(`${n}d`),u>0&&a.push(`${u}h`),i>0&&a.push(`${i}m`),o>0&&a.push(`${o}s`),r>0&&a.length===0&&a.push(`${r}ms`),a.join(" ")||"0ms"}function et(t){let e=t.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);if(!e)return;let n=parseFloat(e[1]);switch(e[2].toLowerCase()){case"ms":return D(n);case"s":return w(n);case"m":return T(n);case"h":return k(n);case"d":return M(n);default:return}}var I={millis:D,seconds:w,minutes:T,hours:k,days:M,zero:R,infinity:H,toMillis:l,toSeconds:P,toMinutes:C,toHours:W,toDays:N,add:_,subtract:L,multiply:x,divide:Z,lessThan:B,lessThanOrEqual:G,greaterThan:J,greaterThanOrEqual:K,equals:Q,min:j,max:F,clamp:U,isZero:V,isInfinite:X,isFinite:Y,isDuration:$,format:tt,parse:et};var h={iterations:0,elapsed:I.zero,lastInput:void 0,lastOutput:void 0};function d(t,e){return{_tag:"Continue",delay:t,output:e}}function S(){return{_tag:"Done"}}function c(t,e,n,u){return{iterations:t.iterations+1,elapsed:_(t.elapsed,e),lastInput:n,lastOutput:u}}function nt(){return{_tag:"Schedule",initial:h,step:(t,e)=>d(I.zero,e.iterations)}}function ut(t){return{_tag:"Schedule",initial:h,step:(e,n)=>n.iterations<t?d(I.zero,n.iterations):S()}}function it(){return{_tag:"Schedule",initial:h,step:(t,e)=>e.iterations===0?d(I.zero,void 0):S()}}function ot(){return{_tag:"Schedule",initial:h,step:()=>S()}}function z(t){return{_tag:"Schedule",initial:h,step:(e,n)=>d(t,n.iterations)}}var $t=z;function rt(t,e=2){return{_tag:"Schedule",initial:h,step:(n,u)=>{let i=x(t,Math.pow(e,u.iterations));return d(i,i)}}}function at(t){return{_tag:"Schedule",initial:h,step:(e,n)=>{let u=x(t,n.iterations+1);return d(u,u)}}}function lt(t){let e=[1,1];for(let n=2;n<50;n++)e[n]=e[n-1]+e[n-2];return{_tag:"Schedule",initial:h,step:(n,u)=>{let i=Math.min(u.iterations,e.length-1),o=x(t,e[i]);return d(o,o)}}}function st(t){return e=>({_tag:"Schedule",initial:e.initial,step:(n,u)=>u.iterations>=t?S():e.step(n,u)})}function ct(t){return e=>({_tag:"Schedule",initial:e.initial,step:(n,u)=>l(u.elapsed)>=l(t)?S():e.step(n,u)})}function dt(t){return e=>({_tag:"Schedule",initial:e.initial,step:(n,u)=>{let i=e.step(n,u);if(i._tag==="Done")return i;let o=l(i.delay)>l(t)?t:i.delay;return d(o,i.output)}})}function pt(t){return e=>({_tag:"Schedule",initial:e.initial,step:(n,u)=>{let i=e.step(n,u);if(i._tag==="Done")return i;let o=l(i.delay)<l(t)?t:i.delay;return d(o,i.output)}})}function q(t){return e=>({_tag:"Schedule",initial:e.initial,step:(n,u)=>t(n)?e.step(n,u):S()})}function A(t){return e=>({_tag:"Schedule",initial:e.initial,step:(n,u)=>{let i=e.step(n,u);return i._tag==="Done"||t(i.output)?i:S()}})}function St(t){return q(e=>!t(e))}function ht(t){return A(e=>!t(e))}function ft(t=.2){return e=>({_tag:"Schedule",initial:e.initial,step:(n,u)=>{let i=e.step(n,u);if(i._tag==="Done")return i;let o=1-t+Math.random()*t*2,r=D(l(i.delay)*o);return d(r,i.output)}})}function Dt(t){return e=>({_tag:"Schedule",initial:e.initial,step:(n,u)=>{let i=e.step(n,u);if(i._tag==="Done")return i;let o=D(Math.random()*l(t)),r=_(i.delay,o);return d(r,i.output)}})}function mt(t){return e=>{let n={inSecondPhase:!1,firstState:e.initial,secondState:t.initial};return{_tag:"Schedule",initial:{...h,meta:n},step:(u,i)=>{let o=i.meta??n;if(!o.inSecondPhase){let p=e.step(u,o.firstState);if(p._tag==="Continue"){let g=p.nextState??c(o.firstState,p.delay,u,p.output),b={...c(i,p.delay,u,p.output),meta:{...o,firstState:g}};return{_tag:"Continue",delay:p.delay,output:p.output,nextState:b}}let s=t.step(u,t.initial);if(s._tag==="Done")return S();let m=s.nextState??c(t.initial,s.delay,u,s.output),y={...c(i,s.delay,u,s.output),meta:{inSecondPhase:!0,firstState:o.firstState,secondState:m}};return{_tag:"Continue",delay:s.delay,output:s.output,nextState:y}}let r=t.step(u,o.secondState);if(r._tag==="Done")return S();let a=r.nextState??c(o.secondState,r.delay,u,r.output),O={...c(i,r.delay,u,r.output),meta:{...o,secondState:a}};return{_tag:"Continue",delay:r.delay,output:r.output,nextState:O}}}}}function yt(t,e){let n={firstState:t.initial,secondState:e.initial};return{_tag:"Schedule",initial:{...h,meta:n},step:(u,i)=>{let o=i.meta??n,r=t.step(u,o.firstState),a=e.step(u,o.secondState);if(r._tag==="Done"&&a._tag==="Done")return S();let O=r._tag==="Continue"?r.nextState??c(o.firstState,r.delay,u,r.output):o.firstState,p=a._tag==="Continue"?a.nextState??c(o.secondState,a.delay,u,a.output):o.secondState,s=r._tag==="Continue"?l(r.delay):1/0,m=a._tag==="Continue"?l(a.delay):1/0,y=D(Math.min(s,m)),g=[r._tag==="Continue"?r.output:void 0,a._tag==="Continue"?a.output:void 0],b={...c(i,y,u,g),meta:{firstState:O,secondState:p}};return{_tag:"Continue",delay:y,output:g,nextState:b}}}}function It(t,e){let n={firstState:t.initial,secondState:e.initial};return{_tag:"Schedule",initial:{...h,meta:n},step:(u,i)=>{let o=i.meta??n,r=t.step(u,o.firstState),a=e.step(u,o.secondState);if(r._tag==="Done"||a._tag==="Done")return S();let O=r.nextState??c(o.firstState,r.delay,u,r.output),p=a.nextState??c(o.secondState,a.delay,u,a.output),s=D(Math.max(l(r.delay),l(a.delay))),m=[r.output,a.output],y={...c(i,s,u,m),meta:{firstState:O,secondState:p}};return{_tag:"Continue",delay:s,output:m,nextState:y}}}}function Ot(t){return e=>({_tag:"Schedule",initial:e.initial,step:(n,u)=>{let i=e.step(n,u);return i._tag==="Done"?S():d(i.delay,t(i.output))}})}function xt(t){return e=>({_tag:"Schedule",initial:e.initial,step:(n,u)=>{let i=e.step(n,u);return i._tag==="Continue"&&t(i.output,u),i}})}function gt(t){return e=>({_tag:"Schedule",initial:e.initial,step:(n,u)=>{let i=e.step(n,u);return i._tag==="Done"?i:d(t(i.delay,i.output),i.output)}})}function E(t){let e=t.initial;return{next(n){let u=t.step(n,e);return u._tag==="Done"?{done:!0}:(e=u.nextState??c(e,u.delay,n,u.output),{done:!1,value:{delay:u.delay,output:u.output}})}}}function _t(t,e=100){let n=[],u=E(t);for(let i=0;i<e;i++){let o=u.next(void 0);if(o.done)break;n.push(o.value.delay)}return n}function bt(t){return typeof t=="object"&&t!==null&&"_tag"in t&&t._tag==="Schedule"}function f(t){return{...t,pipe(e){let n=e(t);return bt(n)?f(n):n}}}var v=t=>f(z(t)),wt=(t,e)=>f(rt(t,e)),Tt=t=>f(at(t)),kt=t=>f(lt(t)),Mt=t=>f(ut(t)),Pt=()=>f(nt()),Ct=()=>f(it()),Wt=(t,e)=>f(yt(t,e)),Nt=(t,e)=>f(It(t,e)),vt={forever:Pt,once:Ct,recurs:Mt,stop:ot,spaced:v,fixed:v,exponential:wt,linear:Tt,fibonacci:kt,upTo:st,upToElapsed:ct,maxDelay:dt,minDelay:pt,whileInput:q,whileOutput:A,untilInput:St,untilOutput:ht,jittered:ft,addDelay:Dt,andThen:mt,union:Wt,intersect:Nt,map:Ot,tap:xt,modifyDelay:gt,run:E,delays:_t};export{I as Duration,vt as Schedule,Dt as addDelay,mt as andThen,M as days,_t as delays,rt as exponential,lt as fibonacci,$t as fixed,nt as forever,k as hours,It as intersect,$ as isDuration,ft as jittered,at as linear,Ot as map,dt as maxDelay,D as millis,pt as minDelay,T as minutes,gt as modifyDelay,it as once,ut as recurs,E as run,w as seconds,z as spaced,ot as stop,xt as tap,N as toDays,W as toHours,l as toMillis,C as toMinutes,P as toSeconds,yt as union,St as untilInput,ht as untilOutput,st as upTo,ct as upToElapsed,q as whileInput,A as whileOutput};
2
- //# sourceMappingURL=retry.js.map
package/dist/retry.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/duration.ts","../src/schedule/index.ts"],"sourcesContent":["/**\n * awaitly/duration\n *\n * Type-safe duration handling inspired by Effect's Duration module.\n * Prevents unit confusion (milliseconds vs seconds) with explicit constructors.\n */\n\n// =============================================================================\n// Duration Type\n// =============================================================================\n\n/**\n * A type-safe representation of a time duration.\n * Use the constructor functions (millis, seconds, etc.) to create durations.\n */\nexport interface Duration {\n readonly _tag: \"Duration\";\n readonly millis: number;\n}\n\n// =============================================================================\n// Constructors\n// =============================================================================\n\n/**\n * Create a Duration from milliseconds.\n *\n * @example\n * ```typescript\n * const d = Duration.millis(500)\n * ```\n */\nexport function millis(ms: number): Duration {\n return { _tag: \"Duration\", millis: ms };\n}\n\n/**\n * Create a Duration from seconds.\n *\n * @example\n * ```typescript\n * const d = Duration.seconds(5) // 5000ms\n * ```\n */\nexport function seconds(s: number): Duration {\n return { _tag: \"Duration\", millis: s * 1000 };\n}\n\n/**\n * Create a Duration from minutes.\n *\n * @example\n * ```typescript\n * const d = Duration.minutes(2) // 120000ms\n * ```\n */\nexport function minutes(m: number): Duration {\n return { _tag: \"Duration\", millis: m * 60 * 1000 };\n}\n\n/**\n * Create a Duration from hours.\n *\n * @example\n * ```typescript\n * const d = Duration.hours(1) // 3600000ms\n * ```\n */\nexport function hours(h: number): Duration {\n return { _tag: \"Duration\", millis: h * 60 * 60 * 1000 };\n}\n\n/**\n * Create a Duration from days.\n *\n * @example\n * ```typescript\n * const d = Duration.days(1) // 86400000ms\n * ```\n */\nexport function days(d: number): Duration {\n return { _tag: \"Duration\", millis: d * 24 * 60 * 60 * 1000 };\n}\n\n/**\n * Zero duration.\n */\nexport const zero: Duration = { _tag: \"Duration\", millis: 0 };\n\n/**\n * Infinite duration (represented as Infinity milliseconds).\n */\nexport const infinity: Duration = { _tag: \"Duration\", millis: Infinity };\n\n// =============================================================================\n// Conversions\n// =============================================================================\n\n/**\n * Convert a Duration to milliseconds.\n */\nexport function toMillis(duration: Duration): number {\n return duration.millis;\n}\n\n/**\n * Convert a Duration to seconds.\n */\nexport function toSeconds(duration: Duration): number {\n return duration.millis / 1000;\n}\n\n/**\n * Convert a Duration to minutes.\n */\nexport function toMinutes(duration: Duration): number {\n return duration.millis / (60 * 1000);\n}\n\n/**\n * Convert a Duration to hours.\n */\nexport function toHours(duration: Duration): number {\n return duration.millis / (60 * 60 * 1000);\n}\n\n/**\n * Convert a Duration to days.\n */\nexport function toDays(duration: Duration): number {\n return duration.millis / (24 * 60 * 60 * 1000);\n}\n\n// =============================================================================\n// Operations\n// =============================================================================\n\n/**\n * Add two durations.\n *\n * @example\n * ```typescript\n * const total = Duration.add(Duration.seconds(5), Duration.millis(500))\n * // 5500ms\n * ```\n */\nexport function add(a: Duration, b: Duration): Duration {\n return { _tag: \"Duration\", millis: a.millis + b.millis };\n}\n\n/**\n * Subtract duration b from duration a.\n * Result is clamped to zero (no negative durations).\n *\n * @example\n * ```typescript\n * const remaining = Duration.subtract(Duration.seconds(5), Duration.seconds(2))\n * // 3000ms\n * ```\n */\nexport function subtract(a: Duration, b: Duration): Duration {\n return { _tag: \"Duration\", millis: Math.max(0, a.millis - b.millis) };\n}\n\n/**\n * Multiply a duration by a factor.\n *\n * @example\n * ```typescript\n * const doubled = Duration.multiply(Duration.seconds(5), 2)\n * // 10000ms\n * ```\n */\nexport function multiply(duration: Duration, factor: number): Duration {\n return { _tag: \"Duration\", millis: duration.millis * factor };\n}\n\n/**\n * Divide a duration by a divisor.\n *\n * @example\n * ```typescript\n * const half = Duration.divide(Duration.seconds(10), 2)\n * // 5000ms\n * ```\n */\nexport function divide(duration: Duration, divisor: number): Duration {\n return { _tag: \"Duration\", millis: duration.millis / divisor };\n}\n\n// =============================================================================\n// Comparisons\n// =============================================================================\n\n/**\n * Check if duration a is less than duration b.\n */\nexport function lessThan(a: Duration, b: Duration): boolean {\n return a.millis < b.millis;\n}\n\n/**\n * Check if duration a is less than or equal to duration b.\n */\nexport function lessThanOrEqual(a: Duration, b: Duration): boolean {\n return a.millis <= b.millis;\n}\n\n/**\n * Check if duration a is greater than duration b.\n */\nexport function greaterThan(a: Duration, b: Duration): boolean {\n return a.millis > b.millis;\n}\n\n/**\n * Check if duration a is greater than or equal to duration b.\n */\nexport function greaterThanOrEqual(a: Duration, b: Duration): boolean {\n return a.millis >= b.millis;\n}\n\n/**\n * Check if two durations are equal.\n */\nexport function equals(a: Duration, b: Duration): boolean {\n return a.millis === b.millis;\n}\n\n/**\n * Get the minimum of two durations.\n */\nexport function min(a: Duration, b: Duration): Duration {\n return a.millis <= b.millis ? a : b;\n}\n\n/**\n * Get the maximum of two durations.\n */\nexport function max(a: Duration, b: Duration): Duration {\n return a.millis >= b.millis ? a : b;\n}\n\n/**\n * Clamp a duration between a minimum and maximum.\n */\nexport function clamp(duration: Duration, minimum: Duration, maximum: Duration): Duration {\n return min(max(duration, minimum), maximum);\n}\n\n// =============================================================================\n// Predicates\n// =============================================================================\n\n/**\n * Check if a duration is zero.\n */\nexport function isZero(duration: Duration): boolean {\n return duration.millis === 0;\n}\n\n/**\n * Check if a duration is infinite.\n */\nexport function isInfinite(duration: Duration): boolean {\n return duration.millis === Infinity;\n}\n\n/**\n * Check if a duration is finite and positive.\n */\nexport function isFinite(duration: Duration): boolean {\n return Number.isFinite(duration.millis) && duration.millis > 0;\n}\n\n/**\n * Type guard to check if a value is a Duration.\n */\nexport function isDuration(value: unknown): value is Duration {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"_tag\" in value &&\n value._tag === \"Duration\" &&\n \"millis\" in value &&\n typeof value.millis === \"number\"\n );\n}\n\n// =============================================================================\n// Formatting\n// =============================================================================\n\n/**\n * Format a duration as a human-readable string.\n *\n * @example\n * ```typescript\n * Duration.format(Duration.seconds(90)) // \"1m 30s\"\n * Duration.format(Duration.millis(500)) // \"500ms\"\n * ```\n */\nexport function format(duration: Duration): string {\n const ms = duration.millis;\n\n if (ms === Infinity) return \"∞\";\n if (ms === 0) return \"0ms\";\n\n const days = Math.floor(ms / (24 * 60 * 60 * 1000));\n const hours = Math.floor((ms % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));\n const minutes = Math.floor((ms % (60 * 60 * 1000)) / (60 * 1000));\n const seconds = Math.floor((ms % (60 * 1000)) / 1000);\n const millis = ms % 1000;\n\n const parts: string[] = [];\n if (days > 0) parts.push(`${days}d`);\n if (hours > 0) parts.push(`${hours}h`);\n if (minutes > 0) parts.push(`${minutes}m`);\n if (seconds > 0) parts.push(`${seconds}s`);\n if (millis > 0 && parts.length === 0) parts.push(`${millis}ms`);\n\n return parts.join(\" \") || \"0ms\";\n}\n\n// =============================================================================\n// Parsing\n// =============================================================================\n\n/**\n * Parse a duration from a string like \"100ms\", \"5s\", \"2m\", \"1h\", \"1d\".\n * Returns undefined if parsing fails.\n *\n * @example\n * ```typescript\n * Duration.parse(\"5s\") // Duration.seconds(5)\n * Duration.parse(\"100ms\") // Duration.millis(100)\n * Duration.parse(\"2m\") // Duration.minutes(2)\n * ```\n */\nexport function parse(input: string): Duration | undefined {\n const match = input.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d)$/i);\n if (!match) return undefined;\n\n const value = parseFloat(match[1]);\n const unit = match[2].toLowerCase();\n\n switch (unit) {\n case \"ms\":\n return millis(value);\n case \"s\":\n return seconds(value);\n case \"m\":\n return minutes(value);\n case \"h\":\n return hours(value);\n case \"d\":\n return days(value);\n default:\n return undefined;\n }\n}\n\n// =============================================================================\n// Namespace Export\n// =============================================================================\n\n/**\n * Duration namespace with all functions for convenient access.\n *\n * @example\n * ```typescript\n * import { Duration } from \"awaitly\";\n *\n * const timeout = Duration.seconds(30);\n * const delay = Duration.millis(100);\n * const total = Duration.add(timeout, delay);\n *\n * console.log(Duration.format(total)); // \"30s 100ms\"\n * ```\n */\nexport const Duration = {\n // Constructors\n millis,\n seconds,\n minutes,\n hours,\n days,\n zero,\n infinity,\n\n // Conversions\n toMillis,\n toSeconds,\n toMinutes,\n toHours,\n toDays,\n\n // Operations\n add,\n subtract,\n multiply,\n divide,\n\n // Comparisons\n lessThan,\n lessThanOrEqual,\n greaterThan,\n greaterThanOrEqual,\n equals,\n min,\n max,\n clamp,\n\n // Predicates\n isZero,\n isInfinite,\n isFinite,\n isDuration,\n\n // Formatting\n format,\n parse,\n} as const;\n\nexport type { Duration as DurationType };\n","/**\n * awaitly/schedule\n *\n * Composable scheduling primitives inspired by Effect's Schedule module.\n * Build complex retry and polling strategies by composing simple building blocks.\n *\n * @example\n * ```typescript\n * // \"Exponential backoff with jitter, max 5 attempts, then poll every minute\"\n * const schedule = Schedule.exponential(Duration.millis(100))\n * .pipe(Schedule.jittered(0.2))\n * .pipe(Schedule.upTo(5))\n * .pipe(Schedule.andThen(Schedule.spaced(Duration.minutes(1))))\n *\n * // Use with workflows\n * const result = await step('fetchData', () => fetchData(), { schedule })\n * ```\n */\n\nimport { Duration, millis, toMillis, multiply, add, type Duration as DurationType } from \"../duration\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * The state maintained by a schedule during execution.\n */\nexport interface ScheduleState {\n /** Number of iterations completed */\n readonly iterations: number;\n /** Total elapsed time since schedule started */\n readonly elapsed: DurationType;\n /** The last input received (if any) */\n readonly lastInput?: unknown;\n /** The last output produced (if any) */\n readonly lastOutput?: unknown;\n /** Combinator-specific metadata (used by andThen, union, intersect, etc.) */\n readonly meta?: unknown;\n}\n\n/**\n * Decision returned by a schedule step.\n * Combinators can optionally provide `nextState` to thread custom state through execution.\n */\nexport type ScheduleDecision<Out> =\n | { readonly _tag: \"Continue\"; readonly delay: DurationType; readonly output: Out; readonly nextState?: ScheduleState }\n | { readonly _tag: \"Done\" };\n\n/**\n * A Schedule defines a recurring pattern with delays and outputs.\n *\n * @typeParam In - The input type (from retry attempts, etc.)\n * @typeParam Out - The output type (often the delay or iteration count)\n */\nexport interface Schedule<In = unknown, Out = unknown> {\n readonly _tag: \"Schedule\";\n /** Compute the next step given input and current state */\n readonly step: (input: In, state: ScheduleState) => ScheduleDecision<Out>;\n /** Initial state for this schedule */\n readonly initial: ScheduleState;\n}\n\n// =============================================================================\n// Internal Helpers\n// =============================================================================\n\nconst initialState: ScheduleState = {\n iterations: 0,\n elapsed: Duration.zero,\n lastInput: undefined,\n lastOutput: undefined,\n};\n\nfunction continueWith<Out>(delay: DurationType, output: Out): ScheduleDecision<Out> {\n return { _tag: \"Continue\", delay, output };\n}\n\nfunction done<Out>(): ScheduleDecision<Out> {\n return { _tag: \"Done\" };\n}\n\nfunction updateState(state: ScheduleState, delay: DurationType, input: unknown, output: unknown): ScheduleState {\n return {\n iterations: state.iterations + 1,\n elapsed: add(state.elapsed, delay),\n lastInput: input,\n lastOutput: output,\n };\n}\n\n// =============================================================================\n// Base Schedules\n// =============================================================================\n\n/**\n * A schedule that repeats forever with no delay.\n */\nexport function forever<In = unknown>(): Schedule<In, number> {\n return {\n _tag: \"Schedule\",\n initial: initialState,\n step: (_input, state) => continueWith(Duration.zero, state.iterations),\n };\n}\n\n/**\n * A schedule that repeats exactly n times.\n *\n * @example\n * ```typescript\n * const thrice = Schedule.recurs(3)\n * ```\n */\nexport function recurs<In = unknown>(n: number): Schedule<In, number> {\n return {\n _tag: \"Schedule\",\n initial: initialState,\n step: (_input, state) =>\n state.iterations < n ? continueWith(Duration.zero, state.iterations) : done(),\n };\n}\n\n/**\n * A schedule that repeats once.\n */\nexport function once<In = unknown>(): Schedule<In, void> {\n return {\n _tag: \"Schedule\",\n initial: initialState,\n step: (_input, state) =>\n state.iterations === 0 ? continueWith(Duration.zero, undefined) : done(),\n };\n}\n\n/**\n * A schedule that always stops immediately.\n */\nexport function stop<In = unknown>(): Schedule<In, never> {\n return {\n _tag: \"Schedule\",\n initial: initialState,\n step: () => done(),\n };\n}\n\n// =============================================================================\n// Delay-Based Schedules\n// =============================================================================\n\n/**\n * A schedule that waits a fixed duration between each iteration.\n *\n * @example\n * ```typescript\n * const pollEvery5s = Schedule.spaced(Duration.seconds(5))\n * ```\n */\nexport function spaced<In = unknown>(delay: DurationType): Schedule<In, number> {\n return {\n _tag: \"Schedule\",\n initial: initialState,\n step: (_input, state) => continueWith(delay, state.iterations),\n };\n}\n\n/**\n * Alias for spaced - a fixed interval schedule.\n */\nexport const fixed = spaced;\n\n/**\n * A schedule with exponentially increasing delays.\n * delay(n) = base * factor^n\n *\n * @example\n * ```typescript\n * // 100ms, 200ms, 400ms, 800ms, ...\n * const exponential = Schedule.exponential(Duration.millis(100))\n *\n * // With custom factor: 100ms, 300ms, 900ms, ...\n * const triple = Schedule.exponential(Duration.millis(100), 3)\n * ```\n */\nexport function exponential<In = unknown>(\n base: DurationType,\n factor: number = 2\n): Schedule<In, DurationType> {\n return {\n _tag: \"Schedule\",\n initial: initialState,\n step: (_input, state) => {\n const delay = multiply(base, Math.pow(factor, state.iterations));\n return continueWith(delay, delay);\n },\n };\n}\n\n/**\n * A schedule with linearly increasing delays.\n * delay(n) = base * (n + 1)\n *\n * @example\n * ```typescript\n * // 100ms, 200ms, 300ms, 400ms, ...\n * const linear = Schedule.linear(Duration.millis(100))\n * ```\n */\nexport function linear<In = unknown>(base: DurationType): Schedule<In, DurationType> {\n return {\n _tag: \"Schedule\",\n initial: initialState,\n step: (_input, state) => {\n const delay = multiply(base, state.iterations + 1);\n return continueWith(delay, delay);\n },\n };\n}\n\n/**\n * A schedule with fibonacci-sequence delays.\n * delay(n) follows fibonacci: base, base, 2*base, 3*base, 5*base, ...\n *\n * @example\n * ```typescript\n * // 100ms, 100ms, 200ms, 300ms, 500ms, 800ms, ...\n * const fib = Schedule.fibonacci(Duration.millis(100))\n * ```\n */\nexport function fibonacci<In = unknown>(base: DurationType): Schedule<In, DurationType> {\n // Precompute fibonacci numbers for reasonable iteration counts\n const fibNumbers: number[] = [1, 1];\n for (let i = 2; i < 50; i++) {\n fibNumbers[i] = fibNumbers[i - 1] + fibNumbers[i - 2];\n }\n\n return {\n _tag: \"Schedule\",\n initial: initialState,\n step: (_input, state) => {\n const fibIndex = Math.min(state.iterations, fibNumbers.length - 1);\n const delay = multiply(base, fibNumbers[fibIndex]);\n return continueWith(delay, delay);\n },\n };\n}\n\n// =============================================================================\n// Combinators: Limits\n// =============================================================================\n\n/**\n * Limit a schedule to at most n iterations.\n *\n * @example\n * ```typescript\n * // Exponential backoff, max 5 attempts\n * const limited = Schedule.exponential(Duration.millis(100))\n * .pipe(Schedule.upTo(5))\n * ```\n */\nexport function upTo<In, Out>(\n n: number\n): (schedule: Schedule<In, Out>) => Schedule<In, Out> {\n return (schedule) => ({\n _tag: \"Schedule\",\n initial: schedule.initial,\n step: (input, state) => {\n if (state.iterations >= n) return done();\n return schedule.step(input, state);\n },\n });\n}\n\n/**\n * Limit a schedule by total elapsed time.\n *\n * @example\n * ```typescript\n * // Retry for at most 30 seconds\n * const timeLimited = Schedule.spaced(Duration.seconds(1))\n * .pipe(Schedule.upToElapsed(Duration.seconds(30)))\n * ```\n */\nexport function upToElapsed<In, Out>(\n maxElapsed: DurationType\n): (schedule: Schedule<In, Out>) => Schedule<In, Out> {\n return (schedule) => ({\n _tag: \"Schedule\",\n initial: schedule.initial,\n step: (input, state) => {\n if (toMillis(state.elapsed) >= toMillis(maxElapsed)) return done();\n return schedule.step(input, state);\n },\n });\n}\n\n/**\n * Cap the maximum delay of a schedule.\n *\n * @example\n * ```typescript\n * // Exponential, but never more than 30 seconds\n * const capped = Schedule.exponential(Duration.millis(100))\n * .pipe(Schedule.maxDelay(Duration.seconds(30)))\n * ```\n */\nexport function maxDelay<In, Out>(\n max: DurationType\n): (schedule: Schedule<In, Out>) => Schedule<In, Out> {\n return (schedule) => ({\n _tag: \"Schedule\",\n initial: schedule.initial,\n step: (input, state) => {\n const decision = schedule.step(input, state);\n if (decision._tag === \"Done\") return decision;\n const capped = toMillis(decision.delay) > toMillis(max) ? max : decision.delay;\n return continueWith(capped, decision.output);\n },\n });\n}\n\n/**\n * Set a minimum delay for a schedule.\n *\n * @example\n * ```typescript\n * const atLeast1s = schedule.pipe(Schedule.minDelay(Duration.seconds(1)))\n * ```\n */\nexport function minDelay<In, Out>(\n min: DurationType\n): (schedule: Schedule<In, Out>) => Schedule<In, Out> {\n return (schedule) => ({\n _tag: \"Schedule\",\n initial: schedule.initial,\n step: (input, state) => {\n const decision = schedule.step(input, state);\n if (decision._tag === \"Done\") return decision;\n const floored = toMillis(decision.delay) < toMillis(min) ? min : decision.delay;\n return continueWith(floored, decision.output);\n },\n });\n}\n\n// =============================================================================\n// Combinators: Conditions\n// =============================================================================\n\n/**\n * Continue while a predicate on the input returns true.\n *\n * @example\n * ```typescript\n * // Retry while the error is transient\n * const retryTransient = Schedule.exponential(Duration.millis(100))\n * .pipe(Schedule.whileInput((err: Error) => err.message.includes(\"ECONNRESET\")))\n * ```\n */\nexport function whileInput<In, Out>(\n predicate: (input: In) => boolean\n): (schedule: Schedule<In, Out>) => Schedule<In, Out> {\n return (schedule) => ({\n _tag: \"Schedule\",\n initial: schedule.initial,\n step: (input, state) => {\n if (!predicate(input)) return done();\n return schedule.step(input, state);\n },\n });\n}\n\n/**\n * Continue while a predicate on the output returns true.\n *\n * @example\n * ```typescript\n * // Poll until status is \"ready\"\n * const untilReady = Schedule.spaced(Duration.seconds(1))\n * .pipe(Schedule.whileOutput((status: string) => status !== \"ready\"))\n * ```\n */\nexport function whileOutput<In, Out>(\n predicate: (output: Out) => boolean\n): (schedule: Schedule<In, Out>) => Schedule<In, Out> {\n return (schedule) => ({\n _tag: \"Schedule\",\n initial: schedule.initial,\n step: (input, state) => {\n const decision = schedule.step(input, state);\n if (decision._tag === \"Done\") return decision;\n if (!predicate(decision.output)) return done();\n return decision;\n },\n });\n}\n\n/**\n * Continue until a predicate on the input returns true.\n * Opposite of whileInput.\n */\nexport function untilInput<In, Out>(\n predicate: (input: In) => boolean\n): (schedule: Schedule<In, Out>) => Schedule<In, Out> {\n return whileInput((input: In) => !predicate(input));\n}\n\n/**\n * Continue until a predicate on the output returns true.\n * Opposite of whileOutput.\n */\nexport function untilOutput<In, Out>(\n predicate: (output: Out) => boolean\n): (schedule: Schedule<In, Out>) => Schedule<In, Out> {\n return whileOutput((output: Out) => !predicate(output));\n}\n\n// =============================================================================\n// Combinators: Jitter\n// =============================================================================\n\n/**\n * Add random jitter to delays to prevent thundering herd.\n *\n * @param factor - Jitter factor (0.0 to 1.0). Delay will be multiplied by (1 - factor) to (1 + factor).\n *\n * @example\n * ```typescript\n * // ±20% jitter\n * const jittered = Schedule.exponential(Duration.millis(100))\n * .pipe(Schedule.jittered(0.2))\n * ```\n */\nexport function jittered<In, Out>(\n factor: number = 0.2\n): (schedule: Schedule<In, Out>) => Schedule<In, Out> {\n return (schedule) => ({\n _tag: \"Schedule\",\n initial: schedule.initial,\n step: (input, state) => {\n const decision = schedule.step(input, state);\n if (decision._tag === \"Done\") return decision;\n\n // Random factor between (1 - factor) and (1 + factor)\n const jitterMultiplier = 1 - factor + Math.random() * factor * 2;\n const jitteredDelay = millis(toMillis(decision.delay) * jitterMultiplier);\n\n return continueWith(jitteredDelay, decision.output);\n },\n });\n}\n\n/**\n * Add a fixed random delay to each iteration.\n *\n * @example\n * ```typescript\n * // Add 0-500ms random delay\n * const randomized = schedule.pipe(Schedule.addDelay(Duration.millis(500)))\n * ```\n */\nexport function addDelay<In, Out>(\n maxExtra: DurationType\n): (schedule: Schedule<In, Out>) => Schedule<In, Out> {\n return (schedule) => ({\n _tag: \"Schedule\",\n initial: schedule.initial,\n step: (input, state) => {\n const decision = schedule.step(input, state);\n if (decision._tag === \"Done\") return decision;\n\n const extra = millis(Math.random() * toMillis(maxExtra));\n const newDelay = add(decision.delay, extra);\n\n return continueWith(newDelay, decision.output);\n },\n });\n}\n\n// =============================================================================\n// Combinators: Composition\n// =============================================================================\n\n/** Internal metadata for andThen combinator */\ninterface AndThenMeta {\n readonly inSecondPhase: boolean;\n readonly firstState: ScheduleState; // Preserves first schedule's state (including its meta)\n readonly secondState: ScheduleState;\n}\n\n/**\n * Chain two schedules: run the first until done, then run the second.\n * The second schedule starts with fresh state when it begins.\n *\n * @example\n * ```typescript\n * // 5 exponential retries, then poll every minute\n * const strategy = Schedule.exponential(Duration.millis(100))\n * .pipe(Schedule.upTo(5))\n * .pipe(Schedule.andThen(Schedule.spaced(Duration.minutes(1))))\n * ```\n */\nexport function andThen<In, Out1, Out2>(\n second: Schedule<In, Out2>\n): (first: Schedule<In, Out1>) => Schedule<In, Out1 | Out2> {\n return (first) => {\n const initialMeta: AndThenMeta = {\n inSecondPhase: false,\n firstState: first.initial, // Preserve first's initial state (including its meta)\n secondState: second.initial,\n };\n\n return {\n _tag: \"Schedule\",\n initial: { ...initialState, meta: initialMeta },\n step: (input, state) => {\n const meta = (state.meta as AndThenMeta) ?? initialMeta;\n\n if (!meta.inSecondPhase) {\n // Pass first's isolated state (not outer state) to preserve its meta\n const decision = first.step(input, meta.firstState);\n if (decision._tag === \"Continue\") {\n // Update first's state - use nextState if provided, otherwise compute it\n const nextFirstState = decision.nextState ?? updateState(meta.firstState, decision.delay, input, decision.output);\n const nextState: ScheduleState = {\n ...updateState(state, decision.delay, input, decision.output),\n meta: { ...meta, firstState: nextFirstState },\n };\n return { _tag: \"Continue\", delay: decision.delay, output: decision.output as Out1 | Out2, nextState };\n }\n // First schedule done, switch to second with fresh state\n const secondDecision = second.step(input, second.initial);\n if (secondDecision._tag === \"Done\") return done();\n\n const nextSecondState = secondDecision.nextState ?? updateState(second.initial, secondDecision.delay, input, secondDecision.output);\n const nextState: ScheduleState = {\n ...updateState(state, secondDecision.delay, input, secondDecision.output),\n meta: { inSecondPhase: true, firstState: meta.firstState, secondState: nextSecondState },\n };\n return { _tag: \"Continue\", delay: secondDecision.delay, output: secondDecision.output as Out1 | Out2, nextState };\n }\n\n // In second phase - use secondState from meta\n const decision = second.step(input, meta.secondState);\n if (decision._tag === \"Done\") return done();\n\n // Update second's state\n const nextSecondState = decision.nextState ?? updateState(meta.secondState, decision.delay, input, decision.output);\n const nextState: ScheduleState = {\n ...updateState(state, decision.delay, input, decision.output),\n meta: { ...meta, secondState: nextSecondState },\n };\n\n return { _tag: \"Continue\", delay: decision.delay, output: decision.output as Out1 | Out2, nextState };\n },\n };\n };\n}\n\n/** Internal metadata for union/intersect combinators */\ninterface ParallelMeta {\n readonly firstState: ScheduleState;\n readonly secondState: ScheduleState;\n}\n\n/**\n * Run two schedules in parallel, using the shorter delay.\n * Both schedules advance their state independently.\n *\n * @example\n * ```typescript\n * // Use whichever delay is shorter\n * const union = Schedule.union(\n * Schedule.exponential(Duration.millis(100)),\n * Schedule.spaced(Duration.seconds(1))\n * )\n * ```\n */\nexport function union<In, Out1, Out2>(\n first: Schedule<In, Out1>,\n second: Schedule<In, Out2>\n): Schedule<In, [Out1, Out2]> {\n const initialMeta: ParallelMeta = {\n firstState: first.initial,\n secondState: second.initial,\n };\n\n return {\n _tag: \"Schedule\",\n initial: { ...initialState, meta: initialMeta },\n step: (input, state) => {\n const meta = (state.meta as ParallelMeta) ?? initialMeta;\n\n const firstDecision = first.step(input, meta.firstState);\n const secondDecision = second.step(input, meta.secondState);\n\n if (firstDecision._tag === \"Done\" && secondDecision._tag === \"Done\") {\n return done();\n }\n\n // Compute next child states - respect nextState if child provides custom state threading\n const nextFirstState = firstDecision._tag === \"Continue\"\n ? (firstDecision.nextState ?? updateState(meta.firstState, firstDecision.delay, input, firstDecision.output))\n : meta.firstState;\n const nextSecondState = secondDecision._tag === \"Continue\"\n ? (secondDecision.nextState ?? updateState(meta.secondState, secondDecision.delay, input, secondDecision.output))\n : meta.secondState;\n\n // Take the shorter delay\n const firstDelay = firstDecision._tag === \"Continue\" ? toMillis(firstDecision.delay) : Infinity;\n const secondDelay = secondDecision._tag === \"Continue\" ? toMillis(secondDecision.delay) : Infinity;\n\n const delay = millis(Math.min(firstDelay, secondDelay));\n const output: [Out1, Out2] = [\n firstDecision._tag === \"Continue\" ? firstDecision.output : (undefined as Out1),\n secondDecision._tag === \"Continue\" ? secondDecision.output : (undefined as Out2),\n ];\n\n const nextState: ScheduleState = {\n ...updateState(state, delay, input, output),\n meta: { firstState: nextFirstState, secondState: nextSecondState },\n };\n\n return { _tag: \"Continue\", delay, output, nextState };\n },\n };\n}\n\n/**\n * Run two schedules in parallel, using the longer delay.\n * Both schedules advance their state independently. Stops when either schedule stops.\n *\n * @example\n * ```typescript\n * // Use whichever delay is longer\n * const intersect = Schedule.intersect(\n * Schedule.exponential(Duration.millis(100)),\n * Schedule.spaced(Duration.seconds(1))\n * )\n * ```\n */\nexport function intersect<In, Out1, Out2>(\n first: Schedule<In, Out1>,\n second: Schedule<In, Out2>\n): Schedule<In, [Out1, Out2]> {\n const initialMeta: ParallelMeta = {\n firstState: first.initial,\n secondState: second.initial,\n };\n\n return {\n _tag: \"Schedule\",\n initial: { ...initialState, meta: initialMeta },\n step: (input, state) => {\n const meta = (state.meta as ParallelMeta) ?? initialMeta;\n\n const firstDecision = first.step(input, meta.firstState);\n const secondDecision = second.step(input, meta.secondState);\n\n // Both must continue\n if (firstDecision._tag === \"Done\" || secondDecision._tag === \"Done\") {\n return done();\n }\n\n // Compute next child states - respect nextState if child provides custom state threading\n const nextFirstState = firstDecision.nextState ?? updateState(meta.firstState, firstDecision.delay, input, firstDecision.output);\n const nextSecondState = secondDecision.nextState ?? updateState(meta.secondState, secondDecision.delay, input, secondDecision.output);\n\n // Take the longer delay\n const delay = millis(Math.max(toMillis(firstDecision.delay), toMillis(secondDecision.delay)));\n const output: [Out1, Out2] = [firstDecision.output, secondDecision.output];\n\n const nextState: ScheduleState = {\n ...updateState(state, delay, input, output),\n meta: { firstState: nextFirstState, secondState: nextSecondState },\n };\n\n return { _tag: \"Continue\", delay, output, nextState };\n },\n };\n}\n\n// =============================================================================\n// Combinators: Transformations\n// =============================================================================\n\n/**\n * Transform the output of a schedule.\n *\n * @example\n * ```typescript\n * const withIteration = Schedule.spaced(Duration.seconds(1))\n * .pipe(Schedule.map((n) => ({ attempt: n + 1 })))\n * ```\n */\nexport function map<In, Out, NewOut>(\n fn: (output: Out) => NewOut\n): (schedule: Schedule<In, Out>) => Schedule<In, NewOut> {\n return (schedule) => ({\n _tag: \"Schedule\",\n initial: schedule.initial,\n step: (input, state) => {\n const decision = schedule.step(input, state);\n if (decision._tag === \"Done\") return done();\n return continueWith(decision.delay, fn(decision.output));\n },\n });\n}\n\n/**\n * Perform a side effect on each iteration.\n *\n * @example\n * ```typescript\n * const logged = Schedule.exponential(Duration.millis(100))\n * .pipe(Schedule.tap((delay) => console.log(`Waiting ${delay}ms`)))\n * ```\n */\nexport function tap<In, Out>(\n fn: (output: Out, state: ScheduleState) => void\n): (schedule: Schedule<In, Out>) => Schedule<In, Out> {\n return (schedule) => ({\n _tag: \"Schedule\",\n initial: schedule.initial,\n step: (input, state) => {\n const decision = schedule.step(input, state);\n if (decision._tag === \"Continue\") {\n fn(decision.output, state);\n }\n return decision;\n },\n });\n}\n\n/**\n * Modify the delay of a schedule.\n *\n * @example\n * ```typescript\n * const doubled = schedule.pipe(Schedule.modifyDelay(d => Duration.multiply(d, 2)))\n * ```\n */\nexport function modifyDelay<In, Out>(\n fn: (delay: DurationType, output: Out) => DurationType\n): (schedule: Schedule<In, Out>) => Schedule<In, Out> {\n return (schedule) => ({\n _tag: \"Schedule\",\n initial: schedule.initial,\n step: (input, state) => {\n const decision = schedule.step(input, state);\n if (decision._tag === \"Done\") return decision;\n return continueWith(fn(decision.delay, decision.output), decision.output);\n },\n });\n}\n\n// =============================================================================\n// Running Schedules\n// =============================================================================\n\n/**\n * Create an iterator for running a schedule step-by-step.\n *\n * @example\n * ```typescript\n * const runner = Schedule.run(mySchedule)\n *\n * while (true) {\n * const next = runner.next(lastResult)\n * if (next.done) break\n * await sleep(next.value.delay)\n * }\n * ```\n */\nexport function run<In, Out>(\n schedule: Schedule<In, Out>\n): { next: (input: In) => { done: false; value: { delay: DurationType; output: Out } } | { done: true } } {\n let state = schedule.initial;\n\n return {\n next(input: In) {\n const decision = schedule.step(input, state);\n if (decision._tag === \"Done\") {\n return { done: true as const };\n }\n\n // Use combinator-provided nextState if available, otherwise compute standard update\n state = decision.nextState ?? updateState(state, decision.delay, input, decision.output);\n return {\n done: false as const,\n value: { delay: decision.delay, output: decision.output },\n };\n },\n };\n}\n\n/**\n * Get all delays from a schedule (for testing/visualization).\n * Runs the schedule with undefined input until it completes or reaches maxIterations.\n */\nexport function delays<Out>(\n schedule: Schedule<undefined, Out>,\n maxIterations: number = 100\n): DurationType[] {\n const result: DurationType[] = [];\n const runner = run(schedule);\n\n for (let i = 0; i < maxIterations; i++) {\n const next = runner.next(undefined);\n if (next.done) break;\n result.push(next.value.delay);\n }\n\n return result;\n}\n\n// =============================================================================\n// Pipe Support\n// =============================================================================\n\n/**\n * Type guard to check if a value is a Schedule.\n */\nfunction isSchedule(value: unknown): value is Schedule<unknown, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"_tag\" in value &&\n (value as { _tag: unknown })._tag === \"Schedule\"\n );\n}\n\n/**\n * A schedule with pipe support for method chaining.\n */\ntype PipedSchedule<In, Out> = Schedule<In, Out> & {\n pipe: <NewOut>(fn: (s: Schedule<In, Out>) => Schedule<In, NewOut>) => PipedSchedule<In, NewOut>;\n} & {\n pipe: <R>(fn: (s: Schedule<In, Out>) => R) => R;\n};\n\n/**\n * Create a schedule with pipe support for method chaining.\n */\nfunction withPipe<In, Out>(schedule: Schedule<In, Out>): PipedSchedule<In, Out> {\n return {\n ...schedule,\n pipe(fn: (s: Schedule<In, Out>) => unknown): unknown {\n const result = fn(schedule);\n if (isSchedule(result)) {\n return withPipe(result as Schedule<unknown, unknown>);\n }\n return result;\n },\n } as PipedSchedule<In, Out>;\n}\n\n// Wrapped versions with pipe support\nconst spacedWithPipe = <In = unknown>(delay: DurationType) => withPipe(spaced<In>(delay));\nconst exponentialWithPipe = <In = unknown>(base: DurationType, factor?: number) => withPipe(exponential<In>(base, factor));\nconst linearWithPipe = <In = unknown>(base: DurationType) => withPipe(linear<In>(base));\nconst fibonacciWithPipe = <In = unknown>(base: DurationType) => withPipe(fibonacci<In>(base));\nconst recursWithPipe = <In = unknown>(n: number) => withPipe(recurs<In>(n));\nconst foreverWithPipe = <In = unknown>() => withPipe(forever<In>());\nconst onceWithPipe = <In = unknown>() => withPipe(once<In>());\nconst unionWithPipe = <In, Out1, Out2>(first: Schedule<In, Out1>, second: Schedule<In, Out2>) => withPipe(union(first, second));\nconst intersectWithPipe = <In, Out1, Out2>(first: Schedule<In, Out1>, second: Schedule<In, Out2>) => withPipe(intersect(first, second));\n\n// =============================================================================\n// Namespace Export\n// =============================================================================\n\n/**\n * Schedule namespace for composable scheduling.\n *\n * @example\n * ```typescript\n * import { Schedule, Duration } from \"awaitly\";\n *\n * // Exponential backoff with jitter, max 5 attempts\n * const retry = Schedule.exponential(Duration.millis(100))\n * .pipe(Schedule.jittered(0.2))\n * .pipe(Schedule.upTo(5))\n * .pipe(Schedule.maxDelay(Duration.seconds(30)))\n *\n * // Then poll every minute forever\n * const poll = Schedule.spaced(Duration.minutes(1))\n *\n * // Chain them\n * const strategy = retry.pipe(Schedule.andThen(poll))\n * ```\n */\nexport const Schedule = {\n // Base schedules\n forever: foreverWithPipe,\n once: onceWithPipe,\n recurs: recursWithPipe,\n stop,\n\n // Delay-based\n spaced: spacedWithPipe,\n fixed: spacedWithPipe,\n exponential: exponentialWithPipe,\n linear: linearWithPipe,\n fibonacci: fibonacciWithPipe,\n\n // Limits\n upTo,\n upToElapsed,\n maxDelay,\n minDelay,\n\n // Conditions\n whileInput,\n whileOutput,\n untilInput,\n untilOutput,\n\n // Jitter\n jittered,\n addDelay,\n\n // Composition\n andThen,\n union: unionWithPipe,\n intersect: intersectWithPipe,\n\n // Transformations\n map,\n tap,\n modifyDelay,\n\n // Running\n run,\n delays,\n} as const;\n\nexport type { Schedule as ScheduleType };\n"],"mappings":"AAgCO,SAASA,EAAOC,EAAsB,CAC3C,MAAO,CAAE,KAAM,WAAY,OAAQA,CAAG,CACxC,CAUO,SAASC,EAAQC,EAAqB,CAC3C,MAAO,CAAE,KAAM,WAAY,OAAQA,EAAI,GAAK,CAC9C,CAUO,SAASC,EAAQC,EAAqB,CAC3C,MAAO,CAAE,KAAM,WAAY,OAAQA,EAAI,GAAK,GAAK,CACnD,CAUO,SAASC,EAAMC,EAAqB,CACzC,MAAO,CAAE,KAAM,WA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,GAAWC,CAAC,CAAC,EACpEuE,GAAkB,IAAoBN,EAASpE,GAAY,CAAC,EAC5D2E,GAAe,IAAoBP,EAAShE,GAAS,CAAC,EACtDwE,GAAgB,CAAiBhC,EAA2BD,IAA+ByB,EAASjB,GAAMP,EAAOD,CAAM,CAAC,EACxHkC,GAAoB,CAAiBjC,EAA2BD,IAA+ByB,EAASb,GAAUX,EAAOD,CAAM,CAAC,EA0BzHmC,GAAW,CAEtB,QAASJ,GACT,KAAMC,GACN,OAAQF,GACR,KAAApE,GAGA,OAAQgE,EACR,MAAOA,EACP,YAAaC,GACb,OAAQC,GACR,UAAWC,GAGX,KAAAvD,GACA,YAAAE,GACA,SAAAG,GACA,SAAAI,GAGA,WAAAG,EACA,YAAAE,EACA,WAAAC,GACA,YAAAC,GAGA,SAAAC,GACA,SAAAI,GAGA,QAAAI,GACA,MAAOkC,GACP,UAAWC,GAGX,IAAArB,GACA,IAAAE,GACA,YAAAC,GAGA,IAAAC,EACA,OAAAC,EACF","names":["millis","ms","seconds","s","minutes","m","hours","h","days","d","zero","infinity","toMillis","duration","toSeconds","toMinutes","toHours","toDays","add","a","b","subtract","multiply","factor","divide","divisor","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","equals","min","max","clamp","minimum","maximum","isZero","isInfinite","isFinite","isDuration","value","format","parts","parse","input","match","Duration","initialState","Duration","continueWith","delay","output","done","updateState","state","input","add","forever","_input","recurs","n","once","stop","spaced","fixed","exponential","base","factor","multiply","linear","fibonacci","fibNumbers","i","fibIndex","upTo","schedule","upToElapsed","maxElapsed","toMillis","maxDelay","max","decision","capped","minDelay","min","floored","whileInput","predicate","whileOutput","untilInput","untilOutput","jittered","jitterMultiplier","jitteredDelay","millis","addDelay","maxExtra","extra","newDelay","andThen","second","first","initialMeta","meta","nextFirstState","nextState","secondDecision","nextSecondState","union","firstDecision","firstDelay","secondDelay","intersect","map","fn","tap","modifyDelay","run","delays","maxIterations","result","runner","next","isSchedule","value","withPipe","spacedWithPipe","exponentialWithPipe","linearWithPipe","fibonacciWithPipe","recursWithPipe","foreverWithPipe","onceWithPipe","unionWithPipe","intersectWithPipe","Schedule"]}
package/dist/run.cjs DELETED
@@ -1,7 +0,0 @@
1
- "use strict";var de=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Ke=Object.prototype.hasOwnProperty;var je=(o,e)=>{for(var c in e)de(o,c,{get:e[c],enumerable:!0})},Fe=(o,e,c,g)=>{if(e&&typeof e=="object"||typeof e=="function")for(let _ of Ne(e))!Ke.call(o,_)&&_!==c&&de(o,_,{get:()=>e[_],enumerable:!(g=Ue(e,_))||g.enumerable});return o};var Le=o=>Fe(de({},"__esModule",{value:!0}),o);var Ge={};je(Ge,{EARLY_EXIT_SYMBOL:()=>ie,STEP_TIMEOUT_MARKER:()=>J,createEarlyExit:()=>fe,getStepTimeoutMeta:()=>we,isEarlyExit:()=>ge,isStepTimeoutError:()=>se,run:()=>ae});module.exports=Le(Ge);var Be={"step-require-id":"step-require-id","step-no-immediate-execution":"step-no-immediate-execution","step-require-thunk-for-key":"step-require-thunk-for-key","step-no-bare-await":"step-no-bare-await","step-no-try-catch-wrap":"step-no-try-catch-wrap","step-stable-cache-keys":"step-stable-cache-keys","workflow-no-floating":"workflow-no-floating","workflow-options-position":"workflow-options-position","workflow-callback-shape":"workflow-callback-shape","workflow-no-callable-form":"workflow-no-callable-form","workflow-no-dynamic-import":"workflow-no-dynamic-import","result-no-floating":"result-no-floating","result-require-handling":"result-require-handling","result-no-double-wrap":"result-no-double-wrap","result-no-manual-propagation":"result-no-manual-propagation","result-no-direct-ok-err":"result-no-direct-ok-err","error-check-unexpected-first":"error-check-unexpected-first","error-access-cause":"error-access-cause","error-normalize":"error-normalize","error-no-throw-in-deps":"error-no-throw-in-deps","concurrency-no-promise-all":"concurrency-no-promise-all","concurrency-no-promise-race":"concurrency-no-promise-race","concurrency-no-promise-allsettled":"concurrency-no-promise-allsettled","runtime-step-timeout":"runtime-step-timeout","runtime-step-aborted":"runtime-step-aborted","runtime-retry-exhausted":"runtime-retry-exhausted","runtime-rate-limit":"runtime-rate-limit","runtime-circuit-open":"runtime-circuit-open","runtime-unexpected":"runtime-unexpected","runtime-resolver-not-found":"runtime-resolver-not-found","runtime-saga-compensation":"runtime-saga-compensation"};function Te(o){return`https://jagreehal.github.io/awaitly/rules/#${o}`}var tt=Object.keys(Be);var ee=class extends Error{_tag};function K(o,e){return class extends ee{_tag=o;constructor(c,g){let _=e?.message?e.message(c??{}):o;if(super(_),this.name=o,e?.slug!==void 0){if(!e.hint)throw new TypeError(`TaggedError: 'hint' is required when 'slug' is set (slug: "${e.slug}")`);Object.defineProperty(this,"code",{value:e.slug,enumerable:!0,writable:!1,configurable:!1}),Object.defineProperty(this,"hint",{value:e.hint,enumerable:!0,writable:!1,configurable:!1}),Object.defineProperty(this,"docsUrl",{value:Te(e.slug),enumerable:!0,writable:!1,configurable:!1})}if(Object.setPrototypeOf(this,new.target.prototype),c&&typeof c=="object"){let h;if(e?.slug!==void 0){let{_tag:a,name:U,message:M,stack:N,code:$,hint:u,docsUrl:I,...V}=c;h=V}else{let{_tag:a,name:U,message:M,stack:N,...$}=c;h=$}let S=Object.prototype.hasOwnProperty.call(h,"cause"),y=S?h.cause:void 0;S&&delete h.cause;let v=g?.cause!==void 0;if(S&&v)throw new TypeError("TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause");Object.assign(this,h),S&&(this.cause=y),v&&(this.cause=g?.cause)}else g?.cause!==void 0&&(this.cause=g.cause)}}}Object.defineProperty(K,Symbol.hasInstance,{value:o=>o instanceof ee});(_=>{function o(h){return h instanceof Error}_.isError=o;function e(h){return h instanceof ee}_.isTaggedError=e;function c(h,S){let y=h._tag,v=S[y];return v(h)}_.match=c;function g(h,S,y){let v=h._tag,a=S[v];return a?a(h):y(h)}_.matchPartial=g})(K||={});var ke=class extends K("TimeoutError",{slug:"runtime-step-timeout",hint:"Increase the step's timeout option, or check why the upstream operation is slow.",message:e=>e.operation?`TimeoutError: ${e.operation} timed out after ${e.ms}ms`:`TimeoutError: Operation timed out after ${e.ms}ms`}){},Re=class extends K("RetryExhaustedError",{slug:"runtime-retry-exhausted",hint:"All retry attempts failed. Inspect lastError and decide whether to surface it or compensate.",message:e=>e.operation?`RetryExhaustedError: ${e.operation} failed after ${e.attempts} attempts`:`RetryExhaustedError: Operation failed after ${e.attempts} attempts`}){},xe=class extends K("RateLimitError",{slug:"runtime-rate-limit",hint:"Wait retryAfterMs before retrying, or apply step.cache to deduplicate calls.",message:e=>e.limiterName?`RateLimitError: Rate limit exceeded for ${e.limiterName}${e.retryAfterMs?`, retry after ${e.retryAfterMs}ms`:""}`:`RateLimitError: Rate limit exceeded${e.retryAfterMs?`, retry after ${e.retryAfterMs}ms`:""}`}){},he=class extends K("CircuitBreakerOpenError",{slug:"runtime-circuit-open",hint:"The circuit is open. Wait for it to half-open or fall back to a degraded path.",message:e=>`CircuitBreakerOpenError: Circuit ${e.circuitName} is ${e.state??"OPEN"}${e.retryAfterMs?`, retry after ${Math.ceil(e.retryAfterMs/1e3)}s`:""}`}){},Ce=class extends K("ValidationError",{message:e=>`ValidationError: Invalid ${e.field} - ${e.reason}`}){},be=class extends K("NotFoundError",{message:e=>e.id?`NotFoundError: ${e.resource} with id ${e.id} not found`:`NotFoundError: ${e.resource} not found`}){},Se=class extends K("UnauthorizedError",{message:e=>e.reason?`UnauthorizedError: ${e.reason}`:e.action&&e.resource?`UnauthorizedError: Not authorized to ${e.action} ${e.resource}`:"UnauthorizedError: Access denied"}){},Ae=class extends K("NetworkError",{message:e=>e.url?`NetworkError: ${e.reason} (${e.url})`:`NetworkError: ${e.reason}`}){},_e=class extends K("CompensationError",{slug:"runtime-saga-compensation",hint:"A saga compensation step failed. Inspect compensationError and ensure compensation is idempotent.",message:e=>`CompensationError: Failed to compensate step ${e.step}`}){},ne=class extends K("UnexpectedError",{slug:"runtime-unexpected",hint:"An unexpected exception escaped a step. Inspect cause; consider returning a typed Result instead of throwing.",message:e=>`UnexpectedError: ${e.cause instanceof Error?e.cause.message:String(e.cause??"unknown")}`}){};function $e(o){let e=o.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);if(!e)return;let c=parseFloat(e[1]),g=e[2].toLowerCase();return{_tag:"Duration",millis:c*({ms:1,s:1e3,m:6e4,h:36e5,d:864e5}[g]??1)}}function Ve(o){return new ne({cause:o})}function B(o){return{ok:!0,value:o}}function D(o,e){let c=e?.cause;return{ok:!1,error:o,...c!==void 0?{cause:c}:{}}}function We(o){if(o==null)return"unknown";if(typeof o=="string")return o.trim()||"unknown";if(typeof o=="object"){let e=o;if(typeof e._tag=="string"){let c=e._tag.trim();if(c)return c}if(typeof e.tag=="string"){let c=e.tag.trim();if(c)return c}if(typeof e.code=="string"){let c=e.code.trim();if(c)return c}else if(typeof e.code=="number")return String(e.code);if(o instanceof Error&&o.name){let c=o.name.trim();if(c)return c}}return"unknown"}function He(o,e){if(!(!e||!o))return e[o]}function qe(o){let{intent:e,domain:c,owner:g,tags:_,stateChanges:h,emits:S,calls:y}=o;if(!e&&!c&&!g&&!_?.length&&!h?.length&&!S?.length&&!y?.length)return;let v={};return e&&(v.intent=e),c&&(v.domain=c),g&&(v.owner=g),_?.length&&(v.tags=_),h?.length&&(v.stateChanges=h),S?.length&&(v.emits=S),y?.length&&(v.calls=y),v}function j(o,e,c,g,_){let h=We(o),S=He(h,e),y={tag:h,origin:c};return S!==void 0&&(y.classification=S),g!==void 0&&(y.attempt=g),_!==void 0&&(y.cumulativeDurationMs=_),y}var J=Symbol.for("step_timeout_marker");function se(o){return typeof o!="object"||o===null?!1:o.type==="STEP_TIMEOUT"?!0:J in o}function we(o){if(!(typeof o!="object"||o===null)){if(o.type==="STEP_TIMEOUT"){let e=o;return{timeoutMs:e.timeoutMs,stepName:e.stepName,stepKey:e.stepKey,attempt:e.attempt}}if(J in o)return o[J]}}var ie=Symbol("early-exit");function fe(o,e){return{[ie]:!0,error:o,meta:e}}function ge(o){return typeof o=="object"&&o!==null&&o[ie]===!0}var ve=Symbol("mapper-exception");function X(o){return{[ve]:!0,thrown:o}}function Ye(o){return typeof o=="object"&&o!==null&&o[ve]===!0}function Ee(o,e){let{backoff:c,initialDelay:g,maxDelay:_,jitter:h}=e,S;switch(c){case"fixed":S=g;break;case"linear":S=g*o;break;case"exponential":S=g*Math.pow(2,o-1);break}if(S=Math.min(S,_),h){let y=S*.25*Math.random();S=S+y}return Math.floor(S)}function ye(o){return new Promise(e=>setTimeout(e,o))}var Pe=Symbol("timeout"),oe=Symbol("timeout-option");function ze(o){return typeof o=="object"&&o!==null&&o[oe]===!0}async function Je(o,e,c,g){let _=new AbortController,h=e.onTimeout??"error",S=()=>typeof h=="function"?h({name:c.name,key:c.key,ms:e.ms}):e.error??{type:"STEP_TIMEOUT",stepName:c.name,stepKey:c.key,timeoutMs:e.ms,attempt:c.attempt},y;g?.aborted&&_.abort(g.reason);let v;g&&!g.aborted&&(v=()=>_.abort(g.reason),g.addEventListener("abort",v,{once:!0}));let a=new Promise((M,N)=>{y=setTimeout(()=>{if(h!=="disconnect"&&_.abort(),h==="option"){N({[oe]:!0,ms:e.ms});return}N({[Pe]:!0,error:S()})},e.ms)}),U;e.signal?U=Promise.resolve(o(_.signal)):U=Promise.resolve(o());try{return await Promise.race([U,a])}catch(M){if(typeof M=="object"&&M!==null&&M[oe]===!0)throw{[oe]:!0,ms:e.ms};if(typeof M=="object"&&M!==null&&M[Pe]===!0){h==="disconnect"&&U.catch(()=>{});let N=M.error;if(typeof N=="object"&&N!==null&&N.type!=="STEP_TIMEOUT"){let $={timeoutMs:e.ms,stepName:c.name,stepKey:c.key,attempt:c.attempt};J in N?N[J]=$:Object.defineProperty(N,J,{value:$,enumerable:!1,writable:!0,configurable:!1})}throw N}throw M}finally{clearTimeout(y),v&&g&&g.removeEventListener("abort",v)}}var Q={backoff:"exponential",initialDelay:100,maxDelay:3e4,jitter:!0,shouldRetry:()=>!0,onRetry:()=>{}};async function ae(o,e){let{onError:c,onEvent:g,catchUnexpected:_,workflowId:h,workflowName:S,context:y,_workflowSignal:v}=e&&typeof e=="object"?e:{},a=h??crypto.randomUUID(),U=_??Ve,M=[],N=0,$=p=>p??`step_${++N}`,u=p=>{let F=p.context!==void 0||y===void 0?p:{...p,context:y},q=S!==void 0&&F.workflowName===void 0?{...F,workflowName:S}:F;if(q.type==="step_success"){let te=q.stepId;for(let re=M.length-1;re>=0;re--){let L=M[re];if(L.type==="race"&&!L.winnerId){L.winnerId=te;break}}}g?.(q,y)},I=fe,V=p=>ge(p),H=(p,F)=>p,Me=p=>typeof p=="function"?!1:!!(p&&typeof p=="object"&&"ok"in p||p&&typeof p=="object"&&"then"in p&&typeof p.then=="function");try{let F=function(s){let m={};for(let[r,n]of Object.entries(s))if(typeof n=="function")m[r]=n;else if(n&&typeof n=="object"&&"fn"in n)m[r]=n.fn;else throw new TypeError(`step.all: operation "${r}" must be a function or { fn, errors? } object`);return m},q=function(s,m){let r=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let n=performance.now(),t=!1;M.push({scopeId:r,type:"parallel"});let i=()=>{if(t)return;t=!0;let l=M.findIndex(d=>d.scopeId===r);l!==-1&&M.splice(l,1),u({type:"scope_end",workflowId:a,scopeId:r,ts:Date.now(),durationMs:performance.now()-n})};u({type:"scope_start",workflowId:a,scopeId:r,scopeType:"parallel",name:s,ts:Date.now()});try{let l=await m();if(i(),!l.ok)throw c?.(l.error,s,y),I(l.error,{origin:"result",resultCause:l.cause});return l.value}catch(l){throw i(),l}})()},te=function(s,m){let r=Object.keys(s),n=m.name??`Parallel(${r.join(", ")})`,t=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let i=performance.now(),l=!1;M.push({scopeId:t,type:"parallel"});let d=()=>{if(l)return;l=!0;let E=M.findIndex(w=>w.scopeId===t);E!==-1&&M.splice(E,1),u({type:"scope_end",workflowId:a,scopeId:t,ts:Date.now(),durationMs:performance.now()-i})};u({type:"scope_start",workflowId:a,scopeId:t,scopeType:"parallel",name:n,ts:Date.now()});try{let E=await new Promise(T=>{if(r.length===0){T([]);return}let b=!1,O=r.length,k=new Array(r.length);for(let P=0;P<r.length;P++){let R=r[P],C=P;Promise.resolve(s[R]()).catch(x=>D({type:"PROMISE_REJECTED",cause:x},{cause:{type:"PROMISE_REJECTION",reason:x}})).then(x=>{if(!b){if(!x.ok){b=!0,T([{key:R,result:x}]);return}k[C]={key:R,result:x},O--,O===0&&T(k)}})}});d();let w={};for(let{key:T,result:b}of E){if(!b.ok)throw c?.(b.error,T,y),I(b.error,{origin:"result",resultCause:b.cause});w[T]=b.value}return w}catch(E){throw d(),E}})()};var Xe=F,Qe=q,Ze=te;let p=(s,m,r)=>(async()=>{if(typeof s!="string"||s.length===0)throw new Error('[awaitly] step() requires an explicit string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))');let n=r??{},t=qe(n),i=s,l=n.key??s,d=n.key??s,{description:E,retry:w,timeout:T}=n,b=$(l),O=g,k=O?performance.now():0,R=Me(m)?()=>m:m,x={attempts:Math.max(1,w?.attempts??1),backoff:w?.backoff??Q.backoff,initialDelay:w?.initialDelay??Q.initialDelay,maxDelay:w?.maxDelay??Q.maxDelay,jitter:w?.jitter??Q.jitter,shouldRetry:w?.shouldRetry??Q.shouldRetry,onRetry:w?.onRetry??Q.onRetry};g&&u({type:"step_start",workflowId:a,stepId:b,stepKey:l,name:i,description:E,ts:Date.now(),...t&&{metadata:t}});let G;for(let A=1;A<=x.attempts;A++){let Ie=O?performance.now():0;try{let f;if(T?f=await Je(R,T,{name:i,key:l,attempt:A},v):f=await R(),f.ok){let z=performance.now()-k;return u({type:"step_success",workflowId:a,stepId:b,stepKey:l,name:i,description:E,ts:Date.now(),durationMs:z,...t&&{metadata:t}}),d&&u({type:"step_complete",workflowId:a,stepKey:d,name:i,description:E,ts:Date.now(),durationMs:z,result:f,...t&&{metadata:t}}),f.value}if(G=f,A<x.attempts&&x.shouldRetry(f.error,A)){let z=Ee(A,x);u({type:"step_retry",workflowId:a,stepId:b,stepKey:l,name:i,ts:Date.now(),attempt:A+1,maxAttempts:x.attempts,delayMs:z,error:f.error,...t&&{metadata:t},diagnostics:j(f.error,n.errorMeta,"result",A,performance.now()-k)}),x.onRetry(f.error,A,z),await ye(z);continue}x.attempts>1&&u({type:"step_retries_exhausted",workflowId:a,stepId:b,stepKey:l,name:i,ts:Date.now(),durationMs:performance.now()-k,attempts:A,lastError:f.error,...t&&{metadata:t},diagnostics:j(f.error,n.errorMeta,"result",A,performance.now()-k)});break}catch(f){let z=performance.now()-Ie;if(ze(f)){let W=f.ms;u({type:"step_timeout",workflowId:a,stepId:b,stepKey:l,name:i,ts:Date.now(),timeoutMs:W,attempt:A,...t&&{metadata:t},diagnostics:j(f,n.errorMeta,"timeout",A)}),u({type:"step_success",workflowId:a,stepId:b,stepKey:l,name:i,description:E,ts:Date.now(),durationMs:performance.now()-k,...t&&{metadata:t}}),d&&u({type:"step_complete",workflowId:a,stepKey:d,name:i,description:E,ts:Date.now(),durationMs:performance.now()-k,result:B(void 0),...t&&{metadata:t}});return}if(V(f))throw u({type:"step_aborted",workflowId:a,stepId:b,stepKey:l,name:i,description:E,ts:Date.now(),durationMs:z,...t&&{metadata:t}}),f;if(se(f)){let W=we(f),De=T?.ms??W?.timeoutMs??0;if(u({type:"step_timeout",workflowId:a,stepId:b,stepKey:l,name:i,ts:Date.now(),timeoutMs:De,attempt:A,...t&&{metadata:t},diagnostics:j(f,n.errorMeta,"timeout",A)}),A<x.attempts&&x.shouldRetry(f,A)){let me=Ee(A,x);u({type:"step_retry",workflowId:a,stepId:b,stepKey:l,name:i,ts:Date.now(),attempt:A+1,maxAttempts:x.attempts,delayMs:me,error:f,...t&&{metadata:t},diagnostics:j(f,n.errorMeta,"timeout",A,performance.now()-k)}),x.onRetry(f,A,me),await ye(me);continue}x.attempts>1&&u({type:"step_retries_exhausted",workflowId:a,stepId:b,stepKey:l,name:i,ts:Date.now(),durationMs:performance.now()-k,attempts:A,lastError:f,...t&&{metadata:t},diagnostics:j(f,n.errorMeta,"timeout",A,performance.now()-k)});let pe=performance.now()-k;throw u({type:"step_error",workflowId:a,stepId:b,stepKey:l,name:i,description:E,ts:Date.now(),durationMs:pe,error:f,...t&&{metadata:t},diagnostics:j(f,n.errorMeta,"timeout",A,pe)}),d&&u({type:"step_complete",workflowId:a,stepKey:d,name:i,description:E,ts:Date.now(),durationMs:pe,result:D(f,{cause:f}),meta:{origin:"throw",thrown:f},...t&&{metadata:t}}),c?.(f,i,y),I(f,{origin:"throw",thrown:f})}if(A<x.attempts&&x.shouldRetry(f,A)){let W=Ee(A,x);u({type:"step_retry",workflowId:a,stepId:b,stepKey:l,name:i,ts:Date.now(),attempt:A+1,maxAttempts:x.attempts,delayMs:W,error:f,...t&&{metadata:t},diagnostics:j(f,n.errorMeta,"throw",A,performance.now()-k)}),x.onRetry(f,A,W),await ye(W);continue}x.attempts>1&&!se(f)&&u({type:"step_retries_exhausted",workflowId:a,stepId:b,stepKey:l,name:i,ts:Date.now(),durationMs:performance.now()-k,attempts:A,lastError:f,...t&&{metadata:t},diagnostics:j(f,n.errorMeta,"throw",A,performance.now()-k)});let le=performance.now()-k,Z;try{Z=U(f)}catch(W){throw X(W)}throw u({type:"step_error",workflowId:a,stepId:b,stepKey:l,name:i,description:E,ts:Date.now(),durationMs:le,error:Z,...t&&{metadata:t},diagnostics:j(f,n.errorMeta,"throw",A,le)}),d&&u({type:"step_complete",workflowId:a,stepKey:d,name:i,description:E,ts:Date.now(),durationMs:le,result:D(Z,{cause:f}),meta:{origin:"throw",thrown:f},...t&&{metadata:t}}),c?.(Z,i,y),I(Z,{origin:"throw",thrown:f})}}let Y=G,ue=performance.now()-k,ce=H(Y.error,{origin:"result",resultCause:Y.cause});throw u({type:"step_error",workflowId:a,stepId:b,stepKey:l,name:i,description:E,ts:Date.now(),durationMs:ue,error:ce,...t&&{metadata:t},diagnostics:j(Y.error,n.errorMeta,"result",x.attempts,ue)}),d&&u({type:"step_complete",workflowId:a,stepKey:d,name:i,description:E,ts:Date.now(),durationMs:ue,result:Y,meta:{origin:"result",resultCause:Y.cause},...t&&{metadata:t}}),c?.(ce,i,y),I(ce,{origin:"result",resultCause:Y.cause})})();p.try=(s,m,r)=>{if(typeof s!="string"||s.length===0)throw new Error('[awaitly] step.try() requires an explicit string ID as the first argument. Example: step.try("parse", () => JSON.parse(str), { error: "PARSE_ERROR" })');let n="error"in r?()=>r.error:r.onError;if(r.retry||r.timeout)return p.retry(s,async()=>{try{return B(await m())}catch(E){return D(n(E),{cause:E})}},{attempts:r.retry?.attempts??1,...r.retry??{},key:r.key,timeout:r.timeout});let t=r.key??s,i=s,l=s,d=g;return(async()=>{let E=d?performance.now():0;g&&u({type:"step_start",workflowId:a,stepId:l,stepKey:t,name:i,ts:Date.now()});try{let w=await m(),T=performance.now()-E;return u({type:"step_success",workflowId:a,stepId:l,stepKey:t,name:i,ts:Date.now(),durationMs:T}),t&&u({type:"step_complete",workflowId:a,stepKey:t,name:i,ts:Date.now(),durationMs:T,result:B(w)}),w}catch(w){let T=n(w),b=performance.now()-E,O=H(T,{origin:"throw",thrown:w});throw u({type:"step_error",workflowId:a,stepId:l,stepKey:t,name:i,ts:Date.now(),durationMs:b,error:O}),t&&u({type:"step_complete",workflowId:a,stepKey:t,name:i,ts:Date.now(),durationMs:b,result:D(T,{cause:w}),meta:{origin:"throw",thrown:w}}),c?.(O,i,y),I(O,{origin:"throw",thrown:w})}})()},p.fromResult=(s,m,r)=>{if(typeof s!="string"||s.length===0)throw new Error('[awaitly] step.fromResult() requires an explicit string ID as the first argument. Example: step.fromResult("callProvider", () => callProvider(input), { onError: (e) => ({ type: "FAILED" }) })');let n=r.key??s,t=s,i=s,l="error"in r?()=>r.error:r.onError,d=g;return(async()=>{let E=d?performance.now():0;g&&u({type:"step_start",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now()});let w=await m();if(w.ok){let T=performance.now()-E;return u({type:"step_success",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now(),durationMs:T}),n&&u({type:"step_complete",workflowId:a,stepKey:n,name:t,ts:Date.now(),durationMs:T,result:B(w.value)}),w.value}else{let T=l(w.error),b=performance.now()-E,O=H(T,{origin:"result",resultCause:w.error});throw u({type:"step_error",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now(),durationMs:b,error:O}),n&&u({type:"step_complete",workflowId:a,stepKey:n,name:t,ts:Date.now(),durationMs:b,result:D(T,{cause:w.error}),meta:{origin:"result",resultCause:w.error}}),c?.(O,t,y),I(O,{origin:"result",resultCause:w.error})}})()},p.fromNullable=(s,m,r,n)=>{if(typeof s!="string"||s.length===0)throw new Error('[awaitly] step.fromNullable() requires an explicit string ID as the first argument. Example: step.fromNullable("getUser", () => db.find(id), () => ({ type: "NOT_FOUND" }))');return p(s,async()=>{let t=await m();return t!=null?B(t):D(r())},n)},p.retry=(s,m,r)=>{if(typeof s!="string"||s.length===0)throw new Error('[awaitly] step.retry() requires an explicit string ID as the first argument. Example: step.retry("fetchData", () => fetchData(), { attempts: 3 })');return p(s,m,{key:r.key??s,retry:{attempts:r.attempts,backoff:r.backoff,initialDelay:r.initialDelay,maxDelay:r.maxDelay,jitter:r.jitter,shouldRetry:r.shouldRetry,onRetry:r.onRetry},timeout:r.timeout})},p.withTimeout=(s,m,r)=>{if(typeof s!="string"||s.length===0)throw new Error('[awaitly] step.withTimeout() requires an explicit string ID as the first argument. Example: step.withTimeout("slowOp", () => slowOp(), { ms: 5000 })');return p(s,m,{key:r.key??s,timeout:r})},p.sleep=(s,m,r)=>{if(typeof s!="string"||s.length===0)throw new Error('[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")');let n=typeof m=="string"?$e(m):m;if(!n)throw new Error(`step.sleep: invalid duration '${m}'`);let t=n.millis,i=r?.signal;return p(s,async()=>{if(v?.aborted||i?.aborted){let l=new Error("Sleep aborted");throw l.name="AbortError",l}return new Promise((l,d)=>{let E={timeoutId:void 0},w=()=>{E.timeoutId&&clearTimeout(E.timeoutId);let T=new Error("Sleep aborted");T.name="AbortError",d(T)};v?.addEventListener("abort",w,{once:!0}),i?.addEventListener("abort",w,{once:!0}),E.timeoutId=setTimeout(()=>{v?.removeEventListener("abort",w),i?.removeEventListener("abort",w),l(B(void 0))},t)})},{key:r?.key??s,description:r?.description})},p.all=((...s)=>{if(typeof s[0]!="string")throw new TypeError("step.all(name, ...): first argument must be a string (step name). Example: step.all('Fetch data', { user: () => fetchUser(), posts: () => fetchPosts() })");let m=s[0],r=s[1];if(typeof r=="function")return q(m,r);if(r&&typeof r=="object"&&!Array.isArray(r)){let t=F(r);return te(t,{name:m})}throw new TypeError("step.all(name, ...): second argument must be a function (array form) or an object of operations (object form).")}),p.race=(s,m)=>{let r=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let n=performance.now(),t=!1,i={scopeId:r,type:"race",winnerId:void 0};M.push(i);let l=()=>{if(t)return;t=!0;let d=M.findIndex(E=>E.scopeId===r);d!==-1&&M.splice(d,1),u({type:"scope_end",workflowId:a,scopeId:r,ts:Date.now(),durationMs:performance.now()-n,winnerId:i.winnerId})};u({type:"scope_start",workflowId:a,scopeId:r,scopeType:"race",name:s,ts:Date.now()});try{let d=await m();if(l(),!d.ok)throw c?.(d.error,s,y),I(d.error,{origin:"result",resultCause:d.cause});return d.value}catch(d){throw l(),d}})()},p.if=(s,m,r)=>r(),p.label=p.if,p.branch=async(s,m)=>{let{condition:r,then:n,else:t}=m;if(r())return await n();if(t)return await t()},p.arm=(s,m)=>({fn:s,errors:m}),p.forEach=async(s,m,r)=>{let n=[],t=r.maxIterations,i=0,l="run"in r,d=Symbol.asyncIterator in m?m:(async function*(){yield*m})();for await(let E of d){if(t!==void 0&&i>=t)break;let w;l?w=await r.run(E,i):w=await r.item.handler(E,i,p),n.push(w),i++}return n},p.item=s=>({__forEachItemHandler:!0,handler:s}),p.dep=(s,m)=>m,p.workflow=(s,m,r)=>p(s,m,r),p.map=async(s,m,r,n)=>{let t=n?.concurrency??m.length;return p(s,()=>t>=m.length?Oe(m.map((i,l)=>r(i,l))):(async()=>{let i=[];for(let l=0;l<m.length;l+=t){let d=m.slice(l,l+t),E=await Oe(d.map((w,T)=>r(w,l+T)));if(!E.ok)return E;i.push(...E.value)}return B(i)})(),{key:n?.key})},p.withFallback=(s,m,r)=>{if(typeof s!="string"||s.length===0)throw new Error('[awaitly] step.withFallback() requires an explicit string ID as the first argument. Example: step.withFallback("getUser", () => fetchUser(id), { fallback: () => fetchFromCache(id) })');let n=r.key??s,t=s,i=$(n),l=g;return(async()=>{let d=l?performance.now():0;g&&u({type:"step_start",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now()});let E;try{E=await m()}catch(k){if(V(k))throw u({type:"step_aborted",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now(),durationMs:performance.now()-d}),k;let P;try{P=U(k)}catch(C){throw X(C)}if(r.on!==void 0&&r.on!==P){let C=performance.now()-d;throw u({type:"step_error",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now(),durationMs:C,error:P}),n&&u({type:"step_complete",workflowId:a,stepKey:n,name:t,ts:Date.now(),durationMs:C,result:D(P,{cause:k}),meta:{origin:"throw",thrown:k}}),c?.(P,t,y),I(P,{origin:"throw",thrown:k})}let R;try{R=await r.fallback()}catch(C){if(V(C))throw u({type:"step_aborted",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now(),durationMs:performance.now()-d}),C;let x;try{x=U(C)}catch(Y){throw X(Y)}let G=performance.now()-d;throw u({type:"step_error",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now(),durationMs:G,error:x}),n&&u({type:"step_complete",workflowId:a,stepKey:n,name:t,ts:Date.now(),durationMs:G,result:D(x,{cause:C}),meta:{origin:"throw",thrown:C}}),c?.(x,t,y),I(x,{origin:"throw",thrown:C})}if(R.ok){let C=performance.now()-d;return u({type:"step_success",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now(),durationMs:C}),n&&u({type:"step_complete",workflowId:a,stepKey:n,name:t,ts:Date.now(),durationMs:C,result:R,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(P)}}),R.value}else{let C=performance.now()-d,x=H(R.error,{origin:"result",resultCause:R.cause});throw u({type:"step_error",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now(),durationMs:C,error:x}),n&&u({type:"step_complete",workflowId:a,stepKey:n,name:t,ts:Date.now(),durationMs:C,result:R,meta:{origin:"result",resultCause:R.cause}}),c?.(x,t,y),I(x,{origin:"result",resultCause:R.cause})}}if(E.ok){let k=performance.now()-d;return u({type:"step_success",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now(),durationMs:k}),n&&u({type:"step_complete",workflowId:a,stepKey:n,name:t,ts:Date.now(),durationMs:k,result:E}),E.value}let w=E.error;if(r.on!==void 0&&r.on!==w){let k=performance.now()-d,P=H(w,{origin:"result",resultCause:E.cause});throw u({type:"step_error",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now(),durationMs:k,error:P}),n&&u({type:"step_complete",workflowId:a,stepKey:n,name:t,ts:Date.now(),durationMs:k,result:E,meta:{origin:"result",resultCause:E.cause}}),c?.(P,t,y),I(P,{origin:"result",resultCause:E.cause})}let T;try{T=await r.fallback()}catch(k){if(V(k))throw u({type:"step_aborted",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now(),durationMs:performance.now()-d}),k;let P;try{P=U(k)}catch(C){throw X(C)}let R=performance.now()-d;throw u({type:"step_error",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now(),durationMs:R,error:P}),n&&u({type:"step_complete",workflowId:a,stepKey:n,name:t,ts:Date.now(),durationMs:R,result:D(P,{cause:k}),meta:{origin:"throw",thrown:k}}),c?.(P,t,y),I(P,{origin:"throw",thrown:k})}if(T.ok){let k=performance.now()-d;return u({type:"step_success",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now(),durationMs:k}),n&&u({type:"step_complete",workflowId:a,stepKey:n,name:t,ts:Date.now(),durationMs:k,result:T,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(w)}}),T.value}let b=performance.now()-d,O=H(T.error,{origin:"result",resultCause:T.cause});throw u({type:"step_error",workflowId:a,stepId:i,stepKey:n,name:t,ts:Date.now(),durationMs:b,error:O}),n&&u({type:"step_complete",workflowId:a,stepKey:n,name:t,ts:Date.now(),durationMs:b,result:T,meta:{origin:"result",resultCause:T.cause}}),c?.(O,t,y),I(O,{origin:"result",resultCause:T.cause})})()},p.withResource=(s,m)=>{if(typeof s!="string"||s.length===0)throw new Error('[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() })');let r=s,n=s,t=$(r),i=g;return(async()=>{let l=i?performance.now():0;g&&u({type:"step_start",workflowId:a,stepId:t,stepKey:r,name:n,ts:Date.now()});let d;try{d=await m.acquire()}catch(R){if(V(R))throw u({type:"step_aborted",workflowId:a,stepId:t,stepKey:r,name:n,ts:Date.now(),durationMs:performance.now()-l}),R;let C;try{C=U(R)}catch(G){throw X(G)}let x=performance.now()-l;throw u({type:"step_error",workflowId:a,stepId:t,stepKey:r,name:n,ts:Date.now(),durationMs:x,error:C}),r&&u({type:"step_complete",workflowId:a,stepKey:r,name:n,ts:Date.now(),durationMs:x,result:D(C,{cause:R}),meta:{origin:"throw",thrown:R}}),c?.(C,n,y),I(C,{origin:"throw",thrown:R})}if(!d.ok){let R=performance.now()-l,C=H(d.error,{origin:"result",resultCause:d.cause});throw u({type:"step_error",workflowId:a,stepId:t,stepKey:r,name:n,ts:Date.now(),durationMs:R,error:C}),r&&u({type:"step_complete",workflowId:a,stepKey:r,name:n,ts:Date.now(),durationMs:R,result:d,meta:{origin:"result",resultCause:d.cause}}),c?.(C,n,y),I(C,{origin:"result",resultCause:d.cause})}let E=d.value,w,T,b=!1;try{w=await m.use(E)}catch(R){if(V(R)){try{await m.release(E)}catch(C){console.warn(`[awaitly] step.withResource("${s}"): release threw after earlyExit:`,C)}throw R}T=R,b=!0}try{await m.release(E)}catch(R){console.warn(`[awaitly] step.withResource("${s}"): release threw:`,R)}if(b){let R;try{R=U(T)}catch(x){throw X(x)}let C=performance.now()-l;throw u({type:"step_error",workflowId:a,stepId:t,stepKey:r,name:n,ts:Date.now(),durationMs:C,error:R}),r&&u({type:"step_complete",workflowId:a,stepKey:r,name:n,ts:Date.now(),durationMs:C,result:D(R,{cause:T}),meta:{origin:"throw",thrown:T}}),c?.(R,n,y),I(R,{origin:"throw",thrown:T})}let O=w;if(O.ok){let R=performance.now()-l;return u({type:"step_success",workflowId:a,stepId:t,stepKey:r,name:n,ts:Date.now(),durationMs:R}),r&&u({type:"step_complete",workflowId:a,stepKey:r,name:n,ts:Date.now(),durationMs:R,result:O}),O.value}let k=performance.now()-l,P=H(O.error,{origin:"result",resultCause:O.cause});throw u({type:"step_error",workflowId:a,stepId:t,stepKey:r,name:n,ts:Date.now(),durationMs:k,error:P}),r&&u({type:"step_complete",workflowId:a,stepKey:r,name:n,ts:Date.now(),durationMs:k,result:O,meta:{origin:"result",resultCause:O.cause}}),c?.(P,n,y),I(P,{origin:"result",resultCause:O.cause})})()};let L=await o({step:p});if(process.env.NODE_ENV!=="production"&&L!==null&&typeof L=="object"&&"ok"in L&&typeof L.ok=="boolean"){let s=L;(s.ok===!0&&"value"in s||s.ok===!1&&"error"in s)&&console.warn(`awaitly: Workflow executor returned a Result-like object. Return raw values, not ok() or err().
2
-
3
- Incorrect: return ok({ data });
4
- Correct: return { data };
5
-
6
- See: https://jagreehal.github.io/awaitly/guides/troubleshooting/#returning-ok-from-workflow-executor-double-wrapping`)}return B(L)}catch(p){if(Ye(p))throw p.thrown;if(V(p)){let q=p.meta.origin==="throw"?p.meta.thrown:p.meta.origin==="result"?p.meta.resultCause:void 0;return D(p.error,{cause:q})}let F=U(p);return c?.(F,"unexpected",y),D(F,{cause:p})}}ae.strict=(o,e)=>ae(o,e);async function Oe(o){return o.length===0?B([]):new Promise(e=>{let c=!1,g=o.length,_=new Array(o.length);for(let h=0;h<o.length;h++){let S=h;Promise.resolve(o[S]).catch(y=>D({type:"PROMISE_REJECTED",cause:y},{cause:{type:"PROMISE_REJECTION",reason:y}})).then(y=>{if(!c){if(!y.ok){c=!0,e(y);return}_[S]=y.value,g--,g===0&&e(B(_))}})}})}0&&(module.exports={EARLY_EXIT_SYMBOL,STEP_TIMEOUT_MARKER,createEarlyExit,getStepTimeoutMeta,isEarlyExit,isStepTimeoutError,run});
7
- //# sourceMappingURL=run.cjs.map