@tanstack/pacer-lite 0.2.1 → 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 (41) hide show
  1. package/README.md +29 -14
  2. package/dist/lite-batcher.d.ts +4 -6
  3. package/dist/lite-batcher.js +72 -45
  4. package/dist/lite-debouncer.d.ts +5 -9
  5. package/dist/lite-debouncer.js +58 -40
  6. package/dist/lite-queuer.d.ts +5 -7
  7. package/dist/lite-queuer.js +170 -89
  8. package/dist/lite-rate-limiter.d.ts +5 -9
  9. package/dist/lite-rate-limiter.js +89 -63
  10. package/dist/lite-throttler.d.ts +5 -9
  11. package/dist/lite-throttler.js +63 -40
  12. package/dist/pacer/dist/types.d.ts +7 -0
  13. package/package.json +13 -33
  14. package/dist/index.cjs +0 -16
  15. package/dist/index.d.cts +0 -6
  16. package/dist/lite-batcher.cjs +0 -175
  17. package/dist/lite-batcher.cjs.map +0 -1
  18. package/dist/lite-batcher.d.cts +0 -184
  19. package/dist/lite-batcher.js.map +0 -1
  20. package/dist/lite-debouncer.cjs +0 -125
  21. package/dist/lite-debouncer.cjs.map +0 -1
  22. package/dist/lite-debouncer.d.cts +0 -127
  23. package/dist/lite-debouncer.js.map +0 -1
  24. package/dist/lite-queuer.cjs +0 -208
  25. package/dist/lite-queuer.cjs.map +0 -1
  26. package/dist/lite-queuer.d.cts +0 -243
  27. package/dist/lite-queuer.js.map +0 -1
  28. package/dist/lite-rate-limiter.cjs +0 -149
  29. package/dist/lite-rate-limiter.cjs.map +0 -1
  30. package/dist/lite-rate-limiter.d.cts +0 -149
  31. package/dist/lite-rate-limiter.js.map +0 -1
  32. package/dist/lite-throttler.cjs +0 -127
  33. package/dist/lite-throttler.cjs.map +0 -1
  34. package/dist/lite-throttler.d.cts +0 -134
  35. package/dist/lite-throttler.js.map +0 -1
  36. package/src/index.ts +0 -5
  37. package/src/lite-batcher.ts +0 -267
  38. package/src/lite-debouncer.ts +0 -184
  39. package/src/lite-queuer.ts +0 -434
  40. package/src/lite-rate-limiter.ts +0 -246
  41. package/src/lite-throttler.ts +0 -195
@@ -1,127 +0,0 @@
1
- import { AnyFunction } from "@tanstack/pacer/types";
2
-
3
- //#region src/lite-debouncer.d.ts
4
-
5
- /**
6
- * Options for configuring a lite debounced function
7
- */
8
- interface LiteDebouncerOptions<TFn extends AnyFunction = AnyFunction> {
9
- /**
10
- * Whether to execute on the leading edge of the timeout.
11
- * The first call will execute immediately and the rest will wait the delay.
12
- * Defaults to false.
13
- */
14
- leading?: boolean;
15
- /**
16
- * Callback function that is called after the function is executed
17
- */
18
- onExecute?: (args: Parameters<TFn>, debouncer: LiteDebouncer<TFn>) => void;
19
- /**
20
- * Whether to execute on the trailing edge of the timeout.
21
- * Defaults to true.
22
- */
23
- trailing?: boolean;
24
- /**
25
- * Delay in milliseconds before executing the function.
26
- */
27
- wait: number;
28
- }
29
- /**
30
- * A lightweight class that creates a debounced function.
31
- *
32
- * This is an alternative to the Debouncer in the core @tanstack/pacer package, but is more
33
- * suitable for libraries and npm packages that need minimal overhead. Unlike the core Debouncer,
34
- * this version does not use TanStack Store for state management, has no devtools integration,
35
- * and provides only essential debouncing functionality.
36
- *
37
- * Debouncing ensures that a function is only executed after a certain amount of time has passed
38
- * since its last invocation. This is useful for handling frequent events like window resizing,
39
- * scroll events, or input changes where you want to limit the rate of execution.
40
- *
41
- * The debounced function can be configured to execute either at the start of the delay period
42
- * (leading edge) or at the end (trailing edge, default). Each new call during the wait period
43
- * will reset the timer.
44
- *
45
- * Features:
46
- * - Zero dependencies - no external libraries required
47
- * - Minimal API surface - only essential methods (maybeExecute, flush, cancel)
48
- * - Simple state management - uses basic private properties instead of reactive stores
49
- * - Callback support for monitoring execution events
50
- * - Lightweight - designed for use in npm packages where bundle size matters
51
- *
52
- * @example
53
- * ```ts
54
- * const debouncer = new LiteDebouncer((value: string) => {
55
- * saveToDatabase(value);
56
- * }, {
57
- * wait: 500,
58
- * onExecute: (args, debouncer) => {
59
- * console.log('Saved value:', args[0]);
60
- * }
61
- * });
62
- *
63
- * // Will only save after 500ms of no new input
64
- * inputElement.addEventListener('input', () => {
65
- * debouncer.maybeExecute(inputElement.value);
66
- * });
67
- * ```
68
- */
69
- declare class LiteDebouncer<TFn extends AnyFunction> {
70
- fn: TFn;
71
- options: LiteDebouncerOptions<TFn>;
72
- private timeoutId;
73
- private lastArgs;
74
- private canLeadingExecute;
75
- constructor(fn: TFn, options: LiteDebouncerOptions<TFn>);
76
- /**
77
- * Attempts to execute the debounced function.
78
- * If leading is true and this is the first call, executes immediately.
79
- * Otherwise, queues the execution for after the wait time.
80
- * Each new call resets the timer.
81
- */
82
- maybeExecute: (...args: Parameters<TFn>) => void;
83
- /**
84
- * Processes the current pending execution immediately.
85
- * If there's a pending execution, it will be executed right away
86
- * and the timeout will be cleared.
87
- */
88
- flush: () => void;
89
- /**
90
- * Cancels any pending execution.
91
- * Clears the timeout and resets the internal state.
92
- */
93
- cancel: () => void;
94
- }
95
- /**
96
- * Creates a lightweight debounced function that delays invoking the provided function until after a specified wait time.
97
- * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.
98
- *
99
- * This is an alternative to the debounce function in the core @tanstack/pacer package, but is more
100
- * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,
101
- * this function creates a debouncer with no external dependencies, devtools integration, or reactive state.
102
- *
103
- * If leading option is true, the function will execute immediately on the first call, then wait the delay
104
- * before allowing another execution.
105
- *
106
- * @example
107
- * ```ts
108
- * const debouncedSave = liteDebounce(() => {
109
- * saveChanges();
110
- * }, { wait: 1000 });
111
- *
112
- * // Called repeatedly but executes at most once per second
113
- * inputElement.addEventListener('input', debouncedSave);
114
- * ```
115
- *
116
- * @example
117
- * ```ts
118
- * // Leading edge execution - fires immediately then waits
119
- * const debouncedSearch = liteDebounce((query: string) => {
120
- * performSearch(query);
121
- * }, { wait: 300, leading: true });
122
- * ```
123
- */
124
- declare function liteDebounce<TFn extends AnyFunction>(fn: TFn, options: LiteDebouncerOptions<TFn>): (...args: Parameters<TFn>) => void;
125
- //#endregion
126
- export { LiteDebouncer, LiteDebouncerOptions, liteDebounce };
127
- //# sourceMappingURL=lite-debouncer.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"lite-debouncer.js","names":["fn: TFn","options: LiteDebouncerOptions<TFn>"],"sources":["../src/lite-debouncer.ts"],"sourcesContent":["import type { AnyFunction } from '@tanstack/pacer/types'\n\n/**\n * Options for configuring a lite debounced function\n */\nexport interface LiteDebouncerOptions<TFn extends AnyFunction = AnyFunction> {\n /**\n * Whether to execute on the leading edge of the timeout.\n * The first call will execute immediately and the rest will wait the delay.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, debouncer: LiteDebouncer<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds before executing the function.\n */\n wait: number\n}\n\n/**\n * A lightweight class that creates a debounced function.\n *\n * This is an alternative to the Debouncer in the core @tanstack/pacer package, but is more\n * suitable for libraries and npm packages that need minimal overhead. Unlike the core Debouncer,\n * this version does not use TanStack Store for state management, has no devtools integration,\n * and provides only essential debouncing functionality.\n *\n * Debouncing ensures that a function is only executed after a certain amount of time has passed\n * since its last invocation. This is useful for handling frequent events like window resizing,\n * scroll events, or input changes where you want to limit the rate of execution.\n *\n * The debounced function can be configured to execute either at the start of the delay period\n * (leading edge) or at the end (trailing edge, default). Each new call during the wait period\n * will reset the timer.\n *\n * Features:\n * - Zero dependencies - no external libraries required\n * - Minimal API surface - only essential methods (maybeExecute, flush, cancel)\n * - Simple state management - uses basic private properties instead of reactive stores\n * - Callback support for monitoring execution events\n * - Lightweight - designed for use in npm packages where bundle size matters\n *\n * @example\n * ```ts\n * const debouncer = new LiteDebouncer((value: string) => {\n * saveToDatabase(value);\n * }, {\n * wait: 500,\n * onExecute: (args, debouncer) => {\n * console.log('Saved value:', args[0]);\n * }\n * });\n *\n * // Will only save after 500ms of no new input\n * inputElement.addEventListener('input', () => {\n * debouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class LiteDebouncer<TFn extends AnyFunction> {\n private timeoutId: NodeJS.Timeout | undefined\n private lastArgs: Parameters<TFn> | undefined\n private canLeadingExecute = true\n\n constructor(\n public fn: TFn,\n public options: LiteDebouncerOptions<TFn>,\n ) {\n // Default trailing to true if neither leading nor trailing is specified\n if (\n this.options.leading === undefined &&\n this.options.trailing === undefined\n ) {\n this.options.trailing = true\n }\n }\n\n /**\n * Attempts to execute the debounced function.\n * If leading is true and this is the first call, executes immediately.\n * Otherwise, queues the execution for after the wait time.\n * Each new call resets the timer.\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n let didLeadingExecute = false\n\n if (this.options.leading && this.canLeadingExecute) {\n this.canLeadingExecute = false\n didLeadingExecute = true\n this.fn(...args)\n this.options.onExecute?.(args, this)\n }\n\n this.lastArgs = args\n\n if (this.timeoutId) {\n clearTimeout(this.timeoutId)\n }\n\n this.timeoutId = setTimeout(() => {\n this.canLeadingExecute = true\n if (this.options.trailing && !didLeadingExecute && this.lastArgs) {\n this.fn(...this.lastArgs)\n this.options.onExecute?.(this.lastArgs, this)\n }\n this.lastArgs = undefined\n }, this.options.wait)\n }\n\n /**\n * Processes the current pending execution immediately.\n * If there's a pending execution, it will be executed right away\n * and the timeout will be cleared.\n */\n flush = (): void => {\n if (this.timeoutId && this.lastArgs) {\n clearTimeout(this.timeoutId)\n this.timeoutId = undefined\n const args = this.lastArgs\n this.fn(...args)\n this.options.onExecute?.(args, this)\n this.lastArgs = undefined\n this.canLeadingExecute = true\n }\n }\n\n /**\n * Cancels any pending execution.\n * Clears the timeout and resets the internal state.\n */\n cancel = (): void => {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId)\n this.timeoutId = undefined\n }\n this.lastArgs = undefined\n this.canLeadingExecute = true\n }\n}\n\n/**\n * Creates a lightweight debounced function that delays invoking the provided function until after a specified wait time.\n * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.\n *\n * This is an alternative to the debounce function in the core @tanstack/pacer package, but is more\n * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,\n * this function creates a debouncer with no external dependencies, devtools integration, or reactive state.\n *\n * If leading option is true, the function will execute immediately on the first call, then wait the delay\n * before allowing another execution.\n *\n * @example\n * ```ts\n * const debouncedSave = liteDebounce(() => {\n * saveChanges();\n * }, { wait: 1000 });\n *\n * // Called repeatedly but executes at most once per second\n * inputElement.addEventListener('input', debouncedSave);\n * ```\n *\n * @example\n * ```ts\n * // Leading edge execution - fires immediately then waits\n * const debouncedSearch = liteDebounce((query: string) => {\n * performSearch(query);\n * }, { wait: 300, leading: true });\n * ```\n */\nexport function liteDebounce<TFn extends AnyFunction>(\n fn: TFn,\n options: LiteDebouncerOptions<TFn>,\n): (...args: Parameters<TFn>) => void {\n const debouncer = new LiteDebouncer(fn, options)\n return debouncer.maybeExecute\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,IAAa,gBAAb,MAAoD;CAKlD,YACE,AAAOA,IACP,AAAOC,SACP;EAFO;EACA;2BAJmB;uBAqBZ,GAAG,SAAgC;GACjD,IAAI,oBAAoB;AAExB,OAAI,KAAK,QAAQ,WAAW,KAAK,mBAAmB;AAClD,SAAK,oBAAoB;AACzB,wBAAoB;AACpB,SAAK,GAAG,GAAG,KAAK;AAChB,SAAK,QAAQ,YAAY,MAAM,KAAK;;AAGtC,QAAK,WAAW;AAEhB,OAAI,KAAK,UACP,cAAa,KAAK,UAAU;AAG9B,QAAK,YAAY,iBAAiB;AAChC,SAAK,oBAAoB;AACzB,QAAI,KAAK,QAAQ,YAAY,CAAC,qBAAqB,KAAK,UAAU;AAChE,UAAK,GAAG,GAAG,KAAK,SAAS;AACzB,UAAK,QAAQ,YAAY,KAAK,UAAU,KAAK;;AAE/C,SAAK,WAAW;MACf,KAAK,QAAQ,KAAK;;qBAQH;AAClB,OAAI,KAAK,aAAa,KAAK,UAAU;AACnC,iBAAa,KAAK,UAAU;AAC5B,SAAK,YAAY;IACjB,MAAM,OAAO,KAAK;AAClB,SAAK,GAAG,GAAG,KAAK;AAChB,SAAK,QAAQ,YAAY,MAAM,KAAK;AACpC,SAAK,WAAW;AAChB,SAAK,oBAAoB;;;sBAQR;AACnB,OAAI,KAAK,WAAW;AAClB,iBAAa,KAAK,UAAU;AAC5B,SAAK,YAAY;;AAEnB,QAAK,WAAW;AAChB,QAAK,oBAAoB;;AAnEzB,MACE,KAAK,QAAQ,YAAY,UACzB,KAAK,QAAQ,aAAa,OAE1B,MAAK,QAAQ,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgG9B,SAAgB,aACd,IACA,SACoC;AAEpC,QADkB,IAAI,cAAc,IAAI,QAAQ,CAC/B"}
@@ -1,208 +0,0 @@
1
-
2
- //#region src/lite-queuer.ts
3
- /**
4
- * A lightweight class that creates a queue for processing items.
5
- *
6
- * This is an alternative to the Queuer in the core @tanstack/pacer package, but is more
7
- * suitable for libraries and npm packages that need minimal overhead. Unlike the core Queuer,
8
- * this version does not use TanStack Store for state management, has no devtools integration,
9
- * no callbacks, and provides only essential queueing functionality.
10
- *
11
- * The queuer supports FIFO (First In First Out), LIFO (Last In First Out), and priority-based
12
- * processing of items. Items can be processed automatically with configurable wait times
13
- * between executions, or processed manually using the execute methods.
14
- *
15
- * Features included:
16
- * - Automatic or manual processing of items
17
- * - FIFO, LIFO, and priority-based ordering
18
- * - Queue size limits with item rejection
19
- * - Configurable wait times between processing
20
- * - Batch processing capabilities
21
- * - Start/stop processing control
22
- * - Callback support for monitoring execution, rejection, and state change events
23
- *
24
- * Features NOT included (compared to core Queuer):
25
- * - No TanStack Store state management
26
- * - No devtools integration
27
- * - No item expiration functionality (no onExpire callback)
28
- * - No dynamic options updates (setOptions)
29
- * - No detailed state tracking (execution counts, etc.)
30
- *
31
- * Queue behavior:
32
- * - Default: FIFO (add to back, process from front)
33
- * - LIFO: Configure addItemsTo: 'back', getItemsFrom: 'back'
34
- * - Priority: Provide getPriority function; higher values processed first
35
- *
36
- * @example
37
- * ```ts
38
- * // Basic FIFO queue
39
- * const queue = new LiteQueuer((item: string) => {
40
- * console.log('Processing:', item);
41
- * }, { wait: 100 });
42
- *
43
- * queue.addItem('task1');
44
- * queue.addItem('task2');
45
- * // Processes: task1, then task2 after 100ms delay
46
- * ```
47
- *
48
- * @example
49
- * ```ts
50
- * // Priority queue
51
- * const priorityQueue = new LiteQueuer((item: Task) => {
52
- * processTask(item);
53
- * }, {
54
- * getPriority: task => task.priority,
55
- * wait: 500
56
- * });
57
- *
58
- * priorityQueue.addItem({ name: 'low', priority: 1 });
59
- * priorityQueue.addItem({ name: 'high', priority: 10 });
60
- * // Processes high priority task first
61
- * ```
62
- */
63
- var LiteQueuer = class {
64
- constructor(fn, options = {}) {
65
- this.fn = fn;
66
- this.options = options;
67
- this.items = [];
68
- this.timeoutId = null;
69
- this.isRunning = true;
70
- this.pendingTick = false;
71
- this.addItem = (item, position = this.options.addItemsTo, startProcessing = true) => {
72
- if (this.items.length >= this.options.maxSize) return false;
73
- if (this.options.getPriority) {
74
- const priority = this.options.getPriority(item);
75
- if (priority !== void 0) {
76
- const insertIndex = this.items.findIndex((existing) => {
77
- return (this.options.getPriority(existing) ?? -Infinity) < priority;
78
- });
79
- if (insertIndex === -1) this.items.push(item);
80
- else this.items.splice(insertIndex, 0, item);
81
- } else this.insertAtPosition(item, position);
82
- } else this.insertAtPosition(item, position);
83
- if (startProcessing && this.isRunning && !this.pendingTick) this.tick();
84
- return true;
85
- };
86
- this.insertAtPosition = (item, position) => {
87
- if (position === "front") this.items.unshift(item);
88
- else this.items.push(item);
89
- };
90
- this.getNextItem = (position = this.options.getItemsFrom) => {
91
- if (this.items.length === 0) return;
92
- let item;
93
- if (this.options.getPriority || position === "front") item = this.items.shift();
94
- else item = this.items.pop();
95
- return item;
96
- };
97
- this.execute = (position) => {
98
- const item = this.getNextItem(position);
99
- if (item !== void 0) this.fn(item);
100
- return item;
101
- };
102
- this.tick = () => {
103
- if (!this.isRunning) {
104
- this.pendingTick = false;
105
- return;
106
- }
107
- this.pendingTick = true;
108
- while (this.items.length > 0) {
109
- if (this.execute(this.options.getItemsFrom) === void 0) break;
110
- const wait = this.options.wait;
111
- if (wait > 0) {
112
- this.timeoutId = setTimeout(() => this.tick(), wait);
113
- return;
114
- }
115
- }
116
- this.pendingTick = false;
117
- };
118
- this.start = () => {
119
- this.isRunning = true;
120
- if (!this.pendingTick && this.items.length > 0) this.tick();
121
- };
122
- this.stop = () => {
123
- this.clearTimeout();
124
- this.isRunning = false;
125
- this.pendingTick = false;
126
- };
127
- this.clearTimeout = () => {
128
- if (this.timeoutId) {
129
- clearTimeout(this.timeoutId);
130
- this.timeoutId = null;
131
- }
132
- };
133
- this.peekNextItem = (position = "front") => {
134
- if (this.items.length === 0) return;
135
- if (this.options.getPriority || position === "front") return this.items[0];
136
- else return this.items[this.items.length - 1];
137
- };
138
- this.peekAllItems = () => {
139
- return [...this.items];
140
- };
141
- this.flush = (numberOfItems = this.items.length, position) => {
142
- this.clearTimeout();
143
- for (let i = 0; i < numberOfItems && this.items.length > 0; i++) this.execute(position);
144
- if (this.isRunning && this.items.length > 0 && !this.pendingTick) this.tick();
145
- };
146
- this.flushAsBatch = (batchFunction) => {
147
- const items = this.peekAllItems();
148
- this.clear();
149
- batchFunction(items);
150
- };
151
- this.clear = () => {
152
- this.items = [];
153
- };
154
- this.options.addItemsTo = this.options.addItemsTo ?? "back";
155
- this.options.getItemsFrom = this.options.getItemsFrom ?? "front";
156
- this.options.maxSize = this.options.maxSize ?? Infinity;
157
- this.options.started = this.options.started ?? true;
158
- this.options.wait = this.options.wait ?? 0;
159
- this.isRunning = this.options.started;
160
- if (this.options.initialItems) for (const item of this.options.initialItems) this.addItem(item, this.options.addItemsTo, false);
161
- if (this.isRunning && this.items.length > 0) this.tick();
162
- }
163
- /**
164
- * Number of items currently in the queue
165
- */
166
- get size() {
167
- return this.items.length;
168
- }
169
- /**
170
- * Whether the queue is empty
171
- */
172
- get isEmpty() {
173
- return this.items.length === 0;
174
- }
175
- /**
176
- * Whether the queue is currently running (auto-processing items)
177
- */
178
- get isQueueRunning() {
179
- return this.isRunning;
180
- }
181
- };
182
- /**
183
- * Creates a lightweight queue that processes items using the provided function.
184
- *
185
- * This is an alternative to the queue function in the core @tanstack/pacer package, but is more
186
- * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,
187
- * this function creates a queuer with no external dependencies, devtools integration, or reactive state.
188
- *
189
- * @example
190
- * ```ts
191
- * const processItem = liteQueue((item: string) => {
192
- * console.log('Processing:', item);
193
- * }, { wait: 1000 });
194
- *
195
- * processItem('task1');
196
- * processItem('task2');
197
- * // Processes each item with 1 second delay between them
198
- * ```
199
- */
200
- function liteQueue(fn, options = {}) {
201
- const queuer = new LiteQueuer(fn, options);
202
- return (item) => queuer.addItem(item);
203
- }
204
-
205
- //#endregion
206
- exports.LiteQueuer = LiteQueuer;
207
- exports.liteQueue = liteQueue;
208
- //# sourceMappingURL=lite-queuer.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"lite-queuer.cjs","names":["fn: (item: TValue) => void","options: LiteQueuerOptions<TValue>","item: TValue | undefined"],"sources":["../src/lite-queuer.ts"],"sourcesContent":["/**\n * Position type for addItem and getNextItem operations.\n *\n * - 'front': Operate on the front of the queue (FIFO for getNextItem)\n * - 'back': Operate on the back of the queue (LIFO for getNextItem)\n */\nexport type QueuePosition = 'front' | 'back'\n\n/**\n * Options for configuring a lite queuer instance\n */\nexport interface LiteQueuerOptions<TValue> {\n /**\n * Default position to add items to the queue\n * @default 'back'\n */\n addItemsTo?: QueuePosition\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 queue\n * Higher priority items will be processed first\n * Return undefined for items that should use positional ordering\n */\n getPriority?: (item: TValue) => number | undefined\n /**\n * Initial items to populate the queue with\n */\n initialItems?: Array<TValue>\n /**\n * Maximum number of items allowed in the queue\n */\n maxSize?: number\n /**\n * Whether the queuer should start processing items immediately\n * @default true\n */\n started?: boolean\n /**\n * Time in milliseconds to wait between processing items\n * @default 0\n */\n wait?: number\n}\n\n/**\n * A lightweight class that creates a queue for processing items.\n *\n * This is an alternative to the Queuer in the core @tanstack/pacer package, but is more\n * suitable for libraries and npm packages that need minimal overhead. Unlike the core Queuer,\n * this version does not use TanStack Store for state management, has no devtools integration,\n * no callbacks, and provides only essential queueing functionality.\n *\n * The queuer supports FIFO (First In First Out), LIFO (Last In First Out), and priority-based\n * processing of items. Items can be processed automatically with configurable wait times\n * between executions, or processed manually using the execute methods.\n *\n * Features included:\n * - Automatic or manual processing of items\n * - FIFO, LIFO, and priority-based ordering\n * - Queue size limits with item rejection\n * - Configurable wait times between processing\n * - Batch processing capabilities\n * - Start/stop processing control\n * - Callback support for monitoring execution, rejection, and state change events\n *\n * Features NOT included (compared to core Queuer):\n * - No TanStack Store state management\n * - No devtools integration\n * - No item expiration functionality (no onExpire callback)\n * - No dynamic options updates (setOptions)\n * - No detailed state tracking (execution counts, etc.)\n *\n * Queue behavior:\n * - Default: FIFO (add to back, process from front)\n * - LIFO: Configure addItemsTo: 'back', getItemsFrom: 'back'\n * - Priority: Provide getPriority function; higher values processed first\n *\n * @example\n * ```ts\n * // Basic FIFO queue\n * const queue = new LiteQueuer((item: string) => {\n * console.log('Processing:', item);\n * }, { wait: 100 });\n *\n * queue.addItem('task1');\n * queue.addItem('task2');\n * // Processes: task1, then task2 after 100ms delay\n * ```\n *\n * @example\n * ```ts\n * // Priority queue\n * const priorityQueue = new LiteQueuer((item: Task) => {\n * processTask(item);\n * }, {\n * getPriority: task => task.priority,\n * wait: 500\n * });\n *\n * priorityQueue.addItem({ name: 'low', priority: 1 });\n * priorityQueue.addItem({ name: 'high', priority: 10 });\n * // Processes high priority task first\n * ```\n */\nexport class LiteQueuer<TValue> {\n private items: Array<TValue> = []\n private timeoutId: NodeJS.Timeout | null = null\n private isRunning = true\n private pendingTick = false\n\n constructor(\n public fn: (item: TValue) => void,\n public options: LiteQueuerOptions<TValue> = {},\n ) {\n // Set defaults\n this.options.addItemsTo = this.options.addItemsTo ?? 'back'\n this.options.getItemsFrom = this.options.getItemsFrom ?? 'front'\n this.options.maxSize = this.options.maxSize ?? Infinity\n this.options.started = this.options.started ?? true\n this.options.wait = this.options.wait ?? 0\n\n this.isRunning = this.options.started\n\n // Add initial items if provided\n if (this.options.initialItems) {\n for (const item of this.options.initialItems) {\n this.addItem(item, this.options.addItemsTo, false)\n }\n }\n\n // Start processing if enabled and has items\n if (this.isRunning && this.items.length > 0) {\n this.tick()\n }\n }\n\n /**\n * Number of items currently in the queue\n */\n get size(): number {\n return this.items.length\n }\n\n /**\n * Whether the queue is empty\n */\n get isEmpty(): boolean {\n return this.items.length === 0\n }\n\n /**\n * Whether the queue is currently running (auto-processing items)\n */\n get isQueueRunning(): boolean {\n return this.isRunning\n }\n\n /**\n * Adds an item to the queue. If the queue is full, the item is rejected.\n * Items can be inserted at the front or back, and priority ordering is applied if getPriority is configured.\n *\n * Returns true if the item was added, false if the queue is full.\n *\n * @example\n * ```ts\n * queue.addItem('task1'); // Add to default position (back)\n * queue.addItem('task2', 'front'); // Add to front\n * ```\n */\n addItem = (\n item: TValue,\n position: QueuePosition = this.options.addItemsTo!,\n startProcessing: boolean = true,\n ): boolean => {\n // Check size limit\n if (this.items.length >= this.options.maxSize!) {\n return false\n }\n\n // Handle priority insertion\n if (this.options.getPriority) {\n const priority = this.options.getPriority(item)\n if (priority !== undefined) {\n // Find insertion point for priority\n const insertIndex = this.items.findIndex((existing) => {\n const existingPriority = this.options.getPriority!(existing)\n // Treat undefined priority as negative infinity for comparison\n const effectivePriority = existingPriority ?? -Infinity\n return effectivePriority < priority\n })\n\n if (insertIndex === -1) {\n this.items.push(item)\n } else {\n this.items.splice(insertIndex, 0, item)\n }\n } else {\n // No priority, use position\n this.insertAtPosition(item, position)\n }\n } else {\n // No priority function, use position\n this.insertAtPosition(item, position)\n }\n\n // Start processing if running and not already processing\n if (startProcessing && this.isRunning && !this.pendingTick) {\n this.tick()\n }\n\n return true\n }\n\n private insertAtPosition = (item: TValue, position: QueuePosition): void => {\n if (position === 'front') {\n this.items.unshift(item)\n } else {\n this.items.push(item)\n }\n }\n\n /**\n * Removes and returns the next item from the queue without executing the function.\n * Use for manual queue management. Normally, use execute() to process items.\n *\n * @example\n * ```ts\n * const nextItem = queue.getNextItem(); // Get from default position (front)\n * const lastItem = queue.getNextItem('back'); // Get from back (LIFO)\n * ```\n */\n getNextItem = (\n position: QueuePosition = this.options.getItemsFrom!,\n ): TValue | undefined => {\n if (this.items.length === 0) {\n return undefined\n }\n\n let item: TValue | undefined\n\n // When priority function is provided, always get from front (highest priority)\n if (this.options.getPriority || position === 'front') {\n item = this.items.shift()\n } else {\n item = this.items.pop()\n }\n\n return item\n }\n\n /**\n * Removes and returns the next item from the queue and processes it using the provided function.\n *\n * @example\n * ```ts\n * queue.execute(); // Execute from default position\n * queue.execute('back'); // Execute from back (LIFO)\n * ```\n */\n execute = (position?: QueuePosition): TValue | undefined => {\n const item = this.getNextItem(position)\n if (item !== undefined) {\n this.fn(item)\n }\n return item\n }\n\n /**\n * Internal method that processes items in the queue with wait intervals\n */\n private tick = (): void => {\n if (!this.isRunning) {\n this.pendingTick = false\n return\n }\n\n this.pendingTick = true\n\n // Process items while queue is not empty\n while (this.items.length > 0) {\n const item = this.execute(this.options.getItemsFrom)\n if (item === undefined) {\n break\n }\n\n const wait = this.options.wait!\n if (wait > 0) {\n // Schedule next processing after wait time\n this.timeoutId = setTimeout(() => this.tick(), wait)\n return\n }\n\n // No wait time, continue processing immediately\n }\n\n this.pendingTick = false\n }\n\n /**\n * Starts processing items in the queue. If already running, does nothing.\n */\n start = (): void => {\n this.isRunning = true\n if (!this.pendingTick && this.items.length > 0) {\n this.tick()\n }\n }\n\n /**\n * Stops processing items in the queue. Does not clear the queue.\n */\n stop = (): void => {\n this.clearTimeout()\n this.isRunning = false\n this.pendingTick = false\n }\n\n /**\n * Clears any pending timeout\n */\n private clearTimeout = (): void => {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId)\n this.timeoutId = null\n }\n }\n\n /**\n * Returns the next item in the queue without removing it.\n *\n * @example\n * ```ts\n * const next = queue.peekNextItem(); // Peek at front\n * const last = queue.peekNextItem('back'); // Peek at back\n * ```\n */\n peekNextItem = (position: QueuePosition = 'front'): TValue | undefined => {\n if (this.items.length === 0) {\n return undefined\n }\n\n if (this.options.getPriority || position === 'front') {\n return this.items[0]\n } else {\n return this.items[this.items.length - 1]\n }\n }\n\n /**\n * Returns a copy of all items in the queue.\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.items]\n }\n\n /**\n * Processes a specified number of items immediately with no wait time.\n * If no numberOfItems is provided, all items will be processed.\n *\n * @example\n * ```ts\n * queue.flush(); // Process all items immediately\n * queue.flush(3); // Process next 3 items immediately\n * ```\n */\n flush = (\n numberOfItems: number = this.items.length,\n position?: QueuePosition,\n ): void => {\n this.clearTimeout() // Clear any pending timeout\n for (let i = 0; i < numberOfItems && this.items.length > 0; i++) {\n this.execute(position)\n }\n // Restart normal processing if still running and has items\n if (this.isRunning && this.items.length > 0 && !this.pendingTick) {\n this.tick()\n }\n }\n\n /**\n * Processes all items in the queue as a batch using the provided function.\n * The queue is cleared after processing.\n *\n * @example\n * ```ts\n * queue.flushAsBatch((items) => {\n * console.log('Processing batch:', items);\n * // Process all items together\n * });\n * ```\n */\n flushAsBatch = (batchFunction: (items: Array<TValue>) => void): void => {\n const items = this.peekAllItems()\n this.clear()\n batchFunction(items)\n }\n\n /**\n * Removes all items from the queue. Does not affect items being processed.\n */\n clear = (): void => {\n this.items = []\n }\n}\n\n/**\n * Creates a lightweight queue that processes items using the provided function.\n *\n * This is an alternative to the queue function in the core @tanstack/pacer package, but is more\n * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,\n * this function creates a queuer with no external dependencies, devtools integration, or reactive state.\n *\n * @example\n * ```ts\n * const processItem = liteQueue((item: string) => {\n * console.log('Processing:', item);\n * }, { wait: 1000 });\n *\n * processItem('task1');\n * processItem('task2');\n * // Processes each item with 1 second delay between them\n * ```\n */\nexport function liteQueue<TValue>(\n fn: (item: TValue) => void,\n options: LiteQueuerOptions<TValue> = {},\n): (item: TValue) => boolean {\n const queuer = new LiteQueuer(fn, options)\n return (item: TValue) => queuer.addItem(item)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,IAAa,aAAb,MAAgC;CAM9B,YACE,AAAOA,IACP,AAAOC,UAAqC,EAAE,EAC9C;EAFO;EACA;eAPsB,EAAE;mBACU;mBACvB;qBACE;kBA8DpB,MACA,WAA0B,KAAK,QAAQ,YACvC,kBAA2B,SACf;AAEZ,OAAI,KAAK,MAAM,UAAU,KAAK,QAAQ,QACpC,QAAO;AAIT,OAAI,KAAK,QAAQ,aAAa;IAC5B,MAAM,WAAW,KAAK,QAAQ,YAAY,KAAK;AAC/C,QAAI,aAAa,QAAW;KAE1B,MAAM,cAAc,KAAK,MAAM,WAAW,aAAa;AAIrD,cAHyB,KAAK,QAAQ,YAAa,SAAS,IAEd,aACnB;OAC3B;AAEF,SAAI,gBAAgB,GAClB,MAAK,MAAM,KAAK,KAAK;SAErB,MAAK,MAAM,OAAO,aAAa,GAAG,KAAK;UAIzC,MAAK,iBAAiB,MAAM,SAAS;SAIvC,MAAK,iBAAiB,MAAM,SAAS;AAIvC,OAAI,mBAAmB,KAAK,aAAa,CAAC,KAAK,YAC7C,MAAK,MAAM;AAGb,UAAO;;2BAGmB,MAAc,aAAkC;AAC1E,OAAI,aAAa,QACf,MAAK,MAAM,QAAQ,KAAK;OAExB,MAAK,MAAM,KAAK,KAAK;;sBAevB,WAA0B,KAAK,QAAQ,iBAChB;AACvB,OAAI,KAAK,MAAM,WAAW,EACxB;GAGF,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E,MAAM,QAAQ,KAAK,cAAc;AACjC,QAAK,OAAO;AACZ,iBAAc,MAAM;;qBAMF;AAClB,QAAK,QAAQ,EAAE;;AA9Rf,OAAK,QAAQ,aAAa,KAAK,QAAQ,cAAc;AACrD,OAAK,QAAQ,eAAe,KAAK,QAAQ,gBAAgB;AACzD,OAAK,QAAQ,UAAU,KAAK,QAAQ,WAAW;AAC/C,OAAK,QAAQ,UAAU,KAAK,QAAQ,WAAW;AAC/C,OAAK,QAAQ,OAAO,KAAK,QAAQ,QAAQ;AAEzC,OAAK,YAAY,KAAK,QAAQ;AAG9B,MAAI,KAAK,QAAQ,aACf,MAAK,MAAM,QAAQ,KAAK,QAAQ,aAC9B,MAAK,QAAQ,MAAM,KAAK,QAAQ,YAAY,MAAM;AAKtD,MAAI,KAAK,aAAa,KAAK,MAAM,SAAS,EACxC,MAAK,MAAM;;;;;CAOf,IAAI,OAAe;AACjB,SAAO,KAAK,MAAM;;;;;CAMpB,IAAI,UAAmB;AACrB,SAAO,KAAK,MAAM,WAAW;;;;;CAM/B,IAAI,iBAA0B;AAC5B,SAAO,KAAK;;;;;;;;;;;;;;;;;;;;;AA6QhB,SAAgB,UACd,IACA,UAAqC,EAAE,EACZ;CAC3B,MAAM,SAAS,IAAI,WAAW,IAAI,QAAQ;AAC1C,SAAQ,SAAiB,OAAO,QAAQ,KAAK"}
@@ -1,243 +0,0 @@
1
- //#region src/lite-queuer.d.ts
2
- /**
3
- * Position type for addItem and getNextItem operations.
4
- *
5
- * - 'front': Operate on the front of the queue (FIFO for getNextItem)
6
- * - 'back': Operate on the back of the queue (LIFO for getNextItem)
7
- */
8
- type QueuePosition = 'front' | 'back';
9
- /**
10
- * Options for configuring a lite queuer instance
11
- */
12
- interface LiteQueuerOptions<TValue> {
13
- /**
14
- * Default position to add items to the queue
15
- * @default 'back'
16
- */
17
- addItemsTo?: QueuePosition;
18
- /**
19
- * Default position to get items from during processing
20
- * @default 'front'
21
- */
22
- getItemsFrom?: QueuePosition;
23
- /**
24
- * Function to determine priority of items in the queue
25
- * Higher priority items will be processed first
26
- * Return undefined for items that should use positional ordering
27
- */
28
- getPriority?: (item: TValue) => number | undefined;
29
- /**
30
- * Initial items to populate the queue with
31
- */
32
- initialItems?: Array<TValue>;
33
- /**
34
- * Maximum number of items allowed in the queue
35
- */
36
- maxSize?: number;
37
- /**
38
- * Whether the queuer should start processing items immediately
39
- * @default true
40
- */
41
- started?: boolean;
42
- /**
43
- * Time in milliseconds to wait between processing items
44
- * @default 0
45
- */
46
- wait?: number;
47
- }
48
- /**
49
- * A lightweight class that creates a queue for processing items.
50
- *
51
- * This is an alternative to the Queuer in the core @tanstack/pacer package, but is more
52
- * suitable for libraries and npm packages that need minimal overhead. Unlike the core Queuer,
53
- * this version does not use TanStack Store for state management, has no devtools integration,
54
- * no callbacks, and provides only essential queueing functionality.
55
- *
56
- * The queuer supports FIFO (First In First Out), LIFO (Last In First Out), and priority-based
57
- * processing of items. Items can be processed automatically with configurable wait times
58
- * between executions, or processed manually using the execute methods.
59
- *
60
- * Features included:
61
- * - Automatic or manual processing of items
62
- * - FIFO, LIFO, and priority-based ordering
63
- * - Queue size limits with item rejection
64
- * - Configurable wait times between processing
65
- * - Batch processing capabilities
66
- * - Start/stop processing control
67
- * - Callback support for monitoring execution, rejection, and state change events
68
- *
69
- * Features NOT included (compared to core Queuer):
70
- * - No TanStack Store state management
71
- * - No devtools integration
72
- * - No item expiration functionality (no onExpire callback)
73
- * - No dynamic options updates (setOptions)
74
- * - No detailed state tracking (execution counts, etc.)
75
- *
76
- * Queue behavior:
77
- * - Default: FIFO (add to back, process from front)
78
- * - LIFO: Configure addItemsTo: 'back', getItemsFrom: 'back'
79
- * - Priority: Provide getPriority function; higher values processed first
80
- *
81
- * @example
82
- * ```ts
83
- * // Basic FIFO queue
84
- * const queue = new LiteQueuer((item: string) => {
85
- * console.log('Processing:', item);
86
- * }, { wait: 100 });
87
- *
88
- * queue.addItem('task1');
89
- * queue.addItem('task2');
90
- * // Processes: task1, then task2 after 100ms delay
91
- * ```
92
- *
93
- * @example
94
- * ```ts
95
- * // Priority queue
96
- * const priorityQueue = new LiteQueuer((item: Task) => {
97
- * processTask(item);
98
- * }, {
99
- * getPriority: task => task.priority,
100
- * wait: 500
101
- * });
102
- *
103
- * priorityQueue.addItem({ name: 'low', priority: 1 });
104
- * priorityQueue.addItem({ name: 'high', priority: 10 });
105
- * // Processes high priority task first
106
- * ```
107
- */
108
- declare class LiteQueuer<TValue> {
109
- fn: (item: TValue) => void;
110
- options: LiteQueuerOptions<TValue>;
111
- private items;
112
- private timeoutId;
113
- private isRunning;
114
- private pendingTick;
115
- constructor(fn: (item: TValue) => void, options?: LiteQueuerOptions<TValue>);
116
- /**
117
- * Number of items currently in the queue
118
- */
119
- get size(): number;
120
- /**
121
- * Whether the queue is empty
122
- */
123
- get isEmpty(): boolean;
124
- /**
125
- * Whether the queue is currently running (auto-processing items)
126
- */
127
- get isQueueRunning(): boolean;
128
- /**
129
- * Adds an item to the queue. If the queue is full, the item is rejected.
130
- * Items can be inserted at the front or back, and priority ordering is applied if getPriority is configured.
131
- *
132
- * Returns true if the item was added, false if the queue is full.
133
- *
134
- * @example
135
- * ```ts
136
- * queue.addItem('task1'); // Add to default position (back)
137
- * queue.addItem('task2', 'front'); // Add to front
138
- * ```
139
- */
140
- addItem: (item: TValue, position?: QueuePosition, startProcessing?: boolean) => boolean;
141
- private insertAtPosition;
142
- /**
143
- * Removes and returns the next item from the queue without executing the function.
144
- * Use for manual queue management. Normally, use execute() to process items.
145
- *
146
- * @example
147
- * ```ts
148
- * const nextItem = queue.getNextItem(); // Get from default position (front)
149
- * const lastItem = queue.getNextItem('back'); // Get from back (LIFO)
150
- * ```
151
- */
152
- getNextItem: (position?: QueuePosition) => TValue | undefined;
153
- /**
154
- * Removes and returns the next item from the queue and processes it using the provided function.
155
- *
156
- * @example
157
- * ```ts
158
- * queue.execute(); // Execute from default position
159
- * queue.execute('back'); // Execute from back (LIFO)
160
- * ```
161
- */
162
- execute: (position?: QueuePosition) => TValue | undefined;
163
- /**
164
- * Internal method that processes items in the queue with wait intervals
165
- */
166
- private tick;
167
- /**
168
- * Starts processing items in the queue. If already running, does nothing.
169
- */
170
- start: () => void;
171
- /**
172
- * Stops processing items in the queue. Does not clear the queue.
173
- */
174
- stop: () => void;
175
- /**
176
- * Clears any pending timeout
177
- */
178
- private clearTimeout;
179
- /**
180
- * Returns the next item in the queue without removing it.
181
- *
182
- * @example
183
- * ```ts
184
- * const next = queue.peekNextItem(); // Peek at front
185
- * const last = queue.peekNextItem('back'); // Peek at back
186
- * ```
187
- */
188
- peekNextItem: (position?: QueuePosition) => TValue | undefined;
189
- /**
190
- * Returns a copy of all items in the queue.
191
- */
192
- peekAllItems: () => Array<TValue>;
193
- /**
194
- * Processes a specified number of items immediately with no wait time.
195
- * If no numberOfItems is provided, all items will be processed.
196
- *
197
- * @example
198
- * ```ts
199
- * queue.flush(); // Process all items immediately
200
- * queue.flush(3); // Process next 3 items immediately
201
- * ```
202
- */
203
- flush: (numberOfItems?: number, position?: QueuePosition) => void;
204
- /**
205
- * Processes all items in the queue as a batch using the provided function.
206
- * The queue is cleared after processing.
207
- *
208
- * @example
209
- * ```ts
210
- * queue.flushAsBatch((items) => {
211
- * console.log('Processing batch:', items);
212
- * // Process all items together
213
- * });
214
- * ```
215
- */
216
- flushAsBatch: (batchFunction: (items: Array<TValue>) => void) => void;
217
- /**
218
- * Removes all items from the queue. Does not affect items being processed.
219
- */
220
- clear: () => void;
221
- }
222
- /**
223
- * Creates a lightweight queue that processes items using the provided function.
224
- *
225
- * This is an alternative to the queue function in the core @tanstack/pacer package, but is more
226
- * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,
227
- * this function creates a queuer with no external dependencies, devtools integration, or reactive state.
228
- *
229
- * @example
230
- * ```ts
231
- * const processItem = liteQueue((item: string) => {
232
- * console.log('Processing:', item);
233
- * }, { wait: 1000 });
234
- *
235
- * processItem('task1');
236
- * processItem('task2');
237
- * // Processes each item with 1 second delay between them
238
- * ```
239
- */
240
- declare function liteQueue<TValue>(fn: (item: TValue) => void, options?: LiteQueuerOptions<TValue>): (item: TValue) => boolean;
241
- //#endregion
242
- export { LiteQueuer, LiteQueuerOptions, QueuePosition, liteQueue };
243
- //# sourceMappingURL=lite-queuer.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"lite-queuer.js","names":["fn: (item: TValue) => void","options: LiteQueuerOptions<TValue>","item: TValue | undefined"],"sources":["../src/lite-queuer.ts"],"sourcesContent":["/**\n * Position type for addItem and getNextItem operations.\n *\n * - 'front': Operate on the front of the queue (FIFO for getNextItem)\n * - 'back': Operate on the back of the queue (LIFO for getNextItem)\n */\nexport type QueuePosition = 'front' | 'back'\n\n/**\n * Options for configuring a lite queuer instance\n */\nexport interface LiteQueuerOptions<TValue> {\n /**\n * Default position to add items to the queue\n * @default 'back'\n */\n addItemsTo?: QueuePosition\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 queue\n * Higher priority items will be processed first\n * Return undefined for items that should use positional ordering\n */\n getPriority?: (item: TValue) => number | undefined\n /**\n * Initial items to populate the queue with\n */\n initialItems?: Array<TValue>\n /**\n * Maximum number of items allowed in the queue\n */\n maxSize?: number\n /**\n * Whether the queuer should start processing items immediately\n * @default true\n */\n started?: boolean\n /**\n * Time in milliseconds to wait between processing items\n * @default 0\n */\n wait?: number\n}\n\n/**\n * A lightweight class that creates a queue for processing items.\n *\n * This is an alternative to the Queuer in the core @tanstack/pacer package, but is more\n * suitable for libraries and npm packages that need minimal overhead. Unlike the core Queuer,\n * this version does not use TanStack Store for state management, has no devtools integration,\n * no callbacks, and provides only essential queueing functionality.\n *\n * The queuer supports FIFO (First In First Out), LIFO (Last In First Out), and priority-based\n * processing of items. Items can be processed automatically with configurable wait times\n * between executions, or processed manually using the execute methods.\n *\n * Features included:\n * - Automatic or manual processing of items\n * - FIFO, LIFO, and priority-based ordering\n * - Queue size limits with item rejection\n * - Configurable wait times between processing\n * - Batch processing capabilities\n * - Start/stop processing control\n * - Callback support for monitoring execution, rejection, and state change events\n *\n * Features NOT included (compared to core Queuer):\n * - No TanStack Store state management\n * - No devtools integration\n * - No item expiration functionality (no onExpire callback)\n * - No dynamic options updates (setOptions)\n * - No detailed state tracking (execution counts, etc.)\n *\n * Queue behavior:\n * - Default: FIFO (add to back, process from front)\n * - LIFO: Configure addItemsTo: 'back', getItemsFrom: 'back'\n * - Priority: Provide getPriority function; higher values processed first\n *\n * @example\n * ```ts\n * // Basic FIFO queue\n * const queue = new LiteQueuer((item: string) => {\n * console.log('Processing:', item);\n * }, { wait: 100 });\n *\n * queue.addItem('task1');\n * queue.addItem('task2');\n * // Processes: task1, then task2 after 100ms delay\n * ```\n *\n * @example\n * ```ts\n * // Priority queue\n * const priorityQueue = new LiteQueuer((item: Task) => {\n * processTask(item);\n * }, {\n * getPriority: task => task.priority,\n * wait: 500\n * });\n *\n * priorityQueue.addItem({ name: 'low', priority: 1 });\n * priorityQueue.addItem({ name: 'high', priority: 10 });\n * // Processes high priority task first\n * ```\n */\nexport class LiteQueuer<TValue> {\n private items: Array<TValue> = []\n private timeoutId: NodeJS.Timeout | null = null\n private isRunning = true\n private pendingTick = false\n\n constructor(\n public fn: (item: TValue) => void,\n public options: LiteQueuerOptions<TValue> = {},\n ) {\n // Set defaults\n this.options.addItemsTo = this.options.addItemsTo ?? 'back'\n this.options.getItemsFrom = this.options.getItemsFrom ?? 'front'\n this.options.maxSize = this.options.maxSize ?? Infinity\n this.options.started = this.options.started ?? true\n this.options.wait = this.options.wait ?? 0\n\n this.isRunning = this.options.started\n\n // Add initial items if provided\n if (this.options.initialItems) {\n for (const item of this.options.initialItems) {\n this.addItem(item, this.options.addItemsTo, false)\n }\n }\n\n // Start processing if enabled and has items\n if (this.isRunning && this.items.length > 0) {\n this.tick()\n }\n }\n\n /**\n * Number of items currently in the queue\n */\n get size(): number {\n return this.items.length\n }\n\n /**\n * Whether the queue is empty\n */\n get isEmpty(): boolean {\n return this.items.length === 0\n }\n\n /**\n * Whether the queue is currently running (auto-processing items)\n */\n get isQueueRunning(): boolean {\n return this.isRunning\n }\n\n /**\n * Adds an item to the queue. If the queue is full, the item is rejected.\n * Items can be inserted at the front or back, and priority ordering is applied if getPriority is configured.\n *\n * Returns true if the item was added, false if the queue is full.\n *\n * @example\n * ```ts\n * queue.addItem('task1'); // Add to default position (back)\n * queue.addItem('task2', 'front'); // Add to front\n * ```\n */\n addItem = (\n item: TValue,\n position: QueuePosition = this.options.addItemsTo!,\n startProcessing: boolean = true,\n ): boolean => {\n // Check size limit\n if (this.items.length >= this.options.maxSize!) {\n return false\n }\n\n // Handle priority insertion\n if (this.options.getPriority) {\n const priority = this.options.getPriority(item)\n if (priority !== undefined) {\n // Find insertion point for priority\n const insertIndex = this.items.findIndex((existing) => {\n const existingPriority = this.options.getPriority!(existing)\n // Treat undefined priority as negative infinity for comparison\n const effectivePriority = existingPriority ?? -Infinity\n return effectivePriority < priority\n })\n\n if (insertIndex === -1) {\n this.items.push(item)\n } else {\n this.items.splice(insertIndex, 0, item)\n }\n } else {\n // No priority, use position\n this.insertAtPosition(item, position)\n }\n } else {\n // No priority function, use position\n this.insertAtPosition(item, position)\n }\n\n // Start processing if running and not already processing\n if (startProcessing && this.isRunning && !this.pendingTick) {\n this.tick()\n }\n\n return true\n }\n\n private insertAtPosition = (item: TValue, position: QueuePosition): void => {\n if (position === 'front') {\n this.items.unshift(item)\n } else {\n this.items.push(item)\n }\n }\n\n /**\n * Removes and returns the next item from the queue without executing the function.\n * Use for manual queue management. Normally, use execute() to process items.\n *\n * @example\n * ```ts\n * const nextItem = queue.getNextItem(); // Get from default position (front)\n * const lastItem = queue.getNextItem('back'); // Get from back (LIFO)\n * ```\n */\n getNextItem = (\n position: QueuePosition = this.options.getItemsFrom!,\n ): TValue | undefined => {\n if (this.items.length === 0) {\n return undefined\n }\n\n let item: TValue | undefined\n\n // When priority function is provided, always get from front (highest priority)\n if (this.options.getPriority || position === 'front') {\n item = this.items.shift()\n } else {\n item = this.items.pop()\n }\n\n return item\n }\n\n /**\n * Removes and returns the next item from the queue and processes it using the provided function.\n *\n * @example\n * ```ts\n * queue.execute(); // Execute from default position\n * queue.execute('back'); // Execute from back (LIFO)\n * ```\n */\n execute = (position?: QueuePosition): TValue | undefined => {\n const item = this.getNextItem(position)\n if (item !== undefined) {\n this.fn(item)\n }\n return item\n }\n\n /**\n * Internal method that processes items in the queue with wait intervals\n */\n private tick = (): void => {\n if (!this.isRunning) {\n this.pendingTick = false\n return\n }\n\n this.pendingTick = true\n\n // Process items while queue is not empty\n while (this.items.length > 0) {\n const item = this.execute(this.options.getItemsFrom)\n if (item === undefined) {\n break\n }\n\n const wait = this.options.wait!\n if (wait > 0) {\n // Schedule next processing after wait time\n this.timeoutId = setTimeout(() => this.tick(), wait)\n return\n }\n\n // No wait time, continue processing immediately\n }\n\n this.pendingTick = false\n }\n\n /**\n * Starts processing items in the queue. If already running, does nothing.\n */\n start = (): void => {\n this.isRunning = true\n if (!this.pendingTick && this.items.length > 0) {\n this.tick()\n }\n }\n\n /**\n * Stops processing items in the queue. Does not clear the queue.\n */\n stop = (): void => {\n this.clearTimeout()\n this.isRunning = false\n this.pendingTick = false\n }\n\n /**\n * Clears any pending timeout\n */\n private clearTimeout = (): void => {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId)\n this.timeoutId = null\n }\n }\n\n /**\n * Returns the next item in the queue without removing it.\n *\n * @example\n * ```ts\n * const next = queue.peekNextItem(); // Peek at front\n * const last = queue.peekNextItem('back'); // Peek at back\n * ```\n */\n peekNextItem = (position: QueuePosition = 'front'): TValue | undefined => {\n if (this.items.length === 0) {\n return undefined\n }\n\n if (this.options.getPriority || position === 'front') {\n return this.items[0]\n } else {\n return this.items[this.items.length - 1]\n }\n }\n\n /**\n * Returns a copy of all items in the queue.\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.items]\n }\n\n /**\n * Processes a specified number of items immediately with no wait time.\n * If no numberOfItems is provided, all items will be processed.\n *\n * @example\n * ```ts\n * queue.flush(); // Process all items immediately\n * queue.flush(3); // Process next 3 items immediately\n * ```\n */\n flush = (\n numberOfItems: number = this.items.length,\n position?: QueuePosition,\n ): void => {\n this.clearTimeout() // Clear any pending timeout\n for (let i = 0; i < numberOfItems && this.items.length > 0; i++) {\n this.execute(position)\n }\n // Restart normal processing if still running and has items\n if (this.isRunning && this.items.length > 0 && !this.pendingTick) {\n this.tick()\n }\n }\n\n /**\n * Processes all items in the queue as a batch using the provided function.\n * The queue is cleared after processing.\n *\n * @example\n * ```ts\n * queue.flushAsBatch((items) => {\n * console.log('Processing batch:', items);\n * // Process all items together\n * });\n * ```\n */\n flushAsBatch = (batchFunction: (items: Array<TValue>) => void): void => {\n const items = this.peekAllItems()\n this.clear()\n batchFunction(items)\n }\n\n /**\n * Removes all items from the queue. Does not affect items being processed.\n */\n clear = (): void => {\n this.items = []\n }\n}\n\n/**\n * Creates a lightweight queue that processes items using the provided function.\n *\n * This is an alternative to the queue function in the core @tanstack/pacer package, but is more\n * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,\n * this function creates a queuer with no external dependencies, devtools integration, or reactive state.\n *\n * @example\n * ```ts\n * const processItem = liteQueue((item: string) => {\n * console.log('Processing:', item);\n * }, { wait: 1000 });\n *\n * processItem('task1');\n * processItem('task2');\n * // Processes each item with 1 second delay between them\n * ```\n */\nexport function liteQueue<TValue>(\n fn: (item: TValue) => void,\n options: LiteQueuerOptions<TValue> = {},\n): (item: TValue) => boolean {\n const queuer = new LiteQueuer(fn, options)\n return (item: TValue) => queuer.addItem(item)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,IAAa,aAAb,MAAgC;CAM9B,YACE,AAAOA,IACP,AAAOC,UAAqC,EAAE,EAC9C;EAFO;EACA;eAPsB,EAAE;mBACU;mBACvB;qBACE;kBA8Dp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