@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,429 +0,0 @@
1
- import { Store } from '@tanstack/store'
2
- import { parseFunctionOrValue } from './utils'
3
- import { emitChange, pacerEventClient } from './event-client'
4
- import type { AnyFunction } from './types'
5
-
6
- export interface RateLimiterState {
7
- /**
8
- * Number of function executions that have been completed
9
- */
10
- executionCount: 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
- * Number of times maybeExecute has been called (for reduction calculations)
21
- */
22
- maybeExecuteCount: number
23
- /**
24
- * Number of function executions that have been rejected due to rate limiting
25
- */
26
- rejectionCount: number
27
- /**
28
- * Current execution status - 'disabled' when not active, 'executing' when executing, 'idle' when not executing, 'exceeded' when rate limit is exceeded
29
- */
30
- status: 'disabled' | 'exceeded' | 'idle'
31
- }
32
-
33
- function getDefaultRateLimiterState(): RateLimiterState {
34
- return {
35
- executionCount: 0,
36
- executionTimes: [],
37
- isExceeded: false,
38
- rejectionCount: 0,
39
- status: 'idle',
40
- maybeExecuteCount: 0,
41
- }
42
- }
43
-
44
- /**
45
- * Options for configuring a rate-limited function
46
- */
47
- export interface RateLimiterOptions<TFn extends AnyFunction> {
48
- /**
49
- * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
50
- * Defaults to true.
51
- */
52
- enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean)
53
- /**
54
- * Initial state for the rate limiter
55
- */
56
- initialState?: Partial<RateLimiterState>
57
- /**
58
- * Optional key to identify this rate limiter instance.
59
- * If provided, the rate limiter will be identified by this key in the devtools and PacerProvider if applicable.
60
- */
61
- key?: string
62
- /**
63
- * Maximum number of executions allowed within the time window.
64
- * Can be a number or a callback function that receives the rate limiter instance and returns a number.
65
- */
66
- limit: number | ((rateLimiter: RateLimiter<TFn>) => number)
67
- /**
68
- * Callback function that is called after the function is executed
69
- */
70
- onExecute?: (args: Parameters<TFn>, rateLimiter: RateLimiter<TFn>) => void
71
- /**
72
- * Optional callback function that is called when an execution is rejected due to rate limiting
73
- */
74
- onReject?: (rateLimiter: RateLimiter<TFn>) => void
75
- /**
76
- * Time window in milliseconds within which the limit applies.
77
- * Can be a number or a callback function that receives the rate limiter instance and returns a number.
78
- */
79
- window: number | ((rateLimiter: RateLimiter<TFn>) => number)
80
- /**
81
- * Type of window to use for rate limiting
82
- * - 'fixed': Uses a fixed window that resets after the window period
83
- * - 'sliding': Uses a sliding window that allows executions as old ones expire
84
- * Defaults to 'fixed'
85
- */
86
- windowType?: 'fixed' | 'sliding'
87
- }
88
-
89
- /**
90
- * Utility function for sharing common `RateLimiterOptions` options between different `RateLimiter` instances.
91
- */
92
- export function rateLimiterOptions<
93
- TFn extends AnyFunction = AnyFunction,
94
- TOptions extends Partial<RateLimiterOptions<TFn>> = Partial<
95
- RateLimiterOptions<TFn>
96
- >,
97
- >(options: TOptions): TOptions {
98
- return options
99
- }
100
-
101
- const defaultOptions: Omit<
102
- Required<RateLimiterOptions<any>>,
103
- 'initialState' | 'onExecute' | 'onReject' | 'key'
104
- > = {
105
- enabled: true,
106
- limit: 1,
107
- window: 0,
108
- windowType: 'fixed',
109
- }
110
-
111
- /**
112
- * A class that creates a rate-limited function.
113
- *
114
- * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
115
- * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
116
- * all executions happen immediately, followed by a complete block.
117
- * This synchronous version is lighter weight and often all you need - upgrade to AsyncRateLimiter when you need promises, retry support, abort capabilities, or advanced error handling.
118
- *
119
- * The rate limiter supports two types of windows:
120
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
121
- * towards the limit, and the window resets completely after the period.
122
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
123
- * consistent rate of execution over time.
124
- *
125
- * For smoother execution patterns, consider using:
126
- * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
127
- * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
128
- *
129
- * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
130
- * smoothing out frequent events, throttling or debouncing usually provide better user experience.
131
- *
132
- * State Management:
133
- * - Uses TanStack Store for reactive state management
134
- * - Use `initialState` to provide initial state values when creating the rate limiter
135
- * - Use `onExecute` callback to react to function execution and implement custom logic
136
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
137
- * - The state includes execution count, execution times, and rejection count
138
- * - State can be accessed via `rateLimiter.store.state` when using the class directly
139
- * - When using framework adapters (React/Solid), state is accessed from `rateLimiter.state`
140
- *
141
- * @example
142
- * ```ts
143
- * const rateLimiter = new RateLimiter(
144
- * (id: string) => api.getData(id),
145
- * {
146
- * limit: 5,
147
- * window: 1000,
148
- * windowType: 'sliding',
149
- * }
150
- * );
151
- *
152
- * // Will execute immediately until limit reached, then block
153
- * rateLimiter.maybeExecute('123');
154
- * ```
155
- */
156
- export class RateLimiter<TFn extends AnyFunction> {
157
- readonly store: Store<Readonly<RateLimiterState>> =
158
- new Store<RateLimiterState>(getDefaultRateLimiterState())
159
- key: string | undefined
160
- options: RateLimiterOptions<TFn>
161
- #timeoutIds: Set<ReturnType<typeof setTimeout>> = new Set()
162
-
163
- constructor(
164
- public fn: TFn,
165
- initialOptions: RateLimiterOptions<TFn>,
166
- ) {
167
- this.key = initialOptions.key
168
- this.options = {
169
- ...defaultOptions,
170
- ...initialOptions,
171
- }
172
- this.#setState(this.options.initialState ?? {})
173
- for (const executionTime of this.#getExecutionTimesInWindow()) {
174
- this.#setCleanupTimeout(executionTime)
175
- }
176
-
177
- if (this.key) {
178
- pacerEventClient.on('d-RateLimiter', (event) => {
179
- if (event.payload.key !== this.key) return
180
- this.#setState(event.payload.store.state as Partial<RateLimiterState>)
181
- this.setOptions(
182
- event.payload.options as Partial<RateLimiterOptions<TFn>>,
183
- )
184
- })
185
- }
186
- }
187
-
188
- /**
189
- * Updates the rate limiter options
190
- */
191
- setOptions = (newOptions: Partial<RateLimiterOptions<TFn>>): void => {
192
- this.options = { ...this.options, ...newOptions }
193
- }
194
-
195
- #setState = (newState: Partial<RateLimiterState>): void => {
196
- this.store.setState((state) => {
197
- const combinedState = {
198
- ...state,
199
- ...newState,
200
- }
201
- const isExceeded = combinedState.executionTimes.length >= this.#getLimit()
202
- const status = !this.#getEnabled()
203
- ? 'disabled'
204
- : isExceeded
205
- ? 'exceeded'
206
- : 'idle'
207
- return {
208
- ...combinedState,
209
- isExceeded,
210
- status,
211
- }
212
- })
213
- emitChange('RateLimiter', this)
214
- }
215
-
216
- /**
217
- * Returns the current enabled state of the rate limiter
218
- */
219
- #getEnabled = (): boolean => {
220
- return !!parseFunctionOrValue(this.options.enabled, this)
221
- }
222
-
223
- /**
224
- * Returns the current limit of executions allowed within the time window
225
- */
226
- #getLimit = (): number => {
227
- return parseFunctionOrValue(this.options.limit, this)
228
- }
229
-
230
- /**
231
- * Returns the current time window in milliseconds
232
- */
233
- #getWindow = (): number => {
234
- return parseFunctionOrValue(this.options.window, this)
235
- }
236
-
237
- /**
238
- * Attempts to execute the rate-limited function if within the configured limits.
239
- * Will reject execution if the number of calls in the current window exceeds the limit.
240
- *
241
- * @example
242
- * ```ts
243
- * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });
244
- *
245
- * // First 5 calls will return true
246
- * rateLimiter.maybeExecute('arg1', 'arg2'); // true
247
- *
248
- * // Additional calls within the window will return false
249
- * rateLimiter.maybeExecute('arg1', 'arg2'); // false
250
- * ```
251
- */
252
- maybeExecute = (...args: Parameters<TFn>): boolean => {
253
- this.#setState({
254
- maybeExecuteCount: this.store.state.maybeExecuteCount + 1,
255
- })
256
-
257
- this.#cleanupOldExecutions()
258
-
259
- const relevantExecutionTimes = this.#getExecutionTimesInWindow()
260
-
261
- if (relevantExecutionTimes.length < this.#getLimit()) {
262
- this.#execute(...args)
263
- return true
264
- }
265
-
266
- this.#setState({
267
- rejectionCount: this.store.state.rejectionCount + 1,
268
- })
269
- this.options.onReject?.(this)
270
- return false
271
- }
272
-
273
- #execute = (...args: Parameters<TFn>): void => {
274
- if (!this.#getEnabled()) return
275
- const now = Date.now()
276
- this.fn(...args) // EXECUTE!
277
- this.store.state.executionTimes.push(now) // mutate state directly for performance
278
-
279
- this.#setCleanupTimeout(now)
280
-
281
- this.#setState({
282
- executionCount: this.store.state.executionCount + 1,
283
- })
284
- this.options.onExecute?.(args, this)
285
- }
286
-
287
- #getExecutionTimesInWindow = (): Array<number> => {
288
- if (this.options.windowType === 'sliding') {
289
- // For sliding window, return all executions within the current window
290
- return this.store.state.executionTimes.filter(
291
- (time) => time > Date.now() - this.#getWindow(),
292
- )
293
- } else {
294
- // For fixed window, return all executions in the current window
295
- // The window starts from the oldest execution time
296
- if (this.store.state.executionTimes.length === 0) {
297
- return []
298
- }
299
- const oldestExecution = Math.min(...this.store.state.executionTimes)
300
- const windowStart = oldestExecution
301
- const windowEnd = windowStart + this.#getWindow()
302
- const now = Date.now()
303
-
304
- // If the window has expired, return empty array
305
- if (now > windowEnd) {
306
- return []
307
- }
308
-
309
- // Otherwise, return all executions in the current window
310
- return this.store.state.executionTimes.filter(
311
- (time) => time >= windowStart && time <= windowEnd,
312
- )
313
- }
314
- }
315
-
316
- #setCleanupTimeout = (executionTime: number): void => {
317
- if (
318
- this.options.windowType === 'sliding' ||
319
- this.#timeoutIds.size === 0 // new fixed window
320
- ) {
321
- const now = Date.now()
322
- const timeUntilExpiration = executionTime - now + this.#getWindow() + 1
323
- const timeoutId = setTimeout(() => {
324
- this.#cleanupOldExecutions()
325
- this.#clearTimeout(timeoutId)
326
- }, timeUntilExpiration)
327
- this.#timeoutIds.add(timeoutId)
328
- }
329
- }
330
-
331
- #clearTimeout = (timeoutId: ReturnType<typeof setTimeout>): void => {
332
- clearTimeout(timeoutId)
333
- this.#timeoutIds.delete(timeoutId)
334
- }
335
-
336
- #clearTimeouts = (): void => {
337
- this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))
338
- this.#timeoutIds.clear()
339
- }
340
-
341
- #cleanupOldExecutions = (): void => {
342
- this.#setState({
343
- executionTimes: this.#getExecutionTimesInWindow(),
344
- })
345
- }
346
-
347
- /**
348
- * Returns the number of remaining executions allowed in the current window
349
- */
350
- getRemainingInWindow = (): number => {
351
- const relevantExecutionTimes = this.#getExecutionTimesInWindow()
352
- return Math.max(0, this.#getLimit() - relevantExecutionTimes.length)
353
- }
354
-
355
- /**
356
- * Returns the number of milliseconds until the next execution will be possible
357
- */
358
- getMsUntilNextWindow = (): number => {
359
- if (this.getRemainingInWindow() > 0) {
360
- return 0
361
- }
362
- const oldestExecution = this.store.state.executionTimes[0] ?? Infinity
363
- return oldestExecution + this.#getWindow() - Date.now()
364
- }
365
-
366
- /**
367
- * Resets the rate limiter state
368
- */
369
- reset = (): void => {
370
- this.#setState(getDefaultRateLimiterState())
371
- this.#clearTimeouts()
372
- }
373
- }
374
-
375
- /**
376
- * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
377
- *
378
- * This synchronous version is lighter weight and often all you need - upgrade to asyncRateLimit when you need promises, retry support, abort capabilities, or advanced error handling.
379
- *
380
- * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
381
- * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
382
- * - A throttler ensures even spacing between executions, which can be better for consistent performance
383
- * - A debouncer collapses multiple calls into one, which is better for handling bursts of events
384
- *
385
- * The rate limiter supports two types of windows:
386
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
387
- * towards the limit, and the window resets completely after the period.
388
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
389
- * consistent rate of execution over time.
390
- *
391
- * State Management:
392
- * - Uses TanStack Store for reactive state management
393
- * - Use `initialState` to provide initial state values when creating the rate limiter
394
- * - Use `onExecute` callback to react to function execution and implement custom logic
395
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
396
- * - The state includes execution count, execution times, and rejection count
397
- * - State can be accessed via the underlying RateLimiter instance's `store.state` property
398
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
399
- *
400
- * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
401
- * need to enforce a hard limit on the number of executions within a time period.
402
- *
403
- * @example
404
- * ```ts
405
- * // Rate limit to 5 calls per minute with a sliding window
406
- * const rateLimited = rateLimit(makeApiCall, {
407
- * limit: 5,
408
- * window: 60000,
409
- * windowType: 'sliding',
410
- * onReject: (rateLimiter) => {
411
- * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
412
- * }
413
- * });
414
- *
415
- * // First 5 calls will execute immediately
416
- * // Additional calls will be rejected until the minute window resets
417
- * rateLimited();
418
- *
419
- * // For more even execution, consider using throttle instead:
420
- * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
421
- * ```
422
- */
423
- export function rateLimit<TFn extends AnyFunction>(
424
- fn: TFn,
425
- initialOptions: RateLimiterOptions<TFn>,
426
- ) {
427
- const rateLimiter = new RateLimiter(fn, initialOptions)
428
- return rateLimiter.maybeExecute
429
- }