@tanstack/pacer 0.7.0 → 0.9.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 (91) hide show
  1. package/dist/cjs/async-batcher.cjs +163 -0
  2. package/dist/cjs/async-batcher.cjs.map +1 -0
  3. package/dist/cjs/async-batcher.d.cts +273 -0
  4. package/dist/cjs/async-debouncer.cjs +149 -162
  5. package/dist/cjs/async-debouncer.cjs.map +1 -1
  6. package/dist/cjs/async-debouncer.d.cts +76 -57
  7. package/dist/cjs/async-queuer.cjs +282 -343
  8. package/dist/cjs/async-queuer.cjs.map +1 -1
  9. package/dist/cjs/async-queuer.d.cts +123 -102
  10. package/dist/cjs/async-rate-limiter.cjs +128 -185
  11. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  12. package/dist/cjs/async-rate-limiter.d.cts +72 -61
  13. package/dist/cjs/async-throttler.cjs +168 -178
  14. package/dist/cjs/async-throttler.cjs.map +1 -1
  15. package/dist/cjs/async-throttler.d.cts +97 -69
  16. package/dist/cjs/batcher.cjs +110 -119
  17. package/dist/cjs/batcher.cjs.map +1 -1
  18. package/dist/cjs/batcher.d.cts +76 -51
  19. package/dist/cjs/debouncer.cjs +97 -85
  20. package/dist/cjs/debouncer.cjs.map +1 -1
  21. package/dist/cjs/debouncer.d.cts +54 -26
  22. package/dist/cjs/index.cjs +3 -6
  23. package/dist/cjs/index.cjs.map +1 -1
  24. package/dist/cjs/index.d.cts +1 -1
  25. package/dist/cjs/queuer.cjs +246 -294
  26. package/dist/cjs/queuer.cjs.map +1 -1
  27. package/dist/cjs/queuer.d.cts +105 -84
  28. package/dist/cjs/rate-limiter.cjs +97 -130
  29. package/dist/cjs/rate-limiter.cjs.map +1 -1
  30. package/dist/cjs/rate-limiter.d.cts +50 -37
  31. package/dist/cjs/throttler.cjs +107 -123
  32. package/dist/cjs/throttler.cjs.map +1 -1
  33. package/dist/cjs/throttler.d.cts +59 -35
  34. package/dist/cjs/utils.cjs +0 -13
  35. package/dist/cjs/utils.cjs.map +1 -1
  36. package/dist/cjs/utils.d.cts +0 -1
  37. package/dist/esm/async-batcher.d.ts +273 -0
  38. package/dist/esm/async-batcher.js +163 -0
  39. package/dist/esm/async-batcher.js.map +1 -0
  40. package/dist/esm/async-debouncer.d.ts +76 -57
  41. package/dist/esm/async-debouncer.js +149 -162
  42. package/dist/esm/async-debouncer.js.map +1 -1
  43. package/dist/esm/async-queuer.d.ts +123 -102
  44. package/dist/esm/async-queuer.js +282 -343
  45. package/dist/esm/async-queuer.js.map +1 -1
  46. package/dist/esm/async-rate-limiter.d.ts +72 -61
  47. package/dist/esm/async-rate-limiter.js +128 -185
  48. package/dist/esm/async-rate-limiter.js.map +1 -1
  49. package/dist/esm/async-throttler.d.ts +97 -69
  50. package/dist/esm/async-throttler.js +168 -178
  51. package/dist/esm/async-throttler.js.map +1 -1
  52. package/dist/esm/batcher.d.ts +76 -51
  53. package/dist/esm/batcher.js +110 -119
  54. package/dist/esm/batcher.js.map +1 -1
  55. package/dist/esm/debouncer.d.ts +54 -26
  56. package/dist/esm/debouncer.js +97 -85
  57. package/dist/esm/debouncer.js.map +1 -1
  58. package/dist/esm/index.d.ts +1 -1
  59. package/dist/esm/index.js +4 -7
  60. package/dist/esm/queuer.d.ts +105 -84
  61. package/dist/esm/queuer.js +246 -294
  62. package/dist/esm/queuer.js.map +1 -1
  63. package/dist/esm/rate-limiter.d.ts +50 -37
  64. package/dist/esm/rate-limiter.js +97 -130
  65. package/dist/esm/rate-limiter.js.map +1 -1
  66. package/dist/esm/throttler.d.ts +59 -35
  67. package/dist/esm/throttler.js +107 -123
  68. package/dist/esm/throttler.js.map +1 -1
  69. package/dist/esm/utils.d.ts +0 -1
  70. package/dist/esm/utils.js +0 -13
  71. package/dist/esm/utils.js.map +1 -1
  72. package/package.json +14 -11
  73. package/src/async-batcher.ts +475 -0
  74. package/src/async-debouncer.ts +201 -121
  75. package/src/async-queuer.ts +341 -220
  76. package/src/async-rate-limiter.ts +176 -136
  77. package/src/async-throttler.ts +233 -139
  78. package/src/batcher.ts +159 -93
  79. package/src/debouncer.ts +135 -52
  80. package/src/index.ts +1 -1
  81. package/src/queuer.ts +349 -227
  82. package/src/rate-limiter.ts +125 -80
  83. package/src/throttler.ts +152 -78
  84. package/src/utils.ts +0 -15
  85. package/dist/cjs/compare.cjs +0 -72
  86. package/dist/cjs/compare.cjs.map +0 -1
  87. package/dist/cjs/compare.d.cts +0 -12
  88. package/dist/esm/compare.d.ts +0 -12
  89. package/dist/esm/compare.js +0 -72
  90. package/dist/esm/compare.js.map +0 -1
  91. package/src/compare.ts +0 -105
@@ -1,376 +1,315 @@
1
+ import { Store } from "@tanstack/store";
1
2
  import { parseFunctionOrValue } from "./utils.js";
3
+ function getDefaultAsyncQueuerState() {
4
+ return structuredClone({
5
+ activeItems: [],
6
+ errorCount: 0,
7
+ expirationCount: 0,
8
+ isEmpty: true,
9
+ isFull: false,
10
+ isIdle: true,
11
+ isRunning: true,
12
+ itemTimestamps: [],
13
+ items: [],
14
+ lastResult: null,
15
+ pendingTick: false,
16
+ rejectionCount: 0,
17
+ settledCount: 0,
18
+ size: 0,
19
+ status: "idle",
20
+ successCount: 0
21
+ });
22
+ }
2
23
  const defaultOptions = {
3
24
  addItemsTo: "back",
4
25
  concurrency: 1,
5
26
  expirationDuration: Infinity,
6
27
  getIsExpired: () => false,
7
28
  getItemsFrom: "front",
8
- getPriority: (item) => (item == null ? void 0 : item.priority) ?? 0,
29
+ getPriority: (item) => item?.priority ?? 0,
9
30
  initialItems: [],
10
31
  maxSize: Infinity,
11
32
  started: true,
12
33
  wait: 0
13
34
  };
14
35
  class AsyncQueuer {
15
- constructor(fn, initialOptions) {
36
+ constructor(fn, initialOptions = {}) {
16
37
  this.fn = fn;
17
- this._activeItems = /* @__PURE__ */ new Set();
18
- this._successCount = 0;
19
- this._errorCount = 0;
20
- this._settledCount = 0;
21
- this._rejectionCount = 0;
22
- this._expirationCount = 0;
23
- this._items = [];
24
- this._itemTimestamps = [];
25
- this._pendingTick = false;
26
- this._options = {
27
- ...defaultOptions,
28
- ...initialOptions,
29
- throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
38
+ this.store = new Store(getDefaultAsyncQueuerState());
39
+ this.#timeoutIds = /* @__PURE__ */ new Set();
40
+ this.setOptions = (newOptions) => {
41
+ this.options = { ...this.options, ...newOptions };
30
42
  };
31
- this._running = this._options.started;
32
- for (let i = 0; i < this._options.initialItems.length; i++) {
33
- const item = this._options.initialItems[i];
34
- const isLast = i === this._options.initialItems.length - 1;
35
- this.addItem(item, this._options.addItemsTo, isLast);
36
- }
37
- }
38
- /**
39
- * Updates the queuer options. New options are merged with existing options.
40
- */
41
- setOptions(newOptions) {
42
- this._options = { ...this._options, ...newOptions };
43
- }
44
- /**
45
- * Returns the current queuer options, including defaults and any overrides.
46
- */
47
- getOptions() {
48
- return this._options;
49
- }
50
- /**
51
- * Returns the current wait time (in milliseconds) between processing items.
52
- * If a function is provided, it is called with the queuer instance.
53
- */
54
- getWait() {
55
- return parseFunctionOrValue(this._options.wait, this);
56
- }
57
- /**
58
- * Returns the current concurrency limit for processing items.
59
- * If a function is provided, it is called with the queuer instance.
60
- */
61
- getConcurrency() {
62
- return parseFunctionOrValue(this._options.concurrency, this);
63
- }
64
- /**
65
- * Processes items in the queue up to the concurrency limit. Internal use only.
66
- */
67
- tick() {
68
- var _a, _b;
69
- if (!this._running) {
70
- this._pendingTick = false;
71
- return;
72
- }
73
- this.checkExpiredItems();
74
- while (this._activeItems.size < this.getConcurrency() && !this.getIsEmpty()) {
75
- const nextItem = this.getPeek();
76
- if (!nextItem) {
77
- break;
43
+ this.#setState = (newState) => {
44
+ this.store.setState((state) => {
45
+ const combinedState = {
46
+ ...state,
47
+ ...newState
48
+ };
49
+ const { activeItems, items, isRunning } = combinedState;
50
+ const size = items.length;
51
+ const isFull = size >= (this.options.maxSize ?? Infinity);
52
+ const isEmpty = size === 0;
53
+ const isIdle = isRunning && isEmpty && activeItems.length === 0;
54
+ const status = isIdle ? "idle" : isRunning ? "running" : "stopped";
55
+ return {
56
+ ...combinedState,
57
+ isEmpty,
58
+ isFull,
59
+ isIdle,
60
+ size,
61
+ status
62
+ };
63
+ });
64
+ };
65
+ this.#getWait = () => {
66
+ return parseFunctionOrValue(this.options.wait ?? 0, this);
67
+ };
68
+ this.#getConcurrency = () => {
69
+ return parseFunctionOrValue(this.options.concurrency ?? 1, this);
70
+ };
71
+ this.#tick = () => {
72
+ if (!this.store.state.isRunning) {
73
+ this.#setState({ pendingTick: false });
74
+ return;
78
75
  }
79
- this._activeItems.add(nextItem);
80
- (_b = (_a = this._options).onItemsChange) == null ? void 0 : _b.call(_a, this);
81
- (async () => {
82
- this._lastResult = await this.execute();
83
- const wait = this.getWait();
84
- if (wait > 0) {
85
- setTimeout(() => this.tick(), wait);
86
- return;
76
+ this.#setState({ pendingTick: true });
77
+ this.#checkExpiredItems();
78
+ const activeItems = this.store.state.activeItems;
79
+ while (activeItems.length < this.#getConcurrency() && !this.store.state.isEmpty) {
80
+ const nextItem = this.peekNextItem();
81
+ if (!nextItem) {
82
+ break;
83
+ }
84
+ activeItems.push(nextItem);
85
+ this.#setState({
86
+ activeItems
87
+ });
88
+ (async () => {
89
+ const result = await this.execute();
90
+ this.#setState({ lastResult: result });
91
+ const wait = this.#getWait();
92
+ if (wait > 0) {
93
+ const timeoutId = setTimeout(() => this.#tick(), wait);
94
+ this.#timeoutIds.add(timeoutId);
95
+ return;
96
+ }
97
+ this.#tick();
98
+ })();
99
+ }
100
+ this.#setState({ pendingTick: false });
101
+ };
102
+ this.addItem = (item, position = this.options.addItemsTo ?? "back", runOnItemsChange = true) => {
103
+ if (this.store.state.isFull) {
104
+ this.#setState({
105
+ rejectionCount: this.store.state.rejectionCount + 1
106
+ });
107
+ this.options.onReject?.(item, this);
108
+ return false;
109
+ }
110
+ const priority = this.options.getPriority !== defaultOptions.getPriority ? this.options.getPriority(item) : item.priority;
111
+ const items = this.store.state.items;
112
+ const itemTimestamps = this.store.state.itemTimestamps;
113
+ if (priority !== void 0) {
114
+ const insertIndex = items.findIndex((existing) => {
115
+ const existingPriority = this.options.getPriority !== defaultOptions.getPriority ? this.options.getPriority(existing) : existing.priority;
116
+ return existingPriority < priority;
117
+ });
118
+ if (insertIndex === -1) {
119
+ items.push(item);
120
+ itemTimestamps.push(Date.now());
121
+ } else {
122
+ items.splice(insertIndex, 0, item);
123
+ itemTimestamps.splice(insertIndex, 0, Date.now());
87
124
  }
88
- this.tick();
89
- })();
90
- }
91
- this._pendingTick = false;
92
- }
93
- /**
94
- * Starts processing items in the queue. If already running, does nothing.
95
- */
96
- start() {
97
- var _a, _b;
98
- this._running = true;
99
- if (!this._pendingTick && !this.getIsEmpty()) {
100
- this._pendingTick = true;
101
- this.tick();
102
- }
103
- (_b = (_a = this._options).onIsRunningChange) == null ? void 0 : _b.call(_a, this);
104
- }
105
- /**
106
- * Stops processing items in the queue. Does not clear the queue.
107
- */
108
- stop() {
109
- var _a, _b;
110
- this._running = false;
111
- this._pendingTick = false;
112
- (_b = (_a = this._options).onIsRunningChange) == null ? void 0 : _b.call(_a, this);
113
- }
114
- /**
115
- * Removes all pending items from the queue. Does not affect active tasks.
116
- */
117
- clear() {
118
- var _a, _b;
119
- this._items = [];
120
- (_b = (_a = this._options).onItemsChange) == null ? void 0 : _b.call(_a, this);
121
- }
122
- /**
123
- * Resets the queuer to its initial state. Optionally repopulates with initial items.
124
- * Does not affect callbacks or options.
125
- */
126
- reset(withInitialItems) {
127
- this.clear();
128
- this._successCount = 0;
129
- this._errorCount = 0;
130
- this._settledCount = 0;
131
- if (withInitialItems) {
132
- this._items = [...this._options.initialItems];
133
- }
134
- this._running = this._options.started;
135
- }
136
- /**
137
- * Adds an item to the queue. If the queue is full, the item is rejected and onReject is called.
138
- * Items can be inserted based on priority or at the front/back depending on configuration.
139
- *
140
- * @example
141
- * ```ts
142
- * queuer.addItem({ value: 'task', priority: 10 });
143
- * queuer.addItem('task2', 'front');
144
- * ```
145
- */
146
- addItem(item, position = this._options.addItemsTo, runOnItemsChange = true) {
147
- var _a, _b, _c, _d;
148
- if (this.getIsFull()) {
149
- this._rejectionCount++;
150
- (_b = (_a = this._options).onReject) == null ? void 0 : _b.call(_a, item, this);
151
- return;
152
- }
153
- const priority = this._options.getPriority !== defaultOptions.getPriority ? this._options.getPriority(item) : item.priority;
154
- if (priority !== void 0) {
155
- const insertIndex = this._items.findIndex((existing) => {
156
- const existingPriority = this._options.getPriority !== defaultOptions.getPriority ? this._options.getPriority(existing) : existing.priority;
157
- return existingPriority < priority;
158
- });
159
- if (insertIndex === -1) {
160
- this._items.push(item);
161
- this._itemTimestamps.push(Date.now());
162
125
  } else {
163
- this._items.splice(insertIndex, 0, item);
164
- this._itemTimestamps.splice(insertIndex, 0, Date.now());
126
+ if (position === "front") {
127
+ items.unshift(item);
128
+ itemTimestamps.unshift(Date.now());
129
+ } else {
130
+ items.push(item);
131
+ itemTimestamps.push(Date.now());
132
+ }
165
133
  }
166
- } else {
134
+ this.#setState({
135
+ items,
136
+ itemTimestamps
137
+ });
138
+ if (runOnItemsChange) {
139
+ this.options.onItemsChange?.(this);
140
+ }
141
+ if (this.store.state.isRunning && !this.store.state.pendingTick) {
142
+ this.#tick();
143
+ }
144
+ return true;
145
+ };
146
+ this.getNextItem = (position = this.options.getItemsFrom ?? "front") => {
147
+ const { items, itemTimestamps } = this.store.state;
148
+ let item;
167
149
  if (position === "front") {
168
- this._items.unshift(item);
169
- this._itemTimestamps.unshift(Date.now());
150
+ item = items[0];
151
+ if (item !== void 0) {
152
+ this.#setState({
153
+ items: items.slice(1),
154
+ itemTimestamps: itemTimestamps.slice(1)
155
+ });
156
+ }
170
157
  } else {
171
- this._items.push(item);
172
- this._itemTimestamps.push(Date.now());
158
+ item = items[items.length - 1];
159
+ if (item !== void 0) {
160
+ this.#setState({
161
+ items: items.slice(0, -1),
162
+ itemTimestamps: itemTimestamps.slice(0, -1)
163
+ });
164
+ }
173
165
  }
174
- }
175
- if (runOnItemsChange) {
176
- (_d = (_c = this._options).onItemsChange) == null ? void 0 : _d.call(_c, this);
177
- }
178
- if (this._running && !this._pendingTick) {
179
- this._pendingTick = true;
180
- this.tick();
181
- }
182
- }
183
- /**
184
- * Removes and returns the next item from the queue without executing the task function.
185
- * Use for manual queue management. Normally, use execute() to process items.
186
- *
187
- * @example
188
- * ```ts
189
- * // FIFO
190
- * queuer.getNextItem();
191
- * // LIFO
192
- * queuer.getNextItem('back');
193
- * ```
194
- */
195
- getNextItem(position = this._options.getItemsFrom) {
196
- var _a, _b;
197
- let item;
198
- if (position === "front") {
199
- item = this._items.shift();
200
- this._itemTimestamps.shift();
201
- } else {
202
- item = this._items.pop();
203
- this._itemTimestamps.pop();
204
- }
205
- if (item !== void 0) {
206
- (_b = (_a = this._options).onItemsChange) == null ? void 0 : _b.call(_a, this);
207
- }
208
- return item;
209
- }
210
- /**
211
- * Removes and returns the next item from the queue and executes the task function with it.
212
- *
213
- * @example
214
- * ```ts
215
- * queuer.execute();
216
- * // LIFO
217
- * queuer.execute('back');
218
- * ```
219
- */
220
- async execute(position) {
221
- var _a, _b, _c, _d, _e, _f, _g, _h;
222
- const item = this.getNextItem(position);
223
- if (item !== void 0) {
224
- try {
225
- this._lastResult = await this.fn(item);
226
- this._successCount++;
227
- (_b = (_a = this._options).onSuccess) == null ? void 0 : _b.call(_a, this._lastResult, this);
228
- } catch (error) {
229
- this._errorCount++;
230
- (_d = (_c = this._options).onError) == null ? void 0 : _d.call(_c, error, this);
231
- if (this._options.throwOnError) {
232
- throw error;
166
+ if (item !== void 0) {
167
+ this.options.onItemsChange?.(this);
168
+ }
169
+ return item;
170
+ };
171
+ this.execute = async (position) => {
172
+ const item = this.getNextItem(position);
173
+ if (item !== void 0) {
174
+ try {
175
+ const lastResult = await this.fn(item);
176
+ this.#setState({
177
+ successCount: this.store.state.successCount + 1,
178
+ lastResult
179
+ });
180
+ this.options.onSuccess?.(lastResult, this);
181
+ } catch (error) {
182
+ this.#setState({
183
+ errorCount: this.store.state.errorCount + 1
184
+ });
185
+ this.options.onError?.(error, this);
186
+ if (this.options.throwOnError) {
187
+ throw error;
188
+ }
189
+ } finally {
190
+ this.#setState({
191
+ activeItems: this.store.state.activeItems.filter(
192
+ (activeItem) => activeItem !== item
193
+ ),
194
+ settledCount: this.store.state.settledCount + 1
195
+ });
196
+ this.options.onSettled?.(this);
233
197
  }
234
- } finally {
235
- this._settledCount++;
236
- this._activeItems.delete(item);
237
- (_f = (_e = this._options).onItemsChange) == null ? void 0 : _f.call(_e, this);
238
- (_h = (_g = this._options).onSettled) == null ? void 0 : _h.call(_g, this);
239
198
  }
240
- }
241
- return item;
242
- }
243
- /**
244
- * Checks for expired items in the queue and removes them. Calls onExpire for each expired item.
245
- * Internal use only.
246
- */
247
- checkExpiredItems() {
248
- var _a, _b, _c, _d;
249
- if (this._options.expirationDuration === Infinity && this._options.getIsExpired === defaultOptions.getIsExpired)
250
- return;
251
- const now = Date.now();
252
- const expiredIndices = [];
253
- for (let i = 0; i < this._items.length; i++) {
254
- const timestamp = this._itemTimestamps[i];
255
- if (timestamp === void 0) continue;
256
- const item = this._items[i];
257
- if (item === void 0) continue;
258
- const isExpired = this._options.getIsExpired !== defaultOptions.getIsExpired ? this._options.getIsExpired(item, timestamp) : now - timestamp > this._options.expirationDuration;
259
- if (isExpired) {
260
- expiredIndices.push(i);
199
+ return item;
200
+ };
201
+ this.flush = (numberOfItems = this.store.state.items.length, position) => {
202
+ this.#clearTimeouts();
203
+ for (let i = 0; i < numberOfItems; i++) {
204
+ this.execute(position);
205
+ }
206
+ };
207
+ this.#checkExpiredItems = () => {
208
+ if ((this.options.expirationDuration ?? Infinity) === Infinity && this.options.getIsExpired === defaultOptions.getIsExpired) {
209
+ return;
210
+ }
211
+ const now = Date.now();
212
+ const expiredIndices = [];
213
+ for (let i = 0; i < this.store.state.size; i++) {
214
+ const timestamp = this.store.state.itemTimestamps[i];
215
+ if (timestamp === void 0) continue;
216
+ const item = this.store.state.items[i];
217
+ if (item === void 0) continue;
218
+ const isExpired = this.options.getIsExpired !== defaultOptions.getIsExpired ? this.options.getIsExpired(item, timestamp) : now - timestamp > (this.options.expirationDuration ?? Infinity);
219
+ if (isExpired) {
220
+ expiredIndices.push(i);
221
+ }
222
+ }
223
+ for (let i = expiredIndices.length - 1; i >= 0; i--) {
224
+ const index = expiredIndices[i];
225
+ if (index === void 0) continue;
226
+ const expiredItem = this.store.state.items[index];
227
+ if (expiredItem === void 0) continue;
228
+ const newItems = [...this.store.state.items];
229
+ const newTimestamps = [...this.store.state.itemTimestamps];
230
+ newItems.splice(index, 1);
231
+ newTimestamps.splice(index, 1);
232
+ this.#setState({
233
+ items: newItems,
234
+ itemTimestamps: newTimestamps,
235
+ expirationCount: this.store.state.expirationCount + 1
236
+ });
237
+ this.options.onExpire?.(expiredItem, this);
238
+ }
239
+ if (expiredIndices.length > 0) {
240
+ this.options.onItemsChange?.(this);
241
+ }
242
+ };
243
+ this.peekNextItem = (position = "front") => {
244
+ if (position === "front") {
245
+ return this.store.state.items[0];
246
+ }
247
+ return this.store.state.items[this.store.state.size - 1];
248
+ };
249
+ this.peekAllItems = () => {
250
+ return [...this.peekActiveItems(), ...this.peekPendingItems()];
251
+ };
252
+ this.peekActiveItems = () => {
253
+ return [...this.store.state.activeItems];
254
+ };
255
+ this.peekPendingItems = () => {
256
+ return [...this.store.state.items];
257
+ };
258
+ this.start = () => {
259
+ this.#setState({ isRunning: true });
260
+ if (!this.store.state.pendingTick && !this.store.state.isEmpty) {
261
+ this.#tick();
262
+ }
263
+ };
264
+ this.stop = () => {
265
+ this.#clearTimeouts();
266
+ this.#setState({ isRunning: false, pendingTick: false });
267
+ };
268
+ this.#clearTimeouts = () => {
269
+ this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId));
270
+ this.#timeoutIds.clear();
271
+ };
272
+ this.clear = () => {
273
+ this.#setState({ items: [], itemTimestamps: [] });
274
+ this.options.onItemsChange?.(this);
275
+ };
276
+ this.reset = () => {
277
+ this.#setState(getDefaultAsyncQueuerState());
278
+ this.options.onItemsChange?.(this);
279
+ };
280
+ this.options = {
281
+ ...defaultOptions,
282
+ ...initialOptions,
283
+ throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
284
+ };
285
+ const isInitiallyRunning = this.options.initialState?.isRunning ?? this.options.started ?? true;
286
+ this.#setState({
287
+ ...this.options.initialState,
288
+ isRunning: isInitiallyRunning
289
+ });
290
+ if (this.options.initialState?.items) {
291
+ if (this.store.state.isRunning) {
292
+ this.#tick();
293
+ }
294
+ } else {
295
+ for (let i = 0; i < (this.options.initialItems?.length ?? 0); i++) {
296
+ const item = this.options.initialItems[i];
297
+ const isLast = i === (this.options.initialItems?.length ?? 0) - 1;
298
+ this.addItem(item, this.options.addItemsTo ?? "back", isLast);
261
299
  }
262
300
  }
263
- for (let i = expiredIndices.length - 1; i >= 0; i--) {
264
- const index = expiredIndices[i];
265
- if (index === void 0) continue;
266
- const expiredItem = this._items[index];
267
- if (expiredItem === void 0) continue;
268
- this._items.splice(index, 1);
269
- this._itemTimestamps.splice(index, 1);
270
- this._expirationCount++;
271
- (_b = (_a = this._options).onExpire) == null ? void 0 : _b.call(_a, expiredItem, this);
272
- }
273
- if (expiredIndices.length > 0) {
274
- (_d = (_c = this._options).onItemsChange) == null ? void 0 : _d.call(_c, this);
275
- }
276
- }
277
- /**
278
- * Returns the next item in the queue without removing it.
279
- *
280
- * @example
281
- * ```ts
282
- * queuer.getPeek(); // front
283
- * queuer.getPeek('back'); // back
284
- * ```
285
- */
286
- getPeek(position = "front") {
287
- if (position === "front") {
288
- return this._items[0];
289
- }
290
- return this._items[this._items.length - 1];
291
- }
292
- /**
293
- * Returns true if the queue is empty (no pending items).
294
- */
295
- getIsEmpty() {
296
- return this._items.length === 0;
297
- }
298
- /**
299
- * Returns true if the queue is full (reached maxSize).
300
- */
301
- getIsFull() {
302
- return this._items.length >= this._options.maxSize;
303
- }
304
- /**
305
- * Returns the number of pending items in the queue.
306
- */
307
- getSize() {
308
- return this._items.length;
309
- }
310
- /**
311
- * Returns a copy of all items in the queue, including active and pending items.
312
- */
313
- getAllItems() {
314
- return [...this.getActiveItems(), ...this.getPendingItems()];
315
- }
316
- /**
317
- * Returns the items currently being processed (active tasks).
318
- */
319
- getActiveItems() {
320
- return Array.from(this._activeItems);
321
- }
322
- /**
323
- * Returns the items waiting to be processed (pending tasks).
324
- */
325
- getPendingItems() {
326
- return [...this._items];
327
- }
328
- /**
329
- * Returns the number of items that have been successfully processed.
330
- */
331
- getSuccessCount() {
332
- return this._successCount;
333
- }
334
- /**
335
- * Returns the number of items that have failed processing.
336
- */
337
- getErrorCount() {
338
- return this._errorCount;
339
- }
340
- /**
341
- * Returns the number of items that have completed processing (success or error).
342
- */
343
- getSettledCount() {
344
- return this._settledCount;
345
- }
346
- /**
347
- * Returns the number of items that have been rejected from being added to the queue.
348
- */
349
- getRejectionCount() {
350
- return this._rejectionCount;
351
- }
352
- /**
353
- * Returns true if the queuer is currently running (processing items).
354
- */
355
- getIsRunning() {
356
- return this._running;
357
- }
358
- /**
359
- * Returns true if the queuer is running but has no items to process and no active tasks.
360
- */
361
- getIsIdle() {
362
- return this._running && this.getIsEmpty() && this._activeItems.size === 0;
363
- }
364
- /**
365
- * Returns the number of items that have expired and been removed from the queue.
366
- */
367
- getExpirationCount() {
368
- return this._expirationCount;
369
301
  }
302
+ #timeoutIds;
303
+ #setState;
304
+ #getWait;
305
+ #getConcurrency;
306
+ #tick;
307
+ #checkExpiredItems;
308
+ #clearTimeouts;
370
309
  }
371
310
  function asyncQueue(fn, initialOptions) {
372
311
  const asyncQueuer = new AsyncQueuer(fn, initialOptions);
373
- return asyncQueuer.addItem.bind(asyncQueuer);
312
+ return asyncQueuer.addItem;
374
313
  }
375
314
  export {
376
315
  AsyncQueuer,