@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,330 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_utils = require('./utils.cjs');
3
- const require_event_client = require('./event-client.cjs');
4
- const require_async_retryer = require('./async-retryer.cjs');
5
- let _tanstack_store = require("@tanstack/store");
6
-
7
- //#region src/async-debouncer.ts
8
- function getDefaultAsyncDebouncerState() {
9
- return {
10
- canLeadingExecute: true,
11
- errorCount: 0,
12
- isExecuting: false,
13
- isPending: false,
14
- lastArgs: void 0,
15
- lastResult: void 0,
16
- maybeExecuteCount: 0,
17
- settleCount: 0,
18
- status: "idle",
19
- successCount: 0
20
- };
21
- }
22
- /**
23
- * Utility function for sharing common `AsyncDebouncerOptions` options between different `AsyncDebouncer` instances.
24
- */
25
- function asyncDebouncerOptions(options) {
26
- return options;
27
- }
28
- const defaultOptions = {
29
- asyncRetryerOptions: { maxAttempts: 1 },
30
- enabled: true,
31
- leading: false,
32
- trailing: true,
33
- wait: 0
34
- };
35
- /**
36
- * A class that creates an async debounced function.
37
- *
38
- * Async vs Sync Versions:
39
- * The async version provides advanced features over the sync Debouncer:
40
- * - Returns promises that can be awaited for debounced function results
41
- * - Built-in retry support via AsyncRetryer integration
42
- * - Abort support to cancel in-flight executions
43
- * - Cancel support to prevent pending executions from starting
44
- * - Comprehensive error handling with onError callbacks and throwOnError control
45
- * - Detailed execution tracking (success/error/settle counts)
46
- *
47
- * The sync Debouncer is lighter weight and simpler when you don't need async features,
48
- * return values, or execution control.
49
- *
50
- * What is Debouncing?
51
- * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.
52
- * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
53
- * or input changes where you only want to execute the handler after the events have stopped occurring.
54
- *
55
- * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
56
- * the function stops being called for the specified delay period.
57
- *
58
- * Error Handling:
59
- * - If an `onError` handler is provided, it will be called with the error and debouncer instance
60
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
61
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
62
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
63
- * - The error state can be checked using the underlying store
64
- *
65
- * State Management:
66
- * - The debouncer uses a reactive store for state management
67
- * - Use `initialState` to provide initial state values when creating the async debouncer
68
- * - The state includes canLeadingExecute, error count, execution status, and success/settle counts
69
- * - State can be accessed via the `store` property and its `state` getter
70
- * - The store is reactive and will notify subscribers of state changes
71
- *
72
- * @example
73
- * ```ts
74
- * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
75
- * const results = await searchAPI(value);
76
- * return results; // Return value is preserved
77
- * }, {
78
- * wait: 500,
79
- * onError: (error) => {
80
- * console.error('Search failed:', error);
81
- * }
82
- * });
83
- *
84
- * // Called on each keystroke but only executes after 500ms of no typing
85
- * // Returns the API response directly
86
- * const results = await asyncDebouncer.maybeExecute(inputElement.value);
87
- * ```
88
- */
89
- var AsyncDebouncer = class {
90
- #timeoutId;
91
- #resolvePreviousPromise;
92
- constructor(fn, initialOptions) {
93
- this.fn = fn;
94
- this.store = new _tanstack_store.Store(getDefaultAsyncDebouncerState());
95
- this.asyncRetryers = /* @__PURE__ */ new Map();
96
- this.#timeoutId = null;
97
- this.#resolvePreviousPromise = null;
98
- this.setOptions = (newOptions) => {
99
- this.options = {
100
- ...this.options,
101
- ...newOptions
102
- };
103
- if (!this.#getEnabled()) this.cancel();
104
- };
105
- this.#setState = (newState) => {
106
- this.store.setState((state) => {
107
- const combinedState = {
108
- ...state,
109
- ...newState
110
- };
111
- const { isPending, isExecuting, settleCount } = combinedState;
112
- return {
113
- ...combinedState,
114
- status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : isExecuting ? "executing" : settleCount > 0 ? "settled" : "idle"
115
- };
116
- });
117
- require_event_client.emitChange("AsyncDebouncer", this);
118
- };
119
- this.#getEnabled = () => {
120
- return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
121
- };
122
- this.#getWait = () => {
123
- return require_utils.parseFunctionOrValue(this.options.wait, this);
124
- };
125
- this.maybeExecute = async (...args) => {
126
- if (!this.#getEnabled()) return void 0;
127
- this.#cancelPendingExecution();
128
- this.#setState({
129
- lastArgs: args,
130
- maybeExecuteCount: this.store.state.maybeExecuteCount + 1
131
- });
132
- if (this.options.leading && this.store.state.canLeadingExecute) {
133
- this.#setState({ canLeadingExecute: false });
134
- await this.#execute(...args);
135
- return this.store.state.lastResult;
136
- }
137
- if (this.options.trailing && this.#getEnabled()) this.#setState({ isPending: true });
138
- return new Promise((resolve, reject) => {
139
- this.#resolvePreviousPromise = resolve;
140
- this.#timeoutId = setTimeout(async () => {
141
- if (this.options.trailing && this.store.state.lastArgs) try {
142
- await this.#execute(...this.store.state.lastArgs);
143
- } catch (error) {
144
- reject(error);
145
- }
146
- this.#setState({ canLeadingExecute: true });
147
- this.#resolvePreviousPromise = null;
148
- resolve(this.store.state.lastResult);
149
- }, this.#getWait());
150
- });
151
- };
152
- this.#execute = async (...args) => {
153
- if (!this.#getEnabled()) return void 0;
154
- const currentMaybeExecuteCount = this.store.state.maybeExecuteCount + 1;
155
- try {
156
- this.#setState({ isExecuting: true });
157
- const currentAsyncRetryer = new require_async_retryer.AsyncRetryer(this.fn, {
158
- ...this.options.asyncRetryerOptions,
159
- key: `${this.key}-retryer-${currentMaybeExecuteCount}`
160
- });
161
- this.asyncRetryers.set(currentMaybeExecuteCount, currentAsyncRetryer);
162
- const result = await currentAsyncRetryer.execute(...args);
163
- this.#setState({
164
- lastResult: result,
165
- successCount: this.store.state.successCount + 1
166
- });
167
- this.options.onSuccess?.(result, args, this);
168
- } catch (error) {
169
- this.#setState({ errorCount: this.store.state.errorCount + 1 });
170
- this.options.onError?.(error, args, this);
171
- if (this.options.throwOnError) throw error;
172
- } finally {
173
- this.asyncRetryers.delete(currentMaybeExecuteCount);
174
- this.#setState({
175
- isExecuting: false,
176
- isPending: false,
177
- lastArgs: void 0,
178
- settleCount: this.store.state.settleCount + 1
179
- });
180
- this.options.onSettled?.(args, this);
181
- }
182
- return this.store.state.lastResult;
183
- };
184
- this.flush = async () => {
185
- if (this.store.state.isPending && this.store.state.lastArgs) {
186
- const { lastArgs } = this.store.state;
187
- this.#cancelPendingExecution();
188
- return await this.#execute(...lastArgs);
189
- }
190
- };
191
- this.#resolvePreviousPromiseInternal = () => {
192
- if (this.#resolvePreviousPromise) {
193
- this.#resolvePreviousPromise(this.store.state.lastResult);
194
- this.#resolvePreviousPromise = null;
195
- }
196
- };
197
- this.#clearTimeout = () => {
198
- if (this.#timeoutId) {
199
- clearTimeout(this.#timeoutId);
200
- this.#timeoutId = null;
201
- }
202
- };
203
- this.#cancelPendingExecution = () => {
204
- this.#clearTimeout();
205
- this.#resolvePreviousPromiseInternal();
206
- this.#setState({
207
- isPending: false,
208
- lastArgs: void 0
209
- });
210
- };
211
- this.getAbortSignal = (maybeExecuteCount) => {
212
- const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount;
213
- return this.asyncRetryers.get(count)?.getAbortSignal() ?? null;
214
- };
215
- this.abort = () => {
216
- this.asyncRetryers.forEach((retryer) => retryer.abort());
217
- this.asyncRetryers.clear();
218
- this.#setState({ isExecuting: false });
219
- };
220
- this.cancel = () => {
221
- this.#cancelPendingExecution();
222
- this.#setState({ canLeadingExecute: true });
223
- };
224
- this.reset = () => {
225
- this.#setState(getDefaultAsyncDebouncerState());
226
- this.asyncRetryers.forEach((retryer) => retryer.reset());
227
- };
228
- this.key = initialOptions.key;
229
- this.options = {
230
- ...defaultOptions,
231
- ...initialOptions,
232
- throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
233
- };
234
- this.#setState(this.options.initialState ?? {});
235
- if (this.key) require_event_client.pacerEventClient.on("d-AsyncDebouncer", (event) => {
236
- if (event.payload.key !== this.key) return;
237
- this.#setState(event.payload.store.state);
238
- this.setOptions(event.payload.options);
239
- });
240
- }
241
- #setState;
242
- /**
243
- * Returns the current debouncer enabled state
244
- */
245
- #getEnabled;
246
- /**
247
- * Returns the current debouncer wait state
248
- */
249
- #getWait;
250
- #execute;
251
- #resolvePreviousPromiseInternal;
252
- #clearTimeout;
253
- /**
254
- * Internal cancel without resetting the leading execute state
255
- */
256
- #cancelPendingExecution;
257
- };
258
- /**
259
- * Creates an async debounced function that delays execution until after a specified wait time.
260
- * The debounced function will only execute once the wait period has elapsed without any new calls.
261
- * If called again during the wait period, the timer resets and a new wait period begins.
262
- *
263
- * Async vs Sync Versions:
264
- * The async version provides advanced features over the sync debounce function:
265
- * - Returns promises that can be awaited for debounced function results
266
- * - Built-in retry support via AsyncRetryer integration
267
- * - Abort support to cancel in-flight executions
268
- * - Cancel support to prevent pending executions from starting
269
- * - Comprehensive error handling with onError callbacks and throwOnError control
270
- * - Detailed execution tracking (success/error/settle counts)
271
- *
272
- * The sync debounce function is lighter weight and simpler when you don't need async features,
273
- * return values, or execution control.
274
- *
275
- * What is Debouncing?
276
- * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.
277
- * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
278
- * or input changes where you only want to execute the handler after the events have stopped occurring.
279
- *
280
- * Configuration Options:
281
- * - `wait`: Delay in milliseconds to wait after the last call (required)
282
- * - `leading`: Execute on the leading edge of the timeout (default: false)
283
- * - `trailing`: Execute on the trailing edge of the timeout (default: true)
284
- * - `enabled`: Whether the debouncer is enabled (default: true)
285
- * - `asyncRetryerOptions`: Configure retry behavior for executions
286
- *
287
- * Error Handling:
288
- * - If an `onError` handler is provided, it will be called with the error and debouncer instance
289
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
290
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
291
- * - The error state can be checked using the underlying AsyncDebouncer instance
292
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
293
- *
294
- * State Management:
295
- * - Uses TanStack Store for reactive state management
296
- * - Use `initialState` to provide initial state values when creating the async debouncer
297
- * - Use `onSuccess` callback to react to successful function execution and implement custom logic
298
- * - Use `onError` callback to react to function execution errors and implement custom error handling
299
- * - Use `onSettled` callback to react to function execution completion (success or error) and implement custom logic
300
- * - The state includes canLeadingExecute, error count, execution status, and success/settle counts
301
- * - State can be accessed via `asyncDebouncer.store.state` when using the class directly
302
- * - When using framework adapters (React/Solid), state is accessed from `asyncDebouncer.state`
303
- *
304
- * @example
305
- * ```ts
306
- * const debounced = asyncDebounce(async (value: string) => {
307
- * const result = await saveToAPI(value);
308
- * return result; // Return value is preserved
309
- * }, {
310
- * wait: 1000,
311
- * onError: (error) => {
312
- * console.error('API call failed:', error);
313
- * },
314
- * throwOnError: true // Will both log the error and throw it
315
- * });
316
- *
317
- * // Will only execute once, 1 second after the last call
318
- * // Returns the API response directly
319
- * const result = await debounced("third");
320
- * ```
321
- */
322
- function asyncDebounce(fn, initialOptions) {
323
- return new AsyncDebouncer(fn, initialOptions).maybeExecute;
324
- }
325
-
326
- //#endregion
327
- exports.AsyncDebouncer = AsyncDebouncer;
328
- exports.asyncDebounce = asyncDebounce;
329
- exports.asyncDebouncerOptions = asyncDebouncerOptions;
330
- //# sourceMappingURL=async-debouncer.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"async-debouncer.cjs","names":["Store","#getEnabled","parseFunctionOrValue","#cancelPendingExecution","#setState","#execute","#resolvePreviousPromise","#timeoutId","#getWait","AsyncRetryer","#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,IAAIA,sBAE9D,+BAAoC,CAAC;uCAGvB,IAAI,KAAgC;oBACD;iCAGxC;qBA8BG,eAA0D;GACtE,KAAK,UAAU;IAA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