@tanstack/pacer 0.16.2 → 0.16.4

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 (180) hide show
  1. package/README.md +165 -0
  2. package/dist/async-batcher.cjs +355 -0
  3. package/dist/async-batcher.cjs.map +1 -0
  4. package/dist/async-batcher.d.cts +344 -0
  5. package/dist/async-batcher.d.ts +344 -0
  6. package/dist/async-batcher.js +353 -0
  7. package/dist/async-batcher.js.map +1 -0
  8. package/dist/async-debouncer.cjs +340 -0
  9. package/dist/async-debouncer.cjs.map +1 -0
  10. package/dist/async-debouncer.d.cts +300 -0
  11. package/dist/async-debouncer.d.ts +300 -0
  12. package/dist/async-debouncer.js +338 -0
  13. package/dist/async-debouncer.js.map +1 -0
  14. package/dist/async-queuer.cjs +496 -0
  15. package/dist/async-queuer.cjs.map +1 -0
  16. package/dist/async-queuer.d.cts +440 -0
  17. package/dist/async-queuer.d.ts +440 -0
  18. package/dist/async-queuer.js +494 -0
  19. package/dist/async-queuer.js.map +1 -0
  20. package/dist/async-rate-limiter.cjs +381 -0
  21. package/dist/async-rate-limiter.cjs.map +1 -0
  22. package/dist/{cjs/async-rate-limiter.d.cts → async-rate-limiter.d.cts} +190 -185
  23. package/dist/{esm/async-rate-limiter.d.ts → async-rate-limiter.d.ts} +190 -185
  24. package/dist/async-rate-limiter.js +379 -0
  25. package/dist/async-rate-limiter.js.map +1 -0
  26. package/dist/async-retryer.cjs +378 -0
  27. package/dist/async-retryer.cjs.map +1 -0
  28. package/dist/async-retryer.d.cts +312 -0
  29. package/dist/async-retryer.d.ts +312 -0
  30. package/dist/async-retryer.js +376 -0
  31. package/dist/async-retryer.js.map +1 -0
  32. package/dist/async-throttler.cjs +362 -0
  33. package/dist/async-throttler.cjs.map +1 -0
  34. package/dist/async-throttler.d.cts +320 -0
  35. package/dist/async-throttler.d.ts +320 -0
  36. package/dist/async-throttler.js +360 -0
  37. package/dist/async-throttler.js.map +1 -0
  38. package/dist/batcher.cjs +194 -0
  39. package/dist/batcher.cjs.map +1 -0
  40. package/dist/batcher.d.cts +180 -0
  41. package/dist/batcher.d.ts +180 -0
  42. package/dist/batcher.js +193 -0
  43. package/dist/batcher.js.map +1 -0
  44. package/dist/debouncer.cjs +197 -0
  45. package/dist/debouncer.cjs.map +1 -0
  46. package/dist/debouncer.d.cts +167 -0
  47. package/dist/debouncer.d.ts +167 -0
  48. package/dist/debouncer.js +195 -0
  49. package/dist/debouncer.js.map +1 -0
  50. package/dist/event-client.cjs +20 -0
  51. package/dist/event-client.cjs.map +1 -0
  52. package/dist/event-client.d.cts +49 -0
  53. package/dist/event-client.d.ts +49 -0
  54. package/dist/event-client.js +19 -0
  55. package/dist/event-client.js.map +1 -0
  56. package/dist/index.cjs +49 -0
  57. package/dist/index.d.cts +15 -0
  58. package/dist/index.d.ts +15 -0
  59. package/dist/{esm/index.js → index.js} +5 -41
  60. package/dist/queuer.cjs +393 -0
  61. package/dist/queuer.cjs.map +1 -0
  62. package/dist/queuer.d.cts +345 -0
  63. package/dist/queuer.d.ts +345 -0
  64. package/dist/queuer.js +391 -0
  65. package/dist/queuer.js.map +1 -0
  66. package/dist/rate-limiter.cjs +251 -0
  67. package/dist/rate-limiter.cjs.map +1 -0
  68. package/dist/{cjs/rate-limiter.d.cts → rate-limiter.d.cts} +113 -108
  69. package/dist/{esm/rate-limiter.d.ts → rate-limiter.d.ts} +113 -108
  70. package/dist/rate-limiter.js +249 -0
  71. package/dist/rate-limiter.js.map +1 -0
  72. package/dist/throttler.cjs +209 -0
  73. package/dist/throttler.cjs.map +1 -0
  74. package/dist/throttler.d.cts +207 -0
  75. package/dist/throttler.d.ts +207 -0
  76. package/dist/throttler.js +207 -0
  77. package/dist/throttler.js.map +1 -0
  78. package/dist/types.cjs +0 -0
  79. package/dist/types.d.cts +13 -0
  80. package/dist/types.d.ts +13 -0
  81. package/dist/types.js +1 -0
  82. package/dist/utils.cjs +13 -0
  83. package/dist/utils.cjs.map +1 -0
  84. package/dist/utils.d.cts +8 -0
  85. package/dist/utils.d.ts +8 -0
  86. package/dist/utils.js +11 -0
  87. package/dist/utils.js.map +1 -0
  88. package/package.json +38 -122
  89. package/src/async-batcher.ts +7 -5
  90. package/src/async-debouncer.ts +7 -5
  91. package/src/async-queuer.ts +7 -5
  92. package/src/async-rate-limiter.ts +7 -5
  93. package/src/async-retryer.ts +7 -5
  94. package/src/async-throttler.ts +7 -5
  95. package/src/batcher.ts +7 -5
  96. package/src/debouncer.ts +7 -5
  97. package/src/queuer.ts +7 -5
  98. package/src/rate-limiter.ts +7 -5
  99. package/src/throttler.ts +7 -5
  100. package/dist/cjs/async-batcher.cjs +0 -220
  101. package/dist/cjs/async-batcher.cjs.map +0 -1
  102. package/dist/cjs/async-batcher.d.cts +0 -340
  103. package/dist/cjs/async-debouncer.cjs +0 -231
  104. package/dist/cjs/async-debouncer.cjs.map +0 -1
  105. package/dist/cjs/async-debouncer.d.cts +0 -295
  106. package/dist/cjs/async-queuer.cjs +0 -397
  107. package/dist/cjs/async-queuer.cjs.map +0 -1
  108. package/dist/cjs/async-queuer.d.cts +0 -435
  109. package/dist/cjs/async-rate-limiter.cjs +0 -252
  110. package/dist/cjs/async-rate-limiter.cjs.map +0 -1
  111. package/dist/cjs/async-retryer.cjs +0 -285
  112. package/dist/cjs/async-retryer.cjs.map +0 -1
  113. package/dist/cjs/async-retryer.d.cts +0 -308
  114. package/dist/cjs/async-throttler.cjs +0 -261
  115. package/dist/cjs/async-throttler.cjs.map +0 -1
  116. package/dist/cjs/async-throttler.d.cts +0 -315
  117. package/dist/cjs/batcher.cjs +0 -130
  118. package/dist/cjs/batcher.cjs.map +0 -1
  119. package/dist/cjs/batcher.d.cts +0 -176
  120. package/dist/cjs/debouncer.cjs +0 -137
  121. package/dist/cjs/debouncer.cjs.map +0 -1
  122. package/dist/cjs/debouncer.d.cts +0 -162
  123. package/dist/cjs/event-client.cjs +0 -20
  124. package/dist/cjs/event-client.cjs.map +0 -1
  125. package/dist/cjs/event-client.d.cts +0 -45
  126. package/dist/cjs/index.cjs +0 -51
  127. package/dist/cjs/index.cjs.map +0 -1
  128. package/dist/cjs/index.d.cts +0 -15
  129. package/dist/cjs/queuer.cjs +0 -306
  130. package/dist/cjs/queuer.cjs.map +0 -1
  131. package/dist/cjs/queuer.d.cts +0 -340
  132. package/dist/cjs/rate-limiter.cjs +0 -179
  133. package/dist/cjs/rate-limiter.cjs.map +0 -1
  134. package/dist/cjs/throttler.cjs +0 -151
  135. package/dist/cjs/throttler.cjs.map +0 -1
  136. package/dist/cjs/throttler.d.cts +0 -202
  137. package/dist/cjs/types.d.cts +0 -9
  138. package/dist/cjs/utils.cjs +0 -11
  139. package/dist/cjs/utils.cjs.map +0 -1
  140. package/dist/cjs/utils.d.cts +0 -3
  141. package/dist/esm/async-batcher.d.ts +0 -340
  142. package/dist/esm/async-batcher.js +0 -220
  143. package/dist/esm/async-batcher.js.map +0 -1
  144. package/dist/esm/async-debouncer.d.ts +0 -295
  145. package/dist/esm/async-debouncer.js +0 -231
  146. package/dist/esm/async-debouncer.js.map +0 -1
  147. package/dist/esm/async-queuer.d.ts +0 -435
  148. package/dist/esm/async-queuer.js +0 -397
  149. package/dist/esm/async-queuer.js.map +0 -1
  150. package/dist/esm/async-rate-limiter.js +0 -252
  151. package/dist/esm/async-rate-limiter.js.map +0 -1
  152. package/dist/esm/async-retryer.d.ts +0 -308
  153. package/dist/esm/async-retryer.js +0 -285
  154. package/dist/esm/async-retryer.js.map +0 -1
  155. package/dist/esm/async-throttler.d.ts +0 -315
  156. package/dist/esm/async-throttler.js +0 -261
  157. package/dist/esm/async-throttler.js.map +0 -1
  158. package/dist/esm/batcher.d.ts +0 -176
  159. package/dist/esm/batcher.js +0 -130
  160. package/dist/esm/batcher.js.map +0 -1
  161. package/dist/esm/debouncer.d.ts +0 -162
  162. package/dist/esm/debouncer.js +0 -137
  163. package/dist/esm/debouncer.js.map +0 -1
  164. package/dist/esm/event-client.d.ts +0 -45
  165. package/dist/esm/event-client.js +0 -20
  166. package/dist/esm/event-client.js.map +0 -1
  167. package/dist/esm/index.d.ts +0 -15
  168. package/dist/esm/index.js.map +0 -1
  169. package/dist/esm/queuer.d.ts +0 -340
  170. package/dist/esm/queuer.js +0 -306
  171. package/dist/esm/queuer.js.map +0 -1
  172. package/dist/esm/rate-limiter.js +0 -179
  173. package/dist/esm/rate-limiter.js.map +0 -1
  174. package/dist/esm/throttler.d.ts +0 -202
  175. package/dist/esm/throttler.js +0 -151
  176. package/dist/esm/throttler.js.map +0 -1
  177. package/dist/esm/types.d.ts +0 -9
  178. package/dist/esm/utils.d.ts +0 -3
  179. package/dist/esm/utils.js +0 -11
  180. package/dist/esm/utils.js.map +0 -1
@@ -0,0 +1,251 @@
1
+ const require_utils = require('./utils.cjs');
2
+ const require_event_client = require('./event-client.cjs');
3
+ let __tanstack_store = require("@tanstack/store");
4
+
5
+ //#region src/rate-limiter.ts
6
+ function getDefaultRateLimiterState() {
7
+ return {
8
+ executionCount: 0,
9
+ executionTimes: [],
10
+ isExceeded: false,
11
+ rejectionCount: 0,
12
+ status: "idle",
13
+ maybeExecuteCount: 0
14
+ };
15
+ }
16
+ /**
17
+ * Utility function for sharing common `RateLimiterOptions` options between different `RateLimiter` instances.
18
+ */
19
+ function rateLimiterOptions(options) {
20
+ return options;
21
+ }
22
+ const defaultOptions = {
23
+ enabled: true,
24
+ limit: 1,
25
+ window: 0,
26
+ windowType: "fixed"
27
+ };
28
+ /**
29
+ * A class that creates a rate-limited function.
30
+ *
31
+ * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
32
+ * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
33
+ * all executions happen immediately, followed by a complete block.
34
+ * 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.
35
+ *
36
+ * The rate limiter supports two types of windows:
37
+ * - 'fixed': A strict window that resets after the window period. All executions within the window count
38
+ * towards the limit, and the window resets completely after the period.
39
+ * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
40
+ * consistent rate of execution over time.
41
+ *
42
+ * For smoother execution patterns, consider using:
43
+ * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
44
+ * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
45
+ *
46
+ * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
47
+ * smoothing out frequent events, throttling or debouncing usually provide better user experience.
48
+ *
49
+ * State Management:
50
+ * - Uses TanStack Store for reactive state management
51
+ * - Use `initialState` to provide initial state values when creating the rate limiter
52
+ * - Use `onExecute` callback to react to function execution and implement custom logic
53
+ * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
54
+ * - The state includes execution count, execution times, and rejection count
55
+ * - State can be accessed via `rateLimiter.store.state` when using the class directly
56
+ * - When using framework adapters (React/Solid), state is accessed from `rateLimiter.state`
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * const rateLimiter = new RateLimiter(
61
+ * (id: string) => api.getData(id),
62
+ * {
63
+ * limit: 5,
64
+ * window: 1000,
65
+ * windowType: 'sliding',
66
+ * }
67
+ * );
68
+ *
69
+ * // Will execute immediately until limit reached, then block
70
+ * rateLimiter.maybeExecute('123');
71
+ * ```
72
+ */
73
+ var RateLimiter = class {
74
+ #timeoutIds = /* @__PURE__ */ new Set();
75
+ constructor(fn, initialOptions) {
76
+ this.fn = fn;
77
+ this.store = new __tanstack_store.Store(getDefaultRateLimiterState());
78
+ this.setOptions = (newOptions) => {
79
+ this.options = {
80
+ ...this.options,
81
+ ...newOptions
82
+ };
83
+ };
84
+ this.maybeExecute = (...args) => {
85
+ this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
86
+ this.#cleanupOldExecutions();
87
+ if (this.#getExecutionTimesInWindow().length < this.#getLimit()) {
88
+ this.#execute(...args);
89
+ return true;
90
+ }
91
+ this.#setState({ rejectionCount: this.store.state.rejectionCount + 1 });
92
+ this.options.onReject?.(this);
93
+ return false;
94
+ };
95
+ this.getRemainingInWindow = () => {
96
+ const relevantExecutionTimes = this.#getExecutionTimesInWindow();
97
+ return Math.max(0, this.#getLimit() - relevantExecutionTimes.length);
98
+ };
99
+ this.getMsUntilNextWindow = () => {
100
+ if (this.getRemainingInWindow() > 0) return 0;
101
+ return (this.store.state.executionTimes[0] ?? Infinity) + this.#getWindow() - Date.now();
102
+ };
103
+ this.reset = () => {
104
+ this.#setState(getDefaultRateLimiterState());
105
+ this.#clearTimeouts();
106
+ };
107
+ this.key = initialOptions.key;
108
+ this.options = {
109
+ ...defaultOptions,
110
+ ...initialOptions
111
+ };
112
+ this.#setState(this.options.initialState ?? {});
113
+ for (const executionTime of this.#getExecutionTimesInWindow()) this.#setCleanupTimeout(executionTime);
114
+ if (this.key) require_event_client.pacerEventClient.on("d-RateLimiter", (event) => {
115
+ if (event.payload.key !== this.key) return;
116
+ this.#setState(event.payload.store.state);
117
+ this.setOptions(event.payload.options);
118
+ });
119
+ }
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
+ require_event_client.emitChange("RateLimiter", this);
135
+ };
136
+ /**
137
+ * Returns the current enabled state of the rate limiter
138
+ */
139
+ #getEnabled = () => {
140
+ return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
141
+ };
142
+ /**
143
+ * Returns the current limit of executions allowed within the time window
144
+ */
145
+ #getLimit = () => {
146
+ return require_utils.parseFunctionOrValue(this.options.limit, this);
147
+ };
148
+ /**
149
+ * Returns the current time window in milliseconds
150
+ */
151
+ #getWindow = () => {
152
+ return require_utils.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
+ };
194
+ };
195
+ /**
196
+ * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
197
+ *
198
+ * 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.
199
+ *
200
+ * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
201
+ * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
202
+ * - A throttler ensures even spacing between executions, which can be better for consistent performance
203
+ * - A debouncer collapses multiple calls into one, which is better for handling bursts of events
204
+ *
205
+ * The rate limiter supports two types of windows:
206
+ * - 'fixed': A strict window that resets after the window period. All executions within the window count
207
+ * towards the limit, and the window resets completely after the period.
208
+ * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
209
+ * consistent rate of execution over time.
210
+ *
211
+ * State Management:
212
+ * - Uses TanStack Store for reactive state management
213
+ * - Use `initialState` to provide initial state values when creating the rate limiter
214
+ * - Use `onExecute` callback to react to function execution and implement custom logic
215
+ * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded
216
+ * - The state includes execution count, execution times, and rejection count
217
+ * - State can be accessed via the underlying RateLimiter instance's `store.state` property
218
+ * - When using framework adapters (React/Solid), state is accessed from the hook's state property
219
+ *
220
+ * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
221
+ * need to enforce a hard limit on the number of executions within a time period.
222
+ *
223
+ * @example
224
+ * ```ts
225
+ * // Rate limit to 5 calls per minute with a sliding window
226
+ * const rateLimited = rateLimit(makeApiCall, {
227
+ * limit: 5,
228
+ * window: 60000,
229
+ * windowType: 'sliding',
230
+ * onReject: (rateLimiter) => {
231
+ * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
232
+ * }
233
+ * });
234
+ *
235
+ * // First 5 calls will execute immediately
236
+ * // Additional calls will be rejected until the minute window resets
237
+ * rateLimited();
238
+ *
239
+ * // For more even execution, consider using throttle instead:
240
+ * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
241
+ * ```
242
+ */
243
+ function rateLimit(fn, initialOptions) {
244
+ return new RateLimiter(fn, initialOptions).maybeExecute;
245
+ }
246
+
247
+ //#endregion
248
+ exports.RateLimiter = RateLimiter;
249
+ exports.rateLimit = rateLimit;
250
+ exports.rateLimiterOptions = rateLimiterOptions;
251
+ //# sourceMappingURL=rate-limiter.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limiter.cjs","names":["defaultOptions: Omit<\n Required<RateLimiterOptions<any>>,\n 'initialState' | 'onExecute' | 'onReject' | 'key'\n>","fn: TFn","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<NodeJS.Timeout> = 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)\n this.setOptions(event.payload.options)\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: NodeJS.Timeout): 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":"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"}
@@ -1,79 +1,81 @@
1
- import { Store } from '@tanstack/store';
2
- import { AnyFunction } from './types.cjs';
3
- export interface RateLimiterState {
4
- /**
5
- * Number of function executions that have been completed
6
- */
7
- executionCount: number;
8
- /**
9
- * Array of timestamps when executions occurred for rate limiting calculations
10
- */
11
- executionTimes: Array<number>;
12
- /**
13
- * Whether the rate limiter has exceeded the limit
14
- */
15
- isExceeded: boolean;
16
- /**
17
- * Number of times maybeExecute has been called (for reduction calculations)
18
- */
19
- maybeExecuteCount: number;
20
- /**
21
- * Number of function executions that have been rejected due to rate limiting
22
- */
23
- rejectionCount: number;
24
- /**
25
- * Current execution status - 'disabled' when not active, 'executing' when executing, 'idle' when not executing, 'exceeded' when rate limit is exceeded
26
- */
27
- status: 'disabled' | 'exceeded' | 'idle';
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';
28
30
  }
29
31
  /**
30
32
  * Options for configuring a rate-limited function
31
33
  */
32
- export interface RateLimiterOptions<TFn extends AnyFunction> {
33
- /**
34
- * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
35
- * Defaults to true.
36
- */
37
- enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean);
38
- /**
39
- * Initial state for the rate limiter
40
- */
41
- initialState?: Partial<RateLimiterState>;
42
- /**
43
- * Optional key to identify this rate limiter instance.
44
- * If provided, the rate limiter will be identified by this key in the devtools and PacerProvider if applicable.
45
- */
46
- key?: string;
47
- /**
48
- * Maximum number of executions allowed within the time window.
49
- * Can be a number or a callback function that receives the rate limiter instance and returns a number.
50
- */
51
- limit: number | ((rateLimiter: RateLimiter<TFn>) => number);
52
- /**
53
- * Callback function that is called after the function is executed
54
- */
55
- onExecute?: (args: Parameters<TFn>, rateLimiter: RateLimiter<TFn>) => void;
56
- /**
57
- * Optional callback function that is called when an execution is rejected due to rate limiting
58
- */
59
- onReject?: (rateLimiter: RateLimiter<TFn>) => void;
60
- /**
61
- * Time window in milliseconds within which the limit applies.
62
- * Can be a number or a callback function that receives the rate limiter instance and returns a number.
63
- */
64
- window: number | ((rateLimiter: RateLimiter<TFn>) => number);
65
- /**
66
- * Type of window to use for rate limiting
67
- * - 'fixed': Uses a fixed window that resets after the window period
68
- * - 'sliding': Uses a sliding window that allows executions as old ones expire
69
- * Defaults to 'fixed'
70
- */
71
- windowType?: 'fixed' | 'sliding';
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';
72
74
  }
73
75
  /**
74
76
  * Utility function for sharing common `RateLimiterOptions` options between different `RateLimiter` instances.
75
77
  */
76
- export declare function rateLimiterOptions<TFn extends AnyFunction = AnyFunction, TOptions extends Partial<RateLimiterOptions<TFn>> = Partial<RateLimiterOptions<TFn>>>(options: TOptions): TOptions;
78
+ declare function rateLimiterOptions<TFn extends AnyFunction = AnyFunction, TOptions extends Partial<RateLimiterOptions<TFn>> = Partial<RateLimiterOptions<TFn>>>(options: TOptions): TOptions;
77
79
  /**
78
80
  * A class that creates a rate-limited function.
79
81
  *
@@ -119,45 +121,45 @@ export declare function rateLimiterOptions<TFn extends AnyFunction = AnyFunction
119
121
  * rateLimiter.maybeExecute('123');
120
122
  * ```
121
123
  */
122
- export declare class RateLimiter<TFn extends AnyFunction> {
123
- #private;
124
- fn: TFn;
125
- readonly store: Store<Readonly<RateLimiterState>>;
126
- key: string | undefined;
127
- options: RateLimiterOptions<TFn>;
128
- constructor(fn: TFn, initialOptions: RateLimiterOptions<TFn>);
129
- /**
130
- * Updates the rate limiter options
131
- */
132
- setOptions: (newOptions: Partial<RateLimiterOptions<TFn>>) => void;
133
- /**
134
- * Attempts to execute the rate-limited function if within the configured limits.
135
- * Will reject execution if the number of calls in the current window exceeds the limit.
136
- *
137
- * @example
138
- * ```ts
139
- * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });
140
- *
141
- * // First 5 calls will return true
142
- * rateLimiter.maybeExecute('arg1', 'arg2'); // true
143
- *
144
- * // Additional calls within the window will return false
145
- * rateLimiter.maybeExecute('arg1', 'arg2'); // false
146
- * ```
147
- */
148
- maybeExecute: (...args: Parameters<TFn>) => boolean;
149
- /**
150
- * Returns the number of remaining executions allowed in the current window
151
- */
152
- getRemainingInWindow: () => number;
153
- /**
154
- * Returns the number of milliseconds until the next execution will be possible
155
- */
156
- getMsUntilNextWindow: () => number;
157
- /**
158
- * Resets the rate limiter state
159
- */
160
- reset: () => void;
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;
161
163
  }
162
164
  /**
163
165
  * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
@@ -207,4 +209,7 @@ export declare class RateLimiter<TFn extends AnyFunction> {
207
209
  * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
208
210
  * ```
209
211
  */
210
- export declare function rateLimit<TFn extends AnyFunction>(fn: TFn, initialOptions: RateLimiterOptions<TFn>): (...args: Parameters<TFn>) => boolean;
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