@tanstack/pacer 0.20.1 → 0.21.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 (45) hide show
  1. package/dist/async-batcher.cjs +72 -67
  2. package/dist/async-batcher.cjs.map +1 -1
  3. package/dist/async-batcher.js +72 -67
  4. package/dist/async-batcher.js.map +1 -1
  5. package/dist/async-debouncer.cjs +83 -74
  6. package/dist/async-debouncer.cjs.map +1 -1
  7. package/dist/async-debouncer.js +83 -74
  8. package/dist/async-debouncer.js.map +1 -1
  9. package/dist/async-queuer.cjs +102 -94
  10. package/dist/async-queuer.cjs.map +1 -1
  11. package/dist/async-queuer.js +102 -94
  12. package/dist/async-queuer.js.map +1 -1
  13. package/dist/async-rate-limiter.cjs +104 -93
  14. package/dist/async-rate-limiter.cjs.map +1 -1
  15. package/dist/async-rate-limiter.js +104 -93
  16. package/dist/async-rate-limiter.js.map +1 -1
  17. package/dist/async-retryer.cjs +67 -59
  18. package/dist/async-retryer.cjs.map +1 -1
  19. package/dist/async-retryer.js +67 -59
  20. package/dist/async-retryer.js.map +1 -1
  21. package/dist/async-throttler.cjs +81 -73
  22. package/dist/async-throttler.cjs.map +1 -1
  23. package/dist/async-throttler.js +81 -73
  24. package/dist/async-throttler.js.map +1 -1
  25. package/dist/batcher.cjs +45 -40
  26. package/dist/batcher.cjs.map +1 -1
  27. package/dist/batcher.js +45 -40
  28. package/dist/batcher.js.map +1 -1
  29. package/dist/debouncer.cjs +41 -36
  30. package/dist/debouncer.cjs.map +1 -1
  31. package/dist/debouncer.js +41 -36
  32. package/dist/debouncer.js.map +1 -1
  33. package/dist/queuer.cjs +92 -85
  34. package/dist/queuer.cjs.map +1 -1
  35. package/dist/queuer.js +92 -85
  36. package/dist/queuer.js.map +1 -1
  37. package/dist/rate-limiter.cjs +77 -66
  38. package/dist/rate-limiter.cjs.map +1 -1
  39. package/dist/rate-limiter.js +77 -66
  40. package/dist/rate-limiter.js.map +1 -1
  41. package/dist/throttler.cjs +49 -44
  42. package/dist/throttler.cjs.map +1 -1
  43. package/dist/throttler.js +49 -44
  44. package/dist/throttler.js.map +1 -1
  45. package/package.json +2 -2
@@ -72,16 +72,42 @@ const defaultOptions = {
72
72
  * ```
73
73
  */
74
74
  var RateLimiter = class {
75
- #timeoutIds = /* @__PURE__ */ new Set();
75
+ #timeoutIds;
76
76
  constructor(fn, initialOptions) {
77
77
  this.fn = fn;
78
78
  this.store = new _tanstack_store.Store(getDefaultRateLimiterState());
79
+ this.#timeoutIds = /* @__PURE__ */ new Set();
79
80
  this.setOptions = (newOptions) => {
80
81
  this.options = {
81
82
  ...this.options,
82
83
  ...newOptions
83
84
  };
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
+ };
85
111
  this.maybeExecute = (...args) => {
86
112
  this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
87
113
  this.#cleanupOldExecutions();
@@ -93,6 +119,46 @@ var RateLimiter = class {
93
119
  this.options.onReject?.(this);
94
120
  return false;
95
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
+ };
96
162
  this.getRemainingInWindow = () => {
97
163
  const relevantExecutionTimes = this.#getExecutionTimesInWindow();
98
164
  return Math.max(0, this.#getLimit() - relevantExecutionTimes.length);
@@ -118,80 +184,25 @@ var RateLimiter = class {
118
184
  this.setOptions(event.payload.options);
119
185
  });
120
186
  }
121
- #setState = (newState) => {
122
- this.store.setState((state) => {
123
- const combinedState = {
124
- ...state,
125
- ...newState
126
- };
127
- const isExceeded = combinedState.executionTimes.length >= this.#getLimit();
128
- const status = !this.#getEnabled() ? "disabled" : isExceeded ? "exceeded" : "idle";
129
- return {
130
- ...combinedState,
131
- isExceeded,
132
- status
133
- };
134
- });
135
- require_event_client.emitChange("RateLimiter", this);
136
- };
187
+ #setState;
137
188
  /**
138
189
  * Returns the current enabled state of the rate limiter
139
190
  */
140
- #getEnabled = () => {
141
- return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
142
- };
191
+ #getEnabled;
143
192
  /**
144
193
  * Returns the current limit of executions allowed within the time window
145
194
  */
146
- #getLimit = () => {
147
- return require_utils.parseFunctionOrValue(this.options.limit, this);
148
- };
195
+ #getLimit;
149
196
  /**
150
197
  * Returns the current time window in milliseconds
151
198
  */
152
- #getWindow = () => {
153
- return require_utils.parseFunctionOrValue(this.options.window, this);
154
- };
155
- #execute = (...args) => {
156
- if (!this.#getEnabled()) return;
157
- const now = Date.now();
158
- this.fn(...args);
159
- this.store.state.executionTimes.push(now);
160
- this.#setCleanupTimeout(now);
161
- this.#setState({ executionCount: this.store.state.executionCount + 1 });
162
- this.options.onExecute?.(args, this);
163
- };
164
- #getExecutionTimesInWindow = () => {
165
- if (this.options.windowType === "sliding") return this.store.state.executionTimes.filter((time) => time > Date.now() - this.#getWindow());
166
- else {
167
- if (this.store.state.executionTimes.length === 0) return [];
168
- const windowStart = Math.min(...this.store.state.executionTimes);
169
- const windowEnd = windowStart + this.#getWindow();
170
- if (Date.now() > windowEnd) return [];
171
- return this.store.state.executionTimes.filter((time) => time >= windowStart && time <= windowEnd);
172
- }
173
- };
174
- #setCleanupTimeout = (executionTime) => {
175
- if (this.options.windowType === "sliding" || this.#timeoutIds.size === 0) {
176
- const timeUntilExpiration = executionTime - Date.now() + this.#getWindow() + 1;
177
- const timeoutId = setTimeout(() => {
178
- this.#cleanupOldExecutions();
179
- this.#clearTimeout(timeoutId);
180
- }, timeUntilExpiration);
181
- this.#timeoutIds.add(timeoutId);
182
- }
183
- };
184
- #clearTimeout = (timeoutId) => {
185
- clearTimeout(timeoutId);
186
- this.#timeoutIds.delete(timeoutId);
187
- };
188
- #clearTimeouts = () => {
189
- this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId));
190
- this.#timeoutIds.clear();
191
- };
192
- #cleanupOldExecutions = () => {
193
- this.#setState({ executionTimes: this.#getExecutionTimesInWindow() });
194
- };
199
+ #getWindow;
200
+ #execute;
201
+ #getExecutionTimesInWindow;
202
+ #setCleanupTimeout;
203
+ #clearTimeout;
204
+ #clearTimeouts;
205
+ #cleanupOldExecutions;
195
206
  };
196
207
  /**
197
208
  * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
@@ -1 +1 @@
1
- {"version":3,"file":"rate-limiter.cjs","names":["Store","#setState","#cleanupOldExecutions","#getExecutionTimesInWindow","#getLimit","#execute","#getWindow","#clearTimeouts","#setCleanupTimeout","#getEnabled","parseFunctionOrValue","#timeoutIds","#clearTimeout"],"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;AACtD,QAAO;EACL,gBAAgB;EAChB,gBAAgB,EAAE;EAClB,YAAY;EACZ,gBAAgB;EAChB,QAAQ;EACR,mBAAmB;EACpB;;;;;AAmDH,SAAgB,mBAKd,SAA6B;AAC7B,QAAO;;AAGT,MAAM,iBAGF;CACF,SAAS;CACT,OAAO;CACP,QAAQ;CACR,YAAY;CACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CD,IAAa,cAAb,MAAkD;CAKhD,8BAAkD,IAAI,KAAK;CAE3D,YACE,AAAO,IACP,gBACA;EAFO;eANP,IAAIA,sBAAwB,4BAA4B,CAAC;qBAiC7C,eAAuD;AACnE,QAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;IAAY;;uBA4DnC,GAAG,SAAmC;AACpD,SAAKC,SAAU,EACb,mBAAmB,KAAK,MAAM,MAAM,oBAAoB,GACzD,CAAC;AAEF,SAAKC,sBAAuB;AAI5B,OAF+B,MAAKC,2BAA4B,CAErC,SAAS,MAAKC,UAAW,EAAE;AACpD,UAAKC,QAAS,GAAG,KAAK;AACtB,WAAO;;AAGT,SAAKJ,SAAU,EACb,gBAAgB,KAAK,MAAM,MAAM,iBAAiB,GACnD,CAAC;AACF,QAAK,QAAQ,WAAW,KAAK;AAC7B,UAAO;;oCAgF4B;GACnC,MAAM,yBAAyB,MAAKE,2BAA4B;AAChE,UAAO,KAAK,IAAI,GAAG,MAAKC,UAAW,GAAG,uBAAuB,OAAO;;oCAMjC;AACnC,OAAI,KAAK,sBAAsB,GAAG,EAChC,QAAO;AAGT,WADwB,KAAK,MAAM,MAAM,eAAe,MAAM,YACrC,MAAKE,WAAY,GAAG,KAAK,KAAK;;qBAMrC;AAClB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AGtC,mCAAkD;AAChD,MAAI,KAAK,QAAQ,eAAe,UAE9B,QAAO,KAAK,MAAM,MAAM,eAAe,QACpC,SAAS,OAAO,KAAK,KAAK,GAAG,MAAKK,WAAY,CAChD;OACI;AAGL,OAAI,KAAK,MAAM,MAAM,eAAe,WAAW,EAC7C,QAAO,EAAE;GAGX,MAAM,cADkB,KAAK,IAAI,GAAG,KAAK,MAAM,MAAM,eAAe;GAEpE,MAAM,YAAY,cAAc,MAAKA,WAAY;AAIjD,OAHY,KAAK,KAAK,GAGZ,UACR,QAAO,EAAE;AAIX,UAAO,KAAK,MAAM,MAAM,eAAe,QACpC,SAAS,QAAQ,eAAe,QAAQ,UAC1C;;;CAIL,sBAAsB,kBAAgC;AACpD,MACE,KAAK,QAAQ,eAAe,aAC5B,MAAKK,WAAY,SAAS,GAC1B;GAEA,MAAM,sBAAsB,gBADhB,KAAK,KAAK,GAC4B,MAAKL,WAAY,GAAG;GACtE,MAAM,YAAY,iBAAiB;AACjC,UAAKJ,sBAAuB;AAC5B,UAAKU,aAAc,UAAU;MAC5B,oBAAoB;AACvB,SAAKD,WAAY,IAAI,UAAU;;;CAInC,iBAAiB,cAAmD;AAClE,eAAa,UAAU;AACvB,QAAKA,WAAY,OAAO,UAAU;;CAGpC,uBAA6B;AAC3B,QAAKA,WAAY,SAAS,cAAc,aAAa,UAAU,CAAC;AAChE,QAAKA,WAAY,OAAO;;CAG1B,8BAAoC;AAClC,QAAKV,SAAU,EACb,gBAAgB,MAAKE,2BAA4B,EAClD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+EN,SAAgB,UACd,IACA,gBACA;AAEA,QADoB,IAAI,YAAY,IAAI,eAAe,CACpC"}
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;AACtD,QAAO;EACL,gBAAgB;EAChB,gBAAgB,EAAE;EAClB,YAAY;EACZ,gBAAgB;EAChB,QAAQ;EACR,mBAAmB;EACpB;;;;;AAmDH,SAAgB,mBAKd,SAA6B;AAC7B,QAAO;;AAGT,MAAM,iBAGF;CACF,SAAS;CACT,OAAO;CACP,QAAQ;CACR,YAAY;CACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CD,IAAa,cAAb,MA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;AAC5C,SAAKQ,eAAgB;;AA5MrB,OAAK,MAAM,eAAe;AAC1B,OAAK,UAAU;GACb,GAAG;GACH,GAAG;GACJ;AACD,QAAKR,SAAU,KAAK,QAAQ,gBAAgB,EAAE,CAAC;AAC/C,OAAK,MAAM,iBAAiB,MAAKE,2BAA4B,CAC3D,OAAKE,kBAAmB,cAAc;AAGxC,MAAI,KAAK,IACP,uCAAiB,GAAG,kBAAkB,UAAU;AAC9C,OAAI,MAAM,QAAQ,QAAQ,KAAK,IAAK;AACpC,SAAKJ,SAAU,MAAM,QAAQ,MAAM,MAAmC;AACtE,QAAK,WACH,MAAM,QAAQ,QACf;IACD;;CAWN;;;;CAwBA;;;;CAOA;;;;CAOA;CAwCA;CAcA;CA6BA;CAeA;CAKA;CAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkFF,SAAgB,UACd,IACA,gBACA;AAEA,QADoB,IAAI,YAAY,IAAI,eAAe,CACpC"}
@@ -71,16 +71,42 @@ const defaultOptions = {
71
71
  * ```
72
72
  */
73
73
  var RateLimiter = class {
74
- #timeoutIds = /* @__PURE__ */ new Set();
74
+ #timeoutIds;
75
75
  constructor(fn, initialOptions) {
76
76
  this.fn = fn;
77
77
  this.store = new Store(getDefaultRateLimiterState());
78
+ this.#timeoutIds = /* @__PURE__ */ new Set();
78
79
  this.setOptions = (newOptions) => {
79
80
  this.options = {
80
81
  ...this.options,
81
82
  ...newOptions
82
83
  };
83
84
  };
85
+ this.#setState = (newState) => {
86
+ this.store.setState((state) => {
87
+ const combinedState = {
88
+ ...state,
89
+ ...newState
90
+ };
91
+ const isExceeded = combinedState.executionTimes.length >= this.#getLimit();
92
+ const status = !this.#getEnabled() ? "disabled" : isExceeded ? "exceeded" : "idle";
93
+ return {
94
+ ...combinedState,
95
+ isExceeded,
96
+ status
97
+ };
98
+ });
99
+ emitChange("RateLimiter", this);
100
+ };
101
+ this.#getEnabled = () => {
102
+ return !!parseFunctionOrValue(this.options.enabled, this);
103
+ };
104
+ this.#getLimit = () => {
105
+ return parseFunctionOrValue(this.options.limit, this);
106
+ };
107
+ this.#getWindow = () => {
108
+ return parseFunctionOrValue(this.options.window, this);
109
+ };
84
110
  this.maybeExecute = (...args) => {
85
111
  this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
86
112
  this.#cleanupOldExecutions();
@@ -92,6 +118,46 @@ var RateLimiter = class {
92
118
  this.options.onReject?.(this);
93
119
  return false;
94
120
  };
121
+ this.#execute = (...args) => {
122
+ if (!this.#getEnabled()) return;
123
+ const now = Date.now();
124
+ this.fn(...args);
125
+ this.store.state.executionTimes.push(now);
126
+ this.#setCleanupTimeout(now);
127
+ this.#setState({ executionCount: this.store.state.executionCount + 1 });
128
+ this.options.onExecute?.(args, this);
129
+ };
130
+ this.#getExecutionTimesInWindow = () => {
131
+ if (this.options.windowType === "sliding") return this.store.state.executionTimes.filter((time) => time > Date.now() - this.#getWindow());
132
+ else {
133
+ if (this.store.state.executionTimes.length === 0) return [];
134
+ const windowStart = Math.min(...this.store.state.executionTimes);
135
+ const windowEnd = windowStart + this.#getWindow();
136
+ if (Date.now() > windowEnd) return [];
137
+ return this.store.state.executionTimes.filter((time) => time >= windowStart && time <= windowEnd);
138
+ }
139
+ };
140
+ this.#setCleanupTimeout = (executionTime) => {
141
+ if (this.options.windowType === "sliding" || this.#timeoutIds.size === 0) {
142
+ const timeUntilExpiration = executionTime - Date.now() + this.#getWindow() + 1;
143
+ const timeoutId = setTimeout(() => {
144
+ this.#cleanupOldExecutions();
145
+ this.#clearTimeout(timeoutId);
146
+ }, timeUntilExpiration);
147
+ this.#timeoutIds.add(timeoutId);
148
+ }
149
+ };
150
+ this.#clearTimeout = (timeoutId) => {
151
+ clearTimeout(timeoutId);
152
+ this.#timeoutIds.delete(timeoutId);
153
+ };
154
+ this.#clearTimeouts = () => {
155
+ this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId));
156
+ this.#timeoutIds.clear();
157
+ };
158
+ this.#cleanupOldExecutions = () => {
159
+ this.#setState({ executionTimes: this.#getExecutionTimesInWindow() });
160
+ };
95
161
  this.getRemainingInWindow = () => {
96
162
  const relevantExecutionTimes = this.#getExecutionTimesInWindow();
97
163
  return Math.max(0, this.#getLimit() - relevantExecutionTimes.length);
@@ -117,80 +183,25 @@ var RateLimiter = class {
117
183
  this.setOptions(event.payload.options);
118
184
  });
119
185
  }
120
- #setState = (newState) => {
121
- this.store.setState((state) => {
122
- const combinedState = {
123
- ...state,
124
- ...newState
125
- };
126
- const isExceeded = combinedState.executionTimes.length >= this.#getLimit();
127
- const status = !this.#getEnabled() ? "disabled" : isExceeded ? "exceeded" : "idle";
128
- return {
129
- ...combinedState,
130
- isExceeded,
131
- status
132
- };
133
- });
134
- emitChange("RateLimiter", this);
135
- };
186
+ #setState;
136
187
  /**
137
188
  * Returns the current enabled state of the rate limiter
138
189
  */
139
- #getEnabled = () => {
140
- return !!parseFunctionOrValue(this.options.enabled, this);
141
- };
190
+ #getEnabled;
142
191
  /**
143
192
  * Returns the current limit of executions allowed within the time window
144
193
  */
145
- #getLimit = () => {
146
- return parseFunctionOrValue(this.options.limit, this);
147
- };
194
+ #getLimit;
148
195
  /**
149
196
  * Returns the current time window in milliseconds
150
197
  */
151
- #getWindow = () => {
152
- return parseFunctionOrValue(this.options.window, this);
153
- };
154
- #execute = (...args) => {
155
- if (!this.#getEnabled()) return;
156
- const now = Date.now();
157
- this.fn(...args);
158
- this.store.state.executionTimes.push(now);
159
- this.#setCleanupTimeout(now);
160
- this.#setState({ executionCount: this.store.state.executionCount + 1 });
161
- this.options.onExecute?.(args, this);
162
- };
163
- #getExecutionTimesInWindow = () => {
164
- if (this.options.windowType === "sliding") return this.store.state.executionTimes.filter((time) => time > Date.now() - this.#getWindow());
165
- else {
166
- if (this.store.state.executionTimes.length === 0) return [];
167
- const windowStart = Math.min(...this.store.state.executionTimes);
168
- const windowEnd = windowStart + this.#getWindow();
169
- if (Date.now() > windowEnd) return [];
170
- return this.store.state.executionTimes.filter((time) => time >= windowStart && time <= windowEnd);
171
- }
172
- };
173
- #setCleanupTimeout = (executionTime) => {
174
- if (this.options.windowType === "sliding" || this.#timeoutIds.size === 0) {
175
- const timeUntilExpiration = executionTime - Date.now() + this.#getWindow() + 1;
176
- const timeoutId = setTimeout(() => {
177
- this.#cleanupOldExecutions();
178
- this.#clearTimeout(timeoutId);
179
- }, timeUntilExpiration);
180
- this.#timeoutIds.add(timeoutId);
181
- }
182
- };
183
- #clearTimeout = (timeoutId) => {
184
- clearTimeout(timeoutId);
185
- this.#timeoutIds.delete(timeoutId);
186
- };
187
- #clearTimeouts = () => {
188
- this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId));
189
- this.#timeoutIds.clear();
190
- };
191
- #cleanupOldExecutions = () => {
192
- this.#setState({ executionTimes: this.#getExecutionTimesInWindow() });
193
- };
198
+ #getWindow;
199
+ #execute;
200
+ #getExecutionTimesInWindow;
201
+ #setCleanupTimeout;
202
+ #clearTimeout;
203
+ #clearTimeouts;
204
+ #cleanupOldExecutions;
194
205
  };
195
206
  /**
196
207
  * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
@@ -1 +1 @@
1
- {"version":3,"file":"rate-limiter.js","names":["#setState","#cleanupOldExecutions","#getExecutionTimesInWindow","#getLimit","#execute","#getWindow","#clearTimeouts","#setCleanupTimeout","#getEnabled","#timeoutIds","#clearTimeout"],"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;AACtD,QAAO;EACL,gBAAgB;EAChB,gBAAgB,EAAE;EAClB,YAAY;EACZ,gBAAgB;EAChB,QAAQ;EACR,mBAAmB;EACpB;;;;;AAmDH,SAAgB,mBAKd,SAA6B;AAC7B,QAAO;;AAGT,MAAM,iBAGF;CACF,SAAS;CACT,OAAO;CACP,QAAQ;CACR,YAAY;CACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CD,IAAa,cAAb,MAAkD;CAKhD,8BAAkD,IAAI,KAAK;CAE3D,YACE,AAAO,IACP,gBACA;EAFO;eANP,IAAI,MAAwB,4BAA4B,CAAC;qBAiC7C,eAAuD;AACnE,QAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;IAAY;;uBA4DnC,GAAG,SAAmC;AACpD,SAAKA,SAAU,EACb,mBAAmB,KAAK,MAAM,MAAM,oBAAoB,GACzD,CAAC;AAEF,SAAKC,sBAAuB;AAI5B,OAF+B,MAAKC,2BAA4B,CAErC,SAAS,MAAKC,UAAW,EAAE;AAC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AAS,cAAc,aAAa,UAAU,CAAC;AAChE,QAAKA,WAAY,OAAO;;CAG1B,8BAAoC;AAClC,QAAKT,SAAU,EACb,gBAAgB,MAAKE,2BAA4B,EAClD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+EN,SAAgB,UACd,IACA,gBACA;AAEA,QADoB,IAAI,YAAY,IAAI,eAAe,CACpC"}
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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U,CAAC;AAChE,SAAKA,WAAY,OAAO;;qCAGU;AAClC,SAAKN,SAAU,EACb,gBAAgB,MAAKE,2BAA4B,EAClD,CAAC;;oCAMiC;GACnC,MAAM,yBAAyB,MAAKA,2BAA4B;AAChE,UAAO,KAAK,IAAI,GAAG,MAAKJ,UAAW,GAAG,uBAAuB,OAAO;;oCAMjC;AACnC,OAAI,KAAK,sBAAsB,GAAG,EAChC,QAAO;AAGT,WADwB,KAAK,MAAM,MAAM,eAAe,MAAM,YACrC,MAAKO,WAAY,GAAG,KAAK,KAAK;;qBAMrC;AAClB,SAAKL,SAAU,4BAA4B,CAAC;AAC5C,SAAKQ,eAAgB;;AA5MrB,OAAK,MAAM,eAAe;AAC1B,OAAK,UAAU;GACb,GAAG;GACH,GAAG;GACJ;AACD,QAAKR,SAAU,KAAK,QAAQ,gBAAgB,EAAE,CAAC;AAC/C,OAAK,MAAM,iBAAiB,MAAKE,2BAA4B,CAC3D,OAAKE,kBAAmB,cAAc;AAGxC,MAAI,KAAK,IACP,kBAAiB,GAAG,kBAAkB,UAAU;AAC9C,OAAI,MAAM,QAAQ,QAAQ,KAAK,IAAK;AACpC,SAAKJ,SAAU,MAAM,QAAQ,MAAM,MAAmC;AACtE,QAAK,WACH,MAAM,QAAQ,QACf;IACD;;CAWN;;;;CAwBA;;;;CAOA;;;;CAOA;CAwCA;CAcA;CA6BA;CAeA;CAKA;CAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkFF,SAAgB,UACd,IACA,gBACA;AAEA,QADoB,IAAI,YAAY,IAAI,eAAe,CACpC"}
@@ -75,6 +75,26 @@ var Throttler = class {
75
75
  };
76
76
  if (!this.#getEnabled()) this.cancel();
77
77
  };
78
+ this.#setState = (newState) => {
79
+ this.store.setState((state) => {
80
+ const combinedState = {
81
+ ...state,
82
+ ...newState
83
+ };
84
+ const { isPending } = combinedState;
85
+ return {
86
+ ...combinedState,
87
+ status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
88
+ };
89
+ });
90
+ require_event_client.emitChange("Throttler", this);
91
+ };
92
+ this.#getEnabled = () => {
93
+ return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
94
+ };
95
+ this.#getWait = () => {
96
+ return require_utils.parseFunctionOrValue(this.options.wait, this);
97
+ };
78
98
  this.maybeExecute = (...args) => {
79
99
  this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
80
100
  const now = Date.now();
@@ -93,9 +113,33 @@ var Throttler = class {
93
113
  }
94
114
  }
95
115
  };
116
+ this.#execute = (...args) => {
117
+ if (!this.#getEnabled()) return;
118
+ this.fn(...args);
119
+ const lastExecutionTime = Date.now();
120
+ const nextExecutionTime = lastExecutionTime + this.#getWait();
121
+ this.#clearTimeout();
122
+ this.#setState({
123
+ executionCount: this.store.state.executionCount + 1,
124
+ lastExecutionTime,
125
+ nextExecutionTime,
126
+ isPending: false,
127
+ lastArgs: void 0
128
+ });
129
+ this.options.onExecute?.(args, this);
130
+ setTimeout(() => {
131
+ if (!this.store.state.isPending) this.#setState({ nextExecutionTime: void 0 });
132
+ }, this.#getWait());
133
+ };
96
134
  this.flush = () => {
97
135
  if (this.store.state.isPending && this.store.state.lastArgs) this.#execute(...this.store.state.lastArgs);
98
136
  };
137
+ this.#clearTimeout = () => {
138
+ if (this.#timeoutId) {
139
+ clearTimeout(this.#timeoutId);
140
+ this.#timeoutId = void 0;
141
+ }
142
+ };
99
143
  this.cancel = () => {
100
144
  this.#clearTimeout();
101
145
  this.#setState({
@@ -118,50 +162,11 @@ var Throttler = class {
118
162
  this.setOptions(event.payload.options);
119
163
  });
120
164
  }
121
- #setState = (newState) => {
122
- this.store.setState((state) => {
123
- const combinedState = {
124
- ...state,
125
- ...newState
126
- };
127
- const { isPending } = combinedState;
128
- return {
129
- ...combinedState,
130
- status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
131
- };
132
- });
133
- require_event_client.emitChange("Throttler", this);
134
- };
135
- #getEnabled = () => {
136
- return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
137
- };
138
- #getWait = () => {
139
- return require_utils.parseFunctionOrValue(this.options.wait, this);
140
- };
141
- #execute = (...args) => {
142
- if (!this.#getEnabled()) return;
143
- this.fn(...args);
144
- const lastExecutionTime = Date.now();
145
- const nextExecutionTime = lastExecutionTime + this.#getWait();
146
- this.#clearTimeout();
147
- this.#setState({
148
- executionCount: this.store.state.executionCount + 1,
149
- lastExecutionTime,
150
- nextExecutionTime,
151
- isPending: false,
152
- lastArgs: void 0
153
- });
154
- this.options.onExecute?.(args, this);
155
- setTimeout(() => {
156
- if (!this.store.state.isPending) this.#setState({ nextExecutionTime: void 0 });
157
- }, this.#getWait());
158
- };
159
- #clearTimeout = () => {
160
- if (this.#timeoutId) {
161
- clearTimeout(this.#timeoutId);
162
- this.#timeoutId = void 0;
163
- }
164
- };
165
+ #setState;
166
+ #getEnabled;
167
+ #getWait;
168
+ #execute;
169
+ #clearTimeout;
165
170
  };
166
171
  /**
167
172
  * Creates a throttled function that limits how often the provided function can execute.