@tanstack/pacer 0.22.0 → 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 (100) hide show
  1. package/README.md +4 -4
  2. package/dist/async-batcher.d.ts +11 -13
  3. package/dist/async-batcher.js +185 -131
  4. package/dist/async-debouncer.d.ts +6 -8
  5. package/dist/async-debouncer.js +186 -142
  6. package/dist/async-queuer.d.ts +11 -13
  7. package/dist/async-queuer.js +383 -290
  8. package/dist/async-rate-limiter.d.ts +6 -8
  9. package/dist/async-rate-limiter.js +197 -143
  10. package/dist/async-retryer.d.ts +6 -8
  11. package/dist/async-retryer.js +209 -179
  12. package/dist/async-throttler.d.ts +6 -8
  13. package/dist/async-throttler.js +214 -157
  14. package/dist/batcher.d.ts +5 -7
  15. package/dist/batcher.js +107 -87
  16. package/dist/debouncer.d.ts +6 -8
  17. package/dist/debouncer.js +99 -86
  18. package/dist/event-client.d.ts +8 -10
  19. package/dist/event-client.js +1 -2
  20. package/dist/queuer.d.ts +7 -9
  21. package/dist/queuer.js +277 -212
  22. package/dist/rate-limiter.d.ts +6 -8
  23. package/dist/rate-limiter.js +127 -109
  24. package/dist/throttler.d.ts +6 -8
  25. package/dist/throttler.js +127 -90
  26. package/dist/types.d.ts +4 -6
  27. package/dist/utils.d.ts +3 -5
  28. package/dist/utils.js +1 -2
  29. package/package.json +21 -68
  30. package/dist/async-batcher.cjs +0 -337
  31. package/dist/async-batcher.cjs.map +0 -1
  32. package/dist/async-batcher.d.cts +0 -343
  33. package/dist/async-batcher.js.map +0 -1
  34. package/dist/async-debouncer.cjs +0 -327
  35. package/dist/async-debouncer.cjs.map +0 -1
  36. package/dist/async-debouncer.d.cts +0 -299
  37. package/dist/async-debouncer.js.map +0 -1
  38. package/dist/async-queuer.cjs +0 -516
  39. package/dist/async-queuer.cjs.map +0 -1
  40. package/dist/async-queuer.d.cts +0 -440
  41. package/dist/async-queuer.js.map +0 -1
  42. package/dist/async-rate-limiter.cjs +0 -370
  43. package/dist/async-rate-limiter.cjs.map +0 -1
  44. package/dist/async-rate-limiter.d.cts +0 -356
  45. package/dist/async-rate-limiter.js.map +0 -1
  46. package/dist/async-retryer.cjs +0 -365
  47. package/dist/async-retryer.cjs.map +0 -1
  48. package/dist/async-retryer.d.cts +0 -321
  49. package/dist/async-retryer.js.map +0 -1
  50. package/dist/async-throttler.cjs +0 -344
  51. package/dist/async-throttler.cjs.map +0 -1
  52. package/dist/async-throttler.d.cts +0 -319
  53. package/dist/async-throttler.js.map +0 -1
  54. package/dist/batcher.cjs +0 -200
  55. package/dist/batcher.cjs.map +0 -1
  56. package/dist/batcher.d.cts +0 -179
  57. package/dist/batcher.js.map +0 -1
  58. package/dist/debouncer.cjs +0 -203
  59. package/dist/debouncer.cjs.map +0 -1
  60. package/dist/debouncer.d.cts +0 -166
  61. package/dist/debouncer.js.map +0 -1
  62. package/dist/event-client.cjs +0 -64
  63. package/dist/event-client.cjs.map +0 -1
  64. package/dist/event-client.d.cts +0 -65
  65. package/dist/event-client.js.map +0 -1
  66. package/dist/index.cjs +0 -52
  67. package/dist/index.d.cts +0 -15
  68. package/dist/queuer.cjs +0 -406
  69. package/dist/queuer.cjs.map +0 -1
  70. package/dist/queuer.d.cts +0 -345
  71. package/dist/queuer.js.map +0 -1
  72. package/dist/rate-limiter.cjs +0 -263
  73. package/dist/rate-limiter.cjs.map +0 -1
  74. package/dist/rate-limiter.d.cts +0 -214
  75. package/dist/rate-limiter.js.map +0 -1
  76. package/dist/throttler.cjs +0 -215
  77. package/dist/throttler.cjs.map +0 -1
  78. package/dist/throttler.d.cts +0 -206
  79. package/dist/throttler.js.map +0 -1
  80. package/dist/types.cjs +0 -0
  81. package/dist/types.d.cts +0 -13
  82. package/dist/utils.cjs +0 -13
  83. package/dist/utils.cjs.map +0 -1
  84. package/dist/utils.d.cts +0 -7
  85. package/dist/utils.js.map +0 -1
  86. package/src/async-batcher.ts +0 -594
  87. package/src/async-debouncer.ts +0 -566
  88. package/src/async-queuer.ts +0 -988
  89. package/src/async-rate-limiter.ts +0 -648
  90. package/src/async-retryer.ts +0 -673
  91. package/src/async-throttler.ts +0 -634
  92. package/src/batcher.ts +0 -329
  93. package/src/debouncer.ts +0 -334
  94. package/src/event-client.ts +0 -129
  95. package/src/index.ts +0 -24
  96. package/src/queuer.ts +0 -751
  97. package/src/rate-limiter.ts +0 -429
  98. package/src/throttler.ts +0 -380
  99. package/src/types.ts +0 -12
  100. package/src/utils.ts +0 -12
@@ -1 +0,0 @@
1
- {"version":3,"file":"async-queuer.cjs","names":["Store","parseFunctionOrValue","#setState","#checkExpiredItems","#getConcurrency","#getWait","#timeoutIds","#tick","AsyncRetryer","#clearTimeouts","#getAllItems"],"sources":["../src/async-queuer.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 { OptionalKeys } from './types'\nimport type { QueuePosition } from './queuer'\n\nexport interface AsyncQueuerState<TValue> {\n /**\n * Items currently being processed by the queuer\n */\n activeItems: Array<TValue>\n /**\n * Number of times addItem has been called (for reduction calculations)\n */\n addItemCount: number\n /**\n * Number of task executions that have resulted in errors\n */\n errorCount: number\n /**\n * Number of times execute has been called\n */\n executeCount: number\n /**\n * Number of items that have been removed from the queue due to expiration\n */\n expirationCount: number\n /**\n * Whether the queuer has no items to process (items array is empty)\n */\n isEmpty: boolean\n /**\n * Whether the queuer is currently executing\n */\n isExecuting: boolean\n /**\n * Whether the queuer has reached its maximum capacity\n */\n isFull: boolean\n /**\n * Whether the queuer is not currently processing any items\n */\n isIdle: boolean\n /**\n * Whether the queuer is active and will process items automatically\n */\n isRunning: boolean\n /**\n * Array of items currently waiting to be processed\n */\n items: Array<TValue>\n /**\n * Timestamps when items were added to the queue for expiration tracking\n */\n itemTimestamps: Array<number>\n /**\n * The result from the most recent task execution\n */\n lastResult: any\n /**\n * Whether the queuer has a pending timeout for processing the next item\n */\n pendingTick: boolean\n /**\n * Number of items that have been rejected from being added to the queue\n */\n rejectionCount: number\n /**\n * Number of task executions that have completed (either successfully or with errors)\n */\n settledCount: number\n /**\n * Number of items currently in the queue\n */\n size: number\n /**\n * Current processing status - 'idle' when not processing, 'running' when active, 'stopped' when paused\n */\n status: 'idle' | 'running' | 'stopped'\n /**\n * Number of task executions that have completed successfully\n */\n successCount: number\n}\n\nfunction getDefaultAsyncQueuerState<TValue>(): AsyncQueuerState<TValue> {\n return {\n activeItems: [],\n addItemCount: 0,\n errorCount: 0,\n executeCount: 0,\n expirationCount: 0,\n isEmpty: true,\n isExecuting: false,\n isFull: false,\n isIdle: true,\n isRunning: true,\n itemTimestamps: [],\n items: [],\n lastResult: null,\n pendingTick: false,\n rejectionCount: 0,\n settledCount: 0,\n size: 0,\n status: 'idle',\n successCount: 0,\n }\n}\n\nexport interface AsyncQueuerOptions<TValue> {\n /**\n * Options for configuring the underlying async retryer\n */\n asyncRetryerOptions?: AsyncRetryerOptions<(item: TValue) => Promise<any>>\n /**\n * Default position to add items to the queuer\n * @default 'back'\n */\n addItemsTo?: QueuePosition\n /**\n * Maximum number of concurrent tasks to process.\n * Can be a number or a function that returns a number.\n * @default 1\n */\n concurrency?: number | ((queuer: AsyncQueuer<TValue>) => number)\n /**\n * Maximum time in milliseconds that an item can stay in the queue\n * If not provided, items will never expire\n */\n expirationDuration?: number\n /**\n * Function to determine if an item has expired\n * If provided, this overrides the expirationDuration behavior\n */\n getIsExpired?: (item: TValue, addedAt: number) => boolean\n /**\n * Default position to get items from during processing\n * @default 'front'\n */\n getItemsFrom?: QueuePosition\n /**\n * Function to determine priority of items in the queuer\n * Higher priority items will be processed first\n * If not provided, will use static priority values attached to tasks\n */\n getPriority?: (item: TValue) => number\n /**\n * Initial items to populate the queuer with\n */\n initialItems?: Array<TValue>\n /**\n * Initial state for the async queuer\n */\n initialState?: Partial<AsyncQueuerState<TValue>>\n /**\n * Optional key to identify this async queuer instance.\n * If provided, the async queuer will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of items allowed in the queuer\n */\n maxSize?: number\n /**\n * Optional error handler for when a task throws.\n * If provided, the handler will be called with the error and queuer instance.\n * This can be used alongside throwOnError - the handler will be called before any error is thrown.\n */\n onError?: (error: Error, item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item expires in the queuer\n */\n onExpire?: (item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item is added or removed from the queuer\n */\n onItemsChange?: (queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item is rejected from being added to the queuer\n */\n onReject?: (item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Optional callback to call when a task is settled\n */\n onSettled?: (item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Optional callback to call when a task succeeds\n */\n onSuccess?: (result: any, item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Whether the queuer should start processing tasks immediately or not.\n */\n started?: boolean\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 * Time in milliseconds to wait between processing items.\n * Can be a number or a function that returns a number.\n * @default 0\n */\n wait?: number | ((queuer: AsyncQueuer<TValue>) => number)\n}\n\n/**\n * Utility function for sharing common `AsyncQueuerOptions` options between different `AsyncQueuer` instances.\n */\nexport function asyncQueuerOptions<\n TValue = any,\n TOptions extends Partial<AsyncQueuerOptions<TValue>> = Partial<\n AsyncQueuerOptions<TValue>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\ntype AsyncQueuerOptionsWithOptionalCallbacks = OptionalKeys<\n Required<AsyncQueuerOptions<any>>,\n | 'initialState'\n | 'throwOnError'\n | 'onSuccess'\n | 'onSettled'\n | 'onReject'\n | 'onItemsChange'\n | 'onExpire'\n | 'onError'\n | 'key'\n>\n\nconst defaultOptions: AsyncQueuerOptionsWithOptionalCallbacks = {\n addItemsTo: 'back',\n asyncRetryerOptions: {\n maxAttempts: 1,\n },\n concurrency: 1,\n expirationDuration: Infinity,\n getIsExpired: () => false,\n getItemsFrom: 'front',\n getPriority: (item: any) => item?.priority ?? 0,\n initialItems: [],\n maxSize: Infinity,\n started: true,\n wait: 0,\n}\n\n/**\n * A flexible asynchronous queue for processing tasks with configurable concurrency, priority, and expiration.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync Queuer:\n * - Returns promises that can be awaited for task results\n * - Built-in retry support via AsyncRetryer integration for each queued task\n * - Abort support to cancel in-flight task executions\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n * - Concurrent execution support (process multiple items simultaneously)\n *\n * The sync Queuer is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Queuing?\n * Queuing is a technique for managing and processing items sequentially or with controlled concurrency.\n * Tasks are processed up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if the concurrency limit allows.\n *\n * Key Features:\n * - Priority queue support via the getPriority option\n * - Configurable concurrency limit\n * - Callbacks for task success, error, completion, and queue state changes\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause and resume processing\n * - Item expiration to remove stale items from the queue\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer 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 AsyncQueuer instance\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the async queuer\n * - Use `onSuccess` callback to react to successful task execution and implement custom logic\n * - Use `onError` callback to react to task execution errors and implement custom error handling\n * - Use `onSettled` callback to react to task execution completion (success or error) and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the queue\n * - Use `onExpire` callback to react to items expiring and implement custom logic\n * - Use `onReject` callback to react to items being rejected when the queue is full\n * - The state includes error count, expiration count, rejection count, running status, and success/settle counts\n * - State can be accessed via `asyncQueuer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `asyncQueuer.state`\n *\n * Example usage:\n * ```ts\n * const asyncQueuer = new AsyncQueuer<string>(async (item) => {\n * // process item\n * return item.toUpperCase();\n * }, {\n * concurrency: 2,\n * onSuccess: (result) => {\n * console.log(result);\n * }\n * });\n *\n * asyncQueuer.addItem('hello');\n * asyncQueuer.start();\n * ```\n */\nexport class AsyncQueuer<TValue> {\n readonly store: Store<Readonly<AsyncQueuerState<TValue>>> = new Store<\n AsyncQueuerState<TValue>\n >(getDefaultAsyncQueuerState<TValue>())\n key: string | undefined\n options: AsyncQueuerOptions<TValue>\n asyncRetryers = new Map<\n number,\n AsyncRetryer<(item: TValue) => Promise<any>>\n >()\n #timeoutIds: Set<ReturnType<typeof setTimeout>> = new Set()\n\n constructor(\n public fn: (item: TValue) => Promise<any>,\n initialOptions: AsyncQueuerOptions<TValue> = {},\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n const isInitiallyRunning =\n this.options.initialState?.isRunning ?? this.options.started ?? true\n this.#setState({\n ...this.options.initialState,\n isRunning: isInitiallyRunning,\n })\n\n if (this.options.initialState?.items) {\n if (this.store.state.isRunning) {\n this.#tick()\n }\n } else {\n for (let i = 0; i < (this.options.initialItems?.length ?? 0); i++) {\n const item = this.options.initialItems![i]!\n const isLast = i === (this.options.initialItems?.length ?? 0) - 1\n this.addItem(item, this.options.addItemsTo ?? 'back', isLast)\n }\n }\n\n if (this.key) {\n pacerEventClient.on('d-AsyncQueuer', (e) => {\n if (e.payload.key !== this.key) return\n this.#setState(\n e.payload.store.state as Partial<AsyncQueuerState<TValue>>,\n )\n this.setOptions(\n e.payload.options as Partial<AsyncQueuerOptions<TValue>>,\n )\n })\n }\n }\n\n /**\n * Updates the queuer options. New options are merged with existing options.\n */\n setOptions = (newOptions: Partial<AsyncQueuerOptions<TValue>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<AsyncQueuerState<TValue>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n\n const { activeItems, items, isRunning } = combinedState\n\n const size = items.length\n const isFull = size >= (this.options.maxSize ?? Infinity)\n const isEmpty = size === 0\n const isIdle = isRunning && isEmpty && activeItems.length === 0\n\n const status = isIdle ? 'idle' : isRunning ? 'running' : 'stopped'\n\n return {\n ...combinedState,\n isEmpty,\n isFull,\n isIdle,\n size,\n status,\n }\n })\n emitChange('AsyncQueuer', this)\n }\n\n /**\n * Returns the current wait time (in milliseconds) between processing items.\n * If a function is provided, it is called with the queuer instance.\n */\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait ?? 0, this)\n }\n\n /**\n * Returns the current concurrency limit for processing items.\n * If a function is provided, it is called with the queuer instance.\n */\n #getConcurrency = (): number => {\n return parseFunctionOrValue(this.options.concurrency ?? 1, this)\n }\n\n /**\n * Processes items in the queue up to the concurrency limit. Internal use only.\n */\n #tick = () => {\n if (!this.store.state.isRunning) {\n this.#setState({ pendingTick: false })\n return\n }\n this.#setState({ pendingTick: true })\n\n // Check for expired items\n this.#checkExpiredItems()\n\n // Process items concurrently up to the concurrency limit\n let scheduledAsyncWork = false\n const activeItems = [...this.store.state.activeItems]\n while (\n activeItems.length < this.#getConcurrency() &&\n this.store.state.items.length > 0\n ) {\n const nextItem = this.peekNextItem()\n if (nextItem === undefined) {\n break\n }\n activeItems.push(nextItem)\n this.#setState({\n activeItems: [...activeItems],\n })\n scheduledAsyncWork = true\n ;(async () => {\n try {\n await this.execute()\n } catch {\n // errors are already surfaced via onError/errorCount (and rethrown to\n // direct execute/flush callers); swallowing here prevents unhandled\n // rejections and keeps the processing chain alive\n }\n\n const wait = this.#getWait()\n if (wait > 0) {\n const timeoutId = setTimeout(() => {\n this.#timeoutIds.delete(timeoutId)\n this.#tick()\n }, wait)\n this.#timeoutIds.add(timeoutId)\n return\n }\n\n this.#tick()\n })()\n }\n\n // pendingTick must stay true while executions or wait timers are pending so\n // that addItem does not trigger an extra tick that bypasses the wait period\n if (!scheduledAsyncWork) {\n this.#setState({ pendingTick: false })\n }\n }\n\n /**\n * Adds an item to the queue. If the queue is full, the item is rejected and onReject is called.\n * Items can be inserted based on priority or at the front/back depending on configuration.\n * `undefined` cannot be queued (it is the internal \"no item\" sentinel) and is always rejected.\n *\n * @example\n * ```ts\n * queuer.addItem({ value: 'task', priority: 10 });\n * queuer.addItem('task2', 'front');\n * ```\n */\n addItem = (\n item: TValue,\n position: QueuePosition = this.options.addItemsTo ?? 'back',\n runOnItemsChange: boolean = true,\n ): boolean => {\n this.#setState({\n addItemCount: this.store.state.addItemCount + 1,\n })\n\n // undefined is the internal \"no item\" sentinel (peekNextItem/getNextItem);\n // queuing it would wedge the processing loop and block items behind it\n if (item === undefined) {\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(item, this)\n return false\n }\n\n if (this.store.state.items.length >= (this.options.maxSize ?? Infinity)) {\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(item, this)\n return false\n }\n\n // Get priority either from the function or from getPriority option\n const priority =\n this.options.getPriority !== defaultOptions.getPriority\n ? this.options.getPriority!(item)\n : (item as any)?.priority\n\n const items = this.store.state.items\n const itemTimestamps = this.store.state.itemTimestamps\n\n if (priority !== undefined) {\n // Insert based on priority - higher priority items go to front\n const insertIndex = items.findIndex((existing) => {\n const existingPriority =\n this.options.getPriority !== defaultOptions.getPriority\n ? this.options.getPriority!(existing)\n : (existing as any)?.priority\n return existingPriority < priority\n })\n\n if (insertIndex === -1) {\n items.push(item)\n itemTimestamps.push(Date.now())\n } else {\n items.splice(insertIndex, 0, item)\n itemTimestamps.splice(insertIndex, 0, Date.now())\n }\n } else {\n if (position === 'front') {\n // Default FIFO/LIFO behavior\n items.unshift(item)\n itemTimestamps.unshift(Date.now())\n } else {\n // LIFO\n items.push(item)\n itemTimestamps.push(Date.now())\n }\n }\n\n this.#setState({\n items,\n itemTimestamps,\n })\n\n if (runOnItemsChange) {\n this.options.onItemsChange?.(this)\n }\n\n if (this.store.state.isRunning && !this.store.state.pendingTick) {\n this.#tick()\n }\n\n return true\n }\n\n /**\n * Removes and returns the next item from the queue without executing the task function.\n * Use for manual queue management. Normally, use execute() to process items.\n *\n * @example\n * ```ts\n * // FIFO\n * queuer.getNextItem();\n * // LIFO\n * queuer.getNextItem('back');\n * ```\n */\n getNextItem = (\n position: QueuePosition = this.options.getItemsFrom ?? 'front',\n ): TValue | undefined => {\n const { items, itemTimestamps } = this.store.state\n let item: TValue | undefined\n\n // When priority function is provided or position is 'front', always get from front (highest priority)\n // Priority takes precedence over FIFO/LIFO behavior\n if (\n this.options.getPriority !== defaultOptions.getPriority ||\n position === 'front'\n ) {\n item = items[0]\n if (item !== undefined) {\n this.#setState({\n items: items.slice(1),\n itemTimestamps: itemTimestamps.slice(1),\n })\n }\n } else {\n item = items[items.length - 1]\n if (item !== undefined) {\n this.#setState({\n items: items.slice(0, -1),\n itemTimestamps: itemTimestamps.slice(0, -1),\n })\n }\n }\n\n if (item !== undefined) {\n this.options.onItemsChange?.(this)\n }\n\n return item\n }\n\n #getAllItems = (): Array<TValue> => {\n const items = this.peekAllItems()\n this.clear()\n return items\n }\n\n /**\n * Removes and returns the next item from the queue and executes the task function with it.\n *\n * @example\n * ```ts\n * queuer.execute();\n * // LIFO\n * queuer.execute('back');\n * ```\n */\n execute = async (position?: QueuePosition): Promise<any> => {\n const item = this.getNextItem(position)\n\n if (item !== undefined) {\n const currentExecuteCount = this.store.state.executeCount + 1\n this.#setState({\n executeCount: currentExecuteCount,\n isExecuting: true,\n })\n try {\n const currentAsyncRetryer = new AsyncRetryer(\n this.fn,\n this.options.asyncRetryerOptions,\n )\n this.asyncRetryers.set(currentExecuteCount, currentAsyncRetryer)\n const lastResult = await currentAsyncRetryer.execute(item) // EXECUTE!\n this.#setState({\n successCount: this.store.state.successCount + 1,\n lastResult,\n })\n this.options.onSuccess?.(lastResult, item, this)\n } catch (error) {\n this.#setState({\n errorCount: this.store.state.errorCount + 1,\n })\n this.options.onError?.(error as Error, item, this)\n if (this.options.throwOnError) {\n throw error\n }\n } finally {\n this.asyncRetryers.delete(currentExecuteCount) // dispose retryer\n // remove only one occurrence so duplicate item values keep accurate\n // concurrency accounting\n const remainingActiveItems = [...this.store.state.activeItems]\n const activeItemIndex = remainingActiveItems.indexOf(item)\n if (activeItemIndex !== -1) {\n remainingActiveItems.splice(activeItemIndex, 1)\n }\n this.#setState({\n activeItems: remainingActiveItems,\n // other executions may still be in flight (concurrency > 1 or flush)\n isExecuting: this.asyncRetryers.size > 0,\n settledCount: this.store.state.settledCount + 1,\n })\n this.options.onSettled?.(item, this)\n }\n }\n return item\n }\n\n /**\n * Processes a specified number of items to execute immediately with no wait time\n * If no numberOfItems is provided, all items will be processed\n */\n flush = async (\n numberOfItems: number = this.store.state.items.length,\n position?: QueuePosition,\n ): Promise<void> => {\n this.#clearTimeouts() // clear any pending timeouts (kills the tick chain)\n const results = await Promise.allSettled(\n Array.from({ length: numberOfItems }, () => this.execute(position)),\n )\n // the tick chain was killed above; restart it so remaining and future items\n // process even when a flushed task rejected. Remaining items resume with the\n // normal wait spacing after the flushed executions.\n this.#setState({ pendingTick: false })\n if (this.store.state.isRunning && this.store.state.items.length > 0) {\n const wait = this.#getWait()\n if (wait > 0) {\n this.#setState({ pendingTick: true })\n const timeoutId = setTimeout(() => {\n this.#timeoutIds.delete(timeoutId)\n this.#tick()\n }, wait)\n this.#timeoutIds.add(timeoutId)\n } else {\n this.#tick()\n }\n }\n const failure = results.find(\n (result): result is PromiseRejectedResult => result.status === 'rejected',\n )\n if (failure) {\n throw failure.reason\n }\n }\n\n /**\n * Processes all items in the queue as a batch using the provided function as an argument\n * The queue is cleared after processing\n */\n flushAsBatch = async (\n batchFunction: (items: Array<TValue>) => Promise<any>,\n ): Promise<void> => {\n this.#clearTimeouts() // clear any pending timeouts (kills the tick chain)\n const items = this.#getAllItems()\n try {\n await batchFunction(items)\n } finally {\n // restore the tick chain even when the batch function rejects\n this.#setState({ pendingTick: false })\n if (this.store.state.isRunning && this.store.state.items.length > 0) {\n this.#tick()\n }\n }\n }\n\n /**\n * Checks for expired items in the queue and removes them. Calls onExpire for each expired item.\n * Internal use only.\n */\n #checkExpiredItems = (): void => {\n if (\n (this.options.expirationDuration ?? Infinity) === Infinity &&\n this.options.getIsExpired === defaultOptions.getIsExpired\n ) {\n return\n }\n\n const now = Date.now()\n const expiredIndices: Array<number> = []\n\n // Find indices of expired items\n for (let i = 0; i < this.store.state.items.length; i++) {\n const timestamp = this.store.state.itemTimestamps[i]\n if (timestamp === undefined) continue\n\n const item = this.store.state.items[i]\n if (item === undefined) continue\n\n const isExpired =\n this.options.getIsExpired !== defaultOptions.getIsExpired\n ? this.options.getIsExpired!(item, timestamp)\n : now - timestamp > (this.options.expirationDuration ?? Infinity)\n\n if (isExpired) {\n expiredIndices.push(i)\n }\n }\n\n // Remove expired items from back to front to maintain indices\n for (let i = expiredIndices.length - 1; i >= 0; i--) {\n const index = expiredIndices[i]\n if (index === undefined) continue\n\n const expiredItem = this.store.state.items[index]\n if (expiredItem === undefined) continue\n\n const newItems = [...this.store.state.items]\n const newTimestamps = [...this.store.state.itemTimestamps]\n newItems.splice(index, 1)\n newTimestamps.splice(index, 1)\n this.#setState({\n items: newItems,\n itemTimestamps: newTimestamps,\n expirationCount: this.store.state.expirationCount + 1,\n })\n this.options.onExpire?.(expiredItem, this)\n }\n\n if (expiredIndices.length > 0) {\n this.options.onItemsChange?.(this)\n }\n }\n\n /**\n * Returns the next item in the queue without removing it.\n *\n * @example\n * ```ts\n * queuer.peekNextItem(); // front\n * queuer.peekNextItem('back'); // back\n * ```\n */\n peekNextItem = (position: QueuePosition = 'front'): TValue | undefined => {\n if (position === 'front') {\n return this.store.state.items[0]\n }\n return this.store.state.items[this.store.state.items.length - 1]\n }\n\n /**\n * Returns a copy of all items in the queue, including active and pending items.\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.peekActiveItems(), ...this.peekPendingItems()]\n }\n\n /**\n * Returns the items currently being processed (active tasks).\n */\n peekActiveItems = (): Array<TValue> => {\n return [...this.store.state.activeItems]\n }\n\n /**\n * Returns the items waiting to be processed (pending tasks).\n */\n peekPendingItems = (): Array<TValue> => {\n return [...this.store.state.items]\n }\n\n /**\n * Starts processing items in the queue. If already running, does nothing.\n */\n start = (): void => {\n this.#setState({ isRunning: true })\n if (!this.store.state.pendingTick && this.store.state.items.length > 0) {\n this.#tick()\n }\n }\n\n /**\n * Stops processing items in the queue. Does not clear the queue.\n */\n stop = (): void => {\n this.#clearTimeouts()\n this.#setState({ isRunning: false, pendingTick: false })\n }\n\n #clearTimeouts = (): void => {\n this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))\n this.#timeoutIds.clear()\n }\n\n /**\n * Removes all pending items from the queue.\n * Does NOT affect active tasks.\n */\n clear = (): void => {\n this.#setState({ items: [], itemTimestamps: [] })\n this.options.onItemsChange?.(this)\n }\n\n /**\n * Returns the AbortSignal for a specific execution.\n * If no executeCount 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 executeCount - Optional specific execution to get signal for\n * @example\n * ```typescript\n * const queuer = new AsyncQueuer(\n * async (item: string) => {\n * const signal = queuer.getAbortSignal()\n * if (signal) {\n * const response = await fetch(`/api/process/${item}`, { signal })\n * return response.json()\n * }\n * },\n * { concurrency: 2 }\n * )\n * ```\n */\n getAbortSignal = (executeCount?: number): AbortSignal | null => {\n const count = executeCount ?? this.store.state.executeCount\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 clear out the items.\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 * Resets the queuer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultAsyncQueuerState<TValue>())\n this.options.onItemsChange?.(this)\n this.asyncRetryers.forEach((retryer) => retryer.reset())\n }\n}\n\n/**\n * Creates a new AsyncQueuer instance and returns a bound addItem function for adding tasks.\n * The queuer is started automatically and ready to process items.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync queue function:\n * - Returns promises that can be awaited for task results\n * - Built-in retry support via AsyncRetryer integration for each queued task\n * - Abort support to cancel in-flight task executions\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n * - Concurrent execution support (process multiple items simultaneously)\n *\n * The sync queue function is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Queuing?\n * Queuing is a technique for managing and processing items sequentially or with controlled concurrency.\n * Tasks are processed up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if the concurrency limit allows.\n *\n * Configuration Options:\n * - `concurrency`: Maximum number of concurrent tasks (default: 1)\n * - `wait`: Time to wait between processing items (default: 0)\n * - `maxSize`: Maximum number of items allowed in the queue (default: Infinity)\n * - `getPriority`: Function to determine item priority\n * - `addItemsTo`: Default position to add items ('back' or 'front', default: 'back')\n * - `getItemsFrom`: Default position to get items ('front' or 'back', default: 'front')\n * - `expirationDuration`: Maximum time items can stay in queue\n * - `started`: Whether to start processing immediately (default: true)\n * - `asyncRetryerOptions`: Configure retry behavior for task executions\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer 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 AsyncQueuer instance\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the async queuer\n * - Use `onSuccess` callback to react to successful task execution and implement custom logic\n * - Use `onError` callback to react to task execution errors and implement custom error handling\n * - Use `onSettled` callback to react to task execution completion (success or error) and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the queue\n * - Use `onExpire` callback to react to items expiring and implement custom logic\n * - Use `onReject` callback to react to items being rejected when the queue is full\n * - The state includes error count, expiration count, rejection count, running status, and success/settle counts\n * - State can be accessed via the underlying AsyncQueuer instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * @example\n * ```ts\n * const enqueue = asyncQueue<string>(async (item) => {\n * return item.toUpperCase();\n * }, {\n * concurrency: 2,\n * wait: 100,\n * onSuccess: (result) => console.log('Processed:', result)\n * });\n *\n * enqueue('hello');\n * ```\n */\nexport function asyncQueue<TValue>(\n fn: (value: TValue) => Promise<any>,\n initialOptions: AsyncQueuerOptions<TValue>,\n) {\n const asyncQueuer = new AsyncQueuer<TValue>(fn, initialOptions)\n return asyncQueuer.addItem\n}\n"],"mappings":";;;;;;;AAuFA,SAAS,6BAA+D;CACtE,OAAO;EACL,aAAa,CAAC;EACd,cAAc;EACd,YAAY;EACZ,cAAc;EACd,iBAAiB;EACjB,SAAS;EACT,aAAa;EACb,QAAQ;EACR,QAAQ;EACR,WAAW;EACX,gBAAgB,CAAC;EACjB,OAAO,CAAC;EACR,YAAY;EACZ,aAAa;EACb,gBAAgB;EAChB,cAAc;EACd,MAAM;EACN,QAAQ;EACR,cAAc;CAChB;AACF;;;;AAuGA,SAAgB,mBAKd,SAA6B;CAC7B,OAAO;AACT;AAeA,MAAM,iBAA0D;CAC9D,YAAY;CACZ,qBAAqB,EACnB,aAAa,EACf;CACA,aAAa;CACb,oBAAoB;CACpB,oBAAoB;CACpB,cAAc;CACd,cAAc,SAAc,MAAM,YAAY;CAC9C,cAAc,CAAC;CACf,SAAS;CACT,SAAS;CACT,MAAM;AACR;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,SAAgB,WACd,IACA,gBACA;CAEA,OAAO,IADiB,YAAoB,IAAI,cAC/B,CAAC,CAAC;AACrB"}
@@ -1,440 +0,0 @@
1
- import { AsyncRetryer, AsyncRetryerOptions } from "./async-retryer.cjs";
2
- import { QueuePosition } from "./queuer.cjs";
3
- import { Store } from "@tanstack/store";
4
- //#region src/async-queuer.d.ts
5
- interface AsyncQueuerState<TValue> {
6
- /**
7
- * Items currently being processed by the queuer
8
- */
9
- activeItems: Array<TValue>;
10
- /**
11
- * Number of times addItem has been called (for reduction calculations)
12
- */
13
- addItemCount: number;
14
- /**
15
- * Number of task executions that have resulted in errors
16
- */
17
- errorCount: number;
18
- /**
19
- * Number of times execute has been called
20
- */
21
- executeCount: number;
22
- /**
23
- * Number of items that have been removed from the queue due to expiration
24
- */
25
- expirationCount: number;
26
- /**
27
- * Whether the queuer has no items to process (items array is empty)
28
- */
29
- isEmpty: boolean;
30
- /**
31
- * Whether the queuer is currently executing
32
- */
33
- isExecuting: boolean;
34
- /**
35
- * Whether the queuer has reached its maximum capacity
36
- */
37
- isFull: boolean;
38
- /**
39
- * Whether the queuer is not currently processing any items
40
- */
41
- isIdle: boolean;
42
- /**
43
- * Whether the queuer is active and will process items automatically
44
- */
45
- isRunning: boolean;
46
- /**
47
- * Array of items currently waiting to be processed
48
- */
49
- items: Array<TValue>;
50
- /**
51
- * Timestamps when items were added to the queue for expiration tracking
52
- */
53
- itemTimestamps: Array<number>;
54
- /**
55
- * The result from the most recent task execution
56
- */
57
- lastResult: any;
58
- /**
59
- * Whether the queuer has a pending timeout for processing the next item
60
- */
61
- pendingTick: boolean;
62
- /**
63
- * Number of items that have been rejected from being added to the queue
64
- */
65
- rejectionCount: number;
66
- /**
67
- * Number of task executions that have completed (either successfully or with errors)
68
- */
69
- settledCount: number;
70
- /**
71
- * Number of items currently in the queue
72
- */
73
- size: number;
74
- /**
75
- * Current processing status - 'idle' when not processing, 'running' when active, 'stopped' when paused
76
- */
77
- status: 'idle' | 'running' | 'stopped';
78
- /**
79
- * Number of task executions that have completed successfully
80
- */
81
- successCount: number;
82
- }
83
- interface AsyncQueuerOptions<TValue> {
84
- /**
85
- * Options for configuring the underlying async retryer
86
- */
87
- asyncRetryerOptions?: AsyncRetryerOptions<(item: TValue) => Promise<any>>;
88
- /**
89
- * Default position to add items to the queuer
90
- * @default 'back'
91
- */
92
- addItemsTo?: QueuePosition;
93
- /**
94
- * Maximum number of concurrent tasks to process.
95
- * Can be a number or a function that returns a number.
96
- * @default 1
97
- */
98
- concurrency?: number | ((queuer: AsyncQueuer<TValue>) => number);
99
- /**
100
- * Maximum time in milliseconds that an item can stay in the queue
101
- * If not provided, items will never expire
102
- */
103
- expirationDuration?: number;
104
- /**
105
- * Function to determine if an item has expired
106
- * If provided, this overrides the expirationDuration behavior
107
- */
108
- getIsExpired?: (item: TValue, addedAt: number) => boolean;
109
- /**
110
- * Default position to get items from during processing
111
- * @default 'front'
112
- */
113
- getItemsFrom?: QueuePosition;
114
- /**
115
- * Function to determine priority of items in the queuer
116
- * Higher priority items will be processed first
117
- * If not provided, will use static priority values attached to tasks
118
- */
119
- getPriority?: (item: TValue) => number;
120
- /**
121
- * Initial items to populate the queuer with
122
- */
123
- initialItems?: Array<TValue>;
124
- /**
125
- * Initial state for the async queuer
126
- */
127
- initialState?: Partial<AsyncQueuerState<TValue>>;
128
- /**
129
- * Optional key to identify this async queuer instance.
130
- * If provided, the async queuer will be identified by this key in the devtools and PacerProvider if applicable.
131
- */
132
- key?: string;
133
- /**
134
- * Maximum number of items allowed in the queuer
135
- */
136
- maxSize?: number;
137
- /**
138
- * Optional error handler for when a task throws.
139
- * If provided, the handler will be called with the error and queuer instance.
140
- * This can be used alongside throwOnError - the handler will be called before any error is thrown.
141
- */
142
- onError?: (error: Error, item: TValue, queuer: AsyncQueuer<TValue>) => void;
143
- /**
144
- * Callback fired whenever an item expires in the queuer
145
- */
146
- onExpire?: (item: TValue, queuer: AsyncQueuer<TValue>) => void;
147
- /**
148
- * Callback fired whenever an item is added or removed from the queuer
149
- */
150
- onItemsChange?: (queuer: AsyncQueuer<TValue>) => void;
151
- /**
152
- * Callback fired whenever an item is rejected from being added to the queuer
153
- */
154
- onReject?: (item: TValue, queuer: AsyncQueuer<TValue>) => void;
155
- /**
156
- * Optional callback to call when a task is settled
157
- */
158
- onSettled?: (item: TValue, queuer: AsyncQueuer<TValue>) => void;
159
- /**
160
- * Optional callback to call when a task succeeds
161
- */
162
- onSuccess?: (result: any, item: TValue, queuer: AsyncQueuer<TValue>) => void;
163
- /**
164
- * Whether the queuer should start processing tasks immediately or not.
165
- */
166
- started?: boolean;
167
- /**
168
- * Whether to throw errors when they occur.
169
- * Defaults to true if no onError handler is provided, false if an onError handler is provided.
170
- * Can be explicitly set to override these defaults.
171
- */
172
- throwOnError?: boolean;
173
- /**
174
- * Time in milliseconds to wait between processing items.
175
- * Can be a number or a function that returns a number.
176
- * @default 0
177
- */
178
- wait?: number | ((queuer: AsyncQueuer<TValue>) => number);
179
- }
180
- /**
181
- * Utility function for sharing common `AsyncQueuerOptions` options between different `AsyncQueuer` instances.
182
- */
183
- declare function asyncQueuerOptions<TValue = any, TOptions extends Partial<AsyncQueuerOptions<TValue>> = Partial<AsyncQueuerOptions<TValue>>>(options: TOptions): TOptions;
184
- /**
185
- * A flexible asynchronous queue for processing tasks with configurable concurrency, priority, and expiration.
186
- *
187
- * Async vs Sync Versions:
188
- * The async version provides advanced features over the sync Queuer:
189
- * - Returns promises that can be awaited for task results
190
- * - Built-in retry support via AsyncRetryer integration for each queued task
191
- * - Abort support to cancel in-flight task executions
192
- * - Comprehensive error handling with onError callbacks and throwOnError control
193
- * - Detailed execution tracking (success/error/settle counts)
194
- * - Concurrent execution support (process multiple items simultaneously)
195
- *
196
- * The sync Queuer is lighter weight and simpler when you don't need async features,
197
- * return values, or execution control.
198
- *
199
- * What is Queuing?
200
- * Queuing is a technique for managing and processing items sequentially or with controlled concurrency.
201
- * Tasks are processed up to the configured concurrency limit. When a task completes,
202
- * the next pending task is processed if the concurrency limit allows.
203
- *
204
- * Key Features:
205
- * - Priority queue support via the getPriority option
206
- * - Configurable concurrency limit
207
- * - Callbacks for task success, error, completion, and queue state changes
208
- * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior
209
- * - Pause and resume processing
210
- * - Item expiration to remove stale items from the queue
211
- *
212
- * Error Handling:
213
- * - If an `onError` handler is provided, it will be called with the error and queuer instance
214
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
215
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
216
- * - Both onError and throwOnError can be used together; the handler will be called before any error is thrown
217
- * - The error state can be checked using the AsyncQueuer instance
218
- *
219
- * State Management:
220
- * - Uses TanStack Store for reactive state management
221
- * - Use `initialState` to provide initial state values when creating the async queuer
222
- * - Use `onSuccess` callback to react to successful task execution and implement custom logic
223
- * - Use `onError` callback to react to task execution errors and implement custom error handling
224
- * - Use `onSettled` callback to react to task execution completion (success or error) and implement custom logic
225
- * - Use `onItemsChange` callback to react to items being added or removed from the queue
226
- * - Use `onExpire` callback to react to items expiring and implement custom logic
227
- * - Use `onReject` callback to react to items being rejected when the queue is full
228
- * - The state includes error count, expiration count, rejection count, running status, and success/settle counts
229
- * - State can be accessed via `asyncQueuer.store.state` when using the class directly
230
- * - When using framework adapters (React/Solid), state is accessed from `asyncQueuer.state`
231
- *
232
- * Example usage:
233
- * ```ts
234
- * const asyncQueuer = new AsyncQueuer<string>(async (item) => {
235
- * // process item
236
- * return item.toUpperCase();
237
- * }, {
238
- * concurrency: 2,
239
- * onSuccess: (result) => {
240
- * console.log(result);
241
- * }
242
- * });
243
- *
244
- * asyncQueuer.addItem('hello');
245
- * asyncQueuer.start();
246
- * ```
247
- */
248
- declare class AsyncQueuer<TValue> {
249
- #private;
250
- fn: (item: TValue) => Promise<any>;
251
- readonly store: Store<Readonly<AsyncQueuerState<TValue>>>;
252
- key: string | undefined;
253
- options: AsyncQueuerOptions<TValue>;
254
- asyncRetryers: Map<number, AsyncRetryer<(item: TValue) => Promise<any>>>;
255
- constructor(fn: (item: TValue) => Promise<any>, initialOptions?: AsyncQueuerOptions<TValue>);
256
- /**
257
- * Updates the queuer options. New options are merged with existing options.
258
- */
259
- setOptions: (newOptions: Partial<AsyncQueuerOptions<TValue>>) => void;
260
- /**
261
- * Adds an item to the queue. If the queue is full, the item is rejected and onReject is called.
262
- * Items can be inserted based on priority or at the front/back depending on configuration.
263
- * `undefined` cannot be queued (it is the internal "no item" sentinel) and is always rejected.
264
- *
265
- * @example
266
- * ```ts
267
- * queuer.addItem({ value: 'task', priority: 10 });
268
- * queuer.addItem('task2', 'front');
269
- * ```
270
- */
271
- addItem: (item: TValue, position?: QueuePosition, runOnItemsChange?: boolean) => boolean;
272
- /**
273
- * Removes and returns the next item from the queue without executing the task function.
274
- * Use for manual queue management. Normally, use execute() to process items.
275
- *
276
- * @example
277
- * ```ts
278
- * // FIFO
279
- * queuer.getNextItem();
280
- * // LIFO
281
- * queuer.getNextItem('back');
282
- * ```
283
- */
284
- getNextItem: (position?: QueuePosition) => TValue | undefined;
285
- /**
286
- * Removes and returns the next item from the queue and executes the task function with it.
287
- *
288
- * @example
289
- * ```ts
290
- * queuer.execute();
291
- * // LIFO
292
- * queuer.execute('back');
293
- * ```
294
- */
295
- execute: (position?: QueuePosition) => Promise<any>;
296
- /**
297
- * Processes a specified number of items to execute immediately with no wait time
298
- * If no numberOfItems is provided, all items will be processed
299
- */
300
- flush: (numberOfItems?: number, position?: QueuePosition) => Promise<void>;
301
- /**
302
- * Processes all items in the queue as a batch using the provided function as an argument
303
- * The queue is cleared after processing
304
- */
305
- flushAsBatch: (batchFunction: (items: Array<TValue>) => Promise<any>) => Promise<void>;
306
- /**
307
- * Returns the next item in the queue without removing it.
308
- *
309
- * @example
310
- * ```ts
311
- * queuer.peekNextItem(); // front
312
- * queuer.peekNextItem('back'); // back
313
- * ```
314
- */
315
- peekNextItem: (position?: QueuePosition) => TValue | undefined;
316
- /**
317
- * Returns a copy of all items in the queue, including active and pending items.
318
- */
319
- peekAllItems: () => Array<TValue>;
320
- /**
321
- * Returns the items currently being processed (active tasks).
322
- */
323
- peekActiveItems: () => Array<TValue>;
324
- /**
325
- * Returns the items waiting to be processed (pending tasks).
326
- */
327
- peekPendingItems: () => Array<TValue>;
328
- /**
329
- * Starts processing items in the queue. If already running, does nothing.
330
- */
331
- start: () => void;
332
- /**
333
- * Stops processing items in the queue. Does not clear the queue.
334
- */
335
- stop: () => void;
336
- /**
337
- * Removes all pending items from the queue.
338
- * Does NOT affect active tasks.
339
- */
340
- clear: () => void;
341
- /**
342
- * Returns the AbortSignal for a specific execution.
343
- * If no executeCount is provided, returns the signal for the most recent execution.
344
- * Returns null if no execution is found or not currently executing.
345
- *
346
- * @param executeCount - Optional specific execution to get signal for
347
- * @example
348
- * ```typescript
349
- * const queuer = new AsyncQueuer(
350
- * async (item: string) => {
351
- * const signal = queuer.getAbortSignal()
352
- * if (signal) {
353
- * const response = await fetch(`/api/process/${item}`, { signal })
354
- * return response.json()
355
- * }
356
- * },
357
- * { concurrency: 2 }
358
- * )
359
- * ```
360
- */
361
- getAbortSignal: (executeCount?: number) => AbortSignal | null;
362
- /**
363
- * Aborts all ongoing executions with the internal abort controllers.
364
- * Does NOT clear out the items.
365
- */
366
- abort: () => void;
367
- /**
368
- * Resets the queuer state to its default values
369
- */
370
- reset: () => void;
371
- }
372
- /**
373
- * Creates a new AsyncQueuer instance and returns a bound addItem function for adding tasks.
374
- * The queuer is started automatically and ready to process items.
375
- *
376
- * Async vs Sync Versions:
377
- * The async version provides advanced features over the sync queue function:
378
- * - Returns promises that can be awaited for task results
379
- * - Built-in retry support via AsyncRetryer integration for each queued task
380
- * - Abort support to cancel in-flight task executions
381
- * - Comprehensive error handling with onError callbacks and throwOnError control
382
- * - Detailed execution tracking (success/error/settle counts)
383
- * - Concurrent execution support (process multiple items simultaneously)
384
- *
385
- * The sync queue function is lighter weight and simpler when you don't need async features,
386
- * return values, or execution control.
387
- *
388
- * What is Queuing?
389
- * Queuing is a technique for managing and processing items sequentially or with controlled concurrency.
390
- * Tasks are processed up to the configured concurrency limit. When a task completes,
391
- * the next pending task is processed if the concurrency limit allows.
392
- *
393
- * Configuration Options:
394
- * - `concurrency`: Maximum number of concurrent tasks (default: 1)
395
- * - `wait`: Time to wait between processing items (default: 0)
396
- * - `maxSize`: Maximum number of items allowed in the queue (default: Infinity)
397
- * - `getPriority`: Function to determine item priority
398
- * - `addItemsTo`: Default position to add items ('back' or 'front', default: 'back')
399
- * - `getItemsFrom`: Default position to get items ('front' or 'back', default: 'front')
400
- * - `expirationDuration`: Maximum time items can stay in queue
401
- * - `started`: Whether to start processing immediately (default: true)
402
- * - `asyncRetryerOptions`: Configure retry behavior for task executions
403
- *
404
- * Error Handling:
405
- * - If an `onError` handler is provided, it will be called with the error and queuer instance
406
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
407
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
408
- * - Both onError and throwOnError can be used together; the handler will be called before any error is thrown
409
- * - The error state can be checked using the underlying AsyncQueuer instance
410
- *
411
- * State Management:
412
- * - Uses TanStack Store for reactive state management
413
- * - Use `initialState` to provide initial state values when creating the async queuer
414
- * - Use `onSuccess` callback to react to successful task execution and implement custom logic
415
- * - Use `onError` callback to react to task execution errors and implement custom error handling
416
- * - Use `onSettled` callback to react to task execution completion (success or error) and implement custom logic
417
- * - Use `onItemsChange` callback to react to items being added or removed from the queue
418
- * - Use `onExpire` callback to react to items expiring and implement custom logic
419
- * - Use `onReject` callback to react to items being rejected when the queue is full
420
- * - The state includes error count, expiration count, rejection count, running status, and success/settle counts
421
- * - State can be accessed via the underlying AsyncQueuer instance's `store.state` property
422
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
423
- *
424
- * @example
425
- * ```ts
426
- * const enqueue = asyncQueue<string>(async (item) => {
427
- * return item.toUpperCase();
428
- * }, {
429
- * concurrency: 2,
430
- * wait: 100,
431
- * onSuccess: (result) => console.log('Processed:', result)
432
- * });
433
- *
434
- * enqueue('hello');
435
- * ```
436
- */
437
- declare function asyncQueue<TValue>(fn: (value: TValue) => Promise<any>, initialOptions: AsyncQueuerOptions<TValue>): (item: TValue, position?: QueuePosition, runOnItemsChange?: boolean) => boolean;
438
- //#endregion
439
- export { AsyncQueuer, AsyncQueuerOptions, AsyncQueuerState, asyncQueue, asyncQueuerOptions };
440
- //# sourceMappingURL=async-queuer.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"async-queuer.js","names":["#setState","#checkExpiredItems","#getConcurrency","#getWait","#timeoutIds","#tick","#clearTimeouts","#getAllItems"],"sources":["../src/async-queuer.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 { OptionalKeys } from './types'\nimport type { QueuePosition } from './queuer'\n\nexport interface AsyncQueuerState<TValue> {\n /**\n * Items currently being processed by the queuer\n */\n activeItems: Array<TValue>\n /**\n * Number of times addItem has been called (for reduction calculations)\n */\n addItemCount: number\n /**\n * Number of task executions that have resulted in errors\n */\n errorCount: number\n /**\n * Number of times execute has been called\n */\n executeCount: number\n /**\n * Number of items that have been removed from the queue due to expiration\n */\n expirationCount: number\n /**\n * Whether the queuer has no items to process (items array is empty)\n */\n isEmpty: boolean\n /**\n * Whether the queuer is currently executing\n */\n isExecuting: boolean\n /**\n * Whether the queuer has reached its maximum capacity\n */\n isFull: boolean\n /**\n * Whether the queuer is not currently processing any items\n */\n isIdle: boolean\n /**\n * Whether the queuer is active and will process items automatically\n */\n isRunning: boolean\n /**\n * Array of items currently waiting to be processed\n */\n items: Array<TValue>\n /**\n * Timestamps when items were added to the queue for expiration tracking\n */\n itemTimestamps: Array<number>\n /**\n * The result from the most recent task execution\n */\n lastResult: any\n /**\n * Whether the queuer has a pending timeout for processing the next item\n */\n pendingTick: boolean\n /**\n * Number of items that have been rejected from being added to the queue\n */\n rejectionCount: number\n /**\n * Number of task executions that have completed (either successfully or with errors)\n */\n settledCount: number\n /**\n * Number of items currently in the queue\n */\n size: number\n /**\n * Current processing status - 'idle' when not processing, 'running' when active, 'stopped' when paused\n */\n status: 'idle' | 'running' | 'stopped'\n /**\n * Number of task executions that have completed successfully\n */\n successCount: number\n}\n\nfunction getDefaultAsyncQueuerState<TValue>(): AsyncQueuerState<TValue> {\n return {\n activeItems: [],\n addItemCount: 0,\n errorCount: 0,\n executeCount: 0,\n expirationCount: 0,\n isEmpty: true,\n isExecuting: false,\n isFull: false,\n isIdle: true,\n isRunning: true,\n itemTimestamps: [],\n items: [],\n lastResult: null,\n pendingTick: false,\n rejectionCount: 0,\n settledCount: 0,\n size: 0,\n status: 'idle',\n successCount: 0,\n }\n}\n\nexport interface AsyncQueuerOptions<TValue> {\n /**\n * Options for configuring the underlying async retryer\n */\n asyncRetryerOptions?: AsyncRetryerOptions<(item: TValue) => Promise<any>>\n /**\n * Default position to add items to the queuer\n * @default 'back'\n */\n addItemsTo?: QueuePosition\n /**\n * Maximum number of concurrent tasks to process.\n * Can be a number or a function that returns a number.\n * @default 1\n */\n concurrency?: number | ((queuer: AsyncQueuer<TValue>) => number)\n /**\n * Maximum time in milliseconds that an item can stay in the queue\n * If not provided, items will never expire\n */\n expirationDuration?: number\n /**\n * Function to determine if an item has expired\n * If provided, this overrides the expirationDuration behavior\n */\n getIsExpired?: (item: TValue, addedAt: number) => boolean\n /**\n * Default position to get items from during processing\n * @default 'front'\n */\n getItemsFrom?: QueuePosition\n /**\n * Function to determine priority of items in the queuer\n * Higher priority items will be processed first\n * If not provided, will use static priority values attached to tasks\n */\n getPriority?: (item: TValue) => number\n /**\n * Initial items to populate the queuer with\n */\n initialItems?: Array<TValue>\n /**\n * Initial state for the async queuer\n */\n initialState?: Partial<AsyncQueuerState<TValue>>\n /**\n * Optional key to identify this async queuer instance.\n * If provided, the async queuer will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of items allowed in the queuer\n */\n maxSize?: number\n /**\n * Optional error handler for when a task throws.\n * If provided, the handler will be called with the error and queuer instance.\n * This can be used alongside throwOnError - the handler will be called before any error is thrown.\n */\n onError?: (error: Error, item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item expires in the queuer\n */\n onExpire?: (item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item is added or removed from the queuer\n */\n onItemsChange?: (queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item is rejected from being added to the queuer\n */\n onReject?: (item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Optional callback to call when a task is settled\n */\n onSettled?: (item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Optional callback to call when a task succeeds\n */\n onSuccess?: (result: any, item: TValue, queuer: AsyncQueuer<TValue>) => void\n /**\n * Whether the queuer should start processing tasks immediately or not.\n */\n started?: boolean\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 * Time in milliseconds to wait between processing items.\n * Can be a number or a function that returns a number.\n * @default 0\n */\n wait?: number | ((queuer: AsyncQueuer<TValue>) => number)\n}\n\n/**\n * Utility function for sharing common `AsyncQueuerOptions` options between different `AsyncQueuer` instances.\n */\nexport function asyncQueuerOptions<\n TValue = any,\n TOptions extends Partial<AsyncQueuerOptions<TValue>> = Partial<\n AsyncQueuerOptions<TValue>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\ntype AsyncQueuerOptionsWithOptionalCallbacks = OptionalKeys<\n Required<AsyncQueuerOptions<any>>,\n | 'initialState'\n | 'throwOnError'\n | 'onSuccess'\n | 'onSettled'\n | 'onReject'\n | 'onItemsChange'\n | 'onExpire'\n | 'onError'\n | 'key'\n>\n\nconst defaultOptions: AsyncQueuerOptionsWithOptionalCallbacks = {\n addItemsTo: 'back',\n asyncRetryerOptions: {\n maxAttempts: 1,\n },\n concurrency: 1,\n expirationDuration: Infinity,\n getIsExpired: () => false,\n getItemsFrom: 'front',\n getPriority: (item: any) => item?.priority ?? 0,\n initialItems: [],\n maxSize: Infinity,\n started: true,\n wait: 0,\n}\n\n/**\n * A flexible asynchronous queue for processing tasks with configurable concurrency, priority, and expiration.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync Queuer:\n * - Returns promises that can be awaited for task results\n * - Built-in retry support via AsyncRetryer integration for each queued task\n * - Abort support to cancel in-flight task executions\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n * - Concurrent execution support (process multiple items simultaneously)\n *\n * The sync Queuer is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Queuing?\n * Queuing is a technique for managing and processing items sequentially or with controlled concurrency.\n * Tasks are processed up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if the concurrency limit allows.\n *\n * Key Features:\n * - Priority queue support via the getPriority option\n * - Configurable concurrency limit\n * - Callbacks for task success, error, completion, and queue state changes\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause and resume processing\n * - Item expiration to remove stale items from the queue\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer 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 AsyncQueuer instance\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the async queuer\n * - Use `onSuccess` callback to react to successful task execution and implement custom logic\n * - Use `onError` callback to react to task execution errors and implement custom error handling\n * - Use `onSettled` callback to react to task execution completion (success or error) and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the queue\n * - Use `onExpire` callback to react to items expiring and implement custom logic\n * - Use `onReject` callback to react to items being rejected when the queue is full\n * - The state includes error count, expiration count, rejection count, running status, and success/settle counts\n * - State can be accessed via `asyncQueuer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `asyncQueuer.state`\n *\n * Example usage:\n * ```ts\n * const asyncQueuer = new AsyncQueuer<string>(async (item) => {\n * // process item\n * return item.toUpperCase();\n * }, {\n * concurrency: 2,\n * onSuccess: (result) => {\n * console.log(result);\n * }\n * });\n *\n * asyncQueuer.addItem('hello');\n * asyncQueuer.start();\n * ```\n */\nexport class AsyncQueuer<TValue> {\n readonly store: Store<Readonly<AsyncQueuerState<TValue>>> = new Store<\n AsyncQueuerState<TValue>\n >(getDefaultAsyncQueuerState<TValue>())\n key: string | undefined\n options: AsyncQueuerOptions<TValue>\n asyncRetryers = new Map<\n number,\n AsyncRetryer<(item: TValue) => Promise<any>>\n >()\n #timeoutIds: Set<ReturnType<typeof setTimeout>> = new Set()\n\n constructor(\n public fn: (item: TValue) => Promise<any>,\n initialOptions: AsyncQueuerOptions<TValue> = {},\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n const isInitiallyRunning =\n this.options.initialState?.isRunning ?? this.options.started ?? true\n this.#setState({\n ...this.options.initialState,\n isRunning: isInitiallyRunning,\n })\n\n if (this.options.initialState?.items) {\n if (this.store.state.isRunning) {\n this.#tick()\n }\n } else {\n for (let i = 0; i < (this.options.initialItems?.length ?? 0); i++) {\n const item = this.options.initialItems![i]!\n const isLast = i === (this.options.initialItems?.length ?? 0) - 1\n this.addItem(item, this.options.addItemsTo ?? 'back', isLast)\n }\n }\n\n if (this.key) {\n pacerEventClient.on('d-AsyncQueuer', (e) => {\n if (e.payload.key !== this.key) return\n this.#setState(\n e.payload.store.state as Partial<AsyncQueuerState<TValue>>,\n )\n this.setOptions(\n e.payload.options as Partial<AsyncQueuerOptions<TValue>>,\n )\n })\n }\n }\n\n /**\n * Updates the queuer options. New options are merged with existing options.\n */\n setOptions = (newOptions: Partial<AsyncQueuerOptions<TValue>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<AsyncQueuerState<TValue>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n\n const { activeItems, items, isRunning } = combinedState\n\n const size = items.length\n const isFull = size >= (this.options.maxSize ?? Infinity)\n const isEmpty = size === 0\n const isIdle = isRunning && isEmpty && activeItems.length === 0\n\n const status = isIdle ? 'idle' : isRunning ? 'running' : 'stopped'\n\n return {\n ...combinedState,\n isEmpty,\n isFull,\n isIdle,\n size,\n status,\n }\n })\n emitChange('AsyncQueuer', this)\n }\n\n /**\n * Returns the current wait time (in milliseconds) between processing items.\n * If a function is provided, it is called with the queuer instance.\n */\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait ?? 0, this)\n }\n\n /**\n * Returns the current concurrency limit for processing items.\n * If a function is provided, it is called with the queuer instance.\n */\n #getConcurrency = (): number => {\n return parseFunctionOrValue(this.options.concurrency ?? 1, this)\n }\n\n /**\n * Processes items in the queue up to the concurrency limit. Internal use only.\n */\n #tick = () => {\n if (!this.store.state.isRunning) {\n this.#setState({ pendingTick: false })\n return\n }\n this.#setState({ pendingTick: true })\n\n // Check for expired items\n this.#checkExpiredItems()\n\n // Process items concurrently up to the concurrency limit\n let scheduledAsyncWork = false\n const activeItems = [...this.store.state.activeItems]\n while (\n activeItems.length < this.#getConcurrency() &&\n this.store.state.items.length > 0\n ) {\n const nextItem = this.peekNextItem()\n if (nextItem === undefined) {\n break\n }\n activeItems.push(nextItem)\n this.#setState({\n activeItems: [...activeItems],\n })\n scheduledAsyncWork = true\n ;(async () => {\n try {\n await this.execute()\n } catch {\n // errors are already surfaced via onError/errorCount (and rethrown to\n // direct execute/flush callers); swallowing here prevents unhandled\n // rejections and keeps the processing chain alive\n }\n\n const wait = this.#getWait()\n if (wait > 0) {\n const timeoutId = setTimeout(() => {\n this.#timeoutIds.delete(timeoutId)\n this.#tick()\n }, wait)\n this.#timeoutIds.add(timeoutId)\n return\n }\n\n this.#tick()\n })()\n }\n\n // pendingTick must stay true while executions or wait timers are pending so\n // that addItem does not trigger an extra tick that bypasses the wait period\n if (!scheduledAsyncWork) {\n this.#setState({ pendingTick: false })\n }\n }\n\n /**\n * Adds an item to the queue. If the queue is full, the item is rejected and onReject is called.\n * Items can be inserted based on priority or at the front/back depending on configuration.\n * `undefined` cannot be queued (it is the internal \"no item\" sentinel) and is always rejected.\n *\n * @example\n * ```ts\n * queuer.addItem({ value: 'task', priority: 10 });\n * queuer.addItem('task2', 'front');\n * ```\n */\n addItem = (\n item: TValue,\n position: QueuePosition = this.options.addItemsTo ?? 'back',\n runOnItemsChange: boolean = true,\n ): boolean => {\n this.#setState({\n addItemCount: this.store.state.addItemCount + 1,\n })\n\n // undefined is the internal \"no item\" sentinel (peekNextItem/getNextItem);\n // queuing it would wedge the processing loop and block items behind it\n if (item === undefined) {\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(item, this)\n return false\n }\n\n if (this.store.state.items.length >= (this.options.maxSize ?? Infinity)) {\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(item, this)\n return false\n }\n\n // Get priority either from the function or from getPriority option\n const priority =\n this.options.getPriority !== defaultOptions.getPriority\n ? this.options.getPriority!(item)\n : (item as any)?.priority\n\n const items = this.store.state.items\n const itemTimestamps = this.store.state.itemTimestamps\n\n if (priority !== undefined) {\n // Insert based on priority - higher priority items go to front\n const insertIndex = items.findIndex((existing) => {\n const existingPriority =\n this.options.getPriority !== defaultOptions.getPriority\n ? this.options.getPriority!(existing)\n : (existing as any)?.priority\n return existingPriority < priority\n })\n\n if (insertIndex === -1) {\n items.push(item)\n itemTimestamps.push(Date.now())\n } else {\n items.splice(insertIndex, 0, item)\n itemTimestamps.splice(insertIndex, 0, Date.now())\n }\n } else {\n if (position === 'front') {\n // Default FIFO/LIFO behavior\n items.unshift(item)\n itemTimestamps.unshift(Date.now())\n } else {\n // LIFO\n items.push(item)\n itemTimestamps.push(Date.now())\n }\n }\n\n this.#setState({\n items,\n itemTimestamps,\n })\n\n if (runOnItemsChange) {\n this.options.onItemsChange?.(this)\n }\n\n if (this.store.state.isRunning && !this.store.state.pendingTick) {\n this.#tick()\n }\n\n return true\n }\n\n /**\n * Removes and returns the next item from the queue without executing the task function.\n * Use for manual queue management. Normally, use execute() to process items.\n *\n * @example\n * ```ts\n * // FIFO\n * queuer.getNextItem();\n * // LIFO\n * queuer.getNextItem('back');\n * ```\n */\n getNextItem = (\n position: QueuePosition = this.options.getItemsFrom ?? 'front',\n ): TValue | undefined => {\n const { items, itemTimestamps } = this.store.state\n let item: TValue | undefined\n\n // When priority function is provided or position is 'front', always get from front (highest priority)\n // Priority takes precedence over FIFO/LIFO behavior\n if (\n this.options.getPriority !== defaultOptions.getPriority ||\n position === 'front'\n ) {\n item = items[0]\n if (item !== undefined) {\n this.#setState({\n items: items.slice(1),\n itemTimestamps: itemTimestamps.slice(1),\n })\n }\n } else {\n item = items[items.length - 1]\n if (item !== undefined) {\n this.#setState({\n items: items.slice(0, -1),\n itemTimestamps: itemTimestamps.slice(0, -1),\n })\n }\n }\n\n if (item !== undefined) {\n this.options.onItemsChange?.(this)\n }\n\n return item\n }\n\n #getAllItems = (): Array<TValue> => {\n const items = this.peekAllItems()\n this.clear()\n return items\n }\n\n /**\n * Removes and returns the next item from the queue and executes the task function with it.\n *\n * @example\n * ```ts\n * queuer.execute();\n * // LIFO\n * queuer.execute('back');\n * ```\n */\n execute = async (position?: QueuePosition): Promise<any> => {\n const item = this.getNextItem(position)\n\n if (item !== undefined) {\n const currentExecuteCount = this.store.state.executeCount + 1\n this.#setState({\n executeCount: currentExecuteCount,\n isExecuting: true,\n })\n try {\n const currentAsyncRetryer = new AsyncRetryer(\n this.fn,\n this.options.asyncRetryerOptions,\n )\n this.asyncRetryers.set(currentExecuteCount, currentAsyncRetryer)\n const lastResult = await currentAsyncRetryer.execute(item) // EXECUTE!\n this.#setState({\n successCount: this.store.state.successCount + 1,\n lastResult,\n })\n this.options.onSuccess?.(lastResult, item, this)\n } catch (error) {\n this.#setState({\n errorCount: this.store.state.errorCount + 1,\n })\n this.options.onError?.(error as Error, item, this)\n if (this.options.throwOnError) {\n throw error\n }\n } finally {\n this.asyncRetryers.delete(currentExecuteCount) // dispose retryer\n // remove only one occurrence so duplicate item values keep accurate\n // concurrency accounting\n const remainingActiveItems = [...this.store.state.activeItems]\n const activeItemIndex = remainingActiveItems.indexOf(item)\n if (activeItemIndex !== -1) {\n remainingActiveItems.splice(activeItemIndex, 1)\n }\n this.#setState({\n activeItems: remainingActiveItems,\n // other executions may still be in flight (concurrency > 1 or flush)\n isExecuting: this.asyncRetryers.size > 0,\n settledCount: this.store.state.settledCount + 1,\n })\n this.options.onSettled?.(item, this)\n }\n }\n return item\n }\n\n /**\n * Processes a specified number of items to execute immediately with no wait time\n * If no numberOfItems is provided, all items will be processed\n */\n flush = async (\n numberOfItems: number = this.store.state.items.length,\n position?: QueuePosition,\n ): Promise<void> => {\n this.#clearTimeouts() // clear any pending timeouts (kills the tick chain)\n const results = await Promise.allSettled(\n Array.from({ length: numberOfItems }, () => this.execute(position)),\n )\n // the tick chain was killed above; restart it so remaining and future items\n // process even when a flushed task rejected. Remaining items resume with the\n // normal wait spacing after the flushed executions.\n this.#setState({ pendingTick: false })\n if (this.store.state.isRunning && this.store.state.items.length > 0) {\n const wait = this.#getWait()\n if (wait > 0) {\n this.#setState({ pendingTick: true })\n const timeoutId = setTimeout(() => {\n this.#timeoutIds.delete(timeoutId)\n this.#tick()\n }, wait)\n this.#timeoutIds.add(timeoutId)\n } else {\n this.#tick()\n }\n }\n const failure = results.find(\n (result): result is PromiseRejectedResult => result.status === 'rejected',\n )\n if (failure) {\n throw failure.reason\n }\n }\n\n /**\n * Processes all items in the queue as a batch using the provided function as an argument\n * The queue is cleared after processing\n */\n flushAsBatch = async (\n batchFunction: (items: Array<TValue>) => Promise<any>,\n ): Promise<void> => {\n this.#clearTimeouts() // clear any pending timeouts (kills the tick chain)\n const items = this.#getAllItems()\n try {\n await batchFunction(items)\n } finally {\n // restore the tick chain even when the batch function rejects\n this.#setState({ pendingTick: false })\n if (this.store.state.isRunning && this.store.state.items.length > 0) {\n this.#tick()\n }\n }\n }\n\n /**\n * Checks for expired items in the queue and removes them. Calls onExpire for each expired item.\n * Internal use only.\n */\n #checkExpiredItems = (): void => {\n if (\n (this.options.expirationDuration ?? Infinity) === Infinity &&\n this.options.getIsExpired === defaultOptions.getIsExpired\n ) {\n return\n }\n\n const now = Date.now()\n const expiredIndices: Array<number> = []\n\n // Find indices of expired items\n for (let i = 0; i < this.store.state.items.length; i++) {\n const timestamp = this.store.state.itemTimestamps[i]\n if (timestamp === undefined) continue\n\n const item = this.store.state.items[i]\n if (item === undefined) continue\n\n const isExpired =\n this.options.getIsExpired !== defaultOptions.getIsExpired\n ? this.options.getIsExpired!(item, timestamp)\n : now - timestamp > (this.options.expirationDuration ?? Infinity)\n\n if (isExpired) {\n expiredIndices.push(i)\n }\n }\n\n // Remove expired items from back to front to maintain indices\n for (let i = expiredIndices.length - 1; i >= 0; i--) {\n const index = expiredIndices[i]\n if (index === undefined) continue\n\n const expiredItem = this.store.state.items[index]\n if (expiredItem === undefined) continue\n\n const newItems = [...this.store.state.items]\n const newTimestamps = [...this.store.state.itemTimestamps]\n newItems.splice(index, 1)\n newTimestamps.splice(index, 1)\n this.#setState({\n items: newItems,\n itemTimestamps: newTimestamps,\n expirationCount: this.store.state.expirationCount + 1,\n })\n this.options.onExpire?.(expiredItem, this)\n }\n\n if (expiredIndices.length > 0) {\n this.options.onItemsChange?.(this)\n }\n }\n\n /**\n * Returns the next item in the queue without removing it.\n *\n * @example\n * ```ts\n * queuer.peekNextItem(); // front\n * queuer.peekNextItem('back'); // back\n * ```\n */\n peekNextItem = (position: QueuePosition = 'front'): TValue | undefined => {\n if (position === 'front') {\n return this.store.state.items[0]\n }\n return this.store.state.items[this.store.state.items.length - 1]\n }\n\n /**\n * Returns a copy of all items in the queue, including active and pending items.\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.peekActiveItems(), ...this.peekPendingItems()]\n }\n\n /**\n * Returns the items currently being processed (active tasks).\n */\n peekActiveItems = (): Array<TValue> => {\n return [...this.store.state.activeItems]\n }\n\n /**\n * Returns the items waiting to be processed (pending tasks).\n */\n peekPendingItems = (): Array<TValue> => {\n return [...this.store.state.items]\n }\n\n /**\n * Starts processing items in the queue. If already running, does nothing.\n */\n start = (): void => {\n this.#setState({ isRunning: true })\n if (!this.store.state.pendingTick && this.store.state.items.length > 0) {\n this.#tick()\n }\n }\n\n /**\n * Stops processing items in the queue. Does not clear the queue.\n */\n stop = (): void => {\n this.#clearTimeouts()\n this.#setState({ isRunning: false, pendingTick: false })\n }\n\n #clearTimeouts = (): void => {\n this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))\n this.#timeoutIds.clear()\n }\n\n /**\n * Removes all pending items from the queue.\n * Does NOT affect active tasks.\n */\n clear = (): void => {\n this.#setState({ items: [], itemTimestamps: [] })\n this.options.onItemsChange?.(this)\n }\n\n /**\n * Returns the AbortSignal for a specific execution.\n * If no executeCount 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 executeCount - Optional specific execution to get signal for\n * @example\n * ```typescript\n * const queuer = new AsyncQueuer(\n * async (item: string) => {\n * const signal = queuer.getAbortSignal()\n * if (signal) {\n * const response = await fetch(`/api/process/${item}`, { signal })\n * return response.json()\n * }\n * },\n * { concurrency: 2 }\n * )\n * ```\n */\n getAbortSignal = (executeCount?: number): AbortSignal | null => {\n const count = executeCount ?? this.store.state.executeCount\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 clear out the items.\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 * Resets the queuer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultAsyncQueuerState<TValue>())\n this.options.onItemsChange?.(this)\n this.asyncRetryers.forEach((retryer) => retryer.reset())\n }\n}\n\n/**\n * Creates a new AsyncQueuer instance and returns a bound addItem function for adding tasks.\n * The queuer is started automatically and ready to process items.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync queue function:\n * - Returns promises that can be awaited for task results\n * - Built-in retry support via AsyncRetryer integration for each queued task\n * - Abort support to cancel in-flight task executions\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n * - Concurrent execution support (process multiple items simultaneously)\n *\n * The sync queue function is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Queuing?\n * Queuing is a technique for managing and processing items sequentially or with controlled concurrency.\n * Tasks are processed up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if the concurrency limit allows.\n *\n * Configuration Options:\n * - `concurrency`: Maximum number of concurrent tasks (default: 1)\n * - `wait`: Time to wait between processing items (default: 0)\n * - `maxSize`: Maximum number of items allowed in the queue (default: Infinity)\n * - `getPriority`: Function to determine item priority\n * - `addItemsTo`: Default position to add items ('back' or 'front', default: 'back')\n * - `getItemsFrom`: Default position to get items ('front' or 'back', default: 'front')\n * - `expirationDuration`: Maximum time items can stay in queue\n * - `started`: Whether to start processing immediately (default: true)\n * - `asyncRetryerOptions`: Configure retry behavior for task executions\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer 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 AsyncQueuer instance\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the async queuer\n * - Use `onSuccess` callback to react to successful task execution and implement custom logic\n * - Use `onError` callback to react to task execution errors and implement custom error handling\n * - Use `onSettled` callback to react to task execution completion (success or error) and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the queue\n * - Use `onExpire` callback to react to items expiring and implement custom logic\n * - Use `onReject` callback to react to items being rejected when the queue is full\n * - The state includes error count, expiration count, rejection count, running status, and success/settle counts\n * - State can be accessed via the underlying AsyncQueuer instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * @example\n * ```ts\n * const enqueue = asyncQueue<string>(async (item) => {\n * return item.toUpperCase();\n * }, {\n * concurrency: 2,\n * wait: 100,\n * onSuccess: (result) => console.log('Processed:', result)\n * });\n *\n * enqueue('hello');\n * ```\n */\nexport function asyncQueue<TValue>(\n fn: (value: TValue) => Promise<any>,\n initialOptions: AsyncQueuerOptions<TValue>,\n) {\n const asyncQueuer = new AsyncQueuer<TValue>(fn, initialOptions)\n return asyncQueuer.addItem\n}\n"],"mappings":";;;;;;AAuFA,SAAS,6BAA+D;CACtE,OAAO;EACL,aAAa,CAAC;EACd,cAAc;EACd,YAAY;EACZ,cAAc;EACd,iBAAiB;EACjB,SAAS;EACT,aAAa;EACb,QAAQ;EACR,QAAQ;EACR,WAAW;EACX,gBAAgB,CAAC;EACjB,OAAO,CAAC;EACR,YAAY;EACZ,aAAa;EACb,gBAAgB;EAChB,cAAc;EACd,MAAM;EACN,QAAQ;EACR,cAAc;CAChB;AACF;;;;AAuGA,SAAgB,mBAKd,SAA6B;CAC7B,OAAO;AACT;AAeA,MAAM,iBAA0D;CAC9D,YAAY;CACZ,qBAAqB,EACnB,aAAa,EACf;CACA,aAAa;CACb,oBAAoB;CACpB,oBAAoB;CACpB,cAAc;CACd,cAAc,SAAc,MAAM,YAAY;CAC9C,cAAc,CAAC;CACf,SAAS;CACT,SAAS;CACT,MAAM;AACR;;;;;;;;;;;;;;;;;;;;;;;;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