@tanstack/pacer 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +4 -4
  2. package/dist/async-batcher.d.ts +11 -13
  3. package/dist/async-batcher.js +185 -131
  4. package/dist/async-debouncer.d.ts +6 -8
  5. package/dist/async-debouncer.js +186 -142
  6. package/dist/async-queuer.d.ts +11 -13
  7. package/dist/async-queuer.js +383 -290
  8. package/dist/async-rate-limiter.d.ts +6 -8
  9. package/dist/async-rate-limiter.js +197 -143
  10. package/dist/async-retryer.d.ts +6 -8
  11. package/dist/async-retryer.js +209 -179
  12. package/dist/async-throttler.d.ts +6 -8
  13. package/dist/async-throttler.js +214 -157
  14. package/dist/batcher.d.ts +5 -7
  15. package/dist/batcher.js +107 -87
  16. package/dist/debouncer.d.ts +6 -8
  17. package/dist/debouncer.js +99 -86
  18. package/dist/event-client.d.ts +8 -10
  19. package/dist/event-client.js +1 -2
  20. package/dist/queuer.d.ts +7 -9
  21. package/dist/queuer.js +277 -212
  22. package/dist/rate-limiter.d.ts +6 -8
  23. package/dist/rate-limiter.js +127 -109
  24. package/dist/throttler.d.ts +6 -8
  25. package/dist/throttler.js +127 -90
  26. package/dist/types.d.ts +4 -6
  27. package/dist/utils.d.ts +3 -5
  28. package/dist/utils.js +1 -2
  29. package/package.json +21 -68
  30. package/dist/async-batcher.cjs +0 -337
  31. package/dist/async-batcher.cjs.map +0 -1
  32. package/dist/async-batcher.d.cts +0 -343
  33. package/dist/async-batcher.js.map +0 -1
  34. package/dist/async-debouncer.cjs +0 -327
  35. package/dist/async-debouncer.cjs.map +0 -1
  36. package/dist/async-debouncer.d.cts +0 -299
  37. package/dist/async-debouncer.js.map +0 -1
  38. package/dist/async-queuer.cjs +0 -516
  39. package/dist/async-queuer.cjs.map +0 -1
  40. package/dist/async-queuer.d.cts +0 -440
  41. package/dist/async-queuer.js.map +0 -1
  42. package/dist/async-rate-limiter.cjs +0 -370
  43. package/dist/async-rate-limiter.cjs.map +0 -1
  44. package/dist/async-rate-limiter.d.cts +0 -356
  45. package/dist/async-rate-limiter.js.map +0 -1
  46. package/dist/async-retryer.cjs +0 -365
  47. package/dist/async-retryer.cjs.map +0 -1
  48. package/dist/async-retryer.d.cts +0 -321
  49. package/dist/async-retryer.js.map +0 -1
  50. package/dist/async-throttler.cjs +0 -344
  51. package/dist/async-throttler.cjs.map +0 -1
  52. package/dist/async-throttler.d.cts +0 -319
  53. package/dist/async-throttler.js.map +0 -1
  54. package/dist/batcher.cjs +0 -200
  55. package/dist/batcher.cjs.map +0 -1
  56. package/dist/batcher.d.cts +0 -179
  57. package/dist/batcher.js.map +0 -1
  58. package/dist/debouncer.cjs +0 -203
  59. package/dist/debouncer.cjs.map +0 -1
  60. package/dist/debouncer.d.cts +0 -166
  61. package/dist/debouncer.js.map +0 -1
  62. package/dist/event-client.cjs +0 -64
  63. package/dist/event-client.cjs.map +0 -1
  64. package/dist/event-client.d.cts +0 -65
  65. package/dist/event-client.js.map +0 -1
  66. package/dist/index.cjs +0 -52
  67. package/dist/index.d.cts +0 -15
  68. package/dist/queuer.cjs +0 -406
  69. package/dist/queuer.cjs.map +0 -1
  70. package/dist/queuer.d.cts +0 -345
  71. package/dist/queuer.js.map +0 -1
  72. package/dist/rate-limiter.cjs +0 -263
  73. package/dist/rate-limiter.cjs.map +0 -1
  74. package/dist/rate-limiter.d.cts +0 -214
  75. package/dist/rate-limiter.js.map +0 -1
  76. package/dist/throttler.cjs +0 -215
  77. package/dist/throttler.cjs.map +0 -1
  78. package/dist/throttler.d.cts +0 -206
  79. package/dist/throttler.js.map +0 -1
  80. package/dist/types.cjs +0 -0
  81. package/dist/types.d.cts +0 -13
  82. package/dist/utils.cjs +0 -13
  83. package/dist/utils.cjs.map +0 -1
  84. package/dist/utils.d.cts +0 -7
  85. package/dist/utils.js.map +0 -1
  86. package/src/async-batcher.ts +0 -594
  87. package/src/async-debouncer.ts +0 -566
  88. package/src/async-queuer.ts +0 -988
  89. package/src/async-rate-limiter.ts +0 -648
  90. package/src/async-retryer.ts +0 -673
  91. package/src/async-throttler.ts +0 -634
  92. package/src/batcher.ts +0 -329
  93. package/src/debouncer.ts +0 -334
  94. package/src/event-client.ts +0 -129
  95. package/src/index.ts +0 -24
  96. package/src/queuer.ts +0 -751
  97. package/src/rate-limiter.ts +0 -429
  98. package/src/throttler.ts +0 -380
  99. package/src/types.ts +0 -12
  100. package/src/utils.ts +0 -12
@@ -1,365 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_utils = require('./utils.cjs');
3
- let _tanstack_store = require("@tanstack/store");
4
-
5
- //#region src/async-retryer.ts
6
- /**
7
- * Creates the default initial state for an AsyncRetryer instance
8
- * @returns The default state with all values reset to initial values
9
- */
10
- function getDefaultAsyncRetryerState() {
11
- return {
12
- currentAttempt: 0,
13
- executionCount: 0,
14
- isExecuting: false,
15
- lastError: void 0,
16
- lastExecutionTime: 0,
17
- lastResult: void 0,
18
- status: "idle",
19
- totalExecutionTime: 0
20
- };
21
- }
22
- /**
23
- * Utility function for sharing common `AsyncRetryerOptions` options between different `AsyncRetryer` instances.
24
- */
25
- function asyncRetryerOptions(options) {
26
- return options;
27
- }
28
- const defaultOptions = {
29
- backoff: "exponential",
30
- baseWait: 1e3,
31
- maxWait: Infinity,
32
- enabled: true,
33
- jitter: 0,
34
- maxAttempts: 3,
35
- maxExecutionTime: Infinity,
36
- maxTotalExecutionTime: Infinity,
37
- throwOnError: "last"
38
- };
39
- /**
40
- * Provides robust retry functionality for asynchronous functions, supporting configurable backoff strategies,
41
- * attempt limits, timeout controls, and detailed state management. The AsyncRetryer class is designed to help you reliably
42
- * execute async operations that may fail intermittently, such as network requests or database operations,
43
- * by automatically retrying them according to your chosen policy.
44
- *
45
- * ## Retrying Concepts
46
- *
47
- * - **Retrying**: Automatically re-executes a failed async function up to a specified number of attempts.
48
- * Useful for handling transient errors (e.g., network flakiness, rate limits, temporary server issues).
49
- * - **Backoff Strategies**: Controls the delay between retry attempts (default: `'exponential'`):
50
- * - `'exponential'`: Wait time doubles with each attempt (1s, 2s, 4s, ...) - **DEFAULT**
51
- * - `'linear'`: Wait time increases linearly (1s, 2s, 3s, ...)
52
- * - `'fixed'`: Waits a constant amount of time (`baseWait`) between each attempt
53
- * - **Jitter**: Adds randomness to retry delays to prevent thundering herd problems (default: `0`).
54
- * Set to a value between 0-1 to apply that percentage of random variation to each delay.
55
- * - **Max Wait**: Caps the maximum wait time between retries (default: `Infinity`).
56
- * Useful for preventing exponential backoff from growing too large (e.g., cap at 30s even if exponential would be 64s).
57
- * - **Timeout Controls**: Set limits on execution time to prevent hanging operations:
58
- * - `maxExecutionTime`: Maximum time for a single function call (default: `Infinity`)
59
- * - `maxTotalExecutionTime`: Maximum time for the entire retry operation (default: `Infinity`)
60
- * - **Abort & Cancellation**: Supports cancellation via an internal `AbortController`. Call `abort()` to stop retries.
61
- * Use `getAbortSignal()` to make your async function actually cancellable (e.g., with fetch requests).
62
- *
63
- * ## State Management
64
- *
65
- * Uses TanStack Store for fine-grained reactivity. State can be accessed via the `store.state` property.
66
- *
67
- * Available state properties:
68
- * - `currentAttempt`: The current retry attempt number (0 when not executing)
69
- * - `executionCount`: Total number of completed executions (successful or failed)
70
- * - `isExecuting`: Whether the retryer is currently executing the function
71
- * - `lastError`: The most recent error encountered during execution
72
- * - `lastExecutionTime`: Timestamp of the last execution completion in milliseconds
73
- * - `lastResult`: The result from the most recent successful execution
74
- * - `status`: Current execution status ('disabled' | 'idle' | 'executing' | 'retrying')
75
- * - `totalExecutionTime`: Total time spent executing (including retries) in milliseconds
76
- *
77
- * ## Error Handling
78
- *
79
- * The `throwOnError` option controls when errors are thrown (default: `'last'`):
80
- * - `'last'`: Only throws the final error after all retries are exhausted - **DEFAULT**
81
- * - `true`: Throws every error immediately (disables retrying)
82
- * - `false`: Never throws errors, returns `undefined` instead
83
- *
84
- * Callbacks for lifecycle management:
85
- * - `onAbort`: Called when execution is aborted (manually or due to timeouts)
86
- * - `onError`: Called for every error (including during retries)
87
- * - `onLastError`: Called only for the final error after all retries fail
88
- * - `onRetry`: Called before each retry attempt
89
- * - `onSettled`: Called after execution completes (success or failure) of each attempt
90
- * - `onSuccess`: Called when execution succeeds
91
- * - `onExecutionTimeout`: Called when a single execution attempt times out
92
- * - `onTotalExecutionTimeout`: Called when the total execution time times out
93
- *
94
- * ## Usage
95
- *
96
- * - Use for async operations that may fail transiently and benefit from retrying.
97
- * - Configure `maxAttempts`, `backoff`, `baseWait`, `maxWait`, and `jitter` to control retry behavior.
98
- * - Set `maxExecutionTime` and `maxTotalExecutionTime` to prevent hanging operations.
99
- * - Use `onAbort`, `onError`, `onLastError`, `onRetry`, `onSettled`, `onSuccess`, `onExecutionTimeout`, and `onTotalExecutionTimeout` for custom side effects.
100
- * - Call `abort()` to cancel ongoing execution and pending retries.
101
- * - Call `reset()` to reset state and cancel execution.
102
- * - Use `getAbortSignal()` to make your async function cancellable.
103
- * - Use dynamic options (functions) for `maxAttempts`, `baseWait`, and `enabled` based on retryer state.
104
- *
105
- * **Important:** This class is designed for single-use execution. Calling `execute()` multiple times
106
- * on the same instance will abort previous executions. For multiple calls, create a new instance
107
- * each time.
108
- *
109
- * @example
110
- * ```typescript
111
- * // Retry a fetch operation up to 5 times with exponential backoff, jitter, and timeouts
112
- * const retryer = new AsyncRetryer(async (url: string) => {
113
- * const signal = retryer.getAbortSignal()
114
- * return await fetch(url, { signal })
115
- * }, {
116
- * maxAttempts: 5,
117
- * backoff: 'exponential',
118
- * baseWait: 1000,
119
- * jitter: 0.1, // Add 10% random variation to prevent thundering herd
120
- * maxExecutionTime: 5000, // Abort individual calls after 5 seconds
121
- * maxTotalExecutionTime: 30000, // Abort entire operation after 30 seconds
122
- * onRetry: (attempt, error) => console.log(`Retry attempt ${attempt} after error:`, error),
123
- * onSuccess: (result) => console.log('Success:', result),
124
- * onError: (error) => console.error('Error:', error),
125
- * onLastError: (error) => console.error('All retries failed:', error),
126
- * })
127
- *
128
- * const result = await retryer.execute('/api/data')
129
- * ```
130
- *
131
- * @template TFn The async function type to be retried.
132
- */
133
- var AsyncRetryer = class {
134
- #abortController;
135
- /**
136
- * Creates a new AsyncRetryer instance
137
- * @param fn The async function to retry
138
- * @param initialOptions Configuration options for the retryer
139
- */
140
- constructor(fn, initialOptions = {}) {
141
- this.fn = fn;
142
- this.store = new _tanstack_store.Store(getDefaultAsyncRetryerState());
143
- this.#abortController = null;
144
- this.setOptions = (newOptions) => {
145
- this.options = {
146
- ...this.options,
147
- ...newOptions
148
- };
149
- };
150
- this.#setState = (newState) => {
151
- this.store.setState((state) => {
152
- const combinedState = {
153
- ...state,
154
- ...newState
155
- };
156
- const { isExecuting, currentAttempt } = combinedState;
157
- return {
158
- ...combinedState,
159
- status: !this.#getEnabled() ? "disabled" : isExecuting && currentAttempt === 1 ? "executing" : isExecuting && currentAttempt > 1 ? "retrying" : "idle"
160
- };
161
- });
162
- };
163
- this.#getEnabled = () => {
164
- return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
165
- };
166
- this.#getMaxAttempts = () => {
167
- return require_utils.parseFunctionOrValue(this.options.maxAttempts, this);
168
- };
169
- this.#getBaseWait = () => {
170
- return require_utils.parseFunctionOrValue(this.options.baseWait, this);
171
- };
172
- this.#getMaxWait = () => {
173
- return require_utils.parseFunctionOrValue(this.options.maxWait, this);
174
- };
175
- this.#calculateJitter = (waitTime) => {
176
- const jitterAmount = this.options.jitter;
177
- if (jitterAmount <= 0) return 0;
178
- try {
179
- const crypto = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
180
- if (crypto?.getRandomValues) {
181
- const array = /* @__PURE__ */ new Uint32Array(1);
182
- crypto.getRandomValues(array);
183
- const randomFactor = array[0] / 4294967295 * 2 - 1;
184
- return Math.floor(waitTime * jitterAmount * randomFactor);
185
- }
186
- } catch {}
187
- return 0;
188
- };
189
- this.#calculateWait = (attempt) => {
190
- const baseWait = this.#getBaseWait();
191
- let waitTime;
192
- switch (this.options.backoff) {
193
- case "linear":
194
- waitTime = baseWait * attempt;
195
- break;
196
- case "exponential":
197
- waitTime = baseWait * Math.pow(2, attempt - 1);
198
- break;
199
- default: waitTime = baseWait;
200
- }
201
- waitTime = Math.min(waitTime, this.#getMaxWait());
202
- const jitter = this.#calculateJitter(waitTime);
203
- return Math.max(0, waitTime + jitter);
204
- };
205
- this.execute = async (...args) => {
206
- if (!this.#getEnabled()) return;
207
- this.abort("new-execution");
208
- const startTime = Date.now();
209
- let lastError;
210
- let result;
211
- this.#abortController = new AbortController();
212
- const signal = this.#abortController.signal;
213
- this.#setState({
214
- isExecuting: true,
215
- currentAttempt: 0,
216
- lastError: void 0
217
- });
218
- let totalTimeoutId;
219
- if (this.options.maxTotalExecutionTime !== Infinity) totalTimeoutId = setTimeout(() => {
220
- this.options.onTotalExecutionTimeout?.(this);
221
- this.abort("total-timeout");
222
- }, this.options.maxTotalExecutionTime);
223
- let isLastAttempt = false;
224
- for (let attempt = 1; attempt <= this.#getMaxAttempts(); attempt++) {
225
- isLastAttempt = attempt === this.#getMaxAttempts();
226
- this.#setState({ currentAttempt: attempt });
227
- try {
228
- if (signal.aborted) return;
229
- const currentTotalTime = Date.now() - startTime;
230
- if (this.options.maxTotalExecutionTime !== Infinity && currentTotalTime >= this.options.maxTotalExecutionTime) {
231
- this.options.onTotalExecutionTimeout?.(this);
232
- this.abort("total-timeout");
233
- return;
234
- }
235
- if (this.options.maxExecutionTime === Infinity) result = await this.fn(...args);
236
- else result = await Promise.race([this.fn(...args), new Promise((_, reject) => {
237
- const timeout = setTimeout(() => {
238
- this.options.onExecutionTimeout?.(this);
239
- this.abort("execution-timeout");
240
- reject(/* @__PURE__ */ new Error(`Execution timeout: ${this.options.maxExecutionTime}ms exceeded`));
241
- }, this.options.maxExecutionTime);
242
- signal.addEventListener("abort", () => {
243
- clearTimeout(timeout);
244
- reject(/* @__PURE__ */ new Error("Aborted"));
245
- }, { once: true });
246
- })]);
247
- if (signal.aborted) return;
248
- const totalTime = Date.now() - startTime;
249
- this.#setState({
250
- executionCount: this.store.state.executionCount + 1,
251
- isExecuting: false,
252
- lastExecutionTime: Date.now(),
253
- totalExecutionTime: totalTime,
254
- currentAttempt: 0,
255
- lastResult: result
256
- });
257
- this.options.onSuccess?.(result, args, this);
258
- return result;
259
- } catch (error) {
260
- if (error && typeof error === "object" && "name" in error && error.name === "AbortError") return;
261
- lastError = error instanceof Error ? error : new Error(String(error));
262
- this.#setState({ lastError });
263
- this.options.onError?.(lastError, args, this);
264
- if (attempt < this.#getMaxAttempts()) {
265
- this.options.onRetry?.(attempt, lastError, this);
266
- const wait = this.#calculateWait(attempt);
267
- if (wait > 0) {
268
- this.#setState({
269
- isExecuting: true,
270
- currentAttempt: attempt + 1
271
- });
272
- await new Promise((resolve) => {
273
- const timeout = setTimeout(() => {
274
- signal.removeEventListener("abort", onAbort);
275
- resolve();
276
- }, wait);
277
- const onAbort = () => {
278
- clearTimeout(timeout);
279
- signal.removeEventListener("abort", onAbort);
280
- resolve();
281
- };
282
- signal.addEventListener("abort", onAbort);
283
- });
284
- if (signal.aborted) return;
285
- }
286
- }
287
- } finally {
288
- this.options.onSettled?.(args, this);
289
- }
290
- }
291
- if (totalTimeoutId) clearTimeout(totalTimeoutId);
292
- this.#setState({ isExecuting: false });
293
- this.options.onLastError?.(lastError, this);
294
- this.options.onSettled?.(args, this);
295
- if (this.options.throwOnError === "last" && isLastAttempt || this.options.throwOnError === true) throw lastError;
296
- };
297
- this.getAbortSignal = () => {
298
- return this.#abortController?.signal ?? null;
299
- };
300
- this.abort = (reason = "manual") => {
301
- if (this.#abortController) {
302
- this.#abortController.abort();
303
- this.#abortController = null;
304
- this.#setState({ isExecuting: false });
305
- this.options.onAbort?.(reason, this);
306
- }
307
- };
308
- this.reset = () => {
309
- this.#setState(getDefaultAsyncRetryerState());
310
- };
311
- this.key = initialOptions.key;
312
- this.options = {
313
- ...defaultOptions,
314
- ...initialOptions,
315
- throwOnError: initialOptions.throwOnError ?? (initialOptions.onError ? false : defaultOptions.throwOnError)
316
- };
317
- this.#setState(this.options.initialState ?? {});
318
- }
319
- #setState;
320
- #getEnabled;
321
- #getMaxAttempts;
322
- #getBaseWait;
323
- #getMaxWait;
324
- #calculateJitter;
325
- #calculateWait;
326
- };
327
- /**
328
- * Creates a retry-enabled version of an async function. This is a convenience wrapper
329
- * around the AsyncRetryer class that returns the execute method.
330
- *
331
- * @param fn The async function to add retry functionality to
332
- * @param initialOptions Configuration options for the retry behavior
333
- * @returns A new function that executes the original with retry logic
334
- *
335
- * @example
336
- * ```typescript
337
- * // Define your async function normally
338
- * async function fetchData(url: string) {
339
- * const response = await fetch(url)
340
- * if (!response.ok) throw new Error('Request failed')
341
- * return response.json()
342
- * }
343
- *
344
- * // Create retry-enabled function
345
- * const fetchWithRetry = asyncRetry(fetchData, {
346
- * maxAttempts: 3,
347
- * backoff: 'exponential',
348
- * baseWait: 1000,
349
- * jitter: 0.1
350
- * })
351
- *
352
- * // Call it multiple times
353
- * const data1 = await fetchWithRetry('/api/data1')
354
- * const data2 = await fetchWithRetry('/api/data2')
355
- * ```
356
- */
357
- function asyncRetry(fn, initialOptions = {}) {
358
- return new AsyncRetryer(fn, initialOptions).execute;
359
- }
360
-
361
- //#endregion
362
- exports.AsyncRetryer = AsyncRetryer;
363
- exports.asyncRetry = asyncRetry;
364
- exports.asyncRetryerOptions = asyncRetryerOptions;
365
- //# sourceMappingURL=async-retryer.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"async-retryer.cjs","names":["Store","#getEnabled","parseFunctionOrValue","#getBaseWait","#getMaxWait","#calculateJitter","#abortController","#setState","#getMaxAttempts","#calculateWait"],"sources":["../src/async-retryer.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction } from './types'\n\nexport interface AsyncRetryerState<TFn extends AnyAsyncFunction> {\n /**\n * The current retry attempt number (0 when not executing)\n */\n currentAttempt: number\n /**\n * Total number of completed executions (successful or failed)\n */\n executionCount: number\n /**\n * Whether the retryer is currently executing the function\n */\n isExecuting: boolean\n /**\n * The most recent error encountered during execution\n */\n lastError: Error | undefined\n /**\n * Timestamp of the last execution completion in milliseconds\n */\n lastExecutionTime: number\n /**\n * The result from the most recent successful execution\n */\n lastResult: Awaited<ReturnType<TFn>> | undefined\n /**\n * Current execution status - 'disabled' when not enabled, 'idle' when ready, 'executing' when running\n */\n status: 'disabled' | 'idle' | 'executing' | 'retrying'\n /**\n * Total time spent executing (including retries) in milliseconds\n */\n totalExecutionTime: number\n}\n\n/**\n * Creates the default initial state for an AsyncRetryer instance\n * @returns The default state with all values reset to initial values\n */\nfunction getDefaultAsyncRetryerState<\n TFn extends AnyAsyncFunction,\n>(): AsyncRetryerState<TFn> {\n return {\n currentAttempt: 0,\n executionCount: 0,\n isExecuting: false,\n lastError: undefined,\n lastExecutionTime: 0,\n lastResult: undefined,\n status: 'idle',\n totalExecutionTime: 0,\n }\n}\n\nexport interface AsyncRetryerOptions<TFn extends AnyAsyncFunction> {\n /**\n * The backoff strategy for retry delays:\n * - 'exponential': Wait time doubles with each attempt (1s, 2s, 4s, ...)\n * - 'linear': Wait time increases linearly (1s, 2s, 3s, ...)\n * - 'fixed': Same wait time for all attempts\n * @default 'exponential'\n */\n backoff?: 'linear' | 'exponential' | 'fixed'\n /**\n * Base wait time in milliseconds between retries, or a function that returns the wait time\n * @default 1000\n */\n baseWait?: number | ((retryer: AsyncRetryer<TFn>) => number)\n /**\n * Whether the retryer is enabled, or a function that determines if it's enabled\n * @default true\n */\n enabled?: boolean | ((retryer: AsyncRetryer<TFn>) => boolean)\n /**\n * Initial state to merge with the default state\n */\n initialState?: Partial<AsyncRetryerState<TFn>>\n /**\n * Jitter percentage to add to retry delays (0-1). Adds randomness to prevent thundering herd.\n * @default 0\n */\n jitter?: number\n /**\n * Optional key to identify this async retryer instance.\n * Note: async retryers are not currently surfaced in the devtools, so this key\n * is only a plain identifier. Retryer instances are often created per-execution\n * (including internally by the other async utilities), so they intentionally do\n * not register with the devtools event bus.\n */\n key?: string\n /**\n * Maximum number of retry attempts, or a function that returns the max attempts\n * @default 3\n */\n maxAttempts?: number | ((retryer: AsyncRetryer<TFn>) => number)\n /**\n * Maximum execution time in milliseconds for a single function call before aborting\n * @default Infinity\n */\n maxExecutionTime?: number\n /**\n * Maximum total execution time in milliseconds for the entire retry operation before aborting\n * @default Infinity\n */\n maxTotalExecutionTime?: number\n /**\n * Maximum wait time in milliseconds to cap retry delays, or a function that returns the max wait time\n * @default Infinity\n */\n maxWait?: number | ((retryer: AsyncRetryer<TFn>) => number)\n /**\n * Callback invoked when the execution is aborted (manually or due to timeouts)\n */\n onAbort?: (\n reason: 'manual' | 'execution-timeout' | 'total-timeout' | 'new-execution',\n retryer: AsyncRetryer<TFn>,\n ) => void\n /**\n * Callback invoked when any error occurs during execution (including retries)\n */\n onError?: (\n error: Error,\n args: Parameters<TFn>,\n retryer: AsyncRetryer<TFn>,\n ) => void\n /**\n * Callback invoked when a single execution attempt times out (maxExecutionTime exceeded)\n */\n onExecutionTimeout?: (retryer: AsyncRetryer<TFn>) => void\n /**\n * Callback invoked when the final error occurs after all retries are exhausted\n */\n onLastError?: (error: Error, retryer: AsyncRetryer<TFn>) => void\n /**\n * Callback invoked before each retry attempt\n */\n onRetry?: (attempt: number, error: Error, retryer: AsyncRetryer<TFn>) => void\n /**\n * Callback invoked after execution completes (success or failure) of each attempt\n */\n onSettled?: (args: Parameters<TFn>, retryer: AsyncRetryer<TFn>) => void\n /**\n * Callback invoked when execution succeeds\n */\n onSuccess?: (\n result: Awaited<ReturnType<TFn>>,\n args: Parameters<TFn>,\n retryer: AsyncRetryer<TFn>,\n ) => void\n /**\n * Callback invoked when the total execution time times out (maxTotalExecutionTime exceeded)\n */\n onTotalExecutionTimeout?: (retryer: AsyncRetryer<TFn>) => void\n /**\n * Controls when errors are thrown:\n * - 'last': Only throw the final error after all retries are exhausted\n * - true: Throw every error immediately (disables retrying)\n * - false: Never throw errors, return undefined instead\n * @default 'last'\n */\n throwOnError?: boolean | 'last'\n}\n\n/**\n * Utility function for sharing common `AsyncRetryerOptions` options between different `AsyncRetryer` instances.\n */\nexport function asyncRetryerOptions<\n TFn extends AnyAsyncFunction = AnyAsyncFunction,\n TOptions extends Partial<AsyncRetryerOptions<TFn>> = Partial<\n AsyncRetryerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<AsyncRetryerOptions<any>>,\n | 'initialState'\n | 'key'\n | 'onAbort'\n | 'onError'\n | 'onLastError'\n | 'onRetry'\n | 'onSettled'\n | 'onSuccess'\n | 'onExecutionTimeout'\n | 'onTotalExecutionTimeout'\n> = {\n backoff: 'exponential',\n baseWait: 1000,\n maxWait: Infinity,\n enabled: true,\n jitter: 0,\n maxAttempts: 3,\n maxExecutionTime: Infinity,\n maxTotalExecutionTime: Infinity,\n throwOnError: 'last',\n}\n\n/**\n * Provides robust retry functionality for asynchronous functions, supporting configurable backoff strategies,\n * attempt limits, timeout controls, and detailed state management. The AsyncRetryer class is designed to help you reliably\n * execute async operations that may fail intermittently, such as network requests or database operations,\n * by automatically retrying them according to your chosen policy.\n *\n * ## Retrying Concepts\n *\n * - **Retrying**: Automatically re-executes a failed async function up to a specified number of attempts.\n * Useful for handling transient errors (e.g., network flakiness, rate limits, temporary server issues).\n * - **Backoff Strategies**: Controls the delay between retry attempts (default: `'exponential'`):\n * - `'exponential'`: Wait time doubles with each attempt (1s, 2s, 4s, ...) - **DEFAULT**\n * - `'linear'`: Wait time increases linearly (1s, 2s, 3s, ...)\n * - `'fixed'`: Waits a constant amount of time (`baseWait`) between each attempt\n * - **Jitter**: Adds randomness to retry delays to prevent thundering herd problems (default: `0`).\n * Set to a value between 0-1 to apply that percentage of random variation to each delay.\n * - **Max Wait**: Caps the maximum wait time between retries (default: `Infinity`).\n * Useful for preventing exponential backoff from growing too large (e.g., cap at 30s even if exponential would be 64s).\n * - **Timeout Controls**: Set limits on execution time to prevent hanging operations:\n * - `maxExecutionTime`: Maximum time for a single function call (default: `Infinity`)\n * - `maxTotalExecutionTime`: Maximum time for the entire retry operation (default: `Infinity`)\n * - **Abort & Cancellation**: Supports cancellation via an internal `AbortController`. Call `abort()` to stop retries.\n * Use `getAbortSignal()` to make your async function actually cancellable (e.g., with fetch requests).\n *\n * ## State Management\n *\n * Uses TanStack Store for fine-grained reactivity. State can be accessed via the `store.state` property.\n *\n * Available state properties:\n * - `currentAttempt`: The current retry attempt number (0 when not executing)\n * - `executionCount`: Total number of completed executions (successful or failed)\n * - `isExecuting`: Whether the retryer is currently executing the function\n * - `lastError`: The most recent error encountered during execution\n * - `lastExecutionTime`: Timestamp of the last execution completion in milliseconds\n * - `lastResult`: The result from the most recent successful execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'executing' | 'retrying')\n * - `totalExecutionTime`: Total time spent executing (including retries) in milliseconds\n *\n * ## Error Handling\n *\n * The `throwOnError` option controls when errors are thrown (default: `'last'`):\n * - `'last'`: Only throws the final error after all retries are exhausted - **DEFAULT**\n * - `true`: Throws every error immediately (disables retrying)\n * - `false`: Never throws errors, returns `undefined` instead\n *\n * Callbacks for lifecycle management:\n * - `onAbort`: Called when execution is aborted (manually or due to timeouts)\n * - `onError`: Called for every error (including during retries)\n * - `onLastError`: Called only for the final error after all retries fail\n * - `onRetry`: Called before each retry attempt\n * - `onSettled`: Called after execution completes (success or failure) of each attempt\n * - `onSuccess`: Called when execution succeeds\n * - `onExecutionTimeout`: Called when a single execution attempt times out\n * - `onTotalExecutionTimeout`: Called when the total execution time times out\n *\n * ## Usage\n *\n * - Use for async operations that may fail transiently and benefit from retrying.\n * - Configure `maxAttempts`, `backoff`, `baseWait`, `maxWait`, and `jitter` to control retry behavior.\n * - Set `maxExecutionTime` and `maxTotalExecutionTime` to prevent hanging operations.\n * - Use `onAbort`, `onError`, `onLastError`, `onRetry`, `onSettled`, `onSuccess`, `onExecutionTimeout`, and `onTotalExecutionTimeout` for custom side effects.\n * - Call `abort()` to cancel ongoing execution and pending retries.\n * - Call `reset()` to reset state and cancel execution.\n * - Use `getAbortSignal()` to make your async function cancellable.\n * - Use dynamic options (functions) for `maxAttempts`, `baseWait`, and `enabled` based on retryer state.\n *\n * **Important:** This class is designed for single-use execution. Calling `execute()` multiple times\n * on the same instance will abort previous executions. For multiple calls, create a new instance\n * each time.\n *\n * @example\n * ```typescript\n * // Retry a fetch operation up to 5 times with exponential backoff, jitter, and timeouts\n * const retryer = new AsyncRetryer(async (url: string) => {\n * const signal = retryer.getAbortSignal()\n * return await fetch(url, { signal })\n * }, {\n * maxAttempts: 5,\n * backoff: 'exponential',\n * baseWait: 1000,\n * jitter: 0.1, // Add 10% random variation to prevent thundering herd\n * maxExecutionTime: 5000, // Abort individual calls after 5 seconds\n * maxTotalExecutionTime: 30000, // Abort entire operation after 30 seconds\n * onRetry: (attempt, error) => console.log(`Retry attempt ${attempt} after error:`, error),\n * onSuccess: (result) => console.log('Success:', result),\n * onError: (error) => console.error('Error:', error),\n * onLastError: (error) => console.error('All retries failed:', error),\n * })\n *\n * const result = await retryer.execute('/api/data')\n * ```\n *\n * @template TFn The async function type to be retried.\n */\nexport class AsyncRetryer<TFn extends AnyAsyncFunction> {\n readonly store: Store<Readonly<AsyncRetryerState<TFn>>> = new Store(\n getDefaultAsyncRetryerState<TFn>(),\n )\n key: string | undefined\n options: AsyncRetryerOptions<TFn> & typeof defaultOptions\n #abortController: AbortController | null = null\n\n /**\n * Creates a new AsyncRetryer instance\n * @param fn The async function to retry\n * @param initialOptions Configuration options for the retryer\n */\n constructor(\n public fn: TFn,\n initialOptions: AsyncRetryerOptions<TFn> = {},\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError:\n initialOptions.throwOnError ??\n (initialOptions.onError ? false : defaultOptions.throwOnError),\n }\n this.#setState(this.options.initialState ?? {})\n }\n\n /**\n * Updates the retryer options\n * @param newOptions Partial options to merge with existing options\n */\n setOptions = (newOptions: Partial<AsyncRetryerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<AsyncRetryerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isExecuting, currentAttempt } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isExecuting && currentAttempt === 1\n ? 'executing'\n : isExecuting && currentAttempt > 1\n ? 'retrying'\n : 'idle',\n }\n })\n }\n\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n #getMaxAttempts = (): number => {\n return parseFunctionOrValue(this.options.maxAttempts, this)\n }\n\n #getBaseWait = (): number => {\n return parseFunctionOrValue(this.options.baseWait, this)\n }\n\n #getMaxWait = (): number => {\n return parseFunctionOrValue(this.options.maxWait, this)\n }\n\n #calculateJitter = (waitTime: number): number => {\n const jitterAmount = this.options.jitter\n if (jitterAmount <= 0) return 0\n\n try {\n const crypto =\n typeof globalThis !== 'undefined' ? globalThis.crypto : undefined\n if (crypto?.getRandomValues) {\n const array = new Uint32Array(1)\n crypto.getRandomValues(array)\n // Convert to 0-1 range and apply jitter percentage\n const randomFactor = (array[0]! / 0xffffffff) * 2 - 1 // -1 to 1\n return Math.floor(waitTime * jitterAmount * randomFactor)\n }\n } catch {\n // No crypto available\n }\n return 0\n }\n\n #calculateWait = (attempt: number): number => {\n const baseWait = this.#getBaseWait()\n let waitTime: number\n\n switch (this.options.backoff) {\n case 'linear':\n waitTime = baseWait * attempt\n break\n case 'exponential':\n waitTime = baseWait * Math.pow(2, attempt - 1)\n break\n case 'fixed':\n default:\n waitTime = baseWait\n break\n }\n\n waitTime = Math.min(waitTime, this.#getMaxWait())\n\n const jitter = this.#calculateJitter(waitTime)\n return Math.max(0, waitTime + jitter)\n }\n\n /**\n * Executes the function with retry logic\n * @param args Arguments to pass to the function\n * @returns The function result, or undefined if disabled or all retries failed (when throwOnError is false)\n * @throws The last error if throwOnError is true and all retries fail\n */\n execute = async (\n ...args: Parameters<TFn>\n ): Promise<Awaited<ReturnType<TFn>> | undefined> => {\n if (!this.#getEnabled()) {\n return undefined\n }\n\n // Cancel any existing execution\n this.abort('new-execution')\n\n const startTime = Date.now()\n let lastError: Error | undefined\n let result: Awaited<ReturnType<TFn>> | undefined\n\n this.#abortController = new AbortController()\n const signal = this.#abortController.signal\n\n this.#setState({\n isExecuting: true,\n currentAttempt: 0,\n lastError: undefined,\n })\n\n // Set up total execution timeout\n let totalTimeoutId: ReturnType<typeof setTimeout> | undefined\n if (this.options.maxTotalExecutionTime !== Infinity) {\n totalTimeoutId = setTimeout(() => {\n this.options.onTotalExecutionTimeout?.(this)\n this.abort('total-timeout')\n }, this.options.maxTotalExecutionTime)\n }\n\n let isLastAttempt = false\n for (let attempt = 1; attempt <= this.#getMaxAttempts(); attempt++) {\n isLastAttempt = attempt === this.#getMaxAttempts()\n this.#setState({ currentAttempt: attempt })\n\n try {\n if (signal.aborted) {\n return undefined\n }\n\n // Check if total execution time has been exceeded\n const currentTotalTime = Date.now() - startTime\n if (\n this.options.maxTotalExecutionTime !== Infinity &&\n currentTotalTime >= this.options.maxTotalExecutionTime\n ) {\n this.options.onTotalExecutionTimeout?.(this)\n this.abort('total-timeout')\n return undefined\n }\n\n // Execute with individual timeout if specified\n if (this.options.maxExecutionTime === Infinity) {\n result = (await this.fn(...args)) as Awaited<ReturnType<TFn>>\n } else {\n result = (await Promise.race([\n this.fn(...args),\n new Promise<never>((_, reject) => {\n const timeout = setTimeout(() => {\n this.options.onExecutionTimeout?.(this)\n this.abort('execution-timeout')\n reject(\n new Error(\n `Execution timeout: ${this.options.maxExecutionTime}ms exceeded`,\n ),\n )\n }, this.options.maxExecutionTime)\n\n signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timeout)\n reject(new Error('Aborted'))\n },\n { once: true },\n )\n }),\n ])) as Awaited<ReturnType<TFn>>\n }\n\n // Check if cancelled during execution\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (signal.aborted) {\n return undefined\n }\n\n const totalTime = Date.now() - startTime\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n isExecuting: false,\n lastExecutionTime: Date.now(),\n totalExecutionTime: totalTime,\n currentAttempt: 0,\n lastResult: result,\n })\n\n this.options.onSuccess?.(result as Awaited<ReturnType<TFn>>, args, this)\n\n return result\n } catch (error) {\n // Treat abort as a non-error cancellation outcome\n if (\n error &&\n typeof error === 'object' &&\n 'name' in error &&\n (error as Error).name === 'AbortError'\n ) {\n return undefined\n }\n lastError = error instanceof Error ? error : new Error(String(error))\n this.#setState({ lastError })\n\n // Call onError for every error (including during retries)\n this.options.onError?.(lastError, args, this)\n\n if (attempt < this.#getMaxAttempts()) {\n this.options.onRetry?.(attempt, lastError, this)\n\n const wait = this.#calculateWait(attempt)\n if (wait > 0) {\n // Eagerly reflect retrying status during the wait window\n this.#setState({ isExecuting: true, currentAttempt: attempt + 1 })\n await new Promise<void>((resolve) => {\n const timeout = setTimeout(() => {\n signal.removeEventListener('abort', onAbort)\n resolve()\n }, wait)\n const onAbort = () => {\n clearTimeout(timeout)\n signal.removeEventListener('abort', onAbort)\n resolve()\n }\n signal.addEventListener('abort', onAbort)\n })\n if (signal.aborted) {\n return undefined\n }\n }\n }\n } finally {\n this.options.onSettled?.(args, this)\n }\n }\n\n // Clean up total timeout\n if (totalTimeoutId) {\n clearTimeout(totalTimeoutId)\n }\n\n // Exhausted retries - finalize state\n this.#setState({ isExecuting: false })\n this.options.onLastError?.(lastError as Error, this)\n this.options.onSettled?.(args, this)\n\n if (\n (this.options.throwOnError === 'last' && isLastAttempt) ||\n this.options.throwOnError === true\n ) {\n throw lastError\n }\n\n return undefined\n }\n\n /**\n * Returns the current AbortSignal for the executing operation.\n * Use this signal in your async function to make it cancellable.\n * Returns null when not currently executing.\n *\n * @example\n * ```typescript\n * const retryer = new AsyncRetryer(async (userId: string) => {\n * const signal = retryer.getAbortSignal()\n * if (signal) {\n * return fetch(`/api/users/${userId}`, { signal })\n * }\n * return fetch(`/api/users/${userId}`)\n * })\n *\n * // Abort will now actually cancel the fetch\n * retryer.abort()\n * ```\n */\n getAbortSignal = (): AbortSignal | null => {\n return this.#abortController?.signal ?? null\n }\n\n /**\n * Cancels the current execution and any pending retries\n * @param reason The reason for the abort (defaults to 'manual')\n */\n abort = (\n reason:\n | 'manual'\n | 'execution-timeout'\n | 'total-timeout'\n | 'new-execution' = 'manual',\n ): void => {\n if (this.#abortController) {\n this.#abortController.abort()\n this.#abortController = null\n this.#setState({\n isExecuting: false,\n })\n this.options.onAbort?.(reason, this)\n }\n }\n\n /**\n * Resets the retryer to its initial state\n */\n reset = (): void => {\n this.#setState(getDefaultAsyncRetryerState<TFn>())\n }\n}\n\n/**\n * Creates a retry-enabled version of an async function. This is a convenience wrapper\n * around the AsyncRetryer class that returns the execute method.\n *\n * @param fn The async function to add retry functionality to\n * @param initialOptions Configuration options for the retry behavior\n * @returns A new function that executes the original with retry logic\n *\n * @example\n * ```typescript\n * // Define your async function normally\n * async function fetchData(url: string) {\n * const response = await fetch(url)\n * if (!response.ok) throw new Error('Request failed')\n * return response.json()\n * }\n *\n * // Create retry-enabled function\n * const fetchWithRetry = asyncRetry(fetchData, {\n * maxAttempts: 3,\n * backoff: 'exponential',\n * baseWait: 1000,\n * jitter: 0.1\n * })\n *\n * // Call it multiple times\n * const data1 = await fetchWithRetry('/api/data1')\n * const data2 = await fetchWithRetry('/api/data2')\n * ```\n */\nexport function asyncRetry<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncRetryerOptions<TFn> = {},\n): (...args: Parameters<TFn>) => Promise<Awaited<ReturnType<TFn>> | undefined> {\n const retryer = new AsyncRetryer(fn, initialOptions)\n return retryer.execute\n}\n"],"mappings":";;;;;;;;;AA2CA,SAAS,8BAEmB;CAC1B,OAAO;EACL,gBAAgB;EAChB,gBAAgB;EAChB,aAAa;EACb,WAAW;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