timeout-flow 0.0.20 → 0.1.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.
package/src/context.txt DELETED
@@ -1,2709 +0,0 @@
1
- ===== Context dump for folder: C:\Users\PC User\GitHub\TimeoutFlow-js\src =====
2
- Extension: .js
3
- Generated on: 26/02/23 13:56:31.70
4
-
5
-
6
- ===== FILE: abort.js =====
7
-
8
- // ./src/abort.js
9
-
10
-
11
-
12
-
13
- /**
14
- * Standardized AbortError factory.
15
- * Works in browsers and Node runtimes that may not have DOMException.
16
- *
17
- * We resolve the best implementation once at module load time.
18
- * This avoids feature detection in the hot path.
19
- */
20
-
21
- let createAbortError;
22
-
23
- // Prefer native DOMException when available (browser + modern Node).
24
- if (typeof DOMException !== 'undefined') {
25
- createAbortError = (message = 'Aborted') =>
26
- new DOMException(message, 'AbortError');
27
- } else {
28
- // Fallback for runtimes without DOMException.
29
- createAbortError = (message = 'Aborted') => {
30
- const err = new Error(message);
31
- err.name = 'AbortError';
32
- return err;
33
- };
34
- }
35
-
36
- export { createAbortError };
37
- /**
38
- * Attach an AbortSignal listener and return a cleanup function.
39
- * - If `signal` is missing, returns a no-op cleanup.
40
- * - If already aborted, calls `onAbort()` immediately and returns a no-op cleanup.
41
- *
42
- * @param {AbortSignal | null | undefined} signal
43
- * @param {() => void} onAbort
44
- * @returns {() => void} cleanup
45
- */
46
- export function attachAbort(signal, onAbort) {
47
- if (!signal) return () => { };
48
- if (signal.aborted) {
49
- onAbort();
50
- return () => { };
51
- }
52
- signal.addEventListener('abort', onAbort, { once: true });
53
- return () => signal.removeEventListener('abort', onAbort);
54
- }
55
-
56
- /**
57
- * Manage AbortSignal listener lifecycle for "pending work" cases.
58
- * Call `add()` when work becomes pending and `remove()` when it’s resolved/canceled.
59
- *
60
- * @param {AbortSignal | null | undefined} signal
61
- * @param {() => void} onAbort
62
- * @returns {{ add: () => void, remove: () => void, reset: () => void }}
63
- */
64
- export function pendingAbort(signal, onAbort) {
65
- let cleanup = null;
66
-
67
- return {
68
- add() {
69
- if (cleanup) return;
70
- cleanup = attachAbort(signal, onAbort);
71
- },
72
- remove() {
73
- if (!cleanup) return;
74
- cleanup();
75
- cleanup = null;
76
- },
77
- reset() {
78
- if (cleanup) cleanup();
79
- cleanup = null;
80
- },
81
- };
82
- }
83
- ===== END FILE: abort.js =====
84
-
85
-
86
- ===== FILE: after.js =====
87
-
88
- // ./src/after.js
89
- import { AfterTimer } from './AfterTimer.js';
90
- import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
91
-
92
- /**
93
- * Schedules a one-time delayed function.
94
- *
95
- * Preferred:
96
- * - after(fn, duration, [options])
97
- *
98
- * Also supported (legacy/alt):
99
- * - after(duration, fn, [options])
100
- *
101
- * @param {Function|string|number} a - Function or duration (see overloads)
102
- * @param {Function|string|number|Object} b - Duration, function, or options
103
- * @param {Object} [c] - Options
104
- * @param {Function} [c.onFinish] - Optional callback after `fn` runs
105
- * @param {AbortSignal} [c.signal] - Optional AbortSignal to auto-cancel
106
- * @returns {{
107
- * pause(): void,
108
- * resume(): void,
109
- * cancel(): void,
110
- * reset(): void,
111
- * readonly isRunning: boolean,
112
- * readonly isPaused: boolean,
113
- * readonly isFinished: boolean
114
- * }}
115
- */
116
- export function after(a, b, c) {
117
- // require explicit duration: defaultDelay = undefined
118
- const { fn, delay, options } = resolveDelayFnOptions(a, b, c, undefined);
119
- return new AfterTimer(delay, fn, options);
120
- }
121
- ===== END FILE: after.js =====
122
-
123
-
124
- ===== FILE: AfterTimer.js =====
125
-
126
- // ./src/AfterTimer.js
127
- import { TimerBase } from './TimerBase.js';
128
- import { attachAbort } from './abort.js';
129
-
130
- /**
131
- * Executes a function once after a delay.
132
- */
133
- export class AfterTimer extends TimerBase {
134
- /** @type {AbortSignal | null} */
135
- #signal = null;
136
-
137
- /** @type {(() => void) | null} */
138
- #onAbort = null;
139
-
140
- /** @type {() => void} */
141
- #cleanupAbort = () => { };
142
-
143
- /**
144
- * @param {string|number} duration - Delay before firing (e.g., '1s', 300)
145
- * @param {Function} fn - Main function to execute
146
- * @param {Object} [options]
147
- * @param {Function} [options.onFinish] - Optional callback when done
148
- * @param {AbortSignal} [options.signal] - Optional AbortSignal to auto-cancel
149
- */
150
- constructor(duration, fn, { onFinish, signal } = {}) {
151
- super(duration);
152
-
153
- this.#signal = signal ?? null;
154
- this.#onAbort = () => this.cancel();
155
-
156
- this.#attachAbort();
157
-
158
- // If already aborted, #attachAbort() will have canceled us.
159
- if (this.isFinished) return;
160
-
161
- this.resume(() => {
162
- this.#cleanupAbortListener();
163
- fn?.();
164
- onFinish?.();
165
- });
166
- }
167
-
168
- #attachAbort() {
169
- if (!this.#signal || !this.#onAbort) return;
170
-
171
- // If already aborted, terminate immediately.
172
- if (this.#signal.aborted) {
173
- super.cancel();
174
- this.#cleanupAbortListener();
175
- return;
176
- }
177
-
178
- this.#cleanupAbort = attachAbort(this.#signal, this.#onAbort);
179
- }
180
-
181
- #cleanupAbortListener() {
182
- this.#cleanupAbort();
183
- this.#cleanupAbort = () => { };
184
-
185
- // Keep signal reference so reset() can reattach.
186
- this.#onAbort = null;
187
- }
188
-
189
- cancel() {
190
- if (this.isFinished) return;
191
-
192
- // Remove listener first to avoid keeping instance alive.
193
- this.#cleanupAbortListener();
194
-
195
- super.cancel();
196
- }
197
-
198
- reset() {
199
- // Preserve AbortSignal semantics.
200
- this.#cleanupAbort();
201
- this.#cleanupAbort = () => { };
202
- this.#onAbort = () => this.cancel();
203
-
204
- super.reset();
205
- this.#attachAbort();
206
- }
207
- }
208
- ===== END FILE: AfterTimer.js =====
209
-
210
-
211
- ===== FILE: debounce.js =====
212
-
213
- // ./src/debounce.js
214
-
215
- import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
216
- import { pendingAbort } from './abort.js';
217
-
218
- /**
219
- * @typedef {((...args: any[]) => void) & {
220
- * cancel: () => void,
221
- * flush: () => void
222
- * }} DebouncedFunction
223
- */
224
-
225
- /**
226
- * Creates a debounced function that delays invoking `fn`
227
- * until after `delay` ms of inactivity.
228
- *
229
- * Preferred:
230
- * - debounce(fn, [delay], [options]) // delay defaults to 0
231
- *
232
- * Also supported:
233
- * - debounce(delay, fn, [options]) // legacy/alt ordering
234
- * - debounce(fn, [options])
235
- *
236
- * Notes:
237
- * - Always invokes with the latest arguments/context.
238
- * - `.cancel()` clears any pending invocation.
239
- * - `.flush()` immediately invokes if pending.
240
- * - Optional AbortSignal: abort cancels pending invocation.
241
- *
242
- * @param {Function|string|number} a - Function or delay (see overloads)
243
- * @param {Function|string|number|Object} [b] - Delay, function, or options
244
- * @param {Object} [c] - Options (3-arg form)
245
- * @param {AbortSignal} [c.signal] - Optional AbortSignal to cancel pending work
246
- * @returns {DebouncedFunction}
247
- */
248
- export function debounce(a, b, c) {
249
- const { fn, delay, options } = resolveDelayFnOptions(a, b, c, 0);
250
- const signal = options?.signal;
251
-
252
- const wait = Math.max(0, delay);
253
-
254
- let timeoutId = 0;
255
-
256
- /** @type {any[] | null} */
257
- let lastArgs = null;
258
- /** @type {any | null} */
259
- let lastThis = null;
260
-
261
- const abort = pendingAbort(signal, () => cancel());
262
-
263
- const invoke = () => {
264
- if (!lastArgs) return;
265
-
266
- const args = lastArgs;
267
- const ctx = lastThis;
268
-
269
- // clear first (re-entrancy safe + GC friendly)
270
- lastArgs = null;
271
- lastThis = null;
272
-
273
- abort.remove();
274
- fn.apply(ctx, args);
275
- };
276
-
277
- const cancel = () => {
278
- if (timeoutId) clearTimeout(timeoutId);
279
- timeoutId = 0;
280
-
281
- lastArgs = null;
282
- lastThis = null;
283
-
284
- abort.remove();
285
- };
286
-
287
- /** @type {any} */
288
- const debounced = function (...args) {
289
- if (signal?.aborted) return;
290
-
291
- lastArgs = args;
292
- lastThis = this;
293
-
294
- if (timeoutId) clearTimeout(timeoutId);
295
-
296
- // Listener should exist only while a call is pending
297
- abort.add();
298
-
299
- timeoutId = setTimeout(() => {
300
- timeoutId = 0;
301
- invoke();
302
- }, wait);
303
- };
304
-
305
- debounced.cancel = cancel;
306
-
307
- debounced.flush = () => {
308
- if (!timeoutId) return;
309
- clearTimeout(timeoutId);
310
- timeoutId = 0;
311
- invoke();
312
- };
313
-
314
- // If already aborted at creation time, ensure clean slate.
315
- if (signal?.aborted) cancel();
316
-
317
- return debounced;
318
- }
319
- ===== END FILE: debounce.js =====
320
-
321
-
322
- ===== FILE: every.js =====
323
-
324
- // ./src/every.js
325
- import { EveryTimer } from './EveryTimer.js';
326
- import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
327
-
328
- /**
329
- * Runs a function every N ms with optional execution limit.
330
- *
331
- * Preferred:
332
- * - every(fn, duration, [options])
333
- *
334
- * Also supported (legacy/alt):
335
- * - every(duration, fn, [options])
336
- *
337
- * @param {Function|string|number} a - Function or duration (see overloads)
338
- * @param {Function|string|number|Object} b - Duration, function, or options
339
- * @param {Object} [c] - Options
340
- * @param {number} [c.max=Infinity] - Max times to run
341
- * @param {boolean} [c.runImmediately=false] - Run immediately on first tick
342
- * @param {AbortSignal} [c.signal] - Optional AbortSignal to auto-cancel
343
- * @returns {{
344
- * pause(): void,
345
- * resume(): void,
346
- * cancel(): void,
347
- * reset(restart?: boolean): void,
348
- * readonly isRunning: boolean,
349
- * readonly isPaused: boolean,
350
- * readonly isFinished: boolean,
351
- * readonly count: number
352
- * }}
353
- */
354
- export function every(a, b, c) {
355
- // require explicit duration: defaultDelay = undefined
356
- const { fn, delay, options } = resolveDelayFnOptions(a, b, c, undefined);
357
- return new EveryTimer(delay, fn, options);
358
- }
359
- ===== END FILE: every.js =====
360
-
361
-
362
- ===== FILE: EveryTimer.js =====
363
-
364
- // ./src/EveryTimer.js
365
- import { attachAbort } from './abort.js';
366
- import { TimerBase } from './TimerBase.js';
367
- import { parseDuration } from './parseDuration.js';
368
-
369
- /**
370
- * Repeatedly runs a function every N ms, with optional max count.
371
- */
372
- export class EveryTimer {
373
- #interval;
374
- #fn;
375
- #max;
376
-
377
- #count = 0;
378
- #finished = false;
379
-
380
- /** @type {TimerBase | null} */
381
- #controller = null;
382
-
383
- /** @type {AbortSignal | null} */
384
- #signal = null;
385
-
386
- /** @type {() => void} */
387
- #cleanupAbort = () => {};
388
-
389
- /**
390
- * @param {string|number} duration - Delay between calls (e.g., '1s', 200)
391
- * @param {Function} fn - Function to call each tick
392
- * @param {Object} [options]
393
- * @param {number} [options.max=Infinity] - Max executions
394
- * @param {boolean} [options.runImmediately=false] - Run `fn` once before first delay
395
- * @param {AbortSignal} [options.signal] - Optional AbortSignal to auto-cancel
396
- */
397
- constructor(duration, fn, { max = Infinity, runImmediately = false, signal } = {}) {
398
- this.#interval = parseDuration(duration);
399
- this.#fn = fn;
400
- this.#max = max;
401
-
402
- this.#signal = signal ?? null;
403
-
404
- // If max is already satisfied, finish immediately.
405
- if (!(this.#max > 0) && this.#max !== Infinity) {
406
- this.#finished = true;
407
- this.#cleanupAbort();
408
- return;
409
- }
410
-
411
- // Abort semantics: if already aborted, immediately finish (terminal).
412
- if (this.#signal?.aborted) {
413
- this.#finished = true;
414
- this.#cleanupAbort();
415
- return;
416
- }
417
-
418
- // Attach abort listener for the lifetime of this timer.
419
- // (Cleanup happens in #finish().)
420
- this.#cleanupAbort = attachAbort(this.#signal, () => this.cancel());
421
-
422
- if (runImmediately) {
423
- this.#tick();
424
- } else {
425
- this.#schedule();
426
- }
427
- }
428
-
429
- /**
430
- * Number of times `fn` has been executed.
431
- */
432
- get count() {
433
- return this.#count;
434
- }
435
-
436
- /**
437
- * Whether the timer is actively running (waiting for next tick).
438
- *
439
- * Note: during the brief moment between a tick firing and the next schedule,
440
- * this may be false — which reflects "no countdown currently pending".
441
- */
442
- get isRunning() {
443
- return !this.#finished && !!this.#controller && this.#controller.isRunning;
444
- }
445
-
446
- /**
447
- * Whether the timer is paused (resumable).
448
- */
449
- get isPaused() {
450
- return !this.#finished && !!this.#controller && this.#controller.isPaused;
451
- }
452
-
453
- /**
454
- * Whether the timer has finished (hit max) or been canceled (terminal).
455
- */
456
- get isFinished() {
457
- return this.#finished;
458
- }
459
-
460
- #finish = () => {
461
- this.#controller?.cancel();
462
- this.#controller = null;
463
-
464
- this.#finished = true;
465
-
466
- this.#cleanupAbort();
467
- this.#cleanupAbort = () => {};
468
- this.#signal = null;
469
- };
470
-
471
- #tick = () => {
472
- if (this.#finished) return;
473
-
474
- if (this.#signal?.aborted) {
475
- this.#finish();
476
- return;
477
- }
478
-
479
- if (this.#count >= this.#max) {
480
- this.#finish();
481
- return;
482
- }
483
-
484
- this.#fn?.(this.#count++);
485
- if (this.#count >= this.#max) {
486
- this.#finish();
487
- return;
488
- }
489
-
490
- this.#schedule();
491
- };
492
-
493
- #schedule() {
494
- if (this.#finished) return;
495
-
496
- if (this.#signal?.aborted) {
497
- this.#finish();
498
- return;
499
- }
500
-
501
- // Fresh controller per interval window
502
- this.#controller = new TimerBase(this.#interval);
503
- this.#controller.resume(this.#tick);
504
- }
505
-
506
- pause() {
507
- if (this.#finished) return;
508
- this.#controller?.pause();
509
- }
510
-
511
- resume() {
512
- if (this.#finished) return;
513
-
514
- if (this.#signal?.aborted) {
515
- this.#finish();
516
- return;
517
- }
518
-
519
- if (this.#count >= this.#max) {
520
- this.#finish();
521
- return;
522
- }
523
-
524
- // Resume existing countdown if paused, otherwise schedule fresh.
525
- if (this.#controller) {
526
- if (this.#controller.isPaused) {
527
- this.#controller.resume(this.#tick);
528
- } else if (!this.#controller.isRunning) {
529
- // Controller exists but isn't active (edge); schedule next window
530
- this.#schedule();
531
- }
532
- return;
533
- }
534
-
535
- this.#schedule();
536
- }
537
-
538
- cancel() {
539
- if (this.#finished) return;
540
- this.#finish();
541
- }
542
-
543
- reset(restart = false) {
544
- // Reset is not terminal; keep signal semantics:
545
- // - If signal exists and is aborted, reset should leave the timer finished.
546
- this.#controller?.cancel();
547
- this.#controller = null;
548
-
549
- this.#count = 0;
550
- this.#finished = false;
551
-
552
- if (this.#signal?.aborted) {
553
- this.#finished = true;
554
- this.#cleanupAbort();
555
- this.#cleanupAbort = () => {};
556
- this.#signal = null;
557
- return;
558
- }
559
-
560
- if (restart) {
561
- // If max is zero-ish, immediately finish (consistent with constructor)
562
- if (!(this.#max > 0) && this.#max !== Infinity) {
563
- this.#finished = true;
564
- this.#cleanupAbort();
565
- this.#cleanupAbort = () => {};
566
- this.#signal = null;
567
- return;
568
- }
569
- this.#schedule();
570
- }
571
- }
572
- }
573
- ===== END FILE: EveryTimer.js =====
574
-
575
-
576
- ===== FILE: index.js =====
577
-
578
- // ./src/index.js
579
-
580
- export { parseDuration } from './parseDuration.js';
581
-
582
- export { flow } from './TimeoutFlow.js';
583
-
584
- export { throttle } from './throttle.js';
585
- export { debounce } from './debounce.js';
586
-
587
- export { after } from './after.js';
588
- export { every } from './every.js';
589
-
590
-
591
- export { waitFor } from './waitFor.js';
592
- export { retry } from './retry.js';
593
-
594
-
595
- export {
596
- afterRaf,
597
- everyRaf,
598
- debounceRaf,
599
- throttleRaf,
600
- waitForRaf
601
- } from './raf/index.js';
602
- ===== END FILE: index.js =====
603
-
604
-
605
- ===== FILE: now.js =====
606
-
607
- // ./src/now.js
608
-
609
- // We resolve the best available clock implementation *once* at module load time.
610
- // This avoids doing feature detection on every call to `now()`,
611
- // keeping the hot path branch-free and fast.
612
-
613
- let now;
614
-
615
- // Prefer high-resolution, monotonic clock when available.
616
- // - Browsers: performance.now()
617
- // - Modern Node: performance.now()
618
- // This is ideal for measuring elapsed time.
619
- if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
620
- now = () => performance.now();
621
- } else {
622
- // Fallback for older Node or minimal runtimes.
623
- // Date.now() is not monotonic, but ensures compatibility.
624
- now = () => Date.now();
625
- }
626
-
627
- // Export the resolved implementation.
628
- // Consumers simply call `now()` without worrying about environment differences.
629
- export { now };
630
- ===== END FILE: now.js =====
631
-
632
-
633
- ===== FILE: parseDuration.js =====
634
-
635
- // ./src/parseDuration.js
636
-
637
-
638
- /**
639
- * Parses a duration string like "2s", "1.5m", "500ms" into milliseconds.
640
- * Also accepts raw number values (treated as ms).
641
- * @param {string|number} input
642
- * @returns {number}
643
- */
644
- export function parseDuration(input) {
645
- if (typeof input === 'number') {
646
- if (!Number.isFinite(input)) {
647
- throw new TypeError(`Expected a finite number of ms, got: ${input}`);
648
- }
649
- return input;
650
- }
651
-
652
- if (typeof input !== 'string') {
653
- throw new TypeError(`Expected a duration string or number, got ${typeof input}`);
654
- }
655
-
656
- const str = input.toLowerCase().trim();
657
- const match = str.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/);
658
-
659
- if (!match) {
660
- throw new Error(
661
- `Invalid duration format: "${input}". Expected formats like "500ms", "2s", "1.5m", or "1h".`
662
- );
663
- }
664
-
665
- const value = Number(match[1]);
666
- if (!Number.isFinite(value)) {
667
- throw new TypeError(`Invalid duration value: "${match[1]}"`);
668
- }
669
-
670
- const unit = match[2];
671
-
672
- switch (unit) {
673
- case 'ms': return value;
674
- case 's': return value * 1000;
675
- case 'm': return value * 60_000;
676
- case 'h': return value * 3_600_000;
677
- default:
678
- // Should be unreachable due to regex, but keeps function total.
679
- throw new Error(`Unsupported duration unit: "${unit}"`);
680
- }
681
- }
682
- ===== END FILE: parseDuration.js =====
683
-
684
-
685
- ===== FILE: resolveDelayAndFn.js =====
686
-
687
- // ./src/resolveDelayAndFn.js
688
- import { parseDuration } from './parseDuration.js';
689
-
690
- const isPlainOptions = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
691
-
692
- /**
693
- * Resolves flexible (fn, delay) or (delay, fn) inputs.
694
- *
695
- * NOTE: This helper is intentionally strict:
696
- * - It requires an explicit delay (2-arg form).
697
- * - Use `resolveDelayFnOptions()` for overloads that allow `(fn, options)` or default delays.
698
- *
699
- * @param {Function|string|number} a - function or duration
700
- * @param {Function|string|number} b - function or duration
701
- * @returns {{ fn: Function, delay: number }}
702
- */
703
- export function resolveDelayAndFn(a, b) {
704
- // Keep legacy semantics but delegate parsing/validation.
705
- const { fn, delay } = resolveDelayFnOptions(a, b, undefined, undefined);
706
-
707
- // If someone called resolveDelayAndFn(fn) by mistake, throw a clearer error.
708
- // (parseDuration(undefined) would be a confusing failure mode.)
709
- if (b == null && typeof a === 'function') {
710
- throw new TypeError('Expected a delay as the second argument (e.g. debounce(fn, "250ms"))');
711
- }
712
-
713
- return { fn, delay };
714
- }
715
-
716
- /**
717
- * Resolves flexible overloads and returns `{ fn, delay, options }`.
718
- *
719
- * Supported forms:
720
- * - (fn, delay, [options])
721
- * - (delay, fn, [options])
722
- * - (fn, [options]) // delay defaults
723
- *
724
- * This is intentionally strict about what counts as "options" to avoid
725
- * treating random values as configuration.
726
- *
727
- * @template {Record<string, any>} O
728
- * @param {Function|string|number} a
729
- * @param {Function|string|number|O} b
730
- * @param {O} [c]
731
- * @param {string|number} [defaultDelay=0]
732
- * @returns {{ fn: Function, delay: number, options: O }}
733
- */
734
- export function resolveDelayFnOptions(a, b, c, defaultDelay = 0) {
735
- /** @type {Function} */
736
- let fn;
737
-
738
- /** @type {string|number|undefined} */
739
- let delayRaw;
740
-
741
- /** @type {any} */
742
- let options;
743
-
744
- if (typeof a === 'function') {
745
- fn = a;
746
-
747
- if (isPlainOptions(b)) {
748
- // (fn, options)
749
- delayRaw = defaultDelay;
750
- options = b;
751
- } else {
752
- // (fn, delay, options?)
753
- delayRaw = /** @type {any} */ (b);
754
- options = isPlainOptions(c) ? c : {};
755
- }
756
- } else {
757
- // (delay, fn, options?)
758
- delayRaw = /** @type {any} */ (a);
759
- fn = /** @type {any} */ (b);
760
- options = isPlainOptions(c) ? c : {};
761
- }
762
-
763
- if (typeof fn !== 'function') {
764
- throw new TypeError(`Expected a function as one argument, got: ${typeof fn}`);
765
- }
766
-
767
- const raw = delayRaw ?? defaultDelay;
768
-
769
- // If someone passes `(fn, options)` but defaultDelay was undefined, surface a clear error.
770
- if (raw == null) {
771
- throw new TypeError('Expected a duration (string/number) for delay');
772
- }
773
-
774
- const delay = parseDuration(raw);
775
- return { fn, delay, options };
776
- }
777
- ===== END FILE: resolveDelayAndFn.js =====
778
-
779
-
780
- ===== FILE: retry.js =====
781
-
782
- // ./src/retry.js
783
- import { parseDuration } from './parseDuration.js';
784
- import { attachAbort, createAbortError } from './abort.js';
785
-
786
- /**
787
- * Retries a promise-returning function with delays.
788
- *
789
- * @param {(attemptIndex: number) => Promise<any>} fn - async function
790
- * @param {Object} [options]
791
- * @param {number} [options.attempts=3] - total attempts (including the first)
792
- * @param {string|number} [options.delay='500ms'] - base delay between retries
793
- * @param {boolean} [options.backoff=false] - exponential backoff if true
794
- * @param {number} [options.factor=2] - backoff multiplier (only if backoff=true)
795
- * @param {string|number} [options.maxDelay] - clamp delay to this max
796
- * @param {boolean|'full'|'equal'|'decorrelated'} [options.jitter=false] - jitter strategy
797
- * @param {AbortSignal} [options.signal] - optional AbortSignal to cancel retries
798
- * @param {() => number} [options.random=Math.random] - injectable RNG for tests
799
- * @param {(err: any, attempt: number) => boolean | Promise<boolean>} [options.shouldRetry]
800
- * Predicate deciding whether to retry after a failure.
801
- * @param {(err: any, attempt: number, delayMs: number) => void | Promise<void>} [options.onRetry]
802
- * Hook invoked after deciding to retry and before waiting.
803
- * @returns {Promise<any>}
804
- */
805
- export async function retry(
806
- fn,
807
- {
808
- attempts = 3,
809
- delay = '500ms',
810
- backoff = false,
811
- factor = 2,
812
- maxDelay,
813
- jitter = false,
814
- signal,
815
- random = Math.random,
816
- shouldRetry,
817
- onRetry,
818
- } = {}
819
- ) {
820
- if (typeof fn !== 'function') throw new TypeError('retry: fn must be a function');
821
-
822
- const totalAttempts = Math.max(1, attempts | 0);
823
-
824
- if (signal?.aborted) throw createAbortError();
825
-
826
- const baseDelay = parseDuration(delay);
827
- const maxDelayMs = maxDelay != null ? parseDuration(maxDelay) : Infinity;
828
-
829
- // decorrelated jitter needs to remember prior sleep
830
- let prevSleep = Math.min(baseDelay, maxDelayMs);
831
-
832
- for (let attempt = 0; attempt < totalAttempts; attempt++) {
833
- if (signal?.aborted) throw createAbortError();
834
-
835
- try {
836
- return await fn(attempt);
837
- } catch (err) {
838
- const lastAttempt = attempt === totalAttempts - 1;
839
- if (lastAttempt) throw err;
840
-
841
- // Decide if we should retry
842
- if (shouldRetry) {
843
- const ok = await shouldRetry(err, attempt);
844
- if (!ok) throw err;
845
- }
846
-
847
- const expDelay = backoff ? baseDelay * Math.pow(factor, attempt) : baseDelay;
848
-
849
- const sleep = computeSleep({
850
- expDelay,
851
- baseDelay,
852
- maxDelayMs,
853
- jitter,
854
- random,
855
- prevSleep,
856
- });
857
-
858
- prevSleep = sleep;
859
-
860
- // Notify caller we're retrying (before waiting)
861
- if (onRetry) {
862
- await onRetry(err, attempt, sleep);
863
- }
864
-
865
- await waitWithAbort(sleep, signal);
866
- }
867
- }
868
-
869
- // Unreachable, but keeps type checkers happy.
870
- // eslint-disable-next-line no-throw-literal
871
- throw new Error('retry: exhausted attempts unexpectedly');
872
- }
873
-
874
- /**
875
- * Compute retry sleep with optional backoff clamp + jitter.
876
- *
877
- * Jitter strategies:
878
- * - false: no jitter
879
- * - 'full': random(0, cap)
880
- * - 'equal': cap/2 + random(0, cap/2)
881
- * - 'decorrelated': random(baseDelay, prevSleep*3) (clamped)
882
- */
883
- function computeSleep({ expDelay, baseDelay, maxDelayMs, jitter, random, prevSleep }) {
884
- const cap = Math.min(expDelay, maxDelayMs);
885
-
886
- if (!jitter) return cap;
887
-
888
- const mode = jitter === true ? 'full' : jitter;
889
-
890
- if (mode === 'full') {
891
- return Math.min(maxDelayMs, randBetween(0, cap, random));
892
- }
893
-
894
- if (mode === 'equal') {
895
- const half = cap / 2;
896
- return Math.min(maxDelayMs, half + randBetween(0, half, random));
897
- }
898
-
899
- if (mode === 'decorrelated') {
900
- const next = randBetween(baseDelay, prevSleep * 3, random);
901
- return Math.min(maxDelayMs, next);
902
- }
903
-
904
- // Unknown mode -> treat as no jitter (safe fallback)
905
- return cap;
906
- }
907
-
908
- function randBetween(min, max, random) {
909
- const r = random();
910
- const t = Number.isFinite(r) ? Math.min(1, Math.max(0, r)) : 0;
911
- return min + (max - min) * t;
912
- }
913
-
914
- /**
915
- * Wait helper that supports AbortSignal.
916
- * Rejects with AbortError if aborted during delay.
917
- */
918
- function waitWithAbort(ms, signal) {
919
- return new Promise((resolve, reject) => {
920
- if (signal?.aborted) {
921
- reject(createAbortError());
922
- return;
923
- }
924
-
925
- let timeoutId = 0;
926
-
927
- const cleanup = () => {
928
- if (timeoutId) clearTimeout(timeoutId);
929
- timeoutId = 0;
930
- cleanupAbort();
931
- };
932
-
933
- const onAbort = () => {
934
- cleanup();
935
- reject(createAbortError());
936
- };
937
-
938
- const cleanupAbort = attachAbort(signal, onAbort);
939
-
940
- timeoutId = setTimeout(() => {
941
- cleanup();
942
- resolve();
943
- }, ms);
944
- });
945
- }
946
- ===== END FILE: retry.js =====
947
-
948
-
949
- ===== FILE: throttle.js =====
950
-
951
- // ./src/throttle.js
952
-
953
- import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
954
- import { pendingAbort } from './abort.js';
955
- import { now } from './now.js'
956
-
957
-
958
- /**
959
- * @typedef {((...args: any[]) => void) & {
960
- * cancel: () => void,
961
- * flush: () => void
962
- * }} ThrottledFunction
963
- */
964
-
965
- /**
966
- * Creates a throttled version of a function.
967
- * Executes immediately, throttles further calls, optional trailing execution.
968
- *
969
- * Preferred:
970
- * - throttle(fn, delay, [options])
971
- *
972
- * Also supported:
973
- * - throttle(delay, fn, [options]) // legacy/alt ordering
974
- *
975
- * Notes:
976
- * - Uses performance.now() (via `now()`) for elapsed timing.
977
- * - If trailing is enabled, uses the latest arguments/context seen during the wait.
978
- * - `.cancel()` clears any pending trailing invocation.
979
- * - `.flush()` immediately invokes a pending trailing call (if scheduled).
980
- * - Optional AbortSignal: abort cancels any pending trailing invocation.
981
- *
982
- * @param {Function|string|number} a
983
- * @param {Function|string|number|Object} b
984
- * @param {Object} [c]
985
- * @param {boolean} [c.trailing=true]
986
- * @param {AbortSignal} [c.signal]
987
- * @returns {ThrottledFunction}
988
- */
989
- export function throttle(a, b, c) {
990
- // Require an explicit delay by passing `undefined` as defaultDelay.
991
- const { fn, delay, options } = resolveDelayFnOptions(a, b, c, undefined);
992
-
993
- const signal = options?.signal;
994
- const trailing = options?.trailing ?? true;
995
-
996
- const waitWindow = Math.max(0, delay);
997
-
998
- let lastCallTime = -Infinity;
999
- let timeoutId = 0;
1000
-
1001
- /** @type {any[] | null} */
1002
- let lastArgs = null;
1003
- /** @type {any | null} */
1004
- let lastThis = null;
1005
-
1006
- const abort = pendingAbort(signal, () => cancel());
1007
-
1008
- const invoke = () => {
1009
- if (!lastArgs) return;
1010
-
1011
- const args = lastArgs;
1012
- const ctx = lastThis;
1013
-
1014
- // clear first (re-entrancy safe + GC friendly)
1015
- lastArgs = null;
1016
- lastThis = null;
1017
-
1018
- abort.remove();
1019
- fn.apply(ctx, args);
1020
- };
1021
-
1022
- const cancel = () => {
1023
- if (timeoutId) clearTimeout(timeoutId);
1024
- timeoutId = 0;
1025
-
1026
- lastArgs = null;
1027
- lastThis = null;
1028
-
1029
- abort.remove();
1030
- };
1031
-
1032
- /** @param {number} wait */
1033
- const scheduleTrailing = (wait) => {
1034
- abort.add();
1035
-
1036
- timeoutId = setTimeout(() => {
1037
- timeoutId = 0;
1038
- lastCallTime = now();
1039
- invoke();
1040
- }, wait);
1041
- };
1042
-
1043
- /** @type {any} */
1044
- const throttled = function (...args) {
1045
- if (signal?.aborted) return;
1046
-
1047
- const currentTime = now();
1048
- const timeSinceLast = currentTime - lastCallTime;
1049
-
1050
- lastArgs = args;
1051
- lastThis = this;
1052
-
1053
- if (timeSinceLast >= waitWindow) {
1054
- // Leading edge: run now
1055
- lastCallTime = currentTime;
1056
-
1057
- // Clear any pending trailing call (and listener)
1058
- if (timeoutId) {
1059
- clearTimeout(timeoutId);
1060
- timeoutId = 0;
1061
- abort.remove();
1062
- }
1063
-
1064
- invoke();
1065
- return;
1066
- }
1067
-
1068
- if (!trailing) return;
1069
-
1070
- // Trailing edge: schedule once, keep latest args
1071
- if (!timeoutId) {
1072
- const wait = Math.max(0, waitWindow - timeSinceLast);
1073
- scheduleTrailing(wait);
1074
- }
1075
- };
1076
-
1077
- throttled.cancel = cancel;
1078
-
1079
- throttled.flush = () => {
1080
- if (!timeoutId) return;
1081
- clearTimeout(timeoutId);
1082
- timeoutId = 0;
1083
-
1084
- lastCallTime = now();
1085
- invoke();
1086
- };
1087
-
1088
- // If already aborted at creation time, ensure clean slate.
1089
- if (signal?.aborted) cancel();
1090
-
1091
- return throttled;
1092
- }
1093
- ===== END FILE: throttle.js =====
1094
-
1095
-
1096
- ===== FILE: TimeoutFlow.js =====
1097
-
1098
- // ./src/TimeoutFlow.js
1099
-
1100
- import { after } from './after.js';
1101
- import { every } from './every.js';
1102
- import { pendingAbort } from './abort.js';
1103
-
1104
- /**
1105
- * Creates a fluent scheduler.
1106
- * Returns a chainable timeline.
1107
- *
1108
- * @param {Object} [options]
1109
- * @param {AbortSignal} [options.signal] - Optional AbortSignal to auto-cancel the flow
1110
- */
1111
- export function flow({ signal } = {}) {
1112
- const steps = [];
1113
- const labelMap = new Map();
1114
-
1115
- let currentIndex = 0;
1116
-
1117
- let started = false;
1118
- let isPaused = false;
1119
- let isCancelled = false;
1120
- let isFinished = false;
1121
-
1122
- let loopEnabled = false;
1123
- let loopLimit = Infinity;
1124
- let loopCount = 0;
1125
-
1126
- /** @type {Function | null} */
1127
- let onFinishCallback = null;
1128
- /** @type {Function | null} */
1129
- let onErrorCallback = null;
1130
-
1131
- let jumpTarget = null;
1132
-
1133
- /** @type {Array<() => boolean>} */
1134
- let conditionStack = [];
1135
-
1136
- let skipMode = false;
1137
-
1138
- let whileCondition = null;
1139
- let doWhileCondition = null;
1140
-
1141
- /** @type {any} */
1142
- let runner;
1143
-
1144
- // Abort wiring is per-run (so we don't retain references forever)
1145
- const abort = pendingAbort(signal, () => runner.cancel());
1146
-
1147
- const clearController = (step) => {
1148
- if (!step) return;
1149
- if (step.controller) step.controller = null;
1150
- };
1151
-
1152
- const cleanupCurrentController = () => {
1153
- const step = steps[currentIndex];
1154
- step?.controller?.cancel?.();
1155
- if (step) step.controller = null;
1156
- };
1157
-
1158
- const finishFlow = () => {
1159
- if (isFinished || isCancelled) return;
1160
-
1161
- started = false;
1162
- isPaused = false;
1163
- isFinished = true;
1164
-
1165
- cleanupCurrentController();
1166
- abort.remove();
1167
-
1168
- onFinishCallback?.();
1169
- };
1170
-
1171
- const cancelFlow = () => {
1172
- if (isCancelled) return;
1173
-
1174
- started = false;
1175
- isPaused = false;
1176
- isFinished = false;
1177
- isCancelled = true;
1178
-
1179
- cleanupCurrentController();
1180
- abort.remove();
1181
- };
1182
-
1183
- const handleError = (err, step) => {
1184
- // best hygiene: cancel current controller so nothing leaks
1185
- cancelFlow();
1186
-
1187
- if (onErrorCallback) {
1188
- try {
1189
- onErrorCallback(err, {
1190
- step,
1191
- index: currentIndex,
1192
- });
1193
- } catch (_) {
1194
- // If the error handler itself throws, fall through to rethrow original.
1195
- }
1196
- return;
1197
- }
1198
-
1199
- // No handler: preserve existing behavior (throw)
1200
- throw err;
1201
- };
1202
-
1203
- const safeCall = (fn, stepForContext) => {
1204
- try {
1205
- return fn();
1206
- } catch (err) {
1207
- handleError(err, stepForContext);
1208
- return undefined;
1209
- }
1210
- };
1211
-
1212
- const incrementStep = (step) => {
1213
- clearController(step);
1214
- currentIndex += 1;
1215
- queueMicrotask(executeNext);
1216
- };
1217
-
1218
- function executeNext() {
1219
- if (isCancelled || isPaused || isFinished) return;
1220
- if (signal?.aborted) {
1221
- cancelFlow();
1222
- return;
1223
- }
1224
-
1225
- // Jump handling
1226
- if (jumpTarget) {
1227
- const targetIndex = labelMap.get(jumpTarget);
1228
- if (typeof targetIndex === 'number') {
1229
- currentIndex = targetIndex;
1230
- } else {
1231
- // treat as a flow error
1232
- safeCall(() => {
1233
- throw new Error(`Label "${jumpTarget}" not found`);
1234
- }, steps[currentIndex]);
1235
- return;
1236
- }
1237
- jumpTarget = null;
1238
- }
1239
-
1240
- // Handle if/unless conditions (applies to the next step only)
1241
- if (conditionStack.length > 0) {
1242
- const predicate = conditionStack.shift();
1243
- const shouldRun = safeCall(predicate, steps[currentIndex]);
1244
- if (!shouldRun) skipMode = true;
1245
- }
1246
-
1247
- // Skip mode: keep skipping until we hit a label (or end)
1248
- if (skipMode) {
1249
- const next = steps[currentIndex];
1250
- if (!next || next.type === 'label') {
1251
- skipMode = false;
1252
- } else {
1253
- return incrementStep(next);
1254
- }
1255
- }
1256
-
1257
- const step = steps[currentIndex];
1258
-
1259
- // End of timeline
1260
- if (!step || currentIndex >= steps.length) {
1261
- if (loopEnabled && ++loopCount < loopLimit) {
1262
- currentIndex = 0;
1263
- executeNext();
1264
- } else {
1265
- finishFlow(); // ✅ only natural completion calls onFinish
1266
- }
1267
- return;
1268
- }
1269
-
1270
- if (step.type === 'label') {
1271
- return incrementStep(step);
1272
- }
1273
-
1274
- if (step.type === 'after') {
1275
- step.controller = after(
1276
- () => safeCall(step.fn, step),
1277
- step.duration,
1278
- { signal, onFinish: () => incrementStep(step) }
1279
- );
1280
- return;
1281
- }
1282
-
1283
- if (step.type === 'every') {
1284
-
1285
- // No ticks will ever fire => advance immediately.
1286
- if (!(step.times > 0) && step.times !== Infinity) {
1287
- return incrementStep(step);
1288
- }
1289
-
1290
- let count = 0;
1291
- const ctrl = every(
1292
- () => {
1293
- if (isPaused || isCancelled || isFinished) return;
1294
- if (signal?.aborted) {
1295
- cancelFlow();
1296
- return;
1297
- }
1298
-
1299
- // Pre-run while guard
1300
- if (step.whileCondition && !safeCall(step.whileCondition, step)) {
1301
- ctrl.cancel();
1302
- return incrementStep(step);
1303
- }
1304
-
1305
- safeCall(() => step.fn(count++), step);
1306
-
1307
- // Post-run doWhile guard
1308
- if (step.doWhileCondition && !safeCall(step.doWhileCondition, step)) {
1309
- ctrl.cancel();
1310
- return incrementStep(step);
1311
- }
1312
-
1313
- if (count >= step.times) {
1314
- ctrl.cancel();
1315
- return incrementStep(step);
1316
- }
1317
- },
1318
- step.duration,
1319
- { max: step.times, signal }
1320
- );
1321
-
1322
- step.controller = ctrl;
1323
- }
1324
- }
1325
-
1326
- runner = {
1327
- after(duration, fn) {
1328
- steps.push({ type: 'after', duration, fn, controller: null });
1329
- return runner;
1330
- },
1331
-
1332
- every(duration, fn, timesOrOptions = Infinity) {
1333
- const raw =
1334
- typeof timesOrOptions === 'number'
1335
- ? timesOrOptions
1336
- : timesOrOptions?.max ?? Infinity;
1337
-
1338
- const times =
1339
- raw === Infinity ? Infinity : Math.max(0, raw | 0); // int >= 0
1340
-
1341
- steps.push({
1342
- type: 'every',
1343
- duration,
1344
- fn,
1345
- times,
1346
- whileCondition,
1347
- doWhileCondition,
1348
- controller: null,
1349
- });
1350
-
1351
- whileCondition = null;
1352
- doWhileCondition = null;
1353
- return runner;
1354
- },
1355
-
1356
- loop(n = true) {
1357
- loopEnabled = true;
1358
- loopLimit = n === true ? Infinity : n;
1359
- return runner;
1360
- },
1361
-
1362
- onFinish(cb) {
1363
- onFinishCallback = cb;
1364
- return runner;
1365
- },
1366
-
1367
- onError(cb) {
1368
- onErrorCallback = cb;
1369
- return runner;
1370
- },
1371
-
1372
- start() {
1373
- // restart hygiene: cancel any active controller from a previous run
1374
- cleanupCurrentController();
1375
-
1376
- isCancelled = false;
1377
- isFinished = false;
1378
- isPaused = false;
1379
- started = true;
1380
-
1381
- currentIndex = 0;
1382
- loopCount = 0;
1383
-
1384
- // Abort wiring is per-run
1385
- abort.reset();
1386
- if (!signal?.aborted) abort.add();
1387
-
1388
- if (signal?.aborted) {
1389
- cancelFlow(); // no-op start if already aborted
1390
- return runner;
1391
- }
1392
-
1393
- executeNext();
1394
- return runner;
1395
- },
1396
-
1397
- pause() {
1398
- if (isPaused || isCancelled || isFinished) return;
1399
- isPaused = true;
1400
- steps[currentIndex]?.controller?.pause?.();
1401
- },
1402
-
1403
- resume() {
1404
- if (!isPaused || isCancelled || isFinished) return;
1405
- if (signal?.aborted) {
1406
- cancelFlow();
1407
- return;
1408
- }
1409
- isPaused = false;
1410
- steps[currentIndex]?.controller?.resume?.();
1411
- },
1412
-
1413
- cancel() {
1414
- cancelFlow(); // ✅ never calls onFinish
1415
- },
1416
-
1417
- reset() {
1418
- cancelFlow();
1419
-
1420
- steps.length = 0;
1421
- labelMap.clear();
1422
-
1423
- currentIndex = 0;
1424
- loopCount = 0;
1425
-
1426
- onFinishCallback = null;
1427
- onErrorCallback = null;
1428
-
1429
- jumpTarget = null;
1430
- conditionStack = [];
1431
- skipMode = false;
1432
-
1433
- whileCondition = null;
1434
- doWhileCondition = null;
1435
-
1436
- // allow reuse after reset (fresh state)
1437
- started = false;
1438
- isPaused = false;
1439
- isCancelled = false;
1440
- isFinished = false;
1441
-
1442
- return runner;
1443
- },
1444
-
1445
- label(name) {
1446
- labelMap.set(name, steps.length); // point to next step index
1447
- steps.push({ type: 'label', name, controller: null });
1448
- return runner;
1449
- },
1450
-
1451
- jumpTo(name) {
1452
- jumpTarget = name;
1453
- return runner;
1454
- },
1455
-
1456
- if(predicate) {
1457
- conditionStack.push(() =>
1458
- typeof predicate === 'function' ? !!predicate() : !!predicate
1459
- );
1460
- return runner;
1461
- },
1462
-
1463
- unless(predicate) {
1464
- conditionStack.push(() =>
1465
- typeof predicate === 'function' ? !predicate() : !predicate
1466
- );
1467
- return runner;
1468
- },
1469
-
1470
- while(predicate) {
1471
- whileCondition = () =>
1472
- typeof predicate === 'function' ? !!predicate() : !!predicate;
1473
- return runner;
1474
- },
1475
-
1476
- doWhile(predicate) {
1477
- doWhileCondition = () =>
1478
- typeof predicate === 'function' ? !!predicate() : !!predicate;
1479
- return runner;
1480
- },
1481
-
1482
- // unified lifecycle surface
1483
- get isRunning() {
1484
- return started && !isPaused && !isCancelled && !isFinished;
1485
- },
1486
- get isPaused() {
1487
- return isPaused;
1488
- },
1489
- get isCancelled() {
1490
- return isCancelled;
1491
- },
1492
- get isFinished() {
1493
- return isFinished;
1494
- },
1495
- };
1496
-
1497
- return runner;
1498
- }
1499
- ===== END FILE: TimeoutFlow.js =====
1500
-
1501
-
1502
- ===== FILE: TimerBase.js =====
1503
-
1504
- // ./src/TimerBase.js
1505
- import { parseDuration } from './parseDuration.js';
1506
- import { now } from './now.js'
1507
-
1508
-
1509
- /**
1510
- * Base timer class to manage pause/resume/cancel behavior.
1511
- * Not meant to be used directly—subclass for concrete behavior.
1512
- */
1513
- export class TimerBase {
1514
- #ms;
1515
- #startTime = null; // performance.now()
1516
- #remaining;
1517
- #timer = null;
1518
-
1519
- #running = false;
1520
- #paused = false;
1521
- #finished = false;
1522
-
1523
- /**
1524
- * @param {string|number} duration - The duration to wait in ms or shorthand format
1525
- */
1526
- constructor(duration) {
1527
- this.#ms = parseDuration(duration);
1528
- this.#remaining = this.#ms;
1529
- }
1530
-
1531
- /**
1532
- * Whether the timer is currently running (actively counting down).
1533
- * @returns {boolean}
1534
- */
1535
- get isRunning() {
1536
- return this.#running;
1537
- }
1538
-
1539
- /**
1540
- * Whether the timer is paused (resumable).
1541
- * @returns {boolean}
1542
- */
1543
- get isPaused() {
1544
- return this.#paused;
1545
- }
1546
-
1547
- /**
1548
- * Whether the timer has finished or been canceled (terminal state).
1549
- * @returns {boolean}
1550
- */
1551
- get isFinished() {
1552
- return this.#finished;
1553
- }
1554
-
1555
- /**
1556
- * Pause the active timer, storing remaining time.
1557
- */
1558
- pause() {
1559
- if (!this.#running) return;
1560
-
1561
- clearTimeout(this.#timer);
1562
- this.#timer = null;
1563
-
1564
- const elapsed = now() - this.#startTime;
1565
- this.#remaining = Math.max(0, this.#remaining - elapsed);
1566
-
1567
- this.#running = false;
1568
- this.#paused = true;
1569
- // not finished; still resumable
1570
- }
1571
-
1572
- /**
1573
- * Resume the timer using the remaining time (or an override delay).
1574
- * @param {Function} callback - Called when time completes
1575
- * @param {number|null} [overrideDelay=null] - Optional custom delay in ms
1576
- */
1577
- resume(callback, overrideDelay = null) {
1578
- if (this.#finished) return;
1579
- if (this.#running) return;
1580
-
1581
- const rawDelay = overrideDelay ?? this.#remaining;
1582
-
1583
- // Reject invalid delays (avoid scheduling with NaN/Infinity/etc.)
1584
- if (!Number.isFinite(rawDelay) || rawDelay < 0) return;
1585
-
1586
- // Support 0ms timers (schedule next macrotask)
1587
- const delay = Math.max(0, rawDelay);
1588
-
1589
- // Important: remaining must reflect what we actually scheduled,
1590
- // otherwise pause() math will be wrong when overrideDelay is used.
1591
- this.#remaining = delay;
1592
-
1593
- this.#startTime = now();
1594
- this.#running = true;
1595
- this.#paused = false;
1596
-
1597
- this.#timer = setTimeout(() => {
1598
- this.#timer = null;
1599
- this.#running = false;
1600
- this.#paused = false;
1601
- this.#finished = true;
1602
- this.#remaining = 0;
1603
- callback?.();
1604
- }, delay);
1605
- }
1606
-
1607
- /**
1608
- * Cancel the timer immediately (terminal).
1609
- */
1610
- cancel() {
1611
- if (this.#timer) clearTimeout(this.#timer);
1612
- this.#timer = null;
1613
-
1614
- this.#running = false;
1615
- this.#paused = false;
1616
- this.#finished = true;
1617
- // leave #remaining as-is or set to 0; prefer 0 for "terminal means done"
1618
- this.#remaining = 0;
1619
- }
1620
-
1621
- /**
1622
- * Reset the timer to its original delay, cancelling if needed.
1623
- * After reset, the timer is not running.
1624
- */
1625
- reset() {
1626
- if (this.#timer) clearTimeout(this.#timer);
1627
- this.#timer = null;
1628
-
1629
- this.#startTime = null;
1630
- this.#remaining = this.#ms;
1631
-
1632
- this.#running = false;
1633
- this.#paused = false;
1634
- this.#finished = false;
1635
- }
1636
- }
1637
- ===== END FILE: TimerBase.js =====
1638
-
1639
-
1640
- ===== FILE: waitFor.js =====
1641
-
1642
- // ./src/waitFor.js
1643
-
1644
- import { parseDuration } from './parseDuration.js';
1645
- import { attachAbort, createAbortError } from './abort.js';
1646
- import { now } from './now.js'
1647
-
1648
-
1649
- /**
1650
- * Waits for a condition to become true, polling at intervals.
1651
- *
1652
- * @param {Function} condition - returns truthy when satisfied
1653
- * @param {Object} [options] - optional polling control
1654
- * @param {string|number} [options.interval='250ms'] - poll frequency
1655
- * @param {string|number} [options.timeout] - max wait time
1656
- * @param {boolean} [options.immediate=false] - If true, evaluate condition immediately
1657
- * @param {AbortSignal} [options.signal] - Optional AbortSignal to cancel waiting
1658
- * @returns {Promise<void>}
1659
- */
1660
- export function waitFor(condition, { interval = '250ms', timeout, immediate = false, signal } = {}) {
1661
- return new Promise((resolve, reject) => {
1662
- if (signal?.aborted) {
1663
- reject(createAbortError());
1664
- return;
1665
- }
1666
-
1667
- const start = now();
1668
-
1669
- const intervalMs = typeof interval === 'string' ? parseDuration(interval) : interval;
1670
- const timeoutMs = timeout != null ? parseDuration(timeout) : null;
1671
-
1672
- let poller = null;
1673
-
1674
- const cleanup = () => {
1675
- if (poller != null) {
1676
- clearInterval(poller);
1677
- poller = null;
1678
- }
1679
- cleanupAbort();
1680
- };
1681
-
1682
- const onAbort = () => {
1683
- cleanup();
1684
- reject(createAbortError());
1685
- };
1686
-
1687
- const cleanupAbort = attachAbort(signal, onAbort);
1688
-
1689
- const check = () => {
1690
- let ok = false;
1691
-
1692
- try {
1693
- ok = !!condition();
1694
- } catch (err) {
1695
- cleanup();
1696
- reject(err);
1697
- return;
1698
- }
1699
-
1700
- if (ok) {
1701
- cleanup();
1702
- resolve();
1703
- return;
1704
- }
1705
-
1706
- if (timeoutMs != null && now() - start >= timeoutMs) {
1707
- cleanup();
1708
- reject(new Error('waitFor timed out'));
1709
- }
1710
- };
1711
-
1712
- // Only evaluate immediately if explicitly requested
1713
- if (immediate) check();
1714
-
1715
- // Schedule exactly once
1716
- poller = setInterval(check, intervalMs);
1717
- });
1718
- }
1719
- ===== END FILE: waitFor.js =====
1720
-
1721
-
1722
- ===== FILE: raf\afterRaf.js =====
1723
-
1724
- // ./raf/afterRaf.js
1725
- import { resolveDelayFnOptions } from '../resolveDelayAndFn.js';
1726
- import { attachAbort } from '../abort.js';
1727
- import { now } from '../now.js';
1728
-
1729
- /**
1730
- * Schedules a one-time delayed function using requestAnimationFrame.
1731
- *
1732
- * Preferred:
1733
- * - afterRaf(fn, duration, [options])
1734
- *
1735
- * Also supported (legacy):
1736
- * - afterRaf(duration, fn, [onFinish], [options])
1737
- *
1738
- * Timing model:
1739
- * - Uses frame timestamps for progression.
1740
- * - Paused time does NOT count toward elapsed time (pause freezes remaining).
1741
- *
1742
- * @param {Function|string|number} a
1743
- * @param {Function|string|number|Object} b
1744
- * @param {Function|Object} [c] - legacy onFinish OR options
1745
- * @param {Object} [d] - legacy options (when using 4 args)
1746
- * @param {Function} [c.onFinish] - optional callback after finishing (preferred: in options)
1747
- * @param {AbortSignal} [c.signal] - optional AbortSignal to auto-cancel
1748
- * @returns {{
1749
- * pause(): void,
1750
- * resume(): void,
1751
- * cancel(): void,
1752
- * reset(): void,
1753
- * readonly isRunning: boolean,
1754
- * readonly isPaused: boolean,
1755
- * readonly isFinished: boolean
1756
- * }}
1757
- */
1758
- export function afterRaf(a, b, c, d) {
1759
- const legacyOnFinish = typeof c === 'function' ? c : undefined;
1760
- const maybeOptions = legacyOnFinish ? d : c;
1761
-
1762
- // Require explicit duration: defaultDelay = undefined
1763
- const { fn, delay, options } = resolveDelayFnOptions(a, b, maybeOptions, undefined);
1764
-
1765
- const { signal, onFinish } = legacyOnFinish
1766
- ? { ...options, onFinish: legacyOnFinish }
1767
- : options;
1768
-
1769
- const totalMs = Math.max(0, delay);
1770
-
1771
- let rafId = 0;
1772
-
1773
- // remaining time until fire (pause-safe)
1774
- let remaining = totalMs;
1775
-
1776
- // start timestamp for the current running segment
1777
- let segmentStart = null; // number | null
1778
-
1779
- let running = false;
1780
- let paused = false;
1781
- let finished = false;
1782
-
1783
- const cancelFrame = () => {
1784
- if (rafId) cancelAnimationFrame(rafId);
1785
- rafId = 0;
1786
- };
1787
-
1788
- let cleanupAbort = () => { };
1789
-
1790
- const cleanupAbortListener = () => {
1791
- cleanupAbort();
1792
- cleanupAbort = () => { };
1793
- };
1794
-
1795
- const finish = () => {
1796
- cancelFrame();
1797
- running = false;
1798
- paused = false;
1799
- finished = true;
1800
- segmentStart = null;
1801
- remaining = 0;
1802
- cleanupAbortListener();
1803
- };
1804
-
1805
- const execFinish = () => {
1806
- finish();
1807
- fn?.();
1808
- onFinish?.();
1809
- };
1810
-
1811
- const cancel = () => {
1812
- if (finished) return;
1813
- finish();
1814
- };
1815
-
1816
- const attachAbortListener = () => {
1817
- cleanupAbortListener();
1818
-
1819
- // Preserve semantics: if already aborted, become terminal.
1820
- if (signal?.aborted) {
1821
- finished = true;
1822
- remaining = 0;
1823
- return;
1824
- }
1825
-
1826
- cleanupAbort = attachAbort(signal, cancel);
1827
- };
1828
-
1829
- // Attach abort for the lifetime of this timer instance
1830
- attachAbortListener();
1831
-
1832
- const tick = (ts) => {
1833
- if (!running || finished) return;
1834
-
1835
- if (segmentStart == null) segmentStart = ts;
1836
-
1837
- const elapsed = ts - segmentStart;
1838
-
1839
- if (elapsed >= remaining) {
1840
- execFinish();
1841
- return;
1842
- }
1843
-
1844
- rafId = requestAnimationFrame(tick);
1845
- };
1846
-
1847
- const pause = () => {
1848
- if (!running || finished) return;
1849
-
1850
- cancelFrame();
1851
-
1852
- // Freeze remaining based on how long we ran in this segment
1853
- const currentTime = now();
1854
- if (segmentStart != null) {
1855
- const elapsed = currentTime - segmentStart;
1856
- remaining = Math.max(0, remaining - elapsed);
1857
- }
1858
-
1859
- segmentStart = null;
1860
- running = false;
1861
- paused = true;
1862
- };
1863
-
1864
- const resume = () => {
1865
- if (finished || running || !paused) return;
1866
- if (signal?.aborted) return;
1867
-
1868
- // If nothing remains, finish synchronously
1869
- if (!(remaining > 0)) {
1870
- execFinish();
1871
- return;
1872
- }
1873
-
1874
- paused = false;
1875
- running = true;
1876
- segmentStart = null; // will be set on first tick
1877
- rafId = requestAnimationFrame(tick);
1878
- };
1879
-
1880
- const reset = () => {
1881
- cancelFrame();
1882
-
1883
- segmentStart = null;
1884
- remaining = totalMs;
1885
-
1886
- running = false;
1887
- paused = false;
1888
- finished = false;
1889
-
1890
- // Re-attach abort on reset (more consistent with non-RAF timers)
1891
- attachAbortListener();
1892
-
1893
- if (finished) {
1894
- // signal was aborted during attachAbortListener()
1895
- return;
1896
- }
1897
- };
1898
-
1899
- // Start immediately unless already aborted/finished
1900
- if (!finished) {
1901
- // Support 0ms: fire on next frame (consistent with RAF timing)
1902
- if (!(remaining > 0)) {
1903
- execFinish();
1904
- } else {
1905
- running = true;
1906
- rafId = requestAnimationFrame(tick);
1907
- }
1908
- } else {
1909
- cleanupAbortListener();
1910
- }
1911
-
1912
- return {
1913
- pause,
1914
- resume,
1915
- cancel,
1916
- reset,
1917
- get isRunning() {
1918
- return running;
1919
- },
1920
- get isPaused() {
1921
- return paused;
1922
- },
1923
- get isFinished() {
1924
- return finished;
1925
- },
1926
- };
1927
- }
1928
- ===== END FILE: raf\afterRaf.js =====
1929
-
1930
-
1931
- ===== FILE: raf\debounceRaf.js =====
1932
-
1933
- // ./raf/debounceRaf.js
1934
- import { resolveDelayFnOptions } from '../resolveDelayAndFn.js';
1935
- import { pendingAbort } from '../abort.js';
1936
- import { now } from '../now.js';
1937
-
1938
- /**
1939
- * Debounces a function using requestAnimationFrame.
1940
- *
1941
- * Preferred:
1942
- * - debounceRaf(fn, [duration], [options]) // duration defaults to 0 (next frame)
1943
- *
1944
- * Also supported:
1945
- * - debounceRaf(duration, fn, [options])
1946
- * - debounceRaf(fn, [options])
1947
- *
1948
- * Timing model:
1949
- * - Waits until `ms` of inactivity have passed (measured using frame timestamps).
1950
- * - `ms = 0` means "run on the next animation frame" (still debounced).
1951
- *
1952
- * Supports:
1953
- * - `.cancel()` clears any pending invocation.
1954
- * - `.flush()` immediately invokes if pending.
1955
- * - Optional AbortSignal: abort cancels any pending invocation.
1956
- *
1957
- * @param {Function|string|number} a - function or duration
1958
- * @param {Function|string|number|Object} [b] - duration, fn, or options
1959
- * @param {Object} [c] - options (3-arg form)
1960
- * @param {AbortSignal} [c.signal] - AbortSignal to auto-cancel pending work
1961
- * @returns {((...args: any[]) => void) & { cancel: () => void, flush: () => void }}
1962
- */
1963
- export function debounceRaf(a, b, c) {
1964
- // duration is optional for debounceRaf (defaults to 0)
1965
- const { fn, delay, options } = resolveDelayFnOptions(a, b, c, 0);
1966
-
1967
- const ms = Math.max(0, delay);
1968
- const signal = options?.signal;
1969
-
1970
- let rafId = 0;
1971
-
1972
- /** @type {any[] | null} */
1973
- let lastArgs = null;
1974
- /** @type {any | null} */
1975
- let lastThis = null;
1976
-
1977
- // last time the debounced function was called (used for inactivity measurement)
1978
- let lastCallTime = 0;
1979
-
1980
- const clearRaf = () => {
1981
- if (rafId) cancelAnimationFrame(rafId);
1982
- rafId = 0;
1983
- };
1984
-
1985
- const abort = pendingAbort(signal, () => cancel());
1986
-
1987
- const cancel = () => {
1988
- clearRaf();
1989
- lastArgs = null;
1990
- lastThis = null;
1991
- lastCallTime = 0;
1992
- abort.remove();
1993
- };
1994
-
1995
- const invoke = () => {
1996
- if (!lastArgs) return;
1997
-
1998
- const args = lastArgs;
1999
- const ctx = lastThis;
2000
-
2001
- // Clear first (re-entrancy safe + GC friendly)
2002
- lastArgs = null;
2003
- lastThis = null;
2004
-
2005
- abort.remove();
2006
- fn.apply(ctx, args);
2007
- };
2008
-
2009
- const tick = (ts) => {
2010
- if (!rafId) return; // canceled
2011
-
2012
- if (!lastArgs) {
2013
- // Nothing pending; clean slate
2014
- cancel();
2015
- return;
2016
- }
2017
-
2018
- const elapsed = ts - lastCallTime;
2019
-
2020
- if (elapsed >= ms) {
2021
- // Stop scheduling first, then invoke
2022
- clearRaf();
2023
- invoke();
2024
- return;
2025
- }
2026
-
2027
- rafId = requestAnimationFrame(tick);
2028
- };
2029
-
2030
- /** @type {any} */
2031
- const debounced = function (...args) {
2032
- if (signal?.aborted) return;
2033
-
2034
- lastArgs = args;
2035
- lastThis = this;
2036
-
2037
- // Use monotonic clock for call timestamp; RAF tick uses its own timestamp.
2038
- lastCallTime = now();
2039
-
2040
- // Ensure abort listener exists only while pending work exists
2041
- abort.add();
2042
-
2043
- clearRaf();
2044
- rafId = requestAnimationFrame(tick);
2045
- };
2046
-
2047
- debounced.cancel = cancel;
2048
-
2049
- debounced.flush = () => {
2050
- if (!rafId || !lastArgs) return;
2051
- clearRaf();
2052
- invoke();
2053
- };
2054
-
2055
- // If already aborted at creation time, ensure clean slate.
2056
- if (signal?.aborted) cancel();
2057
-
2058
- return debounced;
2059
- }
2060
- ===== END FILE: raf\debounceRaf.js =====
2061
-
2062
-
2063
- ===== FILE: raf\everyRaf.js =====
2064
-
2065
- // ./raf/everyRaf.js
2066
- import { resolveDelayFnOptions } from '../resolveDelayAndFn.js';
2067
- import { attachAbort } from '../abort.js';
2068
- import { now } from '../now.js';
2069
-
2070
- const isPlainOptions = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
2071
-
2072
- /**
2073
- * Repeats a function every N milliseconds using requestAnimationFrame.
2074
- *
2075
- * Preferred:
2076
- * - everyRaf(fn, duration, [options])
2077
- *
2078
- * Also supported (legacy):
2079
- * - everyRaf(duration, fn, [maxTimes], [runImmediately], [options])
2080
- *
2081
- * Timing model:
2082
- * - Counts down using frame deltas.
2083
- * - Paused time does NOT count (pause freezes remaining-to-next-tick).
2084
- * - On large frame gaps, may "catch up" by running multiple ticks in one frame,
2085
- * but will never exceed max.
2086
- *
2087
- * @param {Function|string|number} a
2088
- * @param {Function|string|number|Object} b
2089
- * @param {number|boolean|Object} [c] - legacy maxTimes OR legacy runImmediately OR options
2090
- * @param {boolean|Object} [d] - legacy runImmediately OR options
2091
- * @param {Object} [e] - legacy options
2092
- * @returns {{
2093
- * pause(): void,
2094
- * resume(): void,
2095
- * cancel(): void,
2096
- * reset(restart?: boolean): void,
2097
- * readonly isRunning: boolean,
2098
- * readonly isPaused: boolean,
2099
- * readonly isFinished: boolean,
2100
- * readonly count: number
2101
- * }}
2102
- */
2103
- export function everyRaf(a, b, c, d, e) {
2104
- const durationFirst = typeof a !== 'function';
2105
-
2106
- // ---- Normalize legacy positional args into options (without breaking legacy behavior) ----
2107
- let legacyMax;
2108
- let legacyRunImmediately;
2109
-
2110
- /** @type {any} */
2111
- let optionsCandidate;
2112
-
2113
- if (durationFirst) {
2114
- // Legacy or duration-first:
2115
- // - everyRaf(duration, fn, options)
2116
- // - everyRaf(duration, fn, maxTimes, runImmediately, options)
2117
- // - everyRaf(duration, fn, maxTimes, options)
2118
- // - everyRaf(duration, fn, runImmediately, options) (extra leniency)
2119
- if (isPlainOptions(c)) {
2120
- optionsCandidate = c;
2121
- } else if (isPlainOptions(d)) {
2122
- optionsCandidate = d;
2123
- } else if (isPlainOptions(e)) {
2124
- optionsCandidate = e;
2125
- } else {
2126
- optionsCandidate = {};
2127
- }
2128
-
2129
- if (typeof c === 'number') legacyMax = c;
2130
- if (typeof d === 'boolean') legacyRunImmediately = d;
2131
-
2132
- // Lenient support: (duration, fn, true, options) => runImmediately=true
2133
- if (legacyRunImmediately == null && typeof c === 'boolean') legacyRunImmediately = c;
2134
- } else {
2135
- // Preferred fn-first:
2136
- // - everyRaf(fn, duration, options?)
2137
- optionsCandidate = isPlainOptions(c) ? c : {};
2138
- }
2139
-
2140
- // Parse fn + duration using shared helper (duration is REQUIRED)
2141
- const { fn, delay, options } = resolveDelayFnOptions(a, b, optionsCandidate, undefined);
2142
-
2143
- const signal = options?.signal;
2144
-
2145
- const maxFromOptions = options?.max ?? Infinity;
2146
- const runImmediatelyFromOptions = options?.runImmediately ?? false;
2147
-
2148
- // Legacy positional should win (to preserve prior behavior)
2149
- const max = legacyMax != null ? legacyMax : maxFromOptions;
2150
- const runImmediately =
2151
- legacyRunImmediately != null ? legacyRunImmediately : runImmediatelyFromOptions;
2152
-
2153
- const intervalMs = Math.max(0, delay);
2154
-
2155
- let rafId = 0;
2156
- let count = 0;
2157
-
2158
- // remaining time until next tick (pause-safe)
2159
- let remainingToNext = intervalMs;
2160
-
2161
- // last frame timestamp (used for delta while running)
2162
- let lastTs = null; // number | null
2163
-
2164
- let running = false;
2165
- let paused = false;
2166
- let finished = false;
2167
-
2168
- const cancelFrame = () => {
2169
- if (rafId) cancelAnimationFrame(rafId);
2170
- rafId = 0;
2171
- };
2172
-
2173
- let cleanupAbort = () => { };
2174
-
2175
- const cleanupAbortListener = () => {
2176
- cleanupAbort();
2177
- cleanupAbort = () => { };
2178
- };
2179
-
2180
- const finish = () => {
2181
- cancelFrame();
2182
- running = false;
2183
- paused = false;
2184
- finished = true;
2185
-
2186
- lastTs = null;
2187
- remainingToNext = 0;
2188
-
2189
- cleanupAbortListener();
2190
- };
2191
-
2192
- const cancel = () => {
2193
- if (finished) return;
2194
- finish();
2195
- };
2196
-
2197
- const attachAbortListener = () => {
2198
- cleanupAbortListener();
2199
-
2200
- // Preserve semantics: if already aborted, become terminal (and do not attach).
2201
- if (signal?.aborted) {
2202
- finished = true;
2203
- remainingToNext = 0;
2204
- return;
2205
- }
2206
-
2207
- cleanupAbort = attachAbort(signal, cancel);
2208
- };
2209
-
2210
- attachAbortListener();
2211
-
2212
- const canRunMore = () => count < max;
2213
-
2214
- const fire = () => {
2215
- fn?.(count++);
2216
- if (!canRunMore()) {
2217
- finish();
2218
- return false;
2219
- }
2220
- return true;
2221
- };
2222
-
2223
- const tick = (ts) => {
2224
- if (!running || finished) return;
2225
-
2226
- if (signal?.aborted) {
2227
- finish();
2228
- return;
2229
- }
2230
-
2231
- if (!canRunMore()) {
2232
- finish();
2233
- return;
2234
- }
2235
-
2236
- if (lastTs == null) lastTs = ts;
2237
-
2238
- const delta = ts - lastTs;
2239
- lastTs = ts;
2240
-
2241
- // Decrement remaining time based on frame delta
2242
- remainingToNext -= delta;
2243
-
2244
- // Catch-up loop: if we missed multiple intervals, fire multiple times.
2245
- // Protect against infinite loops: intervalMs could be 0.
2246
- const step = Math.max(0, intervalMs);
2247
-
2248
- if (step === 0) {
2249
- // If interval is 0ms, treat as "once per frame"
2250
- remainingToNext = 0;
2251
- fire();
2252
- rafId = requestAnimationFrame(tick);
2253
- return;
2254
- }
2255
-
2256
- while (remainingToNext <= 0 && !finished) {
2257
- const ok = fire();
2258
- if (!ok) return;
2259
-
2260
- // carry over overshoot
2261
- remainingToNext += step;
2262
- }
2263
-
2264
- rafId = requestAnimationFrame(tick);
2265
- };
2266
-
2267
- const startLoop = () => {
2268
- if (finished) return;
2269
-
2270
- if (signal?.aborted) {
2271
- finish();
2272
- return;
2273
- }
2274
-
2275
- if (!canRunMore()) {
2276
- finish();
2277
- return;
2278
- }
2279
-
2280
- running = true;
2281
- paused = false;
2282
- lastTs = null;
2283
- rafId = requestAnimationFrame(tick);
2284
- };
2285
-
2286
- const pause = () => {
2287
- if (!running || finished) return;
2288
-
2289
- cancelFrame();
2290
-
2291
- // Freeze remainingToNext based on time since lastTs
2292
- const currentTime = now(); // ✅ fixed: no shadowing / TDZ
2293
- if (lastTs != null) {
2294
- const delta = currentTime - lastTs;
2295
- remainingToNext = Math.max(0, remainingToNext - delta);
2296
- }
2297
-
2298
- lastTs = null;
2299
- running = false;
2300
- paused = true;
2301
- };
2302
-
2303
- const resume = () => {
2304
- if (finished || running || !paused) return;
2305
- if (signal?.aborted) return;
2306
-
2307
- if (!canRunMore()) {
2308
- finish();
2309
- return;
2310
- }
2311
-
2312
- startLoop();
2313
- };
2314
-
2315
- const reset = (restart = false) => {
2316
- cancelFrame();
2317
-
2318
- count = 0;
2319
- remainingToNext = intervalMs;
2320
- lastTs = null;
2321
-
2322
- running = false;
2323
- paused = false;
2324
- finished = false;
2325
-
2326
- // Re-attach abort on reset (consistent with non-RAF timers)
2327
- attachAbortListener();
2328
- if (finished) return;
2329
-
2330
- // If max is already satisfied by definition (<=0 but not Infinity), finish.
2331
- if (!(max > 0) && max !== Infinity) {
2332
- finish();
2333
- return;
2334
- }
2335
-
2336
- if (restart) {
2337
- // Optionally honor runImmediately on restart (matching constructor semantics)
2338
- if (runImmediately && canRunMore()) {
2339
- fire();
2340
- if (finished) return;
2341
- }
2342
- startLoop();
2343
- }
2344
- };
2345
-
2346
- // Initial launch
2347
- if (!finished) {
2348
- if (!(max > 0) && max !== Infinity) {
2349
- finish();
2350
- } else {
2351
- if (runImmediately && canRunMore()) {
2352
- fire();
2353
- }
2354
- if (!finished) {
2355
- remainingToNext = Math.max(0, intervalMs);
2356
- startLoop();
2357
- }
2358
- }
2359
- } else {
2360
- cleanupAbortListener();
2361
- }
2362
-
2363
- return {
2364
- pause,
2365
- resume,
2366
- cancel,
2367
- reset,
2368
- get isRunning() {
2369
- return running;
2370
- },
2371
- get isPaused() {
2372
- return paused;
2373
- },
2374
- get isFinished() {
2375
- return finished;
2376
- },
2377
- get count() {
2378
- return count;
2379
- },
2380
- };
2381
- }
2382
- ===== END FILE: raf\everyRaf.js =====
2383
-
2384
-
2385
- ===== FILE: raf\index.js =====
2386
-
2387
- // ./raf/index.js
2388
-
2389
- import { afterRaf as _afterRaf } from './afterRaf.js';
2390
- import { everyRaf as _everyRaf } from './everyRaf.js';
2391
- import { debounceRaf as _debounceRaf } from './debounceRaf.js';
2392
- import { throttleRaf as _throttleRaf } from './throttleRaf.js';
2393
- import { waitForRaf as _waitForRaf } from './waitForRaf.js';
2394
-
2395
- export function assertRafAvailable() {
2396
- if (typeof requestAnimationFrame !== 'function') {
2397
- throw new Error(
2398
- 'requestAnimationFrame is not available in this environment. ' +
2399
- 'Use the non-RAF timers (after/every/waitFor) in Node, or provide a RAF polyfill.'
2400
- );
2401
- }
2402
- }
2403
-
2404
- const guard = (fn) =>
2405
- (...args) => {
2406
- assertRafAvailable();
2407
- return fn(...args);
2408
- };
2409
-
2410
- export const afterRaf = guard(_afterRaf);
2411
- export const everyRaf = guard(_everyRaf);
2412
- export const debounceRaf = guard(_debounceRaf);
2413
- export const throttleRaf = guard(_throttleRaf);
2414
- export const waitForRaf = guard(_waitForRaf);
2415
- ===== END FILE: raf\index.js =====
2416
-
2417
-
2418
- ===== FILE: raf\throttleRaf.js =====
2419
-
2420
- // ./raf/throttleRaf.js
2421
- import { pendingAbort } from '../abort.js';
2422
-
2423
- const isPlainOptions = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
2424
-
2425
- /**
2426
- * Throttles a function using `requestAnimationFrame`, with optional frame skipping.
2427
- *
2428
- * Preferred:
2429
- * - throttleRaf(fn, [frameSkip], [options])
2430
- *
2431
- * Also supported:
2432
- * - throttleRaf(fn, [options]) // frameSkip defaults to 0
2433
- *
2434
- * Executes at most once every `(frameSkip + 1)` frames.
2435
- *
2436
- * Argument behavior while throttled:
2437
- * - trailing=true (default): uses the latest args/this seen while waiting
2438
- * - trailing=false: keeps the first args/this and ignores later calls until it fires
2439
- *
2440
- * AbortSignal:
2441
- * - If `signal` is provided, abort will cancel any pending scheduled execution.
2442
- * - Listener is attached only while a call is pending.
2443
- *
2444
- * @template {(...args: any[]) => any} T
2445
- * @param {T} fn
2446
- * @param {number|{signal?: AbortSignal, trailing?: boolean}} [frameSkipOrOptions=0]
2447
- * @param {{signal?: AbortSignal, trailing?: boolean}} [maybeOptions]
2448
- * @returns {T & { cancel: () => void, flush: () => void }}
2449
- */
2450
- export function throttleRaf(fn, frameSkipOrOptions = 0, maybeOptions) {
2451
- if (typeof fn !== 'function') {
2452
- throw new TypeError(`Expected a function, got: ${typeof fn}`);
2453
- }
2454
-
2455
- const frameSkip = typeof frameSkipOrOptions === 'number' ? frameSkipOrOptions : 0;
2456
-
2457
- const options = isPlainOptions(frameSkipOrOptions)
2458
- ? frameSkipOrOptions
2459
- : isPlainOptions(maybeOptions)
2460
- ? maybeOptions
2461
- : {};
2462
-
2463
- const signal = options.signal;
2464
- const trailing = options.trailing ?? true;
2465
-
2466
- // Normalize once: int >= 0
2467
- const skip = Math.max(0, frameSkip | 0);
2468
-
2469
- let scheduled = false;
2470
- let rafId = 0;
2471
-
2472
- /** @type {any[] | null} */
2473
- let lastArgs = null;
2474
- /** @type {any | null} */
2475
- let lastThis = null;
2476
-
2477
- // countdown for skip-path only
2478
- let remaining = skip;
2479
-
2480
- const abort = pendingAbort(signal, () => cancel());
2481
-
2482
- const clearState = () => {
2483
- scheduled = false;
2484
-
2485
- if (rafId) cancelAnimationFrame(rafId);
2486
- rafId = 0;
2487
-
2488
- remaining = skip;
2489
-
2490
- lastArgs = null;
2491
- lastThis = null;
2492
-
2493
- abort.remove();
2494
- };
2495
-
2496
- const cancel = () => {
2497
- clearState();
2498
- };
2499
-
2500
- const invoke = () => {
2501
- if (!lastArgs) return;
2502
-
2503
- const args = lastArgs;
2504
- const ctx = lastThis;
2505
-
2506
- // Clear first to aid GC + prevent re-entrancy oddities
2507
- lastArgs = null;
2508
- lastThis = null;
2509
-
2510
- abort.remove();
2511
- fn.apply(ctx, args);
2512
- };
2513
-
2514
- const fire = () => {
2515
- scheduled = false;
2516
- rafId = 0;
2517
- remaining = skip;
2518
- invoke();
2519
- };
2520
-
2521
- const tickSkip = () => {
2522
- if (!scheduled) return;
2523
-
2524
- if (signal?.aborted) {
2525
- cancel();
2526
- return;
2527
- }
2528
-
2529
- if (remaining === 0) {
2530
- fire();
2531
- return;
2532
- }
2533
-
2534
- remaining -= 1;
2535
- rafId = requestAnimationFrame(tickSkip);
2536
- };
2537
-
2538
- // Fast path for skip === 0
2539
- const tick0 = () => {
2540
- if (!scheduled) return;
2541
-
2542
- if (signal?.aborted) {
2543
- cancel();
2544
- return;
2545
- }
2546
-
2547
- fire();
2548
- };
2549
-
2550
- const schedule =
2551
- skip === 0
2552
- ? () => {
2553
- scheduled = true;
2554
- abort.add();
2555
- rafId = requestAnimationFrame(tick0);
2556
- }
2557
- : () => {
2558
- scheduled = true;
2559
- remaining = skip;
2560
- abort.add();
2561
- rafId = requestAnimationFrame(tickSkip);
2562
- };
2563
-
2564
- /** @type {any} */
2565
- const throttled = function (...args) {
2566
- if (signal?.aborted) return;
2567
-
2568
- // While waiting, keep latest args only if trailing=true
2569
- if (!scheduled || trailing) {
2570
- lastArgs = args;
2571
- lastThis = this;
2572
- }
2573
-
2574
- if (scheduled) return;
2575
- schedule();
2576
- };
2577
-
2578
- throttled.cancel = cancel;
2579
-
2580
- throttled.flush = () => {
2581
- if (!scheduled) return;
2582
-
2583
- if (signal?.aborted) {
2584
- cancel();
2585
- return;
2586
- }
2587
-
2588
- // Cancel RAF and invoke immediately
2589
- scheduled = false;
2590
- if (rafId) cancelAnimationFrame(rafId);
2591
- rafId = 0;
2592
- remaining = skip;
2593
-
2594
- invoke();
2595
- };
2596
-
2597
- // If already aborted at creation time, ensure clean slate.
2598
- if (signal?.aborted) cancel();
2599
-
2600
- return throttled;
2601
- }
2602
- ===== END FILE: raf\throttleRaf.js =====
2603
-
2604
-
2605
- ===== FILE: raf\waitForRaf.js =====
2606
-
2607
- // ./raf/waitForRaf.js
2608
- import { parseDuration } from '../parseDuration.js';
2609
- import { attachAbort, createAbortError } from '../abort.js';
2610
-
2611
- /**
2612
- * Waits for a condition to return truthy, polling each frame.
2613
- *
2614
- * Timing model:
2615
- * - Evaluates `condition()` once per animation frame until it returns truthy.
2616
- * - If `timeout` is provided, timeout is measured in RAF time (frame timestamps).
2617
- *
2618
- * @param {Function} condition - Function returning truthy when complete
2619
- * @param {Object} [options]
2620
- * @param {string|number} [options.timeout] - Optional max time to wait
2621
- * @param {AbortSignal} [options.signal] - Optional AbortSignal to cancel waiting
2622
- * @param {boolean} [options.immediate=false] - If true, evaluate condition immediately before first frame
2623
- * @returns {Promise<void>} Resolves when condition is met, rejects on timeout/abort
2624
- */
2625
- export function waitForRaf(condition, { timeout, signal, immediate = false } = {}) {
2626
- return new Promise((resolve, reject) => {
2627
- if (typeof condition !== 'function') {
2628
- reject(new TypeError(`waitForRaf: condition must be a function, got: ${typeof condition}`));
2629
- return;
2630
- }
2631
-
2632
- if (signal?.aborted) {
2633
- reject(createAbortError());
2634
- return;
2635
- }
2636
-
2637
- const timeoutMs = timeout != null ? Math.max(0, parseDuration(timeout)) : null;
2638
-
2639
- let rafId = 0;
2640
- let startedAt = null; // RAF timestamp of first tick (or immediate tick reference)
2641
-
2642
- const cleanup = () => {
2643
- if (rafId) cancelAnimationFrame(rafId);
2644
- rafId = 0;
2645
- cleanupAbort();
2646
- };
2647
-
2648
- const onAbort = () => {
2649
- cleanup();
2650
- reject(createAbortError());
2651
- };
2652
-
2653
- const cleanupAbort = attachAbort(signal, onAbort);
2654
-
2655
- const evaluateCondition = () => {
2656
- try {
2657
- return !!condition();
2658
- } catch (err) {
2659
- cleanup();
2660
- reject(err);
2661
- return null;
2662
- }
2663
- };
2664
-
2665
- // Optional immediate evaluation (before any frames)
2666
- if (immediate) {
2667
- const ok = evaluateCondition();
2668
- if (ok === null) return;
2669
- if (ok) {
2670
- cleanup();
2671
- resolve();
2672
- return;
2673
- }
2674
-
2675
- // If timeout is explicitly 0, and immediate failed, we can fail fast.
2676
- if (timeoutMs === 0) {
2677
- cleanup();
2678
- reject(new Error('waitForRaf timed out'));
2679
- return;
2680
- }
2681
- }
2682
-
2683
- const tick = (ts) => {
2684
- // Initialize start time using the same clock as `ts`
2685
- if (startedAt == null) startedAt = ts;
2686
-
2687
- const ok = evaluateCondition();
2688
- if (ok === null) return;
2689
-
2690
- if (ok) {
2691
- cleanup();
2692
- resolve();
2693
- return;
2694
- }
2695
-
2696
- if (timeoutMs != null && ts - startedAt >= timeoutMs) {
2697
- cleanup();
2698
- reject(new Error('waitForRaf timed out'));
2699
- return;
2700
- }
2701
-
2702
- rafId = requestAnimationFrame(tick);
2703
- };
2704
-
2705
- rafId = requestAnimationFrame(tick);
2706
- });
2707
- }
2708
- ===== END FILE: raf\waitForRaf.js =====
2709
-