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/src/index.js CHANGED
@@ -11,6 +11,7 @@ export { after } from './after.js';
11
11
  export { every } from './every.js';
12
12
 
13
13
 
14
+ export { sleep } from './sleep.js';
14
15
  export { waitFor } from './waitFor.js';
15
16
  export { retry } from './retry.js';
16
17
 
@@ -1,6 +1,6 @@
1
1
  // ./raf/waitForRaf.js
2
2
  import { parseDuration } from '../parseDuration.js';
3
- import { attachAbort, createAbortError } from '../abort.js';
3
+ import { attachAbort, abortReason } from '../abort.js';
4
4
 
5
5
  /**
6
6
  * Waits for a condition to return truthy, polling each frame.
@@ -12,7 +12,7 @@ import { attachAbort, createAbortError } from '../abort.js';
12
12
  * @param {Function} condition - Function returning truthy when complete
13
13
  * @param {Object} [options]
14
14
  * @param {string|number} [options.timeout] - Optional max time to wait
15
- * @param {AbortSignal} [options.signal] - Optional AbortSignal to cancel waiting
15
+ * @param {AbortSignal} [options.signal] - Optional AbortSignal; rejects with `signal.reason`
16
16
  * @param {boolean} [options.immediate=false] - If true, evaluate condition immediately before first frame
17
17
  * @returns {Promise<void>} Resolves when condition is met, rejects on timeout/abort
18
18
  */
@@ -24,7 +24,7 @@ export function waitForRaf(condition, { timeout, signal, immediate = false } = {
24
24
  }
25
25
 
26
26
  if (signal?.aborted) {
27
- reject(createAbortError());
27
+ reject(abortReason(signal));
28
28
  return;
29
29
  }
30
30
 
@@ -41,7 +41,7 @@ export function waitForRaf(condition, { timeout, signal, immediate = false } = {
41
41
 
42
42
  const onAbort = () => {
43
43
  cleanup();
44
- reject(createAbortError());
44
+ reject(abortReason(signal));
45
45
  };
46
46
 
47
47
  const cleanupAbort = attachAbort(signal, onAbort);
package/src/retry.js CHANGED
@@ -1,25 +1,58 @@
1
1
  // ./src/retry.js
2
2
  import { parseDuration } from './parseDuration.js';
3
- import { attachAbort, createAbortError } from './abort.js';
3
+ import { abortReason } from './abort.js';
4
+ import { now as defaultNow } from './now.js';
5
+ import { sleep as defaultSleep, toDelay } from './sleep.js';
4
6
 
5
7
  /**
6
- * Retries a promise-returning function with delays.
8
+ * Retries a (possibly async) function with delays between attempts.
7
9
  *
8
- * @param {(attemptIndex: number) => Promise<any>} fn - async function
10
+ * Attempt numbers are 0-based everywhere (`fn`, hooks, predicates).
11
+ *
12
+ * Outcome:
13
+ * - Resolves with the first successful result.
14
+ * - When retries stop (attempts exhausted, `timeout` reached, or
15
+ * `shouldRetry` returned false) it rejects with the last failure:
16
+ * the last thrown error as-is, or, when the last attempt resolved with a
17
+ * result rejected by `isSuccess`, a `RetryError` (`name: 'RetryError'`)
18
+ * carrying `.result` and `.attempts`.
19
+ * - On abort it rejects with `signal.reason` (an AbortError by default).
20
+ *
21
+ * @template T
22
+ * @param {(attempt: number) => T | Promise<T>} fn - sync or async function
9
23
  * @param {Object} [options]
10
- * @param {number} [options.attempts=3] - total attempts (including the first)
11
- * @param {string|number} [options.delay='500ms'] - base delay between retries
12
- * @param {boolean} [options.backoff=false] - exponential backoff if true
13
- * @param {number} [options.factor=2] - backoff multiplier (only if backoff=true)
14
- * @param {string|number} [options.maxDelay] - clamp delay to this max
15
- * @param {boolean|'full'|'equal'|'decorrelated'} [options.jitter=false] - jitter strategy
16
- * @param {AbortSignal} [options.signal] - optional AbortSignal to cancel retries
17
- * @param {() => number} [options.random=Math.random] - injectable RNG for tests
24
+ * @param {number} [options.attempts=3] - total attempts including the first (`Infinity` allowed)
25
+ * @param {string|number} [options.delay='500ms'] - base delay between attempts
26
+ * @param {boolean|'fixed'|'linear'|'exponential'} [options.backoff=false]
27
+ * Delay growth per retry n (0-based): fixed (false) = delay,
28
+ * linear = delay*(n+1), exponential (true) = delay*factor^n.
29
+ * @param {number} [options.factor=2] - exponential multiplier
30
+ * @param {string|number} [options.maxDelay] - cap for each computed delay
31
+ * @param {boolean|number|'full'|'equal'|'decorrelated'} [options.jitter=false] - jitter strategy.
32
+ * A number j in [0, 1] applies proportional �j jitter:
33
+ * delay * (1 + (random()*2 - 1) * j), after the maxDelay cap and then
34
+ * re-capped by maxDelay, clamped to >= 0 and rounded. Other numbers
35
+ * (or NaN) reject with a RangeError before any attempt.
36
+ * `delayFirst` is never jittered.
37
+ * @param {boolean|string|number} [options.delayFirst=false]
38
+ * Wait before the first attempt (`true` = `delay`, or an explicit duration).
39
+ * @param {string|number} [options.timeout] - overall deadline measured from the call.
40
+ * A retry is skipped when its wait would end past the deadline; the first
41
+ * attempt always runs and an in-flight attempt is never interrupted.
42
+ * @param {AbortSignal} [options.signal] - cancels waiting and further attempts
43
+ * @param {(result: T, attempt: number) => boolean | Promise<boolean>} [options.isSuccess]
44
+ * Treat a resolved result as a failure (and retry) when this returns false.
18
45
  * @param {(err: any, attempt: number) => boolean | Promise<boolean>} [options.shouldRetry]
19
- * Predicate deciding whether to retry after a failure.
46
+ * Return false to stop retrying after a failure.
47
+ * @param {(attempt: number, elapsedMs: number) => void | Promise<void>} [options.onAttempt]
48
+ * Called before every attempt.
20
49
  * @param {(err: any, attempt: number, delayMs: number) => void | Promise<void>} [options.onRetry]
21
- * Hook invoked after deciding to retry and before waiting.
22
- * @returns {Promise<any>}
50
+ * Called after deciding to retry and before waiting.
51
+ * @param {(ms: number, options: { signal?: AbortSignal }) => Promise<void>} [options.sleep]
52
+ * Injectable sleep (e.g. for fake-timer tests).
53
+ * @param {() => number} [options.now] - injectable clock used for `timeout`
54
+ * @param {() => number} [options.random=Math.random] - injectable RNG for tests
55
+ * @returns {Promise<T>}
23
56
  */
24
57
  export async function retry(
25
58
  fn,
@@ -30,64 +63,99 @@ export async function retry(
30
63
  factor = 2,
31
64
  maxDelay,
32
65
  jitter = false,
66
+ delayFirst = false,
67
+ timeout,
33
68
  signal,
34
- random = Math.random,
69
+ isSuccess,
35
70
  shouldRetry,
71
+ onAttempt,
36
72
  onRetry,
73
+ sleep = defaultSleep,
74
+ now = defaultNow,
75
+ random = Math.random,
37
76
  } = {}
38
77
  ) {
39
78
  if (typeof fn !== 'function') throw new TypeError('retry: fn must be a function');
40
79
 
41
- const totalAttempts = Math.max(1, attempts | 0);
80
+ const totalAttempts = attempts === Infinity ? Infinity : Math.max(1, attempts | 0);
42
81
 
43
- if (signal?.aborted) throw createAbortError();
82
+ const throwIfAborted = () => {
83
+ if (signal?.aborted) throw abortReason(signal);
84
+ };
85
+ throwIfAborted();
86
+
87
+ if (typeof jitter === 'number' && !(jitter >= 0 && jitter <= 1)) {
88
+ throw new RangeError(`retry: numeric jitter must be within [0, 1], got: ${jitter}`);
89
+ }
44
90
 
45
91
  const baseDelay = parseDuration(delay);
46
92
  const maxDelayMs = maxDelay != null ? parseDuration(maxDelay) : Infinity;
93
+ const deadline = timeout != null ? parseDuration(timeout) : Infinity;
94
+ const mode = backoff === true ? 'exponential' : backoff || 'fixed';
95
+ const start = now();
96
+ const elapsed = () => now() - start;
97
+
98
+ const wait = async (ms) => {
99
+ await sleep(ms, { signal });
100
+ throwIfAborted(); // custom sleeps may ignore the signal
101
+ };
102
+
103
+ if (delayFirst) await wait(toDelay(delayFirst === true ? baseDelay : delayFirst));
47
104
 
48
105
  // decorrelated jitter needs to remember prior sleep
49
106
  let prevSleep = Math.min(baseDelay, maxDelayMs);
50
107
 
51
- for (let attempt = 0; attempt < totalAttempts; attempt++) {
52
- if (signal?.aborted) throw createAbortError();
108
+ for (let attempt = 0; ; attempt++) {
109
+ throwIfAborted();
110
+ if (onAttempt) await onAttempt(attempt, elapsed());
53
111
 
112
+ let failure;
54
113
  try {
55
- return await fn(attempt);
114
+ const result = await fn(attempt);
115
+ if (!isSuccess || (await isSuccess(result, attempt))) return result;
116
+ failure = new RetryError(result, attempt + 1);
56
117
  } catch (err) {
57
- const lastAttempt = attempt === totalAttempts - 1;
58
- if (lastAttempt) throw err;
59
-
60
- // Decide if we should retry
61
- if (shouldRetry) {
62
- const ok = await shouldRetry(err, attempt);
63
- if (!ok) throw err;
64
- }
65
-
66
- const expDelay = backoff ? baseDelay * Math.pow(factor, attempt) : baseDelay;
67
-
68
- const sleep = computeSleep({
69
- expDelay,
70
- baseDelay,
71
- maxDelayMs,
72
- jitter,
73
- random,
74
- prevSleep,
75
- });
76
-
77
- prevSleep = sleep;
78
-
79
- // Notify caller we're retrying (before waiting)
80
- if (onRetry) {
81
- await onRetry(err, attempt, sleep);
82
- }
83
-
84
- await waitWithAbort(sleep, signal);
118
+ failure = err;
85
119
  }
120
+
121
+ if (attempt + 1 >= totalAttempts) throw failure;
122
+ if (shouldRetry && !(await shouldRetry(failure, attempt))) throw failure;
123
+
124
+ const growth =
125
+ mode === 'exponential' ? Math.pow(factor, attempt) :
126
+ mode === 'linear' ? attempt + 1 :
127
+ 1;
128
+
129
+ const ms = toDelay(Math.round(computeSleep({
130
+ expDelay: baseDelay * growth,
131
+ baseDelay,
132
+ maxDelayMs,
133
+ jitter,
134
+ random,
135
+ prevSleep,
136
+ })));
137
+ prevSleep = ms;
138
+
139
+ // Don't begin a wait whose next attempt would start past the deadline.
140
+ if (elapsed() + ms > deadline) throw failure;
141
+
142
+ if (onRetry) await onRetry(failure, attempt, ms);
143
+
144
+ await wait(ms);
86
145
  }
146
+ }
87
147
 
88
- // Unreachable, but keeps type checkers happy.
89
- // eslint-disable-next-line no-throw-literal
90
- throw new Error('retry: exhausted attempts unexpectedly');
148
+ /**
149
+ * Rejection used when the final attempt resolved with a result that
150
+ * `isSuccess` rejected. Check with `err.name === 'RetryError'`.
151
+ */
152
+ class RetryError extends Error {
153
+ constructor(result, attempts) {
154
+ super(`retry: unsuccessful result after ${attempts} attempt(s)`);
155
+ this.name = 'RetryError';
156
+ this.result = result;
157
+ this.attempts = attempts;
158
+ }
91
159
  }
92
160
 
93
161
  /**
@@ -98,12 +166,18 @@ export async function retry(
98
166
  * - 'full': random(0, cap)
99
167
  * - 'equal': cap/2 + random(0, cap/2)
100
168
  * - 'decorrelated': random(baseDelay, prevSleep*3) (clamped)
169
+ * - number j: cap * (1 � j), re-capped by maxDelay, >= 0
101
170
  */
102
171
  function computeSleep({ expDelay, baseDelay, maxDelayMs, jitter, random, prevSleep }) {
103
172
  const cap = Math.min(expDelay, maxDelayMs);
104
173
 
105
174
  if (!jitter) return cap;
106
175
 
176
+ if (typeof jitter === 'number') {
177
+ const spread = randBetween(-1, 1, random) * jitter;
178
+ return Math.min(maxDelayMs, Math.max(0, cap * (1 + spread)));
179
+ }
180
+
107
181
  const mode = jitter === true ? 'full' : jitter;
108
182
 
109
183
  if (mode === 'full') {
@@ -129,36 +203,3 @@ function randBetween(min, max, random) {
129
203
  const t = Number.isFinite(r) ? Math.min(1, Math.max(0, r)) : 0;
130
204
  return min + (max - min) * t;
131
205
  }
132
-
133
- /**
134
- * Wait helper that supports AbortSignal.
135
- * Rejects with AbortError if aborted during delay.
136
- */
137
- function waitWithAbort(ms, signal) {
138
- return new Promise((resolve, reject) => {
139
- if (signal?.aborted) {
140
- reject(createAbortError());
141
- return;
142
- }
143
-
144
- let timeoutId = 0;
145
-
146
- const cleanup = () => {
147
- if (timeoutId) clearTimeout(timeoutId);
148
- timeoutId = 0;
149
- cleanupAbort();
150
- };
151
-
152
- const onAbort = () => {
153
- cleanup();
154
- reject(createAbortError());
155
- };
156
-
157
- const cleanupAbort = attachAbort(signal, onAbort);
158
-
159
- timeoutId = setTimeout(() => {
160
- cleanup();
161
- resolve();
162
- }, ms);
163
- });
164
- }
package/src/sleep.js ADDED
@@ -0,0 +1,58 @@
1
+ // ./src/sleep.js
2
+ import { parseDuration } from './parseDuration.js';
3
+ import { attachAbort, abortReason } from './abort.js';
4
+
5
+ // Largest delay setTimeout can hold; larger values overflow and fire immediately.
6
+ const MAX_DELAY = 2_147_483_647;
7
+
8
+ /**
9
+ * Normalizes a duration to a setTimeout-safe delay in ms.
10
+ * - Strings are parsed ("500ms", "1s", "1.5m", "1h"); invalid strings throw.
11
+ * - Numbers behave like setTimeout: NaN and negative values clamp to 0.
12
+ * - Values above setTimeout's 32-bit limit (including Infinity) are capped at
13
+ * 2147483647 ms (~24.8 days) instead of overflowing and firing immediately.
14
+ *
15
+ * @param {string|number|null|undefined} duration
16
+ * @returns {number}
17
+ */
18
+ export function toDelay(duration) {
19
+ if (duration == null) return 0;
20
+ const ms = typeof duration === 'number' ? duration : parseDuration(duration);
21
+ return ms > 0 ? Math.min(ms, MAX_DELAY) : 0;
22
+ }
23
+
24
+ /**
25
+ * Promise-based delay: `await sleep('500ms')`.
26
+ *
27
+ * - Accepts the same durations as the rest of TimeoutFlow ("500ms", "1s", 250).
28
+ * - Numbers behave like setTimeout: NaN / negative become 0; huge values
29
+ * (including Infinity) are capped at ~24.8 days rather than firing at once.
30
+ * - Invalid duration strings reject with an Error (never throw synchronously).
31
+ * - With `signal`, rejects with `signal.reason` (an AbortError by default)
32
+ * and clears its timer; an already-aborted signal rejects immediately.
33
+ *
34
+ * @param {string|number} [duration=0]
35
+ * @param {Object} [options]
36
+ * @param {AbortSignal} [options.signal]
37
+ * @returns {Promise<void>}
38
+ */
39
+ export function sleep(duration = 0, { signal } = {}) {
40
+ return new Promise((resolve, reject) => {
41
+ const ms = toDelay(duration);
42
+
43
+ if (signal?.aborted) {
44
+ reject(abortReason(signal));
45
+ return;
46
+ }
47
+
48
+ const cleanupAbort = attachAbort(signal, () => {
49
+ clearTimeout(timer);
50
+ reject(abortReason(signal));
51
+ });
52
+
53
+ const timer = setTimeout(() => {
54
+ cleanupAbort();
55
+ resolve();
56
+ }, ms);
57
+ });
58
+ }
package/src/waitFor.js CHANGED
@@ -1,77 +1,96 @@
1
1
  // ./src/waitFor.js
2
2
 
3
- import { parseDuration } from './parseDuration.js';
4
- import { attachAbort, createAbortError } from './abort.js';
5
- import { now } from './now.js'
3
+ import { attachAbort, abortReason } from './abort.js';
4
+ import { toDelay } from './sleep.js';
6
5
 
7
6
 
8
7
  /**
9
- * Waits for a condition to become true, polling at intervals.
8
+ * Waits for a condition to become truthy, polling at intervals.
10
9
  *
11
- * @param {Function} condition - returns truthy when satisfied
10
+ * Timing model:
11
+ * - With `immediate: false` (default) the first check runs after `interval`.
12
+ * - The next check is scheduled `interval` after the previous one finishes,
13
+ * so async conditions never overlap.
14
+ * - `timeout` is measured from the call and enforced by its own timer, so it
15
+ * is not rounded up to the next poll. At the deadline a sync condition gets
16
+ * one final check (success at exactly `timeout` counts, like `>=`); an async
17
+ * check still pending at the deadline is abandoned and the promise rejects.
18
+ *
19
+ * @template T
20
+ * @param {() => T | Promise<T>} condition - sync or async; truthy when satisfied
12
21
  * @param {Object} [options] - optional polling control
13
- * @param {string|number} [options.interval='250ms'] - poll frequency
14
- * @param {string|number} [options.timeout] - max wait time
22
+ * @param {string|number} [options.interval='250ms'] - delay between checks
23
+ * @param {string|number} [options.timeout] - max wait time; rejects with an
24
+ * Error named 'TimeoutError' (message 'waitFor timed out')
15
25
  * @param {boolean} [options.immediate=false] - If true, evaluate condition immediately
16
- * @param {AbortSignal} [options.signal] - Optional AbortSignal to cancel waiting
17
- * @returns {Promise<void>}
26
+ * @param {AbortSignal} [options.signal] - rejects with `signal.reason` on abort
27
+ * @returns {Promise<T>} resolves with the condition's truthy value
18
28
  */
19
29
  export function waitFor(condition, { interval = '250ms', timeout, immediate = false, signal } = {}) {
20
30
  return new Promise((resolve, reject) => {
21
31
  if (signal?.aborted) {
22
- reject(createAbortError());
32
+ reject(abortReason(signal));
23
33
  return;
24
34
  }
25
35
 
26
- const start = now();
27
-
28
- const intervalMs = typeof interval === 'string' ? parseDuration(interval) : interval;
29
- const timeoutMs = timeout != null ? parseDuration(timeout) : null;
36
+ const intervalMs = toDelay(interval);
37
+ const timeoutMs = timeout != null ? toDelay(timeout) : null;
30
38
 
31
- let poller = null;
39
+ let done = false;
40
+ let pending = false;
41
+ let poller = 0;
42
+ let deadline = 0;
32
43
 
33
- const cleanup = () => {
34
- if (poller != null) {
35
- clearInterval(poller);
36
- poller = null;
37
- }
44
+ const finish = (settle, value) => {
45
+ if (done) return;
46
+ done = true;
47
+ clearTimeout(poller);
48
+ clearTimeout(deadline);
38
49
  cleanupAbort();
50
+ settle(value);
39
51
  };
40
52
 
41
- const onAbort = () => {
42
- cleanup();
43
- reject(createAbortError());
44
- };
45
-
46
- const cleanupAbort = attachAbort(signal, onAbort);
47
-
48
- const check = () => {
49
- let ok = false;
53
+ const cleanupAbort = attachAbort(signal, () => finish(reject, abortReason(signal)));
50
54
 
55
+ const check = async () => {
56
+ let value;
57
+ pending = true;
51
58
  try {
52
- ok = !!condition();
59
+ value = await condition();
53
60
  } catch (err) {
54
- cleanup();
55
- reject(err);
61
+ finish(reject, err);
56
62
  return;
63
+ } finally {
64
+ pending = false;
57
65
  }
58
-
59
- if (ok) {
60
- cleanup();
61
- resolve();
62
- return;
63
- }
64
-
65
- if (timeoutMs != null && now() - start >= timeoutMs) {
66
- cleanup();
67
- reject(new Error('waitFor timed out'));
68
- }
66
+ if (done) return;
67
+ if (value) finish(resolve, value);
68
+ else poller = setTimeout(check, intervalMs);
69
69
  };
70
70
 
71
- // Only evaluate immediately if explicitly requested
72
71
  if (immediate) check();
72
+ else poller = setTimeout(check, intervalMs);
73
73
 
74
- // Schedule exactly once
75
- poller = setInterval(check, intervalMs);
74
+ if (timeoutMs != null) {
75
+ deadline = setTimeout(() => {
76
+ if (!pending) {
77
+ // Final check at the deadline (sync results only).
78
+ let value;
79
+ try {
80
+ value = condition();
81
+ } catch (err) {
82
+ finish(reject, err);
83
+ return;
84
+ }
85
+ if (value && typeof value.then !== 'function') {
86
+ finish(resolve, value);
87
+ return;
88
+ }
89
+ }
90
+ const err = new Error('waitFor timed out');
91
+ err.name = 'TimeoutError';
92
+ finish(reject, err);
93
+ }, timeoutMs);
94
+ }
76
95
  });
77
- }
96
+ }
package/types/abort.d.ts CHANGED
@@ -1,31 +1,40 @@
1
- /**
2
- * Attach an AbortSignal listener and return a cleanup function.
3
- * - If `signal` is missing, returns a no-op cleanup.
4
- * - If already aborted, calls `onAbort()` immediately and returns a no-op cleanup.
5
- *
6
- * @param {AbortSignal | null | undefined} signal
7
- * @param {() => void} onAbort
8
- * @returns {() => void} cleanup
9
- */
10
- export function attachAbort(signal: AbortSignal | null | undefined, onAbort: () => void): () => void;
11
- /**
12
- * Manage AbortSignal listener lifecycle for "pending work" cases.
13
- * Call `add()` when work becomes pending and `remove()` when it’s resolved/canceled.
14
- *
15
- * @param {AbortSignal | null | undefined} signal
16
- * @param {() => void} onAbort
17
- * @returns {{ add: () => void, remove: () => void, reset: () => void }}
18
- */
19
- export function pendingAbort(signal: AbortSignal | null | undefined, onAbort: () => void): {
20
- add: () => void;
21
- remove: () => void;
22
- reset: () => void;
23
- };
24
- /**
25
- * Standardized AbortError factory.
26
- * Works in browsers and Node runtimes that may not have DOMException.
27
- *
28
- * We resolve the best implementation once at module load time.
29
- * This avoids feature detection in the hot path.
30
- */
31
- export let createAbortError: any;
1
+ /**
2
+ * Attach an AbortSignal listener and return a cleanup function.
3
+ * - If `signal` is missing, returns a no-op cleanup.
4
+ * - If already aborted, calls `onAbort()` immediately and returns a no-op cleanup.
5
+ *
6
+ * @param {AbortSignal | null | undefined} signal
7
+ * @param {() => void} onAbort
8
+ * @returns {() => void} cleanup
9
+ */
10
+ export function attachAbort(signal: AbortSignal | null | undefined, onAbort: () => void): () => void;
11
+ /**
12
+ * Manage AbortSignal listener lifecycle for "pending work" cases.
13
+ * Call `add()` when work becomes pending and `remove()` when it’s resolved/canceled.
14
+ *
15
+ * @param {AbortSignal | null | undefined} signal
16
+ * @param {() => void} onAbort
17
+ * @returns {{ add: () => void, remove: () => void, reset: () => void }}
18
+ */
19
+ export function pendingAbort(signal: AbortSignal | null | undefined, onAbort: () => void): {
20
+ add: () => void;
21
+ remove: () => void;
22
+ reset: () => void;
23
+ };
24
+ /**
25
+ * The error an aborted operation should reject with: the signal's own
26
+ * `reason` (what `fetch()` and other web APIs use), falling back to a
27
+ * standard AbortError for runtimes without `AbortSignal.reason`.
28
+ *
29
+ * @param {AbortSignal | null | undefined} signal
30
+ * @returns {any}
31
+ */
32
+ export function abortReason(signal: AbortSignal | null | undefined): any;
33
+ /**
34
+ * Standardized AbortError factory.
35
+ * Works in browsers and Node runtimes that may not have DOMException.
36
+ *
37
+ * We resolve the best implementation once at module load time.
38
+ * This avoids feature detection in the hot path.
39
+ */
40
+ export let createAbortError: any;
package/types/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
- export { parseDuration } from "./parseDuration.js";
2
- export { flow } from "./TimeoutFlow.js";
3
- export { throttle } from "./throttle.js";
4
- export { debounce } from "./debounce.js";
5
- export { after } from "./after.js";
6
- export { every } from "./every.js";
7
- export { waitFor } from "./waitFor.js";
8
- export { retry } from "./retry.js";
9
- export { afterRaf, everyRaf, debounceRaf, throttleRaf, waitForRaf } from "./raf/index.js";
1
+ export { parseDuration } from "./parseDuration.js";
2
+ export { flow } from "./TimeoutFlow.js";
3
+ export { throttle } from "./throttle.js";
4
+ export { debounce } from "./debounce.js";
5
+ export { after } from "./after.js";
6
+ export { every } from "./every.js";
7
+ export { sleep } from "./sleep.js";
8
+ export { waitFor } from "./waitFor.js";
9
+ export { retry } from "./retry.js";
10
+ export { afterRaf, everyRaf, debounceRaf, throttleRaf, waitForRaf } from "./raf/index.js";
@@ -1,19 +1,19 @@
1
- /**
2
- * Waits for a condition to return truthy, polling each frame.
3
- *
4
- * Timing model:
5
- * - Evaluates `condition()` once per animation frame until it returns truthy.
6
- * - If `timeout` is provided, timeout is measured in RAF time (frame timestamps).
7
- *
8
- * @param {Function} condition - Function returning truthy when complete
9
- * @param {Object} [options]
10
- * @param {string|number} [options.timeout] - Optional max time to wait
11
- * @param {AbortSignal} [options.signal] - Optional AbortSignal to cancel waiting
12
- * @param {boolean} [options.immediate=false] - If true, evaluate condition immediately before first frame
13
- * @returns {Promise<void>} Resolves when condition is met, rejects on timeout/abort
14
- */
15
- export function waitForRaf(condition: Function, { timeout, signal, immediate }?: {
16
- timeout?: string | number | undefined;
17
- signal?: AbortSignal | undefined;
18
- immediate?: boolean | undefined;
19
- }): Promise<void>;
1
+ /**
2
+ * Waits for a condition to return truthy, polling each frame.
3
+ *
4
+ * Timing model:
5
+ * - Evaluates `condition()` once per animation frame until it returns truthy.
6
+ * - If `timeout` is provided, timeout is measured in RAF time (frame timestamps).
7
+ *
8
+ * @param {Function} condition - Function returning truthy when complete
9
+ * @param {Object} [options]
10
+ * @param {string|number} [options.timeout] - Optional max time to wait
11
+ * @param {AbortSignal} [options.signal] - Optional AbortSignal; rejects with `signal.reason`
12
+ * @param {boolean} [options.immediate=false] - If true, evaluate condition immediately before first frame
13
+ * @returns {Promise<void>} Resolves when condition is met, rejects on timeout/abort
14
+ */
15
+ export function waitForRaf(condition: Function, { timeout, signal, immediate }?: {
16
+ timeout?: string | number | undefined;
17
+ signal?: AbortSignal | undefined;
18
+ immediate?: boolean | undefined;
19
+ }): Promise<void>;