@tanstack/pacer 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/cjs/async-debouncer.cjs +32 -17
  2. package/dist/cjs/async-debouncer.cjs.map +1 -1
  3. package/dist/cjs/async-debouncer.d.cts +51 -9
  4. package/dist/cjs/async-queuer.cjs +189 -191
  5. package/dist/cjs/async-queuer.cjs.map +1 -1
  6. package/dist/cjs/async-queuer.d.cts +151 -94
  7. package/dist/cjs/async-rate-limiter.cjs +23 -13
  8. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  9. package/dist/cjs/async-rate-limiter.d.cts +54 -5
  10. package/dist/cjs/async-throttler.cjs +38 -17
  11. package/dist/cjs/async-throttler.cjs.map +1 -1
  12. package/dist/cjs/async-throttler.d.cts +51 -8
  13. package/dist/cjs/batcher.cjs +138 -0
  14. package/dist/cjs/batcher.cjs.map +1 -0
  15. package/dist/cjs/batcher.d.cts +149 -0
  16. package/dist/cjs/debouncer.cjs +3 -4
  17. package/dist/cjs/debouncer.cjs.map +1 -1
  18. package/dist/cjs/debouncer.d.cts +1 -2
  19. package/dist/cjs/index.cjs +3 -0
  20. package/dist/cjs/index.cjs.map +1 -1
  21. package/dist/cjs/index.d.cts +1 -0
  22. package/dist/cjs/queuer.cjs +68 -41
  23. package/dist/cjs/queuer.cjs.map +1 -1
  24. package/dist/cjs/queuer.d.cts +123 -92
  25. package/dist/cjs/rate-limiter.cjs +3 -4
  26. package/dist/cjs/rate-limiter.cjs.map +1 -1
  27. package/dist/cjs/rate-limiter.d.cts +1 -2
  28. package/dist/cjs/throttler.cjs +3 -4
  29. package/dist/cjs/throttler.cjs.map +1 -1
  30. package/dist/cjs/throttler.d.cts +1 -2
  31. package/dist/cjs/types.d.cts +1 -0
  32. package/dist/esm/async-debouncer.d.ts +51 -9
  33. package/dist/esm/async-debouncer.js +32 -17
  34. package/dist/esm/async-debouncer.js.map +1 -1
  35. package/dist/esm/async-queuer.d.ts +151 -94
  36. package/dist/esm/async-queuer.js +189 -191
  37. package/dist/esm/async-queuer.js.map +1 -1
  38. package/dist/esm/async-rate-limiter.d.ts +54 -5
  39. package/dist/esm/async-rate-limiter.js +23 -13
  40. package/dist/esm/async-rate-limiter.js.map +1 -1
  41. package/dist/esm/async-throttler.d.ts +51 -8
  42. package/dist/esm/async-throttler.js +38 -17
  43. package/dist/esm/async-throttler.js.map +1 -1
  44. package/dist/esm/batcher.d.ts +149 -0
  45. package/dist/esm/batcher.js +138 -0
  46. package/dist/esm/batcher.js.map +1 -0
  47. package/dist/esm/debouncer.d.ts +1 -2
  48. package/dist/esm/debouncer.js +3 -4
  49. package/dist/esm/debouncer.js.map +1 -1
  50. package/dist/esm/index.d.ts +1 -0
  51. package/dist/esm/index.js +3 -0
  52. package/dist/esm/index.js.map +1 -1
  53. package/dist/esm/queuer.d.ts +123 -92
  54. package/dist/esm/queuer.js +68 -41
  55. package/dist/esm/queuer.js.map +1 -1
  56. package/dist/esm/rate-limiter.d.ts +1 -2
  57. package/dist/esm/rate-limiter.js +3 -4
  58. package/dist/esm/rate-limiter.js.map +1 -1
  59. package/dist/esm/throttler.d.ts +1 -2
  60. package/dist/esm/throttler.js +3 -4
  61. package/dist/esm/throttler.js.map +1 -1
  62. package/dist/esm/types.d.ts +1 -0
  63. package/package.json +11 -1
  64. package/src/async-debouncer.ts +76 -20
  65. package/src/async-queuer.ts +309 -275
  66. package/src/async-rate-limiter.ts +73 -16
  67. package/src/async-throttler.ts +84 -20
  68. package/src/batcher.ts +253 -0
  69. package/src/debouncer.ts +3 -4
  70. package/src/index.ts +1 -0
  71. package/src/queuer.ts +142 -98
  72. package/src/rate-limiter.ts +3 -4
  73. package/src/throttler.ts +3 -4
  74. package/src/types.ts +3 -0
@@ -10,32 +10,26 @@ const defaultOptions = {
10
10
  getPriority: (item) => (item == null ? void 0 : item.priority) ?? 0,
11
11
  initialItems: [],
12
12
  maxSize: Infinity,
13
- onGetNextItem: () => {
14
- },
15
- onIsRunningChange: () => {
16
- },
17
- onItemsChange: () => {
18
- },
19
- onReject: () => {
20
- },
21
- onExpire: () => {
22
- },
23
13
  started: true,
24
14
  wait: 0
25
15
  };
26
16
  class AsyncQueuer {
27
- constructor(initialOptions = defaultOptions) {
17
+ constructor(fn, initialOptions) {
18
+ this.fn = fn;
28
19
  this._activeItems = /* @__PURE__ */ new Set();
29
- this._executionCount = 0;
20
+ this._successCount = 0;
21
+ this._errorCount = 0;
22
+ this._settledCount = 0;
30
23
  this._rejectionCount = 0;
31
24
  this._expirationCount = 0;
32
25
  this._items = [];
33
26
  this._itemTimestamps = [];
34
- this._onErrorCallbacks = [];
35
- this._onSettledCallbacks = [];
36
- this._onSuccessCallbacks = [];
37
27
  this._pendingTick = false;
38
- this._options = { ...defaultOptions, ...initialOptions };
28
+ this._options = {
29
+ ...defaultOptions,
30
+ ...initialOptions,
31
+ throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
32
+ };
39
33
  this._running = this._options.started;
40
34
  for (let i = 0; i < this._options.initialItems.length; i++) {
41
35
  const item = this._options.initialItems[i];
@@ -44,65 +38,50 @@ class AsyncQueuer {
44
38
  }
45
39
  }
46
40
  /**
47
- * Updates the queuer options
48
- * Returns the new options state
41
+ * Updates the queuer options. New options are merged with existing options.
49
42
  */
50
43
  setOptions(newOptions) {
51
44
  this._options = { ...this._options, ...newOptions };
52
45
  }
53
46
  /**
54
- * Returns the current queuer options
47
+ * Returns the current queuer options, including defaults and any overrides.
55
48
  */
56
49
  getOptions() {
57
50
  return this._options;
58
51
  }
59
52
  /**
60
- * Returns the current wait time between processing items
53
+ * Returns the current wait time (in milliseconds) between processing items.
54
+ * If a function is provided, it is called with the queuer instance.
61
55
  */
62
56
  getWait() {
63
57
  return utils.parseFunctionOrValue(this._options.wait, this);
64
58
  }
65
59
  /**
66
- * Returns the current concurrency limit
60
+ * Returns the current concurrency limit for processing items.
61
+ * If a function is provided, it is called with the queuer instance.
67
62
  */
68
63
  getConcurrency() {
69
64
  return utils.parseFunctionOrValue(this._options.concurrency, this);
70
65
  }
71
66
  /**
72
- * Processes items in the queuer
67
+ * Processes items in the queue up to the concurrency limit. Internal use only.
73
68
  */
74
69
  tick() {
70
+ var _a, _b;
75
71
  if (!this._running) {
76
72
  this._pendingTick = false;
77
73
  return;
78
74
  }
79
75
  this.checkExpiredItems();
80
76
  while (this._activeItems.size < this.getConcurrency() && !this.getIsEmpty()) {
81
- const nextFn = this.getNextItem();
82
- if (!nextFn) {
77
+ const nextItem = this.getPeek();
78
+ if (!nextItem) {
83
79
  break;
84
80
  }
85
- this._activeItems.add(nextFn);
86
- this._options.onItemsChange(this);
81
+ this._activeItems.add(nextItem);
82
+ (_b = (_a = this._options).onItemsChange) == null ? void 0 : _b.call(_a, this);
87
83
  (async () => {
88
- let success = false;
89
- let res;
90
- let error;
91
- try {
92
- res = await nextFn();
93
- success = true;
94
- } catch (e) {
95
- error = e;
96
- } finally {
97
- this._activeItems.delete(nextFn);
98
- this._options.onItemsChange(this);
99
- }
100
- if (success) {
101
- this._onSuccessCallbacks.forEach((cb) => cb(res));
102
- } else {
103
- this._onErrorCallbacks.forEach((cb) => cb(error));
104
- }
105
- this._onSettledCallbacks.forEach((cb) => cb(success ? res : error));
84
+ this._lastResult = await this.execute();
106
85
  const wait = this.getWait();
107
86
  if (wait > 0) {
108
87
  setTimeout(() => this.tick(), wait);
@@ -114,142 +93,109 @@ class AsyncQueuer {
114
93
  this._pendingTick = false;
115
94
  }
116
95
  /**
117
- * Checks for and removes expired items from the queuer
118
- */
119
- checkExpiredItems() {
120
- if (this._options.expirationDuration === Infinity && this._options.getIsExpired === defaultOptions.getIsExpired)
121
- return;
122
- const now = Date.now();
123
- const expiredIndices = [];
124
- for (let i = 0; i < this._items.length; i++) {
125
- const timestamp = this._itemTimestamps[i];
126
- if (timestamp === void 0) continue;
127
- const item = this._items[i];
128
- if (item === void 0) continue;
129
- const isExpired = this._options.getIsExpired !== defaultOptions.getIsExpired ? this._options.getIsExpired(item, timestamp) : now - timestamp > this._options.expirationDuration;
130
- if (isExpired) {
131
- expiredIndices.push(i);
132
- }
133
- }
134
- for (let i = expiredIndices.length - 1; i >= 0; i--) {
135
- const index = expiredIndices[i];
136
- if (index === void 0) continue;
137
- const expiredItem = this._items[index];
138
- if (expiredItem === void 0) continue;
139
- this._items.splice(index, 1);
140
- this._itemTimestamps.splice(index, 1);
141
- this._expirationCount++;
142
- this._options.onExpire(expiredItem, this);
143
- }
144
- if (expiredIndices.length > 0) {
145
- this._options.onItemsChange(this);
146
- }
147
- }
148
- /**
149
- * Starts the queuer and processes items
96
+ * Starts processing items in the queue. If already running, does nothing.
150
97
  */
151
98
  start() {
99
+ var _a, _b;
152
100
  this._running = true;
153
101
  if (!this._pendingTick && !this.getIsEmpty()) {
154
102
  this._pendingTick = true;
155
103
  this.tick();
156
104
  }
157
- this._options.onIsRunningChange(this);
158
- return new Promise((resolve) => {
159
- const checkIdle = () => {
160
- if (this.getIsIdle()) {
161
- resolve();
162
- } else {
163
- setTimeout(checkIdle, 100);
164
- }
165
- };
166
- checkIdle();
167
- });
105
+ (_b = (_a = this._options).onIsRunningChange) == null ? void 0 : _b.call(_a, this);
168
106
  }
169
107
  /**
170
- * Stops the queuer from processing items
108
+ * Stops processing items in the queue. Does not clear the queue.
171
109
  */
172
110
  stop() {
111
+ var _a, _b;
173
112
  this._running = false;
174
113
  this._pendingTick = false;
175
- this._options.onIsRunningChange(this);
114
+ (_b = (_a = this._options).onIsRunningChange) == null ? void 0 : _b.call(_a, this);
176
115
  }
177
116
  /**
178
- * Removes all items from the queuer
117
+ * Removes all pending items from the queue. Does not affect active tasks.
179
118
  */
180
119
  clear() {
120
+ var _a, _b;
181
121
  this._items = [];
182
- this._options.onItemsChange(this);
122
+ (_b = (_a = this._options).onItemsChange) == null ? void 0 : _b.call(_a, this);
183
123
  }
184
124
  /**
185
- * Resets the queuer to its initial state
125
+ * Resets the queuer to its initial state. Optionally repopulates with initial items.
126
+ * Does not affect callbacks or options.
186
127
  */
187
128
  reset(withInitialItems) {
188
129
  this.clear();
189
- this._executionCount = 0;
130
+ this._successCount = 0;
131
+ this._errorCount = 0;
132
+ this._settledCount = 0;
190
133
  if (withInitialItems) {
191
134
  this._items = [...this._options.initialItems];
192
135
  }
193
136
  this._running = this._options.started;
194
137
  }
195
138
  /**
196
- * Adds a task to the queuer
139
+ * Adds an item to the queue. If the queue is full, the item is rejected and onReject is called.
140
+ * Items can be inserted based on priority or at the front/back depending on configuration.
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * queuer.addItem({ value: 'task', priority: 10 });
145
+ * queuer.addItem('task2', 'front');
146
+ * ```
197
147
  */
198
- addItem(fn, position = this._options.addItemsTo, runOnItemsChange = true) {
148
+ addItem(item, position = this._options.addItemsTo, runOnItemsChange = true) {
149
+ var _a, _b, _c, _d;
199
150
  if (this.getIsFull()) {
200
151
  this._rejectionCount++;
201
- this._options.onReject(fn, this);
202
- return Promise.reject(new Error("Queuer is full"));
152
+ (_b = (_a = this._options).onReject) == null ? void 0 : _b.call(_a, item, this);
153
+ return;
203
154
  }
204
- return new Promise((resolve, reject) => {
205
- const task = Object.assign(
206
- async () => {
207
- try {
208
- const result = await fn();
209
- resolve(result);
210
- return result;
211
- } catch (error) {
212
- reject(error);
213
- throw error;
214
- }
215
- },
216
- { priority: fn.priority ?? void 0 }
217
- );
218
- const priority = this._options.getPriority !== defaultOptions.getPriority ? this._options.getPriority(task) : task.priority;
219
- if (priority !== void 0) {
220
- const insertIndex = this._items.findIndex((existing) => {
221
- const existingPriority = this._options.getPriority !== defaultOptions.getPriority ? this._options.getPriority(existing) : existing.priority;
222
- return existingPriority > priority;
223
- });
224
- if (insertIndex === -1) {
225
- this._items.push(task);
226
- this._itemTimestamps.push(Date.now());
227
- } else {
228
- this._items.splice(insertIndex, 0, task);
229
- this._itemTimestamps.splice(insertIndex, 0, Date.now());
230
- }
155
+ const priority = this._options.getPriority !== defaultOptions.getPriority ? this._options.getPriority(item) : item.priority;
156
+ if (priority !== void 0) {
157
+ const insertIndex = this._items.findIndex((existing) => {
158
+ const existingPriority = this._options.getPriority !== defaultOptions.getPriority ? this._options.getPriority(existing) : existing.priority;
159
+ return existingPriority < priority;
160
+ });
161
+ if (insertIndex === -1) {
162
+ this._items.push(item);
163
+ this._itemTimestamps.push(Date.now());
231
164
  } else {
232
- if (position === "front") {
233
- this._items.unshift(task);
234
- this._itemTimestamps.unshift(Date.now());
235
- } else {
236
- this._items.push(task);
237
- this._itemTimestamps.push(Date.now());
238
- }
239
- }
240
- if (runOnItemsChange) {
241
- this._options.onItemsChange(this);
165
+ this._items.splice(insertIndex, 0, item);
166
+ this._itemTimestamps.splice(insertIndex, 0, Date.now());
242
167
  }
243
- if (this._running && !this._pendingTick) {
244
- this._pendingTick = true;
245
- this.tick();
168
+ } else {
169
+ if (position === "front") {
170
+ this._items.unshift(item);
171
+ this._itemTimestamps.unshift(Date.now());
172
+ } else {
173
+ this._items.push(item);
174
+ this._itemTimestamps.push(Date.now());
246
175
  }
247
- });
176
+ }
177
+ if (runOnItemsChange) {
178
+ (_d = (_c = this._options).onItemsChange) == null ? void 0 : _d.call(_c, this);
179
+ }
180
+ if (this._running && !this._pendingTick) {
181
+ this._pendingTick = true;
182
+ this.tick();
183
+ }
248
184
  }
249
185
  /**
250
- * Removes and returns an item from the queuer
186
+ * Removes and returns the next item from the queue without executing the task function.
187
+ * Use for manual queue management. Normally, use execute() to process items.
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * // FIFO
192
+ * queuer.getNextItem();
193
+ * // LIFO
194
+ * queuer.getNextItem('back');
195
+ * ```
251
196
  */
252
197
  getNextItem(position = this._options.getItemsFrom) {
198
+ var _a, _b;
253
199
  let item;
254
200
  if (position === "front") {
255
201
  item = this._items.shift();
@@ -259,14 +205,85 @@ class AsyncQueuer {
259
205
  this._itemTimestamps.pop();
260
206
  }
261
207
  if (item !== void 0) {
262
- this._executionCount++;
263
- this._options.onItemsChange(this);
264
- this._options.onGetNextItem(item, this);
208
+ (_b = (_a = this._options).onItemsChange) == null ? void 0 : _b.call(_a, this);
209
+ }
210
+ return item;
211
+ }
212
+ /**
213
+ * Removes and returns the next item from the queue and executes the task function with it.
214
+ *
215
+ * @example
216
+ * ```ts
217
+ * queuer.execute();
218
+ * // LIFO
219
+ * queuer.execute('back');
220
+ * ```
221
+ */
222
+ async execute(position) {
223
+ var _a, _b, _c, _d, _e, _f, _g, _h;
224
+ const item = this.getNextItem(position);
225
+ if (item !== void 0) {
226
+ try {
227
+ this._lastResult = await this.fn(item);
228
+ this._successCount++;
229
+ (_b = (_a = this._options).onSuccess) == null ? void 0 : _b.call(_a, this._lastResult, this);
230
+ } catch (error) {
231
+ this._errorCount++;
232
+ (_d = (_c = this._options).onError) == null ? void 0 : _d.call(_c, error, this);
233
+ if (this._options.throwOnError) {
234
+ throw error;
235
+ }
236
+ } finally {
237
+ this._settledCount++;
238
+ this._activeItems.delete(item);
239
+ (_f = (_e = this._options).onItemsChange) == null ? void 0 : _f.call(_e, this);
240
+ (_h = (_g = this._options).onSettled) == null ? void 0 : _h.call(_g, this);
241
+ }
265
242
  }
266
243
  return item;
267
244
  }
268
245
  /**
269
- * Returns an item without removing it
246
+ * Checks for expired items in the queue and removes them. Calls onExpire for each expired item.
247
+ * Internal use only.
248
+ */
249
+ checkExpiredItems() {
250
+ var _a, _b, _c, _d;
251
+ if (this._options.expirationDuration === Infinity && this._options.getIsExpired === defaultOptions.getIsExpired)
252
+ return;
253
+ const now = Date.now();
254
+ const expiredIndices = [];
255
+ for (let i = 0; i < this._items.length; i++) {
256
+ const timestamp = this._itemTimestamps[i];
257
+ if (timestamp === void 0) continue;
258
+ const item = this._items[i];
259
+ if (item === void 0) continue;
260
+ const isExpired = this._options.getIsExpired !== defaultOptions.getIsExpired ? this._options.getIsExpired(item, timestamp) : now - timestamp > this._options.expirationDuration;
261
+ if (isExpired) {
262
+ expiredIndices.push(i);
263
+ }
264
+ }
265
+ for (let i = expiredIndices.length - 1; i >= 0; i--) {
266
+ const index = expiredIndices[i];
267
+ if (index === void 0) continue;
268
+ const expiredItem = this._items[index];
269
+ if (expiredItem === void 0) continue;
270
+ this._items.splice(index, 1);
271
+ this._itemTimestamps.splice(index, 1);
272
+ this._expirationCount++;
273
+ (_b = (_a = this._options).onExpire) == null ? void 0 : _b.call(_a, expiredItem, this);
274
+ }
275
+ if (expiredIndices.length > 0) {
276
+ (_d = (_c = this._options).onItemsChange) == null ? void 0 : _d.call(_c, this);
277
+ }
278
+ }
279
+ /**
280
+ * Returns the next item in the queue without removing it.
281
+ *
282
+ * @example
283
+ * ```ts
284
+ * queuer.getPeek(); // front
285
+ * queuer.getPeek('back'); // back
286
+ * ```
270
287
  */
271
288
  getPeek(position = "front") {
272
289
  if (position === "front") {
@@ -275,106 +292,87 @@ class AsyncQueuer {
275
292
  return this._items[this._items.length - 1];
276
293
  }
277
294
  /**
278
- * Returns true if the queuer is empty
295
+ * Returns true if the queue is empty (no pending items).
279
296
  */
280
297
  getIsEmpty() {
281
298
  return this._items.length === 0;
282
299
  }
283
300
  /**
284
- * Returns true if the queuer is full
301
+ * Returns true if the queue is full (reached maxSize).
285
302
  */
286
303
  getIsFull() {
287
304
  return this._items.length >= this._options.maxSize;
288
305
  }
289
306
  /**
290
- * Returns the current size of the queuer
307
+ * Returns the number of pending items in the queue.
291
308
  */
292
309
  getSize() {
293
310
  return this._items.length;
294
311
  }
295
312
  /**
296
- * Returns a copy of all items in the queuer
313
+ * Returns a copy of all items in the queue, including active and pending items.
297
314
  */
298
315
  getAllItems() {
299
316
  return [...this.getActiveItems(), ...this.getPendingItems()];
300
317
  }
301
318
  /**
302
- * Returns the active items
319
+ * Returns the items currently being processed (active tasks).
303
320
  */
304
321
  getActiveItems() {
305
322
  return Array.from(this._activeItems);
306
323
  }
307
324
  /**
308
- * Returns the pending items
325
+ * Returns the items waiting to be processed (pending tasks).
309
326
  */
310
327
  getPendingItems() {
311
328
  return [...this._items];
312
329
  }
313
330
  /**
314
- * Returns the number of items that have been removed from the queuer
331
+ * Returns the number of items that have been successfully processed.
315
332
  */
316
- getExecutionCount() {
317
- return this._executionCount;
333
+ getSuccessCount() {
334
+ return this._successCount;
318
335
  }
319
336
  /**
320
- * Returns the number of items that have been rejected from the queuer
337
+ * Returns the number of items that have failed processing.
321
338
  */
322
- getRejectionCount() {
323
- return this._rejectionCount;
339
+ getErrorCount() {
340
+ return this._errorCount;
324
341
  }
325
342
  /**
326
- * Returns true if the queuer is running
343
+ * Returns the number of items that have completed processing (success or error).
327
344
  */
328
- getIsRunning() {
329
- return this._running;
345
+ getSettledCount() {
346
+ return this._settledCount;
330
347
  }
331
348
  /**
332
- * Returns true if the queuer is running but has no items to process
349
+ * Returns the number of items that have been rejected from being added to the queue.
333
350
  */
334
- getIsIdle() {
335
- return this._running && this.getIsEmpty() && this._activeItems.size === 0;
336
- }
337
- /**
338
- * Adds a callback to be called when a task succeeds
339
- */
340
- onSuccess(cb) {
341
- this._onSuccessCallbacks.push(cb);
342
- return () => {
343
- this._onSuccessCallbacks = this._onSuccessCallbacks.filter(
344
- (d) => d !== cb
345
- );
346
- };
351
+ getRejectionCount() {
352
+ return this._rejectionCount;
347
353
  }
348
354
  /**
349
- * Adds a callback to be called when a task errors
355
+ * Returns true if the queuer is currently running (processing items).
350
356
  */
351
- onError(cb) {
352
- this._onErrorCallbacks.push(cb);
353
- return () => {
354
- this._onErrorCallbacks = this._onErrorCallbacks.filter((d) => d !== cb);
355
- };
357
+ getIsRunning() {
358
+ return this._running;
356
359
  }
357
360
  /**
358
- * Adds a callback to be called when a task is settled
361
+ * Returns true if the queuer is running but has no items to process and no active tasks.
359
362
  */
360
- onSettled(cb) {
361
- this._onSettledCallbacks.push(cb);
362
- return () => {
363
- this._onSettledCallbacks = this._onSettledCallbacks.filter(
364
- (d) => d !== cb
365
- );
366
- };
363
+ getIsIdle() {
364
+ return this._running && this.getIsEmpty() && this._activeItems.size === 0;
367
365
  }
368
366
  /**
369
- * Returns the number of items that have expired from the queuer
367
+ * Returns the number of items that have expired and been removed from the queue.
370
368
  */
371
369
  getExpirationCount() {
372
370
  return this._expirationCount;
373
371
  }
374
372
  }
375
- function asyncQueue(options) {
376
- const queuer = new AsyncQueuer(options);
377
- return queuer.addItem.bind(queuer);
373
+ function asyncQueue(fn, initialOptions) {
374
+ const asyncQueuer = new AsyncQueuer(fn, initialOptions);
375
+ return asyncQueuer.addItem.bind(asyncQueuer);
378
376
  }
379
377
  exports.AsyncQueuer = AsyncQueuer;
380
378
  exports.asyncQueue = asyncQueue;
@@ -1 +1 @@
1
- {"version":3,"file":"async-queuer.cjs","sources":["../../src/async-queuer.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction } from './types'\nimport type { QueuePosition } from './queuer'\n\nexport interface AsyncQueuerOptions<TValue> {\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: () => Promise<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: () => Promise<TValue>) => number\n /**\n * Initial items to populate the queuer with\n */\n initialItems?: Array<(() => Promise<TValue>) & { priority?: number }>\n /**\n * Maximum number of items allowed in the queuer\n */\n maxSize?: number\n /**\n * Callback fired whenever an item is removed from the queuer\n */\n onGetNextItem?: (\n item: () => Promise<TValue>,\n queuer: AsyncQueuer<TValue>,\n ) => void\n /**\n * Callback fired whenever the queuer's running state changes\n */\n onIsRunningChange?: (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: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void\n /**\n * Callback fired whenever an item expires in the queuer\n */\n onExpire?: (item: () => Promise<TValue>, queuer: AsyncQueuer<TValue>) => void\n /**\n * Whether the queuer should start processing tasks immediately or not.\n */\n started?: 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\nconst defaultOptions: Required<AsyncQueuerOptions<any>> = {\n addItemsTo: 'back',\n concurrency: 1,\n expirationDuration: Infinity,\n getIsExpired: () => false,\n getItemsFrom: 'front',\n getPriority: (item) => (item as any)?.priority ?? 0,\n initialItems: [],\n maxSize: Infinity,\n onGetNextItem: () => {},\n onIsRunningChange: () => {},\n onItemsChange: () => {},\n onReject: () => {},\n onExpire: () => {},\n started: true,\n wait: 0,\n}\n\n/**\n * A flexible asynchronous queue that processes tasks with configurable concurrency control.\n *\n * Features:\n * - Priority queue support via getPriority option\n * - Configurable concurrency limit\n * - Task success/error/completion callbacks\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause/resume task processing\n * - Task cancellation\n * - Item expiration to clear stale items from the queue\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if below the concurrency limit.\n *\n * @example\n * ```ts\n * const asyncQueuer = new AsyncQueuer<string>({ concurrency: 2 });\n *\n * asyncQueuer.addItem(async () => {\n * return 'Hello';\n * });\n *\n * asyncQueuer.start();\n *\n * asyncQueuer.onSuccess((result) => {\n * console.log(result); // 'Hello'\n * });\n * ```\n */\nexport class AsyncQueuer<TValue> {\n private _options: Required<AsyncQueuerOptions<TValue>>\n private _activeItems: Set<() => Promise<TValue>> = new Set()\n private _executionCount = 0\n private _rejectionCount = 0\n private _expirationCount = 0\n private _items: Array<() => Promise<TValue>> = []\n private _itemTimestamps: Array<number> = []\n private _onErrorCallbacks: Array<(error: Error) => void> = []\n private _onSettledCallbacks: Array<(result: TValue | Error) => void> = []\n private _onSuccessCallbacks: Array<(result: TValue) => void> = []\n private _pendingTick = false\n private _running: boolean\n\n constructor(initialOptions: AsyncQueuerOptions<TValue> = defaultOptions) {\n this._options = { ...defaultOptions, ...initialOptions }\n this._running = this._options.started\n\n for (let i = 0; i < this._options.initialItems.length; i++) {\n const item = this._options.initialItems[i]!\n const isLast = i === this._options.initialItems.length - 1\n this.addItem(item, this._options.addItemsTo, isLast)\n }\n }\n\n /**\n * Updates the queuer options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncQueuerOptions<TValue>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current queuer options\n */\n getOptions(): Required<AsyncQueuerOptions<TValue>> {\n return this._options\n }\n\n /**\n * Returns the current wait time between processing items\n */\n getWait(): number {\n return parseFunctionOrValue(this._options.wait, this)\n }\n\n /**\n * Returns the current concurrency limit\n */\n getConcurrency(): number {\n return parseFunctionOrValue(this._options.concurrency, this)\n }\n\n /**\n * Processes items in the queuer\n */\n private tick() {\n if (!this._running) {\n this._pendingTick = false\n return\n }\n\n // Check for expired items\n this.checkExpiredItems()\n\n while (\n this._activeItems.size < this.getConcurrency() &&\n !this.getIsEmpty()\n ) {\n const nextFn = this.getNextItem()\n if (!nextFn) {\n break\n }\n this._activeItems.add(nextFn)\n this._options.onItemsChange(this)\n ;(async () => {\n let success = false\n let res!: TValue\n let error: Error | undefined\n\n try {\n res = await nextFn()\n success = true\n } catch (e) {\n error = e as Error\n } finally {\n this._activeItems.delete(nextFn)\n this._options.onItemsChange(this)\n }\n\n if (success) {\n this._onSuccessCallbacks.forEach((cb) => cb(res))\n } else {\n this._onErrorCallbacks.forEach((cb) => cb(error!))\n }\n this._onSettledCallbacks.forEach((cb) => cb(success ? res : error!))\n\n const wait = this.getWait()\n if (wait > 0) {\n setTimeout(() => this.tick(), wait)\n return\n }\n\n this.tick()\n })()\n }\n\n this._pendingTick = false\n }\n\n /**\n * Checks for and removes expired items from the queuer\n */\n private checkExpiredItems() {\n if (\n this._options.expirationDuration === Infinity &&\n this._options.getIsExpired === defaultOptions.getIsExpired\n )\n return\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._items.length; i++) {\n const timestamp = this._itemTimestamps[i]\n if (timestamp === undefined) continue\n\n const item = this._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\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._items[index]\n if (expiredItem === undefined) continue\n\n this._items.splice(index, 1)\n this._itemTimestamps.splice(index, 1)\n this._expirationCount++\n this._options.onExpire(expiredItem, this)\n }\n\n if (expiredIndices.length > 0) {\n this._options.onItemsChange(this)\n }\n }\n\n /**\n * Starts the queuer and processes items\n */\n start(): Promise<void> {\n this._running = true\n if (!this._pendingTick && !this.getIsEmpty()) {\n this._pendingTick = true\n this.tick()\n }\n this._options.onIsRunningChange(this)\n\n return new Promise<void>((resolve) => {\n const checkIdle = () => {\n if (this.getIsIdle()) {\n resolve()\n } else {\n setTimeout(checkIdle, 100)\n }\n }\n checkIdle()\n })\n }\n\n /**\n * Stops the queuer from processing items\n */\n stop(): void {\n this._running = false\n this._pendingTick = false\n this._options.onIsRunningChange(this)\n }\n\n /**\n * Removes all items from the queuer\n */\n clear(): void {\n this._items = []\n this._options.onItemsChange(this)\n }\n\n /**\n * Resets the queuer to its initial state\n */\n reset(withInitialItems?: boolean): void {\n this.clear()\n this._executionCount = 0\n if (withInitialItems) {\n this._items = [...this._options.initialItems]\n }\n this._running = this._options.started\n }\n\n /**\n * Adds a task to the queuer\n */\n addItem(\n fn: AnyAsyncFunction & { priority?: number },\n position: QueuePosition = this._options.addItemsTo,\n runOnItemsChange: boolean = true,\n ): Promise<TValue> {\n if (this.getIsFull()) {\n this._rejectionCount++\n this._options.onReject(fn, this)\n return Promise.reject(new Error('Queuer is full'))\n }\n\n return new Promise<TValue>((resolve, reject) => {\n const task = Object.assign(\n async () => {\n try {\n const result = await fn()\n resolve(result)\n return result\n } catch (error) {\n reject(error)\n throw error\n }\n },\n { priority: fn.priority ?? undefined },\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(task)\n : task.priority\n\n if (priority !== undefined) {\n // Insert based on priority\n const insertIndex = this._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 this._items.push(task)\n this._itemTimestamps.push(Date.now())\n } else {\n this._items.splice(insertIndex, 0, task)\n this._itemTimestamps.splice(insertIndex, 0, Date.now())\n }\n } else {\n // Default FIFO/LIFO behavior\n if (position === 'front') {\n this._items.unshift(task)\n this._itemTimestamps.unshift(Date.now())\n } else {\n this._items.push(task)\n this._itemTimestamps.push(Date.now())\n }\n }\n\n if (runOnItemsChange) {\n this._options.onItemsChange(this)\n }\n\n if (this._running && !this._pendingTick) {\n this._pendingTick = true\n this.tick()\n }\n })\n }\n\n /**\n * Removes and returns an item from the queuer\n */\n getNextItem(\n position: QueuePosition = this._options.getItemsFrom,\n ): (() => Promise<TValue>) | undefined {\n let item: (() => Promise<TValue>) | undefined\n\n if (position === 'front') {\n item = this._items.shift()\n this._itemTimestamps.shift()\n } else {\n item = this._items.pop()\n this._itemTimestamps.pop()\n }\n\n if (item !== undefined) {\n this._executionCount++\n this._options.onItemsChange(this)\n this._options.onGetNextItem(item, this)\n }\n return item\n }\n\n /**\n * Returns an item without removing it\n */\n getPeek(\n position: QueuePosition = 'front',\n ): (() => Promise<TValue>) | undefined {\n if (position === 'front') {\n return this._items[0]\n }\n return this._items[this._items.length - 1]\n }\n\n /**\n * Returns true if the queuer is empty\n */\n getIsEmpty(): boolean {\n return this._items.length === 0\n }\n\n /**\n * Returns true if the queuer is full\n */\n getIsFull(): boolean {\n return this._items.length >= this._options.maxSize\n }\n\n /**\n * Returns the current size of the queuer\n */\n getSize(): number {\n return this._items.length\n }\n\n /**\n * Returns a copy of all items in the queuer\n */\n getAllItems(): Array<() => Promise<TValue>> {\n return [...this.getActiveItems(), ...this.getPendingItems()]\n }\n\n /**\n * Returns the active items\n */\n getActiveItems(): Array<() => Promise<TValue>> {\n return Array.from(this._activeItems)\n }\n\n /**\n * Returns the pending items\n */\n getPendingItems(): Array<() => Promise<TValue>> {\n return [...this._items]\n }\n\n /**\n * Returns the number of items that have been removed from the queuer\n */\n getExecutionCount(): number {\n return this._executionCount\n }\n\n /**\n * Returns the number of items that have been rejected from the queuer\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns true if the queuer is running\n */\n getIsRunning(): boolean {\n return this._running\n }\n\n /**\n * Returns true if the queuer is running but has no items to process\n */\n getIsIdle(): boolean {\n return this._running && this.getIsEmpty() && this._activeItems.size === 0\n }\n\n /**\n * Adds a callback to be called when a task succeeds\n */\n onSuccess(cb: (result: TValue) => void) {\n this._onSuccessCallbacks.push(cb)\n return () => {\n this._onSuccessCallbacks = this._onSuccessCallbacks.filter(\n (d) => d !== cb,\n )\n }\n }\n\n /**\n * Adds a callback to be called when a task errors\n */\n onError(cb: (error: Error) => void) {\n this._onErrorCallbacks.push(cb)\n return () => {\n this._onErrorCallbacks = this._onErrorCallbacks.filter((d) => d !== cb)\n }\n }\n\n /**\n * Adds a callback to be called when a task is settled\n */\n onSettled(cb: (result: TValue | Error) => void) {\n this._onSettledCallbacks.push(cb)\n return () => {\n this._onSettledCallbacks = this._onSettledCallbacks.filter(\n (d) => d !== cb,\n )\n }\n }\n\n /**\n * Returns the number of items that have expired from the queuer\n */\n getExpirationCount(): number {\n return this._expirationCount\n }\n}\n\n/**\n * Creates a new AsyncQueuer instance with the given options and returns a bound addItem function.\n * The queuer is automatically started and ready to process items.\n *\n * @example\n * ```ts\n * const enqueue = asyncQueue<string>();\n *\n * // Add items to be processed\n * enqueue(async () => {\n * return 'Hello';\n * });\n * ```\n *\n * @param options - Configuration options for the AsyncQueuer\n * @returns A bound addItem function that can be used to add tasks to the queuer\n */\nexport function asyncQueue<TValue>(options: AsyncQueuerOptions<TValue>) {\n const queuer = new AsyncQueuer<TValue>(options)\n return queuer.addItem.bind(queuer)\n}\n"],"names":["parseFunctionOrValue"],"mappings":";;;AAgFA,MAAM,iBAAoD;AAAA,EACxD,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,oBAAoB;AAAA,EACpB,cAAc,MAAM;AAAA,EACpB,cAAc;AAAA,EACd,aAAa,CAAC,UAAU,6BAAc,aAAY;AAAA,EAClD,cAAc,CAAC;AAAA,EACf,SAAS;AAAA,EACT,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,mBAAmB,MAAM;AAAA,EAAC;AAAA,EAC1B,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,SAAS;AAAA,EACT,MAAM;AACR;AAgCO,MAAM,YAAoB;AAAA,EAc/B,YAAY,iBAA6C,gBAAgB;AAZjE,SAAA,mCAA+C,IAAI;AAC3D,SAAQ,kBAAkB;AAC1B,SAAQ,kBAAkB;AAC1B,SAAQ,mBAAmB;AAC3B,SAAQ,SAAuC,CAAC;AAChD,SAAQ,kBAAiC,CAAC;AAC1C,SAAQ,oBAAmD,CAAC;AAC5D,SAAQ,sBAA+D,CAAC;AACxE,SAAQ,sBAAuD,CAA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AAAA;AAAA;AAAA;AAAA,EAMd,YAAqB;AACnB,WAAO,KAAK,YAAY,KAAK,WAAgB,KAAA,KAAK,aAAa,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM1E,UAAU,IAA8B;AACjC,SAAA,oBAAoB,KAAK,EAAE;AAChC,WAAO,MAAM;AACN,WAAA,sBAAsB,KAAK,oBAAoB;AAAA,QAClD,CAAC,MAAM,MAAM;AAAA,MACf;AAAA,IACF;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,QAAQ,IAA4B;AAC7B,SAAA,kBAAkB,KAAK,EAAE;AAC9B,WAAO,MAAM;AACX,WAAK,oBAAoB,KAAK,kBAAkB,OAAO,CAAC,MAAM,MAAM,EAAE;AAAA,IACxE;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,UAAU,IAAsC;AACzC,SAAA,oBAAoB,KAAK,EAAE;AAChC,WAAO,MAAM;AACN,WAAA,sBAAsB,KAAK,oBAAoB;AAAA,QAClD,CAAC,MAAM,MAAM;AAAA,MACf;AAAA,IACF;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,qBAA6B;AAC3B,WAAO,KAAK;AAAA,EAAA;AAEhB;AAmBO,SAAS,WAAmB,SAAqC;AAChE,QAAA,SAAS,IAAI,YAAoB,OAAO;AACvC,SAAA,OAAO,QAAQ,KAAK,MAAM;AACnC;;;"}
1
+ {"version":3,"file":"async-queuer.cjs","sources":["../../src/async-queuer.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { OptionalKeys } from './types'\nimport type { QueuePosition } from './queuer'\n\nexport interface AsyncQueuerOptions<TValue> {\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 * 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: unknown, 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 the queuer's running state changes\n */\n onIsRunningChange?: (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?: (queuer: AsyncQueuer<TValue>) => void\n /**\n * Optional callback to call when a task succeeds\n */\n onSuccess?: (result: 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\ntype AsyncQueuerOptionsWithOptionalCallbacks = OptionalKeys<\n Required<AsyncQueuerOptions<any>>,\n | 'throwOnError'\n | 'onSuccess'\n | 'onSettled'\n | 'onReject'\n | 'onItemsChange'\n | 'onIsRunningChange'\n | 'onExpire'\n | 'onError'\n>\n\nconst defaultOptions: AsyncQueuerOptionsWithOptionalCallbacks = {\n addItemsTo: 'back',\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 * 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 * - Task cancellation\n * - Item expiration to remove stale items from the queue\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if the concurrency limit allows.\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 * 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 private _options: AsyncQueuerOptionsWithOptionalCallbacks\n private _activeItems: Set<TValue> = new Set()\n private _successCount = 0\n private _errorCount = 0\n private _settledCount = 0\n private _rejectionCount = 0\n private _expirationCount = 0\n private _items: Array<TValue> = []\n private _itemTimestamps: Array<number> = []\n private _pendingTick = false\n private _running: boolean\n private _lastResult: any\n\n constructor(\n private fn: (value: TValue) => Promise<any>,\n initialOptions: AsyncQueuerOptions<TValue>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n this._running = this._options.started\n\n for (let i = 0; i < this._options.initialItems.length; i++) {\n const item = this._options.initialItems[i]!\n const isLast = i === this._options.initialItems.length - 1\n this.addItem(item, this._options.addItemsTo, isLast)\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 /**\n * Returns the current queuer options, including defaults and any overrides.\n */\n getOptions(): AsyncQueuerOptions<TValue> {\n return this._options\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, 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, this)\n }\n\n /**\n * Processes items in the queue up to the concurrency limit. Internal use only.\n */\n private tick() {\n if (!this._running) {\n this._pendingTick = false\n return\n }\n\n // Check for expired items\n this.checkExpiredItems()\n\n // Process items concurrently up to the concurrency limit\n while (\n this._activeItems.size < this.getConcurrency() &&\n !this.getIsEmpty()\n ) {\n const nextItem = this.getPeek()\n if (!nextItem) {\n break\n }\n this._activeItems.add(nextItem)\n this._options.onItemsChange?.(this)\n ;(async () => {\n this._lastResult = await this.execute()\n\n const wait = this.getWait()\n if (wait > 0) {\n setTimeout(() => this.tick(), wait)\n return\n }\n\n this.tick()\n })()\n }\n\n this._pendingTick = false\n }\n\n /**\n * Starts processing items in the queue. If already running, does nothing.\n */\n start(): void {\n this._running = true\n if (!this._pendingTick && !this.getIsEmpty()) {\n this._pendingTick = true\n this.tick()\n }\n this._options.onIsRunningChange?.(this)\n }\n\n /**\n * Stops processing items in the queue. Does not clear the queue.\n */\n stop(): void {\n this._running = false\n this._pendingTick = false\n this._options.onIsRunningChange?.(this)\n }\n\n /**\n * Removes all pending items from the queue. Does not affect active tasks.\n */\n clear(): void {\n this._items = []\n this._options.onItemsChange?.(this)\n }\n\n /**\n * Resets the queuer to its initial state. Optionally repopulates with initial items.\n * Does not affect callbacks or options.\n */\n reset(withInitialItems?: boolean): void {\n this.clear()\n this._successCount = 0\n this._errorCount = 0\n this._settledCount = 0\n if (withInitialItems) {\n this._items = [...this._options.initialItems]\n }\n this._running = this._options.started\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 *\n * @example\n * ```ts\n * queuer.addItem({ value: 'task', priority: 10 });\n * queuer.addItem('task2', 'front');\n * ```\n */\n addItem(\n item: TValue & { priority?: number },\n position: QueuePosition = this._options.addItemsTo,\n runOnItemsChange: boolean = true,\n ): void {\n if (this.getIsFull()) {\n this._rejectionCount++\n this._options.onReject?.(item, this)\n return\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.priority\n\n if (priority !== undefined) {\n // Insert based on priority - higher priority items go to front\n const insertIndex = this._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 this._items.push(item)\n this._itemTimestamps.push(Date.now())\n } else {\n this._items.splice(insertIndex, 0, item)\n this._itemTimestamps.splice(insertIndex, 0, Date.now())\n }\n } else {\n if (position === 'front') {\n // Default FIFO/LIFO behavior\n this._items.unshift(item)\n this._itemTimestamps.unshift(Date.now())\n } else {\n // LIFO\n this._items.push(item)\n this._itemTimestamps.push(Date.now())\n }\n }\n\n if (runOnItemsChange) {\n this._options.onItemsChange?.(this)\n }\n\n if (this._running && !this._pendingTick) {\n this._pendingTick = true\n this.tick()\n }\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,\n ): TValue | undefined {\n let item: TValue | undefined\n\n if (position === 'front') {\n item = this._items.shift()\n this._itemTimestamps.shift()\n } else {\n item = this._items.pop()\n this._itemTimestamps.pop()\n }\n\n if (item !== undefined) {\n this._options.onItemsChange?.(this)\n }\n\n return item\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 async execute(position?: QueuePosition): Promise<any> {\n const item = this.getNextItem(position)\n if (item !== undefined) {\n try {\n this._lastResult = await this.fn(item)\n this._successCount++\n this._options.onSuccess?.(this._lastResult, this)\n } catch (error) {\n this._errorCount++\n this._options.onError?.(error, this)\n if (this._options.throwOnError) {\n throw error\n }\n } finally {\n this._settledCount++\n this._activeItems.delete(item)\n this._options.onItemsChange?.(this)\n this._options.onSettled?.(this)\n }\n }\n return item\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 private checkExpiredItems(): void {\n if (\n this._options.expirationDuration === Infinity &&\n this._options.getIsExpired === defaultOptions.getIsExpired\n )\n return\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._items.length; i++) {\n const timestamp = this._itemTimestamps[i]\n if (timestamp === undefined) continue\n\n const item = this._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\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._items[index]\n if (expiredItem === undefined) continue\n\n this._items.splice(index, 1)\n this._itemTimestamps.splice(index, 1)\n this._expirationCount++\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.getPeek(); // front\n * queuer.getPeek('back'); // back\n * ```\n */\n getPeek(position: QueuePosition = 'front'): TValue | undefined {\n if (position === 'front') {\n return this._items[0]\n }\n return this._items[this._items.length - 1]\n }\n\n /**\n * Returns true if the queue is empty (no pending items).\n */\n getIsEmpty(): boolean {\n return this._items.length === 0\n }\n\n /**\n * Returns true if the queue is full (reached maxSize).\n */\n getIsFull(): boolean {\n return this._items.length >= this._options.maxSize\n }\n\n /**\n * Returns the number of pending items in the queue.\n */\n getSize(): number {\n return this._items.length\n }\n\n /**\n * Returns a copy of all items in the queue, including active and pending items.\n */\n getAllItems(): Array<TValue> {\n return [...this.getActiveItems(), ...this.getPendingItems()]\n }\n\n /**\n * Returns the items currently being processed (active tasks).\n */\n getActiveItems(): Array<TValue> {\n return Array.from(this._activeItems)\n }\n\n /**\n * Returns the items waiting to be processed (pending tasks).\n */\n getPendingItems(): Array<TValue> {\n return [...this._items]\n }\n\n /**\n * Returns the number of items that have been successfully processed.\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of items that have failed processing.\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns the number of items that have completed processing (success or error).\n */\n getSettledCount(): number {\n return this._settledCount\n }\n\n /**\n * Returns the number of items that have been rejected from being added to the queue.\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns true if the queuer is currently running (processing items).\n */\n getIsRunning(): boolean {\n return this._running\n }\n\n /**\n * Returns true if the queuer is running but has no items to process and no active tasks.\n */\n getIsIdle(): boolean {\n return this._running && this.getIsEmpty() && this._activeItems.size === 0\n }\n\n /**\n * Returns the number of items that have expired and been removed from the queue.\n */\n getExpirationCount(): number {\n return this._expirationCount\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 * 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 * Example usage:\n * ```ts\n * const enqueue = asyncQueue<string>(async (item) => {\n * return item.toUpperCase();\n * }, {...options});\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.bind(asyncQueuer)\n}\n"],"names":["parseFunctionOrValue"],"mappings":";;;AAyGA,MAAM,iBAA0D;AAAA,EAC9D,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,oBAAoB;AAAA,EACpB,cAAc,MAAM;AAAA,EACpB,cAAc;AAAA,EACd,aAAa,CAAC,UAAc,6BAAM,aAAY;AAAA,EAC9C,cAAc,CAAC;AAAA,EACf,SAAS;AAAA,EACT,SAAS;AAAA,EACT,MAAM;AACR;AAwCO,MAAM,YAAoB;AAAA,EAc/B,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAbF,SAAA,mCAAgC,IAAI;AAC5C,SAAQ,gBAAgB;AACxB,SAAQ,cAAc;AACtB,SAAQ,gBAAgB;AACxB,SAAQ,kBAAkB;AAC1B,SAAQ,mBAAmB;AAC3B,SAAQ,SAAwB,CAAC;AACjC,SAAQ,kBAAiC,CAAC;AAC1C,SAAQ,eAAe;AAQrB,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,MACH,cAAc,eAAe,gBAAgB,CAAC,eAA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