@tanstack/pacer 0.1.0 → 0.3.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 +112 -63
  2. package/dist/cjs/async-debouncer.cjs.map +1 -1
  3. package/dist/cjs/async-debouncer.d.cts +66 -25
  4. package/dist/cjs/async-queuer.cjs +198 -124
  5. package/dist/cjs/async-queuer.cjs.map +1 -1
  6. package/dist/cjs/async-queuer.d.cts +91 -49
  7. package/dist/cjs/async-rate-limiter.cjs +83 -55
  8. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  9. package/dist/cjs/async-rate-limiter.d.cts +55 -28
  10. package/dist/cjs/async-throttler.cjs +121 -70
  11. package/dist/cjs/async-throttler.cjs.map +1 -1
  12. package/dist/cjs/async-throttler.d.cts +75 -25
  13. package/dist/cjs/debouncer.cjs +45 -23
  14. package/dist/cjs/debouncer.cjs.map +1 -1
  15. package/dist/cjs/debouncer.d.cts +27 -12
  16. package/dist/cjs/index.cjs +2 -0
  17. package/dist/cjs/index.cjs.map +1 -1
  18. package/dist/cjs/index.d.cts +2 -0
  19. package/dist/cjs/queuer.cjs +161 -101
  20. package/dist/cjs/queuer.cjs.map +1 -1
  21. package/dist/cjs/queuer.d.cts +80 -38
  22. package/dist/cjs/rate-limiter.cjs +52 -44
  23. package/dist/cjs/rate-limiter.cjs.map +1 -1
  24. package/dist/cjs/rate-limiter.d.cts +38 -46
  25. package/dist/cjs/throttler.cjs +57 -44
  26. package/dist/cjs/throttler.cjs.map +1 -1
  27. package/dist/cjs/throttler.d.cts +35 -23
  28. package/dist/cjs/types.d.cts +8 -0
  29. package/dist/cjs/utils.cjs +13 -0
  30. package/dist/cjs/utils.cjs.map +1 -0
  31. package/dist/cjs/utils.d.cts +1 -0
  32. package/dist/esm/async-debouncer.d.ts +66 -25
  33. package/dist/esm/async-debouncer.js +112 -63
  34. package/dist/esm/async-debouncer.js.map +1 -1
  35. package/dist/esm/async-queuer.d.ts +91 -49
  36. package/dist/esm/async-queuer.js +198 -124
  37. package/dist/esm/async-queuer.js.map +1 -1
  38. package/dist/esm/async-rate-limiter.d.ts +55 -28
  39. package/dist/esm/async-rate-limiter.js +83 -55
  40. package/dist/esm/async-rate-limiter.js.map +1 -1
  41. package/dist/esm/async-throttler.d.ts +75 -25
  42. package/dist/esm/async-throttler.js +121 -70
  43. package/dist/esm/async-throttler.js.map +1 -1
  44. package/dist/esm/debouncer.d.ts +27 -12
  45. package/dist/esm/debouncer.js +45 -23
  46. package/dist/esm/debouncer.js.map +1 -1
  47. package/dist/esm/index.d.ts +2 -0
  48. package/dist/esm/index.js +2 -0
  49. package/dist/esm/index.js.map +1 -1
  50. package/dist/esm/queuer.d.ts +80 -38
  51. package/dist/esm/queuer.js +161 -101
  52. package/dist/esm/queuer.js.map +1 -1
  53. package/dist/esm/rate-limiter.d.ts +38 -46
  54. package/dist/esm/rate-limiter.js +52 -44
  55. package/dist/esm/rate-limiter.js.map +1 -1
  56. package/dist/esm/throttler.d.ts +35 -23
  57. package/dist/esm/throttler.js +57 -44
  58. package/dist/esm/throttler.js.map +1 -1
  59. package/dist/esm/types.d.ts +8 -0
  60. package/dist/esm/utils.d.ts +1 -0
  61. package/dist/esm/utils.js +13 -0
  62. package/dist/esm/utils.js.map +1 -0
  63. package/package.json +8 -1
  64. package/src/async-debouncer.ts +157 -88
  65. package/src/async-queuer.ts +266 -148
  66. package/src/async-rate-limiter.ts +123 -83
  67. package/src/async-throttler.ts +173 -89
  68. package/src/debouncer.ts +71 -42
  69. package/src/index.ts +2 -0
  70. package/src/queuer.ts +219 -114
  71. package/src/rate-limiter.ts +74 -88
  72. package/src/throttler.ts +83 -65
  73. package/src/types.ts +9 -0
  74. package/src/utils.ts +13 -0
@@ -1,32 +1,43 @@
1
1
  const defaultOptions = {
2
2
  addItemsTo: "back",
3
3
  concurrency: 1,
4
+ expirationDuration: Infinity,
5
+ getIsExpired: () => false,
4
6
  getItemsFrom: "front",
5
- getPriority: (item) => item.priority ?? 0,
7
+ getPriority: (item) => (item == null ? void 0 : item.priority) ?? 0,
6
8
  initialItems: [],
7
9
  maxSize: Infinity,
8
10
  onGetNextItem: () => {
9
11
  },
10
- onUpdate: () => {
12
+ onIsRunningChange: () => {
11
13
  },
12
- started: false,
14
+ onItemsChange: () => {
15
+ },
16
+ onReject: () => {
17
+ },
18
+ onExpire: () => {
19
+ },
20
+ started: true,
13
21
  wait: 0
14
22
  };
15
23
  class AsyncQueuer {
16
24
  constructor(initialOptions = defaultOptions) {
17
- this.items = [];
18
- this.activeItems = /* @__PURE__ */ new Set();
19
- this.onSuccessCallbacks = [];
20
- this.onErrorCallbacks = [];
21
- this.onSettledCallbacks = [];
22
- this.pendingTick = false;
23
- this.executionCount = 0;
24
- this.options = { ...defaultOptions, ...initialOptions };
25
- this.running = this.options.started;
26
- for (let i = 0; i < this.options.initialItems.length; i++) {
27
- const item = this.options.initialItems[i];
28
- const isLast = i === this.options.initialItems.length - 1;
29
- this.addItem(item, this.options.addItemsTo, isLast);
25
+ this._activeItems = /* @__PURE__ */ new Set();
26
+ this._executionCount = 0;
27
+ this._rejectionCount = 0;
28
+ this._expirationCount = 0;
29
+ this._items = [];
30
+ this._itemTimestamps = [];
31
+ this._onErrorCallbacks = [];
32
+ this._onSettledCallbacks = [];
33
+ this._onSuccessCallbacks = [];
34
+ this._pendingTick = false;
35
+ this._options = { ...defaultOptions, ...initialOptions };
36
+ this._running = this._options.started;
37
+ for (let i = 0; i < this._options.initialItems.length; i++) {
38
+ const item = this._options.initialItems[i];
39
+ const isLast = i === this._options.initialItems.length - 1;
40
+ this.addItem(item, this._options.addItemsTo, isLast);
30
41
  }
31
42
  }
32
43
  /**
@@ -34,23 +45,30 @@ class AsyncQueuer {
34
45
  * Returns the new options state
35
46
  */
36
47
  setOptions(newOptions) {
37
- this.options = { ...this.options, ...newOptions };
38
- return this.options;
48
+ this._options = { ...this._options, ...newOptions };
49
+ }
50
+ /**
51
+ * Returns the current queuer options
52
+ */
53
+ getOptions() {
54
+ return this._options;
39
55
  }
40
56
  /**
41
57
  * Processes items in the queuer
42
58
  */
43
59
  tick() {
44
- if (!this.running) {
45
- this.pendingTick = false;
60
+ if (!this._running) {
61
+ this._pendingTick = false;
46
62
  return;
47
63
  }
48
- while (this.activeItems.size < this.options.concurrency && !this.isEmpty()) {
64
+ this.checkExpiredItems();
65
+ while (this._activeItems.size < this._options.concurrency && !this.getIsEmpty()) {
49
66
  const nextFn = this.getNextItem();
50
67
  if (!nextFn) {
51
68
  break;
52
69
  }
53
- this.activeItems.add(nextFn);
70
+ this._activeItems.add(nextFn);
71
+ this._options.onItemsChange(this);
54
72
  (async () => {
55
73
  let success = false;
56
74
  let res;
@@ -61,29 +79,110 @@ class AsyncQueuer {
61
79
  } catch (e) {
62
80
  error = e;
63
81
  } finally {
64
- this.options.onUpdate(this);
82
+ this._activeItems.delete(nextFn);
83
+ this._options.onItemsChange(this);
65
84
  }
66
- this.activeItems.delete(nextFn);
67
85
  if (success) {
68
- this.onSuccessCallbacks.forEach((cb) => cb(res));
86
+ this._onSuccessCallbacks.forEach((cb) => cb(res));
69
87
  } else {
70
- this.onErrorCallbacks.forEach((cb) => cb(error));
88
+ this._onErrorCallbacks.forEach((cb) => cb(error));
71
89
  }
72
- this.onSettledCallbacks.forEach((cb) => cb(success ? res : error));
73
- if (this.options.wait > 0) {
74
- setTimeout(() => this.tick(), this.options.wait);
90
+ this._onSettledCallbacks.forEach((cb) => cb(success ? res : error));
91
+ if (this._options.wait > 0) {
92
+ setTimeout(() => this.tick(), this._options.wait);
75
93
  return;
76
94
  }
77
95
  this.tick();
78
96
  })();
79
97
  }
80
- this.pendingTick = false;
98
+ this._pendingTick = false;
99
+ }
100
+ /**
101
+ * Checks for and removes expired items from the queuer
102
+ */
103
+ checkExpiredItems() {
104
+ if (this._options.expirationDuration === Infinity && this._options.getIsExpired === defaultOptions.getIsExpired)
105
+ return;
106
+ const now = Date.now();
107
+ const expiredIndices = [];
108
+ for (let i = 0; i < this._items.length; i++) {
109
+ const timestamp = this._itemTimestamps[i];
110
+ if (timestamp === void 0) continue;
111
+ const item = this._items[i];
112
+ if (item === void 0) continue;
113
+ const isExpired = this._options.getIsExpired !== defaultOptions.getIsExpired ? this._options.getIsExpired(item, timestamp) : now - timestamp > this._options.expirationDuration;
114
+ if (isExpired) {
115
+ expiredIndices.push(i);
116
+ }
117
+ }
118
+ for (let i = expiredIndices.length - 1; i >= 0; i--) {
119
+ const index = expiredIndices[i];
120
+ if (index === void 0) continue;
121
+ const expiredItem = this._items[index];
122
+ if (expiredItem === void 0) continue;
123
+ this._items.splice(index, 1);
124
+ this._itemTimestamps.splice(index, 1);
125
+ this._expirationCount++;
126
+ this._options.onExpire(expiredItem, this);
127
+ }
128
+ if (expiredIndices.length > 0) {
129
+ this._options.onItemsChange(this);
130
+ }
131
+ }
132
+ /**
133
+ * Starts the queuer and processes items
134
+ */
135
+ start() {
136
+ this._running = true;
137
+ if (!this._pendingTick && !this.getIsEmpty()) {
138
+ this._pendingTick = true;
139
+ this.tick();
140
+ }
141
+ this._options.onIsRunningChange(this);
142
+ return new Promise((resolve) => {
143
+ const checkIdle = () => {
144
+ if (this.getIsIdle()) {
145
+ resolve();
146
+ } else {
147
+ setTimeout(checkIdle, 100);
148
+ }
149
+ };
150
+ checkIdle();
151
+ });
152
+ }
153
+ /**
154
+ * Stops the queuer from processing items
155
+ */
156
+ stop() {
157
+ this._running = false;
158
+ this._pendingTick = false;
159
+ this._options.onIsRunningChange(this);
160
+ }
161
+ /**
162
+ * Removes all items from the queuer
163
+ */
164
+ clear() {
165
+ this._items = [];
166
+ this._options.onItemsChange(this);
167
+ }
168
+ /**
169
+ * Resets the queuer to its initial state
170
+ */
171
+ reset(withInitialItems) {
172
+ this.clear();
173
+ this._executionCount = 0;
174
+ if (withInitialItems) {
175
+ this._items = [...this._options.initialItems];
176
+ }
177
+ this._running = this._options.started;
81
178
  }
82
179
  /**
83
180
  * Adds a task to the queuer
84
181
  */
85
- addItem(fn, position = this.options.addItemsTo, runOnUpdate = true) {
86
- if (this.isFull()) {
182
+ addItem(fn, position = this._options.addItemsTo, runOnUpdate = true) {
183
+ if (this.getIsFull()) {
184
+ this._rejectionCount++;
185
+ this._options.onReject(fn, this);
87
186
  return Promise.reject(new Error("Queuer is full"));
88
187
  }
89
188
  return new Promise((resolve, reject) => {
@@ -100,29 +199,33 @@ class AsyncQueuer {
100
199
  },
101
200
  { priority: fn.priority ?? void 0 }
102
201
  );
103
- const priority = this.options.getPriority !== defaultOptions.getPriority ? this.options.getPriority(task) : task.priority;
202
+ const priority = this._options.getPriority !== defaultOptions.getPriority ? this._options.getPriority(task) : task.priority;
104
203
  if (priority !== void 0) {
105
- const insertIndex = this.items.findIndex((existing) => {
106
- const existingPriority = this.options.getPriority !== defaultOptions.getPriority ? this.options.getPriority(existing) : existing.priority;
204
+ const insertIndex = this._items.findIndex((existing) => {
205
+ const existingPriority = this._options.getPriority !== defaultOptions.getPriority ? this._options.getPriority(existing) : existing.priority;
107
206
  return existingPriority > priority;
108
207
  });
109
208
  if (insertIndex === -1) {
110
- this.items.push(task);
209
+ this._items.push(task);
210
+ this._itemTimestamps.push(Date.now());
111
211
  } else {
112
- this.items.splice(insertIndex, 0, task);
212
+ this._items.splice(insertIndex, 0, task);
213
+ this._itemTimestamps.splice(insertIndex, 0, Date.now());
113
214
  }
114
215
  } else {
115
216
  if (position === "front") {
116
- this.items.unshift(task);
217
+ this._items.unshift(task);
218
+ this._itemTimestamps.unshift(Date.now());
117
219
  } else {
118
- this.items.push(task);
220
+ this._items.push(task);
221
+ this._itemTimestamps.push(Date.now());
119
222
  }
120
223
  }
121
224
  if (runOnUpdate) {
122
- this.options.onUpdate(this);
225
+ this._options.onItemsChange(this);
123
226
  }
124
- if (this.running && !this.pendingTick) {
125
- this.pendingTick = true;
227
+ if (this._running && !this._pendingTick) {
228
+ this._pendingTick = true;
126
229
  this.tick();
127
230
  }
128
231
  });
@@ -130,160 +233,131 @@ class AsyncQueuer {
130
233
  /**
131
234
  * Removes and returns an item from the queuer
132
235
  */
133
- getNextItem(position = this.options.getItemsFrom) {
236
+ getNextItem(position = this._options.getItemsFrom) {
134
237
  let item;
135
238
  if (position === "front") {
136
- item = this.items.shift();
239
+ item = this._items.shift();
240
+ this._itemTimestamps.shift();
137
241
  } else {
138
- item = this.items.pop();
242
+ item = this._items.pop();
243
+ this._itemTimestamps.pop();
139
244
  }
140
245
  if (item !== void 0) {
141
- this.executionCount++;
142
- this.options.onUpdate(this);
143
- this.options.onGetNextItem(item, this);
246
+ this._executionCount++;
247
+ this._options.onItemsChange(this);
248
+ this._options.onGetNextItem(item, this);
144
249
  }
145
250
  return item;
146
251
  }
147
252
  /**
148
253
  * Returns an item without removing it
149
254
  */
150
- peek(position = "front") {
255
+ getPeek(position = "front") {
151
256
  if (position === "front") {
152
- return this.items[0];
257
+ return this._items[0];
153
258
  }
154
- return this.items[this.items.length - 1];
259
+ return this._items[this._items.length - 1];
155
260
  }
156
261
  /**
157
262
  * Returns true if the queuer is empty
158
263
  */
159
- isEmpty() {
160
- return this.items.length === 0;
264
+ getIsEmpty() {
265
+ return this._items.length === 0;
161
266
  }
162
267
  /**
163
268
  * Returns true if the queuer is full
164
269
  */
165
- isFull() {
166
- return this.items.length >= this.options.maxSize;
270
+ getIsFull() {
271
+ return this._items.length >= this._options.maxSize;
167
272
  }
168
273
  /**
169
274
  * Returns the current size of the queuer
170
275
  */
171
- size() {
172
- return this.items.length;
276
+ getSize() {
277
+ return this._items.length;
173
278
  }
174
279
  /**
175
- * Removes all items from the queuer
280
+ * Returns a copy of all items in the queuer
176
281
  */
177
- clear() {
178
- this.items = [];
179
- this.options.onUpdate(this);
282
+ getAllItems() {
283
+ return [...this.getActiveItems(), ...this.getPendingItems()];
180
284
  }
181
285
  /**
182
- * Resets the queuer to its initial state
286
+ * Returns the active items
183
287
  */
184
- reset(withInitialItems) {
185
- this.clear();
186
- this.executionCount = 0;
187
- if (withInitialItems) {
188
- this.items = [...this.options.initialItems];
189
- }
190
- this.running = this.options.started;
288
+ getActiveItems() {
289
+ return Array.from(this._activeItems);
191
290
  }
192
291
  /**
193
- * Returns a copy of all items in the queuer
292
+ * Returns the pending items
194
293
  */
195
- getAllItems() {
196
- return [...this.items];
294
+ getPendingItems() {
295
+ return [...this._items];
197
296
  }
198
297
  /**
199
298
  * Returns the number of items that have been removed from the queuer
200
299
  */
201
300
  getExecutionCount() {
202
- return this.executionCount;
301
+ return this._executionCount;
203
302
  }
204
303
  /**
205
- * Returns the active items
304
+ * Returns the number of items that have been rejected from the queuer
206
305
  */
207
- getActiveItems() {
208
- return Array.from(this.activeItems);
306
+ getRejectionCount() {
307
+ return this._rejectionCount;
209
308
  }
210
309
  /**
211
- * Returns the pending items
310
+ * Returns true if the queuer is running
212
311
  */
213
- getPendingItems() {
214
- return this.getAllItems();
312
+ getIsRunning() {
313
+ return this._running;
314
+ }
315
+ /**
316
+ * Returns true if the queuer is running but has no items to process
317
+ */
318
+ getIsIdle() {
319
+ return this._running && this.getIsEmpty() && this._activeItems.size === 0;
215
320
  }
216
321
  /**
217
322
  * Adds a callback to be called when a task succeeds
218
323
  */
219
324
  onSuccess(cb) {
220
- this.onSuccessCallbacks.push(cb);
325
+ this._onSuccessCallbacks.push(cb);
221
326
  return () => {
222
- this.onSuccessCallbacks = this.onSuccessCallbacks.filter((d) => d !== cb);
327
+ this._onSuccessCallbacks = this._onSuccessCallbacks.filter(
328
+ (d) => d !== cb
329
+ );
223
330
  };
224
331
  }
225
332
  /**
226
333
  * Adds a callback to be called when a task errors
227
334
  */
228
335
  onError(cb) {
229
- this.onErrorCallbacks.push(cb);
336
+ this._onErrorCallbacks.push(cb);
230
337
  return () => {
231
- this.onErrorCallbacks = this.onErrorCallbacks.filter((d) => d !== cb);
338
+ this._onErrorCallbacks = this._onErrorCallbacks.filter((d) => d !== cb);
232
339
  };
233
340
  }
234
341
  /**
235
342
  * Adds a callback to be called when a task is settled
236
343
  */
237
344
  onSettled(cb) {
238
- this.onSettledCallbacks.push(cb);
345
+ this._onSettledCallbacks.push(cb);
239
346
  return () => {
240
- this.onSettledCallbacks = this.onSettledCallbacks.filter((d) => d !== cb);
347
+ this._onSettledCallbacks = this._onSettledCallbacks.filter(
348
+ (d) => d !== cb
349
+ );
241
350
  };
242
351
  }
243
352
  /**
244
- * Starts the queuer and processes items
245
- */
246
- start() {
247
- this.running = true;
248
- if (!this.pendingTick && !this.isEmpty()) {
249
- this.pendingTick = true;
250
- this.tick();
251
- }
252
- this.options.onUpdate(this);
253
- return new Promise((resolve) => {
254
- const checkIdle = () => {
255
- if (this.isIdle()) {
256
- resolve();
257
- } else {
258
- setTimeout(checkIdle, 100);
259
- }
260
- };
261
- checkIdle();
262
- });
263
- }
264
- /**
265
- * Stops the queuer from processing items
266
- */
267
- stop() {
268
- this.running = false;
269
- this.pendingTick = false;
270
- this.options.onUpdate(this);
271
- }
272
- /**
273
- * Returns true if the queuer is running
274
- */
275
- isRunning() {
276
- return this.running;
277
- }
278
- /**
279
- * Returns true if the queuer is running but has no items to process
353
+ * Returns the number of items that have expired from the queuer
280
354
  */
281
- isIdle() {
282
- return this.running && this.isEmpty() && this.activeItems.size === 0;
355
+ getExpirationCount() {
356
+ return this._expirationCount;
283
357
  }
284
358
  }
285
359
  function asyncQueue(options = {}) {
286
- const queuer = new AsyncQueuer({ ...options, started: true });
360
+ const queuer = new AsyncQueuer(options);
287
361
  return queuer.addItem.bind(queuer);
288
362
  }
289
363
  export {
@@ -1 +1 @@
1
- {"version":3,"file":"async-queuer.js","sources":["../../src/async-queuer.ts"],"sourcesContent":["import 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 */\n concurrency?: number\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 an item is added or removed from the queuer\n */\n onUpdate?: (queuer: AsyncQueuer<TValue>) => void\n /**\n * Whether the queuer should start processing tasks immediately\n */\n started?: boolean\n /**\n * Time in milliseconds to wait between processing items\n */\n wait?: number\n}\n\nconst defaultOptions: Required<AsyncQueuerOptions<any>> = {\n addItemsTo: 'back',\n concurrency: 1,\n getItemsFrom: 'front',\n getPriority: (item) => (item as any).priority ?? 0,\n initialItems: [],\n maxSize: Infinity,\n onGetNextItem: () => {},\n onUpdate: () => {},\n started: false,\n wait: 0,\n}\n\n/**\n * A flexible asynchronous queuer that processes tasks with configurable concurrency control.\n *\n * Features:\n * - Priority queuer 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) queuer behavior\n * - Pause/resume task processing\n * - Task cancellation\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 queuer = new AsyncQueuer<string>({ concurrency: 2 });\n *\n * queuer.addItem(async () => {\n * return 'Hello';\n * });\n *\n * queuer.start();\n *\n * queuer.onSuccess((result) => {\n * console.log(result); // 'Hello'\n * });\n * ```\n */\nexport class AsyncQueuer<TValue> {\n protected options: Required<AsyncQueuerOptions<TValue>>\n private items: Array<() => Promise<TValue>> = []\n private activeItems: Set<() => Promise<TValue>> = new Set()\n private onSuccessCallbacks: Array<(result: TValue) => void> = []\n private onErrorCallbacks: Array<(error: Error) => void> = []\n private onSettledCallbacks: Array<(result: TValue | Error) => void> = []\n private running: boolean\n private pendingTick = false\n private executionCount = 0\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(\n newOptions: Partial<AsyncQueuerOptions<TValue>>,\n ): AsyncQueuerOptions<TValue> {\n this.options = { ...this.options, ...newOptions }\n return this.options\n }\n\n /**\n * Processes items in the queuer\n */\n protected tick() {\n if (!this.running) {\n this.pendingTick = false\n return\n }\n\n while (\n this.activeItems.size < this.options.concurrency &&\n !this.isEmpty()\n ) {\n const nextFn = this.getNextItem()\n if (!nextFn) {\n break\n }\n\n this.activeItems.add(nextFn)\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.options.onUpdate(this)\n }\n\n this.activeItems.delete(nextFn)\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 if (this.options.wait > 0) {\n setTimeout(() => this.tick(), this.options.wait)\n return\n }\n\n this.tick()\n })()\n }\n\n this.pendingTick = false\n }\n\n /**\n * Adds a task to the queuer\n */\n addItem(\n fn: (() => Promise<TValue>) & { priority?: number },\n position: QueuePosition = this.options.addItemsTo,\n runOnUpdate: boolean = true,\n ): Promise<TValue> {\n if (this.isFull()) {\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 } else {\n this.items.splice(insertIndex, 0, task)\n }\n } else {\n // Default FIFO/LIFO behavior\n if (position === 'front') {\n this.items.unshift(task)\n } else {\n this.items.push(task)\n }\n }\n\n if (runOnUpdate) {\n this.options.onUpdate(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 } else {\n item = this.items.pop()\n }\n\n if (item !== undefined) {\n this.executionCount++\n this.options.onUpdate(this)\n this.options.onGetNextItem(item, this)\n }\n return item\n }\n\n /**\n * Returns an item without removing it\n */\n peek(position: QueuePosition = 'front'): (() => 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 isEmpty(): boolean {\n return this.items.length === 0\n }\n\n /**\n * Returns true if the queuer is full\n */\n isFull(): boolean {\n return this.items.length >= this.options.maxSize\n }\n\n /**\n * Returns the current size of the queuer\n */\n size(): number {\n return this.items.length\n }\n\n /**\n * Removes all items from the queuer\n */\n clear(): void {\n this.items = []\n this.options.onUpdate(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 * Returns a copy of all items in the queuer\n */\n getAllItems(): 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 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.getAllItems()\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((d) => d !== cb)\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((d) => d !== cb)\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.isEmpty()) {\n this.pendingTick = true\n this.tick()\n }\n this.options.onUpdate(this)\n\n return new Promise<void>((resolve) => {\n const checkIdle = () => {\n if (this.isIdle()) {\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.onUpdate(this)\n }\n\n /**\n * Returns true if the queuer is running\n */\n isRunning(): boolean {\n return this.running\n }\n\n /**\n * Returns true if the queuer is running but has no items to process\n */\n isIdle(): boolean {\n return this.running && this.isEmpty() && this.activeItems.size === 0\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, started: true })\n return queuer.addItem.bind(queuer)\n}\n"],"names":[],"mappings":"AAoDA,MAAM,iBAAoD;AAAA,EACxD,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,cAAc;AAAA,EACd,aAAa,CAAC,SAAU,KAAa,YAAY;AAAA,EACjD,cAAc,CAAC;AAAA,EACf,SAAS;AAAA,EACT,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,SAAS;AAAA,EACT,MAAM;AACR;AA+BO,MAAM,YAAoB;AAAA,EAW/B,YAAY,iBAA6C,gBAAgB;AATzE,SAAQ,QAAsC,CAAC;AACvC,SAAA,kCAA8C,IAAI;AAC1D,SAAQ,qBAAsD,CAAC;AAC/D,SAAQ,mBAAkD,CAAC;AAC3D,SAAQ,qBAA8D,CAAC;AAEvE,SAAQ,cAAc;AACtB,SAAQ,iBAAiB;AAGvB,SAAK,UAAU,EAAE,GAAG,gBAAgB,GAAG,eAAe;AACjD,SAAA,UAAU,KAAK,QAAQ;AAE5B,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,aAAa,QAAQ,KAAK;AACzD,YAAM,OAAO,KAAK,QAAQ,aAAa,CAAC;AACxC,YAAM,SAAS,MAAM,KAAK,QAAQ,aAAa,SAAS;AACxD,WAAK,QAAQ,MAAM,KAAK,QAAQ,YAAY,MAAM;AAAA,IAAA;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WACE,YAC4B;AAC5B,SAAK,UAAU,EAAE,GAAG,KAAK,SAAS,GAAG,WAAW;AAChD,WAAO,K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"async-queuer.js","sources":["../../src/async-queuer.ts"],"sourcesContent":["import 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 */\n concurrency?: 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 */\n wait?: 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 * 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._options.concurrency &&\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 if (this._options.wait > 0) {\n setTimeout(() => this.tick(), this._options.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: (() => Promise<TValue>) & { priority?: number },\n position: QueuePosition = this._options.addItemsTo,\n runOnUpdate: 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 (runOnUpdate) {\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>(\n options: Omit<AsyncQueuerOptions<TValue>, 'started'> = {},\n) {\n const queuer = new AsyncQueuer<TValue>(options)\n return queuer.addItem.bind(queuer)\n}\n"],"names":[],"mappings":"AA0EA,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,E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