@tanstack/pacer 0.21.1 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +21 -6
  2. package/dist/async-batcher.d.ts +11 -14
  3. package/dist/async-batcher.js +186 -132
  4. package/dist/async-debouncer.d.ts +10 -13
  5. package/dist/async-debouncer.js +187 -146
  6. package/dist/async-queuer.d.ts +12 -14
  7. package/dist/async-queuer.js +384 -259
  8. package/dist/async-rate-limiter.d.ts +9 -12
  9. package/dist/async-rate-limiter.js +198 -147
  10. package/dist/async-retryer.d.ts +10 -10
  11. package/dist/async-retryer.js +209 -188
  12. package/dist/async-throttler.d.ts +10 -13
  13. package/dist/async-throttler.js +215 -161
  14. package/dist/batcher.d.ts +5 -8
  15. package/dist/batcher.js +107 -87
  16. package/dist/debouncer.d.ts +6 -9
  17. package/dist/debouncer.js +99 -86
  18. package/dist/event-client.d.ts +8 -11
  19. package/dist/event-client.js +1 -2
  20. package/dist/index.js +1 -1
  21. package/dist/queuer.d.ts +8 -10
  22. package/dist/queuer.js +277 -207
  23. package/dist/rate-limiter.d.ts +6 -9
  24. package/dist/rate-limiter.js +127 -109
  25. package/dist/throttler.d.ts +6 -9
  26. package/dist/throttler.js +127 -90
  27. package/dist/types.d.ts +4 -6
  28. package/dist/utils.d.ts +3 -6
  29. package/dist/utils.js +1 -2
  30. package/package.json +23 -70
  31. package/dist/async-batcher.cjs +0 -337
  32. package/dist/async-batcher.cjs.map +0 -1
  33. package/dist/async-batcher.d.cts +0 -344
  34. package/dist/async-batcher.js.map +0 -1
  35. package/dist/async-debouncer.cjs +0 -330
  36. package/dist/async-debouncer.cjs.map +0 -1
  37. package/dist/async-debouncer.d.cts +0 -300
  38. package/dist/async-debouncer.js.map +0 -1
  39. package/dist/async-queuer.cjs +0 -484
  40. package/dist/async-queuer.cjs.map +0 -1
  41. package/dist/async-queuer.d.cts +0 -440
  42. package/dist/async-queuer.js.map +0 -1
  43. package/dist/async-rate-limiter.cjs +0 -373
  44. package/dist/async-rate-limiter.cjs.map +0 -1
  45. package/dist/async-rate-limiter.d.cts +0 -357
  46. package/dist/async-rate-limiter.js.map +0 -1
  47. package/dist/async-retryer.cjs +0 -374
  48. package/dist/async-retryer.cjs.map +0 -1
  49. package/dist/async-retryer.d.cts +0 -319
  50. package/dist/async-retryer.js.map +0 -1
  51. package/dist/async-throttler.cjs +0 -347
  52. package/dist/async-throttler.cjs.map +0 -1
  53. package/dist/async-throttler.d.cts +0 -320
  54. package/dist/async-throttler.js.map +0 -1
  55. package/dist/batcher.cjs +0 -200
  56. package/dist/batcher.cjs.map +0 -1
  57. package/dist/batcher.d.cts +0 -180
  58. package/dist/batcher.js.map +0 -1
  59. package/dist/debouncer.cjs +0 -203
  60. package/dist/debouncer.cjs.map +0 -1
  61. package/dist/debouncer.d.cts +0 -167
  62. package/dist/debouncer.js.map +0 -1
  63. package/dist/event-client.cjs +0 -64
  64. package/dist/event-client.cjs.map +0 -1
  65. package/dist/event-client.d.cts +0 -66
  66. package/dist/event-client.js.map +0 -1
  67. package/dist/index.cjs +0 -52
  68. package/dist/index.d.cts +0 -15
  69. package/dist/queuer.cjs +0 -401
  70. package/dist/queuer.cjs.map +0 -1
  71. package/dist/queuer.d.cts +0 -345
  72. package/dist/queuer.js.map +0 -1
  73. package/dist/rate-limiter.cjs +0 -263
  74. package/dist/rate-limiter.cjs.map +0 -1
  75. package/dist/rate-limiter.d.cts +0 -215
  76. package/dist/rate-limiter.js.map +0 -1
  77. package/dist/throttler.cjs +0 -215
  78. package/dist/throttler.cjs.map +0 -1
  79. package/dist/throttler.d.cts +0 -207
  80. package/dist/throttler.js.map +0 -1
  81. package/dist/types.cjs +0 -0
  82. package/dist/types.d.cts +0 -13
  83. package/dist/utils.cjs +0 -14
  84. package/dist/utils.cjs.map +0 -1
  85. package/dist/utils.d.cts +0 -8
  86. package/dist/utils.js.map +0 -1
  87. package/src/async-batcher.ts +0 -594
  88. package/src/async-debouncer.ts +0 -565
  89. package/src/async-queuer.ts +0 -925
  90. package/src/async-rate-limiter.ts +0 -647
  91. package/src/async-retryer.ts +0 -684
  92. package/src/async-throttler.ts +0 -633
  93. package/src/batcher.ts +0 -329
  94. package/src/debouncer.ts +0 -334
  95. package/src/event-client.ts +0 -129
  96. package/src/index.ts +0 -24
  97. package/src/queuer.ts +0 -740
  98. package/src/rate-limiter.ts +0 -429
  99. package/src/throttler.ts +0 -380
  100. package/src/types.ts +0 -12
  101. package/src/utils.ts +0 -12
@@ -1,300 +0,0 @@
1
- import { AnyAsyncFunction } from "./types.cjs";
2
- import { AsyncRetryer, AsyncRetryerOptions } from "./async-retryer.cjs";
3
- import { Store } from "@tanstack/store";
4
-
5
- //#region src/async-debouncer.d.ts
6
- interface AsyncDebouncerState<TFn extends AnyAsyncFunction> {
7
- /**
8
- * Whether the debouncer can execute on the leading edge of the timeout
9
- */
10
- canLeadingExecute: boolean;
11
- /**
12
- * Number of function executions that have resulted in errors
13
- */
14
- errorCount: number;
15
- /**
16
- * Whether the debounced function is currently executing asynchronously
17
- */
18
- isExecuting: boolean;
19
- /**
20
- * Whether the debouncer is waiting for the timeout to trigger execution
21
- */
22
- isPending: boolean;
23
- /**
24
- * The arguments from the most recent call to maybeExecute
25
- */
26
- lastArgs: Parameters<TFn> | undefined;
27
- /**
28
- * The result from the most recent successful function execution
29
- */
30
- lastResult: ReturnType<TFn> | undefined;
31
- /**
32
- * Number of times maybeExecute has been called (for reduction calculations)
33
- */
34
- maybeExecuteCount: number;
35
- /**
36
- * Number of function executions that have completed (either successfully or with errors)
37
- */
38
- settleCount: number;
39
- /**
40
- * Current execution status - 'idle' when not active, 'pending' when waiting, 'executing' when running, 'settled' when completed
41
- */
42
- status: 'disabled' | 'idle' | 'pending' | 'executing' | 'settled';
43
- /**
44
- * Number of function executions that have completed successfully
45
- */
46
- successCount: number;
47
- }
48
- /**
49
- * Options for configuring an async debounced function
50
- */
51
- interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
52
- /**
53
- * Options for configuring the underlying async retryer
54
- */
55
- asyncRetryerOptions?: AsyncRetryerOptions<TFn>;
56
- /**
57
- * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
58
- * Can be a boolean or a function that returns a boolean.
59
- * Defaults to true.
60
- */
61
- enabled?: boolean | ((debouncer: AsyncDebouncer<TFn>) => boolean);
62
- /**
63
- * Initial state for the async debouncer
64
- */
65
- initialState?: Partial<AsyncDebouncerState<TFn>>;
66
- /**
67
- * Optional key to identify this async debouncer instance.
68
- * If provided, the async debouncer will be identified by this key in the devtools and PacerProvider if applicable.
69
- */
70
- key?: string;
71
- /**
72
- * Whether to execute on the leading edge of the timeout.
73
- * Defaults to false.
74
- */
75
- leading?: boolean;
76
- /**
77
- * Optional error handler for when the debounced function throws.
78
- * If provided, the handler will be called with the error and debouncer instance.
79
- * This can be used alongside throwOnError - the handler will be called before any error is thrown.
80
- */
81
- onError?: (error: Error, args: Parameters<TFn>, debouncer: AsyncDebouncer<TFn>) => void;
82
- /**
83
- * Optional callback to call when the debounced function is executed
84
- */
85
- onSettled?: (args: Parameters<TFn>, debouncer: AsyncDebouncer<TFn>) => void;
86
- /**
87
- * Optional callback to call when the debounced function is executed
88
- */
89
- onSuccess?: (result: ReturnType<TFn>, args: Parameters<TFn>, debouncer: AsyncDebouncer<TFn>) => void;
90
- /**
91
- * Whether to throw errors when they occur.
92
- * Defaults to true if no onError handler is provided, false if an onError handler is provided.
93
- * Can be explicitly set to override these defaults.
94
- */
95
- throwOnError?: boolean;
96
- /**
97
- * Whether to execute on the trailing edge of the timeout.
98
- * Defaults to true.
99
- */
100
- trailing?: boolean;
101
- /**
102
- * Delay in milliseconds to wait after the last call before executing.
103
- * Can be a number or a function that returns a number.
104
- * Defaults to 0ms
105
- */
106
- wait: number | ((debouncer: AsyncDebouncer<TFn>) => number);
107
- }
108
- /**
109
- * Utility function for sharing common `AsyncDebouncerOptions` options between different `AsyncDebouncer` instances.
110
- */
111
- declare function asyncDebouncerOptions<TFn extends AnyAsyncFunction = AnyAsyncFunction, TOptions extends Partial<AsyncDebouncerOptions<TFn>> = Partial<AsyncDebouncerOptions<TFn>>>(options: TOptions): TOptions;
112
- /**
113
- * A class that creates an async debounced function.
114
- *
115
- * Async vs Sync Versions:
116
- * The async version provides advanced features over the sync Debouncer:
117
- * - Returns promises that can be awaited for debounced function results
118
- * - Built-in retry support via AsyncRetryer integration
119
- * - Abort support to cancel in-flight executions
120
- * - Cancel support to prevent pending executions from starting
121
- * - Comprehensive error handling with onError callbacks and throwOnError control
122
- * - Detailed execution tracking (success/error/settle counts)
123
- *
124
- * The sync Debouncer is lighter weight and simpler when you don't need async features,
125
- * return values, or execution control.
126
- *
127
- * What is Debouncing?
128
- * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.
129
- * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
130
- * or input changes where you only want to execute the handler after the events have stopped occurring.
131
- *
132
- * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
133
- * the function stops being called for the specified delay period.
134
- *
135
- * Error Handling:
136
- * - If an `onError` handler is provided, it will be called with the error and debouncer instance
137
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
138
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
139
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
140
- * - The error state can be checked using the underlying store
141
- *
142
- * State Management:
143
- * - The debouncer uses a reactive store for state management
144
- * - Use `initialState` to provide initial state values when creating the async debouncer
145
- * - The state includes canLeadingExecute, error count, execution status, and success/settle counts
146
- * - State can be accessed via the `store` property and its `state` getter
147
- * - The store is reactive and will notify subscribers of state changes
148
- *
149
- * @example
150
- * ```ts
151
- * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
152
- * const results = await searchAPI(value);
153
- * return results; // Return value is preserved
154
- * }, {
155
- * wait: 500,
156
- * onError: (error) => {
157
- * console.error('Search failed:', error);
158
- * }
159
- * });
160
- *
161
- * // Called on each keystroke but only executes after 500ms of no typing
162
- * // Returns the API response directly
163
- * const results = await asyncDebouncer.maybeExecute(inputElement.value);
164
- * ```
165
- */
166
- declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
167
- #private;
168
- fn: TFn;
169
- readonly store: Store<Readonly<AsyncDebouncerState<TFn>>>;
170
- key: string | undefined;
171
- options: AsyncDebouncerOptions<TFn>;
172
- asyncRetryers: Map<number, AsyncRetryer<TFn>>;
173
- constructor(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn>);
174
- /**
175
- * Updates the async debouncer options
176
- */
177
- setOptions: (newOptions: Partial<AsyncDebouncerOptions<TFn>>) => void;
178
- /**
179
- * Attempts to execute the debounced function.
180
- * If a call is already in progress, it will be queued.
181
- *
182
- * Error Handling:
183
- * - If the debounced function throws and no `onError` handler is configured,
184
- * the error will be thrown from this method.
185
- * - If an `onError` handler is configured, errors will be caught and passed to the handler,
186
- * and this method will return undefined.
187
- * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
188
- *
189
- * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
190
- * @throws The error from the debounced function if no onError handler is configured
191
- */
192
- maybeExecute: (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
193
- /**
194
- * Processes the current pending execution immediately
195
- */
196
- flush: () => Promise<ReturnType<TFn> | undefined>;
197
- /**
198
- * Returns the AbortSignal for a specific execution.
199
- * If no maybeExecuteCount is provided, returns the signal for the most recent execution.
200
- * Returns null if no execution is found or not currently executing.
201
- *
202
- * @param maybeExecuteCount - Optional specific execution to get signal for
203
- * @example
204
- * ```typescript
205
- * const debouncer = new AsyncDebouncer(
206
- * async (searchTerm: string) => {
207
- * const signal = debouncer.getAbortSignal()
208
- * if (signal) {
209
- * const response = await fetch(`/api/search?q=${searchTerm}`, { signal })
210
- * return response.json()
211
- * }
212
- * },
213
- * { wait: 300 }
214
- * )
215
- * ```
216
- */
217
- getAbortSignal: (maybeExecuteCount?: number) => AbortSignal | null;
218
- /**
219
- * Aborts all ongoing executions with the internal abort controllers.
220
- * Does NOT cancel any pending execution that have not started yet.
221
- */
222
- abort: () => void;
223
- /**
224
- * Cancels any pending execution that have not started yet.
225
- * Does NOT abort any execution already in progress.
226
- */
227
- cancel: () => void;
228
- /**
229
- * Resets the debouncer state to its default values
230
- */
231
- reset: () => void;
232
- }
233
- /**
234
- * Creates an async debounced function that delays execution until after a specified wait time.
235
- * The debounced function will only execute once the wait period has elapsed without any new calls.
236
- * If called again during the wait period, the timer resets and a new wait period begins.
237
- *
238
- * Async vs Sync Versions:
239
- * The async version provides advanced features over the sync debounce function:
240
- * - Returns promises that can be awaited for debounced function results
241
- * - Built-in retry support via AsyncRetryer integration
242
- * - Abort support to cancel in-flight executions
243
- * - Cancel support to prevent pending executions from starting
244
- * - Comprehensive error handling with onError callbacks and throwOnError control
245
- * - Detailed execution tracking (success/error/settle counts)
246
- *
247
- * The sync debounce function is lighter weight and simpler when you don't need async features,
248
- * return values, or execution control.
249
- *
250
- * What is Debouncing?
251
- * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.
252
- * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
253
- * or input changes where you only want to execute the handler after the events have stopped occurring.
254
- *
255
- * Configuration Options:
256
- * - `wait`: Delay in milliseconds to wait after the last call (required)
257
- * - `leading`: Execute on the leading edge of the timeout (default: false)
258
- * - `trailing`: Execute on the trailing edge of the timeout (default: true)
259
- * - `enabled`: Whether the debouncer is enabled (default: true)
260
- * - `asyncRetryerOptions`: Configure retry behavior for executions
261
- *
262
- * Error Handling:
263
- * - If an `onError` handler is provided, it will be called with the error and debouncer instance
264
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
265
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
266
- * - The error state can be checked using the underlying AsyncDebouncer instance
267
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
268
- *
269
- * State Management:
270
- * - Uses TanStack Store for reactive state management
271
- * - Use `initialState` to provide initial state values when creating the async debouncer
272
- * - Use `onSuccess` callback to react to successful function execution and implement custom logic
273
- * - Use `onError` callback to react to function execution errors and implement custom error handling
274
- * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
275
- * - The state includes canLeadingExecute, error count, execution status, and success/settle counts
276
- * - State can be accessed via `asyncDebouncer.store.state` when using the class directly
277
- * - When using framework adapters (React/Solid), state is accessed from `asyncDebouncer.state`
278
- *
279
- * @example
280
- * ```ts
281
- * const debounced = asyncDebounce(async (value: string) => {
282
- * const result = await saveToAPI(value);
283
- * return result; // Return value is preserved
284
- * }, {
285
- * wait: 1000,
286
- * onError: (error) => {
287
- * console.error('API call failed:', error);
288
- * },
289
- * throwOnError: true // Will both log the error and throw it
290
- * });
291
- *
292
- * // Will only execute once, 1 second after the last call
293
- * // Returns the API response directly
294
- * const result = await debounced("third");
295
- * ```
296
- */
297
- declare function asyncDebounce<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
298
- //#endregion
299
- export { AsyncDebouncer, AsyncDebouncerOptions, AsyncDebouncerState, asyncDebounce, asyncDebouncerOptions };
300
- //# sourceMappingURL=async-debouncer.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"async-debouncer.js","names":["#getEnabled","#cancelPendingExecution","#setState","#execute","#resolvePreviousPromise","#timeoutId","#getWait","#clearTimeout","#resolvePreviousPromiseInternal"],"sources":["../src/async-debouncer.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { AsyncRetryer } from './async-retryer'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AsyncRetryerOptions } from './async-retryer'\nimport type { AnyAsyncFunction, OptionalKeys } from './types'\n\nexport interface AsyncDebouncerState<TFn extends AnyAsyncFunction> {\n /**\n * Whether the debouncer can execute on the leading edge of the timeout\n */\n canLeadingExecute: boolean\n /**\n * Number of function executions that have resulted in errors\n */\n errorCount: number\n /**\n * Whether the debounced function is currently executing asynchronously\n */\n isExecuting: boolean\n /**\n * Whether the debouncer is waiting for the timeout to trigger execution\n */\n isPending: boolean\n /**\n * The arguments from the most recent call to maybeExecute\n */\n lastArgs: Parameters<TFn> | undefined\n /**\n * The result from the most recent successful function execution\n */\n lastResult: ReturnType<TFn> | undefined\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Number of function executions that have completed (either successfully or with errors)\n */\n settleCount: number\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting, 'executing' when running, 'settled' when completed\n */\n status: 'disabled' | 'idle' | 'pending' | 'executing' | 'settled'\n /**\n * Number of function executions that have completed successfully\n */\n successCount: number\n}\n\nfunction getDefaultAsyncDebouncerState<\n TFn extends AnyAsyncFunction,\n>(): AsyncDebouncerState<TFn> {\n return {\n canLeadingExecute: true,\n errorCount: 0,\n isExecuting: false,\n isPending: false,\n lastArgs: undefined,\n lastResult: undefined,\n maybeExecuteCount: 0,\n settleCount: 0,\n status: 'idle',\n successCount: 0,\n }\n}\n\n/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {\n /**\n * Options for configuring the underlying async retryer\n */\n asyncRetryerOptions?: AsyncRetryerOptions<TFn>\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: AsyncDebouncer<TFn>) => boolean)\n /**\n * Initial state for the async debouncer\n */\n initialState?: Partial<AsyncDebouncerState<TFn>>\n /**\n * Optional key to identify this async debouncer instance.\n * If provided, the async debouncer will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Optional error handler for when the debounced function throws.\n * If provided, the handler will be called with the error and debouncer instance.\n * This can be used alongside throwOnError - the handler will be called before any error is thrown.\n */\n onError?: (\n error: Error,\n args: Parameters<TFn>,\n debouncer: AsyncDebouncer<TFn>,\n ) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSettled?: (args: Parameters<TFn>, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n args: Parameters<TFn>,\n debouncer: AsyncDebouncer<TFn>,\n ) => void\n /**\n * Whether to throw errors when they occur.\n * Defaults to true if no onError handler is provided, false if an onError handler is provided.\n * Can be explicitly set to override these defaults.\n */\n throwOnError?: boolean\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds to wait after the last call before executing.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: AsyncDebouncer<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `AsyncDebouncerOptions` options between different `AsyncDebouncer` instances.\n */\nexport function asyncDebouncerOptions<\n TFn extends AnyAsyncFunction = AnyAsyncFunction,\n TOptions extends Partial<AsyncDebouncerOptions<TFn>> = Partial<\n AsyncDebouncerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\ntype AsyncDebouncerOptionsWithOptionalCallbacks = OptionalKeys<\n AsyncDebouncerOptions<any>,\n 'initialState' | 'onError' | 'onSettled' | 'onSuccess' | 'key'\n>\n\nconst defaultOptions: AsyncDebouncerOptionsWithOptionalCallbacks = {\n asyncRetryerOptions: {\n maxAttempts: 1,\n },\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync Debouncer:\n * - Returns promises that can be awaited for debounced function results\n * - Built-in retry support via AsyncRetryer integration\n * - Abort support to cancel in-flight executions\n * - Cancel support to prevent pending executions from starting\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n *\n * The sync Debouncer is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Debouncing?\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying store\n *\n * State Management:\n * - The debouncer uses a reactive store for state management\n * - Use `initialState` to provide initial state values when creating the async debouncer\n * - The state includes canLeadingExecute, error count, execution status, and success/settle counts\n * - State can be accessed via the `store` property and its `state` getter\n * - The store is reactive and will notify subscribers of state changes\n *\n * @example\n * ```ts\n * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {\n * const results = await searchAPI(value);\n * return results; // Return value is preserved\n * }, {\n * wait: 500,\n * onError: (error) => {\n * console.error('Search failed:', error);\n * }\n * });\n *\n * // Called on each keystroke but only executes after 500ms of no typing\n * // Returns the API response directly\n * const results = await asyncDebouncer.maybeExecute(inputElement.value);\n * ```\n */\nexport class AsyncDebouncer<TFn extends AnyAsyncFunction> {\n readonly store: Store<Readonly<AsyncDebouncerState<TFn>>> = new Store<\n AsyncDebouncerState<TFn>\n >(getDefaultAsyncDebouncerState<TFn>())\n key: string | undefined\n options: AsyncDebouncerOptions<TFn>\n asyncRetryers = new Map<number, AsyncRetryer<TFn>>()\n #timeoutId: ReturnType<typeof setTimeout> | null = null\n #resolvePreviousPromise:\n | ((value?: ReturnType<TFn> | undefined) => void)\n | null = null\n\n constructor(\n public fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-AsyncDebouncer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<AsyncDebouncerState<TFn>>,\n )\n this.setOptions(\n event.payload.options as Partial<AsyncDebouncerOptions<TFn>>,\n )\n })\n }\n }\n\n /**\n * Updates the async debouncer options\n */\n setOptions = (newOptions: Partial<AsyncDebouncerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the debouncer is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<AsyncDebouncerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending, isExecuting, settleCount } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isPending\n ? 'pending'\n : isExecuting\n ? 'executing'\n : settleCount > 0\n ? 'settled'\n : 'idle',\n }\n })\n emitChange('AsyncDebouncer', this)\n }\n\n /**\n * Returns the current debouncer enabled state\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current debouncer wait state\n */\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Attempts to execute the debounced function.\n * If a call is already in progress, it will be queued.\n *\n * Error Handling:\n * - If the debounced function throws and no `onError` handler is configured,\n * the error will be thrown from this method.\n * - If an `onError` handler is configured, errors will be caught and passed to the handler,\n * and this method will return undefined.\n * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.\n *\n * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError\n * @throws The error from the debounced function if no onError handler is configured\n */\n maybeExecute = async (\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> => {\n if (!this.#getEnabled()) return undefined\n this.#cancelPendingExecution()\n this.#setState({\n lastArgs: args,\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n // Handle leading execution\n if (this.options.leading && this.store.state.canLeadingExecute) {\n this.#setState({ canLeadingExecute: false })\n await this.#execute(...args)\n return this.store.state.lastResult\n }\n\n // Handle trailing execution\n if (this.options.trailing && this.#getEnabled()) {\n this.#setState({ isPending: true })\n }\n\n return new Promise((resolve, reject) => {\n this.#resolvePreviousPromise = resolve\n // this.#rejectPreviousPromise = reject\n this.#timeoutId = setTimeout(async () => {\n // Execute trailing if enabled\n if (this.options.trailing && this.store.state.lastArgs) {\n try {\n await this.#execute(...this.store.state.lastArgs)\n } catch (error) {\n reject(error)\n }\n }\n\n // Reset state and resolve\n this.#setState({ canLeadingExecute: true })\n this.#resolvePreviousPromise = null\n resolve(this.store.state.lastResult)\n }, this.#getWait())\n })\n }\n\n #execute = async (\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> => {\n if (!this.#getEnabled()) return undefined\n const currentMaybeExecuteCount = this.store.state.maybeExecuteCount + 1\n\n try {\n this.#setState({ isExecuting: true })\n const currentAsyncRetryer = new AsyncRetryer(this.fn, {\n ...this.options.asyncRetryerOptions,\n key: `${this.key}-retryer-${currentMaybeExecuteCount}`,\n })\n this.asyncRetryers.set(currentMaybeExecuteCount, currentAsyncRetryer)\n const result = await currentAsyncRetryer.execute(...args) // EXECUTE!\n this.#setState({\n lastResult: result,\n successCount: this.store.state.successCount + 1,\n })\n this.options.onSuccess?.(result as ReturnType<TFn>, args, this)\n } catch (error) {\n this.#setState({\n errorCount: this.store.state.errorCount + 1,\n })\n this.options.onError?.(error as Error, args, this)\n if (this.options.throwOnError) {\n throw error\n }\n } finally {\n this.asyncRetryers.delete(currentMaybeExecuteCount) // dispose retryer\n this.#setState({\n isExecuting: false,\n isPending: false,\n lastArgs: undefined,\n settleCount: this.store.state.settleCount + 1,\n })\n this.options.onSettled?.(args, this)\n }\n return this.store.state.lastResult\n }\n\n /**\n * Processes the current pending execution immediately\n */\n flush = async (): Promise<ReturnType<TFn> | undefined> => {\n if (this.store.state.isPending && this.store.state.lastArgs) {\n const { lastArgs } = this.store.state\n this.#cancelPendingExecution()\n return await this.#execute(...lastArgs)\n }\n return undefined\n }\n\n #resolvePreviousPromiseInternal = (): void => {\n if (this.#resolvePreviousPromise) {\n this.#resolvePreviousPromise(this.store.state.lastResult)\n this.#resolvePreviousPromise = null\n }\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = null\n }\n }\n\n /**\n * Internal cancel without resetting the leading execute state\n */\n #cancelPendingExecution = (): void => {\n this.#clearTimeout()\n this.#resolvePreviousPromiseInternal()\n this.#setState({\n isPending: false,\n lastArgs: undefined,\n })\n }\n\n /**\n * Returns the AbortSignal for a specific execution.\n * If no maybeExecuteCount is provided, returns the signal for the most recent execution.\n * Returns null if no execution is found or not currently executing.\n *\n * @param maybeExecuteCount - Optional specific execution to get signal for\n * @example\n * ```typescript\n * const debouncer = new AsyncDebouncer(\n * async (searchTerm: string) => {\n * const signal = debouncer.getAbortSignal()\n * if (signal) {\n * const response = await fetch(`/api/search?q=${searchTerm}`, { signal })\n * return response.json()\n * }\n * },\n * { wait: 300 }\n * )\n * ```\n */\n getAbortSignal = (maybeExecuteCount?: number): AbortSignal | null => {\n const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount\n const retryer = this.asyncRetryers.get(count)\n return retryer?.getAbortSignal() ?? null\n }\n\n /**\n * Aborts all ongoing executions with the internal abort controllers.\n * Does NOT cancel any pending execution that have not started yet.\n */\n abort = (): void => {\n this.asyncRetryers.forEach((retryer) => retryer.abort())\n this.asyncRetryers.clear()\n this.#setState({\n isExecuting: false,\n })\n }\n\n /**\n * Cancels any pending execution that have not started yet.\n * Does NOT abort any execution already in progress.\n */\n cancel = (): void => {\n this.#cancelPendingExecution()\n this.#setState({ canLeadingExecute: true })\n }\n\n /**\n * Resets the debouncer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultAsyncDebouncerState<TFn>())\n this.asyncRetryers.forEach((retryer) => retryer.reset())\n }\n}\n\n/**\n * Creates an async debounced function that delays execution until after a specified wait time.\n * The debounced function will only execute once the wait period has elapsed without any new calls.\n * If called again during the wait period, the timer resets and a new wait period begins.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync debounce function:\n * - Returns promises that can be awaited for debounced function results\n * - Built-in retry support via AsyncRetryer integration\n * - Abort support to cancel in-flight executions\n * - Cancel support to prevent pending executions from starting\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n *\n * The sync debounce function is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Debouncing?\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Configuration Options:\n * - `wait`: Delay in milliseconds to wait after the last call (required)\n * - `leading`: Execute on the leading edge of the timeout (default: false)\n * - `trailing`: Execute on the trailing edge of the timeout (default: true)\n * - `enabled`: Whether the debouncer is enabled (default: true)\n * - `asyncRetryerOptions`: Configure retry behavior for executions\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - The error state can be checked using the underlying AsyncDebouncer instance\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the async debouncer\n * - Use `onSuccess` callback to react to successful function execution and implement custom logic\n * - Use `onError` callback to react to function execution errors and implement custom error handling\n * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic\n * - The state includes canLeadingExecute, error count, execution status, and success/settle counts\n * - State can be accessed via `asyncDebouncer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `asyncDebouncer.state`\n *\n * @example\n * ```ts\n * const debounced = asyncDebounce(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, {\n * wait: 1000,\n * onError: (error) => {\n * console.error('API call failed:', error);\n * },\n * throwOnError: true // Will both log the error and throw it\n * });\n *\n * // Will only execute once, 1 second after the last call\n * // Returns the API response directly\n * const result = await debounced(\"third\");\n * ```\n */\nexport function asyncDebounce<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n) {\n const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)\n return asyncDebouncer.maybeExecute\n}\n"],"mappings":";;;;;;AAkDA,SAAS,gCAEqB;CAC5B,OAAO;EACL,mBAAmB;EACnB,YAAY;EACZ,aAAa;EACb,WAAW;EACX,UAAU;EACV,YAAY;EACZ,mBAAmB;EACnB,aAAa;EACb,QAAQ;EACR,cAAc;EACf;;;;;AA2EH,SAAgB,sBAKd,SAA6B;CAC7B,OAAO;;AAQT,MAAM,iBAA6D;CACjE,qBAAqB,EACnB,aAAa,GACd;CACD,SAAS;CACT,SAAS;CACT,UAAU;CACV,MAAM;CACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDD,IAAa,iBAAb,MAA0D;CAOxD;CACA;CAIA,YACE,AAAO,IACP,gBACA;EAFO;eAZmD,IAAI,MAE9D,+BAAoC,CAAC;uCAGvB,IAAI,KAAgC;oBACD;iCAGxC;qBA8BG,eAA0D;GACtE,KAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;IAAY;GAGjD,IAAI,CAAC,KAAKA,aAAa,EACrB,KAAK,QAAQ;;oBAIJ,aAAsD;GACjE,KAAK,MAAM,UAAU,UAAU;IAC7B,MAAM,gBAAgB;KACpB,GAAG;KACH,GAAG;KACJ;IACD,MAAM,EAAE,WAAW,aAAa,gBAAgB;IAChD,OAAO;KACL,GAAG;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