@tanstack/pacer 0.16.3 → 0.17.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 (169) hide show
  1. package/README.md +165 -0
  2. package/dist/async-batcher.cjs +355 -0
  3. package/dist/async-batcher.cjs.map +1 -0
  4. package/dist/async-batcher.d.cts +344 -0
  5. package/dist/async-batcher.d.ts +344 -0
  6. package/dist/async-batcher.js +353 -0
  7. package/dist/async-batcher.js.map +1 -0
  8. package/dist/async-debouncer.cjs +340 -0
  9. package/dist/async-debouncer.cjs.map +1 -0
  10. package/dist/async-debouncer.d.cts +300 -0
  11. package/dist/async-debouncer.d.ts +300 -0
  12. package/dist/async-debouncer.js +338 -0
  13. package/dist/async-debouncer.js.map +1 -0
  14. package/dist/async-queuer.cjs +496 -0
  15. package/dist/async-queuer.cjs.map +1 -0
  16. package/dist/async-queuer.d.cts +440 -0
  17. package/dist/async-queuer.d.ts +440 -0
  18. package/dist/async-queuer.js +494 -0
  19. package/dist/async-queuer.js.map +1 -0
  20. package/dist/async-rate-limiter.cjs +381 -0
  21. package/dist/async-rate-limiter.cjs.map +1 -0
  22. package/dist/{cjs/async-rate-limiter.d.cts → async-rate-limiter.d.cts} +190 -185
  23. package/dist/{esm/async-rate-limiter.d.ts → async-rate-limiter.d.ts} +190 -185
  24. package/dist/async-rate-limiter.js +379 -0
  25. package/dist/async-rate-limiter.js.map +1 -0
  26. package/dist/async-retryer.cjs +378 -0
  27. package/dist/async-retryer.cjs.map +1 -0
  28. package/dist/async-retryer.d.cts +312 -0
  29. package/dist/async-retryer.d.ts +312 -0
  30. package/dist/async-retryer.js +376 -0
  31. package/dist/async-retryer.js.map +1 -0
  32. package/dist/async-throttler.cjs +362 -0
  33. package/dist/async-throttler.cjs.map +1 -0
  34. package/dist/async-throttler.d.cts +320 -0
  35. package/dist/async-throttler.d.ts +320 -0
  36. package/dist/async-throttler.js +360 -0
  37. package/dist/async-throttler.js.map +1 -0
  38. package/dist/batcher.cjs +194 -0
  39. package/dist/batcher.cjs.map +1 -0
  40. package/dist/batcher.d.cts +180 -0
  41. package/dist/batcher.d.ts +180 -0
  42. package/dist/batcher.js +193 -0
  43. package/dist/batcher.js.map +1 -0
  44. package/dist/debouncer.cjs +197 -0
  45. package/dist/debouncer.cjs.map +1 -0
  46. package/dist/debouncer.d.cts +167 -0
  47. package/dist/debouncer.d.ts +167 -0
  48. package/dist/debouncer.js +195 -0
  49. package/dist/debouncer.js.map +1 -0
  50. package/dist/event-client.cjs +20 -0
  51. package/dist/event-client.cjs.map +1 -0
  52. package/dist/event-client.d.cts +49 -0
  53. package/dist/event-client.d.ts +49 -0
  54. package/dist/event-client.js +19 -0
  55. package/dist/event-client.js.map +1 -0
  56. package/dist/index.cjs +49 -0
  57. package/dist/index.d.cts +15 -0
  58. package/dist/index.d.ts +15 -0
  59. package/dist/{esm/index.js → index.js} +5 -41
  60. package/dist/queuer.cjs +393 -0
  61. package/dist/queuer.cjs.map +1 -0
  62. package/dist/queuer.d.cts +345 -0
  63. package/dist/queuer.d.ts +345 -0
  64. package/dist/queuer.js +391 -0
  65. package/dist/queuer.js.map +1 -0
  66. package/dist/rate-limiter.cjs +251 -0
  67. package/dist/rate-limiter.cjs.map +1 -0
  68. package/dist/{cjs/rate-limiter.d.cts → rate-limiter.d.cts} +113 -108
  69. package/dist/{esm/rate-limiter.d.ts → rate-limiter.d.ts} +113 -108
  70. package/dist/rate-limiter.js +249 -0
  71. package/dist/rate-limiter.js.map +1 -0
  72. package/dist/throttler.cjs +209 -0
  73. package/dist/throttler.cjs.map +1 -0
  74. package/dist/throttler.d.cts +207 -0
  75. package/dist/throttler.d.ts +207 -0
  76. package/dist/throttler.js +207 -0
  77. package/dist/throttler.js.map +1 -0
  78. package/dist/types.cjs +0 -0
  79. package/dist/types.d.cts +13 -0
  80. package/dist/types.d.ts +13 -0
  81. package/dist/types.js +1 -0
  82. package/dist/utils.cjs +13 -0
  83. package/dist/utils.cjs.map +1 -0
  84. package/dist/utils.d.cts +8 -0
  85. package/dist/utils.d.ts +8 -0
  86. package/dist/utils.js +11 -0
  87. package/dist/utils.js.map +1 -0
  88. package/package.json +39 -123
  89. package/dist/cjs/async-batcher.cjs +0 -222
  90. package/dist/cjs/async-batcher.cjs.map +0 -1
  91. package/dist/cjs/async-batcher.d.cts +0 -340
  92. package/dist/cjs/async-debouncer.cjs +0 -233
  93. package/dist/cjs/async-debouncer.cjs.map +0 -1
  94. package/dist/cjs/async-debouncer.d.cts +0 -295
  95. package/dist/cjs/async-queuer.cjs +0 -399
  96. package/dist/cjs/async-queuer.cjs.map +0 -1
  97. package/dist/cjs/async-queuer.d.cts +0 -435
  98. package/dist/cjs/async-rate-limiter.cjs +0 -254
  99. package/dist/cjs/async-rate-limiter.cjs.map +0 -1
  100. package/dist/cjs/async-retryer.cjs +0 -287
  101. package/dist/cjs/async-retryer.cjs.map +0 -1
  102. package/dist/cjs/async-retryer.d.cts +0 -308
  103. package/dist/cjs/async-throttler.cjs +0 -263
  104. package/dist/cjs/async-throttler.cjs.map +0 -1
  105. package/dist/cjs/async-throttler.d.cts +0 -315
  106. package/dist/cjs/batcher.cjs +0 -132
  107. package/dist/cjs/batcher.cjs.map +0 -1
  108. package/dist/cjs/batcher.d.cts +0 -176
  109. package/dist/cjs/debouncer.cjs +0 -139
  110. package/dist/cjs/debouncer.cjs.map +0 -1
  111. package/dist/cjs/debouncer.d.cts +0 -162
  112. package/dist/cjs/event-client.cjs +0 -20
  113. package/dist/cjs/event-client.cjs.map +0 -1
  114. package/dist/cjs/event-client.d.cts +0 -45
  115. package/dist/cjs/index.cjs +0 -51
  116. package/dist/cjs/index.cjs.map +0 -1
  117. package/dist/cjs/index.d.cts +0 -15
  118. package/dist/cjs/queuer.cjs +0 -308
  119. package/dist/cjs/queuer.cjs.map +0 -1
  120. package/dist/cjs/queuer.d.cts +0 -340
  121. package/dist/cjs/rate-limiter.cjs +0 -181
  122. package/dist/cjs/rate-limiter.cjs.map +0 -1
  123. package/dist/cjs/throttler.cjs +0 -153
  124. package/dist/cjs/throttler.cjs.map +0 -1
  125. package/dist/cjs/throttler.d.cts +0 -202
  126. package/dist/cjs/types.d.cts +0 -9
  127. package/dist/cjs/utils.cjs +0 -11
  128. package/dist/cjs/utils.cjs.map +0 -1
  129. package/dist/cjs/utils.d.cts +0 -3
  130. package/dist/esm/async-batcher.d.ts +0 -340
  131. package/dist/esm/async-batcher.js +0 -222
  132. package/dist/esm/async-batcher.js.map +0 -1
  133. package/dist/esm/async-debouncer.d.ts +0 -295
  134. package/dist/esm/async-debouncer.js +0 -233
  135. package/dist/esm/async-debouncer.js.map +0 -1
  136. package/dist/esm/async-queuer.d.ts +0 -435
  137. package/dist/esm/async-queuer.js +0 -399
  138. package/dist/esm/async-queuer.js.map +0 -1
  139. package/dist/esm/async-rate-limiter.js +0 -254
  140. package/dist/esm/async-rate-limiter.js.map +0 -1
  141. package/dist/esm/async-retryer.d.ts +0 -308
  142. package/dist/esm/async-retryer.js +0 -287
  143. package/dist/esm/async-retryer.js.map +0 -1
  144. package/dist/esm/async-throttler.d.ts +0 -315
  145. package/dist/esm/async-throttler.js +0 -263
  146. package/dist/esm/async-throttler.js.map +0 -1
  147. package/dist/esm/batcher.d.ts +0 -176
  148. package/dist/esm/batcher.js +0 -132
  149. package/dist/esm/batcher.js.map +0 -1
  150. package/dist/esm/debouncer.d.ts +0 -162
  151. package/dist/esm/debouncer.js +0 -139
  152. package/dist/esm/debouncer.js.map +0 -1
  153. package/dist/esm/event-client.d.ts +0 -45
  154. package/dist/esm/event-client.js +0 -20
  155. package/dist/esm/event-client.js.map +0 -1
  156. package/dist/esm/index.d.ts +0 -15
  157. package/dist/esm/index.js.map +0 -1
  158. package/dist/esm/queuer.d.ts +0 -340
  159. package/dist/esm/queuer.js +0 -308
  160. package/dist/esm/queuer.js.map +0 -1
  161. package/dist/esm/rate-limiter.js +0 -181
  162. package/dist/esm/rate-limiter.js.map +0 -1
  163. package/dist/esm/throttler.d.ts +0 -202
  164. package/dist/esm/throttler.js +0 -153
  165. package/dist/esm/throttler.js.map +0 -1
  166. package/dist/esm/types.d.ts +0 -9
  167. package/dist/esm/utils.d.ts +0 -3
  168. package/dist/esm/utils.js +0 -11
  169. package/dist/esm/utils.js.map +0 -1
@@ -1,340 +0,0 @@
1
- import { Store } from '@tanstack/store';
2
- export interface QueuerState<TValue> {
3
- /**
4
- * Number of times addItem has been called (for reduction calculations)
5
- */
6
- addItemCount: number;
7
- /**
8
- * Number of items that have been processed by the queuer
9
- */
10
- executionCount: number;
11
- /**
12
- * Number of items that have been removed from the queue due to expiration
13
- */
14
- expirationCount: number;
15
- /**
16
- * Whether the queuer has no items to process (items array is empty)
17
- */
18
- isEmpty: boolean;
19
- /**
20
- * Whether the queuer has reached its maximum capacity
21
- */
22
- isFull: boolean;
23
- /**
24
- * Whether the queuer is not currently processing any items
25
- */
26
- isIdle: boolean;
27
- /**
28
- * Whether the queuer is active and will process items automatically
29
- */
30
- isRunning: boolean;
31
- /**
32
- * Array of items currently waiting to be processed
33
- */
34
- items: Array<TValue>;
35
- /**
36
- * Timestamps when items were added to the queue for expiration tracking
37
- */
38
- itemTimestamps: Array<number>;
39
- /**
40
- * Whether the queuer has a pending timeout for processing the next item
41
- */
42
- pendingTick: boolean;
43
- /**
44
- * Number of items that have been rejected from being added to the queue
45
- */
46
- rejectionCount: number;
47
- /**
48
- * Number of items currently in the queue
49
- */
50
- size: number;
51
- /**
52
- * Current processing status - 'idle' when not processing, 'running' when active, 'stopped' when paused
53
- */
54
- status: 'idle' | 'running' | 'stopped';
55
- }
56
- /**
57
- * Options for configuring a Queuer instance.
58
- *
59
- * These options control queue behavior, item expiration, callbacks, and more.
60
- */
61
- export interface QueuerOptions<TValue> {
62
- /**
63
- * Default position to add items to the queuer
64
- * @default 'back'
65
- */
66
- addItemsTo?: QueuePosition;
67
- /**
68
- * Maximum time in milliseconds that an item can stay in the queue
69
- * If not provided, items will never expire
70
- */
71
- expirationDuration?: number;
72
- /**
73
- * Function to determine if an item has expired
74
- * If provided, this overrides the expirationDuration behavior
75
- */
76
- getIsExpired?: (item: TValue, addedAt: number) => boolean;
77
- /**
78
- * Default position to get items from during processing
79
- * @default 'front'
80
- */
81
- getItemsFrom?: QueuePosition;
82
- /**
83
- * Function to determine priority of items in the queuer
84
- * Higher priority items will be processed first
85
- */
86
- getPriority?: (item: TValue) => number;
87
- /**
88
- * Initial items to populate the queuer with
89
- */
90
- initialItems?: Array<TValue>;
91
- /**
92
- * Initial state for the queuer
93
- */
94
- initialState?: Partial<QueuerState<TValue>>;
95
- /**
96
- * Optional key to identify this queuer instance.
97
- * If provided, the queuer will be identified by this key in the devtools and PacerProvider if applicable.
98
- */
99
- key?: string;
100
- /**
101
- * Maximum number of items allowed in the queuer
102
- */
103
- maxSize?: number;
104
- /**
105
- * Callback fired whenever an item is removed from the queuer
106
- */
107
- onExecute?: (item: TValue, queuer: Queuer<TValue>) => void;
108
- /**
109
- * Callback fired whenever an item expires in the queuer
110
- */
111
- onExpire?: (item: TValue, queuer: Queuer<TValue>) => void;
112
- /**
113
- * Callback fired whenever an item is added or removed from the queuer
114
- */
115
- onItemsChange?: (queuer: Queuer<TValue>) => void;
116
- /**
117
- * Callback fired whenever an item is rejected from being added to the queuer
118
- */
119
- onReject?: (item: TValue, queuer: Queuer<TValue>) => void;
120
- /**
121
- * Whether the queuer should start processing tasks immediately
122
- */
123
- started?: boolean;
124
- /**
125
- * Time in milliseconds to wait between processing items.
126
- * Can be a number or a function that returns a number.
127
- * @default 0
128
- */
129
- wait?: number | ((queuer: Queuer<TValue>) => number);
130
- }
131
- /**
132
- * Utility function for sharing common `QueuerOptions` options between different `Queuer` instances.
133
- */
134
- export declare function queuerOptions<TValue = any, TOptions extends Partial<QueuerOptions<TValue>> = Partial<QueuerOptions<TValue>>>(options: TOptions): TOptions;
135
- /**
136
- * Position type for addItem and getNextItem operations.
137
- *
138
- * - 'front': Operate on the front of the queue (FIFO)
139
- * - 'back': Operate on the back of the queue (LIFO)
140
- */
141
- export type QueuePosition = 'front' | 'back';
142
- /**
143
- * A flexible queue that processes items with configurable wait times, expiration, and priority.
144
- *
145
- * This synchronous version is lighter weight and often all you need - upgrade to AsyncQueuer when you need promises, retry support, abort capabilities, concurrent execution, or advanced error handling.
146
- *
147
- * Features:
148
- * - Automatic or manual processing of items
149
- * - FIFO (First In First Out), LIFO (Last In First Out), or double-ended queue behavior
150
- * - Priority-based ordering when getPriority is provided
151
- * - Item expiration and removal of stale items
152
- * - Callbacks for queue state changes, execution, rejection, and expiration
153
- *
154
- * Running behavior:
155
- * - `start()`: Begins automatically processing items in the queue (defaults to isRunning)
156
- * - `stop()`: Pauses processing but maintains queue state
157
- * - `wait`: Configurable delay between processing items
158
- * - `onItemsChange`/`onExecute`: Callbacks for monitoring queue state
159
- *
160
- * Manual processing is also supported when automatic processing is disabled:
161
- * - `execute()`: Processes the next item using the provided function
162
- * - `getNextItem()`: Removes and returns the next item without processing
163
- *
164
- * Queue behavior defaults to FIFO:
165
- * - `addItem(item)`: Adds to the back of the queue
166
- * - Items processed from the front of the queue
167
- *
168
- * Priority queue:
169
- * - Provide a `getPriority` function; higher values are processed first
170
- *
171
- * Stack (LIFO):
172
- * - `addItem(item, 'back')`: Adds to the back
173
- * - `getNextItem('back')`: Removes from the back
174
- *
175
- * Double-ended queue:
176
- * - `addItem(item, position)`: Adds to specified position ('front'/'back')
177
- * - `getNextItem(position)`: Removes from specified position
178
- *
179
- * Item expiration:
180
- * - `expirationDuration`: Maximum time items can stay in the queue
181
- * - `getIsExpired`: Function to override default expiration
182
- * - `onExpire`: Callback for expired items
183
- *
184
- * State Management:
185
- * - Uses TanStack Store for reactive state management
186
- * - Use `initialState` to provide initial state values when creating the queuer
187
- * - Use `onExecute` callback to react to item execution and implement custom logic
188
- * - Use `onItemsChange` callback to react to items being added or removed from the queue
189
- * - Use `onExpire` callback to react to items expiring and implement custom logic
190
- * - Use `onReject` callback to react to items being rejected when the queue is full
191
- * - The state includes execution count, expiration count, rejection count, and isRunning status
192
- * - State can be accessed via `queuer.store.state` when using the class directly
193
- * - When using framework adapters (React/Solid), state is accessed from `queuer.state`
194
- *
195
- * Example usage:
196
- * ```ts
197
- * // Auto-processing queue with wait time
198
- * const autoQueue = new Queuer<number>((n) => console.log(n), {
199
- * started: true, // Begin processing immediately
200
- * wait: 1000, // Wait 1s between items
201
- * onExecute: (item, queuer) => console.log(`Processed ${item}`)
202
- * });
203
- * autoQueue.addItem(1); // Will process after 1s
204
- * autoQueue.addItem(2); // Will process 1s after first item
205
- *
206
- * // Manual processing queue
207
- * const manualQueue = new Queuer<number>((n) => console.log(n), {
208
- * started: false
209
- * });
210
- * manualQueue.addItem(1); // [1]
211
- * manualQueue.addItem(2); // [1, 2]
212
- * manualQueue.execute(); // logs 1, queue is [2]
213
- * manualQueue.getNextItem(); // returns 2, queue is empty
214
- * ```
215
- */
216
- export declare class Queuer<TValue> {
217
- #private;
218
- fn: (item: TValue) => void;
219
- readonly store: Store<Readonly<QueuerState<TValue>>>;
220
- key: string | undefined;
221
- options: QueuerOptions<TValue>;
222
- constructor(fn: (item: TValue) => void, initialOptions?: QueuerOptions<TValue>);
223
- /**
224
- * Updates the queuer options. New options are merged with existing options.
225
- */
226
- setOptions: (newOptions: Partial<QueuerOptions<TValue>>) => void;
227
- /**
228
- * Adds an item to the queue. If the queue is full, the item is rejected and onReject is called.
229
- * Items can be inserted based on priority or at the front/back depending on configuration.
230
- *
231
- * Returns true if the item was added, false if the queue is full.
232
- *
233
- * Example usage:
234
- * ```ts
235
- * queuer.addItem('task');
236
- * queuer.addItem('task2', 'front');
237
- * ```
238
- */
239
- addItem: (item: TValue, position?: QueuePosition, runOnItemsChange?: boolean) => boolean;
240
- /**
241
- * Removes and returns the next item from the queue without executing the function.
242
- * Use for manual queue management. Normally, use execute() to process items.
243
- *
244
- * Example usage:
245
- * ```ts
246
- * // FIFO
247
- * queuer.getNextItem();
248
- * // LIFO
249
- * queuer.getNextItem('back');
250
- * ```
251
- */
252
- getNextItem: (position?: QueuePosition) => TValue | undefined;
253
- /**
254
- * Removes and returns the next item from the queue and processes it using the provided function.
255
- *
256
- * Example usage:
257
- * ```ts
258
- * queuer.execute();
259
- * // LIFO
260
- * queuer.execute('back');
261
- * ```
262
- */
263
- execute: (position?: QueuePosition) => TValue | undefined;
264
- /**
265
- * Processes a specified number of items to execute immediately with no wait time
266
- * If no numberOfItems is provided, all items will be processed
267
- */
268
- flush: (numberOfItems?: number, position?: QueuePosition) => void;
269
- /**
270
- * Processes all items in the queue as a batch using the provided function as an argument
271
- * The queue is cleared after processing
272
- */
273
- flushAsBatch: (batchFunction: (items: Array<TValue>) => void) => void;
274
- /**
275
- * Returns the next item in the queue without removing it.
276
- *
277
- * Example usage:
278
- * ```ts
279
- * queuer.peekNextItem(); // front
280
- * queuer.peekNextItem('back'); // back
281
- * ```
282
- */
283
- peekNextItem: (position?: QueuePosition) => TValue | undefined;
284
- /**
285
- * Returns a copy of all items in the queue.
286
- */
287
- peekAllItems: () => Array<TValue>;
288
- /**
289
- * Starts processing items in the queue. If already isRunning, does nothing.
290
- */
291
- start: () => void;
292
- /**
293
- * Stops processing items in the queue. Does not clear the queue.
294
- */
295
- stop: () => void;
296
- /**
297
- * Removes all pending items from the queue. Does not affect items being processed.
298
- */
299
- clear: () => void;
300
- /**
301
- * Resets the queuer state to its default values
302
- */
303
- reset: () => void;
304
- }
305
- /**
306
- * Creates a queue that processes items immediately upon addition.
307
- * Items are processed sequentially in FIFO order by default.
308
- *
309
- * This synchronous version is lighter weight and often all you need - upgrade to asyncQueue when you need promises, retry support, abort capabilities, concurrent execution, or advanced error handling.
310
- *
311
- * State Management:
312
- * - Uses TanStack Store for reactive state management
313
- * - Use `initialState` to provide initial state values when creating the queuer
314
- * - Use `onExecute` callback to react to item execution and implement custom logic
315
- * - Use `onItemsChange` callback to react to items being added or removed from the queue
316
- * - Use `onExpire` callback to react to items expiring and implement custom logic
317
- * - Use `onReject` callback to react to items being rejected when the queue is full
318
- * - The state includes execution count, expiration count, rejection count, and isRunning status
319
- * - State can be accessed via the underlying Queuer instance's `store.state` property
320
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
321
- *
322
- * Example usage:
323
- * ```ts
324
- * // Basic sequential processing
325
- * const processItems = queue<number>((n) => console.log(n), {
326
- * wait: 1000,
327
- * onItemsChange: (queuer) => console.log(queuer.peekAllItems())
328
- * });
329
- * processItems(1); // Logs: 1
330
- * processItems(2); // Logs: 2 after 1 completes
331
- *
332
- * // Priority queue
333
- * const processPriority = queue<number>((n) => console.log(n), {
334
- * getPriority: n => n // Higher numbers processed first
335
- * });
336
- * processPriority(1);
337
- * processPriority(3); // Processed before 1
338
- * ```
339
- */
340
- export declare function queue<TValue>(fn: (item: TValue) => void, initialOptions: QueuerOptions<TValue>): (item: TValue, position?: QueuePosition, runOnItemsChange?: boolean) => boolean;
@@ -1,308 +0,0 @@
1
- import { Store } from "@tanstack/store";
2
- import { parseFunctionOrValue } from "./utils.js";
3
- import { emitChange, pacerEventClient } from "./event-client.js";
4
- function getDefaultQueuerState() {
5
- return {
6
- executionCount: 0,
7
- expirationCount: 0,
8
- isEmpty: true,
9
- isFull: false,
10
- isIdle: true,
11
- isRunning: true,
12
- itemTimestamps: [],
13
- items: [],
14
- pendingTick: false,
15
- rejectionCount: 0,
16
- size: 0,
17
- status: "idle",
18
- addItemCount: 0
19
- };
20
- }
21
- function queuerOptions(options) {
22
- return options;
23
- }
24
- const defaultOptions = {
25
- addItemsTo: "back",
26
- getItemsFrom: "front",
27
- getPriority: (item) => item?.priority ?? 0,
28
- getIsExpired: () => false,
29
- expirationDuration: Infinity,
30
- initialItems: [],
31
- maxSize: Infinity,
32
- started: true,
33
- wait: 0
34
- };
35
- class Queuer {
36
- constructor(fn, initialOptions = {}) {
37
- this.fn = fn;
38
- this.store = new Store(
39
- getDefaultQueuerState()
40
- );
41
- this.#timeoutId = null;
42
- this.setOptions = (newOptions) => {
43
- this.options = { ...this.options, ...newOptions };
44
- };
45
- this.#setState = (newState) => {
46
- this.store.setState((state) => {
47
- const combinedState = {
48
- ...state,
49
- ...newState
50
- };
51
- const { items, isRunning } = combinedState;
52
- const size = items.length;
53
- const isFull = size >= (this.options.maxSize ?? Infinity);
54
- const isEmpty = size === 0;
55
- const isIdle = isRunning && isEmpty;
56
- const status = isIdle ? "idle" : isRunning ? "running" : "stopped";
57
- return {
58
- ...combinedState,
59
- isEmpty,
60
- isFull,
61
- isIdle,
62
- size,
63
- status
64
- };
65
- });
66
- emitChange("Queuer", this);
67
- };
68
- this.#getWait = () => {
69
- return parseFunctionOrValue(this.options.wait ?? 0, this);
70
- };
71
- this.#tick = () => {
72
- if (!this.store.state.isRunning) {
73
- this.#setState({ pendingTick: false });
74
- return;
75
- }
76
- this.#setState({ pendingTick: true });
77
- this.#checkExpiredItems();
78
- while (this.store.state.items.length > 0) {
79
- const nextItem = this.execute(this.options.getItemsFrom ?? "front");
80
- if (nextItem === void 0) {
81
- break;
82
- }
83
- const wait = this.#getWait();
84
- if (wait > 0) {
85
- this.#timeoutId = setTimeout(() => this.#tick(), wait);
86
- return;
87
- }
88
- this.#tick();
89
- }
90
- this.#setState({ pendingTick: false });
91
- };
92
- this.addItem = (item, position = this.options.addItemsTo ?? "back", runOnItemsChange = true) => {
93
- this.#setState({
94
- addItemCount: this.store.state.addItemCount + 1
95
- });
96
- if (this.store.state.items.length >= (this.options.maxSize ?? Infinity)) {
97
- this.#setState({
98
- rejectionCount: this.store.state.rejectionCount + 1
99
- });
100
- this.options.onReject?.(item, this);
101
- return false;
102
- }
103
- const priority = this.options.getPriority !== defaultOptions.getPriority ? this.options.getPriority(item) : item.priority;
104
- const items = this.store.state.items;
105
- const itemTimestamps = this.store.state.itemTimestamps;
106
- if (priority !== void 0) {
107
- const insertIndex = items.findIndex((existing) => {
108
- const existingPriority = this.options.getPriority !== defaultOptions.getPriority ? this.options.getPriority(existing) : existing.priority;
109
- return existingPriority < priority;
110
- });
111
- if (insertIndex === -1) {
112
- items.push(item);
113
- itemTimestamps.push(Date.now());
114
- } else {
115
- items.splice(insertIndex, 0, item);
116
- itemTimestamps.splice(insertIndex, 0, Date.now());
117
- }
118
- } else {
119
- if (position === "front") {
120
- items.unshift(item);
121
- itemTimestamps.unshift(Date.now());
122
- } else {
123
- items.push(item);
124
- itemTimestamps.push(Date.now());
125
- }
126
- }
127
- this.#setState({
128
- items,
129
- itemTimestamps
130
- });
131
- if (runOnItemsChange) {
132
- this.options.onItemsChange?.(this);
133
- }
134
- if (this.store.state.isRunning && !this.store.state.pendingTick) {
135
- this.#setState({ pendingTick: true });
136
- this.#tick();
137
- }
138
- return true;
139
- };
140
- this.getNextItem = (position = this.options.getItemsFrom ?? "front") => {
141
- const { items, itemTimestamps } = this.store.state;
142
- let item;
143
- if (this.options.getPriority !== defaultOptions.getPriority || position === "front") {
144
- item = items[0];
145
- if (item !== void 0) {
146
- this.#setState({
147
- items: items.slice(1),
148
- itemTimestamps: itemTimestamps.slice(1)
149
- });
150
- }
151
- } else {
152
- item = items[items.length - 1];
153
- if (item !== void 0) {
154
- this.#setState({
155
- items: items.slice(0, -1),
156
- itemTimestamps: itemTimestamps.slice(0, -1)
157
- });
158
- }
159
- }
160
- if (item !== void 0) {
161
- this.options.onItemsChange?.(this);
162
- }
163
- return item;
164
- };
165
- this.#getAllItems = () => {
166
- const items = this.peekAllItems();
167
- this.clear();
168
- return items;
169
- };
170
- this.execute = (position) => {
171
- const item = this.getNextItem(position);
172
- if (item !== void 0) {
173
- this.fn(item);
174
- this.#setState({
175
- executionCount: this.store.state.executionCount + 1
176
- });
177
- this.options.onExecute?.(item, this);
178
- }
179
- return item;
180
- };
181
- this.flush = (numberOfItems = this.store.state.items.length, position) => {
182
- this.#clearTimeout();
183
- for (let i = 0; i < numberOfItems; i++) {
184
- this.execute(position);
185
- }
186
- this.#tick();
187
- };
188
- this.flushAsBatch = (batchFunction) => {
189
- const items = this.#getAllItems();
190
- this.clear();
191
- batchFunction(items);
192
- };
193
- this.#checkExpiredItems = () => {
194
- if ((this.options.expirationDuration ?? Infinity) === Infinity && this.options.getIsExpired === defaultOptions.getIsExpired) {
195
- return;
196
- }
197
- const now = Date.now();
198
- const expiredIndices = [];
199
- for (let i = 0; i < this.store.state.items.length; i++) {
200
- const timestamp = this.store.state.itemTimestamps[i];
201
- if (timestamp === void 0) continue;
202
- const item = this.store.state.items[i];
203
- if (item === void 0) continue;
204
- const isExpired = this.options.getIsExpired !== defaultOptions.getIsExpired ? this.options.getIsExpired(item, timestamp) : now - timestamp > (this.options.expirationDuration ?? Infinity);
205
- if (isExpired) {
206
- expiredIndices.push(i);
207
- }
208
- }
209
- for (let i = expiredIndices.length - 1; i >= 0; i--) {
210
- const index = expiredIndices[i];
211
- if (index === void 0) continue;
212
- const expiredItem = this.store.state.items[index];
213
- if (expiredItem === void 0) continue;
214
- const newItems = [...this.store.state.items];
215
- const newTimestamps = [...this.store.state.itemTimestamps];
216
- newItems.splice(index, 1);
217
- newTimestamps.splice(index, 1);
218
- this.#setState({
219
- items: newItems,
220
- itemTimestamps: newTimestamps,
221
- expirationCount: this.store.state.expirationCount + 1
222
- });
223
- this.options.onExpire?.(expiredItem, this);
224
- }
225
- if (expiredIndices.length > 0) {
226
- this.options.onItemsChange?.(this);
227
- }
228
- };
229
- this.peekNextItem = (position = "front") => {
230
- if (position === "front") {
231
- return this.store.state.items[0];
232
- }
233
- return this.store.state.items[this.store.state.items.length - 1];
234
- };
235
- this.peekAllItems = () => {
236
- return [...this.store.state.items];
237
- };
238
- this.start = () => {
239
- this.#setState({ isRunning: true });
240
- if (!this.store.state.pendingTick && this.store.state.items.length > 0) {
241
- this.#tick();
242
- }
243
- };
244
- this.stop = () => {
245
- this.#clearTimeout();
246
- this.#setState({ isRunning: false, pendingTick: false });
247
- };
248
- this.#clearTimeout = () => {
249
- if (this.#timeoutId) {
250
- clearTimeout(this.#timeoutId);
251
- this.#timeoutId = null;
252
- }
253
- };
254
- this.clear = () => {
255
- this.#setState({ items: [], itemTimestamps: [] });
256
- this.options.onItemsChange?.(this);
257
- };
258
- this.reset = () => {
259
- this.#setState(getDefaultQueuerState());
260
- this.options.onItemsChange?.(this);
261
- };
262
- this.key = initialOptions.key;
263
- this.options = {
264
- ...defaultOptions,
265
- ...initialOptions
266
- };
267
- const isInitiallyRunning = this.options.initialState?.isRunning ?? this.options.started ?? true;
268
- this.#setState({
269
- ...this.options.initialState,
270
- isRunning: isInitiallyRunning
271
- });
272
- if (this.options.initialState?.items) {
273
- if (this.store.state.isRunning) {
274
- this.#tick();
275
- }
276
- } else {
277
- for (let i = 0; i < (this.options.initialItems?.length ?? 0); i++) {
278
- const item = this.options.initialItems[i];
279
- const isLast = i === (this.options.initialItems?.length ?? 0) - 1;
280
- this.addItem(item, this.options.addItemsTo ?? "back", isLast);
281
- }
282
- }
283
- if (this.key) {
284
- pacerEventClient.on("d-Queuer", (event) => {
285
- if (event.payload.key !== this.key) return;
286
- this.#setState(event.payload.store.state);
287
- this.setOptions(event.payload.options);
288
- });
289
- }
290
- }
291
- #timeoutId;
292
- #setState;
293
- #getWait;
294
- #tick;
295
- #getAllItems;
296
- #checkExpiredItems;
297
- #clearTimeout;
298
- }
299
- function queue(fn, initialOptions) {
300
- const queuer = new Queuer(fn, initialOptions);
301
- return queuer.addItem;
302
- }
303
- export {
304
- Queuer,
305
- queue,
306
- queuerOptions
307
- };
308
- //# sourceMappingURL=queuer.js.map