@tanstack/pacer 0.6.0 → 0.7.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 (71) hide show
  1. package/dist/cjs/async-debouncer.cjs +10 -6
  2. package/dist/cjs/async-debouncer.cjs.map +1 -1
  3. package/dist/cjs/async-debouncer.d.cts +2 -2
  4. package/dist/cjs/async-queuer.cjs +135 -106
  5. package/dist/cjs/async-queuer.cjs.map +1 -1
  6. package/dist/cjs/async-queuer.d.cts +121 -93
  7. package/dist/cjs/async-rate-limiter.cjs +3 -4
  8. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  9. package/dist/cjs/async-rate-limiter.d.cts +1 -2
  10. package/dist/cjs/async-throttler.cjs +14 -4
  11. package/dist/cjs/async-throttler.cjs.map +1 -1
  12. package/dist/cjs/async-throttler.d.cts +3 -2
  13. package/dist/cjs/batcher.cjs +138 -0
  14. package/dist/cjs/batcher.cjs.map +1 -0
  15. package/dist/cjs/batcher.d.cts +149 -0
  16. package/dist/cjs/debouncer.cjs +3 -4
  17. package/dist/cjs/debouncer.cjs.map +1 -1
  18. package/dist/cjs/debouncer.d.cts +1 -2
  19. package/dist/cjs/index.cjs +3 -0
  20. package/dist/cjs/index.cjs.map +1 -1
  21. package/dist/cjs/index.d.cts +1 -0
  22. package/dist/cjs/queuer.cjs +68 -41
  23. package/dist/cjs/queuer.cjs.map +1 -1
  24. package/dist/cjs/queuer.d.cts +123 -92
  25. package/dist/cjs/rate-limiter.cjs +3 -4
  26. package/dist/cjs/rate-limiter.cjs.map +1 -1
  27. package/dist/cjs/rate-limiter.d.cts +1 -2
  28. package/dist/cjs/throttler.cjs +3 -4
  29. package/dist/cjs/throttler.cjs.map +1 -1
  30. package/dist/cjs/throttler.d.cts +1 -2
  31. package/dist/esm/async-debouncer.d.ts +2 -2
  32. package/dist/esm/async-debouncer.js +10 -6
  33. package/dist/esm/async-debouncer.js.map +1 -1
  34. package/dist/esm/async-queuer.d.ts +121 -93
  35. package/dist/esm/async-queuer.js +135 -106
  36. package/dist/esm/async-queuer.js.map +1 -1
  37. package/dist/esm/async-rate-limiter.d.ts +1 -2
  38. package/dist/esm/async-rate-limiter.js +3 -4
  39. package/dist/esm/async-rate-limiter.js.map +1 -1
  40. package/dist/esm/async-throttler.d.ts +3 -2
  41. package/dist/esm/async-throttler.js +14 -4
  42. package/dist/esm/async-throttler.js.map +1 -1
  43. package/dist/esm/batcher.d.ts +149 -0
  44. package/dist/esm/batcher.js +138 -0
  45. package/dist/esm/batcher.js.map +1 -0
  46. package/dist/esm/debouncer.d.ts +1 -2
  47. package/dist/esm/debouncer.js +3 -4
  48. package/dist/esm/debouncer.js.map +1 -1
  49. package/dist/esm/index.d.ts +1 -0
  50. package/dist/esm/index.js +3 -0
  51. package/dist/esm/index.js.map +1 -1
  52. package/dist/esm/queuer.d.ts +123 -92
  53. package/dist/esm/queuer.js +68 -41
  54. package/dist/esm/queuer.js.map +1 -1
  55. package/dist/esm/rate-limiter.d.ts +1 -2
  56. package/dist/esm/rate-limiter.js +3 -4
  57. package/dist/esm/rate-limiter.js.map +1 -1
  58. package/dist/esm/throttler.d.ts +1 -2
  59. package/dist/esm/throttler.js +3 -4
  60. package/dist/esm/throttler.js.map +1 -1
  61. package/package.json +11 -1
  62. package/src/async-debouncer.ts +12 -6
  63. package/src/async-queuer.ts +216 -193
  64. package/src/async-rate-limiter.ts +3 -4
  65. package/src/async-throttler.ts +18 -4
  66. package/src/batcher.ts +253 -0
  67. package/src/debouncer.ts +3 -4
  68. package/src/index.ts +1 -0
  69. package/src/queuer.ts +142 -98
  70. package/src/rate-limiter.ts +3 -4
  71. package/src/throttler.ts +3 -4
@@ -1 +1 @@
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 as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AAA;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,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
+ {"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 private _resolvePreviousPromise:\n | ((value?: ReturnType<TFn> | undefined) => void)\n | 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 */\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.execute(...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._resolvePreviousPromise = resolve\n this._timeoutId = setTimeout(async () => {\n // Execute trailing if enabled\n if (this._options.trailing && this._lastArgs) {\n await this.execute(...this._lastArgs)\n }\n\n // Reset state and resolve\n this._canLeadingExecute = true\n this._resolvePreviousPromise = null\n resolve(this._lastResult)\n }, this.getWait())\n })\n }\n\n private async execute(\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 }\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 if (this._resolvePreviousPromise) {\n this._resolvePreviousPromise(this._lastResult)\n this._resolvePreviousPromise = 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,iBAA6D;AAAA,EACjE,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,MAAM;AACR;AAuCO,MAAM,eAA6C;AAAA,EAgBxD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAfV,SAAQ,mBAA2C;AACnD,SAAQ,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Md,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,9 +1,5 @@
1
- import { AnyAsyncFunction } from './types.js';
2
1
  import { QueuePosition } from './queuer.js';
3
- export type AsyncQueuerFn = AnyAsyncFunction & {
4
- priority?: number;
5
- };
6
- export interface AsyncQueuerOptions<TFn extends AsyncQueuerFn> {
2
+ export interface AsyncQueuerOptions<TValue> {
7
3
  /**
8
4
  * Default position to add items to the queuer
9
5
  * @default 'back'
@@ -14,7 +10,7 @@ export interface AsyncQueuerOptions<TFn extends AsyncQueuerFn> {
14
10
  * Can be a number or a function that returns a number.
15
11
  * @default 1
16
12
  */
17
- concurrency?: number | ((queuer: AsyncQueuer<TFn>) => number);
13
+ concurrency?: number | ((queuer: AsyncQueuer<TValue>) => number);
18
14
  /**
19
15
  * Maximum time in milliseconds that an item can stay in the queue
20
16
  * If not provided, items will never expire
@@ -24,7 +20,7 @@ export interface AsyncQueuerOptions<TFn extends AsyncQueuerFn> {
24
20
  * Function to determine if an item has expired
25
21
  * If provided, this overrides the expirationDuration behavior
26
22
  */
27
- getIsExpired?: (item: TFn, addedAt: number) => boolean;
23
+ getIsExpired?: (item: TValue, addedAt: number) => boolean;
28
24
  /**
29
25
  * Default position to get items from during processing
30
26
  * @default 'front'
@@ -35,13 +31,11 @@ export interface AsyncQueuerOptions<TFn extends AsyncQueuerFn> {
35
31
  * Higher priority items will be processed first
36
32
  * If not provided, will use static priority values attached to tasks
37
33
  */
38
- getPriority?: (item: TFn) => number;
34
+ getPriority?: (item: TValue) => number;
39
35
  /**
40
36
  * Initial items to populate the queuer with
41
37
  */
42
- initialItems?: Array<TFn & {
43
- priority?: number;
44
- }>;
38
+ initialItems?: Array<TValue>;
45
39
  /**
46
40
  * Maximum number of items allowed in the queuer
47
41
  */
@@ -51,35 +45,31 @@ export interface AsyncQueuerOptions<TFn extends AsyncQueuerFn> {
51
45
  * If provided, the handler will be called with the error and queuer instance.
52
46
  * This can be used alongside throwOnError - the handler will be called before any error is thrown.
53
47
  */
54
- onError?: (error: unknown, queuer: AsyncQueuer<TFn>) => void;
48
+ onError?: (error: unknown, queuer: AsyncQueuer<TValue>) => void;
55
49
  /**
56
50
  * Callback fired whenever an item expires in the queuer
57
51
  */
58
- onExpire?: (item: TFn, queuer: AsyncQueuer<TFn>) => void;
59
- /**
60
- * Callback fired whenever an item is removed from the queuer
61
- */
62
- onGetNextItem?: (item: TFn, queuer: AsyncQueuer<TFn>) => void;
52
+ onExpire?: (item: TValue, queuer: AsyncQueuer<TValue>) => void;
63
53
  /**
64
54
  * Callback fired whenever the queuer's running state changes
65
55
  */
66
- onIsRunningChange?: (queuer: AsyncQueuer<TFn>) => void;
56
+ onIsRunningChange?: (queuer: AsyncQueuer<TValue>) => void;
67
57
  /**
68
58
  * Callback fired whenever an item is added or removed from the queuer
69
59
  */
70
- onItemsChange?: (queuer: AsyncQueuer<TFn>) => void;
60
+ onItemsChange?: (queuer: AsyncQueuer<TValue>) => void;
71
61
  /**
72
62
  * Callback fired whenever an item is rejected from being added to the queuer
73
63
  */
74
- onReject?: (item: TFn, queuer: AsyncQueuer<TFn>) => void;
64
+ onReject?: (item: TValue, queuer: AsyncQueuer<TValue>) => void;
75
65
  /**
76
66
  * Optional callback to call when a task is settled
77
67
  */
78
- onSettled?: (queuer: AsyncQueuer<TFn>) => void;
68
+ onSettled?: (queuer: AsyncQueuer<TValue>) => void;
79
69
  /**
80
70
  * Optional callback to call when a task succeeds
81
71
  */
82
- onSuccess?: (result: TFn, queuer: AsyncQueuer<TFn>) => void;
72
+ onSuccess?: (result: TValue, queuer: AsyncQueuer<TValue>) => void;
83
73
  /**
84
74
  * Whether the queuer should start processing tasks immediately or not.
85
75
  */
@@ -95,47 +85,48 @@ export interface AsyncQueuerOptions<TFn extends AsyncQueuerFn> {
95
85
  * Can be a number or a function that returns a number.
96
86
  * @default 0
97
87
  */
98
- wait?: number | ((queuer: AsyncQueuer<TFn>) => number);
88
+ wait?: number | ((queuer: AsyncQueuer<TValue>) => number);
99
89
  }
100
90
  /**
101
- * A flexible asynchronous queue that processes tasks with configurable concurrency control.
91
+ * A flexible asynchronous queue for processing tasks with configurable concurrency, priority, and expiration.
102
92
  *
103
93
  * Features:
104
- * - Priority queue support via getPriority option
94
+ * - Priority queue support via the getPriority option
105
95
  * - Configurable concurrency limit
106
- * - Task success/error/completion callbacks
96
+ * - Callbacks for task success, error, completion, and queue state changes
107
97
  * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior
108
- * - Pause/resume task processing
98
+ * - Pause and resume processing
109
99
  * - Task cancellation
110
- * - Item expiration to clear stale items from the queue
100
+ * - Item expiration to remove stale items from the queue
111
101
  *
112
102
  * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,
113
- * the next pending task is processed if below the concurrency limit.
103
+ * the next pending task is processed if the concurrency limit allows.
114
104
  *
115
105
  * Error Handling:
116
106
  * - If an `onError` handler is provided, it will be called with the error and queuer instance
117
107
  * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
118
108
  * - 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
109
+ * - Both onError and throwOnError can be used together; the handler will be called before any error is thrown
110
+ * - The error state can be checked using the AsyncQueuer instance
121
111
  *
122
- * @example
112
+ * Example usage:
123
113
  * ```ts
124
- * const asyncQueuer = new AsyncQueuer<string>({
114
+ * const asyncQueuer = new AsyncQueuer<string>(async (item) => {
115
+ * // process item
116
+ * return item.toUpperCase();
117
+ * }, {
125
118
  * concurrency: 2,
126
119
  * onSuccess: (result) => {
127
- * console.log(result); // 'Hello'
120
+ * console.log(result);
128
121
  * }
129
122
  * });
130
123
  *
131
- * asyncQueuer.addItem(async () => {
132
- * return 'Hello';
133
- * });
134
- *
124
+ * asyncQueuer.addItem('hello');
135
125
  * asyncQueuer.start();
136
126
  * ```
137
127
  */
138
- export declare class AsyncQueuer<TFn extends AsyncQueuerFn> {
128
+ export declare class AsyncQueuer<TValue> {
129
+ private fn;
139
130
  private _options;
140
131
  private _activeItems;
141
132
  private _successCount;
@@ -147,135 +138,172 @@ export declare class AsyncQueuer<TFn extends AsyncQueuerFn> {
147
138
  private _itemTimestamps;
148
139
  private _pendingTick;
149
140
  private _running;
150
- constructor(initialOptions?: AsyncQueuerOptions<TFn>);
141
+ private _lastResult;
142
+ constructor(fn: (value: TValue) => Promise<any>, initialOptions: AsyncQueuerOptions<TValue>);
151
143
  /**
152
- * Updates the queuer options
153
- * Returns the new options state
144
+ * Updates the queuer options. New options are merged with existing options.
154
145
  */
155
- setOptions(newOptions: Partial<AsyncQueuerOptions<TFn>>): void;
146
+ setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>): void;
156
147
  /**
157
- * Returns the current queuer options
148
+ * Returns the current queuer options, including defaults and any overrides.
158
149
  */
159
- getOptions(): AsyncQueuerOptions<TFn>;
150
+ getOptions(): AsyncQueuerOptions<TValue>;
160
151
  /**
161
- * Returns the current wait time between processing items
152
+ * Returns the current wait time (in milliseconds) between processing items.
153
+ * If a function is provided, it is called with the queuer instance.
162
154
  */
163
155
  getWait(): number;
164
156
  /**
165
- * Returns the current concurrency limit
157
+ * Returns the current concurrency limit for processing items.
158
+ * If a function is provided, it is called with the queuer instance.
166
159
  */
167
160
  getConcurrency(): number;
168
161
  /**
169
- * Processes items in the queuer
162
+ * Processes items in the queue up to the concurrency limit. Internal use only.
170
163
  */
171
164
  private tick;
172
165
  /**
173
- * Checks for and removes expired items from the queuer
174
- */
175
- private checkExpiredItems;
176
- /**
177
- * Starts the queuer and processes items
166
+ * Starts processing items in the queue. If already running, does nothing.
178
167
  */
179
- start(): Promise<void>;
168
+ start(): void;
180
169
  /**
181
- * Stops the queuer from processing items
170
+ * Stops processing items in the queue. Does not clear the queue.
182
171
  */
183
172
  stop(): void;
184
173
  /**
185
- * Removes all items from the queuer
174
+ * Removes all pending items from the queue. Does not affect active tasks.
186
175
  */
187
176
  clear(): void;
188
177
  /**
189
- * Resets the queuer to its initial state
178
+ * Resets the queuer to its initial state. Optionally repopulates with initial items.
179
+ * Does not affect callbacks or options.
190
180
  */
191
181
  reset(withInitialItems?: boolean): void;
192
182
  /**
193
- * Adds a task to the queuer
183
+ * Adds an item to the queue. If the queue is full, the item is rejected and onReject is called.
184
+ * Items can be inserted based on priority or at the front/back depending on configuration.
185
+ *
186
+ * @example
187
+ * ```ts
188
+ * queuer.addItem({ value: 'task', priority: 10 });
189
+ * queuer.addItem('task2', 'front');
190
+ * ```
194
191
  */
195
- addItem(fn: TFn, position?: QueuePosition, runOnItemsChange?: boolean): void;
196
- /**
197
- * Removes and returns an item from the queuer
192
+ addItem(item: TValue & {
193
+ priority?: number;
194
+ }, position?: QueuePosition, runOnItemsChange?: boolean): void;
195
+ /**
196
+ * Removes and returns the next item from the queue without executing the task function.
197
+ * Use for manual queue management. Normally, use execute() to process items.
198
+ *
199
+ * @example
200
+ * ```ts
201
+ * // FIFO
202
+ * queuer.getNextItem();
203
+ * // LIFO
204
+ * queuer.getNextItem('back');
205
+ * ```
206
+ */
207
+ getNextItem(position?: QueuePosition): TValue | undefined;
208
+ /**
209
+ * Removes and returns the next item from the queue and executes the task function with it.
210
+ *
211
+ * @example
212
+ * ```ts
213
+ * queuer.execute();
214
+ * // LIFO
215
+ * queuer.execute('back');
216
+ * ```
217
+ */
218
+ execute(position?: QueuePosition): Promise<any>;
219
+ /**
220
+ * Checks for expired items in the queue and removes them. Calls onExpire for each expired item.
221
+ * Internal use only.
198
222
  */
199
- getNextItem(position?: QueuePosition): TFn | undefined;
223
+ private checkExpiredItems;
200
224
  /**
201
- * Returns an item without removing it
225
+ * Returns the next item in the queue without removing it.
226
+ *
227
+ * @example
228
+ * ```ts
229
+ * queuer.getPeek(); // front
230
+ * queuer.getPeek('back'); // back
231
+ * ```
202
232
  */
203
- getPeek(position?: QueuePosition): TFn | undefined;
233
+ getPeek(position?: QueuePosition): TValue | undefined;
204
234
  /**
205
- * Returns true if the queuer is empty
235
+ * Returns true if the queue is empty (no pending items).
206
236
  */
207
237
  getIsEmpty(): boolean;
208
238
  /**
209
- * Returns true if the queuer is full
239
+ * Returns true if the queue is full (reached maxSize).
210
240
  */
211
241
  getIsFull(): boolean;
212
242
  /**
213
- * Returns the current size of the queuer
243
+ * Returns the number of pending items in the queue.
214
244
  */
215
245
  getSize(): number;
216
246
  /**
217
- * Returns a copy of all items in the queuer
247
+ * Returns a copy of all items in the queue, including active and pending items.
218
248
  */
219
- getAllItems(): Array<TFn>;
249
+ getAllItems(): Array<TValue>;
220
250
  /**
221
- * Returns the active items
251
+ * Returns the items currently being processed (active tasks).
222
252
  */
223
- getActiveItems(): Array<TFn>;
253
+ getActiveItems(): Array<TValue>;
224
254
  /**
225
- * Returns the pending items
255
+ * Returns the items waiting to be processed (pending tasks).
226
256
  */
227
- getPendingItems(): Array<TFn>;
257
+ getPendingItems(): Array<TValue>;
228
258
  /**
229
- * Returns the number of items that have been successfully processed
259
+ * Returns the number of items that have been successfully processed.
230
260
  */
231
261
  getSuccessCount(): number;
232
262
  /**
233
- * Returns the number of items that have failed processing
263
+ * Returns the number of items that have failed processing.
234
264
  */
235
265
  getErrorCount(): number;
236
266
  /**
237
- * Returns the number of items that have completed processing (success or error)
267
+ * Returns the number of items that have completed processing (success or error).
238
268
  */
239
269
  getSettledCount(): number;
240
270
  /**
241
- * Returns the number of items that have been rejected from the queuer
271
+ * Returns the number of items that have been rejected from being added to the queue.
242
272
  */
243
273
  getRejectionCount(): number;
244
274
  /**
245
- * Returns true if the queuer is running
275
+ * Returns true if the queuer is currently running (processing items).
246
276
  */
247
277
  getIsRunning(): boolean;
248
278
  /**
249
- * Returns true if the queuer is running but has no items to process
279
+ * Returns true if the queuer is running but has no items to process and no active tasks.
250
280
  */
251
281
  getIsIdle(): boolean;
252
282
  /**
253
- * Returns the number of items that have expired from the queuer
283
+ * Returns the number of items that have expired and been removed from the queue.
254
284
  */
255
285
  getExpirationCount(): number;
256
286
  }
257
287
  /**
258
- * Creates a new AsyncQueuer instance with the given options and returns a bound addItem function.
259
- * The queuer is automatically started and ready to process items.
288
+ * Creates a new AsyncQueuer instance and returns a bound addItem function for adding tasks.
289
+ * The queuer is started automatically and ready to process items.
260
290
  *
261
291
  * Error Handling:
262
292
  * - If an `onError` handler is provided, it will be called with the error and queuer instance
263
293
  * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
264
294
  * - 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
295
+ * - Both onError and throwOnError can be used together; the handler will be called before any error is thrown
266
296
  * - The error state can be checked using the underlying AsyncQueuer instance
267
297
  *
268
- * @example
298
+ * Example usage:
269
299
  * ```ts
270
- * const enqueue = asyncQueue<string>();
300
+ * const enqueue = asyncQueue<string>(async (item) => {
301
+ * return item.toUpperCase();
302
+ * }, {...options});
271
303
  *
272
- * // Add items to be processed
273
- * enqueue(async () => {
274
- * return 'Hello';
275
- * });
304
+ * enqueue('hello');
276
305
  * ```
277
- *
278
- * @param options - Configuration options for the AsyncQueuer
279
- * @returns A bound addItem function that can be used to add tasks to the queuer
280
306
  */
281
- export declare function asyncQueue<TFn extends AsyncQueuerFn>(options: AsyncQueuerOptions<TFn>): (fn: TFn, position?: QueuePosition, runOnItemsChange?: boolean) => void;
307
+ export declare function asyncQueue<TValue>(fn: (value: TValue) => Promise<any>, initialOptions: AsyncQueuerOptions<TValue>): (item: TValue & {
308
+ priority?: number;
309
+ }, position?: QueuePosition, runOnItemsChange?: boolean) => void;