timeout-flow 0.0.17 → 0.0.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +239 -144
- package/dist/timeout-flow.min.js +1 -6
- package/package.json +2 -1
- package/src/AfterTimer.js +64 -3
- package/src/EveryTimer.js +139 -18
- package/src/TimeoutFlow.js +291 -118
- package/src/TimerBase.js +81 -23
- package/src/abort.js +75 -0
- package/src/after.js +20 -71
- package/src/context-js.bat +58 -0
- package/src/context.txt +2604 -0
- package/src/debounce.js +90 -24
- package/src/every.js +19 -105
- package/src/index.js +7 -2
- package/src/now.js +23 -0
- package/src/parseDuration.js +22 -20
- package/src/raf/afterRaf.js +198 -66
- package/src/raf/debounceRaf.js +108 -26
- package/src/raf/everyRaf.js +278 -67
- package/src/raf/index.js +26 -6
- package/src/raf/throttleRaf.js +175 -31
- package/src/raf/waitForRaf.js +82 -14
- package/src/resolveDelayAndFn.js +69 -7
- package/src/retry.js +152 -12
- package/src/throttle.js +120 -26
- package/src/waitFor.js +68 -24
- package/types/AfterTimer.d.ts +8 -2
- package/types/EveryTimer.d.ts +21 -4
- package/types/TimeoutFlow.d.ts +6 -18
- package/types/TimerBase.d.ts +15 -4
- package/types/abort.d.ts +31 -0
- package/types/after.d.ts +22 -22
- package/types/debounce.d.ts +28 -6
- package/types/every.d.ts +20 -28
- package/types/index.d.ts +1 -1
- package/types/now.d.ts +1 -0
- package/types/raf/afterRaf.d.ts +35 -5
- package/types/raf/debounceRaf.d.ts +27 -6
- package/types/raf/everyRaf.d.ts +39 -9
- package/types/raf/index.d.ts +6 -5
- package/types/raf/throttleRaf.d.ts +33 -10
- package/types/raf/waitForRaf.d.ts +10 -4
- package/types/resolveDelayAndFn.d.ts +27 -0
- package/types/retry.d.ts +25 -8
- package/types/throttle.d.ts +28 -6
- package/types/waitFor.d.ts +11 -6
package/src/raf/throttleRaf.js
CHANGED
|
@@ -1,38 +1,182 @@
|
|
|
1
|
-
|
|
2
1
|
// ./raf/throttleRaf.js
|
|
2
|
+
import { pendingAbort } from '../abort.js';
|
|
3
|
+
|
|
4
|
+
const isPlainOptions = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
|
|
3
5
|
|
|
4
6
|
/**
|
|
5
|
-
* Throttles a function using requestAnimationFrame with optional frame skipping.
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* - frameSkip
|
|
9
|
-
*
|
|
7
|
+
* Throttles a function using `requestAnimationFrame`, with optional frame skipping.
|
|
8
|
+
*
|
|
9
|
+
* Preferred:
|
|
10
|
+
* - throttleRaf(fn, [frameSkip], [options])
|
|
11
|
+
*
|
|
12
|
+
* Also supported:
|
|
13
|
+
* - throttleRaf(fn, [options]) // frameSkip defaults to 0
|
|
14
|
+
*
|
|
15
|
+
* Executes at most once every `(frameSkip + 1)` frames.
|
|
16
|
+
*
|
|
17
|
+
* Argument behavior while throttled:
|
|
18
|
+
* - trailing=true (default): uses the latest args/this seen while waiting
|
|
19
|
+
* - trailing=false: keeps the first args/this and ignores later calls until it fires
|
|
20
|
+
*
|
|
21
|
+
* AbortSignal:
|
|
22
|
+
* - If `signal` is provided, abort will cancel any pending scheduled execution.
|
|
23
|
+
* - Listener is attached only while a call is pending.
|
|
10
24
|
*
|
|
11
|
-
* @
|
|
12
|
-
* @param {
|
|
13
|
-
* @
|
|
25
|
+
* @template {(...args: any[]) => any} T
|
|
26
|
+
* @param {T} fn
|
|
27
|
+
* @param {number|{signal?: AbortSignal, trailing?: boolean}} [frameSkipOrOptions=0]
|
|
28
|
+
* @param {{signal?: AbortSignal, trailing?: boolean}} [maybeOptions]
|
|
29
|
+
* @returns {T & { cancel: () => void, flush: () => void }}
|
|
14
30
|
*/
|
|
15
|
-
export function throttleRaf(fn,
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
31
|
+
export function throttleRaf(fn, frameSkipOrOptions = 0, maybeOptions) {
|
|
32
|
+
if (typeof fn !== 'function') {
|
|
33
|
+
throw new TypeError(`Expected a function, got: ${typeof fn}`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const frameSkip = typeof frameSkipOrOptions === 'number' ? frameSkipOrOptions : 0;
|
|
37
|
+
|
|
38
|
+
const options = isPlainOptions(frameSkipOrOptions)
|
|
39
|
+
? frameSkipOrOptions
|
|
40
|
+
: isPlainOptions(maybeOptions)
|
|
41
|
+
? maybeOptions
|
|
42
|
+
: {};
|
|
43
|
+
|
|
44
|
+
const signal = options.signal;
|
|
45
|
+
const trailing = options.trailing ?? true;
|
|
46
|
+
|
|
47
|
+
// Normalize once: int >= 0
|
|
48
|
+
const skip = Math.max(0, frameSkip | 0);
|
|
49
|
+
|
|
50
|
+
let scheduled = false;
|
|
51
|
+
let rafId = 0;
|
|
52
|
+
|
|
53
|
+
/** @type {any[] | null} */
|
|
54
|
+
let lastArgs = null;
|
|
55
|
+
/** @type {any | null} */
|
|
56
|
+
let lastThis = null;
|
|
57
|
+
|
|
58
|
+
// countdown for skip-path only
|
|
59
|
+
let remaining = skip;
|
|
60
|
+
|
|
61
|
+
const abort = pendingAbort(signal, () => cancel());
|
|
62
|
+
|
|
63
|
+
const clearState = () => {
|
|
64
|
+
scheduled = false;
|
|
65
|
+
|
|
66
|
+
if (rafId) cancelAnimationFrame(rafId);
|
|
67
|
+
rafId = 0;
|
|
68
|
+
|
|
69
|
+
remaining = skip;
|
|
70
|
+
|
|
71
|
+
lastArgs = null;
|
|
72
|
+
lastThis = null;
|
|
73
|
+
|
|
74
|
+
abort.remove();
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const cancel = () => {
|
|
78
|
+
clearState();
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const invoke = () => {
|
|
82
|
+
if (!lastArgs) return;
|
|
83
|
+
|
|
84
|
+
const args = lastArgs;
|
|
85
|
+
const ctx = lastThis;
|
|
86
|
+
|
|
87
|
+
// Clear first to aid GC + prevent re-entrancy oddities
|
|
88
|
+
lastArgs = null;
|
|
89
|
+
lastThis = null;
|
|
90
|
+
|
|
91
|
+
abort.remove();
|
|
92
|
+
fn.apply(ctx, args);
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const fire = () => {
|
|
96
|
+
scheduled = false;
|
|
97
|
+
rafId = 0;
|
|
98
|
+
remaining = skip;
|
|
99
|
+
invoke();
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const tickSkip = () => {
|
|
103
|
+
if (!scheduled) return;
|
|
104
|
+
|
|
105
|
+
if (signal?.aborted) {
|
|
106
|
+
cancel();
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (remaining === 0) {
|
|
111
|
+
fire();
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
remaining -= 1;
|
|
116
|
+
rafId = requestAnimationFrame(tickSkip);
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
// Fast path for skip === 0
|
|
120
|
+
const tick0 = () => {
|
|
121
|
+
if (!scheduled) return;
|
|
122
|
+
|
|
123
|
+
if (signal?.aborted) {
|
|
124
|
+
cancel();
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
fire();
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const schedule =
|
|
132
|
+
skip === 0
|
|
133
|
+
? () => {
|
|
24
134
|
scheduled = true;
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
fn(...lastArgs);
|
|
28
|
-
frameCount = 0;
|
|
29
|
-
scheduled = false;
|
|
30
|
-
} else {
|
|
31
|
-
frameCount++;
|
|
32
|
-
requestAnimationFrame(tick);
|
|
33
|
-
}
|
|
34
|
-
});
|
|
135
|
+
abort.add();
|
|
136
|
+
rafId = requestAnimationFrame(tick0);
|
|
35
137
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
138
|
+
: () => {
|
|
139
|
+
scheduled = true;
|
|
140
|
+
remaining = skip;
|
|
141
|
+
abort.add();
|
|
142
|
+
rafId = requestAnimationFrame(tickSkip);
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
/** @type {any} */
|
|
146
|
+
const throttled = function (...args) {
|
|
147
|
+
if (signal?.aborted) return;
|
|
148
|
+
|
|
149
|
+
// While waiting, keep latest args only if trailing=true
|
|
150
|
+
if (!scheduled || trailing) {
|
|
151
|
+
lastArgs = args;
|
|
152
|
+
lastThis = this;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (scheduled) return;
|
|
156
|
+
schedule();
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
throttled.cancel = cancel;
|
|
160
|
+
|
|
161
|
+
throttled.flush = () => {
|
|
162
|
+
if (!scheduled) return;
|
|
163
|
+
|
|
164
|
+
if (signal?.aborted) {
|
|
165
|
+
cancel();
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Cancel RAF and invoke immediately
|
|
170
|
+
scheduled = false;
|
|
171
|
+
if (rafId) cancelAnimationFrame(rafId);
|
|
172
|
+
rafId = 0;
|
|
173
|
+
remaining = skip;
|
|
174
|
+
|
|
175
|
+
invoke();
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
// If already aborted at creation time, ensure clean slate.
|
|
179
|
+
if (signal?.aborted) cancel();
|
|
180
|
+
|
|
181
|
+
return throttled;
|
|
182
|
+
}
|
package/src/raf/waitForRaf.js
CHANGED
|
@@ -1,33 +1,101 @@
|
|
|
1
1
|
// ./raf/waitForRaf.js
|
|
2
2
|
import { parseDuration } from '../parseDuration.js';
|
|
3
|
+
import { attachAbort, createAbortError } from '../abort.js';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Waits for a condition to return truthy, polling each frame.
|
|
6
|
-
*
|
|
7
|
-
*
|
|
7
|
+
*
|
|
8
|
+
* Timing model:
|
|
9
|
+
* - Evaluates `condition()` once per animation frame until it returns truthy.
|
|
10
|
+
* - If `timeout` is provided, timeout is measured in RAF time (frame timestamps).
|
|
8
11
|
*
|
|
9
12
|
* @param {Function} condition - Function returning truthy when complete
|
|
10
13
|
* @param {Object} [options]
|
|
11
14
|
* @param {string|number} [options.timeout] - Optional max time to wait
|
|
12
|
-
* @
|
|
15
|
+
* @param {AbortSignal} [options.signal] - Optional AbortSignal to cancel waiting
|
|
16
|
+
* @param {boolean} [options.immediate=false] - If true, evaluate condition immediately before first frame
|
|
17
|
+
* @returns {Promise<void>} Resolves when condition is met, rejects on timeout/abort
|
|
13
18
|
*/
|
|
14
|
-
export function waitForRaf(condition, { timeout } = {}) {
|
|
19
|
+
export function waitForRaf(condition, { timeout, signal, immediate = false } = {}) {
|
|
15
20
|
return new Promise((resolve, reject) => {
|
|
16
|
-
|
|
17
|
-
|
|
21
|
+
if (typeof condition !== 'function') {
|
|
22
|
+
reject(new TypeError(`waitForRaf: condition must be a function, got: ${typeof condition}`));
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
if (signal?.aborted) {
|
|
27
|
+
reject(createAbortError());
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const timeoutMs = timeout != null ? Math.max(0, parseDuration(timeout)) : null;
|
|
32
|
+
|
|
33
|
+
let rafId = 0;
|
|
34
|
+
let startedAt = null; // RAF timestamp of first tick (or immediate tick reference)
|
|
35
|
+
|
|
36
|
+
const cleanup = () => {
|
|
37
|
+
if (rafId) cancelAnimationFrame(rafId);
|
|
38
|
+
rafId = 0;
|
|
39
|
+
cleanupAbort();
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const onAbort = () => {
|
|
43
|
+
cleanup();
|
|
44
|
+
reject(createAbortError());
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const cleanupAbort = attachAbort(signal, onAbort);
|
|
48
|
+
|
|
49
|
+
const evaluateCondition = () => {
|
|
50
|
+
try {
|
|
51
|
+
return !!condition();
|
|
52
|
+
} catch (err) {
|
|
53
|
+
cleanup();
|
|
54
|
+
reject(err);
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// Optional immediate evaluation (before any frames)
|
|
60
|
+
if (immediate) {
|
|
61
|
+
const ok = evaluateCondition();
|
|
62
|
+
if (ok === null) return;
|
|
63
|
+
if (ok) {
|
|
64
|
+
cleanup();
|
|
65
|
+
resolve();
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// If timeout is explicitly 0, and immediate failed, we can fail fast.
|
|
70
|
+
if (timeoutMs === 0) {
|
|
71
|
+
cleanup();
|
|
72
|
+
reject(new Error('waitForRaf timed out'));
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const tick = (ts) => {
|
|
78
|
+
// Initialize start time using the same clock as `ts`
|
|
79
|
+
if (startedAt == null) startedAt = ts;
|
|
80
|
+
|
|
81
|
+
const ok = evaluateCondition();
|
|
82
|
+
if (ok === null) return;
|
|
18
83
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
84
|
+
if (ok) {
|
|
85
|
+
cleanup();
|
|
86
|
+
resolve();
|
|
87
|
+
return;
|
|
22
88
|
}
|
|
23
89
|
|
|
24
|
-
if (timeoutMs &&
|
|
25
|
-
|
|
90
|
+
if (timeoutMs != null && ts - startedAt >= timeoutMs) {
|
|
91
|
+
cleanup();
|
|
92
|
+
reject(new Error('waitForRaf timed out'));
|
|
93
|
+
return;
|
|
26
94
|
}
|
|
27
95
|
|
|
28
|
-
requestAnimationFrame(tick);
|
|
96
|
+
rafId = requestAnimationFrame(tick);
|
|
29
97
|
};
|
|
30
98
|
|
|
31
|
-
requestAnimationFrame(tick);
|
|
99
|
+
rafId = requestAnimationFrame(tick);
|
|
32
100
|
});
|
|
33
|
-
}
|
|
101
|
+
}
|
package/src/resolveDelayAndFn.js
CHANGED
|
@@ -1,28 +1,90 @@
|
|
|
1
|
+
// ./src/resolveDelayAndFn.js
|
|
1
2
|
import { parseDuration } from './parseDuration.js';
|
|
2
3
|
|
|
4
|
+
const isPlainOptions = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
|
|
5
|
+
|
|
3
6
|
/**
|
|
4
7
|
* Resolves flexible (fn, delay) or (delay, fn) inputs.
|
|
5
8
|
*
|
|
9
|
+
* NOTE: This helper is intentionally strict:
|
|
10
|
+
* - It requires an explicit delay (2-arg form).
|
|
11
|
+
* - Use `resolveDelayFnOptions()` for overloads that allow `(fn, options)` or default delays.
|
|
12
|
+
*
|
|
6
13
|
* @param {Function|string|number} a - function or duration
|
|
7
14
|
* @param {Function|string|number} b - function or duration
|
|
8
15
|
* @returns {{ fn: Function, delay: number }}
|
|
9
16
|
*/
|
|
10
17
|
export function resolveDelayAndFn(a, b) {
|
|
11
|
-
|
|
18
|
+
// Keep legacy semantics but delegate parsing/validation.
|
|
19
|
+
const { fn, delay } = resolveDelayFnOptions(a, b, undefined, undefined);
|
|
20
|
+
|
|
21
|
+
// If someone called resolveDelayAndFn(fn) by mistake, throw a clearer error.
|
|
22
|
+
// (parseDuration(undefined) would be a confusing failure mode.)
|
|
23
|
+
if (b == null && typeof a === 'function') {
|
|
24
|
+
throw new TypeError('Expected a delay as the second argument (e.g. debounce(fn, "250ms"))');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return { fn, delay };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Resolves flexible overloads and returns `{ fn, delay, options }`.
|
|
32
|
+
*
|
|
33
|
+
* Supported forms:
|
|
34
|
+
* - (fn, delay, [options])
|
|
35
|
+
* - (delay, fn, [options])
|
|
36
|
+
* - (fn, [options]) // delay defaults
|
|
37
|
+
*
|
|
38
|
+
* This is intentionally strict about what counts as "options" to avoid
|
|
39
|
+
* treating random values as configuration.
|
|
40
|
+
*
|
|
41
|
+
* @template {Record<string, any>} O
|
|
42
|
+
* @param {Function|string|number} a
|
|
43
|
+
* @param {Function|string|number|O} b
|
|
44
|
+
* @param {O} [c]
|
|
45
|
+
* @param {string|number} [defaultDelay=0]
|
|
46
|
+
* @returns {{ fn: Function, delay: number, options: O }}
|
|
47
|
+
*/
|
|
48
|
+
export function resolveDelayFnOptions(a, b, c, defaultDelay = 0) {
|
|
49
|
+
/** @type {Function} */
|
|
50
|
+
let fn;
|
|
51
|
+
|
|
52
|
+
/** @type {string|number|undefined} */
|
|
53
|
+
let delayRaw;
|
|
54
|
+
|
|
55
|
+
/** @type {any} */
|
|
56
|
+
let options;
|
|
12
57
|
|
|
13
58
|
if (typeof a === 'function') {
|
|
14
59
|
fn = a;
|
|
15
|
-
|
|
60
|
+
|
|
61
|
+
if (isPlainOptions(b)) {
|
|
62
|
+
// (fn, options)
|
|
63
|
+
delayRaw = defaultDelay;
|
|
64
|
+
options = b;
|
|
65
|
+
} else {
|
|
66
|
+
// (fn, delay, options?)
|
|
67
|
+
delayRaw = /** @type {any} */ (b);
|
|
68
|
+
options = isPlainOptions(c) ? c : {};
|
|
69
|
+
}
|
|
16
70
|
} else {
|
|
17
|
-
fn
|
|
18
|
-
delayRaw = a;
|
|
71
|
+
// (delay, fn, options?)
|
|
72
|
+
delayRaw = /** @type {any} */ (a);
|
|
73
|
+
fn = /** @type {any} */ (b);
|
|
74
|
+
options = isPlainOptions(c) ? c : {};
|
|
19
75
|
}
|
|
20
76
|
|
|
21
77
|
if (typeof fn !== 'function') {
|
|
22
78
|
throw new TypeError(`Expected a function as one argument, got: ${typeof fn}`);
|
|
23
79
|
}
|
|
24
80
|
|
|
25
|
-
const
|
|
81
|
+
const raw = delayRaw ?? defaultDelay;
|
|
26
82
|
|
|
27
|
-
|
|
28
|
-
|
|
83
|
+
// If someone passes `(fn, options)` but defaultDelay was undefined, surface a clear error.
|
|
84
|
+
if (raw == null) {
|
|
85
|
+
throw new TypeError('Expected a duration (string/number) for delay');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const delay = parseDuration(raw);
|
|
89
|
+
return { fn, delay, options };
|
|
90
|
+
}
|
package/src/retry.js
CHANGED
|
@@ -1,24 +1,164 @@
|
|
|
1
|
+
// ./src/retry.js
|
|
1
2
|
import { parseDuration } from './parseDuration.js';
|
|
3
|
+
import { attachAbort, createAbortError } from './abort.js';
|
|
2
4
|
|
|
3
5
|
/**
|
|
4
6
|
* Retries a promise-returning function with delays.
|
|
5
|
-
*
|
|
6
|
-
* @param {
|
|
7
|
-
* @param {
|
|
8
|
-
* @param {
|
|
9
|
-
* @param {
|
|
10
|
-
* @
|
|
7
|
+
*
|
|
8
|
+
* @param {(attemptIndex: number) => Promise<any>} fn - async function
|
|
9
|
+
* @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
|
|
18
|
+
* @param {(err: any, attempt: number) => boolean | Promise<boolean>} [options.shouldRetry]
|
|
19
|
+
* Predicate deciding whether to retry after a failure.
|
|
20
|
+
* @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>}
|
|
11
23
|
*/
|
|
12
|
-
export async function retry(
|
|
24
|
+
export async function retry(
|
|
25
|
+
fn,
|
|
26
|
+
{
|
|
27
|
+
attempts = 3,
|
|
28
|
+
delay = '500ms',
|
|
29
|
+
backoff = false,
|
|
30
|
+
factor = 2,
|
|
31
|
+
maxDelay,
|
|
32
|
+
jitter = false,
|
|
33
|
+
signal,
|
|
34
|
+
random = Math.random,
|
|
35
|
+
shouldRetry,
|
|
36
|
+
onRetry,
|
|
37
|
+
} = {}
|
|
38
|
+
) {
|
|
39
|
+
if (typeof fn !== 'function') throw new TypeError('retry: fn must be a function');
|
|
40
|
+
|
|
41
|
+
const totalAttempts = Math.max(1, attempts | 0);
|
|
42
|
+
|
|
43
|
+
if (signal?.aborted) throw createAbortError();
|
|
44
|
+
|
|
13
45
|
const baseDelay = parseDuration(delay);
|
|
46
|
+
const maxDelayMs = maxDelay != null ? parseDuration(maxDelay) : Infinity;
|
|
47
|
+
|
|
48
|
+
// decorrelated jitter needs to remember prior sleep
|
|
49
|
+
let prevSleep = Math.min(baseDelay, maxDelayMs);
|
|
50
|
+
|
|
51
|
+
for (let attempt = 0; attempt < totalAttempts; attempt++) {
|
|
52
|
+
if (signal?.aborted) throw createAbortError();
|
|
14
53
|
|
|
15
|
-
for (let i = 0; i < attempts; i++) {
|
|
16
54
|
try {
|
|
17
|
-
return await fn();
|
|
55
|
+
return await fn(attempt);
|
|
18
56
|
} catch (err) {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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);
|
|
22
85
|
}
|
|
23
86
|
}
|
|
87
|
+
|
|
88
|
+
// Unreachable, but keeps type checkers happy.
|
|
89
|
+
// eslint-disable-next-line no-throw-literal
|
|
90
|
+
throw new Error('retry: exhausted attempts unexpectedly');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Compute retry sleep with optional backoff clamp + jitter.
|
|
95
|
+
*
|
|
96
|
+
* Jitter strategies:
|
|
97
|
+
* - false: no jitter
|
|
98
|
+
* - 'full': random(0, cap)
|
|
99
|
+
* - 'equal': cap/2 + random(0, cap/2)
|
|
100
|
+
* - 'decorrelated': random(baseDelay, prevSleep*3) (clamped)
|
|
101
|
+
*/
|
|
102
|
+
function computeSleep({ expDelay, baseDelay, maxDelayMs, jitter, random, prevSleep }) {
|
|
103
|
+
const cap = Math.min(expDelay, maxDelayMs);
|
|
104
|
+
|
|
105
|
+
if (!jitter) return cap;
|
|
106
|
+
|
|
107
|
+
const mode = jitter === true ? 'full' : jitter;
|
|
108
|
+
|
|
109
|
+
if (mode === 'full') {
|
|
110
|
+
return Math.min(maxDelayMs, randBetween(0, cap, random));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (mode === 'equal') {
|
|
114
|
+
const half = cap / 2;
|
|
115
|
+
return Math.min(maxDelayMs, half + randBetween(0, half, random));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (mode === 'decorrelated') {
|
|
119
|
+
const next = randBetween(baseDelay, prevSleep * 3, random);
|
|
120
|
+
return Math.min(maxDelayMs, next);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Unknown mode -> treat as no jitter (safe fallback)
|
|
124
|
+
return cap;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function randBetween(min, max, random) {
|
|
128
|
+
const r = random();
|
|
129
|
+
const t = Number.isFinite(r) ? Math.min(1, Math.max(0, r)) : 0;
|
|
130
|
+
return min + (max - min) * t;
|
|
24
131
|
}
|
|
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
|
+
}
|