@tanstack/pacer 0.4.0 → 0.6.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 (70) hide show
  1. package/dist/cjs/async-debouncer.cjs +39 -15
  2. package/dist/cjs/async-debouncer.cjs.map +1 -1
  3. package/dist/cjs/async-debouncer.d.cts +63 -11
  4. package/dist/cjs/async-queuer.cjs +102 -119
  5. package/dist/cjs/async-queuer.cjs.map +1 -1
  6. package/dist/cjs/async-queuer.d.cts +94 -52
  7. package/dist/cjs/async-rate-limiter.cjs +48 -16
  8. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  9. package/dist/cjs/async-rate-limiter.d.cts +74 -9
  10. package/dist/cjs/async-throttler.cjs +42 -17
  11. package/dist/cjs/async-throttler.cjs.map +1 -1
  12. package/dist/cjs/async-throttler.d.cts +62 -10
  13. package/dist/cjs/debouncer.cjs +16 -3
  14. package/dist/cjs/debouncer.cjs.map +1 -1
  15. package/dist/cjs/debouncer.d.cts +14 -4
  16. package/dist/cjs/index.cjs +2 -0
  17. package/dist/cjs/index.cjs.map +1 -1
  18. package/dist/cjs/queuer.cjs +13 -5
  19. package/dist/cjs/queuer.cjs.map +1 -1
  20. package/dist/cjs/queuer.d.cts +9 -3
  21. package/dist/cjs/rate-limiter.cjs +26 -7
  22. package/dist/cjs/rate-limiter.cjs.map +1 -1
  23. package/dist/cjs/rate-limiter.d.cts +20 -6
  24. package/dist/cjs/throttler.cjs +19 -5
  25. package/dist/cjs/throttler.cjs.map +1 -1
  26. package/dist/cjs/throttler.d.cts +15 -4
  27. package/dist/cjs/types.d.cts +1 -0
  28. package/dist/cjs/utils.cjs +18 -7
  29. package/dist/cjs/utils.cjs.map +1 -1
  30. package/dist/cjs/utils.d.cts +3 -0
  31. package/dist/esm/async-debouncer.d.ts +63 -11
  32. package/dist/esm/async-debouncer.js +39 -15
  33. package/dist/esm/async-debouncer.js.map +1 -1
  34. package/dist/esm/async-queuer.d.ts +94 -52
  35. package/dist/esm/async-queuer.js +102 -119
  36. package/dist/esm/async-queuer.js.map +1 -1
  37. package/dist/esm/async-rate-limiter.d.ts +74 -9
  38. package/dist/esm/async-rate-limiter.js +48 -16
  39. package/dist/esm/async-rate-limiter.js.map +1 -1
  40. package/dist/esm/async-throttler.d.ts +62 -10
  41. package/dist/esm/async-throttler.js +42 -17
  42. package/dist/esm/async-throttler.js.map +1 -1
  43. package/dist/esm/debouncer.d.ts +14 -4
  44. package/dist/esm/debouncer.js +16 -3
  45. package/dist/esm/debouncer.js.map +1 -1
  46. package/dist/esm/index.js +3 -1
  47. package/dist/esm/queuer.d.ts +9 -3
  48. package/dist/esm/queuer.js +13 -5
  49. package/dist/esm/queuer.js.map +1 -1
  50. package/dist/esm/rate-limiter.d.ts +20 -6
  51. package/dist/esm/rate-limiter.js +26 -7
  52. package/dist/esm/rate-limiter.js.map +1 -1
  53. package/dist/esm/throttler.d.ts +15 -4
  54. package/dist/esm/throttler.js +19 -5
  55. package/dist/esm/throttler.js.map +1 -1
  56. package/dist/esm/types.d.ts +1 -0
  57. package/dist/esm/utils.d.ts +3 -0
  58. package/dist/esm/utils.js +19 -8
  59. package/dist/esm/utils.js.map +1 -1
  60. package/package.json +9 -3
  61. package/src/async-debouncer.ts +89 -22
  62. package/src/async-queuer.ts +205 -175
  63. package/src/async-rate-limiter.ts +111 -25
  64. package/src/async-throttler.ts +92 -24
  65. package/src/debouncer.ts +24 -7
  66. package/src/queuer.ts +19 -7
  67. package/src/rate-limiter.ts +37 -13
  68. package/src/throttler.ts +28 -9
  69. package/src/types.ts +3 -0
  70. package/src/utils.ts +19 -5
@@ -1,12 +1,7 @@
1
+ import { parseFunctionOrValue } from "./utils.js";
1
2
  const defaultOptions = {
2
3
  enabled: true,
3
4
  leading: false,
4
- onError: () => {
5
- },
6
- onSettled: () => {
7
- },
8
- onSuccess: () => {
9
- },
10
5
  trailing: true,
11
6
  wait: 0
12
7
  };
@@ -23,7 +18,8 @@ class AsyncDebouncer {
23
18
  this._timeoutId = null;
24
19
  this._options = {
25
20
  ...defaultOptions,
26
- ...initialOptions
21
+ ...initialOptions,
22
+ throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
27
23
  };
28
24
  }
29
25
  /**
@@ -43,8 +39,30 @@ class AsyncDebouncer {
43
39
  return this._options;
44
40
  }
45
41
  /**
46
- * Attempts to execute the debounced function
47
- * If a call is already in progress, it will be queued
42
+ * Returns the current debouncer enabled state
43
+ */
44
+ getEnabled() {
45
+ return !!parseFunctionOrValue(this._options.enabled, this);
46
+ }
47
+ /**
48
+ * Returns the current debouncer wait state
49
+ */
50
+ getWait() {
51
+ return parseFunctionOrValue(this._options.wait, this);
52
+ }
53
+ /**
54
+ * Attempts to execute the debounced function.
55
+ * If a call is already in progress, it will be queued.
56
+ *
57
+ * Error Handling:
58
+ * - If the debounced function throws and no `onError` handler is configured,
59
+ * the error will be thrown from this method.
60
+ * - If an `onError` handler is configured, errors will be caught and passed to the handler,
61
+ * and this method will return undefined.
62
+ * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
63
+ *
64
+ * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
65
+ * @throws The error from the debounced function if no onError handler is configured
48
66
  */
49
67
  async maybeExecute(...args) {
50
68
  this._cancel();
@@ -64,26 +82,32 @@ class AsyncDebouncer {
64
82
  }
65
83
  this._canLeadingExecute = true;
66
84
  resolve(this._lastResult);
67
- }, this._options.wait);
85
+ }, this.getWait());
68
86
  });
69
87
  }
70
88
  async executeFunction(...args) {
71
- if (!this._options.enabled) return void 0;
89
+ var _a, _b, _c, _d, _e, _f;
90
+ if (!this.getEnabled()) return void 0;
72
91
  this._abortController = new AbortController();
73
92
  try {
74
93
  this._isExecuting = true;
75
94
  this._lastResult = await this.fn(...args);
76
95
  this._successCount++;
77
- this._options.onSuccess(this._lastResult, this);
96
+ (_b = (_a = this._options).onSuccess) == null ? void 0 : _b.call(_a, this._lastResult, this);
78
97
  } catch (error) {
79
98
  this._errorCount++;
80
- this._options.onError(error, this);
99
+ (_d = (_c = this._options).onError) == null ? void 0 : _d.call(_c, error, this);
100
+ if (this._options.throwOnError) {
101
+ throw error;
102
+ } else {
103
+ console.error(error);
104
+ }
81
105
  } finally {
82
106
  this._isExecuting = false;
83
107
  this._isPending = false;
84
108
  this._settleCount++;
85
109
  this._abortController = null;
86
- this._options.onSettled(this);
110
+ (_f = (_e = this._options).onSettled) == null ? void 0 : _f.call(_e, this);
87
111
  }
88
112
  return this._lastResult;
89
113
  }
@@ -138,7 +162,7 @@ class AsyncDebouncer {
138
162
  * Returns `true` if there is a pending execution queued up for trailing execution
139
163
  */
140
164
  getIsPending() {
141
- return this._options.enabled && this._isPending;
165
+ return this.getEnabled() && this._isPending;
142
166
  }
143
167
  /**
144
168
  * Returns `true` if there is currently an execution in progress
@@ -1 +1 @@
1
- {"version":3,"file":"async-debouncer.js","sources":["../../src/async-debouncer.ts"],"sourcesContent":["import type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\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 */\n onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSettled?: (debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<TFn>) => void\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 * Defaults to 0ms\n */\n wait: number\n}\n\nconst defaultOptions: Required<AsyncDebouncerOptions<any>> = {\n enabled: true,\n leading: false,\n onError: () => {},\n onSettled: () => {},\n onSuccess: () => {},\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\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 * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\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 * }, { wait: 500 });\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 private _abortController: AbortController | null = null\n private _canLeadingExecute = true\n private _errorCount = 0\n private _isExecuting = false\n private _isPending = false\n private _lastArgs: Parameters<TFn> | undefined\n private _lastResult: ReturnType<TFn> | undefined\n private _options: Required<AsyncDebouncerOptions<TFn>>\n private _settleCount = 0\n private _successCount = 0\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the debouncer options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this._isPending = false\n }\n }\n\n /**\n * Returns the current debouncer options\n */\n getOptions(): Required<AsyncDebouncerOptions<TFn>> {\n return this._options\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this._cancel()\n this._lastArgs = args\n\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this._canLeadingExecute = false\n await this.executeFunction(...args)\n return this._lastResult\n }\n\n // Handle trailing execution\n if (this._options.trailing) {\n this._isPending = true\n }\n\n return new Promise((resolve) => {\n this._timeoutId = setTimeout(async () => {\n // Execute trailing if enabled\n if (this._options.trailing && this._lastArgs) {\n await this.executeFunction(...this._lastArgs)\n }\n\n // Reset state and resolve\n this._canLeadingExecute = true\n resolve(this._lastResult)\n }, this._options.wait)\n })\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this._options.enabled) return undefined\n this._abortController = new AbortController()\n try {\n this._isExecuting = true\n this._lastResult = await this.fn(...args) // EXECUTE!\n this._successCount++\n this._options.onSuccess(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError(error, this)\n } finally {\n this._isExecuting = false\n this._isPending = false\n this._settleCount++\n this._abortController = null\n this._options.onSettled(this)\n }\n return this._lastResult\n }\n\n /**\n * Cancel without resetting _canLeadingExecute\n */\n private _cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n if (this._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._lastArgs = undefined\n this._isPending = false\n this._isExecuting = false\n }\n\n /**\n * Cancels any pending execution or aborts any execution in progress\n */\n cancel(): void {\n this._canLeadingExecute = true\n this._cancel()\n }\n\n /**\n * Returns the last result of the debounced function\n */\n getLastResult(): ReturnType<TFn> | undefined {\n return this._lastResult\n }\n\n /**\n * Returns the number of times the function has been executed successfully\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has settled (completed or errored)\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns `true` if there is a pending execution queued up for trailing execution\n */\n getIsPending(): boolean {\n return this._options.enabled && this._isPending\n }\n\n /**\n * Returns `true` if there is currently an execution in progress\n */\n getIsExecuting(): boolean {\n return this._isExecuting\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 * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\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 * }, { wait: 1000 });\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: Omit<AsyncDebouncerOptions<TFn>, 'enabled'>,\n) {\n const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)\n return asyncDebouncer.maybeExecute.bind(asyncDebouncer)\n}\n"],"names":[],"mappings":"AAwCA,MAAM,iBAAuD;AAAA,EAC3D,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU;AAAA,EACV,MAAM;AACR;AA4BO,MAAM,eAA6C;AAAA,EAaxD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAbV,SAAQ,mBAA2C;AACnD,SAAQ,qBAAqB;AAC7B,SAAQ,cAAc;AACtB,SAAQ,eAAe;AACvB,SAAQ,aAAa;AAIrB,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;AACxB,SAAQ,aAAoC;AAM1C,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AA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IAAA;AAE9B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMN,UAAgB;AACtB,QAAI,KAAK,YAAY;AACnB,mBAAa,KAAK,UAAU;AAC5B,WAAK,aAAa;AAAA,IAAA;AAEpB,QAAI,KAAK,kBAAkB;AACzB,WAAK,iBAAiB,MAAM;AAC5B,WAAK,mBAAmB;AAAA,IAAA;AAE1B,SAAK,YAAY;AACjB,SAAK,aAAa;AAClB,SAAK,eAAe;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMtB,SAAe;AACb,SAAK,qBAAqB;AAC1B,SAAK,QAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMf,gBAA6C;AAC3C,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,kBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAAyB;AACvB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,gBAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACf,WAAA,KAAK,SAAS,WAAW,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMvC,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAEhB;AAuBgB,SAAA,cACd,IACA,gBACA;AACA,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;"}
1
+ {"version":3,"file":"async-debouncer.js","sources":["../../src/async-debouncer.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction, OptionalKeys } from './types'\n\n/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {\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 * 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?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSettled?: (debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<TFn>) => 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\ntype AsyncDebouncerOptionsWithOptionalCallbacks = OptionalKeys<\n AsyncDebouncerOptions<any>,\n 'onError' | 'onSettled' | 'onSuccess'\n>\n\nconst defaultOptions: AsyncDebouncerOptionsWithOptionalCallbacks = {\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 * 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 * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an error occurs during execution and no `onError` handler is provided, the error will be thrown and propagate up to the caller.\n * - If an `onError` handler is provided, errors will be caught and passed to the handler instead of being thrown.\n * - The error count can be tracked using `getErrorCount()`.\n * - The debouncer maintains its state and can continue to be used after an error occurs.\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 private _options: AsyncDebouncerOptionsWithOptionalCallbacks\n private _abortController: AbortController | null = null\n private _canLeadingExecute = true\n private _errorCount = 0\n private _isExecuting = false\n private _isPending = false\n private _lastArgs: Parameters<TFn> | undefined\n private _lastResult: ReturnType<TFn> | undefined\n private _settleCount = 0\n private _successCount = 0\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n }\n\n /**\n * Updates the debouncer options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this._isPending = false\n }\n }\n\n /**\n * Returns the current debouncer options\n */\n getOptions(): AsyncDebouncerOptions<TFn> {\n return this._options\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 async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this._cancel()\n this._lastArgs = args\n\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this._canLeadingExecute = false\n await this.executeFunction(...args)\n return this._lastResult\n }\n\n // Handle trailing execution\n if (this._options.trailing) {\n this._isPending = true\n }\n\n return new Promise((resolve) => {\n this._timeoutId = setTimeout(async () => {\n // Execute trailing if enabled\n if (this._options.trailing && this._lastArgs) {\n await this.executeFunction(...this._lastArgs)\n }\n\n // Reset state and resolve\n this._canLeadingExecute = true\n resolve(this._lastResult)\n }, this.getWait())\n })\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this.getEnabled()) return undefined\n this._abortController = new AbortController()\n try {\n this._isExecuting = true\n this._lastResult = await this.fn(...args) // EXECUTE!\n this._successCount++\n this._options.onSuccess?.(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError?.(error, this)\n if (this._options.throwOnError) {\n throw error\n } else {\n console.error(error)\n }\n } finally {\n this._isExecuting = false\n this._isPending = false\n this._settleCount++\n this._abortController = null\n this._options.onSettled?.(this)\n }\n return this._lastResult\n }\n\n /**\n * Cancel without resetting _canLeadingExecute\n */\n private _cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n if (this._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._lastArgs = undefined\n this._isPending = false\n this._isExecuting = false\n }\n\n /**\n * Cancels any pending execution or aborts any execution in progress\n */\n cancel(): void {\n this._canLeadingExecute = true\n this._cancel()\n }\n\n /**\n * Returns the last result of the debounced function\n */\n getLastResult(): ReturnType<TFn> | undefined {\n return this._lastResult\n }\n\n /**\n * Returns the number of times the function has been executed successfully\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has settled (completed or errored)\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns `true` if there is a pending execution queued up for trailing execution\n */\n getIsPending(): boolean {\n return this.getEnabled() && this._isPending\n }\n\n /**\n * Returns `true` if there is currently an execution in progress\n */\n getIsExecuting(): boolean {\n return this._isExecuting\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 * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\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 * @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.bind(asyncDebouncer)\n}\n"],"names":[],"mappings":";AAwDA,MAAM,i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AAA,EAMf,gBAA6C;AAC3C,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,kBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAAyB;AACvB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,gBAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACf,WAAA,KAAK,gBAAgB,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMnC,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAEhB;AAoCgB,SAAA,cACd,IACA,gBACA;AACA,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;"}
@@ -1,14 +1,20 @@
1
+ import { AnyAsyncFunction } from './types.js';
1
2
  import { QueuePosition } from './queuer.js';
2
- export interface AsyncQueuerOptions<TValue> {
3
+ export type AsyncQueuerFn = AnyAsyncFunction & {
4
+ priority?: number;
5
+ };
6
+ export interface AsyncQueuerOptions<TFn extends AsyncQueuerFn> {
3
7
  /**
4
8
  * Default position to add items to the queuer
5
9
  * @default 'back'
6
10
  */
7
11
  addItemsTo?: QueuePosition;
8
12
  /**
9
- * Maximum number of concurrent tasks to process
13
+ * Maximum number of concurrent tasks to process.
14
+ * Can be a number or a function that returns a number.
15
+ * @default 1
10
16
  */
11
- concurrency?: number;
17
+ concurrency?: number | ((queuer: AsyncQueuer<TFn>) => number);
12
18
  /**
13
19
  * Maximum time in milliseconds that an item can stay in the queue
14
20
  * If not provided, items will never expire
@@ -18,7 +24,7 @@ export interface AsyncQueuerOptions<TValue> {
18
24
  * Function to determine if an item has expired
19
25
  * If provided, this overrides the expirationDuration behavior
20
26
  */
21
- getIsExpired?: (item: () => Promise<TValue>, addedAt: number) => boolean;
27
+ getIsExpired?: (item: TFn, addedAt: number) => boolean;
22
28
  /**
23
29
  * Default position to get items from during processing
24
30
  * @default 'front'
@@ -29,45 +35,67 @@ export interface AsyncQueuerOptions<TValue> {
29
35
  * Higher priority items will be processed first
30
36
  * If not provided, will use static priority values attached to tasks
31
37
  */
32
- getPriority?: (item: () => Promise<TValue>) => number;
38
+ getPriority?: (item: TFn) => number;
33
39
  /**
34
40
  * Initial items to populate the queuer with
35
41
  */
36
- initialItems?: Array<(() => Promise<TValue>) & {
42
+ initialItems?: Array<TFn & {
37
43
  priority?: number;
38
44
  }>;
39
45
  /**
40
46
  * Maximum number of items allowed in the queuer
41
47
  */
42
48
  maxSize?: number;
49
+ /**
50
+ * Optional error handler for when a task throws.
51
+ * If provided, the handler will be called with the error and queuer instance.
52
+ * This can be used alongside throwOnError - the handler will be called before any error is thrown.
53
+ */
54
+ onError?: (error: unknown, queuer: AsyncQueuer<TFn>) => void;
55
+ /**
56
+ * Callback fired whenever an item expires in the queuer
57
+ */
58
+ onExpire?: (item: TFn, queuer: AsyncQueuer<TFn>) => void;
43
59
  /**
44
60
  * Callback fired whenever an item is removed from the queuer
45
61
  */
46
- onGetNextItem?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
62
+ onGetNextItem?: (item: TFn, queuer: AsyncQueuer<TFn>) => void;
47
63
  /**
48
64
  * Callback fired whenever the queuer's running state changes
49
65
  */
50
- onIsRunningChange?: (queuer: AsyncQueuer<TValue>) => void;
66
+ onIsRunningChange?: (queuer: AsyncQueuer<TFn>) => void;
51
67
  /**
52
68
  * Callback fired whenever an item is added or removed from the queuer
53
69
  */
54
- onItemsChange?: (queuer: AsyncQueuer<TValue>) => void;
70
+ onItemsChange?: (queuer: AsyncQueuer<TFn>) => void;
55
71
  /**
56
72
  * Callback fired whenever an item is rejected from being added to the queuer
57
73
  */
58
- onReject?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
74
+ onReject?: (item: TFn, queuer: AsyncQueuer<TFn>) => void;
59
75
  /**
60
- * Callback fired whenever an item expires in the queuer
76
+ * Optional callback to call when a task is settled
77
+ */
78
+ onSettled?: (queuer: AsyncQueuer<TFn>) => void;
79
+ /**
80
+ * Optional callback to call when a task succeeds
61
81
  */
62
- onExpire?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void;
82
+ onSuccess?: (result: TFn, queuer: AsyncQueuer<TFn>) => void;
63
83
  /**
64
84
  * Whether the queuer should start processing tasks immediately or not.
65
85
  */
66
86
  started?: boolean;
67
87
  /**
68
- * Time in milliseconds to wait between processing items
88
+ * Whether to throw errors when they occur.
89
+ * Defaults to true if no onError handler is provided, false if an onError handler is provided.
90
+ * Can be explicitly set to override these defaults.
91
+ */
92
+ throwOnError?: boolean;
93
+ /**
94
+ * Time in milliseconds to wait between processing items.
95
+ * Can be a number or a function that returns a number.
96
+ * @default 0
69
97
  */
70
- wait?: number;
98
+ wait?: number | ((queuer: AsyncQueuer<TFn>) => number);
71
99
  }
72
100
  /**
73
101
  * A flexible asynchronous queue that processes tasks with configurable concurrency control.
@@ -84,44 +112,59 @@ export interface AsyncQueuerOptions<TValue> {
84
112
  * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,
85
113
  * the next pending task is processed if below the concurrency limit.
86
114
  *
115
+ * Error Handling:
116
+ * - If an `onError` handler is provided, it will be called with the error and queuer instance
117
+ * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
118
+ * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
119
+ * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
120
+ * - The error state can be checked using the underlying AsyncQueuer instance
121
+ *
87
122
  * @example
88
123
  * ```ts
89
- * const asyncQueuer = new AsyncQueuer<string>({ concurrency: 2 });
124
+ * const asyncQueuer = new AsyncQueuer<string>({
125
+ * concurrency: 2,
126
+ * onSuccess: (result) => {
127
+ * console.log(result); // 'Hello'
128
+ * }
129
+ * });
90
130
  *
91
131
  * asyncQueuer.addItem(async () => {
92
132
  * return 'Hello';
93
133
  * });
94
134
  *
95
135
  * asyncQueuer.start();
96
- *
97
- * asyncQueuer.onSuccess((result) => {
98
- * console.log(result); // 'Hello'
99
- * });
100
136
  * ```
101
137
  */
102
- export declare class AsyncQueuer<TValue> {
138
+ export declare class AsyncQueuer<TFn extends AsyncQueuerFn> {
103
139
  private _options;
104
140
  private _activeItems;
105
- private _executionCount;
141
+ private _successCount;
142
+ private _errorCount;
143
+ private _settledCount;
106
144
  private _rejectionCount;
107
145
  private _expirationCount;
108
146
  private _items;
109
147
  private _itemTimestamps;
110
- private _onErrorCallbacks;
111
- private _onSettledCallbacks;
112
- private _onSuccessCallbacks;
113
148
  private _pendingTick;
114
149
  private _running;
115
- constructor(initialOptions?: AsyncQueuerOptions<TValue>);
150
+ constructor(initialOptions?: AsyncQueuerOptions<TFn>);
116
151
  /**
117
152
  * Updates the queuer options
118
153
  * Returns the new options state
119
154
  */
120
- setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>): void;
155
+ setOptions(newOptions: Partial<AsyncQueuerOptions<TFn>>): void;
121
156
  /**
122
157
  * Returns the current queuer options
123
158
  */
124
- getOptions(): Required<AsyncQueuerOptions<TValue>>;
159
+ getOptions(): AsyncQueuerOptions<TFn>;
160
+ /**
161
+ * Returns the current wait time between processing items
162
+ */
163
+ getWait(): number;
164
+ /**
165
+ * Returns the current concurrency limit
166
+ */
167
+ getConcurrency(): number;
125
168
  /**
126
169
  * Processes items in the queuer
127
170
  */
@@ -149,17 +192,15 @@ export declare class AsyncQueuer<TValue> {
149
192
  /**
150
193
  * Adds a task to the queuer
151
194
  */
152
- addItem(fn: (() => Promise<TValue>) & {
153
- priority?: number;
154
- }, position?: QueuePosition, runOnUpdate?: boolean): Promise<TValue>;
195
+ addItem(fn: TFn, position?: QueuePosition, runOnItemsChange?: boolean): void;
155
196
  /**
156
197
  * Removes and returns an item from the queuer
157
198
  */
158
- getNextItem(position?: QueuePosition): (() => Promise<TValue>) | undefined;
199
+ getNextItem(position?: QueuePosition): TFn | undefined;
159
200
  /**
160
201
  * Returns an item without removing it
161
202
  */
162
- getPeek(position?: QueuePosition): (() => Promise<TValue>) | undefined;
203
+ getPeek(position?: QueuePosition): TFn | undefined;
163
204
  /**
164
205
  * Returns true if the queuer is empty
165
206
  */
@@ -175,19 +216,27 @@ export declare class AsyncQueuer<TValue> {
175
216
  /**
176
217
  * Returns a copy of all items in the queuer
177
218
  */
178
- getAllItems(): Array<() => Promise<TValue>>;
219
+ getAllItems(): Array<TFn>;
179
220
  /**
180
221
  * Returns the active items
181
222
  */
182
- getActiveItems(): Array<() => Promise<TValue>>;
223
+ getActiveItems(): Array<TFn>;
183
224
  /**
184
225
  * Returns the pending items
185
226
  */
186
- getPendingItems(): Array<() => Promise<TValue>>;
227
+ getPendingItems(): Array<TFn>;
228
+ /**
229
+ * Returns the number of items that have been successfully processed
230
+ */
231
+ getSuccessCount(): number;
232
+ /**
233
+ * Returns the number of items that have failed processing
234
+ */
235
+ getErrorCount(): number;
187
236
  /**
188
- * Returns the number of items that have been removed from the queuer
237
+ * Returns the number of items that have completed processing (success or error)
189
238
  */
190
- getExecutionCount(): number;
239
+ getSettledCount(): number;
191
240
  /**
192
241
  * Returns the number of items that have been rejected from the queuer
193
242
  */
@@ -200,18 +249,6 @@ export declare class AsyncQueuer<TValue> {
200
249
  * Returns true if the queuer is running but has no items to process
201
250
  */
202
251
  getIsIdle(): boolean;
203
- /**
204
- * Adds a callback to be called when a task succeeds
205
- */
206
- onSuccess(cb: (result: TValue) => void): () => void;
207
- /**
208
- * Adds a callback to be called when a task errors
209
- */
210
- onError(cb: (error: Error) => void): () => void;
211
- /**
212
- * Adds a callback to be called when a task is settled
213
- */
214
- onSettled(cb: (result: TValue | Error) => void): () => void;
215
252
  /**
216
253
  * Returns the number of items that have expired from the queuer
217
254
  */
@@ -221,6 +258,13 @@ export declare class AsyncQueuer<TValue> {
221
258
  * Creates a new AsyncQueuer instance with the given options and returns a bound addItem function.
222
259
  * The queuer is automatically started and ready to process items.
223
260
  *
261
+ * Error Handling:
262
+ * - If an `onError` handler is provided, it will be called with the error and queuer instance
263
+ * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
264
+ * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
265
+ * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
266
+ * - The error state can be checked using the underlying AsyncQueuer instance
267
+ *
224
268
  * @example
225
269
  * ```ts
226
270
  * const enqueue = asyncQueue<string>();
@@ -234,6 +278,4 @@ export declare class AsyncQueuer<TValue> {
234
278
  * @param options - Configuration options for the AsyncQueuer
235
279
  * @returns A bound addItem function that can be used to add tasks to the queuer
236
280
  */
237
- export declare function asyncQueue<TValue>(options?: Omit<AsyncQueuerOptions<TValue>, 'started'>): (fn: (() => Promise<TValue>) & {
238
- priority?: number;
239
- }, position?: QueuePosition, runOnUpdate?: boolean) => Promise<TValue>;
281
+ export declare function asyncQueue<TFn extends AsyncQueuerFn>(options: AsyncQueuerOptions<TFn>): (fn: TFn, position?: QueuePosition, runOnItemsChange?: boolean) => void;