@tanstack/pacer 0.21.1 → 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 (101) hide show
  1. package/README.md +21 -6
  2. package/dist/async-batcher.d.ts +11 -14
  3. package/dist/async-batcher.js +186 -132
  4. package/dist/async-debouncer.d.ts +10 -13
  5. package/dist/async-debouncer.js +187 -146
  6. package/dist/async-queuer.d.ts +12 -14
  7. package/dist/async-queuer.js +384 -259
  8. package/dist/async-rate-limiter.d.ts +9 -12
  9. package/dist/async-rate-limiter.js +198 -147
  10. package/dist/async-retryer.d.ts +10 -10
  11. package/dist/async-retryer.js +209 -188
  12. package/dist/async-throttler.d.ts +10 -13
  13. package/dist/async-throttler.js +215 -161
  14. package/dist/batcher.d.ts +5 -8
  15. package/dist/batcher.js +107 -87
  16. package/dist/debouncer.d.ts +6 -9
  17. package/dist/debouncer.js +99 -86
  18. package/dist/event-client.d.ts +8 -11
  19. package/dist/event-client.js +1 -2
  20. package/dist/index.js +1 -1
  21. package/dist/queuer.d.ts +8 -10
  22. package/dist/queuer.js +277 -207
  23. package/dist/rate-limiter.d.ts +6 -9
  24. package/dist/rate-limiter.js +127 -109
  25. package/dist/throttler.d.ts +6 -9
  26. package/dist/throttler.js +127 -90
  27. package/dist/types.d.ts +4 -6
  28. package/dist/utils.d.ts +3 -6
  29. package/dist/utils.js +1 -2
  30. package/package.json +23 -70
  31. package/dist/async-batcher.cjs +0 -337
  32. package/dist/async-batcher.cjs.map +0 -1
  33. package/dist/async-batcher.d.cts +0 -344
  34. package/dist/async-batcher.js.map +0 -1
  35. package/dist/async-debouncer.cjs +0 -330
  36. package/dist/async-debouncer.cjs.map +0 -1
  37. package/dist/async-debouncer.d.cts +0 -300
  38. package/dist/async-debouncer.js.map +0 -1
  39. package/dist/async-queuer.cjs +0 -484
  40. package/dist/async-queuer.cjs.map +0 -1
  41. package/dist/async-queuer.d.cts +0 -440
  42. package/dist/async-queuer.js.map +0 -1
  43. package/dist/async-rate-limiter.cjs +0 -373
  44. package/dist/async-rate-limiter.cjs.map +0 -1
  45. package/dist/async-rate-limiter.d.cts +0 -357
  46. package/dist/async-rate-limiter.js.map +0 -1
  47. package/dist/async-retryer.cjs +0 -374
  48. package/dist/async-retryer.cjs.map +0 -1
  49. package/dist/async-retryer.d.cts +0 -319
  50. package/dist/async-retryer.js.map +0 -1
  51. package/dist/async-throttler.cjs +0 -347
  52. package/dist/async-throttler.cjs.map +0 -1
  53. package/dist/async-throttler.d.cts +0 -320
  54. package/dist/async-throttler.js.map +0 -1
  55. package/dist/batcher.cjs +0 -200
  56. package/dist/batcher.cjs.map +0 -1
  57. package/dist/batcher.d.cts +0 -180
  58. package/dist/batcher.js.map +0 -1
  59. package/dist/debouncer.cjs +0 -203
  60. package/dist/debouncer.cjs.map +0 -1
  61. package/dist/debouncer.d.cts +0 -167
  62. package/dist/debouncer.js.map +0 -1
  63. package/dist/event-client.cjs +0 -64
  64. package/dist/event-client.cjs.map +0 -1
  65. package/dist/event-client.d.cts +0 -66
  66. package/dist/event-client.js.map +0 -1
  67. package/dist/index.cjs +0 -52
  68. package/dist/index.d.cts +0 -15
  69. package/dist/queuer.cjs +0 -401
  70. package/dist/queuer.cjs.map +0 -1
  71. package/dist/queuer.d.cts +0 -345
  72. package/dist/queuer.js.map +0 -1
  73. package/dist/rate-limiter.cjs +0 -263
  74. package/dist/rate-limiter.cjs.map +0 -1
  75. package/dist/rate-limiter.d.cts +0 -215
  76. package/dist/rate-limiter.js.map +0 -1
  77. package/dist/throttler.cjs +0 -215
  78. package/dist/throttler.cjs.map +0 -1
  79. package/dist/throttler.d.cts +0 -207
  80. package/dist/throttler.js.map +0 -1
  81. package/dist/types.cjs +0 -0
  82. package/dist/types.d.cts +0 -13
  83. package/dist/utils.cjs +0 -14
  84. package/dist/utils.cjs.map +0 -1
  85. package/dist/utils.d.cts +0 -8
  86. package/dist/utils.js.map +0 -1
  87. package/src/async-batcher.ts +0 -594
  88. package/src/async-debouncer.ts +0 -565
  89. package/src/async-queuer.ts +0 -925
  90. package/src/async-rate-limiter.ts +0 -647
  91. package/src/async-retryer.ts +0 -684
  92. package/src/async-throttler.ts +0 -633
  93. package/src/batcher.ts +0 -329
  94. package/src/debouncer.ts +0 -334
  95. package/src/event-client.ts +0 -129
  96. package/src/index.ts +0 -24
  97. package/src/queuer.ts +0 -740
  98. package/src/rate-limiter.ts +0 -429
  99. package/src/throttler.ts +0 -380
  100. package/src/types.ts +0 -12
  101. package/src/utils.ts +0 -12
@@ -1,357 +0,0 @@
1
- import { AnyAsyncFunction } from "./types.cjs";
2
- import { AsyncRetryer, AsyncRetryerOptions } from "./async-retryer.cjs";
3
- import { Store } from "@tanstack/store";
4
-
5
- //#region src/async-rate-limiter.d.ts
6
- interface AsyncRateLimiterState<TFn extends AnyAsyncFunction> {
7
- /**
8
- * Number of function executions that have resulted in errors
9
- */
10
- errorCount: number;
11
- /**
12
- * Array of timestamps when executions occurred for rate limiting calculations
13
- */
14
- executionTimes: Array<number>;
15
- /**
16
- * Whether the rate limiter has exceeded the limit
17
- */
18
- isExceeded: boolean;
19
- /**
20
- * Whether the rate-limited function is currently executing asynchronously
21
- */
22
- isExecuting: boolean;
23
- /**
24
- * The result from the most recent successful function execution
25
- */
26
- lastResult: ReturnType<TFn> | undefined;
27
- /**
28
- * Number of function executions that have been rejected due to rate limiting
29
- */
30
- rejectionCount: number;
31
- /**
32
- * Number of function executions that have completed (either successfully or with errors)
33
- */
34
- settleCount: number;
35
- /**
36
- * Current execution status - 'disabled' when not active, 'executing' when executing, 'idle' when not executing, 'exceeded' when rate limit is exceeded
37
- */
38
- status: 'disabled' | 'executing' | 'exceeded' | 'idle';
39
- /**
40
- * Number of function executions that have completed successfully
41
- */
42
- successCount: number;
43
- /**
44
- * Number of times maybeExecute has been called (for reduction calculations)
45
- */
46
- maybeExecuteCount: number;
47
- }
48
- /**
49
- * Options for configuring an async rate-limited function
50
- */
51
- interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
52
- /**
53
- * Options for configuring the underlying async retryer
54
- */
55
- asyncRetryerOptions?: AsyncRetryerOptions<TFn>;
56
- /**
57
- * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
58
- * Can be a boolean or a function that returns a boolean.
59
- * Defaults to true.
60
- */
61
- enabled?: boolean | ((rateLimiter: AsyncRateLimiter<TFn>) => boolean);
62
- /**
63
- * Initial state for the rate limiter
64
- */
65
- initialState?: Partial<AsyncRateLimiterState<TFn>>;
66
- /**
67
- * Optional key to identify this async rate limiter instance.
68
- * If provided, the async rate limiter will be identified by this key in the devtools and PacerProvider if applicable.
69
- */
70
- key?: string;
71
- /**
72
- * Maximum number of executions allowed within the time window.
73
- * Can be a number or a function that returns a number.
74
- */
75
- limit: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number);
76
- /**
77
- * Optional error handler for when the rate-limited function throws.
78
- * If provided, the handler will be called with the error and rate limiter instance.
79
- * This can be used alongside throwOnError - the handler will be called before any error is thrown.
80
- */
81
- onError?: (error: Error, args: Parameters<TFn>, rateLimiter: AsyncRateLimiter<TFn>) => void;
82
- /**
83
- * Optional callback function that is called when an execution is rejected due to rate limiting
84
- */
85
- onReject?: (args: Parameters<TFn>, rateLimiter: AsyncRateLimiter<TFn>) => void;
86
- /**
87
- * Optional function to call when the rate-limited function is executed
88
- */
89
- onSettled?: (args: Parameters<TFn>, rateLimiter: AsyncRateLimiter<TFn>) => void;
90
- /**
91
- * Optional function to call when the rate-limited function is executed
92
- */
93
- onSuccess?: (result: ReturnType<TFn>, args: Parameters<TFn>, rateLimiter: AsyncRateLimiter<TFn>) => void;
94
- /**
95
- * Whether to throw errors when they occur.
96
- * Defaults to true if no onError handler is provided, false if an onError handler is provided.
97
- * Can be explicitly set to override these defaults.
98
- */
99
- throwOnError?: boolean;
100
- /**
101
- * Time window in milliseconds within which the limit applies.
102
- * Can be a number or a function that returns a number.
103
- */
104
- window: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number);
105
- /**
106
- * Type of window to use for rate limiting
107
- * - 'fixed': Uses a fixed window that resets after the window period
108
- * - 'sliding': Uses a sliding window that allows executions as old ones expire
109
- * Defaults to 'fixed'
110
- */
111
- windowType?: 'fixed' | 'sliding';
112
- }
113
- /**
114
- * Utility function for sharing common `AsyncRateLimiterOptions` options between different `AsyncRateLimiter` instances.
115
- */
116
- declare function asyncRateLimiterOptions<TFn extends AnyAsyncFunction = AnyAsyncFunction, TOptions extends Partial<AsyncRateLimiterOptions<TFn>> = Partial<AsyncRateLimiterOptions<TFn>>>(options: TOptions): TOptions;
117
- /**
118
- * A class that creates an async rate-limited function.
119
- *
120
- * Async vs Sync Versions:
121
- * The async version provides advanced features over the sync RateLimiter:
122
- * - Returns promises that can be awaited for rate-limited function results
123
- * - Built-in retry support via AsyncRetryer integration
124
- * - Abort support to cancel in-flight executions
125
- * - Comprehensive error handling with onError callbacks and throwOnError control
126
- * - Detailed execution tracking (success/error/settle counts, rejection counts)
127
- * - More sophisticated window management with automatic cleanup
128
- *
129
- * The sync RateLimiter is lighter weight and simpler when you don't need async features,
130
- * return values, or execution control.
131
- *
132
- * What is Rate Limiting?
133
- * Rate limiting allows a function to execute up to a limit within a time window,
134
- * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
135
- * all executions happen immediately, followed by a complete block.
136
- *
137
- * Window Types:
138
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
139
- * towards the limit, and the window resets completely after the period.
140
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
141
- * consistent rate of execution over time.
142
- *
143
- * When to Use Rate Limiting:
144
- * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
145
- * smoothing out frequent events, throttling or debouncing usually provide better user experience.
146
- * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
147
- * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
148
- *
149
- * State Management:
150
- * - Uses TanStack Store for reactive state management
151
- * - Use `initialState` to provide initial state values when creating the rate limiter
152
- * - `initialState` can be a partial state object
153
- * - Use `onSuccess` callback to react to successful function execution and implement custom logic
154
- * - Use `onError` callback to react to function execution errors and implement custom error handling
155
- * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
156
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
157
- * - The state includes execution times, success/error counts, and current execution status
158
- * - State can be accessed via `asyncRateLimiter.store.state` when using the class directly
159
- * - When using framework adapters (React/Solid), state is accessed from `asyncRateLimiter.state`
160
- *
161
- * Error Handling:
162
- * - If an `onError` handler is provided, it will be called with the error and rate limiter instance
163
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
164
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
165
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
166
- * - The error state can be checked using the underlying AsyncRateLimiter instance
167
- * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler
168
- *
169
- * @example
170
- * ```ts
171
- * const rateLimiter = new AsyncRateLimiter(
172
- * async (id: string) => await api.getData(id),
173
- * {
174
- * limit: 5,
175
- * window: 1000,
176
- * windowType: 'sliding',
177
- * onError: (error) => {
178
- * console.error('API call failed:', error);
179
- * },
180
- * onReject: (limiter) => {
181
- * console.log(`Rate limit exceeded. Try again in ${limiter.getMsUntilNextWindow()}ms`);
182
- * }
183
- * }
184
- * );
185
- *
186
- * // Will execute immediately until limit reached, then block
187
- * // Returns the API response directly
188
- * const data = await rateLimiter.maybeExecute('123');
189
- * ```
190
- */
191
- declare class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
192
- #private;
193
- fn: TFn;
194
- readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>;
195
- key: string | undefined;
196
- options: AsyncRateLimiterOptions<TFn>;
197
- asyncRetryers: Map<number, AsyncRetryer<TFn>>;
198
- constructor(fn: TFn, initialOptions: AsyncRateLimiterOptions<TFn>);
199
- /**
200
- * Updates the async rate limiter options
201
- */
202
- setOptions: (newOptions: Partial<AsyncRateLimiterOptions<TFn>>) => void;
203
- /**
204
- * Attempts to execute the rate-limited function if within the configured limits.
205
- * Will reject execution if the number of calls in the current window exceeds the limit.
206
- *
207
- * Error Handling:
208
- * - If the rate-limited function throws and no `onError` handler is configured,
209
- * the error will be thrown from this method.
210
- * - If an `onError` handler is configured, errors will be caught and passed to the handler,
211
- * and this method will return undefined.
212
- * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
213
- *
214
- * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
215
- * @throws The error from the rate-limited function if no onError handler is configured
216
- *
217
- * @example
218
- * ```ts
219
- * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
220
- *
221
- * // First 5 calls will return a promise that resolves with the result
222
- * const result = await rateLimiter.maybeExecute('arg1', 'arg2');
223
- *
224
- * // Additional calls within the window will return undefined
225
- * const result2 = await rateLimiter.maybeExecute('arg1', 'arg2'); // undefined
226
- * ```
227
- */
228
- maybeExecute: (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
229
- /**
230
- * Returns the number of remaining executions allowed in the current window
231
- */
232
- getRemainingInWindow: () => number;
233
- /**
234
- * Returns the number of milliseconds until the next execution will be possible
235
- * For fixed windows, this is the time until the current window resets
236
- * For sliding windows, this is the time until the oldest execution expires
237
- */
238
- getMsUntilNextWindow: () => number;
239
- /**
240
- * Returns the AbortSignal for a specific execution.
241
- * If no maybeExecuteCount is provided, returns the signal for the most recent execution.
242
- * Returns null if no execution is found or not currently executing.
243
- *
244
- * @param maybeExecuteCount - Optional specific execution to get signal for
245
- * @example
246
- * ```typescript
247
- * const rateLimiter = new AsyncRateLimiter(
248
- * async (userId: string) => {
249
- * const signal = rateLimiter.getAbortSignal()
250
- * if (signal) {
251
- * const response = await fetch(`/api/users/${userId}`, { signal })
252
- * return response.json()
253
- * }
254
- * },
255
- * { limit: 5, window: 1000 }
256
- * )
257
- * ```
258
- */
259
- getAbortSignal: (maybeExecuteCount?: number) => AbortSignal | null;
260
- /**
261
- * Aborts all ongoing executions with the internal abort controllers.
262
- * Does NOT clear out the execution times or reset the rate limiter.
263
- */
264
- abort: () => void;
265
- /**
266
- * Resets the rate limiter state
267
- */
268
- reset: () => void;
269
- }
270
- /**
271
- * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.
272
- *
273
- * Async vs Sync Versions:
274
- * The async version provides advanced features over the sync rate limit function:
275
- * - Returns promises that can be awaited for rate-limited function results
276
- * - Built-in retry support via AsyncRetryer integration
277
- * - Abort support to cancel in-flight executions
278
- * - Comprehensive error handling with onError callbacks and throwOnError control
279
- * - Detailed execution tracking (success/error/settle counts, rejection counts)
280
- * - More sophisticated window management with automatic cleanup
281
- *
282
- * The sync rate limit function is lighter weight and simpler when you don't need async features,
283
- * return values, or execution control.
284
- *
285
- * What is Rate Limiting?
286
- * Rate limiting allows a function to execute up to a limit within a time window,
287
- * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
288
- * all executions happen immediately, followed by a complete block.
289
- *
290
- * Window Types:
291
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
292
- * towards the limit, and the window resets completely after the period.
293
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
294
- * consistent rate of execution over time.
295
- *
296
- * Configuration Options:
297
- * - `limit`: Maximum number of executions allowed within the window (required)
298
- * - `window`: Time window in milliseconds (required)
299
- * - `windowType`: 'fixed' or 'sliding' (default: 'fixed')
300
- * - `enabled`: Whether the rate limiter is enabled (default: true)
301
- * - `asyncRetryerOptions`: Configure retry behavior for executions
302
- *
303
- * When to Use Rate Limiting:
304
- * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
305
- * smoothing out frequent events, throttling or debouncing usually provide better user experience.
306
- * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
307
- * - A throttler ensures even spacing between executions, which can be better for consistent performance
308
- * - A debouncer collapses multiple calls into one, which is better for handling bursts of events
309
- *
310
- * Error Handling:
311
- * - If an `onError` handler is provided, it will be called with the error and rate limiter instance
312
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
313
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
314
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
315
- * - The error state can be checked using the underlying AsyncRateLimiter instance
316
- * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler
317
- *
318
- * State Management:
319
- * - Uses TanStack Store for reactive state management
320
- * - Use `initialState` to provide initial state values when creating the rate limiter
321
- * - `initialState` can be a partial state object
322
- * - Use `onSuccess` callback to react to successful function execution and implement custom logic
323
- * - Use `onError` callback to react to function execution errors and implement custom error handling
324
- * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
325
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
326
- * - The state includes execution times, success/error counts, and current execution status
327
- * - State can be accessed via the underlying AsyncRateLimiter instance's `store.state` property
328
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
329
- *
330
- * @example
331
- * ```ts
332
- * // Rate limit to 5 calls per minute with a sliding window
333
- * const rateLimited = asyncRateLimit(makeApiCall, {
334
- * limit: 5,
335
- * window: 60000,
336
- * windowType: 'sliding',
337
- * onError: (error) => {
338
- * console.error('API call failed:', error);
339
- * },
340
- * onReject: (rateLimiter) => {
341
- * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
342
- * }
343
- * });
344
- *
345
- * // First 5 calls will execute immediately
346
- * // Additional calls will be rejected until the minute window resets
347
- * // Returns the API response directly
348
- * const result = await rateLimited();
349
- *
350
- * // For more even execution, consider using throttle instead:
351
- * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
352
- * ```
353
- */
354
- declare function asyncRateLimit<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: AsyncRateLimiterOptions<TFn>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
355
- //#endregion
356
- export { AsyncRateLimiter, AsyncRateLimiterOptions, AsyncRateLimiterState, asyncRateLimit, asyncRateLimiterOptions };
357
- //# sourceMappingURL=async-rate-limiter.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"async-rate-limiter.js","names":["#getLimit","#getEnabled","#setState","#cleanupOldExecutions","#getExecutionTimesInWindow","#execute","#setCleanupTimeout","#getWindow","#timeoutIds","#clearTimeout","#clearTimeouts"],"sources":["../src/async-rate-limiter.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { AsyncRetryer } from './async-retryer'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AsyncRetryerOptions } from './async-retryer'\nimport type { AnyAsyncFunction } from './types'\n\nexport interface AsyncRateLimiterState<TFn extends AnyAsyncFunction> {\n /**\n * Number of function executions that have resulted in errors\n */\n errorCount: number\n /**\n * Array of timestamps when executions occurred for rate limiting calculations\n */\n executionTimes: Array<number>\n /**\n * Whether the rate limiter has exceeded the limit\n */\n isExceeded: boolean\n /**\n * Whether the rate-limited function is currently executing asynchronously\n */\n isExecuting: boolean\n /**\n * The result from the most recent successful function execution\n */\n lastResult: ReturnType<TFn> | undefined\n /**\n * Number of function executions that have been rejected due to rate limiting\n */\n rejectionCount: number\n /**\n * Number of function executions that have completed (either successfully or with errors)\n */\n settleCount: number\n /**\n * Current execution status - 'disabled' when not active, 'executing' when executing, 'idle' when not executing, 'exceeded' when rate limit is exceeded\n */\n status: 'disabled' | 'executing' | 'exceeded' | 'idle'\n /**\n * Number of function executions that have completed successfully\n */\n successCount: number\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n}\n\nfunction getDefaultAsyncRateLimiterState<\n TFn extends AnyAsyncFunction,\n>(): AsyncRateLimiterState<TFn> {\n return {\n errorCount: 0,\n executionTimes: [],\n isExceeded: false,\n isExecuting: false,\n lastResult: undefined,\n maybeExecuteCount: 0,\n rejectionCount: 0,\n settleCount: 0,\n status: 'idle',\n successCount: 0,\n }\n}\n\n/**\n * Options for configuring an async rate-limited function\n */\nexport interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {\n /**\n * Options for configuring the underlying async retryer\n */\n asyncRetryerOptions?: AsyncRetryerOptions<TFn>\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((rateLimiter: AsyncRateLimiter<TFn>) => boolean)\n /**\n * Initial state for the rate limiter\n */\n initialState?: Partial<AsyncRateLimiterState<TFn>>\n /**\n * Optional key to identify this async rate limiter instance.\n * If provided, the async rate limiter will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a function that returns a number.\n */\n limit: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number)\n /**\n * Optional error handler for when the rate-limited function throws.\n * If provided, the handler will be called with the error and rate limiter instance.\n * This can be used alongside throwOnError - the handler will be called before any error is thrown.\n */\n onError?: (\n error: Error,\n args: Parameters<TFn>,\n rateLimiter: AsyncRateLimiter<TFn>,\n ) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (args: Parameters<TFn>, rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSettled?: (\n args: Parameters<TFn>,\n rateLimiter: AsyncRateLimiter<TFn>,\n ) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n args: Parameters<TFn>,\n rateLimiter: AsyncRateLimiter<TFn>,\n ) => void\n /**\n * Whether to throw errors when they occur.\n * Defaults to true if no onError handler is provided, false if an onError handler is provided.\n * Can be explicitly set to override these defaults.\n */\n throwOnError?: boolean\n /**\n * Time window in milliseconds within which the limit applies.\n * Can be a number or a function that returns a number.\n */\n window: number | ((rateLimiter: AsyncRateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\n/**\n * Utility function for sharing common `AsyncRateLimiterOptions` options between different `AsyncRateLimiter` instances.\n */\nexport function asyncRateLimiterOptions<\n TFn extends AnyAsyncFunction = AnyAsyncFunction,\n TOptions extends Partial<AsyncRateLimiterOptions<TFn>> = Partial<\n AsyncRateLimiterOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<AsyncRateLimiterOptions<any>>,\n 'initialState' | 'onError' | 'onReject' | 'onSettled' | 'onSuccess' | 'key'\n> = {\n asyncRetryerOptions: {\n maxAttempts: 1,\n },\n enabled: true,\n limit: 1,\n window: 0,\n windowType: 'fixed',\n throwOnError: true,\n}\n\n/**\n * A class that creates an async rate-limited function.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync RateLimiter:\n * - Returns promises that can be awaited for rate-limited function results\n * - Built-in retry support via AsyncRetryer integration\n * - Abort support to cancel in-flight executions\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts, rejection counts)\n * - More sophisticated window management with automatic cleanup\n *\n * The sync RateLimiter is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Rate Limiting?\n * Rate limiting allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * Window Types:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * When to Use Rate Limiting:\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - `initialState` can be a partial state object\n * - Use `onSuccess` callback to react to successful function execution and implement custom logic\n * - Use `onError` callback to react to function execution errors and implement custom error handling\n * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution times, success/error counts, and current execution status\n * - State can be accessed via `asyncRateLimiter.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `asyncRateLimiter.state`\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(\n * async (id: string) => await api.getData(id),\n * {\n * limit: 5,\n * window: 1000,\n * windowType: 'sliding',\n * onError: (error) => {\n * console.error('API call failed:', error);\n * },\n * onReject: (limiter) => {\n * console.log(`Rate limit exceeded. Try again in ${limiter.getMsUntilNextWindow()}ms`);\n * }\n * }\n * );\n *\n * // Will execute immediately until limit reached, then block\n * // Returns the API response directly\n * const data = await rateLimiter.maybeExecute('123');\n * ```\n */\nexport class AsyncRateLimiter<TFn extends AnyAsyncFunction> {\n readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>> = new Store<\n AsyncRateLimiterState<TFn>\n >(getDefaultAsyncRateLimiterState<TFn>())\n key: string | undefined\n options: AsyncRateLimiterOptions<TFn>\n asyncRetryers = new Map<number, AsyncRetryer<TFn>>()\n #timeoutIds: Set<ReturnType<typeof setTimeout>> = new Set()\n\n constructor(\n public fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n this.#setState(this.options.initialState ?? {})\n for (const executionTime of this.#getExecutionTimesInWindow()) {\n this.#setCleanupTimeout(executionTime)\n }\n\n if (this.key) {\n pacerEventClient.on('d-AsyncRateLimiter', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<AsyncRateLimiterState<TFn>>,\n )\n this.setOptions(\n event.payload.options as Partial<AsyncRateLimiterOptions<TFn>>,\n )\n })\n }\n }\n\n /**\n * Updates the async rate limiter options\n */\n setOptions = (newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<AsyncRateLimiterState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const isExceeded = combinedState.executionTimes.length >= this.#getLimit()\n const status = !this.#getEnabled()\n ? 'disabled'\n : combinedState.isExecuting\n ? 'executing'\n : isExceeded\n ? 'exceeded'\n : 'idle'\n return {\n ...combinedState,\n isExceeded,\n status,\n }\n })\n emitChange('AsyncRateLimiter', this)\n }\n\n /**\n * Returns the current enabled state of the async rate limiter\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current limit of executions allowed within the time window\n */\n #getLimit = (): number => {\n return parseFunctionOrValue(this.options.limit, this)\n }\n\n /**\n * Returns the current time window in milliseconds\n */\n #getWindow = (): number => {\n return parseFunctionOrValue(this.options.window, this)\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n *\n * Error Handling:\n * - If the rate-limited function throws and no `onError` handler is configured,\n * the error will be thrown from this method.\n * - If an `onError` handler is configured, errors will be caught and passed to the handler,\n * and this method will return undefined.\n * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.\n *\n * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError\n * @throws The error from the rate-limited function if no onError handler is configured\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return a promise that resolves with the result\n * const result = await rateLimiter.maybeExecute('arg1', 'arg2');\n *\n * // Additional calls within the window will return undefined\n * const result2 = await rateLimiter.maybeExecute('arg1', 'arg2'); // undefined\n * ```\n */\n maybeExecute = async (\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> => {\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n this.#cleanupOldExecutions()\n\n const relevantExecutionTimes = this.#getExecutionTimesInWindow()\n\n if (relevantExecutionTimes.length < this.#getLimit()) {\n await this.#execute(...args)\n return this.store.state.lastResult\n }\n\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(args, this)\n return undefined\n }\n\n #execute = async (\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> => {\n if (!this.#getEnabled()) return\n\n const currentMaybeExecute = this.store.state.maybeExecuteCount\n const now = Date.now()\n const executionTimes = [...this.store.state.executionTimes, now]\n this.#setState({\n isExecuting: true,\n executionTimes,\n })\n\n try {\n // Create a new AsyncRetryer for this execution to avoid cancelling concurrent executions\n const currentAsyncRetryer = new AsyncRetryer(this.fn, {\n ...this.options.asyncRetryerOptions,\n key: `${this.key}-retryer-${currentMaybeExecute}`,\n })\n this.asyncRetryers.set(currentMaybeExecute, currentAsyncRetryer)\n const result = await currentAsyncRetryer.execute(...args) // EXECUTE!\n this.#setCleanupTimeout(now)\n this.#setState({\n successCount: this.store.state.successCount + 1,\n lastResult: result,\n })\n this.options.onSuccess?.(result as ReturnType<TFn>, args, this)\n } catch (error) {\n this.#setState({\n errorCount: this.store.state.errorCount + 1,\n })\n this.options.onError?.(error as Error, args, this)\n if (this.options.throwOnError) {\n throw error\n }\n } finally {\n this.asyncRetryers.delete(currentMaybeExecute) // dispose retryer\n this.#setState({\n isExecuting: false,\n settleCount: this.store.state.settleCount + 1,\n })\n this.options.onSettled?.(args, this)\n }\n\n return this.store.state.lastResult\n }\n\n #getExecutionTimesInWindow = (): Array<number> => {\n if (this.options.windowType === 'sliding') {\n // For sliding window, return all executions within the current window\n return this.store.state.executionTimes.filter(\n (time) => time > Date.now() - this.#getWindow(),\n )\n } else {\n // For fixed window, return all executions in the current window\n // The window starts from the oldest execution time\n if (this.store.state.executionTimes.length === 0) {\n return []\n }\n const oldestExecution = Math.min(...this.store.state.executionTimes)\n const windowStart = oldestExecution\n const windowEnd = windowStart + this.#getWindow()\n const now = Date.now()\n\n // If the window has expired, return empty array\n if (now > windowEnd) {\n return []\n }\n\n // Otherwise, return all executions in the current window\n return this.store.state.executionTimes.filter(\n (time) => time >= windowStart && time <= windowEnd,\n )\n }\n }\n\n #setCleanupTimeout = (executionTime: number): void => {\n if (\n this.options.windowType === 'sliding' ||\n this.#timeoutIds.size === 0 // new fixed window\n ) {\n const now = Date.now()\n const timeUntilExpiration = executionTime - now + this.#getWindow() + 1\n const timeoutId = setTimeout(() => {\n this.#cleanupOldExecutions()\n this.#clearTimeout(timeoutId)\n }, timeUntilExpiration)\n this.#timeoutIds.add(timeoutId)\n }\n }\n\n #clearTimeout = (timeoutId: ReturnType<typeof setTimeout>): void => {\n clearTimeout(timeoutId)\n this.#timeoutIds.delete(timeoutId)\n }\n\n #clearTimeouts = (): void => {\n this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))\n this.#timeoutIds.clear()\n }\n\n #cleanupOldExecutions = (): void => {\n this.#setState({\n executionTimes: this.#getExecutionTimesInWindow(),\n })\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow = (): number => {\n const relevantExecutionTimes = this.#getExecutionTimesInWindow()\n return Math.max(0, this.#getLimit() - relevantExecutionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n * For fixed windows, this is the time until the current window resets\n * For sliding windows, this is the time until the oldest execution expires\n */\n getMsUntilNextWindow = (): number => {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = this.store.state.executionTimes[0] ?? Infinity\n return oldestExecution + this.#getWindow() - Date.now()\n }\n\n /**\n * Returns the AbortSignal for a specific execution.\n * If no maybeExecuteCount is provided, returns the signal for the most recent execution.\n * Returns null if no execution is found or not currently executing.\n *\n * @param maybeExecuteCount - Optional specific execution to get signal for\n * @example\n * ```typescript\n * const rateLimiter = new AsyncRateLimiter(\n * async (userId: string) => {\n * const signal = rateLimiter.getAbortSignal()\n * if (signal) {\n * const response = await fetch(`/api/users/${userId}`, { signal })\n * return response.json()\n * }\n * },\n * { limit: 5, window: 1000 }\n * )\n * ```\n */\n getAbortSignal = (maybeExecuteCount?: number): AbortSignal | null => {\n const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount\n const retryer = this.asyncRetryers.get(count)\n return retryer?.getAbortSignal() ?? null\n }\n\n /**\n * Aborts all ongoing executions with the internal abort controllers.\n * Does NOT clear out the execution times or reset the rate limiter.\n */\n abort = (): void => {\n this.asyncRetryers.forEach((retryer) => retryer.abort())\n this.asyncRetryers.clear()\n this.#setState({\n isExecuting: false,\n })\n }\n\n /**\n * Resets the rate limiter state\n */\n reset = (): void => {\n this.#setState(getDefaultAsyncRateLimiterState())\n this.#clearTimeouts()\n this.asyncRetryers.forEach((retryer) => retryer.reset())\n }\n}\n\n/**\n * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync rate limit function:\n * - Returns promises that can be awaited for rate-limited function results\n * - Built-in retry support via AsyncRetryer integration\n * - Abort support to cancel in-flight executions\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts, rejection counts)\n * - More sophisticated window management with automatic cleanup\n *\n * The sync rate limit function is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Rate Limiting?\n * Rate limiting allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * Window Types:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Configuration Options:\n * - `limit`: Maximum number of executions allowed within the window (required)\n * - `window`: Time window in milliseconds (required)\n * - `windowType`: 'fixed' or 'sliding' (default: 'fixed')\n * - `enabled`: Whether the rate limiter is enabled (default: true)\n * - `asyncRetryerOptions`: Configure retry behavior for executions\n *\n * When to Use Rate Limiting:\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - `initialState` can be a partial state object\n * - Use `onSuccess` callback to react to successful function execution and implement custom logic\n * - Use `onError` callback to react to function execution errors and implement custom error handling\n * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution times, success/error counts, and current execution status\n * - State can be accessed via the underlying AsyncRateLimiter instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = asyncRateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * onError: (error) => {\n * console.error('API call failed:', error);\n * },\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * // Returns the API response directly\n * const result = await rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function asyncRateLimit<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute\n}\n"],"mappings":";;;;;;AAkDA,SAAS,kCAEuB;CAC9B,OAAO;EACL,YAAY;EACZ,gBAAgB,EAAE;EAClB,YAAY;EACZ,aAAa;EACb,YAAY;EACZ,mBAAmB;EACnB,gBAAgB;EAChB,aAAa;EACb,QAAQ;EACR,cAAc;EACf;;;;;AAmFH,SAAgB,wBAKd,SAA6B;CAC7B,OAAO;;AAGT,MAAM,iBAGF;CACF,qBAAqB,EACnB,aAAa,GACd;CACD,SAAS;CACT,OAAO;CACP,QAAQ;CACR,YAAY;CACZ,cAAc;CACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4ED,IAAa,mBAAb,MAA4D;CAO1D;CAEA,YACE,AAAO,IACP,gBACA;EAFO;eATqD,IAAI,MAEhE,iCAAsC,CAAC;uCAGzB,IAAI,KAAgC;qCACF,IAAI,KAAK;qBAiC7C,eAA4D;GACxE,KAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;IAAY;;oBAGtC,aAAwD;GACnE,KAAK,MAAM,UAAU,UAAU;IAC7B,MA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