@tanstack/pacer 0.21.1 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +21 -6
  2. package/dist/async-batcher.d.ts +11 -14
  3. package/dist/async-batcher.js +186 -132
  4. package/dist/async-debouncer.d.ts +10 -13
  5. package/dist/async-debouncer.js +187 -146
  6. package/dist/async-queuer.d.ts +12 -14
  7. package/dist/async-queuer.js +384 -259
  8. package/dist/async-rate-limiter.d.ts +9 -12
  9. package/dist/async-rate-limiter.js +198 -147
  10. package/dist/async-retryer.d.ts +10 -10
  11. package/dist/async-retryer.js +209 -188
  12. package/dist/async-throttler.d.ts +10 -13
  13. package/dist/async-throttler.js +215 -161
  14. package/dist/batcher.d.ts +5 -8
  15. package/dist/batcher.js +107 -87
  16. package/dist/debouncer.d.ts +6 -9
  17. package/dist/debouncer.js +99 -86
  18. package/dist/event-client.d.ts +8 -11
  19. package/dist/event-client.js +1 -2
  20. package/dist/index.js +1 -1
  21. package/dist/queuer.d.ts +8 -10
  22. package/dist/queuer.js +277 -207
  23. package/dist/rate-limiter.d.ts +6 -9
  24. package/dist/rate-limiter.js +127 -109
  25. package/dist/throttler.d.ts +6 -9
  26. package/dist/throttler.js +127 -90
  27. package/dist/types.d.ts +4 -6
  28. package/dist/utils.d.ts +3 -6
  29. package/dist/utils.js +1 -2
  30. package/package.json +23 -70
  31. package/dist/async-batcher.cjs +0 -337
  32. package/dist/async-batcher.cjs.map +0 -1
  33. package/dist/async-batcher.d.cts +0 -344
  34. package/dist/async-batcher.js.map +0 -1
  35. package/dist/async-debouncer.cjs +0 -330
  36. package/dist/async-debouncer.cjs.map +0 -1
  37. package/dist/async-debouncer.d.cts +0 -300
  38. package/dist/async-debouncer.js.map +0 -1
  39. package/dist/async-queuer.cjs +0 -484
  40. package/dist/async-queuer.cjs.map +0 -1
  41. package/dist/async-queuer.d.cts +0 -440
  42. package/dist/async-queuer.js.map +0 -1
  43. package/dist/async-rate-limiter.cjs +0 -373
  44. package/dist/async-rate-limiter.cjs.map +0 -1
  45. package/dist/async-rate-limiter.d.cts +0 -357
  46. package/dist/async-rate-limiter.js.map +0 -1
  47. package/dist/async-retryer.cjs +0 -374
  48. package/dist/async-retryer.cjs.map +0 -1
  49. package/dist/async-retryer.d.cts +0 -319
  50. package/dist/async-retryer.js.map +0 -1
  51. package/dist/async-throttler.cjs +0 -347
  52. package/dist/async-throttler.cjs.map +0 -1
  53. package/dist/async-throttler.d.cts +0 -320
  54. package/dist/async-throttler.js.map +0 -1
  55. package/dist/batcher.cjs +0 -200
  56. package/dist/batcher.cjs.map +0 -1
  57. package/dist/batcher.d.cts +0 -180
  58. package/dist/batcher.js.map +0 -1
  59. package/dist/debouncer.cjs +0 -203
  60. package/dist/debouncer.cjs.map +0 -1
  61. package/dist/debouncer.d.cts +0 -167
  62. package/dist/debouncer.js.map +0 -1
  63. package/dist/event-client.cjs +0 -64
  64. package/dist/event-client.cjs.map +0 -1
  65. package/dist/event-client.d.cts +0 -66
  66. package/dist/event-client.js.map +0 -1
  67. package/dist/index.cjs +0 -52
  68. package/dist/index.d.cts +0 -15
  69. package/dist/queuer.cjs +0 -401
  70. package/dist/queuer.cjs.map +0 -1
  71. package/dist/queuer.d.cts +0 -345
  72. package/dist/queuer.js.map +0 -1
  73. package/dist/rate-limiter.cjs +0 -263
  74. package/dist/rate-limiter.cjs.map +0 -1
  75. package/dist/rate-limiter.d.cts +0 -215
  76. package/dist/rate-limiter.js.map +0 -1
  77. package/dist/throttler.cjs +0 -215
  78. package/dist/throttler.cjs.map +0 -1
  79. package/dist/throttler.d.cts +0 -207
  80. package/dist/throttler.js.map +0 -1
  81. package/dist/types.cjs +0 -0
  82. package/dist/types.d.cts +0 -13
  83. package/dist/utils.cjs +0 -14
  84. package/dist/utils.cjs.map +0 -1
  85. package/dist/utils.d.cts +0 -8
  86. package/dist/utils.js.map +0 -1
  87. package/src/async-batcher.ts +0 -594
  88. package/src/async-debouncer.ts +0 -565
  89. package/src/async-queuer.ts +0 -925
  90. package/src/async-rate-limiter.ts +0 -647
  91. package/src/async-retryer.ts +0 -684
  92. package/src/async-throttler.ts +0 -633
  93. package/src/batcher.ts +0 -329
  94. package/src/debouncer.ts +0 -334
  95. package/src/event-client.ts +0 -129
  96. package/src/index.ts +0 -24
  97. package/src/queuer.ts +0 -740
  98. package/src/rate-limiter.ts +0 -429
  99. package/src/throttler.ts +0 -380
  100. package/src/types.ts +0 -12
  101. package/src/utils.ts +0 -12
@@ -1,263 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_utils = require('./utils.cjs');
3
- const require_event_client = require('./event-client.cjs');
4
- let _tanstack_store = require("@tanstack/store");
5
-
6
- //#region src/rate-limiter.ts
7
- function getDefaultRateLimiterState() {
8
- return {
9
- executionCount: 0,
10
- executionTimes: [],
11
- isExceeded: false,
12
- rejectionCount: 0,
13
- status: "idle",
14
- maybeExecuteCount: 0
15
- };
16
- }
17
- /**
18
- * Utility function for sharing common `RateLimiterOptions` options between different `RateLimiter` instances.
19
- */
20
- function rateLimiterOptions(options) {
21
- return options;
22
- }
23
- const defaultOptions = {
24
- enabled: true,
25
- limit: 1,
26
- window: 0,
27
- windowType: "fixed"
28
- };
29
- /**
30
- * A class that creates a rate-limited function.
31
- *
32
- * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
33
- * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
34
- * all executions happen immediately, followed by a complete block.
35
- * This synchronous version is lighter weight and often all you need - upgrade to AsyncRateLimiter when you need promises, retry support, abort capabilities, or advanced error handling.
36
- *
37
- * The rate limiter supports two types of windows:
38
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
39
- * towards the limit, and the window resets completely after the period.
40
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
41
- * consistent rate of execution over time.
42
- *
43
- * For smoother execution patterns, consider using:
44
- * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
45
- * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
46
- *
47
- * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
48
- * smoothing out frequent events, throttling or debouncing usually provide better user experience.
49
- *
50
- * State Management:
51
- * - Uses TanStack Store for reactive state management
52
- * - Use `initialState` to provide initial state values when creating the rate limiter
53
- * - Use `onExecute` callback to react to function execution and implement custom logic
54
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
55
- * - The state includes execution count, execution times, and rejection count
56
- * - State can be accessed via `rateLimiter.store.state` when using the class directly
57
- * - When using framework adapters (React/Solid), state is accessed from `rateLimiter.state`
58
- *
59
- * @example
60
- * ```ts
61
- * const rateLimiter = new RateLimiter(
62
- * (id: string) => api.getData(id),
63
- * {
64
- * limit: 5,
65
- * window: 1000,
66
- * windowType: 'sliding',
67
- * }
68
- * );
69
- *
70
- * // Will execute immediately until limit reached, then block
71
- * rateLimiter.maybeExecute('123');
72
- * ```
73
- */
74
- var RateLimiter = class {
75
- #timeoutIds;
76
- constructor(fn, initialOptions) {
77
- this.fn = fn;
78
- this.store = new _tanstack_store.Store(getDefaultRateLimiterState());
79
- this.#timeoutIds = /* @__PURE__ */ new Set();
80
- this.setOptions = (newOptions) => {
81
- this.options = {
82
- ...this.options,
83
- ...newOptions
84
- };
85
- };
86
- this.#setState = (newState) => {
87
- this.store.setState((state) => {
88
- const combinedState = {
89
- ...state,
90
- ...newState
91
- };
92
- const isExceeded = combinedState.executionTimes.length >= this.#getLimit();
93
- const status = !this.#getEnabled() ? "disabled" : isExceeded ? "exceeded" : "idle";
94
- return {
95
- ...combinedState,
96
- isExceeded,
97
- status
98
- };
99
- });
100
- require_event_client.emitChange("RateLimiter", this);
101
- };
102
- this.#getEnabled = () => {
103
- return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
104
- };
105
- this.#getLimit = () => {
106
- return require_utils.parseFunctionOrValue(this.options.limit, this);
107
- };
108
- this.#getWindow = () => {
109
- return require_utils.parseFunctionOrValue(this.options.window, this);
110
- };
111
- this.maybeExecute = (...args) => {
112
- this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
113
- this.#cleanupOldExecutions();
114
- if (this.#getExecutionTimesInWindow().length < this.#getLimit()) {
115
- this.#execute(...args);
116
- return true;
117
- }
118
- this.#setState({ rejectionCount: this.store.state.rejectionCount + 1 });
119
- this.options.onReject?.(this);
120
- return false;
121
- };
122
- this.#execute = (...args) => {
123
- if (!this.#getEnabled()) return;
124
- const now = Date.now();
125
- this.fn(...args);
126
- this.store.state.executionTimes.push(now);
127
- this.#setCleanupTimeout(now);
128
- this.#setState({ executionCount: this.store.state.executionCount + 1 });
129
- this.options.onExecute?.(args, this);
130
- };
131
- this.#getExecutionTimesInWindow = () => {
132
- if (this.options.windowType === "sliding") return this.store.state.executionTimes.filter((time) => time > Date.now() - this.#getWindow());
133
- else {
134
- if (this.store.state.executionTimes.length === 0) return [];
135
- const windowStart = Math.min(...this.store.state.executionTimes);
136
- const windowEnd = windowStart + this.#getWindow();
137
- if (Date.now() > windowEnd) return [];
138
- return this.store.state.executionTimes.filter((time) => time >= windowStart && time <= windowEnd);
139
- }
140
- };
141
- this.#setCleanupTimeout = (executionTime) => {
142
- if (this.options.windowType === "sliding" || this.#timeoutIds.size === 0) {
143
- const timeUntilExpiration = executionTime - Date.now() + this.#getWindow() + 1;
144
- const timeoutId = setTimeout(() => {
145
- this.#cleanupOldExecutions();
146
- this.#clearTimeout(timeoutId);
147
- }, timeUntilExpiration);
148
- this.#timeoutIds.add(timeoutId);
149
- }
150
- };
151
- this.#clearTimeout = (timeoutId) => {
152
- clearTimeout(timeoutId);
153
- this.#timeoutIds.delete(timeoutId);
154
- };
155
- this.#clearTimeouts = () => {
156
- this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId));
157
- this.#timeoutIds.clear();
158
- };
159
- this.#cleanupOldExecutions = () => {
160
- this.#setState({ executionTimes: this.#getExecutionTimesInWindow() });
161
- };
162
- this.getRemainingInWindow = () => {
163
- const relevantExecutionTimes = this.#getExecutionTimesInWindow();
164
- return Math.max(0, this.#getLimit() - relevantExecutionTimes.length);
165
- };
166
- this.getMsUntilNextWindow = () => {
167
- if (this.getRemainingInWindow() > 0) return 0;
168
- return (this.store.state.executionTimes[0] ?? Infinity) + this.#getWindow() - Date.now();
169
- };
170
- this.reset = () => {
171
- this.#setState(getDefaultRateLimiterState());
172
- this.#clearTimeouts();
173
- };
174
- this.key = initialOptions.key;
175
- this.options = {
176
- ...defaultOptions,
177
- ...initialOptions
178
- };
179
- this.#setState(this.options.initialState ?? {});
180
- for (const executionTime of this.#getExecutionTimesInWindow()) this.#setCleanupTimeout(executionTime);
181
- if (this.key) require_event_client.pacerEventClient.on("d-RateLimiter", (event) => {
182
- if (event.payload.key !== this.key) return;
183
- this.#setState(event.payload.store.state);
184
- this.setOptions(event.payload.options);
185
- });
186
- }
187
- #setState;
188
- /**
189
- * Returns the current enabled state of the rate limiter
190
- */
191
- #getEnabled;
192
- /**
193
- * Returns the current limit of executions allowed within the time window
194
- */
195
- #getLimit;
196
- /**
197
- * Returns the current time window in milliseconds
198
- */
199
- #getWindow;
200
- #execute;
201
- #getExecutionTimesInWindow;
202
- #setCleanupTimeout;
203
- #clearTimeout;
204
- #clearTimeouts;
205
- #cleanupOldExecutions;
206
- };
207
- /**
208
- * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
209
- *
210
- * This synchronous version is lighter weight and often all you need - upgrade to asyncRateLimit when you need promises, retry support, abort capabilities, or advanced error handling.
211
- *
212
- * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
213
- * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
214
- * - A throttler ensures even spacing between executions, which can be better for consistent performance
215
- * - A debouncer collapses multiple calls into one, which is better for handling bursts of events
216
- *
217
- * The rate limiter supports two types of windows:
218
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
219
- * towards the limit, and the window resets completely after the period.
220
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
221
- * consistent rate of execution over time.
222
- *
223
- * State Management:
224
- * - Uses TanStack Store for reactive state management
225
- * - Use `initialState` to provide initial state values when creating the rate limiter
226
- * - Use `onExecute` callback to react to function execution and implement custom logic
227
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
228
- * - The state includes execution count, execution times, and rejection count
229
- * - State can be accessed via the underlying RateLimiter instance's `store.state` property
230
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
231
- *
232
- * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
233
- * need to enforce a hard limit on the number of executions within a time period.
234
- *
235
- * @example
236
- * ```ts
237
- * // Rate limit to 5 calls per minute with a sliding window
238
- * const rateLimited = rateLimit(makeApiCall, {
239
- * limit: 5,
240
- * window: 60000,
241
- * windowType: 'sliding',
242
- * onReject: (rateLimiter) => {
243
- * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
244
- * }
245
- * });
246
- *
247
- * // First 5 calls will execute immediately
248
- * // Additional calls will be rejected until the minute window resets
249
- * rateLimited();
250
- *
251
- * // For more even execution, consider using throttle instead:
252
- * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
253
- * ```
254
- */
255
- function rateLimit(fn, initialOptions) {
256
- return new RateLimiter(fn, initialOptions).maybeExecute;
257
- }
258
-
259
- //#endregion
260
- exports.RateLimiter = RateLimiter;
261
- exports.rateLimit = rateLimit;
262
- exports.rateLimiterOptions = rateLimiterOptions;
263
- //# sourceMappingURL=rate-limiter.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rate-limiter.cjs","names":["Store","#getLimit","#getEnabled","parseFunctionOrValue","#setState","#cleanupOldExecutions","#getExecutionTimesInWindow","#execute","#setCleanupTimeout","#getWindow","#timeoutIds","#clearTimeout","#clearTimeouts"],"sources":["../src/rate-limiter.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AnyFunction } from './types'\n\nexport interface RateLimiterState {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Array of timestamps when executions occurred for rate limiting calculations\n */\n executionTimes: Array<number>\n /**\n * Whether the rate limiter has exceeded the limit\n */\n isExceeded: boolean\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Number of function executions that have been rejected due to rate limiting\n */\n rejectionCount: number\n /**\n * Current execution status - 'disabled' when not active, 'executing' when executing, 'idle' when not executing, 'exceeded' when rate limit is exceeded\n */\n status: 'disabled' | 'exceeded' | 'idle'\n}\n\nfunction getDefaultRateLimiterState(): RateLimiterState {\n return {\n executionCount: 0,\n executionTimes: [],\n isExceeded: false,\n rejectionCount: 0,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions<TFn extends AnyFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean)\n /**\n * Initial state for the rate limiter\n */\n initialState?: Partial<RateLimiterState>\n /**\n * Optional key to identify this rate limiter instance.\n * If provided, the rate limiter will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n limit: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, rateLimiter: RateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Time window in milliseconds within which the limit applies.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n window: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\n/**\n * Utility function for sharing common `RateLimiterOptions` options between different `RateLimiter` instances.\n */\nexport function rateLimiterOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<RateLimiterOptions<TFn>> = Partial<\n RateLimiterOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<RateLimiterOptions<any>>,\n 'initialState' | 'onExecute' | 'onReject' | 'key'\n> = {\n enabled: true,\n limit: 1,\n window: 0,\n windowType: 'fixed',\n}\n\n/**\n * A class that creates a 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 * This synchronous version is lighter weight and often all you need - upgrade to AsyncRateLimiter when you need promises, retry support, abort capabilities, or advanced error handling.\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 * 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 * - Use `onExecute` callback to react to function execution and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution count, execution times, and rejection count\n * - State can be accessed via `rateLimiter.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `rateLimiter.state`\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(\n * (id: string) => api.getData(id),\n * {\n * limit: 5,\n * window: 1000,\n * windowType: 'sliding',\n * }\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<TFn extends AnyFunction> {\n readonly store: Store<Readonly<RateLimiterState>> =\n new Store<RateLimiterState>(getDefaultRateLimiterState())\n key: string | undefined\n options: RateLimiterOptions<TFn>\n #timeoutIds: Set<ReturnType<typeof setTimeout>> = new Set()\n\n constructor(\n public fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n for (const executionTime of this.#getExecutionTimesInWindow()) {\n this.#setCleanupTimeout(executionTime)\n }\n\n if (this.key) {\n pacerEventClient.on('d-RateLimiter', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state as Partial<RateLimiterState>)\n this.setOptions(\n event.payload.options as Partial<RateLimiterOptions<TFn>>,\n )\n })\n }\n }\n\n /**\n * Updates the rate limiter options\n */\n setOptions = (newOptions: Partial<RateLimiterOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<RateLimiterState>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const isExceeded = combinedState.executionTimes.length >= this.#getLimit()\n const status = !this.#getEnabled()\n ? 'disabled'\n : isExceeded\n ? 'exceeded'\n : 'idle'\n return {\n ...combinedState,\n isExceeded,\n status,\n }\n })\n emitChange('RateLimiter', this)\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 *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute = (...args: Parameters<TFn>): boolean => {\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n this.#cleanupOldExecutions()\n\n const relevantExecutionTimes = this.#getExecutionTimesInWindow()\n\n if (relevantExecutionTimes.length < this.#getLimit()) {\n this.#execute(...args)\n return true\n }\n\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(this)\n return false\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n const now = Date.now()\n this.fn(...args) // EXECUTE!\n this.store.state.executionTimes.push(now) // mutate state directly for performance\n\n this.#setCleanupTimeout(now)\n\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n })\n this.options.onExecute?.(args, this)\n }\n\n #getExecutionTimesInWindow = (): Array<number> => {\n if (this.options.windowType === 'sliding') {\n // For sliding window, return all executions within the current window\n return this.store.state.executionTimes.filter(\n (time) => time > Date.now() - this.#getWindow(),\n )\n } else {\n // For fixed window, return all executions in the current window\n // The window starts from the oldest execution time\n if (this.store.state.executionTimes.length === 0) {\n return []\n }\n const oldestExecution = Math.min(...this.store.state.executionTimes)\n const windowStart = oldestExecution\n const windowEnd = windowStart + this.#getWindow()\n const now = Date.now()\n\n // If the window has expired, return empty array\n if (now > windowEnd) {\n return []\n }\n\n // Otherwise, return all executions in the current window\n return this.store.state.executionTimes.filter(\n (time) => time >= windowStart && time <= windowEnd,\n )\n }\n }\n\n #setCleanupTimeout = (executionTime: number): void => {\n if (\n this.options.windowType === 'sliding' ||\n this.#timeoutIds.size === 0 // new fixed window\n ) {\n const now = Date.now()\n const timeUntilExpiration = executionTime - now + this.#getWindow() + 1\n const timeoutId = setTimeout(() => {\n this.#cleanupOldExecutions()\n this.#clearTimeout(timeoutId)\n }, timeUntilExpiration)\n this.#timeoutIds.add(timeoutId)\n }\n }\n\n #clearTimeout = (timeoutId: ReturnType<typeof setTimeout>): void => {\n clearTimeout(timeoutId)\n this.#timeoutIds.delete(timeoutId)\n }\n\n #clearTimeouts = (): void => {\n this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))\n this.#timeoutIds.clear()\n }\n\n #cleanupOldExecutions = (): void => {\n this.#setState({\n executionTimes: this.#getExecutionTimesInWindow(),\n })\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow = (): number => {\n const relevantExecutionTimes = this.#getExecutionTimesInWindow()\n return Math.max(0, this.#getLimit() - relevantExecutionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\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(getDefaultRateLimiterState())\n this.#clearTimeouts()\n }\n}\n\n/**\n * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncRateLimit when you need promises, retry support, abort capabilities, or advanced error handling.\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 * 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 * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution count, execution times, and rejection count\n * - State can be accessed via the underlying RateLimiter 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 * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\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 * 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 rateLimit<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute\n}\n"],"mappings":";;;;;;AAgCA,SAAS,6BAA+C;CACtD,OAAO;EACL,gBAAgB;EAChB,gBAAgB,EAAE;EAClB,YAAY;EACZ,gBAAgB;EAChB,QAAQ;EACR,mBAAmB;EACpB;;;;;AAmDH,SAAgB,mBAKd,SAA6B;CAC7B,OAAO;;AAGT,MAAM,iBAGF;CACF,SAAS;CACT,OAAO;CACP,QAAQ;CACR,YAAY;CACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CD,IAAa,cAAb,MAAkD;CAKhD;CAEA,YACE,AAAO,IACP,gBACA;EAFO;eANP,IAAIA,sBAAwB,4BAA4B,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AG;GACH,GAAG;GACJ;EACD,KAAKR,UAAU,KAAK,QAAQ,gBAAgB,EAAE,CAAC;EAC/C,KAAK,MAAM,iBAAiB,KAAKE,4BAA4B,EAC3D,KAAKE,mBAAmB,cAAc;EAGxC,IAAI,KAAK,KACP,sCAAiB,GAAG,kBAAkB,UAAU;GAC9C,IAAI,MAAM,QAAQ,QAAQ,KAAK,KAAK;GACpC,KAAKJ,UAAU,MAAM,QAAQ,MAAM,MAAmC;GACtE,KAAK,WACH,MAAM,QAAQ,QACf;IACD;;CAWN;;;;CAwBA;;;;CAOA;;;;CAOA;CAwCA;CAcA;CA6BA;CAeA;CAKA;CAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkFF,SAAgB,UACd,IACA,gBACA;CAEA,OAAO,IADiB,YAAY,IAAI,eACtB,CAAC"}
@@ -1,215 +0,0 @@
1
- import { AnyFunction } from "./types.cjs";
2
- import { Store } from "@tanstack/store";
3
-
4
- //#region src/rate-limiter.d.ts
5
- interface RateLimiterState {
6
- /**
7
- * Number of function executions that have been completed
8
- */
9
- executionCount: number;
10
- /**
11
- * Array of timestamps when executions occurred for rate limiting calculations
12
- */
13
- executionTimes: Array<number>;
14
- /**
15
- * Whether the rate limiter has exceeded the limit
16
- */
17
- isExceeded: boolean;
18
- /**
19
- * Number of times maybeExecute has been called (for reduction calculations)
20
- */
21
- maybeExecuteCount: number;
22
- /**
23
- * Number of function executions that have been rejected due to rate limiting
24
- */
25
- rejectionCount: number;
26
- /**
27
- * Current execution status - 'disabled' when not active, 'executing' when executing, 'idle' when not executing, 'exceeded' when rate limit is exceeded
28
- */
29
- status: 'disabled' | 'exceeded' | 'idle';
30
- }
31
- /**
32
- * Options for configuring a rate-limited function
33
- */
34
- interface RateLimiterOptions<TFn extends AnyFunction> {
35
- /**
36
- * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
37
- * Defaults to true.
38
- */
39
- enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean);
40
- /**
41
- * Initial state for the rate limiter
42
- */
43
- initialState?: Partial<RateLimiterState>;
44
- /**
45
- * Optional key to identify this rate limiter instance.
46
- * If provided, the rate limiter will be identified by this key in the devtools and PacerProvider if applicable.
47
- */
48
- key?: string;
49
- /**
50
- * Maximum number of executions allowed within the time window.
51
- * Can be a number or a callback function that receives the rate limiter instance and returns a number.
52
- */
53
- limit: number | ((rateLimiter: RateLimiter<TFn>) => number);
54
- /**
55
- * Callback function that is called after the function is executed
56
- */
57
- onExecute?: (args: Parameters<TFn>, rateLimiter: RateLimiter<TFn>) => void;
58
- /**
59
- * Optional callback function that is called when an execution is rejected due to rate limiting
60
- */
61
- onReject?: (rateLimiter: RateLimiter<TFn>) => void;
62
- /**
63
- * Time window in milliseconds within which the limit applies.
64
- * Can be a number or a callback function that receives the rate limiter instance and returns a number.
65
- */
66
- window: number | ((rateLimiter: RateLimiter<TFn>) => number);
67
- /**
68
- * Type of window to use for rate limiting
69
- * - 'fixed': Uses a fixed window that resets after the window period
70
- * - 'sliding': Uses a sliding window that allows executions as old ones expire
71
- * Defaults to 'fixed'
72
- */
73
- windowType?: 'fixed' | 'sliding';
74
- }
75
- /**
76
- * Utility function for sharing common `RateLimiterOptions` options between different `RateLimiter` instances.
77
- */
78
- declare function rateLimiterOptions<TFn extends AnyFunction = AnyFunction, TOptions extends Partial<RateLimiterOptions<TFn>> = Partial<RateLimiterOptions<TFn>>>(options: TOptions): TOptions;
79
- /**
80
- * A class that creates a rate-limited function.
81
- *
82
- * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
83
- * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
84
- * all executions happen immediately, followed by a complete block.
85
- * This synchronous version is lighter weight and often all you need - upgrade to AsyncRateLimiter when you need promises, retry support, abort capabilities, or advanced error handling.
86
- *
87
- * The rate limiter supports two types of windows:
88
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
89
- * towards the limit, and the window resets completely after the period.
90
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
91
- * consistent rate of execution over time.
92
- *
93
- * For smoother execution patterns, consider using:
94
- * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
95
- * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
96
- *
97
- * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
98
- * smoothing out frequent events, throttling or debouncing usually provide better user experience.
99
- *
100
- * State Management:
101
- * - Uses TanStack Store for reactive state management
102
- * - Use `initialState` to provide initial state values when creating the rate limiter
103
- * - Use `onExecute` callback to react to function execution and implement custom logic
104
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
105
- * - The state includes execution count, execution times, and rejection count
106
- * - State can be accessed via `rateLimiter.store.state` when using the class directly
107
- * - When using framework adapters (React/Solid), state is accessed from `rateLimiter.state`
108
- *
109
- * @example
110
- * ```ts
111
- * const rateLimiter = new RateLimiter(
112
- * (id: string) => api.getData(id),
113
- * {
114
- * limit: 5,
115
- * window: 1000,
116
- * windowType: 'sliding',
117
- * }
118
- * );
119
- *
120
- * // Will execute immediately until limit reached, then block
121
- * rateLimiter.maybeExecute('123');
122
- * ```
123
- */
124
- declare class RateLimiter<TFn extends AnyFunction> {
125
- #private;
126
- fn: TFn;
127
- readonly store: Store<Readonly<RateLimiterState>>;
128
- key: string | undefined;
129
- options: RateLimiterOptions<TFn>;
130
- constructor(fn: TFn, initialOptions: RateLimiterOptions<TFn>);
131
- /**
132
- * Updates the rate limiter options
133
- */
134
- setOptions: (newOptions: Partial<RateLimiterOptions<TFn>>) => void;
135
- /**
136
- * Attempts to execute the rate-limited function if within the configured limits.
137
- * Will reject execution if the number of calls in the current window exceeds the limit.
138
- *
139
- * @example
140
- * ```ts
141
- * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });
142
- *
143
- * // First 5 calls will return true
144
- * rateLimiter.maybeExecute('arg1', 'arg2'); // true
145
- *
146
- * // Additional calls within the window will return false
147
- * rateLimiter.maybeExecute('arg1', 'arg2'); // false
148
- * ```
149
- */
150
- maybeExecute: (...args: Parameters<TFn>) => boolean;
151
- /**
152
- * Returns the number of remaining executions allowed in the current window
153
- */
154
- getRemainingInWindow: () => number;
155
- /**
156
- * Returns the number of milliseconds until the next execution will be possible
157
- */
158
- getMsUntilNextWindow: () => number;
159
- /**
160
- * Resets the rate limiter state
161
- */
162
- reset: () => void;
163
- }
164
- /**
165
- * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
166
- *
167
- * This synchronous version is lighter weight and often all you need - upgrade to asyncRateLimit when you need promises, retry support, abort capabilities, or advanced error handling.
168
- *
169
- * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
170
- * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
171
- * - A throttler ensures even spacing between executions, which can be better for consistent performance
172
- * - A debouncer collapses multiple calls into one, which is better for handling bursts of events
173
- *
174
- * The rate limiter supports two types of windows:
175
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
176
- * towards the limit, and the window resets completely after the period.
177
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
178
- * consistent rate of execution over time.
179
- *
180
- * State Management:
181
- * - Uses TanStack Store for reactive state management
182
- * - Use `initialState` to provide initial state values when creating the rate limiter
183
- * - Use `onExecute` callback to react to function execution and implement custom logic
184
- * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
185
- * - The state includes execution count, execution times, and rejection count
186
- * - State can be accessed via the underlying RateLimiter instance's `store.state` property
187
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
188
- *
189
- * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
190
- * need to enforce a hard limit on the number of executions within a time period.
191
- *
192
- * @example
193
- * ```ts
194
- * // Rate limit to 5 calls per minute with a sliding window
195
- * const rateLimited = rateLimit(makeApiCall, {
196
- * limit: 5,
197
- * window: 60000,
198
- * windowType: 'sliding',
199
- * onReject: (rateLimiter) => {
200
- * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
201
- * }
202
- * });
203
- *
204
- * // First 5 calls will execute immediately
205
- * // Additional calls will be rejected until the minute window resets
206
- * rateLimited();
207
- *
208
- * // For more even execution, consider using throttle instead:
209
- * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
210
- * ```
211
- */
212
- declare function rateLimit<TFn extends AnyFunction>(fn: TFn, initialOptions: RateLimiterOptions<TFn>): (...args: Parameters<TFn>) => boolean;
213
- //#endregion
214
- export { RateLimiter, RateLimiterOptions, RateLimiterState, rateLimit, rateLimiterOptions };
215
- //# sourceMappingURL=rate-limiter.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rate-limiter.js","names":["#getLimit","#getEnabled","#setState","#cleanupOldExecutions","#getExecutionTimesInWindow","#execute","#setCleanupTimeout","#getWindow","#timeoutIds","#clearTimeout","#clearTimeouts"],"sources":["../src/rate-limiter.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AnyFunction } from './types'\n\nexport interface RateLimiterState {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Array of timestamps when executions occurred for rate limiting calculations\n */\n executionTimes: Array<number>\n /**\n * Whether the rate limiter has exceeded the limit\n */\n isExceeded: boolean\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Number of function executions that have been rejected due to rate limiting\n */\n rejectionCount: number\n /**\n * Current execution status - 'disabled' when not active, 'executing' when executing, 'idle' when not executing, 'exceeded' when rate limit is exceeded\n */\n status: 'disabled' | 'exceeded' | 'idle'\n}\n\nfunction getDefaultRateLimiterState(): RateLimiterState {\n return {\n executionCount: 0,\n executionTimes: [],\n isExceeded: false,\n rejectionCount: 0,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions<TFn extends AnyFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean)\n /**\n * Initial state for the rate limiter\n */\n initialState?: Partial<RateLimiterState>\n /**\n * Optional key to identify this rate limiter instance.\n * If provided, the rate limiter will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n limit: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, rateLimiter: RateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Time window in milliseconds within which the limit applies.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n window: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\n/**\n * Utility function for sharing common `RateLimiterOptions` options between different `RateLimiter` instances.\n */\nexport function rateLimiterOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<RateLimiterOptions<TFn>> = Partial<\n RateLimiterOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<RateLimiterOptions<any>>,\n 'initialState' | 'onExecute' | 'onReject' | 'key'\n> = {\n enabled: true,\n limit: 1,\n window: 0,\n windowType: 'fixed',\n}\n\n/**\n * A class that creates a 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 * This synchronous version is lighter weight and often all you need - upgrade to AsyncRateLimiter when you need promises, retry support, abort capabilities, or advanced error handling.\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 * 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 * - Use `onExecute` callback to react to function execution and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution count, execution times, and rejection count\n * - State can be accessed via `rateLimiter.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `rateLimiter.state`\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(\n * (id: string) => api.getData(id),\n * {\n * limit: 5,\n * window: 1000,\n * windowType: 'sliding',\n * }\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<TFn extends AnyFunction> {\n readonly store: Store<Readonly<RateLimiterState>> =\n new Store<RateLimiterState>(getDefaultRateLimiterState())\n key: string | undefined\n options: RateLimiterOptions<TFn>\n #timeoutIds: Set<ReturnType<typeof setTimeout>> = new Set()\n\n constructor(\n public fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n for (const executionTime of this.#getExecutionTimesInWindow()) {\n this.#setCleanupTimeout(executionTime)\n }\n\n if (this.key) {\n pacerEventClient.on('d-RateLimiter', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state as Partial<RateLimiterState>)\n this.setOptions(\n event.payload.options as Partial<RateLimiterOptions<TFn>>,\n )\n })\n }\n }\n\n /**\n * Updates the rate limiter options\n */\n setOptions = (newOptions: Partial<RateLimiterOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<RateLimiterState>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const isExceeded = combinedState.executionTimes.length >= this.#getLimit()\n const status = !this.#getEnabled()\n ? 'disabled'\n : isExceeded\n ? 'exceeded'\n : 'idle'\n return {\n ...combinedState,\n isExceeded,\n status,\n }\n })\n emitChange('RateLimiter', this)\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 *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute = (...args: Parameters<TFn>): boolean => {\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n this.#cleanupOldExecutions()\n\n const relevantExecutionTimes = this.#getExecutionTimesInWindow()\n\n if (relevantExecutionTimes.length < this.#getLimit()) {\n this.#execute(...args)\n return true\n }\n\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(this)\n return false\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n const now = Date.now()\n this.fn(...args) // EXECUTE!\n this.store.state.executionTimes.push(now) // mutate state directly for performance\n\n this.#setCleanupTimeout(now)\n\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n })\n this.options.onExecute?.(args, this)\n }\n\n #getExecutionTimesInWindow = (): Array<number> => {\n if (this.options.windowType === 'sliding') {\n // For sliding window, return all executions within the current window\n return this.store.state.executionTimes.filter(\n (time) => time > Date.now() - this.#getWindow(),\n )\n } else {\n // For fixed window, return all executions in the current window\n // The window starts from the oldest execution time\n if (this.store.state.executionTimes.length === 0) {\n return []\n }\n const oldestExecution = Math.min(...this.store.state.executionTimes)\n const windowStart = oldestExecution\n const windowEnd = windowStart + this.#getWindow()\n const now = Date.now()\n\n // If the window has expired, return empty array\n if (now > windowEnd) {\n return []\n }\n\n // Otherwise, return all executions in the current window\n return this.store.state.executionTimes.filter(\n (time) => time >= windowStart && time <= windowEnd,\n )\n }\n }\n\n #setCleanupTimeout = (executionTime: number): void => {\n if (\n this.options.windowType === 'sliding' ||\n this.#timeoutIds.size === 0 // new fixed window\n ) {\n const now = Date.now()\n const timeUntilExpiration = executionTime - now + this.#getWindow() + 1\n const timeoutId = setTimeout(() => {\n this.#cleanupOldExecutions()\n this.#clearTimeout(timeoutId)\n }, timeUntilExpiration)\n this.#timeoutIds.add(timeoutId)\n }\n }\n\n #clearTimeout = (timeoutId: ReturnType<typeof setTimeout>): void => {\n clearTimeout(timeoutId)\n this.#timeoutIds.delete(timeoutId)\n }\n\n #clearTimeouts = (): void => {\n this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))\n this.#timeoutIds.clear()\n }\n\n #cleanupOldExecutions = (): void => {\n this.#setState({\n executionTimes: this.#getExecutionTimesInWindow(),\n })\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow = (): number => {\n const relevantExecutionTimes = this.#getExecutionTimesInWindow()\n return Math.max(0, this.#getLimit() - relevantExecutionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\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(getDefaultRateLimiterState())\n this.#clearTimeouts()\n }\n}\n\n/**\n * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncRateLimit when you need promises, retry support, abort capabilities, or advanced error handling.\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 * 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 * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution count, execution times, and rejection count\n * - State can be accessed via the underlying RateLimiter 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 * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\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 * 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 rateLimit<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute\n}\n"],"mappings":";;;;;AAgCA,SAAS,6BAA+C;CACtD,OAAO;EACL,gBAAgB;EAChB,gBAAgB,EAAE;EAClB,YAAY;EACZ,gBAAgB;EAChB,QAAQ;EACR,mBAAmB;EACpB;;;;;AAmDH,SAAgB,mBAKd,SAA6B;CAC7B,OAAO;;AAGT,MAAM,iBAGF;CACF,SAAS;CACT,OAAO;CACP,QAAQ;CACR,YAAY;CACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CD,IAAa,cAAb,MAAkD;CAKhD;CAEA,YACE,AAAO,IACP,gBACA;EAFO;eANP,IAAI,MAAwB,4BAA4B,CAAC;qCAGT,IAAI,KAAK;qBA8B7C,eAAuD;GACnE,KAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;IAAY;;oBAGtC,aAA8C;GACzD,KAAK,MAAM,UAAU,UAAU;IAC7B,MAAM,gBAAgB;KACpB,GAAG;KACH,GAAG;KACJ;IACD,MAAM,aAAa,cAAc,eAAe,UAAU,KAAKA,WAAW;IAC1E,MAAM,SAAS,CAAC,KAAKC,aAAa,GAC9B,aACA,aACE,aACA;IACN,OAAO;KACL,GAAG;KACH;KACA;KACD;KACD;GACF,WAAW,eAAe,KAAK;;2BAMJ;GAC3B,OAAO,CAAC,CAAC,qBAAqB,KAAK,QAAQ,SAAS,KAAK;;yBAMjC;GACxB,OAAO,qBAAqB,KAAK,QAAQ,OAAO,KAAK;;0BAM5B;GACzB,OAAO,qBAAqB,KAAK,QAAQ,QAAQ,KAAK;;uBAkBxC,GAAG,SAAmC;GACpD,KAAKC,UAAU,EACb,mBAAmB,KAAK,M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