timeout-flow 0.0.18 → 0.0.20

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.
package/README.md CHANGED
@@ -1,189 +1,135 @@
1
- # TimeoutFlow
1
+ # timeout-flow
2
2
 
3
3
  [![npm](https://img.shields.io/npm/v/timeout-flow)](https://www.npmjs.com/package/timeout-flow)
4
- [![gzip size](https://img.shields.io/bundlephobia/minzip/timeout-flow)](https://bundlephobia.com/package/timeout-flow)
5
- [![downloads](https://img.shields.io/npm/dw/timeout-flow)](https://www.npmjs.com/package/timeout-flow)
6
- [![GitHub stars](https://img.shields.io/github/stars/iWhatty/TimeoutFlow-js?style=social)](https://github.com/iWhatty/TimeoutFlow-js)
7
-
8
- **Fluent, human-readable time control for JavaScript.**
9
-
10
- TimeoutFlow makes working with time-based logic intuitive — think of it as a modern, composable upgrade to `setTimeout` and `setInterval`, with chaining, conditional logic, pause/resume control, retries, RAF utilities, and more.
11
-
12
- * Minified: ~6–7 KB
13
- * Gzipped: ~2–3 KB
14
- * Zero dependencies
15
- * ESM-first, tree-shakeable
16
-
17
- ---
18
-
19
- # Philosophy
20
-
21
- TimeoutFlow is not just a wrapper around timers.
22
- It’s a composable toolkit for expressing time as readable logic.
23
-
24
- Temporal behavior should be:
25
-
26
- * **Readable** — durations like `"1s"` and `"500ms"` beat magic numbers.
27
- * **Composable** — sequencing should be declarative.
28
- * **Controllable** — timers should pause, resume, cancel.
29
- * **Branchable** — real flows need `if`, `while`, `label`, `jumpTo()`.
30
- * **Tiny** — no runtime bloat.
31
-
32
- > Think of TimeoutFlow as `setTimeout()` with superpowers.
33
-
34
- ---
35
-
36
- # Clean Signatures
37
-
38
- TimeoutFlow supports **both** natural-language ordering and function-first ordering.
39
-
40
- You can write:
41
-
42
- ```js
43
- after('1s', done);
44
- ```
45
-
46
- Or:
47
-
48
- ```js
49
- after(done, '1s');
50
- ```
51
-
52
- Both are valid.
53
-
54
- This applies to:
55
-
56
- * `after()`
57
- * `every()`
58
- * `debounce()`
59
- * `throttle()`
60
-
61
- Use whichever reads best in your codebase.
4
+ [![downloads](https://img.shields.io/npm/dm/timeout-flow)](https://www.npmjs.com/package/timeout-flow)
5
+ [![bundle size](https://img.shields.io/bundlephobia/minzip/timeout-flow)](https://bundlephobia.com/package/timeout-flow)
6
+ [![license](https://img.shields.io/npm/l/timeout-flow)](https://github.com/iWhatty/timeout-flow/blob/main/LICENSE)
7
+ [![stars](https://img.shields.io/github/stars/iWhatty/timeout-flow?style=social)](https://github.com/iWhatty/timeout-flow)
8
+ [![types](https://img.shields.io/npm/types/timeout-flow)](https://www.npmjs.com/package/timeout-flow)
9
+
10
+ Fluent, human-readable time control for JavaScript. A modern, composable upgrade to `setTimeout` and `setInterval` with chaining, conditional logic, pause/resume control, retries, and RAF utilities.
11
+
12
+ ## Features
13
+
14
+ - Readable durations: `"1s"`, `"500ms"`, plain numbers
15
+ - Pause / resume / cancel controllers for `after()`, `every()`, RAF variants
16
+ - `flow()` builds declarative timelines with branching and labels
17
+ - `sleep()` promise delay with `AbortSignal` cancellation
18
+ - `retry()` with fixed/linear/exponential backoff, jitter, deadlines, result predicates and hooks
19
+ - `waitFor()` polls a sync or async predicate with an exact timeout
20
+ - RAF variants (`afterRaf`, `everyRaf`, `debounceRaf`, `throttleRaf`, `waitForRaf`) for frame-aligned timing
21
+ - ESM-first, tree-shakeable. Per-file subpath exports for size-sensitive consumers (~1.2 KB gzipped for a single primitive)
22
+ - Zero dependencies
23
+ - ~15 KB minified for the full kit (~5.5 KB gzipped)
62
24
 
63
25
  ---
64
26
 
65
- # Installation
27
+ ## Install
66
28
 
67
- ```bash
68
- npm install timeout-flow
29
+ ```sh
30
+ pnpm add timeout-flow
69
31
  ```
70
32
 
71
33
  ---
72
34
 
73
- # Unified Control Surface
74
-
75
- Most time-based primitives return a **controller object**:
35
+ ## Quick start
76
36
 
77
37
  ```js
78
38
  import { after } from 'timeout-flow';
79
39
 
80
- function done() {
81
- console.log('done');
40
+ function greet() {
41
+ console.log('Hello');
82
42
  }
83
43
 
84
- const ctrl = after('1s', done);
44
+ const ctrl = after('2s', greet);
85
45
 
86
46
  ctrl.pause();
87
47
  ctrl.resume();
88
48
  ctrl.cancel();
89
- ctrl.reset?.();
90
-
91
- console.log(ctrl.isRunning);
92
- console.log(ctrl.isPaused);
93
- console.log(ctrl.isFinished);
94
49
  ```
95
50
 
96
- Shared by:
97
-
98
- * `after()`
99
- * `every()`
100
- * `afterRaf()`
101
- * `everyRaf()`
102
-
103
- All controllers are:
104
-
105
- * Pause-safe (paused time does not count)
106
- * Cancel-safe
107
- * Monotonic-time based
108
- * AbortSignal-aware (where supported)
109
-
110
51
  ---
111
52
 
112
- # Core Primitives
53
+ ## API
113
54
 
114
- ## after()
55
+ ### `after(duration, fn, options?)`
115
56
 
116
57
  Run once after a delay.
117
58
 
118
59
  ```js
119
60
  import { after } from 'timeout-flow';
120
61
 
121
- function greet() {
62
+ after('2s', function greet() {
122
63
  console.log('Hello');
123
- }
124
-
125
- after('2s', greet);
64
+ });
126
65
  ```
127
66
 
128
- ---
129
-
130
- ## every()
67
+ ### `every(duration, fn, options?)`
131
68
 
132
69
  Repeat execution with optional limit.
133
70
 
134
71
  ```js
135
72
  import { every } from 'timeout-flow';
136
73
 
137
- function tick(i) {
74
+ const ticker = every('1s', function tick(i) {
138
75
  console.log('Tick', i);
139
- }
140
-
141
- const ticker = every('1s', tick, { max: 5 });
76
+ }, { max: 5 });
142
77
  ```
143
78
 
144
- ---
145
-
146
- ## debounce()
79
+ ### `debounce(duration, fn, options?)`
147
80
 
148
81
  Delay execution until inactivity.
149
82
 
150
83
  ```js
151
84
  import { debounce } from 'timeout-flow';
152
85
 
153
- function search(event) {
86
+ const debouncedSearch = debounce('300ms', function search(event) {
154
87
  console.log('Searching for:', event.target.value);
155
- }
156
-
157
- const debouncedSearch = debounce('300ms', search);
88
+ });
158
89
 
159
90
  debouncedSearch.cancel();
160
91
  debouncedSearch.flush();
161
92
  ```
162
93
 
163
- ---
164
-
165
- ## throttle()
94
+ ### `throttle(duration, fn, options?)`
166
95
 
167
96
  Limit execution frequency.
168
97
 
169
98
  ```js
170
99
  import { throttle } from 'timeout-flow';
171
100
 
172
- function handleScroll() {
101
+ const onScroll = throttle('250ms', function handleScroll() {
173
102
  console.log('scroll');
174
- }
175
-
176
- const onScroll = throttle('250ms', handleScroll);
103
+ });
177
104
 
178
105
  onScroll.cancel();
179
106
  onScroll.flush();
180
107
  ```
181
108
 
182
- ---
109
+ ### `sleep(duration?, options?)`
110
+
111
+ Promise-based delay with the same duration format as everything else.
112
+
113
+ ```js
114
+ import { sleep } from 'timeout-flow';
115
+
116
+ await sleep('500ms');
117
+ await sleep(250);
118
+
119
+ // Cancelable: rejects with signal.reason (an AbortError by default)
120
+ // and clears its timer.
121
+ const ac = new AbortController();
122
+ await sleep('10s', { signal: ac.signal });
123
+ ```
183
124
 
184
- ## retry()
125
+ * Numbers behave like `setTimeout`: `NaN` and negative values wait 0 ms.
126
+ * Huge values (including `Infinity`) are capped at ~24.8 days instead of
127
+ overflowing and firing immediately.
128
+ * Invalid strings (e.g. `'soon'`) reject; `sleep()` never throws synchronously.
185
129
 
186
- Retry async operations with backoff + jitter.
130
+ ### `retry(fn, options?)`
131
+
132
+ Retry sync or async work with delays, backoff, jitter, deadlines and hooks.
187
133
 
188
134
  ```js
189
135
  import { retry } from 'timeout-flow';
@@ -202,16 +148,118 @@ await retry(fetchData, {
202
148
  });
203
149
  ```
204
150
 
205
- ---
151
+ | Option | Default | Meaning |
152
+ | --- | --- | --- |
153
+ | `attempts` | `3` | Total attempts including the first. `Infinity` is allowed (pair it with `timeout`). |
154
+ | `delay` | `'500ms'` | Base delay between attempts. |
155
+ | `backoff` | `false` | `false`/`'fixed'`, `'linear'` (`delay * (n+1)`), `true`/`'exponential'` (`delay * factor^n`). |
156
+ | `factor` | `2` | Exponential multiplier. |
157
+ | `maxDelay` | none | Cap applied to every computed delay. |
158
+ | `jitter` | `false` | `true`/`'full'`, `'equal'`, `'decorrelated'`, or a number `j` in `[0, 1]` for proportional ±j jitter (`delay * (1 + (random()*2 - 1) * j)`, applied after the `maxDelay` cap and re-capped by it, never below 0). Other numbers or `NaN` reject with a `RangeError` before any attempt. `delayFirst` is never jittered. Delays are rounded to whole ms. |
159
+ | `delayFirst` | `false` | Wait before the first attempt: `true` uses `delay`, or pass a duration. |
160
+ | `timeout` | none | Overall deadline from the call. No retry starts after it; an in-flight attempt is not interrupted and the first attempt always runs. |
161
+ | `isSuccess(result, attempt)` | none | Return `false` to treat a resolved result as a failure and retry. |
162
+ | `shouldRetry(error, attempt)` | none | Return `false` to stop retrying. |
163
+ | `onAttempt(attempt, elapsedMs)` | none | Called before every attempt. |
164
+ | `onRetry(error, attempt, delayMs)` | none | Called after deciding to retry, before waiting. |
165
+ | `signal` | none | Abort waiting and further attempts. |
166
+ | `sleep(ms, { signal })` | built-in `sleep` | Injectable wait, e.g. for fake-timer tests. |
167
+ | `now()` | `performance.now` | Injectable clock used for `timeout`. |
168
+ | `random()` | `Math.random` | Injectable RNG for jitter. |
169
+
170
+ Attempt numbers are **0-based** everywhere (`fn(attempt)`, hooks, predicates).
171
+
172
+ Outcome:
173
+
174
+ * Resolves with the first successful result.
175
+ * Otherwise rejects with the **last failure**: the last thrown error as-is, or,
176
+ if the last attempt resolved with a result `isSuccess` rejected, an error
177
+ with `name: 'RetryError'`, `.result` (that last result) and `.attempts`.
178
+ * On abort, rejects with `signal.reason` (an `AbortError` by default).
179
+
180
+ #### Retry recipes
181
+
182
+ Retry until a result looks right, with a little log line per attempt:
183
+
184
+ ```js
185
+ const response = await retry(() => sendMessage(tabId, msg), {
186
+ attempts: 4,
187
+ delay: 200,
188
+ backoff: 'exponential',
189
+ maxDelay: '2s',
190
+ isSuccess: (res) => res?.ok === true,
191
+ onAttempt: (attempt, elapsed) => console.debug('attempt', attempt, Math.round(elapsed), 'ms'),
192
+ });
193
+ ```
194
+
195
+ Exponential backoff with ±15% proportional jitter:
196
+
197
+ ```js
198
+ await retry(poll, {
199
+ attempts: 5,
200
+ delay: 200,
201
+ backoff: true,
202
+ factor: 1.6,
203
+ maxDelay: '1500ms',
204
+ jitter: 0.15, // each wait lands within 85%..115% of its computed delay
205
+ });
206
+ ```
207
+
208
+ Time-bounded retry (deadline instead of an attempt count):
209
+
210
+ ```js
211
+ await retry(() => connect(), {
212
+ attempts: Infinity,
213
+ delay: '250ms',
214
+ timeout: '5s',
215
+ });
216
+ ```
217
+
218
+ Give something a moment to settle before the first try, and stop on fatal errors:
219
+
220
+ ```js
221
+ await retry(loadConfig, {
222
+ delayFirst: '100ms',
223
+ attempts: 3,
224
+ backoff: 'linear',
225
+ shouldRetry: (err) => err.name !== 'SyntaxError',
226
+ });
227
+ ```
228
+
229
+ Return a result object instead of throwing:
230
+
231
+ ```js
232
+ const outcome = await retry(task, { attempts: 3 }).then(
233
+ (value) => ({ ok: true, value }),
234
+ (error) => ({ ok: false, error, value: error?.result })
235
+ );
236
+ ```
237
+
238
+ Deterministic tests without real timers:
239
+
240
+ ```js
241
+ let clock = 0;
242
+ const waits = [];
243
+
244
+ await retry(task, {
245
+ attempts: 4,
246
+ delay: 100,
247
+ backoff: true,
248
+ now: () => clock,
249
+ sleep: async (ms) => { waits.push(ms); clock += ms; },
250
+ }).catch(() => {});
251
+
252
+ // waits -> [100, 200, 400]
253
+ ```
206
254
 
207
- ## waitFor()
255
+ ### `waitFor(predicate, options?)`
208
256
 
209
- Wait until a condition becomes true.
257
+ Wait until a condition becomes truthy. Resolves with the condition's value.
210
258
 
211
259
  ```js
212
260
  import { waitFor } from 'timeout-flow';
213
261
 
214
- await waitFor(function checkLoaded() {
262
+ const el = await waitFor(function findLoaded() {
215
263
  return document.querySelector('#loaded');
216
264
  }, {
217
265
  interval: '250ms',
@@ -220,92 +268,98 @@ await waitFor(function checkLoaded() {
220
268
  });
221
269
  ```
222
270
 
223
- ---
271
+ Timing model:
272
+
273
+ * The first check runs after `interval` unless `immediate: true`.
274
+ * Conditions may be async; the next check is scheduled `interval` after the
275
+ previous one settles, so checks never overlap.
276
+ * `timeout` is measured from the call and has its own timer, so it is not
277
+ rounded up to the next poll. At the deadline a sync condition gets one final
278
+ check, so success at exactly `timeout` counts (`elapsed >= timeout` times out
279
+ only if the condition is still falsy). It rejects with an `Error` named
280
+ `'TimeoutError'` (message `'waitFor timed out'`).
281
+ * `signal` rejects with `signal.reason`.
282
+
283
+ `waitForRaf()` checks once per animation frame and measures `timeout` from the
284
+ first frame's timestamp (RAF time), timing out once `elapsed >= timeout`.
224
285
 
225
- # Fluent Timeline
286
+ ### `flow()`
226
287
 
227
288
  Build declarative time flows.
228
289
 
229
290
  ```js
230
291
  import { flow } from 'timeout-flow';
231
292
 
232
- function stepOne() {
233
- console.log('Step 1');
234
- }
235
-
236
- function tick(i) {
237
- console.log('Tick', i);
238
- }
239
-
240
- function finalStep() {
241
- console.log('Final Step');
242
- }
243
-
244
293
  flow()
245
- .after('1s', stepOne)
246
- .every('500ms', tick, { max: 3 })
247
- .after('1s', finalStep)
294
+ .after('1s', function stepOne() {
295
+ console.log('Step 1');
296
+ })
297
+ .every('500ms', function tick(i) {
298
+ console.log('Tick', i);
299
+ }, { max: 3 })
300
+ .after('1s', function finalStep() {
301
+ console.log('Final Step');
302
+ })
248
303
  .start();
249
304
  ```
250
305
 
251
306
  Flow reads like a timeline and keeps duration-first ordering for readability.
252
307
 
253
- ---
308
+ ### RAF utilities
254
309
 
255
- # AbortSignal Support
310
+ Frame-based timing powered by `requestAnimationFrame`. Ideal for visual updates, scroll handlers, layout checks, and animation loops.
256
311
 
257
- Many utilities accept `{ signal }` for automatic cancellation.
312
+ Available: `afterRaf()`, `everyRaf()`, `debounceRaf()`, `throttleRaf()`, `waitForRaf()`.
258
313
 
259
314
  ```js
260
- import { after } from 'timeout-flow';
261
-
262
- const ac = new AbortController();
263
-
264
- function doWork() {
265
- console.log('Will not run if aborted');
266
- }
315
+ import { throttleRaf } from 'timeout-flow';
267
316
 
268
- after('2s', doWork, { signal: ac.signal });
317
+ const onScroll = throttleRaf(function drawFrame() {
318
+ console.log('draw');
319
+ });
269
320
 
270
- ac.abort();
321
+ onScroll.cancel();
322
+ onScroll.flush();
271
323
  ```
272
324
 
273
- If already aborted at creation time, no work is scheduled.
325
+ ### Controllers
274
326
 
275
- ---
327
+ Most time-based primitives return a controller object:
276
328
 
277
- # RAF Utilities
329
+ ```js
330
+ const ctrl = after('1s', () => console.log('done'));
278
331
 
279
- Frame-based timing powered by `requestAnimationFrame`.
332
+ ctrl.pause();
333
+ ctrl.resume();
334
+ ctrl.cancel();
335
+ ctrl.reset?.();
280
336
 
281
- Ideal for visual updates, scroll handlers, layout checks, and animation loops.
337
+ console.log(ctrl.isRunning);
338
+ console.log(ctrl.isPaused);
339
+ console.log(ctrl.isFinished);
340
+ ```
282
341
 
283
- ## Available
342
+ Shared by `after()`, `every()`, `afterRaf()`, `everyRaf()`. All controllers are pause-safe (paused time does not count), cancel-safe, monotonic-time based, and `AbortSignal`-aware where supported.
284
343
 
285
- * `afterRaf()`
286
- * `everyRaf()`
287
- * `debounceRaf()`
288
- * `throttleRaf()`
289
- * `waitForRaf()`
344
+ ### AbortSignal support
290
345
 
291
- ## Example
346
+ Many utilities accept `{ signal }` for automatic cancellation.
292
347
 
293
348
  ```js
294
- import { throttleRaf } from 'timeout-flow';
349
+ import { after } from 'timeout-flow';
295
350
 
296
- function drawFrame() {
297
- console.log('draw');
298
- }
351
+ const ac = new AbortController();
299
352
 
300
- const onScroll = throttleRaf(drawFrame);
353
+ after('2s', function doWork() {
354
+ console.log('Will not run if aborted');
355
+ }, { signal: ac.signal });
301
356
 
302
- onScroll.cancel();
303
- onScroll.flush();
357
+ ac.abort();
304
358
  ```
305
359
 
306
- ---
360
+ If already aborted at creation time, no work is scheduled.
307
361
 
308
- # Public API
362
+ ### Public surface
309
363
 
310
364
  ```js
311
365
  import {
@@ -313,6 +367,7 @@ import {
313
367
  every,
314
368
  debounce,
315
369
  throttle,
370
+ sleep,
316
371
  retry,
317
372
  waitFor,
318
373
  flow,
@@ -327,6 +382,72 @@ import {
327
382
 
328
383
  ---
329
384
 
330
- # License
385
+ ## Notes
386
+
387
+ ### Tree-shaking and per-primitive imports
388
+
389
+ Two import styles, same package, choose by bundle-size sensitivity:
390
+
391
+ ```js
392
+ // Full kit. Every primitive available on one import.
393
+ // Modern bundlers (esbuild, vite, rollup, webpack 5) will tree-shake
394
+ // unused exports because the package ships `sideEffects: false` and the
395
+ // `.` entrypoint points at ESM source instead of a pre-minified blob.
396
+ import { after, debounce, retry } from 'timeout-flow';
397
+ ```
398
+
399
+ ```js
400
+ // Per-primitive subpath. Explicit minimum surface, useful when you know
401
+ // you only need one primitive and want the bundle to reflect that
402
+ // without relying on the bundler's tree-shaker. Same source either way.
403
+ import { after } from 'timeout-flow/after';
404
+ import { every } from 'timeout-flow/every';
405
+ import { debounce } from 'timeout-flow/debounce';
406
+ import { throttle } from 'timeout-flow/throttle';
407
+ import { sleep } from 'timeout-flow/sleep';
408
+ import { retry } from 'timeout-flow/retry';
409
+ import { waitFor } from 'timeout-flow/wait-for';
410
+ import { flow } from 'timeout-flow/flow';
411
+ import { afterRaf, everyRaf, debounceRaf, throttleRaf, waitForRaf } from 'timeout-flow/raf';
412
+ import { parseDuration } from 'timeout-flow/parse-duration';
413
+ ```
414
+
415
+ Measured for a single `after()` call in a typical browser bundler (esbuild, minified + gzip):
416
+
417
+ | Import style | Gzip |
418
+ |---|---:|
419
+ | pre-0.0.19 default (full minified bundle) | 5098 bytes |
420
+ | 0.0.19 default (`import { after } from 'timeout-flow'`) | 1199 bytes |
421
+ | 0.0.19 subpath (`import { after } from 'timeout-flow/after'`) | 1199 bytes |
422
+
423
+ For unbundled `<script type="module">` consumption of the full kit, use the **`timeout-flow/min`** subpath, which points at the pre-built minified IIFE.
424
+
425
+ ### Clean signatures
426
+
427
+ timeout-flow supports both natural-language and function-first argument ordering:
428
+
429
+ ```js
430
+ after('1s', done);
431
+ // or
432
+ after(done, '1s');
433
+ ```
434
+
435
+ This applies to `after()`, `every()`, `debounce()`, `throttle()`. Use whichever reads best in your codebase.
436
+
437
+ ### Philosophy
438
+
439
+ timeout-flow is not just a wrapper around timers, it's a composable toolkit for expressing time as readable logic. Temporal behavior should be:
440
+
441
+ - **Readable.** Durations like `"1s"` and `"500ms"` beat magic numbers.
442
+ - **Composable.** Sequencing should be declarative.
443
+ - **Controllable.** Timers should pause, resume, cancel.
444
+ - **Branchable.** Real flows need `if`, `while`, `label`, `jumpTo()`.
445
+ - **Tiny.** No runtime bloat.
446
+
447
+ > Think of timeout-flow as `setTimeout()` with superpowers.
448
+
449
+ ---
450
+
451
+ ## License
331
452
 
332
- --{DR.WATT v3.0}--
453
+ Licensed under AGPL-3.0 with WATT3D Additional Terms. See [LICENSE](./LICENSE) and [ADDITIONAL_TERMS.md](./ADDITIONAL_TERMS.md). Commercial AI/model-training use requires compliance with those terms or a separate WATT3D license. © WATT3D.
@@ -1,2 +1,2 @@
1
1
  // TimeoutFlow - Fluent timer + RAF control library
2
- function k(e){if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`Expected a finite number of ms, got: ${e}`);return e}if(typeof e!="string")throw new TypeError(`Expected a duration string or number, got ${typeof e}`);let n=e.toLowerCase().trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/);if(!n)throw new Error(`Invalid duration format: "${e}". Expected formats like "500ms", "2s", "1.5m", or "1h".`);let i=Number(n[1]);if(!Number.isFinite(i))throw new TypeError(`Invalid duration value: "${n[1]}"`);let o=n[2];switch(o){case"ms":return i;case"s":return i*1e3;case"m":return i*6e4;case"h":return i*36e5;default:throw new Error(`Unsupported duration unit: "${o}"`)}}var I;typeof performance<"u"&&typeof performance.now=="function"?I=()=>performance.now():I=()=>Date.now();var W=class{#s;#o=null;#e;#n=null;#t=!1;#r=!1;#i=!1;constructor(r){this.#s=k(r),this.#e=this.#s}get isRunning(){return this.#t}get isPaused(){return this.#r}get isFinished(){return this.#i}pause(){if(!this.#t)return;clearTimeout(this.#n),this.#n=null;let r=I()-this.#o;this.#e=Math.max(0,this.#e-r),this.#t=!1,this.#r=!0}resume(r,n=null){if(this.#i||this.#t)return;let i=n??this.#e;if(!Number.isFinite(i)||i<0)return;let o=Math.max(0,i);this.#e=o,this.#o=I(),this.#t=!0,this.#r=!1,this.#n=setTimeout(()=>{this.#n=null,this.#t=!1,this.#r=!1,this.#i=!0,this.#e=0,r?.()},o)}cancel(){this.#n&&clearTimeout(this.#n),this.#n=null,this.#t=!1,this.#r=!1,this.#i=!0,this.#e=0}reset(){this.#n&&clearTimeout(this.#n),this.#n=null,this.#o=null,this.#e=this.#s,this.#t=!1,this.#r=!1,this.#i=!1}};var L;typeof DOMException<"u"?L=(e="Aborted")=>new DOMException(e,"AbortError"):L=(e="Aborted")=>{let r=new Error(e);return r.name="AbortError",r};function C(e,r){return e?e.aborted?(r(),()=>{}):(e.addEventListener("abort",r,{once:!0}),()=>e.removeEventListener("abort",r)):()=>{}}function $(e,r){let n=null;return{add(){n||(n=C(e,r))},remove(){n&&(n(),n=null)},reset(){n&&n(),n=null}}}var U=class extends W{#s=null;#o=null;#e=()=>{};constructor(r,n,{onFinish:i,signal:o}={}){super(r),this.#s=o??null,this.#o=()=>this.cancel(),this.#n(),!this.isFinished&&this.resume(()=>{this.#t(),n?.(),i?.()})}#n(){if(!(!this.#s||!this.#o)){if(this.#s.aborted){super.cancel(),this.#t();return}this.#e=C(this.#s,this.#o)}}#t(){this.#e(),this.#e=()=>{},this.#o=null}cancel(){this.isFinished||(this.#t(),super.cancel())}reset(){this.#e(),this.#e=()=>{},this.#o=()=>this.cancel(),super.reset(),this.#n()}};var Q=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function q(e,r,n,i=0){let o,l,f;if(typeof e=="function"?(o=e,Q(r)?(l=i,f=r):(l=r,f=Q(n)?n:{})):(l=e,o=r,f=Q(n)?n:{}),typeof o!="function")throw new TypeError(`Expected a function as one argument, got: ${typeof o}`);let a=l??i;if(a==null)throw new TypeError("Expected a duration (string/number) for delay");let s=k(a);return{fn:o,delay:s,options:f}}function V(e,r,n){let{fn:i,delay:o,options:l}=q(e,r,n,void 0);return new U(o,i,l)}var z=class{#s;#o;#e;#n=0;#t=!1;#r=null;#i=null;#l=()=>{};constructor(r,n,{max:i=1/0,runImmediately:o=!1,signal:l}={}){if(this.#s=k(r),this.#o=n,this.#e=i,this.#i=l??null,!(this.#e>0)&&this.#e!==1/0){this.#t=!0,this.#l();return}if(this.#i?.aborted){this.#t=!0,this.#l();return}this.#l=C(this.#i,()=>this.cancel()),o?this.#f():this.#u()}get count(){return this.#n}get isRunning(){return!this.#t&&!!this.#r&&this.#r.isRunning}get isPaused(){return!this.#t&&!!this.#r&&this.#r.isPaused}get isFinished(){return this.#t}#a=()=>{this.#r?.cancel(),this.#r=null,this.#t=!0,this.#l(),this.#l=()=>{},this.#i=null};#f=()=>{if(!this.#t){if(this.#i?.aborted){this.#a();return}if(this.#n>=this.#e){this.#a();return}if(this.#o?.(this.#n++),this.#n>=this.#e){this.#a();return}this.#u()}};#u(){if(!this.#t){if(this.#i?.aborted){this.#a();return}this.#r=new W(this.#s),this.#r.resume(this.#f)}}pause(){this.#t||this.#r?.pause()}resume(){if(!this.#t){if(this.#i?.aborted){this.#a();return}if(this.#n>=this.#e){this.#a();return}if(this.#r){this.#r.isPaused?this.#r.resume(this.#f):this.#r.isRunning||this.#u();return}this.#u()}}cancel(){this.#t||this.#a()}reset(r=!1){if(this.#r?.cancel(),this.#r=null,this.#n=0,this.#t=!1,this.#i?.aborted){this.#t=!0,this.#l(),this.#l=()=>{},this.#i=null;return}if(r){if(!(this.#e>0)&&this.#e!==1/0){this.#t=!0,this.#l(),this.#l=()=>{},this.#i=null;return}this.#u()}}};function X(e,r,n){let{fn:i,delay:o,options:l}=q(e,r,n,void 0);return new z(o,i,l)}function at({signal:e}={}){let r=[],n=new Map,i=0,o=!1,l=!1,f=!1,a=!1,s=!1,c=1/0,p=0,b=null,h=null,y=null,m=[],u=!1,x=null,w=null,d,A=$(e,()=>d.cancel()),v=t=>{t&&t.controller&&(t.controller=null)},F=()=>{let t=r[i];t?.controller?.cancel?.(),t&&(t.controller=null)},T=()=>{a||f||(o=!1,l=!1,a=!0,F(),A.remove(),b?.())},R=()=>{f||(o=!1,l=!1,a=!1,f=!0,F(),A.remove())},E=(t,g)=>{if(R(),h){try{h(t,{step:g,index:i})}catch{}return}throw t},D=(t,g)=>{try{return t()}catch(M){E(M,g);return}},P=t=>{v(t),i+=1,queueMicrotask(_)};function _(){if(f||l||a)return;if(e?.aborted){R();return}if(y){let g=n.get(y);if(typeof g=="number")i=g;else{D(()=>{throw new Error(`Label "${y}" not found`)},r[i]);return}y=null}if(m.length>0){let g=m.shift();D(g,r[i])||(u=!0)}if(u){let g=r[i];if(!g||g.type==="label")u=!1;else return P(g)}let t=r[i];if(!t||i>=r.length){s&&++p<c?(i=0,_()):T();return}if(t.type==="label")return P(t);if(t.type==="after"){t.controller=V(()=>D(t.fn,t),t.duration,{signal:e,onFinish:()=>P(t)});return}if(t.type==="every"){if(!(t.times>0)&&t.times!==1/0)return P(t);let g=0,M=X(()=>{if(!(l||f||a)){if(e?.aborted){R();return}if(t.whileCondition&&!D(t.whileCondition,t)||(D(()=>t.fn(g++),t),t.doWhileCondition&&!D(t.doWhileCondition,t))||g>=t.times)return M.cancel(),P(t)}},t.duration,{max:t.times,signal:e});t.controller=M}}return d={after(t,g){return r.push({type:"after",duration:t,fn:g,controller:null}),d},every(t,g,M=1/0){let N=typeof M=="number"?M:M?.max??1/0,S=N===1/0?1/0:Math.max(0,N|0);return r.push({type:"every",duration:t,fn:g,times:S,whileCondition:x,doWhileCondition:w,controller:null}),x=null,w=null,d},loop(t=!0){return s=!0,c=t===!0?1/0:t,d},onFinish(t){return b=t,d},onError(t){return h=t,d},start(){return F(),f=!1,a=!1,l=!1,o=!0,i=0,p=0,A.reset(),e?.aborted||A.add(),e?.aborted?(R(),d):(_(),d)},pause(){l||f||a||(l=!0,r[i]?.controller?.pause?.())},resume(){if(!(!l||f||a)){if(e?.aborted){R();return}l=!1,r[i]?.controller?.resume?.()}},cancel(){R()},reset(){return R(),r.length=0,n.clear(),i=0,p=0,b=null,h=null,y=null,m=[],u=!1,x=null,w=null,o=!1,l=!1,f=!1,a=!1,d},label(t){return n.set(t,r.length),r.push({type:"label",name:t,controller:null}),d},jumpTo(t){return y=t,d},if(t){return m.push(()=>typeof t=="function"?!!t():!!t),d},unless(t){return m.push(()=>typeof t=="function"?!t():!t),d},while(t){return x=()=>typeof t=="function"?!!t():!!t,d},doWhile(t){return w=()=>typeof t=="function"?!!t():!!t,d},get isRunning(){return o&&!l&&!f&&!a},get isPaused(){return l},get isCancelled(){return f},get isFinished(){return a}},d}function ut(e,r,n){let{fn:i,delay:o,options:l}=q(e,r,n,void 0),f=l?.signal,a=l?.trailing??!0,s=Math.max(0,o),c=-1/0,p=0,b=null,h=null,y=$(f,()=>u()),m=()=>{if(!b)return;let d=b,A=h;b=null,h=null,y.remove(),i.apply(A,d)},u=()=>{p&&clearTimeout(p),p=0,b=null,h=null,y.remove()},x=d=>{y.add(),p=setTimeout(()=>{p=0,c=I(),m()},d)},w=function(...d){if(f?.aborted)return;let A=I(),v=A-c;if(b=d,h=this,v>=s){c=A,p&&(clearTimeout(p),p=0,y.remove()),m();return}if(a&&!p){let F=Math.max(0,s-v);x(F)}};return w.cancel=u,w.flush=()=>{p&&(clearTimeout(p),p=0,c=I(),m())},f?.aborted&&u(),w}function ft(e,r,n){let{fn:i,delay:o,options:l}=q(e,r,n,0),f=l?.signal,a=Math.max(0,o),s=0,c=null,p=null,b=$(f,()=>y()),h=()=>{if(!c)return;let u=c,x=p;c=null,p=null,b.remove(),i.apply(x,u)},y=()=>{s&&clearTimeout(s),s=0,c=null,p=null,b.remove()},m=function(...u){f?.aborted||(c=u,p=this,s&&clearTimeout(s),b.add(),s=setTimeout(()=>{s=0,h()},a))};return m.cancel=y,m.flush=()=>{s&&(clearTimeout(s),s=0,h())},f?.aborted&&y(),m}function ct(e,{interval:r="250ms",timeout:n,immediate:i=!1,signal:o}={}){return new Promise((l,f)=>{if(o?.aborted){f(L());return}let a=I(),s=typeof r=="string"?k(r):r,c=n!=null?k(n):null,p=null,b=()=>{p!=null&&(clearInterval(p),p=null),y()},y=C(o,()=>{b(),f(L())}),m=()=>{let u=!1;try{u=!!e()}catch(x){b(),f(x);return}if(u){b(),l();return}c!=null&&I()-a>=c&&(b(),f(new Error("waitFor timed out")))};i&&m(),p=setInterval(m,s)})}async function ht(e,{attempts:r=3,delay:n="500ms",backoff:i=!1,factor:o=2,maxDelay:l,jitter:f=!1,signal:a,random:s=Math.random,shouldRetry:c,onRetry:p}={}){if(typeof e!="function")throw new TypeError("retry: fn must be a function");let b=Math.max(1,r|0);if(a?.aborted)throw L();let h=k(n),y=l!=null?k(l):1/0,m=Math.min(h,y);for(let u=0;u<b;u++){if(a?.aborted)throw L();try{return await e(u)}catch(x){if(u===b-1||c&&!await c(x,u))throw x;let d=i?h*Math.pow(o,u):h,A=mt({expDelay:d,baseDelay:h,maxDelayMs:y,jitter:f,random:s,prevSleep:m});m=A,p&&await p(x,u,A),await pt(A,a)}}throw new Error("retry: exhausted attempts unexpectedly")}function mt({expDelay:e,baseDelay:r,maxDelayMs:n,jitter:i,random:o,prevSleep:l}){let f=Math.min(e,n);if(!i)return f;let a=i===!0?"full":i;if(a==="full")return Math.min(n,Y(0,f,o));if(a==="equal"){let s=f/2;return Math.min(n,s+Y(0,s,o))}if(a==="decorrelated"){let s=Y(r,l*3,o);return Math.min(n,s)}return f}function Y(e,r,n){let i=n(),o=Number.isFinite(i)?Math.min(1,Math.max(0,i)):0;return e+(r-e)*o}function pt(e,r){return new Promise((n,i)=>{if(r?.aborted){i(L());return}let o=0,l=()=>{o&&clearTimeout(o),o=0,a()},a=C(r,()=>{l(),i(L())});o=setTimeout(()=>{l(),n()},e)})}function j(e,r,n,i){let o=typeof n=="function"?n:void 0,l=o?i:n,{fn:f,delay:a,options:s}=q(e,r,l,void 0),{signal:c,onFinish:p}=o?{...s,onFinish:o}:s,b=Math.max(0,a),h=0,y=b,m=null,u=!1,x=!1,w=!1,d=()=>{h&&cancelAnimationFrame(h),h=0},A=()=>{},v=()=>{A(),A=()=>{}},F=()=>{d(),u=!1,x=!1,w=!0,m=null,y=0,v()},T=()=>{F(),f?.(),p?.()},R=()=>{w||F()},E=()=>{if(v(),c?.aborted){w=!0,y=0;return}A=C(c,R)};E();let D=g=>{if(!u||w)return;if(m==null&&(m=g),g-m>=y){T();return}h=requestAnimationFrame(D)},P=()=>{if(!u||w)return;d();let g=I();if(m!=null){let M=g-m;y=Math.max(0,y-M)}m=null,u=!1,x=!0},_=()=>{if(!(w||u||!x)&&!c?.aborted){if(!(y>0)){T();return}x=!1,u=!0,m=null,h=requestAnimationFrame(D)}},t=()=>{d(),m=null,y=b,u=!1,x=!1,w=!1,E()};return w?v():y>0?(u=!0,h=requestAnimationFrame(D)):T(),{pause:P,resume:_,cancel:R,reset:t,get isRunning(){return u},get isPaused(){return x},get isFinished(){return w}}}var G=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function tt(e,r,n,i,o){let l=typeof e!="function",f,a,s;l?(G(n)?s=n:G(i)?s=i:G(o)?s=o:s={},typeof n=="number"&&(f=n),typeof i=="boolean"&&(a=i),a==null&&typeof n=="boolean"&&(a=n)):s=G(n)?n:{};let{fn:c,delay:p,options:b}=q(e,r,s,void 0),h=b?.signal,y=b?.max??1/0,m=b?.runImmediately??!1,u=f??y,x=a??m,w=Math.max(0,p),d=0,A=0,v=w,F=null,T=!1,R=!1,E=!1,D=()=>{d&&cancelAnimationFrame(d),d=0},P=()=>{},_=()=>{P(),P=()=>{}},t=()=>{D(),T=!1,R=!1,E=!0,F=null,v=0,_()},g=()=>{E||t()},M=()=>{if(_(),h?.aborted){E=!0,v=0;return}P=C(h,g)};M();let N=()=>A<u,S=()=>(c?.(A++),N()?!0:(t(),!1)),H=O=>{if(!T||E)return;if(h?.aborted){t();return}if(!N()){t();return}F==null&&(F=O);let K=O-F;F=O,v-=K;let Z=Math.max(0,w);if(Z===0){v=0,S(),d=requestAnimationFrame(H);return}for(;v<=0&&!E;){if(!S())return;v+=Z}d=requestAnimationFrame(H)},J=()=>{if(!E){if(h?.aborted){t();return}if(!N()){t();return}T=!0,R=!1,F=null,d=requestAnimationFrame(H)}},ot=()=>{if(!T||E)return;D();let O=I();if(F!=null){let K=O-F;v=Math.max(0,v-K)}F=null,T=!1,R=!0},st=()=>{if(!(E||T||!R)&&!h?.aborted){if(!N()){t();return}J()}},lt=(O=!1)=>{if(D(),A=0,v=w,F=null,T=!1,R=!1,E=!1,M(),!E){if(!(u>0)&&u!==1/0){t();return}if(O){if(x&&N()&&(S(),E))return;J()}}};return E?_():!(u>0)&&u!==1/0?t():(x&&N()&&S(),E||(v=Math.max(0,w),J())),{pause:ot,resume:st,cancel:g,reset:lt,get isRunning(){return T},get isPaused(){return R},get isFinished(){return E},get count(){return A}}}function et(e,r,n){let{fn:i,delay:o,options:l}=q(e,r,n,0),f=Math.max(0,o),a=l?.signal,s=0,c=null,p=null,b=0,h=()=>{s&&cancelAnimationFrame(s),s=0},y=$(a,()=>m()),m=()=>{h(),c=null,p=null,b=0,y.remove()},u=()=>{if(!c)return;let d=c,A=p;c=null,p=null,y.remove(),i.apply(A,d)},x=d=>{if(!s)return;if(!c){m();return}if(d-b>=f){h(),u();return}s=requestAnimationFrame(x)},w=function(...d){a?.aborted||(c=d,p=this,b=I(),y.add(),h(),s=requestAnimationFrame(x))};return w.cancel=m,w.flush=()=>{!s||!c||(h(),u())},a?.aborted&&m(),w}var rt=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function nt(e,r=0,n){if(typeof e!="function")throw new TypeError(`Expected a function, got: ${typeof e}`);let i=typeof r=="number"?r:0,o=rt(r)?r:rt(n)?n:{},l=o.signal,f=o.trailing??!0,a=Math.max(0,i|0),s=!1,c=0,p=null,b=null,h=a,y=$(l,()=>u()),m=()=>{s=!1,c&&cancelAnimationFrame(c),c=0,h=a,p=null,b=null,y.remove()},u=()=>{m()},x=()=>{if(!p)return;let T=p,R=b;p=null,b=null,y.remove(),e.apply(R,T)},w=()=>{s=!1,c=0,h=a,x()},d=()=>{if(s){if(l?.aborted){u();return}if(h===0){w();return}h-=1,c=requestAnimationFrame(d)}},A=()=>{if(s){if(l?.aborted){u();return}w()}},v=a===0?()=>{s=!0,y.add(),c=requestAnimationFrame(A)}:()=>{s=!0,h=a,y.add(),c=requestAnimationFrame(d)},F=function(...T){l?.aborted||((!s||f)&&(p=T,b=this),!s&&v())};return F.cancel=u,F.flush=()=>{if(s){if(l?.aborted){u();return}s=!1,c&&cancelAnimationFrame(c),c=0,h=a,x()}},l?.aborted&&u(),F}function it(e,{timeout:r,signal:n,immediate:i=!1}={}){return new Promise((o,l)=>{if(typeof e!="function"){l(new TypeError(`waitForRaf: condition must be a function, got: ${typeof e}`));return}if(n?.aborted){l(L());return}let f=r!=null?Math.max(0,k(r)):null,a=0,s=null,c=()=>{a&&cancelAnimationFrame(a),a=0,b()},b=C(n,()=>{c(),l(L())}),h=()=>{try{return!!e()}catch(m){return c(),l(m),null}};if(i){let m=h();if(m===null)return;if(m){c(),o();return}if(f===0){c(),l(new Error("waitForRaf timed out"));return}}let y=m=>{s==null&&(s=m);let u=h();if(u!==null){if(u){c(),o();return}if(f!=null&&m-s>=f){c(),l(new Error("waitForRaf timed out"));return}a=requestAnimationFrame(y)}};a=requestAnimationFrame(y)})}function dt(){if(typeof requestAnimationFrame!="function")throw new Error("requestAnimationFrame is not available in this environment. Use the non-RAF timers (after/every/waitFor) in Node, or provide a RAF polyfill.")}var B=e=>(...r)=>(dt(),e(...r)),yt=B(j),bt=B(tt),wt=B(et),xt=B(nt),At=B(it);export{V as after,yt as afterRaf,ft as debounce,wt as debounceRaf,X as every,bt as everyRaf,at as flow,k as parseDuration,ht as retry,ut as throttle,xt as throttleRaf,ct as waitFor,At as waitForRaf};
2
+ function P(e){if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`Expected a finite number of ms, got: ${e}`);return e}if(typeof e!="string")throw new TypeError(`Expected a duration string or number, got ${typeof e}`);let n=e.toLowerCase().trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/);if(!n)throw new Error(`Invalid duration format: "${e}". Expected formats like "500ms", "2s", "1.5m", or "1h".`);let i=Number(n[1]);if(!Number.isFinite(i))throw new TypeError(`Invalid duration value: "${n[1]}"`);let s=n[2];switch(s){case"ms":return i;case"s":return i*1e3;case"m":return i*6e4;case"h":return i*36e5;default:throw new Error(`Unsupported duration unit: "${s}"`)}}var k;typeof performance<"u"&&typeof performance.now=="function"?k=()=>performance.now():k=()=>Date.now();var B=class{#s;#o=null;#e;#n=null;#t=!1;#r=!1;#i=!1;constructor(r){this.#s=P(r),this.#e=this.#s}get isRunning(){return this.#t}get isPaused(){return this.#r}get isFinished(){return this.#i}pause(){if(!this.#t)return;clearTimeout(this.#n),this.#n=null;let r=k()-this.#o;this.#e=Math.max(0,this.#e-r),this.#t=!1,this.#r=!0}resume(r,n=null){if(this.#i||this.#t)return;let i=n??this.#e;if(!Number.isFinite(i))return;let s=Math.max(0,i);this.#e=s,this.#o=k(),this.#t=!0,this.#r=!1,this.#n=setTimeout(()=>{this.#n=null,this.#t=!1,this.#r=!1,this.#i=!0,this.#e=0,r?.()},s)}cancel(){this.#n&&clearTimeout(this.#n),this.#n=null,this.#t=!1,this.#r=!1,this.#i=!0,this.#e=0}reset(){this.#n&&clearTimeout(this.#n),this.#n=null,this.#o=null,this.#e=this.#s,this.#t=!1,this.#r=!1,this.#i=!1}};var Q;typeof DOMException<"u"?Q=(e="Aborted")=>new DOMException(e,"AbortError"):Q=(e="Aborted")=>{let r=new Error(e);return r.name="AbortError",r};function L(e,r){return e?e.aborted?(r(),()=>{}):(e.addEventListener("abort",r,{once:!0}),()=>e.removeEventListener("abort",r)):()=>{}}function N(e,r){let n=null;return{add(){n||(n=L(e,r))},remove(){n&&(n(),n=null)},reset(){n&&n(),n=null}}}function $(e){return e?.reason??Q()}var X=class extends B{#s=null;#o=null;#e=()=>{};constructor(r,n,{onFinish:i,signal:s}={}){super(r),this.#s=s??null,this.#o=()=>this.cancel(),this.#n(),!this.isFinished&&this.resume(()=>{this.#t(),n?.(),i?.()})}#n(){if(!(!this.#s||!this.#o)){if(this.#s.aborted){super.cancel(),this.#t();return}this.#e=L(this.#s,this.#o)}}#t(){this.#e(),this.#e=()=>{},this.#o=null}cancel(){this.isFinished||(this.#t(),super.cancel())}reset(){this.#e(),this.#e=()=>{},this.#o=()=>this.cancel(),super.reset(),this.#n()}};var V=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function _(e,r,n,i=0){let s,l,a;if(typeof e=="function"?(s=e,V(r)?(l=i,a=r):(l=r,a=V(n)?n:{})):(l=e,s=r,a=V(n)?n:{}),typeof s!="function")throw new TypeError(`Expected a function as one argument, got: ${typeof s}`);let u=l??i;if(u==null)throw new TypeError("Expected a duration (string/number) for delay");let o=P(u);return{fn:s,delay:o,options:a}}function Z(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,void 0);return new X(s,i,l)}var Y=class{#s;#o;#e;#n=0;#t=!1;#r=null;#i=null;#l=()=>{};constructor(r,n,{max:i=1/0,runImmediately:s=!1,signal:l}={}){if(this.#s=P(r),this.#o=n,this.#e=i,this.#i=l??null,!(this.#e>0)&&this.#e!==1/0){this.#t=!0,this.#l();return}if(this.#i?.aborted){this.#t=!0,this.#l();return}this.#l=L(this.#i,()=>this.cancel()),s?this.#f():this.#u()}get count(){return this.#n}get isRunning(){return!this.#t&&!!this.#r&&this.#r.isRunning}get isPaused(){return!this.#t&&!!this.#r&&this.#r.isPaused}get isFinished(){return this.#t}#a=()=>{this.#r?.cancel(),this.#r=null,this.#t=!0,this.#l(),this.#l=()=>{},this.#i=null};#f=()=>{if(!this.#t){if(this.#i?.aborted){this.#a();return}if(this.#n>=this.#e){this.#a();return}if(this.#o?.(this.#n++),this.#n>=this.#e){this.#a();return}this.#u()}};#u(){if(!this.#t){if(this.#i?.aborted){this.#a();return}this.#r=new B(this.#s),this.#r.resume(this.#f)}}pause(){this.#t||this.#r?.pause()}resume(){if(!this.#t){if(this.#i?.aborted){this.#a();return}if(this.#n>=this.#e){this.#a();return}if(this.#r){this.#r.isPaused?this.#r.resume(this.#f):this.#r.isRunning||this.#u();return}this.#u()}}cancel(){this.#t||this.#a()}reset(r=!1){if(this.#r?.cancel(),this.#r=null,this.#n=0,this.#t=!1,this.#i?.aborted){this.#t=!0,this.#l(),this.#l=()=>{},this.#i=null;return}if(r){if(!(this.#e>0)&&this.#e!==1/0){this.#t=!0,this.#l(),this.#l=()=>{},this.#i=null;return}this.#u()}}};function j(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,void 0);return new Y(s,i,l)}function ht({signal:e}={}){let r=[],n=new Map,i=0,s=!1,l=!1,a=!1,u=!1,o=!1,f=1/0,d=0,w=null,p=null,h=null,y=[],m=!1,x=null,b=null,c,g=N(e,()=>c.cancel()),R=t=>{t&&t.controller&&(t.controller=null)},F=()=>{let t=r[i];t?.controller?.cancel?.(),t&&(t.controller=null)},E=()=>{u||a||(s=!1,l=!1,u=!0,F(),g.remove(),w?.())},I=()=>{a||(s=!1,l=!1,u=!1,a=!0,F(),g.remove())},T=(t,A)=>{if(I(),p){try{p(t,{step:A,index:i})}catch{}return}throw t},D=(t,A)=>{try{return t()}catch(v){T(v,A);return}},C=t=>{R(t),i+=1,queueMicrotask(M)};function M(){if(a||l||u)return;if(e?.aborted){I();return}if(h){let A=n.get(h);if(typeof A=="number")i=A;else{D(()=>{throw new Error(`Label "${h}" not found`)},r[i]);return}h=null}if(y.length>0){let A=y.shift();D(A,r[i])||(m=!0)}if(m){let A=r[i];if(!A||A.type==="label")m=!1;else return C(A)}let t=r[i];if(!t||i>=r.length){o&&++d<f?(i=0,M()):E();return}if(t.type==="label")return C(t);if(t.type==="after"){t.controller=Z(()=>D(t.fn,t),t.duration,{signal:e,onFinish:()=>C(t)});return}if(t.type==="every"){if(!(t.times>0)&&t.times!==1/0)return C(t);let A=0,v=j(()=>{if(!(l||a||u)){if(e?.aborted){I();return}if(t.whileCondition&&!D(t.whileCondition,t)||(D(()=>t.fn(A++),t),t.doWhileCondition&&!D(t.doWhileCondition,t))||A>=t.times)return v.cancel(),C(t)}},t.duration,{max:t.times,signal:e});t.controller=v}}return c={after(t,A){return r.push({type:"after",duration:t,fn:A,controller:null}),c},every(t,A,v=1/0){let q=typeof v=="number"?v:v?.max??1/0,W=q===1/0?1/0:Math.max(0,q|0);return r.push({type:"every",duration:t,fn:A,times:W,whileCondition:x,doWhileCondition:b,controller:null}),x=null,b=null,c},loop(t=!0){return o=!0,f=t===!0?1/0:t,c},onFinish(t){return w=t,c},onError(t){return p=t,c},start(){return F(),a=!1,u=!1,l=!1,s=!0,i=0,d=0,g.reset(),e?.aborted||g.add(),e?.aborted?(I(),c):(M(),c)},pause(){l||a||u||(l=!0,r[i]?.controller?.pause?.())},resume(){if(!(!l||a||u)){if(e?.aborted){I();return}l=!1,r[i]?.controller?.resume?.()}},cancel(){I()},reset(){return I(),r.length=0,n.clear(),i=0,d=0,w=null,p=null,h=null,y=[],m=!1,x=null,b=null,s=!1,l=!1,a=!1,u=!1,c},label(t){return n.set(t,r.length),r.push({type:"label",name:t,controller:null}),c},jumpTo(t){return h=t,c},if(t){return y.push(()=>typeof t=="function"?!!t():!!t),c},unless(t){return y.push(()=>typeof t=="function"?!t():!t),c},while(t){return x=()=>typeof t=="function"?!!t():!!t,c},doWhile(t){return b=()=>typeof t=="function"?!!t():!!t,c},get isRunning(){return s&&!l&&!a&&!u},get isPaused(){return l},get isCancelled(){return a},get isFinished(){return u}},c}function mt(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,void 0),a=l?.signal,u=l?.trailing??!0,o=Math.max(0,s),f=-1/0,d=0,w=null,p=null,h=N(a,()=>m()),y=()=>{if(!w)return;let c=w,g=p;w=null,p=null,h.remove(),i.apply(g,c)},m=()=>{d&&clearTimeout(d),d=0,w=null,p=null,h.remove()},x=c=>{h.add(),d=setTimeout(()=>{d=0,f=k(),y()},c)},b=function(...c){if(a?.aborted)return;let g=k(),R=g-f;if(w=c,p=this,R>=o){f=g,d&&(clearTimeout(d),d=0,h.remove()),y();return}if(u&&!d){let F=Math.max(0,o-R);x(F)}};return b.cancel=m,b.flush=()=>{d&&(clearTimeout(d),d=0,f=k(),y())},a?.aborted&&m(),b}function pt(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,0),a=l?.signal,u=Math.max(0,s),o=0,f=null,d=null,w=N(a,()=>h()),p=()=>{if(!f)return;let m=f,x=d;f=null,d=null,w.remove(),i.apply(x,m)},h=()=>{o&&clearTimeout(o),o=0,f=null,d=null,w.remove()},y=function(...m){a?.aborted||(f=m,d=this,o&&clearTimeout(o),w.add(),o=setTimeout(()=>{o=0,p()},u))};return y.cancel=h,y.flush=()=>{o&&(clearTimeout(o),o=0,p())},a?.aborted&&h(),y}var dt=2147483647;function S(e){if(e==null)return 0;let r=typeof e=="number"?e:P(e);return r>0?Math.min(r,dt):0}function tt(e=0,{signal:r}={}){return new Promise((n,i)=>{let s=S(e);if(r?.aborted){i($(r));return}let l=L(r,()=>{clearTimeout(a),i($(r))}),a=setTimeout(()=>{l(),n()},s)})}function yt(e,{interval:r="250ms",timeout:n,immediate:i=!1,signal:s}={}){return new Promise((l,a)=>{if(s?.aborted){a($(s));return}let u=S(r),o=n!=null?S(n):null,f=!1,d=!1,w=0,p=0,h=(x,b)=>{f||(f=!0,clearTimeout(w),clearTimeout(p),y(),x(b))},y=L(s,()=>h(a,$(s))),m=async()=>{let x;d=!0;try{x=await e()}catch(b){h(a,b);return}finally{d=!1}f||(x?h(l,x):w=setTimeout(m,u))};i?m():w=setTimeout(m,u),o!=null&&(p=setTimeout(()=>{if(!d){let b;try{b=e()}catch(c){h(a,c);return}if(b&&typeof b.then!="function"){h(l,b);return}}let x=new Error("waitFor timed out");x.name="TimeoutError",h(a,x)},o))})}async function bt(e,{attempts:r=3,delay:n="500ms",backoff:i=!1,factor:s=2,maxDelay:l,jitter:a=!1,delayFirst:u=!1,timeout:o,signal:f,isSuccess:d,shouldRetry:w,onAttempt:p,onRetry:h,sleep:y=tt,now:m=k,random:x=Math.random}={}){if(typeof e!="function")throw new TypeError("retry: fn must be a function");let b=r===1/0?1/0:Math.max(1,r|0),c=()=>{if(f?.aborted)throw $(f)};if(c(),typeof a=="number"&&!(a>=0&&a<=1))throw new RangeError(`retry: numeric jitter must be within [0, 1], got: ${a}`);let g=P(n),R=l!=null?P(l):1/0,F=o!=null?P(o):1/0,E=i===!0?"exponential":i||"fixed",I=m(),T=()=>m()-I,D=async M=>{await y(M,{signal:f}),c()};u&&await D(S(u===!0?g:u));let C=Math.min(g,R);for(let M=0;;M++){c(),p&&await p(M,T());let t;try{let q=await e(M);if(!d||await d(q,M))return q;t=new et(q,M+1)}catch(q){t=q}if(M+1>=b||w&&!await w(t,M))throw t;let A=E==="exponential"?Math.pow(s,M):E==="linear"?M+1:1,v=S(Math.round(wt({expDelay:g*A,baseDelay:g,maxDelayMs:R,jitter:a,random:x,prevSleep:C})));if(C=v,T()+v>F)throw t;h&&await h(t,M,v),await D(v)}}var et=class extends Error{constructor(r,n){super(`retry: unsuccessful result after ${n} attempt(s)`),this.name="RetryError",this.result=r,this.attempts=n}};function wt({expDelay:e,baseDelay:r,maxDelayMs:n,jitter:i,random:s,prevSleep:l}){let a=Math.min(e,n);if(!i)return a;if(typeof i=="number"){let o=z(-1,1,s)*i;return Math.min(n,Math.max(0,a*(1+o)))}let u=i===!0?"full":i;if(u==="full")return Math.min(n,z(0,a,s));if(u==="equal"){let o=a/2;return Math.min(n,o+z(0,o,s))}if(u==="decorrelated"){let o=z(r,l*3,s);return Math.min(n,o)}return a}function z(e,r,n){let i=n(),s=Number.isFinite(i)?Math.min(1,Math.max(0,i)):0;return e+(r-e)*s}function nt(e,r,n,i){let s=typeof n=="function"?n:void 0,l=s?i:n,{fn:a,delay:u,options:o}=_(e,r,l,void 0),{signal:f,onFinish:d}=s?{...o,onFinish:s}:o,w=Math.max(0,u),p=0,h=w,y=null,m=!1,x=!1,b=!1,c=()=>{p&&cancelAnimationFrame(p),p=0},g=()=>{},R=()=>{g(),g=()=>{}},F=()=>{c(),m=!1,x=!1,b=!0,y=null,h=0,R()},E=()=>{F(),a?.(),d?.()},I=()=>{b||F()},T=()=>{if(R(),f?.aborted){b=!0,h=0;return}g=L(f,I)};T();let D=A=>{if(!m||b)return;if(y==null&&(y=A),A-y>=h){E();return}p=requestAnimationFrame(D)},C=()=>{if(!m||b)return;c();let A=k();if(y!=null){let v=A-y;h=Math.max(0,h-v)}y=null,m=!1,x=!0},M=()=>{if(!(b||m||!x)&&!f?.aborted){if(!(h>0)){E();return}x=!1,m=!0,y=null,p=requestAnimationFrame(D)}},t=()=>{c(),y=null,h=w,m=!1,x=!1,b=!1,T()};return b?R():h>0?(m=!0,p=requestAnimationFrame(D)):E(),{pause:C,resume:M,cancel:I,reset:t,get isRunning(){return m},get isPaused(){return x},get isFinished(){return b}}}var G=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function it(e,r,n,i,s){let l=typeof e!="function",a,u,o;l?(G(n)?o=n:G(i)?o=i:G(s)?o=s:o={},typeof n=="number"&&(a=n),typeof i=="boolean"&&(u=i),u==null&&typeof n=="boolean"&&(u=n)):o=G(n)?n:{};let{fn:f,delay:d,options:w}=_(e,r,o,void 0),p=w?.signal,h=w?.max??1/0,y=w?.runImmediately??!1,m=a??h,x=u??y,b=Math.max(0,d),c=0,g=0,R=b,F=null,E=!1,I=!1,T=!1,D=()=>{c&&cancelAnimationFrame(c),c=0},C=()=>{},M=()=>{C(),C=()=>{}},t=()=>{D(),E=!1,I=!1,T=!0,F=null,R=0,M()},A=()=>{T||t()},v=()=>{if(M(),p?.aborted){T=!0,R=0;return}C=L(p,A)};v();let q=()=>g<m,W=()=>(f?.(g++),q()?!0:(t(),!1)),H=O=>{if(!E||T)return;if(p?.aborted){t();return}if(!q()){t();return}F==null&&(F=O);let K=O-F;F=O,R-=K;let rt=Math.max(0,b);if(rt===0){R=0,W(),c=requestAnimationFrame(H);return}for(;R<=0&&!T;){if(!W())return;R+=rt}c=requestAnimationFrame(H)},J=()=>{if(!T){if(p?.aborted){t();return}if(!q()){t();return}E=!0,I=!1,F=null,c=requestAnimationFrame(H)}},ut=()=>{if(!E||T)return;D();let O=k();if(F!=null){let K=O-F;R=Math.max(0,R-K)}F=null,E=!1,I=!0},ft=()=>{if(!(T||E||!I)&&!p?.aborted){if(!q()){t();return}J()}},ct=(O=!1)=>{if(D(),g=0,R=b,F=null,E=!1,I=!1,T=!1,v(),!T){if(!(m>0)&&m!==1/0){t();return}if(O){if(x&&q()&&(W(),T))return;J()}}};return T?M():!(m>0)&&m!==1/0?t():(x&&q()&&W(),T||(R=Math.max(0,b),J())),{pause:ut,resume:ft,cancel:A,reset:ct,get isRunning(){return E},get isPaused(){return I},get isFinished(){return T},get count(){return g}}}function ot(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,0),a=Math.max(0,s),u=l?.signal,o=0,f=null,d=null,w=0,p=()=>{o&&cancelAnimationFrame(o),o=0},h=N(u,()=>y()),y=()=>{p(),f=null,d=null,w=0,h.remove()},m=()=>{if(!f)return;let c=f,g=d;f=null,d=null,h.remove(),i.apply(g,c)},x=c=>{if(!o)return;if(!f){y();return}if(c-w>=a){p(),m();return}o=requestAnimationFrame(x)},b=function(...c){u?.aborted||(f=c,d=this,w=k(),h.add(),p(),o=requestAnimationFrame(x))};return b.cancel=y,b.flush=()=>{!o||!f||(p(),m())},u?.aborted&&y(),b}var st=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function lt(e,r=0,n){if(typeof e!="function")throw new TypeError(`Expected a function, got: ${typeof e}`);let i=typeof r=="number"?r:0,s=st(r)?r:st(n)?n:{},l=s.signal,a=s.trailing??!0,u=Math.max(0,i|0),o=!1,f=0,d=null,w=null,p=u,h=N(l,()=>m()),y=()=>{o=!1,f&&cancelAnimationFrame(f),f=0,p=u,d=null,w=null,h.remove()},m=()=>{y()},x=()=>{if(!d)return;let E=d,I=w;d=null,w=null,h.remove(),e.apply(I,E)},b=()=>{o=!1,f=0,p=u,x()},c=()=>{if(o){if(l?.aborted){m();return}if(p===0){b();return}p-=1,f=requestAnimationFrame(c)}},g=()=>{if(o){if(l?.aborted){m();return}b()}},R=u===0?()=>{o=!0,h.add(),f=requestAnimationFrame(g)}:()=>{o=!0,p=u,h.add(),f=requestAnimationFrame(c)},F=function(...E){l?.aborted||((!o||a)&&(d=E,w=this),!o&&R())};return F.cancel=m,F.flush=()=>{if(o){if(l?.aborted){m();return}o=!1,f&&cancelAnimationFrame(f),f=0,p=u,x()}},l?.aborted&&m(),F}function at(e,{timeout:r,signal:n,immediate:i=!1}={}){return new Promise((s,l)=>{if(typeof e!="function"){l(new TypeError(`waitForRaf: condition must be a function, got: ${typeof e}`));return}if(n?.aborted){l($(n));return}let a=r!=null?Math.max(0,P(r)):null,u=0,o=null,f=()=>{u&&cancelAnimationFrame(u),u=0,w()},w=L(n,()=>{f(),l($(n))}),p=()=>{try{return!!e()}catch(y){return f(),l(y),null}};if(i){let y=p();if(y===null)return;if(y){f(),s();return}if(a===0){f(),l(new Error("waitForRaf timed out"));return}}let h=y=>{o==null&&(o=y);let m=p();if(m!==null){if(m){f(),s();return}if(a!=null&&y-o>=a){f(),l(new Error("waitForRaf timed out"));return}u=requestAnimationFrame(h)}};u=requestAnimationFrame(h)})}function xt(){if(typeof requestAnimationFrame!="function")throw new Error("requestAnimationFrame is not available in this environment. Use the non-RAF timers (after/every/waitFor) in Node, or provide a RAF polyfill.")}var U=e=>(...r)=>(xt(),e(...r)),At=U(nt),gt=U(it),Ft=U(ot),Rt=U(lt),vt=U(at);export{Z as after,At as afterRaf,pt as debounce,Ft as debounceRaf,j as every,gt as everyRaf,ht as flow,P as parseDuration,bt as retry,tt as sleep,mt as throttle,Rt as throttleRaf,yt as waitFor,vt as waitForRaf};