@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,343 +0,0 @@
1
- import { OptionalKeys } from "./types.cjs";
2
- import { AsyncRetryer, AsyncRetryerOptions } from "./async-retryer.cjs";
3
- import { Store } from "@tanstack/store";
4
- //#region src/async-batcher.d.ts
5
- interface AsyncBatcherState<TValue> {
6
- /**
7
- * Number of batch executions that have resulted in errors
8
- */
9
- errorCount: number;
10
- /**
11
- * Number of batch executions that have been executed
12
- */
13
- executeCount: number;
14
- /**
15
- * Array of items that failed during batch processing
16
- */
17
- failedItems: Array<TValue>;
18
- /**
19
- * Whether the batcher has no items to process (items array is empty)
20
- */
21
- isEmpty: boolean;
22
- /**
23
- * Whether a batch is currently being processed asynchronously
24
- */
25
- isExecuting: boolean;
26
- /**
27
- * Whether the batcher is waiting for the timeout to trigger batch processing
28
- */
29
- isPending: boolean;
30
- /**
31
- * Array of items currently queued for batch processing
32
- */
33
- items: Array<TValue>;
34
- /**
35
- * The result from the most recent batch execution
36
- */
37
- lastResult: any;
38
- /**
39
- * Number of batch executions that have completed (either successfully or with errors)
40
- */
41
- settleCount: number;
42
- /**
43
- * Number of items currently in the batch queue
44
- */
45
- size: number;
46
- /**
47
- * Current processing status - 'idle' when not processing, 'pending' when waiting for timeout, 'executing' when processing, 'populated' when items are present, but no wait is configured
48
- */
49
- status: 'idle' | 'pending' | 'executing' | 'populated';
50
- /**
51
- * Number of batch executions that have completed successfully
52
- */
53
- successCount: number;
54
- /**
55
- * Total number of items that have failed processing across all batches
56
- */
57
- totalItemsFailed: number;
58
- /**
59
- * Total number of items that have been processed across all batches
60
- */
61
- totalItemsProcessed: number;
62
- }
63
- /**
64
- * Options for configuring an AsyncBatcher instance
65
- */
66
- interface AsyncBatcherOptions<TValue> {
67
- /**
68
- * Options for configuring the underlying async retryer
69
- */
70
- asyncRetryerOptions?: AsyncRetryerOptions<(items: Array<TValue>) => Promise<any>>;
71
- /**
72
- * Custom function to determine if a batch should be processed
73
- * Return true to process the batch immediately
74
- */
75
- getShouldExecute?: (items: Array<TValue>, batcher: AsyncBatcher<TValue>) => boolean;
76
- /**
77
- * Initial state for the async batcher
78
- */
79
- initialState?: Partial<AsyncBatcherState<TValue>>;
80
- /**
81
- * Optional key to identify this async batcher instance.
82
- * If provided, the async batcher will be identified by this key in the devtools and PacerProvider if applicable.
83
- */
84
- key?: string;
85
- /**
86
- * Maximum number of items in a batch
87
- * @default Infinity
88
- */
89
- maxSize?: number;
90
- /**
91
- * Optional error handler for when the batch function throws.
92
- * If provided, the handler will be called with the error, the batch of items that failed, and batcher instance.
93
- * This can be used alongside throwOnError - the handler will be called before any error is thrown.
94
- */
95
- onError?: (error: Error, batch: Array<TValue>, batcher: AsyncBatcher<TValue>) => void;
96
- /**
97
- * Callback fired after items are added to the batcher
98
- */
99
- onItemsChange?: (batcher: AsyncBatcher<TValue>) => void;
100
- /**
101
- * Optional callback to call when a batch is settled (completed or failed)
102
- */
103
- onSettled?: (batch: Array<TValue>, batcher: AsyncBatcher<TValue>) => void;
104
- /**
105
- * Optional callback to call when a batch succeeds
106
- */
107
- onSuccess?: (result: any, batch: Array<TValue>, batcher: AsyncBatcher<TValue>) => void;
108
- /**
109
- * Whether the batcher should start processing immediately
110
- * @default true
111
- */
112
- started?: boolean;
113
- /**
114
- * Whether to throw errors when they occur.
115
- * Defaults to true if no onError handler is provided, false if an onError handler is provided.
116
- * Can be explicitly set to override these defaults.
117
- */
118
- throwOnError?: boolean;
119
- /**
120
- * Maximum time in milliseconds to wait before processing a batch.
121
- * If the wait duration has elapsed, the batch will be processed.
122
- * If not provided, the batch will not be triggered by a timeout.
123
- * @default Infinity
124
- */
125
- wait?: number | ((asyncBatcher: AsyncBatcher<TValue>) => number);
126
- }
127
- /**
128
- * Utility function for sharing common `AsyncBatcherOptions` options between different `AsyncBatcher` instances.
129
- *
130
- */
131
- declare function asyncBatcherOptions<TValue = any, TOptions extends Partial<AsyncBatcherOptions<TValue>> = Partial<AsyncBatcherOptions<TValue>>>(options: TOptions): TOptions;
132
- type AsyncBatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<Required<AsyncBatcherOptions<TValue>>, 'initialState' | 'onError' | 'onItemsChange' | 'onSettled' | 'onSuccess' | 'key'>;
133
- /**
134
- * A class that collects items and processes them in batches asynchronously.
135
- *
136
- * Async vs Sync Versions:
137
- * The async version provides advanced features over the sync Batcher:
138
- * - Returns promises that can be awaited for batch results
139
- * - Built-in retry support via AsyncRetryer integration
140
- * - Abort support to cancel in-flight batch executions
141
- * - Cancel support to prevent pending batches from starting
142
- * - Comprehensive error handling with onError callbacks and throwOnError control
143
- * - Detailed execution tracking (success/error/settle counts)
144
- *
145
- * The sync Batcher is lighter weight and simpler when you don't need async features,
146
- * return values, or execution control.
147
- *
148
- * What is Batching?
149
- * Batching is a technique for grouping multiple operations together to be processed as a single unit.
150
- *
151
- * The AsyncBatcher provides a flexible way to implement async batching with configurable:
152
- * - Maximum batch size (number of items per batch)
153
- * - Time-based batching (process after X milliseconds)
154
- * - Custom batch processing logic via getShouldExecute
155
- * - Event callbacks for monitoring batch operations
156
- * - Error handling for failed batch operations
157
- *
158
- * Error Handling:
159
- * - If an `onError` handler is provided, it will be called with the error, the batch of items that failed, and batcher instance
160
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
161
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
162
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
163
- * - The error state can be checked using the AsyncBatcher instance
164
- *
165
- * State Management:
166
- * - Uses TanStack Store for reactive state management
167
- * - Use `initialState` to provide initial state values when creating the async batcher
168
- * - Use `onSuccess` callback to react to successful batch execution and implement custom logic
169
- * - Use `onError` callback to react to batch execution errors and implement custom error handling
170
- * - Use `onSettled` callback to react to batch execution completion (success or error) and implement custom logic
171
- * - Use `onExecute` callback to react to batch execution and implement custom logic
172
- * - Use `onItemsChange` callback to react to items being added or removed from the batcher
173
- * - The state includes total items processed, success/error counts, and execution status
174
- * - State can be accessed via `asyncBatcher.store.state` when using the class directly
175
- * - When using framework adapters (React/Solid), state is accessed from `asyncBatcher.state`
176
- *
177
- * @example
178
- * ```ts
179
- * const batcher = new AsyncBatcher<number>(
180
- * async (items) => {
181
- * const result = await processItems(items);
182
- * console.log('Processing batch:', items);
183
- * return result;
184
- * },
185
- * {
186
- * maxSize: 5,
187
- * wait: 2000,
188
- * onSuccess: (result) => console.log('Batch succeeded:', result),
189
- * onError: (error) => console.error('Batch failed:', error)
190
- * }
191
- * );
192
- *
193
- * batcher.addItem(1);
194
- * batcher.addItem(2);
195
- * // After 2 seconds or when 5 items are added, whichever comes first,
196
- * // the batch will be processed and the result will be available
197
- * // batcher.execute() // manually trigger a batch
198
- * ```
199
- */
200
- declare class AsyncBatcher<TValue> {
201
- #private;
202
- fn: (items: Array<TValue>) => Promise<any>;
203
- readonly store: Store<Readonly<AsyncBatcherState<TValue>>>;
204
- key: string | undefined;
205
- options: AsyncBatcherOptionsWithOptionalCallbacks<TValue>;
206
- asyncRetryers: Map<number, AsyncRetryer<(items: Array<TValue>) => Promise<any>>>;
207
- constructor(fn: (items: Array<TValue>) => Promise<any>, initialOptions: AsyncBatcherOptions<TValue>);
208
- /**
209
- * Updates the async batcher options
210
- */
211
- setOptions: (newOptions: Partial<AsyncBatcherOptions<TValue>>) => void;
212
- /**
213
- * Adds an item to the async batcher
214
- * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed
215
- *
216
- * @returns The result from the batch function, or undefined if an error occurred and was handled by onError
217
- *
218
- * @throws The error from the batch function if no onError handler is configured or throwOnError is true
219
- */
220
- addItem: (item: TValue) => Promise<any>;
221
- /**
222
- * Processes the current batch of items immediately
223
- */
224
- flush: () => Promise<any>;
225
- /**
226
- * Returns a copy of all items in the async batcher
227
- */
228
- peekAllItems: () => Array<TValue>;
229
- peekFailedItems: () => Array<TValue>;
230
- /**
231
- * Removes all items from the async batcher
232
- */
233
- clear: () => void;
234
- /**
235
- * Returns the AbortSignal for a specific execution.
236
- * If no executeCount is provided, returns the signal for the most recent execution.
237
- * Returns null if no execution is found or not currently executing.
238
- *
239
- * @param executeCount - Optional specific execution to get signal for
240
- * @example
241
- * ```typescript
242
- * const batcher = new AsyncBatcher(
243
- * async (items: string[]) => {
244
- * const signal = batcher.getAbortSignal()
245
- * if (signal) {
246
- * const response = await fetch('/api/batch', {
247
- * method: 'POST',
248
- * body: JSON.stringify(items),
249
- * signal
250
- * })
251
- * return response.json()
252
- * }
253
- * },
254
- * { maxSize: 10, wait: 100 }
255
- * )
256
- * ```
257
- */
258
- getAbortSignal: (executeCount?: number) => AbortSignal | null;
259
- /**
260
- * Aborts all ongoing executions with the internal abort controllers.
261
- * Does NOT cancel any pending execution that have not started yet.
262
- * Does NOT clear out the items.
263
- */
264
- abort: () => void;
265
- /**
266
- * Cancels any pending execution that have not started yet.
267
- * Does NOT abort any execution already in progress.
268
- * Does NOT clear out the items.
269
- */
270
- cancel: () => void;
271
- /**
272
- * Resets the async batcher state to its default values
273
- */
274
- reset: () => void;
275
- }
276
- /**
277
- * Creates an async batcher that processes items in batches.
278
- *
279
- * Async vs Sync Versions:
280
- * The async version provides advanced features over the sync batch function:
281
- * - Returns promises that can be awaited for batch results
282
- * - Built-in retry support via AsyncRetryer integration
283
- * - Abort support to cancel in-flight batch executions
284
- * - Cancel support to prevent pending batches from starting
285
- * - Comprehensive error handling with onError callbacks and throwOnError control
286
- * - Detailed execution tracking (success/error/settle counts)
287
- *
288
- * The sync batch function is lighter weight and simpler when you don't need async features,
289
- * return values, or execution control.
290
- *
291
- * What is Batching?
292
- * Batching is a technique for grouping multiple operations together to be processed as a single unit.
293
- *
294
- * Configuration Options:
295
- * - `maxSize`: Maximum number of items per batch (default: Infinity)
296
- * - `wait`: Time to wait before processing batch (default: Infinity)
297
- * - `getShouldExecute`: Custom logic to trigger batch processing
298
- * - `asyncRetryerOptions`: Configure retry behavior for batch executions
299
- * - `started`: Whether to start processing immediately (default: true)
300
- *
301
- * Error Handling:
302
- * - If an `onError` handler is provided, it will be called with the error, the batch of items that failed, and batcher instance
303
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
304
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
305
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
306
- * - The error state can be checked using the underlying AsyncBatcher instance
307
- *
308
- * State Management:
309
- * - Uses TanStack Store for reactive state management
310
- * - Use `initialState` to provide initial state values when creating the async batcher
311
- * - Use `onSuccess` callback to react to successful batch execution and implement custom logic
312
- * - Use `onError` callback to react to batch execution errors and implement custom error handling
313
- * - Use `onSettled` callback to react to batch execution completion (success or error) and implement custom logic
314
- * - Use `onItemsChange` callback to react to items being added or removed from the batcher
315
- * - The state includes total items processed, success/error counts, and execution status
316
- * - State can be accessed via the underlying AsyncBatcher instance's `store.state` property
317
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
318
- *
319
- * @example
320
- * ```ts
321
- * const batchItems = asyncBatch<number>(
322
- * async (items) => {
323
- * const result = await processApiCall(items);
324
- * console.log('Processing:', items);
325
- * return result;
326
- * },
327
- * {
328
- * maxSize: 3,
329
- * wait: 1000,
330
- * onSuccess: (result) => console.log('Batch succeeded:', result),
331
- * onError: (error) => console.error('Batch failed:', error)
332
- * }
333
- * );
334
- *
335
- * batchItems(1);
336
- * batchItems(2);
337
- * batchItems(3); // Triggers batch processing
338
- * ```
339
- */
340
- declare function asyncBatch<TValue>(fn: (items: Array<TValue>) => Promise<any>, options: AsyncBatcherOptions<TValue>): (item: TValue) => Promise<any>;
341
- //#endregion
342
- export { AsyncBatcher, AsyncBatcherOptions, AsyncBatcherState, asyncBatch, asyncBatcherOptions };
343
- //# sourceMappingURL=async-batcher.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"async-batcher.js","names":["#setState","#execute","#clearTimeout","#timeoutId","#getWait"],"sources":["../src/async-batcher.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'\n\nexport interface AsyncBatcherState<TValue> {\n /**\n * Number of batch executions that have resulted in errors\n */\n errorCount: number\n /**\n * Number of batch executions that have been executed\n */\n executeCount: number\n /**\n * Array of items that failed during batch processing\n */\n failedItems: Array<TValue>\n /**\n * Whether the batcher has no items to process (items array is empty)\n */\n isEmpty: boolean\n /**\n * Whether a batch is currently being processed asynchronously\n */\n isExecuting: boolean\n /**\n * Whether the batcher is waiting for the timeout to trigger batch processing\n */\n isPending: boolean\n /**\n * Array of items currently queued for batch processing\n */\n items: Array<TValue>\n /**\n * The result from the most recent batch execution\n */\n lastResult: any\n /**\n * Number of batch executions that have completed (either successfully or with errors)\n */\n settleCount: number\n /**\n * Number of items currently in the batch queue\n */\n size: number\n /**\n * Current processing status - 'idle' when not processing, 'pending' when waiting for timeout, 'executing' when processing, 'populated' when items are present, but no wait is configured\n */\n status: 'idle' | 'pending' | 'executing' | 'populated'\n /**\n * Number of batch executions that have completed successfully\n */\n successCount: number\n /**\n * Total number of items that have failed processing across all batches\n */\n totalItemsFailed: number\n /**\n * Total number of items that have been processed across all batches\n */\n totalItemsProcessed: number\n}\n\nfunction getDefaultAsyncBatcherState<TValue>(): AsyncBatcherState<TValue> {\n return {\n errorCount: 0,\n executeCount: 0,\n failedItems: [],\n isEmpty: true,\n isExecuting: false,\n isPending: false,\n items: [],\n lastResult: undefined,\n settleCount: 0,\n size: 0,\n status: 'idle',\n successCount: 0,\n totalItemsProcessed: 0,\n totalItemsFailed: 0,\n }\n}\n\n/**\n * Options for configuring an AsyncBatcher instance\n */\nexport interface AsyncBatcherOptions<TValue> {\n /**\n * Options for configuring the underlying async retryer\n */\n asyncRetryerOptions?: AsyncRetryerOptions<\n (items: Array<TValue>) => Promise<any>\n >\n /**\n * Custom function to determine if a batch should be processed\n * Return true to process the batch immediately\n */\n getShouldExecute?: (\n items: Array<TValue>,\n batcher: AsyncBatcher<TValue>,\n ) => boolean\n /**\n * Initial state for the async batcher\n */\n initialState?: Partial<AsyncBatcherState<TValue>>\n /**\n * Optional key to identify this async batcher instance.\n * If provided, the async batcher will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of items in a batch\n * @default Infinity\n */\n maxSize?: number\n /**\n * Optional error handler for when the batch function throws.\n * If provided, the handler will be called with the error, the batch of items that failed, and batcher instance.\n * This can be used alongside throwOnError - the handler will be called before any error is thrown.\n */\n onError?: (\n error: Error,\n batch: Array<TValue>,\n batcher: AsyncBatcher<TValue>,\n ) => void\n /**\n * Callback fired after items are added to the batcher\n */\n onItemsChange?: (batcher: AsyncBatcher<TValue>) => void\n /**\n * Optional callback to call when a batch is settled (completed or failed)\n */\n onSettled?: (batch: Array<TValue>, batcher: AsyncBatcher<TValue>) => void\n /**\n * Optional callback to call when a batch succeeds\n */\n onSuccess?: (\n result: any,\n batch: Array<TValue>,\n batcher: AsyncBatcher<TValue>,\n ) => void\n /**\n * Whether the batcher should start processing immediately\n * @default true\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 * Maximum time in milliseconds to wait before processing a batch.\n * If the wait duration has elapsed, the batch will be processed.\n * If not provided, the batch will not be triggered by a timeout.\n * @default Infinity\n */\n wait?: number | ((asyncBatcher: AsyncBatcher<TValue>) => number)\n}\n\n/**\n * Utility function for sharing common `AsyncBatcherOptions` options between different `AsyncBatcher` instances.\n *\n */\nexport function asyncBatcherOptions<\n TValue = any,\n TOptions extends Partial<AsyncBatcherOptions<TValue>> = Partial<\n AsyncBatcherOptions<TValue>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\ntype AsyncBatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<\n Required<AsyncBatcherOptions<TValue>>,\n | 'initialState'\n | 'onError'\n | 'onItemsChange'\n | 'onSettled'\n | 'onSuccess'\n | 'key'\n>\n\nconst defaultOptions: AsyncBatcherOptionsWithOptionalCallbacks<any> = {\n asyncRetryerOptions: {\n maxAttempts: 1,\n },\n getShouldExecute: () => false,\n maxSize: Infinity,\n started: true,\n throwOnError: true,\n wait: Infinity,\n}\n\n/**\n * A class that collects items and processes them in batches asynchronously.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync Batcher:\n * - Returns promises that can be awaited for batch results\n * - Built-in retry support via AsyncRetryer integration\n * - Abort support to cancel in-flight batch executions\n * - Cancel support to prevent pending batches from starting\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n *\n * The sync Batcher is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Batching?\n * Batching is a technique for grouping multiple operations together to be processed as a single unit.\n *\n * The AsyncBatcher provides a flexible way to implement async batching with configurable:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - Error handling for failed batch operations\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error, the batch of items that failed, and batcher 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 AsyncBatcher 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 batcher\n * - Use `onSuccess` callback to react to successful batch execution and implement custom logic\n * - Use `onError` callback to react to batch execution errors and implement custom error handling\n * - Use `onSettled` callback to react to batch execution completion (success or error) and implement custom logic\n * - Use `onExecute` callback to react to batch execution and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the batcher\n * - The state includes total items processed, success/error counts, and execution status\n * - State can be accessed via `asyncBatcher.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `asyncBatcher.state`\n *\n * @example\n * ```ts\n * const batcher = new AsyncBatcher<number>(\n * async (items) => {\n * const result = await processItems(items);\n * console.log('Processing batch:', items);\n * return result;\n * },\n * {\n * maxSize: 5,\n * wait: 2000,\n * onSuccess: (result) => console.log('Batch succeeded:', result),\n * onError: (error) => console.error('Batch failed:', error)\n * }\n * );\n *\n * batcher.addItem(1);\n * batcher.addItem(2);\n * // After 2 seconds or when 5 items are added, whichever comes first,\n * // the batch will be processed and the result will be available\n * // batcher.execute() // manually trigger a batch\n * ```\n */\nexport class AsyncBatcher<TValue> {\n readonly store: Store<Readonly<AsyncBatcherState<TValue>>> = new Store(\n getDefaultAsyncBatcherState<TValue>(),\n )\n key: string | undefined\n options: AsyncBatcherOptionsWithOptionalCallbacks<TValue>\n asyncRetryers = new Map<\n number,\n AsyncRetryer<(items: Array<TValue>) => Promise<any>>\n >()\n #timeoutId: ReturnType<typeof setTimeout> | null = null\n\n constructor(\n public fn: (items: Array<TValue>) => Promise<any>,\n initialOptions: AsyncBatcherOptions<TValue>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-AsyncBatcher', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<AsyncBatcherState<TValue>>,\n )\n this.setOptions(\n event.payload.options as Partial<AsyncBatcherOptions<TValue>>,\n )\n })\n }\n }\n\n /**\n * Updates the async batcher options\n */\n setOptions = (newOptions: Partial<AsyncBatcherOptions<TValue>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<AsyncBatcherState<TValue>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isExecuting, isPending, items } = combinedState\n const size = items.length\n const isEmpty = size === 0\n return {\n ...combinedState,\n isEmpty,\n size,\n status: isExecuting\n ? 'executing'\n : isPending\n ? 'pending'\n : isEmpty\n ? 'idle'\n : 'populated',\n }\n })\n emitChange('AsyncBatcher', this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Adds an item to the async batcher\n * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed\n *\n * @returns The result from the batch function, or undefined if an error occurred and was handled by onError\n *\n * @throws The error from the batch function if no onError handler is configured or throwOnError is true\n */\n addItem = async (item: TValue): Promise<any> => {\n this.#setState({\n items: [...this.store.state.items, item],\n isPending: this.options.wait !== Infinity,\n })\n this.options.onItemsChange?.(this)\n\n const shouldProcess =\n this.store.state.items.length >= this.options.maxSize ||\n this.options.getShouldExecute(this.store.state.items, this)\n\n if (shouldProcess) {\n return await this.#execute()\n } else if (this.options.wait !== Infinity) {\n this.#clearTimeout() // clear any pending timeout to replace it with a new one\n this.#timeoutId = setTimeout(() => this.#execute(), this.#getWait())\n await new Promise((resolve) => setTimeout(resolve, this.#getWait()))\n }\n }\n\n /**\n * Processes the current batch of items asynchronously.\n * This method will automatically be triggered if the batcher is running and any of these conditions are met:\n * - The number of items reaches maxSize\n * - The wait duration has elapsed\n * - The getShouldExecute function returns true upon adding an item\n *\n * You can also call this method manually to process the current batch at any time.\n *\n * @returns A promise that resolves with the result of the batch function, or undefined if an error occurred and was handled by onError\n * @throws The error from the batch function if no onError handler is configured or throwOnError is true\n */\n #execute = async (): Promise<any> => {\n if (this.store.state.items.length === 0) {\n return undefined\n }\n\n const currentExecuteCount = this.store.state.executeCount + 1\n const batch = this.peekAllItems() // copy of the items to be processed (to prevent race conditions)\n this.clear() // Clear items before processing to prevent race conditions\n this.options.onItemsChange?.(this)\n\n this.#setState({ isExecuting: true, executeCount: currentExecuteCount })\n\n try {\n const currentAsyncRetryer = new AsyncRetryer(\n this.fn,\n this.options.asyncRetryerOptions,\n )\n this.asyncRetryers.set(currentExecuteCount, currentAsyncRetryer)\n const result = await currentAsyncRetryer.execute(batch) // EXECUTE\n this.#setState({\n totalItemsProcessed:\n this.store.state.totalItemsProcessed + batch.length,\n lastResult: result,\n successCount: this.store.state.successCount + 1,\n })\n this.options.onSuccess?.(result, batch, this)\n return result\n } catch (error) {\n this.#setState({\n errorCount: this.store.state.errorCount + 1,\n failedItems: [...this.store.state.failedItems, ...batch],\n totalItemsFailed: this.store.state.totalItemsFailed + batch.length,\n })\n this.options.onError?.(error as Error, batch, this)\n if (this.options.throwOnError) {\n throw error\n }\n return undefined\n } finally {\n this.asyncRetryers.delete(currentExecuteCount) // dispose retryer\n this.#setState({\n isExecuting: false,\n settleCount: this.store.state.settleCount + 1,\n })\n this.options.onSettled?.(batch, this)\n }\n }\n\n /**\n * Processes the current batch of items immediately\n */\n flush = async (): Promise<any> => {\n this.#clearTimeout() // clear any pending timeout\n return await this.#execute()\n }\n\n /**\n * Returns a copy of all items in the async batcher\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.store.state.items]\n }\n\n peekFailedItems = (): Array<TValue> => {\n return [...this.store.state.failedItems]\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = null\n }\n }\n\n /**\n * Removes all items from the async batcher\n */\n clear = (): void => {\n this.#setState({ items: [], failedItems: [], isPending: false })\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 batcher = new AsyncBatcher(\n * async (items: string[]) => {\n * const signal = batcher.getAbortSignal()\n * if (signal) {\n * const response = await fetch('/api/batch', {\n * method: 'POST',\n * body: JSON.stringify(items),\n * signal\n * })\n * return response.json()\n * }\n * },\n * { maxSize: 10, wait: 100 }\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 cancel any pending execution that have not started yet.\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 * Cancels any pending execution that have not started yet.\n * Does NOT abort any execution already in progress.\n * Does NOT clear out the items.\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n isPending: false,\n })\n }\n\n /**\n * Resets the async batcher state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultAsyncBatcherState<TValue>())\n this.options.onItemsChange?.(this)\n this.asyncRetryers.forEach((retryer) => retryer.reset())\n }\n}\n\n/**\n * Creates an async batcher that processes items in batches.\n *\n * Async vs Sync Versions:\n * The async version provides advanced features over the sync batch function:\n * - Returns promises that can be awaited for batch results\n * - Built-in retry support via AsyncRetryer integration\n * - Abort support to cancel in-flight batch executions\n * - Cancel support to prevent pending batches from starting\n * - Comprehensive error handling with onError callbacks and throwOnError control\n * - Detailed execution tracking (success/error/settle counts)\n *\n * The sync batch function is lighter weight and simpler when you don't need async features,\n * return values, or execution control.\n *\n * What is Batching?\n * Batching is a technique for grouping multiple operations together to be processed as a single unit.\n *\n * Configuration Options:\n * - `maxSize`: Maximum number of items per batch (default: Infinity)\n * - `wait`: Time to wait before processing batch (default: Infinity)\n * - `getShouldExecute`: Custom logic to trigger batch processing\n * - `asyncRetryerOptions`: Configure retry behavior for batch executions\n * - `started`: Whether to start processing immediately (default: true)\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error, the batch of items that failed, and batcher 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 AsyncBatcher 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 batcher\n * - Use `onSuccess` callback to react to successful batch execution and implement custom logic\n * - Use `onError` callback to react to batch execution errors and implement custom error handling\n * - Use `onSettled` callback to react to batch execution completion (success or error) and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the batcher\n * - The state includes total items processed, success/error counts, and execution status\n * - State can be accessed via the underlying AsyncBatcher 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 batchItems = asyncBatch<number>(\n * async (items) => {\n * const result = await processApiCall(items);\n * console.log('Processing:', items);\n * return result;\n * },\n * {\n * maxSize: 3,\n * wait: 1000,\n * onSuccess: (result) => console.log('Batch succeeded:', result),\n * onError: (error) => console.error('Batch failed:', error)\n * }\n * );\n *\n * batchItems(1);\n * batchItems(2);\n * batchItems(3); // Triggers batch processing\n * ```\n */\nexport function asyncBatch<TValue>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: AsyncBatcherOptions<TValue>,\n) {\n const batcher = new AsyncBatcher<TValue>(fn, options)\n return batcher.addItem\n}\n"],"mappings":";;;;;;AAkEA,SAAS,8BAAiE;CACxE,OAAO;EACL,YAAY;EACZ,cAAc;EACd,aAAa,CAAC;EACd,SAAS;EACT,aAAa;EACb,WAAW;EACX,OAAO,CAAC;EACR,YAAY;EACZ,aAAa;EACb,MAAM;EACN,QAAQ;EACR,cAAc;EACd,qBAAqB;EACrB,kBAAkB;CACpB;AACF;;;;;AAoFA,SAAgB,oBAKd,SAA6B;CAC7B,OAAO;AACT;AAYA,MAAM,iBAAgE;CACpE,qBAAqB,E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