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