@tanstack/pacer 0.8.0 → 0.9.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 (91) hide show
  1. package/dist/cjs/async-batcher.cjs +163 -0
  2. package/dist/cjs/async-batcher.cjs.map +1 -0
  3. package/dist/cjs/async-batcher.d.cts +273 -0
  4. package/dist/cjs/async-debouncer.cjs +149 -162
  5. package/dist/cjs/async-debouncer.cjs.map +1 -1
  6. package/dist/cjs/async-debouncer.d.cts +76 -57
  7. package/dist/cjs/async-queuer.cjs +282 -343
  8. package/dist/cjs/async-queuer.cjs.map +1 -1
  9. package/dist/cjs/async-queuer.d.cts +121 -100
  10. package/dist/cjs/async-rate-limiter.cjs +128 -185
  11. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  12. package/dist/cjs/async-rate-limiter.d.cts +72 -61
  13. package/dist/cjs/async-throttler.cjs +168 -178
  14. package/dist/cjs/async-throttler.cjs.map +1 -1
  15. package/dist/cjs/async-throttler.d.cts +97 -69
  16. package/dist/cjs/batcher.cjs +110 -119
  17. package/dist/cjs/batcher.cjs.map +1 -1
  18. package/dist/cjs/batcher.d.cts +76 -51
  19. package/dist/cjs/debouncer.cjs +97 -85
  20. package/dist/cjs/debouncer.cjs.map +1 -1
  21. package/dist/cjs/debouncer.d.cts +54 -26
  22. package/dist/cjs/index.cjs +3 -6
  23. package/dist/cjs/index.cjs.map +1 -1
  24. package/dist/cjs/index.d.cts +1 -1
  25. package/dist/cjs/queuer.cjs +246 -294
  26. package/dist/cjs/queuer.cjs.map +1 -1
  27. package/dist/cjs/queuer.d.cts +102 -81
  28. package/dist/cjs/rate-limiter.cjs +97 -130
  29. package/dist/cjs/rate-limiter.cjs.map +1 -1
  30. package/dist/cjs/rate-limiter.d.cts +50 -37
  31. package/dist/cjs/throttler.cjs +107 -123
  32. package/dist/cjs/throttler.cjs.map +1 -1
  33. package/dist/cjs/throttler.d.cts +59 -35
  34. package/dist/cjs/utils.cjs +0 -13
  35. package/dist/cjs/utils.cjs.map +1 -1
  36. package/dist/cjs/utils.d.cts +0 -1
  37. package/dist/esm/async-batcher.d.ts +273 -0
  38. package/dist/esm/async-batcher.js +163 -0
  39. package/dist/esm/async-batcher.js.map +1 -0
  40. package/dist/esm/async-debouncer.d.ts +76 -57
  41. package/dist/esm/async-debouncer.js +149 -162
  42. package/dist/esm/async-debouncer.js.map +1 -1
  43. package/dist/esm/async-queuer.d.ts +121 -100
  44. package/dist/esm/async-queuer.js +282 -343
  45. package/dist/esm/async-queuer.js.map +1 -1
  46. package/dist/esm/async-rate-limiter.d.ts +72 -61
  47. package/dist/esm/async-rate-limiter.js +128 -185
  48. package/dist/esm/async-rate-limiter.js.map +1 -1
  49. package/dist/esm/async-throttler.d.ts +97 -69
  50. package/dist/esm/async-throttler.js +168 -178
  51. package/dist/esm/async-throttler.js.map +1 -1
  52. package/dist/esm/batcher.d.ts +76 -51
  53. package/dist/esm/batcher.js +110 -119
  54. package/dist/esm/batcher.js.map +1 -1
  55. package/dist/esm/debouncer.d.ts +54 -26
  56. package/dist/esm/debouncer.js +97 -85
  57. package/dist/esm/debouncer.js.map +1 -1
  58. package/dist/esm/index.d.ts +1 -1
  59. package/dist/esm/index.js +4 -7
  60. package/dist/esm/queuer.d.ts +102 -81
  61. package/dist/esm/queuer.js +246 -294
  62. package/dist/esm/queuer.js.map +1 -1
  63. package/dist/esm/rate-limiter.d.ts +50 -37
  64. package/dist/esm/rate-limiter.js +97 -130
  65. package/dist/esm/rate-limiter.js.map +1 -1
  66. package/dist/esm/throttler.d.ts +59 -35
  67. package/dist/esm/throttler.js +107 -123
  68. package/dist/esm/throttler.js.map +1 -1
  69. package/dist/esm/utils.d.ts +0 -1
  70. package/dist/esm/utils.js +0 -13
  71. package/dist/esm/utils.js.map +1 -1
  72. package/package.json +14 -11
  73. package/src/async-batcher.ts +475 -0
  74. package/src/async-debouncer.ts +201 -121
  75. package/src/async-queuer.ts +337 -216
  76. package/src/async-rate-limiter.ts +176 -136
  77. package/src/async-throttler.ts +233 -139
  78. package/src/batcher.ts +158 -92
  79. package/src/debouncer.ts +135 -52
  80. package/src/index.ts +1 -1
  81. package/src/queuer.ts +348 -226
  82. package/src/rate-limiter.ts +125 -80
  83. package/src/throttler.ts +152 -78
  84. package/src/utils.ts +0 -15
  85. package/dist/cjs/compare.cjs +0 -72
  86. package/dist/cjs/compare.cjs.map +0 -1
  87. package/dist/cjs/compare.d.cts +0 -12
  88. package/dist/esm/compare.d.ts +0 -12
  89. package/dist/esm/compare.js +0 -72
  90. package/dist/esm/compare.js.map +0 -1
  91. package/src/compare.ts +0 -105
@@ -1,206 +1,149 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const store = require("@tanstack/store");
3
4
  const utils = require("./utils.cjs");
5
+ function getDefaultAsyncRateLimiterState() {
6
+ return {
7
+ errorCount: 0,
8
+ executionTimes: [],
9
+ isExecuting: false,
10
+ lastResult: void 0,
11
+ rejectionCount: 0,
12
+ settleCount: 0,
13
+ successCount: 0
14
+ };
15
+ }
4
16
  const defaultOptions = {
5
17
  enabled: true,
6
- windowType: "fixed"
18
+ limit: 1,
19
+ window: 0,
20
+ windowType: "fixed",
21
+ throwOnError: true
7
22
  };
8
23
  class AsyncRateLimiter {
9
24
  constructor(fn, initialOptions) {
10
25
  this.fn = fn;
11
- this._errorCount = 0;
12
- this._executionTimes = [];
13
- this._rejectionCount = 0;
14
- this._settleCount = 0;
15
- this._successCount = 0;
16
- this._isExecuting = false;
17
- this._options = {
18
- ...defaultOptions,
19
- ...initialOptions,
20
- throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
26
+ this.store = new store.Store(getDefaultAsyncRateLimiterState());
27
+ this.setOptions = (newOptions) => {
28
+ this.options = { ...this.options, ...newOptions };
21
29
  };
22
- }
23
- /**
24
- * Updates the rate limiter options
25
- */
26
- setOptions(newOptions) {
27
- this._options = { ...this._options, ...newOptions };
28
- }
29
- /**
30
- * Returns the current rate limiter options
31
- */
32
- getOptions() {
33
- return this._options;
34
- }
35
- /**
36
- * Returns the current enabled state of the rate limiter
37
- */
38
- getEnabled() {
39
- return !!utils.parseFunctionOrValue(this._options.enabled, this);
40
- }
41
- /**
42
- * Returns the current limit of executions allowed within the time window
43
- */
44
- getLimit() {
45
- return utils.parseFunctionOrValue(this._options.limit, this);
46
- }
47
- /**
48
- * Returns the current time window in milliseconds
49
- */
50
- getWindow() {
51
- return utils.parseFunctionOrValue(this._options.window, this);
52
- }
53
- /**
54
- * Attempts to execute the rate-limited function if within the configured limits.
55
- * Will reject execution if the number of calls in the current window exceeds the limit.
56
- * If execution is allowed, waits for any previous execution to complete before proceeding.
57
- *
58
- * Error Handling:
59
- * - If the rate-limited function throws and no `onError` handler is configured,
60
- * the error will be thrown from this method.
61
- * - If an `onError` handler is configured, errors will be caught and passed to the handler,
62
- * and this method will return undefined.
63
- * - If the rate limit is exceeded, the execution will be rejected and the `onReject` handler
64
- * will be called if configured.
65
- * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
66
- * - Rate limit rejections can be tracked using `getRejectionCount()`.
67
- *
68
- * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
69
- * @throws The error from the rate-limited function if no onError handler is configured
70
- *
71
- * @example
72
- * ```ts
73
- * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
74
- *
75
- * // First 5 calls will execute
76
- * await rateLimiter.maybeExecute('arg1', 'arg2');
77
- *
78
- * // Additional calls within the window will be rejected
79
- * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected
80
- * ```
81
- */
82
- async maybeExecute(...args) {
83
- this.cleanupOldExecutions();
84
- const limit = this.getLimit();
85
- const window = this.getWindow();
86
- if (this._options.windowType === "sliding") {
87
- if (this._executionTimes.length < limit) {
88
- await this.execute(...args);
89
- return this._lastResult;
30
+ this.#setState = (newState) => {
31
+ this.store.setState((state) => {
32
+ const combinedState = {
33
+ ...state,
34
+ ...newState
35
+ };
36
+ return combinedState;
37
+ });
38
+ };
39
+ this.#getEnabled = () => {
40
+ return !!utils.parseFunctionOrValue(this.options.enabled, this);
41
+ };
42
+ this.#getLimit = () => {
43
+ return utils.parseFunctionOrValue(this.options.limit, this);
44
+ };
45
+ this.#getWindow = () => {
46
+ return utils.parseFunctionOrValue(this.options.window, this);
47
+ };
48
+ this.maybeExecute = async (...args) => {
49
+ this.#cleanupOldExecutions();
50
+ const relevantExecutionTimes = this.#getRelevantExecutionTimes();
51
+ if (relevantExecutionTimes.length < this.#getLimit()) {
52
+ await this.#execute(...args);
53
+ return this.store.state.lastResult;
90
54
  }
91
- } else {
55
+ this.#setState({
56
+ rejectionCount: this.store.state.rejectionCount + 1
57
+ });
58
+ this.options.onReject?.(this);
59
+ return void 0;
60
+ };
61
+ this.#execute = async (...args) => {
62
+ if (!this.#getEnabled()) return;
92
63
  const now = Date.now();
93
- const oldestExecution = Math.min(...this._executionTimes);
94
- const isNewWindow = oldestExecution + window <= now;
95
- if (isNewWindow || this._executionTimes.length < limit) {
96
- await this.execute(...args);
97
- return this._lastResult;
64
+ const executionTimes = [...this.store.state.executionTimes, now];
65
+ this.#setState({
66
+ isExecuting: true,
67
+ executionTimes
68
+ });
69
+ try {
70
+ const result = await this.fn(...args);
71
+ this.#setState({
72
+ successCount: this.store.state.successCount + 1,
73
+ lastResult: result
74
+ });
75
+ this.options.onSuccess?.(result, this);
76
+ } catch (error) {
77
+ this.#setState({
78
+ errorCount: this.store.state.errorCount + 1
79
+ });
80
+ this.options.onError?.(error, this);
81
+ if (this.options.throwOnError) {
82
+ throw error;
83
+ }
84
+ } finally {
85
+ this.#setState({
86
+ isExecuting: false,
87
+ settleCount: this.store.state.settleCount + 1
88
+ });
89
+ this.options.onSettled?.(this);
98
90
  }
99
- }
100
- this.rejectFunction();
101
- return void 0;
102
- }
103
- async execute(...args) {
104
- var _a, _b, _c, _d, _e, _f;
105
- if (!this.getEnabled()) return;
106
- this._isExecuting = true;
107
- const now = Date.now();
108
- this._executionTimes.push(now);
109
- try {
110
- this._lastResult = await this.fn(...args);
111
- this._successCount++;
112
- (_b = (_a = this._options).onSuccess) == null ? void 0 : _b.call(_a, this._lastResult, this);
113
- } catch (error) {
114
- this._errorCount++;
115
- (_d = (_c = this._options).onError) == null ? void 0 : _d.call(_c, error, this);
116
- if (this._options.throwOnError) {
117
- throw error;
91
+ return this.store.state.lastResult;
92
+ };
93
+ this.#getRelevantExecutionTimes = () => {
94
+ if (this.options.windowType === "sliding") {
95
+ return this.store.state.executionTimes.filter(
96
+ (time) => time > Date.now() - this.#getWindow()
97
+ );
118
98
  } else {
119
- console.error(error);
99
+ const oldestExecution = Math.min(...this.store.state.executionTimes);
100
+ const windowStart = oldestExecution;
101
+ return this.store.state.executionTimes.filter(
102
+ (time) => time >= windowStart && time <= windowStart + this.#getWindow()
103
+ );
120
104
  }
121
- } finally {
122
- this._isExecuting = false;
123
- this._settleCount++;
124
- (_f = (_e = this._options).onSettled) == null ? void 0 : _f.call(_e, this);
125
- }
126
- return this._lastResult;
127
- }
128
- rejectFunction() {
129
- this._rejectionCount++;
130
- if (this._options.onReject) {
131
- this._options.onReject(this);
132
- }
133
- }
134
- cleanupOldExecutions() {
135
- const now = Date.now();
136
- const windowStart = now - this.getWindow();
137
- this._executionTimes = this._executionTimes.filter(
138
- (time) => time > windowStart
139
- );
140
- }
141
- /**
142
- * Returns the number of remaining executions allowed in the current window
143
- */
144
- getRemainingInWindow() {
145
- this.cleanupOldExecutions();
146
- return Math.max(0, this.getLimit() - this._executionTimes.length);
147
- }
148
- /**
149
- * Returns the number of milliseconds until the next execution will be possible
150
- * For fixed windows, this is the time until the current window resets
151
- * For sliding windows, this is the time until the oldest execution expires
152
- */
153
- getMsUntilNextWindow() {
154
- if (this.getRemainingInWindow() > 0) {
155
- return 0;
156
- }
157
- const oldestExecution = Math.min(...this._executionTimes);
158
- return oldestExecution + this.getWindow() - Date.now();
159
- }
160
- /**
161
- * Returns the number of times the function has been executed
162
- */
163
- getSuccessCount() {
164
- return this._successCount;
165
- }
166
- /**
167
- * Returns the number of times the function has been settled
168
- */
169
- getSettleCount() {
170
- return this._settleCount;
171
- }
172
- /**
173
- * Returns the number of times the function has errored
174
- */
175
- getErrorCount() {
176
- return this._errorCount;
177
- }
178
- /**
179
- * Returns the number of times the function has been rejected
180
- */
181
- getRejectionCount() {
182
- return this._rejectionCount;
183
- }
184
- /**
185
- * Returns whether the function is currently executing
186
- */
187
- getIsExecuting() {
188
- return this._isExecuting;
189
- }
190
- /**
191
- * Resets the rate limiter state
192
- */
193
- reset() {
194
- this._executionTimes = [];
195
- this._successCount = 0;
196
- this._errorCount = 0;
197
- this._rejectionCount = 0;
198
- this._settleCount = 0;
199
- }
105
+ };
106
+ this.#cleanupOldExecutions = () => {
107
+ const now = Date.now();
108
+ const windowStart = now - this.#getWindow();
109
+ this.#setState({
110
+ executionTimes: this.store.state.executionTimes.filter(
111
+ (time) => time > windowStart
112
+ )
113
+ });
114
+ };
115
+ this.getRemainingInWindow = () => {
116
+ const relevantExecutionTimes = this.#getRelevantExecutionTimes();
117
+ return Math.max(0, this.#getLimit() - relevantExecutionTimes.length);
118
+ };
119
+ this.getMsUntilNextWindow = () => {
120
+ if (this.getRemainingInWindow() > 0) {
121
+ return 0;
122
+ }
123
+ const oldestExecution = this.store.state.executionTimes[0] ?? Infinity;
124
+ return oldestExecution + this.#getWindow() - Date.now();
125
+ };
126
+ this.reset = () => {
127
+ this.#setState(getDefaultAsyncRateLimiterState());
128
+ };
129
+ this.options = {
130
+ ...defaultOptions,
131
+ ...initialOptions,
132
+ throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
133
+ };
134
+ this.#setState(this.options.initialState ?? {});
135
+ }
136
+ #setState;
137
+ #getEnabled;
138
+ #getLimit;
139
+ #getWindow;
140
+ #execute;
141
+ #getRelevantExecutionTimes;
142
+ #cleanupOldExecutions;
200
143
  }
201
144
  function asyncRateLimit(fn, initialOptions) {
202
145
  const rateLimiter = new AsyncRateLimiter(fn, initialOptions);
203
- return rateLimiter.maybeExecute.bind(rateLimiter);
146
+ return rateLimiter.maybeExecute;
204
147
  }
205
148
  exports.AsyncRateLimiter = AsyncRateLimiter;
206
149
  exports.asyncRateLimit = asyncRateLimit;
@@ -1 +1 @@
1
- {"version":3,"file":"async-rate-limiter.cjs","sources":["../../src/async-rate-limiter.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction, OptionalKeys } 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 * 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 * 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?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => 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 * 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 * 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\ntype AsyncRateLimiterOptionsWithOptionalCallbacks = OptionalKeys<\n AsyncRateLimiterOptions<any>,\n 'onError' | 'onReject' | 'onSettled' | 'onSuccess'\n>\n\nconst defaultOptions: Omit<\n AsyncRateLimiterOptionsWithOptionalCallbacks,\n 'limit' | 'window'\n> = {\n enabled: true,\n windowType: 'fixed',\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 * The rate limiter supports two types of windows:\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 * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\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 * 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 private _options: AsyncRateLimiterOptionsWithOptionalCallbacks\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 private _isExecuting = false\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n }\n\n /**\n * Updates the rate limiter options\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(): AsyncRateLimiterOptions<TFn> {\n return this._options\n }\n\n /**\n * Returns the current enabled state of the 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 * If execution is allowed, waits for any previous execution to complete before proceeding.\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 * - If the rate limit is exceeded, the execution will be rejected and the `onReject` handler\n * will be called if configured.\n * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.\n * - Rate limit rejections can be tracked using `getRejectionCount()`.\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 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 const limit = this.getLimit()\n const window = this.getWindow()\n\n if (this._options.windowType === 'sliding') {\n // For sliding window, we can execute if we have capacity in the current window\n if (this._executionTimes.length < limit) {\n await this.execute(...args)\n return this._lastResult\n }\n } else {\n // For fixed window, we need to check if we're in a new window\n const now = Date.now()\n const oldestExecution = Math.min(...this._executionTimes)\n const isNewWindow = oldestExecution + window <= now\n\n if (isNewWindow || this._executionTimes.length < limit) {\n await this.execute(...args)\n return this._lastResult\n }\n }\n\n this.rejectFunction()\n return undefined\n }\n\n private async execute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this.getEnabled()) return\n this._isExecuting = true\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 if (this._options.throwOnError) {\n throw error\n } else {\n console.error(error)\n }\n } finally {\n this._isExecuting = false\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.getWindow()\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.getLimit() - this._executionTimes.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 = Math.min(...this._executionTimes)\n return oldestExecution + this.getWindow() - Date.now()\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 * Returns whether the function is currently executing\n */\n getIsExecuting(): boolean {\n return this._isExecuting\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 * Unlike the non-async rate limiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * The rate limiter supports two types of windows:\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 * 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 * 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 * // 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.bind(rateLimiter)\n}\n"],"names":["parseFunctionOrValue"],"mappings":";;;AAgEA,MAAM,iBAGF;AAAA,EACF,SAAS;AAAA,EACT,YAAY;AACd;AAwDO,MAAM,iBAA+C;AAAA,EAU1D,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AATV,SAAQ,cAAc;AACtB,SAAQ,kBAAiC,CAAC;AAE1C,SAAQ,kBAAkB;AAC1B,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;AACxB,SAAQ,eAAe;AAMrB,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;A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AI,KAAK,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMvD,kBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAAyB;AACvB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,gBAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,QAAc;AACZ,SAAK,kBAAkB,CAAC;AACxB,SAAK,gBAAgB;AACrB,SAAK,cAAc;AACnB,SAAK,kBAAkB;AACvB,SAAK,eAAe;AAAA,EAAA;AAExB;AAuDgB,SAAA,eACd,IACA,gBACA;AACA,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 { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\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-limited function is currently executing asynchronously\n */\n isExecuting: boolean\n /**\n * The result from the most recent successful function execution\n */\n lastResult: ReturnType<TFn> | undefined\n /**\n * Number of function executions that have been rejected due to rate limiting\n */\n rejectionCount: number\n /**\n * Number of function executions that have completed (either successfully or with errors)\n */\n settleCount: number\n /**\n * Number of function executions that have completed successfully\n */\n successCount: number\n}\n\nfunction getDefaultAsyncRateLimiterState<\n TFn extends AnyAsyncFunction,\n>(): AsyncRateLimiterState<TFn> {\n return {\n errorCount: 0,\n executionTimes: [],\n isExecuting: false,\n lastResult: undefined,\n rejectionCount: 0,\n settleCount: 0,\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 * 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 * 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?: (error: unknown, rateLimiter: AsyncRateLimiter<TFn>) => 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 * 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 * 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\nconst defaultOptions: Omit<\n Required<AsyncRateLimiterOptions<any>>,\n 'initialState' | 'onError' | 'onReject' | 'onSettled' | 'onSuccess'\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 * 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 * The rate limiter supports two types of windows:\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 * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\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 * 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 options: AsyncRateLimiterOptions<TFn>\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncRateLimiterOptions<TFn>,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n this.#setState(this.options.initialState ?? {})\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 return combinedState\n })\n }\n\n /**\n * Returns the current enabled state of the async rate limiter\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current limit of executions allowed within the time window\n */\n #getLimit = (): number => {\n return parseFunctionOrValue(this.options.limit, this)\n }\n\n /**\n * Returns the current time window in milliseconds\n */\n #getWindow = (): number => {\n return parseFunctionOrValue(this.options.window, this)\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n *\n * Error Handling:\n * - If the rate-limited function throws and no `onError` handler is configured,\n * the error will be thrown from this method.\n * - If an `onError` handler is configured, errors will be caught and passed to the handler,\n * and this method will return undefined.\n * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.\n *\n * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError\n * @throws The error from the rate-limited function if no onError handler is configured\n *\n * @example\n * ```ts\n * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return a promise that resolves with the result\n * const result = await rateLimiter.maybeExecute('arg1', 'arg2');\n *\n * // Additional calls within the window will return undefined\n * const result2 = await rateLimiter.maybeExecute('arg1', 'arg2'); // undefined\n * ```\n */\n maybeExecute = async (\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> => {\n this.#cleanupOldExecutions()\n\n const relevantExecutionTimes = this.#getRelevantExecutionTimes()\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?.(this)\n return undefined\n }\n\n #execute = async (\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> => {\n if (!this.#getEnabled()) return\n\n const now = Date.now()\n const executionTimes = [...this.store.state.executionTimes, now]\n this.#setState({\n isExecuting: true,\n executionTimes,\n })\n\n try {\n const result = await this.fn(...args)\n this.#setState({\n successCount: this.store.state.successCount + 1,\n lastResult: result,\n })\n this.options.onSuccess?.(result, this)\n } catch (error) {\n this.#setState({\n errorCount: this.store.state.errorCount + 1,\n })\n this.options.onError?.(error, this)\n if (this.options.throwOnError) {\n throw error\n }\n } finally {\n this.#setState({\n isExecuting: false,\n settleCount: this.store.state.settleCount + 1,\n })\n this.options.onSettled?.(this)\n }\n\n return this.store.state.lastResult\n }\n\n #getRelevantExecutionTimes = (): 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 const oldestExecution = Math.min(...this.store.state.executionTimes)\n const windowStart = oldestExecution\n return this.store.state.executionTimes.filter(\n (time) =>\n time >= windowStart && time <= windowStart + this.#getWindow(),\n )\n }\n }\n\n #cleanupOldExecutions = (): void => {\n const now = Date.now()\n const windowStart = now - this.#getWindow()\n this.#setState({\n executionTimes: this.store.state.executionTimes.filter(\n (time) => time > windowStart,\n ),\n })\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow = (): number => {\n const relevantExecutionTimes = this.#getRelevantExecutionTimes()\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 * Resets the rate limiter state\n */\n reset = (): void => {\n this.#setState(getDefaultAsyncRateLimiterState())\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 * Unlike the non-async rate limiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * The rate limiter supports two types of windows:\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 * 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 * 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 * 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 * 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 * // 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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MAAM,MAAM,eAAe;AAAA,UACrC,CAAC,SACC,QAAQ,eAAe,QAAQ,cAAc,KAAK,WAAA;AAAA,QAAW;AAAA,MACjE;AAAA,IACF;AAGF,SAAA,wBAAwB,MAAY;AAClC,YAAM,MAAM,KAAK,IAAA;AACjB,YAAM,cAAc,MAAM,KAAK,WAAA;AAC/B,WAAK,UAAU;AAAA,QACb,gBAAgB,KAAK,MAAM,MAAM,eAAe;AAAA,UAC9C,CAAC,SAAS,OAAO;AAAA,QAAA;AAAA,MACnB,CACD;AAAA,IAAA;AAMH,SAAA,uBAAuB,MAAc;AACnC,YAAM,yBAAyB,KAAK,2BAAA;AACpC,aAAO,KAAK,IAAI,GAAG,KAAK,UAAA,IAAc,uBAAuB,MAAM;AAAA,IAAA;AAQrE,SAAA,uBAAuB,MAAc;AACnC,UAAI,KAAK,qBAAA,IAAyB,GAAG;AACnC,eAAO;AAAA,MAAA;AAET,YAAM,kBAAkB,KAAK,MAAM,MAAM,eAAe,CAAC,KAAK;AAC9D,aAAO,kBAAkB,KAAK,WAAA,IAAe,KAAK,IAAA;AAAA,IAAI;AAMxD,SAAA,QAAQ,MAAY;AAClB,WAAK,UAAU,iCAAiC;AAAA,IAAA;AArLhD,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,MACH,cAAc,eAAe,gBAAgB,CAAC,eAAe;AAAA,IAAA;AAE/D,SAAK,UAAU,KAAK,QAAQ,gBAAgB,CAAA,CAAE;AAAA,EAAA;AAAA,EAUhD;AAAA,EAaA;AAAA,EAOA;AAAA,EAOA;AAAA,EAgDA;AAAA,EAsCA;AAAA,EAkBA;AAqCF;AAmEO,SAAS,eACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,iBAAiB,IAAI,cAAc;AAC3D,SAAO,YAAY;AACrB;;;"}
@@ -1,4 +1,35 @@
1
+ import { Store } from '@tanstack/store';
1
2
  import { AnyAsyncFunction } from './types.cjs';
3
+ export interface AsyncRateLimiterState<TFn extends AnyAsyncFunction> {
4
+ /**
5
+ * Number of function executions that have resulted in errors
6
+ */
7
+ errorCount: number;
8
+ /**
9
+ * Array of timestamps when executions occurred for rate limiting calculations
10
+ */
11
+ executionTimes: Array<number>;
12
+ /**
13
+ * Whether the rate-limited function is currently executing asynchronously
14
+ */
15
+ isExecuting: boolean;
16
+ /**
17
+ * The result from the most recent successful function execution
18
+ */
19
+ lastResult: ReturnType<TFn> | undefined;
20
+ /**
21
+ * Number of function executions that have been rejected due to rate limiting
22
+ */
23
+ rejectionCount: number;
24
+ /**
25
+ * Number of function executions that have completed (either successfully or with errors)
26
+ */
27
+ settleCount: number;
28
+ /**
29
+ * Number of function executions that have completed successfully
30
+ */
31
+ successCount: number;
32
+ }
2
33
  /**
3
34
  * Options for configuring an async rate-limited function
4
35
  */
@@ -9,6 +40,10 @@ export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
9
40
  * Defaults to true.
10
41
  */
11
42
  enabled?: boolean | ((rateLimiter: AsyncRateLimiter<TFn>) => boolean);
43
+ /**
44
+ * Initial state for the rate limiter
45
+ */
46
+ initialState?: Partial<AsyncRateLimiterState<TFn>>;
12
47
  /**
13
48
  * Maximum number of executions allowed within the time window.
14
49
  * Can be a number or a function that returns a number.
@@ -75,6 +110,18 @@ export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
75
110
  * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
76
111
  * smoothing out frequent events, throttling or debouncing usually provide better user experience.
77
112
  *
113
+ * State Management:
114
+ * - Uses TanStack Store for reactive state management
115
+ * - Use `initialState` to provide initial state values when creating the rate limiter
116
+ * - `initialState` can be a partial state object
117
+ * - Use `onSuccess` callback to react to successful function execution and implement custom logic
118
+ * - Use `onError` callback to react to function execution errors and implement custom error handling
119
+ * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
120
+ * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
121
+ * - The state includes execution times, success/error counts, and current execution status
122
+ * - State can be accessed via `asyncRateLimiter.store.state` when using the class directly
123
+ * - When using framework adapters (React/Solid), state is accessed from `asyncRateLimiter.state`
124
+ *
78
125
  * Error Handling:
79
126
  * - If an `onError` handler is provided, it will be called with the error and rate limiter instance
80
127
  * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
@@ -106,50 +153,25 @@ export interface AsyncRateLimiterOptions<TFn extends AnyAsyncFunction> {
106
153
  * ```
107
154
  */
108
155
  export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
156
+ #private;
109
157
  private fn;
110
- private _options;
111
- private _errorCount;
112
- private _executionTimes;
113
- private _lastResult;
114
- private _rejectionCount;
115
- private _settleCount;
116
- private _successCount;
117
- private _isExecuting;
158
+ readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>;
159
+ options: AsyncRateLimiterOptions<TFn>;
118
160
  constructor(fn: TFn, initialOptions: AsyncRateLimiterOptions<TFn>);
119
161
  /**
120
- * Updates the rate limiter options
162
+ * Updates the async rate limiter options
121
163
  */
122
- setOptions(newOptions: Partial<AsyncRateLimiterOptions<TFn>>): void;
123
- /**
124
- * Returns the current rate limiter options
125
- */
126
- getOptions(): AsyncRateLimiterOptions<TFn>;
127
- /**
128
- * Returns the current enabled state of the rate limiter
129
- */
130
- getEnabled(): boolean;
131
- /**
132
- * Returns the current limit of executions allowed within the time window
133
- */
134
- getLimit(): number;
135
- /**
136
- * Returns the current time window in milliseconds
137
- */
138
- getWindow(): number;
164
+ setOptions: (newOptions: Partial<AsyncRateLimiterOptions<TFn>>) => void;
139
165
  /**
140
166
  * Attempts to execute the rate-limited function if within the configured limits.
141
167
  * Will reject execution if the number of calls in the current window exceeds the limit.
142
- * If execution is allowed, waits for any previous execution to complete before proceeding.
143
168
  *
144
169
  * Error Handling:
145
170
  * - If the rate-limited function throws and no `onError` handler is configured,
146
171
  * the error will be thrown from this method.
147
172
  * - If an `onError` handler is configured, errors will be caught and passed to the handler,
148
173
  * and this method will return undefined.
149
- * - If the rate limit is exceeded, the execution will be rejected and the `onReject` handler
150
- * will be called if configured.
151
174
  * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
152
- * - Rate limit rejections can be tracked using `getRejectionCount()`.
153
175
  *
154
176
  * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
155
177
  * @throws The error from the rate-limited function if no onError handler is configured
@@ -158,51 +180,28 @@ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
158
180
  * ```ts
159
181
  * const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
160
182
  *
161
- * // First 5 calls will execute
162
- * await rateLimiter.maybeExecute('arg1', 'arg2');
183
+ * // First 5 calls will return a promise that resolves with the result
184
+ * const result = await rateLimiter.maybeExecute('arg1', 'arg2');
163
185
  *
164
- * // Additional calls within the window will be rejected
165
- * await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected
186
+ * // Additional calls within the window will return undefined
187
+ * const result2 = await rateLimiter.maybeExecute('arg1', 'arg2'); // undefined
166
188
  * ```
167
189
  */
168
- maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
169
- private execute;
170
- private rejectFunction;
171
- private cleanupOldExecutions;
190
+ maybeExecute: (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
172
191
  /**
173
192
  * Returns the number of remaining executions allowed in the current window
174
193
  */
175
- getRemainingInWindow(): number;
194
+ getRemainingInWindow: () => number;
176
195
  /**
177
196
  * Returns the number of milliseconds until the next execution will be possible
178
197
  * For fixed windows, this is the time until the current window resets
179
198
  * For sliding windows, this is the time until the oldest execution expires
180
199
  */
181
- getMsUntilNextWindow(): number;
182
- /**
183
- * Returns the number of times the function has been executed
184
- */
185
- getSuccessCount(): number;
186
- /**
187
- * Returns the number of times the function has been settled
188
- */
189
- getSettleCount(): number;
190
- /**
191
- * Returns the number of times the function has errored
192
- */
193
- getErrorCount(): number;
194
- /**
195
- * Returns the number of times the function has been rejected
196
- */
197
- getRejectionCount(): number;
198
- /**
199
- * Returns whether the function is currently executing
200
- */
201
- getIsExecuting(): boolean;
200
+ getMsUntilNextWindow: () => number;
202
201
  /**
203
202
  * Resets the rate limiter state
204
203
  */
205
- reset(): void;
204
+ reset: () => void;
206
205
  }
207
206
  /**
208
207
  * Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.
@@ -222,6 +221,18 @@ export declare class AsyncRateLimiter<TFn extends AnyAsyncFunction> {
222
221
  * - A throttler ensures even spacing between executions, which can be better for consistent performance
223
222
  * - A debouncer collapses multiple calls into one, which is better for handling bursts of events
224
223
  *
224
+ * State Management:
225
+ * - Uses TanStack Store for reactive state management
226
+ * - Use `initialState` to provide initial state values when creating the rate limiter
227
+ * - `initialState` can be a partial state object
228
+ * - Use `onSuccess` callback to react to successful function execution and implement custom logic
229
+ * - Use `onError` callback to react to function execution errors and implement custom error handling
230
+ * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
231
+ * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
232
+ * - The state includes execution times, success/error counts, and current execution status
233
+ * - State can be accessed via the underlying AsyncRateLimiter instance's `store.state` property
234
+ * - When using framework adapters (React/Solid), state is accessed from the hook's state property
235
+ *
225
236
  * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
226
237
  * need to enforce a hard limit on the number of executions within a time period.
227
238
  *