@tanstack/pacer 0.1.0 → 0.3.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 (74) hide show
  1. package/dist/cjs/async-debouncer.cjs +112 -63
  2. package/dist/cjs/async-debouncer.cjs.map +1 -1
  3. package/dist/cjs/async-debouncer.d.cts +66 -25
  4. package/dist/cjs/async-queuer.cjs +198 -124
  5. package/dist/cjs/async-queuer.cjs.map +1 -1
  6. package/dist/cjs/async-queuer.d.cts +91 -49
  7. package/dist/cjs/async-rate-limiter.cjs +83 -55
  8. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  9. package/dist/cjs/async-rate-limiter.d.cts +55 -28
  10. package/dist/cjs/async-throttler.cjs +121 -70
  11. package/dist/cjs/async-throttler.cjs.map +1 -1
  12. package/dist/cjs/async-throttler.d.cts +75 -25
  13. package/dist/cjs/debouncer.cjs +45 -23
  14. package/dist/cjs/debouncer.cjs.map +1 -1
  15. package/dist/cjs/debouncer.d.cts +27 -12
  16. package/dist/cjs/index.cjs +2 -0
  17. package/dist/cjs/index.cjs.map +1 -1
  18. package/dist/cjs/index.d.cts +2 -0
  19. package/dist/cjs/queuer.cjs +161 -101
  20. package/dist/cjs/queuer.cjs.map +1 -1
  21. package/dist/cjs/queuer.d.cts +80 -38
  22. package/dist/cjs/rate-limiter.cjs +52 -44
  23. package/dist/cjs/rate-limiter.cjs.map +1 -1
  24. package/dist/cjs/rate-limiter.d.cts +38 -46
  25. package/dist/cjs/throttler.cjs +57 -44
  26. package/dist/cjs/throttler.cjs.map +1 -1
  27. package/dist/cjs/throttler.d.cts +35 -23
  28. package/dist/cjs/types.d.cts +8 -0
  29. package/dist/cjs/utils.cjs +13 -0
  30. package/dist/cjs/utils.cjs.map +1 -0
  31. package/dist/cjs/utils.d.cts +1 -0
  32. package/dist/esm/async-debouncer.d.ts +66 -25
  33. package/dist/esm/async-debouncer.js +112 -63
  34. package/dist/esm/async-debouncer.js.map +1 -1
  35. package/dist/esm/async-queuer.d.ts +91 -49
  36. package/dist/esm/async-queuer.js +198 -124
  37. package/dist/esm/async-queuer.js.map +1 -1
  38. package/dist/esm/async-rate-limiter.d.ts +55 -28
  39. package/dist/esm/async-rate-limiter.js +83 -55
  40. package/dist/esm/async-rate-limiter.js.map +1 -1
  41. package/dist/esm/async-throttler.d.ts +75 -25
  42. package/dist/esm/async-throttler.js +121 -70
  43. package/dist/esm/async-throttler.js.map +1 -1
  44. package/dist/esm/debouncer.d.ts +27 -12
  45. package/dist/esm/debouncer.js +45 -23
  46. package/dist/esm/debouncer.js.map +1 -1
  47. package/dist/esm/index.d.ts +2 -0
  48. package/dist/esm/index.js +2 -0
  49. package/dist/esm/index.js.map +1 -1
  50. package/dist/esm/queuer.d.ts +80 -38
  51. package/dist/esm/queuer.js +161 -101
  52. package/dist/esm/queuer.js.map +1 -1
  53. package/dist/esm/rate-limiter.d.ts +38 -46
  54. package/dist/esm/rate-limiter.js +52 -44
  55. package/dist/esm/rate-limiter.js.map +1 -1
  56. package/dist/esm/throttler.d.ts +35 -23
  57. package/dist/esm/throttler.js +57 -44
  58. package/dist/esm/throttler.js.map +1 -1
  59. package/dist/esm/types.d.ts +8 -0
  60. package/dist/esm/utils.d.ts +1 -0
  61. package/dist/esm/utils.js +13 -0
  62. package/dist/esm/utils.js.map +1 -0
  63. package/package.json +8 -1
  64. package/src/async-debouncer.ts +157 -88
  65. package/src/async-queuer.ts +266 -148
  66. package/src/async-rate-limiter.ts +123 -83
  67. package/src/async-throttler.ts +173 -89
  68. package/src/debouncer.ts +71 -42
  69. package/src/index.ts +2 -0
  70. package/src/queuer.ts +219 -114
  71. package/src/rate-limiter.ts +74 -88
  72. package/src/throttler.ts +83 -65
  73. package/src/types.ts +9 -0
  74. package/src/utils.ts +13 -0
@@ -9,6 +9,16 @@ export interface AsyncQueuerOptions<TValue> {
9
9
  * Maximum number of concurrent tasks to process
10
10
  */
11
11
  concurrency?: number;
12
+ /**
13
+ * Maximum time in milliseconds that an item can stay in the queue
14
+ * If not provided, items will never expire
15
+ */
16
+ expirationDuration?: number;
17
+ /**
18
+ * Function to determine if an item has expired
19
+ * If provided, this overrides the expirationDuration behavior
20
+ */
21
+ getIsExpired?: (item: () => Promise<TValue>, addedAt: number) => boolean;
12
22
  /**
13
23
  * Default position to get items from during processing
14
24
  * @default 'front'
@@ -34,12 +44,24 @@ export interface AsyncQueuerOptions<TValue> {
34
44
  * Callback fired whenever an item is removed from the queuer
35
45
  */
36
46
  onGetNextItem?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
47
+ /**
48
+ * Callback fired whenever the queuer's running state changes
49
+ */
50
+ onIsRunningChange?: (queuer: AsyncQueuer<TValue>) => void;
37
51
  /**
38
52
  * Callback fired whenever an item is added or removed from the queuer
39
53
  */
40
- onUpdate?: (queuer: AsyncQueuer<TValue>) => void;
54
+ onItemsChange?: (queuer: AsyncQueuer<TValue>) => void;
55
+ /**
56
+ * Callback fired whenever an item is rejected from being added to the queuer
57
+ */
58
+ onReject?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
41
59
  /**
42
- * Whether the queuer should start processing tasks immediately
60
+ * Callback fired whenever an item expires in the queuer
61
+ */
62
+ onExpire?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
63
+ /**
64
+ * Whether the queuer should start processing tasks immediately or not.
43
65
  */
44
66
  started?: boolean;
45
67
  /**
@@ -48,54 +70,82 @@ export interface AsyncQueuerOptions<TValue> {
48
70
  wait?: number;
49
71
  }
50
72
  /**
51
- * A flexible asynchronous queuer that processes tasks with configurable concurrency control.
73
+ * A flexible asynchronous queue that processes tasks with configurable concurrency control.
52
74
  *
53
75
  * Features:
54
- * - Priority queuer support via getPriority option
76
+ * - Priority queue support via getPriority option
55
77
  * - Configurable concurrency limit
56
78
  * - Task success/error/completion callbacks
57
- * - FIFO (First In First Out) or LIFO (Last In First Out) queuer behavior
79
+ * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior
58
80
  * - Pause/resume task processing
59
81
  * - Task cancellation
82
+ * - Item expiration to clear stale items from the queue
60
83
  *
61
84
  * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,
62
85
  * the next pending task is processed if below the concurrency limit.
63
86
  *
64
87
  * @example
65
88
  * ```ts
66
- * const queuer = new AsyncQueuer<string>({ concurrency: 2 });
89
+ * const asyncQueuer = new AsyncQueuer<string>({ concurrency: 2 });
67
90
  *
68
- * queuer.addItem(async () => {
91
+ * asyncQueuer.addItem(async () => {
69
92
  * return 'Hello';
70
93
  * });
71
94
  *
72
- * queuer.start();
95
+ * asyncQueuer.start();
73
96
  *
74
- * queuer.onSuccess((result) => {
97
+ * asyncQueuer.onSuccess((result) => {
75
98
  * console.log(result); // 'Hello'
76
99
  * });
77
100
  * ```
78
101
  */
79
102
  export declare class AsyncQueuer<TValue> {
80
- protected options: Required<AsyncQueuerOptions<TValue>>;
81
- private items;
82
- private activeItems;
83
- private onSuccessCallbacks;
84
- private onErrorCallbacks;
85
- private onSettledCallbacks;
86
- private running;
87
- private pendingTick;
88
- private executionCount;
103
+ private _options;
104
+ private _activeItems;
105
+ private _executionCount;
106
+ private _rejectionCount;
107
+ private _expirationCount;
108
+ private _items;
109
+ private _itemTimestamps;
110
+ private _onErrorCallbacks;
111
+ private _onSettledCallbacks;
112
+ private _onSuccessCallbacks;
113
+ private _pendingTick;
114
+ private _running;
89
115
  constructor(initialOptions?: AsyncQueuerOptions<TValue>);
90
116
  /**
91
117
  * Updates the queuer options
92
118
  * Returns the new options state
93
119
  */
94
- setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>): AsyncQueuerOptions<TValue>;
120
+ setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>): void;
121
+ /**
122
+ * Returns the current queuer options
123
+ */
124
+ getOptions(): Required<AsyncQueuerOptions<TValue>>;
95
125
  /**
96
126
  * Processes items in the queuer
97
127
  */
98
- protected tick(): void;
128
+ private tick;
129
+ /**
130
+ * Checks for and removes expired items from the queuer
131
+ */
132
+ private checkExpiredItems;
133
+ /**
134
+ * Starts the queuer and processes items
135
+ */
136
+ start(): Promise<void>;
137
+ /**
138
+ * Stops the queuer from processing items
139
+ */
140
+ stop(): void;
141
+ /**
142
+ * Removes all items from the queuer
143
+ */
144
+ clear(): void;
145
+ /**
146
+ * Resets the queuer to its initial state
147
+ */
148
+ reset(withInitialItems?: boolean): void;
99
149
  /**
100
150
  * Adds a task to the queuer
101
151
  */
@@ -109,43 +159,47 @@ export declare class AsyncQueuer<TValue> {
109
159
  /**
110
160
  * Returns an item without removing it
111
161
  */
112
- peek(position?: QueuePosition): (() => Promise<TValue>) | undefined;
162
+ getPeek(position?: QueuePosition): (() => Promise<TValue>) | undefined;
113
163
  /**
114
164
  * Returns true if the queuer is empty
115
165
  */
116
- isEmpty(): boolean;
166
+ getIsEmpty(): boolean;
117
167
  /**
118
168
  * Returns true if the queuer is full
119
169
  */
120
- isFull(): boolean;
170
+ getIsFull(): boolean;
121
171
  /**
122
172
  * Returns the current size of the queuer
123
173
  */
124
- size(): number;
174
+ getSize(): number;
125
175
  /**
126
- * Removes all items from the queuer
176
+ * Returns a copy of all items in the queuer
127
177
  */
128
- clear(): void;
178
+ getAllItems(): Array<() => Promise<TValue>>;
129
179
  /**
130
- * Resets the queuer to its initial state
180
+ * Returns the active items
131
181
  */
132
- reset(withInitialItems?: boolean): void;
182
+ getActiveItems(): Array<() => Promise<TValue>>;
133
183
  /**
134
- * Returns a copy of all items in the queuer
184
+ * Returns the pending items
135
185
  */
136
- getAllItems(): Array<() => Promise<TValue>>;
186
+ getPendingItems(): Array<() => Promise<TValue>>;
137
187
  /**
138
188
  * Returns the number of items that have been removed from the queuer
139
189
  */
140
190
  getExecutionCount(): number;
141
191
  /**
142
- * Returns the active items
192
+ * Returns the number of items that have been rejected from the queuer
143
193
  */
144
- getActiveItems(): Array<() => Promise<TValue>>;
194
+ getRejectionCount(): number;
145
195
  /**
146
- * Returns the pending items
196
+ * Returns true if the queuer is running
147
197
  */
148
- getPendingItems(): Array<() => Promise<TValue>>;
198
+ getIsRunning(): boolean;
199
+ /**
200
+ * Returns true if the queuer is running but has no items to process
201
+ */
202
+ getIsIdle(): boolean;
149
203
  /**
150
204
  * Adds a callback to be called when a task succeeds
151
205
  */
@@ -159,21 +213,9 @@ export declare class AsyncQueuer<TValue> {
159
213
  */
160
214
  onSettled(cb: (result: TValue | Error) => void): () => void;
161
215
  /**
162
- * Starts the queuer and processes items
163
- */
164
- start(): Promise<void>;
165
- /**
166
- * Stops the queuer from processing items
167
- */
168
- stop(): void;
169
- /**
170
- * Returns true if the queuer is running
171
- */
172
- isRunning(): boolean;
173
- /**
174
- * Returns true if the queuer is running but has no items to process
216
+ * Returns the number of items that have expired from the queuer
175
217
  */
176
- isIdle(): boolean;
218
+ getExpirationCount(): number;
177
219
  }
178
220
  /**
179
221
  * Creates a new AsyncQueuer instance with the given options and returns a bound addItem function.
@@ -192,6 +234,6 @@ export declare class AsyncQueuer<TValue> {
192
234
  * @param options - Configuration options for the AsyncQueuer
193
235
  * @returns A bound addItem function that can be used to add tasks to the queuer
194
236
  */
195
- export declare function asyncQueue<TValue>(options?: AsyncQueuerOptions<TValue>): (fn: (() => Promise<TValue>) & {
237
+ export declare function asyncQueue<TValue>(options?: Omit<AsyncQueuerOptions<TValue>, 'started'>): (fn: (() => Promise<TValue>) & {
196
238
  priority?: number;
197
239
  }, position?: QueuePosition, runOnUpdate?: boolean) => Promise<TValue>;
@@ -1,13 +1,26 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const defaultOptions = {
4
+ enabled: true,
5
+ onError: () => {
6
+ },
7
+ onReject: () => {
8
+ },
9
+ onSettled: () => {
10
+ },
11
+ onSuccess: () => {
12
+ }
13
+ };
3
14
  class AsyncRateLimiter {
4
15
  constructor(fn, initialOptions) {
5
16
  this.fn = fn;
6
- this.executionCount = 0;
7
- this.rejectionCount = 0;
8
- this.executionTimes = [];
9
- this.options = {
10
- enabled: true,
17
+ this._errorCount = 0;
18
+ this._executionTimes = [];
19
+ this._rejectionCount = 0;
20
+ this._settleCount = 0;
21
+ this._successCount = 0;
22
+ this._options = {
23
+ ...defaultOptions,
11
24
  ...initialOptions
12
25
  };
13
26
  }
@@ -16,30 +29,13 @@ class AsyncRateLimiter {
16
29
  * Returns the new options state
17
30
  */
18
31
  setOptions(newOptions) {
19
- this.options = {
20
- ...this.options,
21
- ...newOptions
22
- };
23
- return this.options;
24
- }
25
- /**
26
- * Returns the number of times the function has been executed
27
- */
28
- getExecutionCount() {
29
- return this.executionCount;
32
+ this._options = { ...this._options, ...newOptions };
30
33
  }
31
34
  /**
32
- * Returns the number of times the function has been rejected
35
+ * Returns the current rate limiter options
33
36
  */
34
- getRejectionCount() {
35
- return this.rejectionCount;
36
- }
37
- /**
38
- * Returns the number of remaining executions allowed in the current window
39
- */
40
- getRemainingInWindow() {
41
- this.cleanupOldExecutions();
42
- return Math.max(0, this.options.limit - this.executionTimes.length);
37
+ getOptions() {
38
+ return this._options;
43
39
  }
44
40
  /**
45
41
  * Attempts to execute the rate-limited function if within the configured limits.
@@ -59,58 +55,90 @@ class AsyncRateLimiter {
59
55
  */
60
56
  async maybeExecute(...args) {
61
57
  this.cleanupOldExecutions();
62
- if (this.executionTimes.length < this.options.limit) {
58
+ if (this._executionTimes.length < this._options.limit) {
63
59
  await this.executeFunction(...args);
64
- return true;
60
+ return this._lastResult;
65
61
  }
66
62
  this.rejectFunction();
67
- return false;
63
+ return void 0;
68
64
  }
69
65
  async executeFunction(...args) {
70
- if (!this.options.enabled) return;
66
+ var _a, _b, _c, _d, _e, _f;
67
+ if (!this._options.enabled) return;
71
68
  const now = Date.now();
72
- this.executionCount++;
73
- this.executionTimes.push(now);
69
+ this._executionTimes.push(now);
74
70
  try {
75
- await this.fn(...args);
71
+ this._lastResult = await this.fn(...args);
72
+ this._successCount++;
73
+ (_b = (_a = this._options).onSuccess) == null ? void 0 : _b.call(_a, this._lastResult, this);
76
74
  } catch (error) {
77
- if (this.options.onError) {
78
- try {
79
- this.options.onError(error);
80
- } catch {
81
- }
82
- }
83
- throw error;
75
+ this._errorCount++;
76
+ (_d = (_c = this._options).onError) == null ? void 0 : _d.call(_c, error, this);
84
77
  } finally {
78
+ this._settleCount++;
79
+ (_f = (_e = this._options).onSettled) == null ? void 0 : _f.call(_e, this);
85
80
  }
81
+ return this._lastResult;
86
82
  }
87
83
  rejectFunction() {
88
- this.rejectionCount++;
89
- if (this.options.onReject) {
90
- const oldestExecution = Math.min(...this.executionTimes);
91
- const msUntilNextWindow = oldestExecution + this.options.window - Date.now();
92
- this.options.onReject({
93
- msUntilNextWindow,
94
- currentExecutions: this.executionTimes.length,
95
- limit: this.options.limit,
96
- rejectionCount: this.rejectionCount
97
- });
84
+ this._rejectionCount++;
85
+ if (this._options.onReject) {
86
+ this._options.onReject(this);
98
87
  }
99
88
  }
100
89
  cleanupOldExecutions() {
101
90
  const now = Date.now();
102
- const windowStart = now - this.options.window;
103
- this.executionTimes = this.executionTimes.filter(
91
+ const windowStart = now - this._options.window;
92
+ this._executionTimes = this._executionTimes.filter(
104
93
  (time) => time > windowStart
105
94
  );
106
95
  }
96
+ /**
97
+ * Returns the number of remaining executions allowed in the current window
98
+ */
99
+ getRemainingInWindow() {
100
+ this.cleanupOldExecutions();
101
+ return Math.max(0, this._options.limit - this._executionTimes.length);
102
+ }
103
+ /**
104
+ * Returns the number of milliseconds until the next execution will be possible
105
+ */
106
+ getMsUntilNextWindow() {
107
+ return this.getRemainingInWindow() * this._options.window;
108
+ }
109
+ /**
110
+ * Returns the number of times the function has been executed
111
+ */
112
+ getSuccessCount() {
113
+ return this._successCount;
114
+ }
115
+ /**
116
+ * Returns the number of times the function has been settled
117
+ */
118
+ getSettleCount() {
119
+ return this._settleCount;
120
+ }
121
+ /**
122
+ * Returns the number of times the function has errored
123
+ */
124
+ getErrorCount() {
125
+ return this._errorCount;
126
+ }
127
+ /**
128
+ * Returns the number of times the function has been rejected
129
+ */
130
+ getRejectionCount() {
131
+ return this._rejectionCount;
132
+ }
107
133
  /**
108
134
  * Resets the rate limiter state
109
135
  */
110
136
  reset() {
111
- this.executionTimes = [];
112
- this.executionCount = 0;
113
- this.rejectionCount = 0;
137
+ this._executionTimes = [];
138
+ this._successCount = 0;
139
+ this._errorCount = 0;
140
+ this._rejectionCount = 0;
141
+ this._settleCount = 0;
114
142
  }
115
143
  }
116
144
  function asyncRateLimit(fn, initialOptions) {
@@ -1 +1 @@
1
- {"version":3,"file":"async-rate-limiter.cjs","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import type { RateLimitRejectionInfo } from './rate-limiter'\n\n/**\n * Options for configuring an async rate-limited function\n */\nexport interface AsyncRateLimiterOptions {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Maximum number of executions allowed within the time window\n */\n limit: number\n /**\n * Time window in milliseconds within which the limit applies\n */\n window: number\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (info: RateLimitRejectionInfo) => void\n /**\n * Optional error handler for when the rate-limited function throws\n */\n onError?: (error: unknown) => void\n}\n\n/**\n * A class that creates an async rate-limited function.\n *\n * Rate limiting is a simple approach that 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 * For smoother execution patterns, consider using:\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 * 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 *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(\n * async (id: string) => await api.getData(id),\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Will execute immediately until limit reached, then block\n * await rateLimiter.maybeExecute('123');\n * ```\n */\nexport class AsyncRateLimiter<\n TFn extends (...args: Array<any>) => Promise<any>,\n TArgs extends Parameters<TFn>,\n> {\n private executionCount = 0\n private rejectionCount = 0\n private executionTimes: Array<number> = []\n private options: AsyncRateLimiterOptions\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions,\n ) {\n this.options = {\n enabled: true,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<AsyncRateLimiterOptions>,\n ): AsyncRateLimiterOptions {\n this.options = {\n ...this.options,\n ...newOptions,\n }\n return this.options\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this.executionCount\n }\n\n /**\n * Returns the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this.rejectionCount\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this.options.limit - this.executionTimes.length)\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 * If execution is allowed, waits for any previous execution to complete before proceeding.\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will execute\n * await rateLimiter.maybeExecute('arg1', 'arg2');\n *\n * // Additional calls within the window will be rejected\n * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected\n * ```\n */\n async maybeExecute(...args: TArgs): Promise<boolean> {\n this.cleanupOldExecutions()\n\n if (this.executionTimes.length < this.options.limit) {\n await this.executeFunction(...args)\n return true\n }\n\n this.rejectFunction()\n return false\n }\n\n private async executeFunction(...args: TArgs): Promise<void> {\n if (!this.options.enabled) return\n const now = Date.now()\n this.executionCount++\n this.executionTimes.push(now)\n\n try {\n await this.fn(...args)\n } catch (error) {\n if (this.options.onError) {\n try {\n this.options.onError(error)\n } catch {\n // Ignore errors from error handler\n }\n }\n throw error\n } finally {\n }\n }\n\n private rejectFunction(): void {\n this.rejectionCount++\n if (this.options.onReject) {\n const oldestExecution = Math.min(...this.executionTimes)\n const msUntilNextWindow =\n oldestExecution + this.options.window - Date.now()\n\n this.options.onReject({\n msUntilNextWindow,\n currentExecutions: this.executionTimes.length,\n limit: this.options.limit,\n rejectionCount: this.rejectionCount,\n })\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this.options.window\n this.executionTimes = this.executionTimes.filter(\n (time) => time > windowStart,\n )\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this.executionTimes = []\n this.executionCount = 0\n this.rejectionCount = 0\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 * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\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 * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute\n * const rateLimited = asyncRateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * onReject: ({ msUntilNextWindow }) => {\n * console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * 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<\n TFn extends (...args: Array<any>) => Promise<any>,\n>(fn: TFn, initialOptions: Omit<AsyncRateLimiterOptions, 'enabled'>) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":";;AAsDO,MAA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;AAAA,QAAA;AAAA,MAER;AAEI,YAAA;AAAA,IAAA,UACN;AAAA,IAAA;AAAA,EACF;AAAA,EAGM,iBAAuB;AACxB,SAAA;AACD,QAAA,KAAK,QAAQ,UAAU;AACzB,YAAM,kBAAkB,KAAK,IAAI,GAAG,KAAK,cAAc;AACvD,YAAM,oBACJ,kBAAkB,KAAK,QAAQ,SAAS,KAAK,IAAI;AAEnD,WAAK,QAAQ,SAAS;AAAA,QACpB;AAAA,QACA,mBAAmB,KAAK,eAAe;AAAA,QACvC,OAAO,KAAK,QAAQ;AAAA,QACpB,gBAAgB,KAAK;AAAA,MAAA,CACtB;AAAA,IAAA;AAAA,EACH;AAAA,EAGM,uBAA6B;AAC7B,UAAA,MAAM,KAAK,IAAI;AACf,UAAA,cAAc,MAAM,KAAK,QAAQ;AAClC,SAAA,iBAAiB,KAAK,eAAe;AAAA,MACxC,CAAC,SAAS,OAAO;AAAA,IACnB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,QAAc;AACZ,SAAK,iBAAiB,CAAC;AACvB,SAAK,iBAAiB;AACtB,SAAK,iBAAiB;AAAA,EAAA;AAE1B;AAgCgB,SAAA,eAEd,IAAS,gBAA0D;AACnE,QAAM,cAAc,IAAI,iBAAiB,IAAI,cAAc;AACpD,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;;;"}
1
+ {"version":3,"file":"async-rate-limiter.cjs","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async rate-limited function\n */\nexport interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Maximum number of executions allowed within the time window\n */\n limit: number\n /**\n * Optional error handler for when the rate-limited function throws\n */\n onError?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSettled?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Optional function to call when the rate-limited function is executed\n */\n onSuccess?: (\n result: ReturnType<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?: (rateLimiter: AsyncRateLimiter<TFn>) => void\n /**\n * Time window in milliseconds within which the limit applies\n */\n window: number\n}\n\nconst defaultOptions: Required<\n Omit<AsyncRateLimiterOptions<any>, 'limit' | 'window'>\n> = {\n enabled: true,\n onError: () => {},\n onReject: () => {},\n onSettled: () => {},\n onSuccess: () => {},\n}\n\n/**\n * A class that creates an async rate-limited function.\n *\n * Rate limiting is a simple approach that 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 * For smoother execution patterns, consider using:\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 * 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 *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(\n * async (id: string) => await api.getData(id),\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Will execute immediately until limit reached, then block\n * await rateLimiter.maybeExecute('123');\n * ```\n */\nexport class AsyncRateLimiter<TFn extends AnyAsyncFunction> {\n private _options: AsyncRateLimiterOptions<TFn>\n private _errorCount = 0\n private _executionTimes: Array<number> = []\n private _lastResult: ReturnType<TFn> | undefined\n private _rejectionCount = 0\n private _settleCount = 0\n private _successCount = 0\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<AsyncRateLimiterOptions<TFn>> {\n return this._options as Required<AsyncRateLimiterOptions<TFn>>\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 * If execution is allowed, waits for any previous execution to complete before proceeding.\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will execute\n * await rateLimiter.maybeExecute('arg1', 'arg2');\n *\n * // Additional calls within the window will be rejected\n * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected\n * ```\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this.cleanupOldExecutions()\n\n if (this._executionTimes.length < this._options.limit) {\n await this.executeFunction(...args)\n return this._lastResult\n }\n\n this.rejectFunction()\n return undefined\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this._options.enabled) return\n const now = Date.now()\n this._executionTimes.push(now)\n\n try {\n this._lastResult = await this.fn(...args)\n this._successCount++\n this._options.onSuccess?.(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError?.(error, this)\n } finally {\n this._settleCount++\n this._options.onSettled?.(this)\n }\n\n return this._lastResult\n }\n\n private rejectFunction(): void {\n this._rejectionCount++\n if (this._options.onReject) {\n this._options.onReject(this)\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this._options.window\n this._executionTimes = this._executionTimes.filter(\n (time) => time > windowStart,\n )\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this._options.limit - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow(): number {\n return this.getRemainingInWindow() * this._options.window\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has been settled\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._successCount = 0\n this._errorCount = 0\n this._rejectionCount = 0\n this._settleCount = 0\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 * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\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 * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute\n * const rateLimited = asyncRateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\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 * 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: Omit<AsyncRateLimiterOptions<TFn>, 'enabled'>,\n) {\n const rateLimiter = new AsyncRateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":";;AAwCA,MAAM,iBAEF;AAAA,EACF,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAA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2
2
  /**
3
3
  * Options for configuring an async rate-limited function
4
4
  */
5
- export interface AsyncRateLimiterOptions {
5
+ export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
6
6
  /**
7
7
  * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
8
8
  * Defaults to true.
@@ -13,17 +13,25 @@ export interface AsyncRateLimiterOptions {
13
13
  */
14
14
  limit: number;
15
15
  /**
16
- * Time window in milliseconds within which the limit applies
16
+ * Optional error handler for when the rate-limited function throws
17
17
  */
18
- window: number;
18
+ onError?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => void;
19
+ /**
20
+ * Optional function to call when the rate-limited function is executed
21
+ */
22
+ onSettled?: (rateLimiter: AsyncRateLimiter<TFn>) => void;
23
+ /**
24
+ * Optional function to call when the rate-limited function is executed
25
+ */
26
+ onSuccess?: (result: ReturnType<TFn>, rateLimiter: AsyncRateLimiter<TFn>) => void;
19
27
  /**
20
28
  * Optional callback function that is called when an execution is rejected due to rate limiting
21
29
  */
22
- onReject?: (info: RateLimitRejectionInfo) => void;
30
+ onReject?: (rateLimiter: AsyncRateLimiter<TFn>) => void;
23
31
  /**
24
- * Optional error handler for when the rate-limited function throws
32
+ * Time window in milliseconds within which the limit applies
25
33
  */
26
- onError?: (error: unknown) => void;
34
+ window: number;
27
35
  }
28
36
  /**
29
37
  * A class that creates an async rate-limited function.
@@ -50,30 +58,25 @@ export interface AsyncRateLimiterOptions {
50
58
  * await rateLimiter.maybeExecute('123');
51
59
  * ```
52
60
  */
53
- export declare class AsyncRateLimiter<TFn extends (...args: Array<any>) => Promise<any>, TArgs extends Parameters<TFn>> {
61
+ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
54
62
  private fn;
55
- private executionCount;
56
- private rejectionCount;
57
- private executionTimes;
58
- private options;
59
- constructor(fn: TFn, initialOptions: AsyncRateLimiterOptions);
63
+ private _options;
64
+ private _errorCount;
65
+ private _executionTimes;
66
+ private _lastResult;
67
+ private _rejectionCount;
68
+ private _settleCount;
69
+ private _successCount;
70
+ constructor(fn: TFn, initialOptions: AsyncRateLimiterOptions<TFn>);
60
71
  /**
61
72
  * Updates the rate limiter options
62
73
  * Returns the new options state
63
74
  */
64
- setOptions(newOptions: Partial<AsyncRateLimiterOptions>): AsyncRateLimiterOptions;
75
+ setOptions(newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void;
65
76
  /**
66
- * Returns the number of times the function has been executed
67
- */
68
- getExecutionCount(): number;
69
- /**
70
- * Returns the number of times the function has been rejected
71
- */
72
- getRejectionCount(): number;
73
- /**
74
- * Returns the number of remaining executions allowed in the current window
77
+ * Returns the current rate limiter options
75
78
  */
76
- getRemainingInWindow(): number;
79
+ getOptions(): Required<AsyncRateLimiterOptions<TFn>>;
77
80
  /**
78
81
  * Attempts to execute the rate-limited function if within the configured limits.
79
82
  * Will reject execution if the number of calls in the current window exceeds the limit.
@@ -90,10 +93,34 @@ export declare class AsyncRateLimiter<TFn extends (...args: Array<any>) => Promi
90
93
  * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected
91
94
  * ```
92
95
  */
93
- maybeExecute(...args: TArgs): Promise<boolean>;
96
+ maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
94
97
  private executeFunction;
95
98
  private rejectFunction;
96
99
  private cleanupOldExecutions;
100
+ /**
101
+ * Returns the number of remaining executions allowed in the current window
102
+ */
103
+ getRemainingInWindow(): number;
104
+ /**
105
+ * Returns the number of milliseconds until the next execution will be possible
106
+ */
107
+ getMsUntilNextWindow(): number;
108
+ /**
109
+ * Returns the number of times the function has been executed
110
+ */
111
+ getSuccessCount(): number;
112
+ /**
113
+ * Returns the number of times the function has been settled
114
+ */
115
+ getSettleCount(): number;
116
+ /**
117
+ * Returns the number of times the function has errored
118
+ */
119
+ getErrorCount(): number;
120
+ /**
121
+ * Returns the number of times the function has been rejected
122
+ */
123
+ getRejectionCount(): number;
97
124
  /**
98
125
  * Resets the rate limiter state
99
126
  */
@@ -116,8 +143,8 @@ export declare class AsyncRateLimiter<TFn extends (...args: Array<any>) => Promi
116
143
  * const rateLimited = asyncRateLimit(makeApiCall, {
117
144
  * limit: 5,
118
145
  * window: 60000,
119
- * onReject: ({ msUntilNextWindow }) => {
120
- * console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}ms`);
146
+ * onReject: (rateLimiter) => {
147
+ * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
121
148
  * }
122
149
  * });
123
150
  *
@@ -129,4 +156,4 @@ export declare class AsyncRateLimiter<TFn extends (...args: Array<any>) => Promi
129
156
  * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
130
157
  * ```
131
158
  */
132
- export declare function asyncRateLimit<TFn extends (...args: Array<any>) => Promise<any>>(fn: TFn, initialOptions: Omit<AsyncRateLimiterOptions, 'enabled'>): (...args: Parameters<TFn>) => Promise<boolean>;
159
+ export declare function asyncRateLimit<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: Omit<AsyncRateLimiterOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;