@tanstack/pacer 0.22.0 → 0.23.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 (100) hide show
  1. package/README.md +4 -4
  2. package/dist/async-batcher.d.ts +11 -13
  3. package/dist/async-batcher.js +185 -131
  4. package/dist/async-debouncer.d.ts +6 -8
  5. package/dist/async-debouncer.js +186 -142
  6. package/dist/async-queuer.d.ts +11 -13
  7. package/dist/async-queuer.js +383 -290
  8. package/dist/async-rate-limiter.d.ts +6 -8
  9. package/dist/async-rate-limiter.js +197 -143
  10. package/dist/async-retryer.d.ts +6 -8
  11. package/dist/async-retryer.js +209 -179
  12. package/dist/async-throttler.d.ts +6 -8
  13. package/dist/async-throttler.js +214 -157
  14. package/dist/batcher.d.ts +5 -7
  15. package/dist/batcher.js +107 -87
  16. package/dist/debouncer.d.ts +6 -8
  17. package/dist/debouncer.js +99 -86
  18. package/dist/event-client.d.ts +8 -10
  19. package/dist/event-client.js +1 -2
  20. package/dist/queuer.d.ts +7 -9
  21. package/dist/queuer.js +277 -212
  22. package/dist/rate-limiter.d.ts +6 -8
  23. package/dist/rate-limiter.js +127 -109
  24. package/dist/throttler.d.ts +6 -8
  25. package/dist/throttler.js +127 -90
  26. package/dist/types.d.ts +4 -6
  27. package/dist/utils.d.ts +3 -5
  28. package/dist/utils.js +1 -2
  29. package/package.json +21 -68
  30. package/dist/async-batcher.cjs +0 -337
  31. package/dist/async-batcher.cjs.map +0 -1
  32. package/dist/async-batcher.d.cts +0 -343
  33. package/dist/async-batcher.js.map +0 -1
  34. package/dist/async-debouncer.cjs +0 -327
  35. package/dist/async-debouncer.cjs.map +0 -1
  36. package/dist/async-debouncer.d.cts +0 -299
  37. package/dist/async-debouncer.js.map +0 -1
  38. package/dist/async-queuer.cjs +0 -516
  39. package/dist/async-queuer.cjs.map +0 -1
  40. package/dist/async-queuer.d.cts +0 -440
  41. package/dist/async-queuer.js.map +0 -1
  42. package/dist/async-rate-limiter.cjs +0 -370
  43. package/dist/async-rate-limiter.cjs.map +0 -1
  44. package/dist/async-rate-limiter.d.cts +0 -356
  45. package/dist/async-rate-limiter.js.map +0 -1
  46. package/dist/async-retryer.cjs +0 -365
  47. package/dist/async-retryer.cjs.map +0 -1
  48. package/dist/async-retryer.d.cts +0 -321
  49. package/dist/async-retryer.js.map +0 -1
  50. package/dist/async-throttler.cjs +0 -344
  51. package/dist/async-throttler.cjs.map +0 -1
  52. package/dist/async-throttler.d.cts +0 -319
  53. package/dist/async-throttler.js.map +0 -1
  54. package/dist/batcher.cjs +0 -200
  55. package/dist/batcher.cjs.map +0 -1
  56. package/dist/batcher.d.cts +0 -179
  57. package/dist/batcher.js.map +0 -1
  58. package/dist/debouncer.cjs +0 -203
  59. package/dist/debouncer.cjs.map +0 -1
  60. package/dist/debouncer.d.cts +0 -166
  61. package/dist/debouncer.js.map +0 -1
  62. package/dist/event-client.cjs +0 -64
  63. package/dist/event-client.cjs.map +0 -1
  64. package/dist/event-client.d.cts +0 -65
  65. package/dist/event-client.js.map +0 -1
  66. package/dist/index.cjs +0 -52
  67. package/dist/index.d.cts +0 -15
  68. package/dist/queuer.cjs +0 -406
  69. package/dist/queuer.cjs.map +0 -1
  70. package/dist/queuer.d.cts +0 -345
  71. package/dist/queuer.js.map +0 -1
  72. package/dist/rate-limiter.cjs +0 -263
  73. package/dist/rate-limiter.cjs.map +0 -1
  74. package/dist/rate-limiter.d.cts +0 -214
  75. package/dist/rate-limiter.js.map +0 -1
  76. package/dist/throttler.cjs +0 -215
  77. package/dist/throttler.cjs.map +0 -1
  78. package/dist/throttler.d.cts +0 -206
  79. package/dist/throttler.js.map +0 -1
  80. package/dist/types.cjs +0 -0
  81. package/dist/types.d.cts +0 -13
  82. package/dist/utils.cjs +0 -13
  83. package/dist/utils.cjs.map +0 -1
  84. package/dist/utils.d.cts +0 -7
  85. package/dist/utils.js.map +0 -1
  86. package/src/async-batcher.ts +0 -594
  87. package/src/async-debouncer.ts +0 -566
  88. package/src/async-queuer.ts +0 -988
  89. package/src/async-rate-limiter.ts +0 -648
  90. package/src/async-retryer.ts +0 -673
  91. package/src/async-throttler.ts +0 -634
  92. package/src/batcher.ts +0 -329
  93. package/src/debouncer.ts +0 -334
  94. package/src/event-client.ts +0 -129
  95. package/src/index.ts +0 -24
  96. package/src/queuer.ts +0 -751
  97. package/src/rate-limiter.ts +0 -429
  98. package/src/throttler.ts +0 -380
  99. package/src/types.ts +0 -12
  100. package/src/utils.ts +0 -12
@@ -1,179 +0,0 @@
1
- import { OptionalKeys } from "./types.cjs";
2
- import { Store } from "@tanstack/store";
3
- //#region src/batcher.d.ts
4
- interface BatcherState<TValue> {
5
- /**
6
- * Number of batch executions that have been completed
7
- */
8
- executionCount: number;
9
- /**
10
- * Whether the batcher has no items to process (items array is empty)
11
- */
12
- isEmpty: boolean;
13
- /**
14
- * Whether the batcher is waiting for the timeout to trigger batch processing
15
- */
16
- isPending: boolean;
17
- /**
18
- * Array of items currently queued for batch processing
19
- */
20
- items: Array<TValue>;
21
- /**
22
- * Number of items currently in the batch queue
23
- */
24
- size: number;
25
- /**
26
- * Current processing status - 'idle' when not processing, 'pending' when waiting for timeout
27
- */
28
- status: 'idle' | 'pending';
29
- /**
30
- * Total number of items that have been processed across all batches
31
- */
32
- totalItemsProcessed: number;
33
- }
34
- /**
35
- * Options for configuring a Batcher instance
36
- */
37
- interface BatcherOptions<TValue> {
38
- /**
39
- * Custom function to determine if a batch should be processed
40
- * Return true to process the batch immediately
41
- */
42
- getShouldExecute?: (items: Array<TValue>, batcher: Batcher<TValue>) => boolean;
43
- /**
44
- * Initial state for the batcher
45
- */
46
- initialState?: Partial<BatcherState<TValue>>;
47
- /**
48
- * Optional key to identify this batcher instance.
49
- * If provided, the batcher will be identified by this key in the devtools and PacerProvider if applicable.
50
- */
51
- key?: string;
52
- /**
53
- * Maximum number of items in a batch
54
- * @default Infinity
55
- */
56
- maxSize?: number;
57
- /**
58
- * Callback fired after a batch is processed
59
- */
60
- onExecute?: (batch: Array<TValue>, batcher: Batcher<TValue>) => void;
61
- /**
62
- * Callback fired after items are added to the batcher
63
- */
64
- onItemsChange?: (batcher: Batcher<TValue>) => void;
65
- /**
66
- * Whether the batcher should start processing immediately
67
- * @default true
68
- */
69
- started?: boolean;
70
- /**
71
- * Maximum time in milliseconds to wait before processing a batch.
72
- * If the wait duration has elapsed, the batch will be processed.
73
- * If not provided, the batch will not be triggered by a timeout.
74
- * @default Infinity
75
- */
76
- wait?: number | ((batcher: Batcher<TValue>) => number);
77
- }
78
- type BatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<Required<BatcherOptions<TValue>>, 'initialState' | 'onExecute' | 'onItemsChange' | 'key'>;
79
- /**
80
- * A class that collects items and processes them in batches.
81
- *
82
- * Batching is a technique for grouping multiple operations together to be processed as a single unit.
83
- * This synchronous version is lighter weight and often all you need - upgrade to AsyncBatcher when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
84
- *
85
- * The Batcher provides a flexible way to implement batching with configurable:
86
- * - Maximum batch size (number of items per batch)
87
- * - Time-based batching (process after X milliseconds)
88
- * - Custom batch processing logic via getShouldExecute
89
- * - Event callbacks for monitoring batch operations
90
- *
91
- * State Management:
92
- * - Uses TanStack Store for reactive state management
93
- * - Use `initialState` to provide initial state values when creating the batcher
94
- * - Use `onExecute` callback to react to batch execution and implement custom logic
95
- * - Use `onItemsChange` callback to react to items being added or removed from the batcher
96
- * - The state includes batch execution count, total items processed, items, and running status
97
- * - State can be accessed via `batcher.store.state` when using the class directly
98
- * - When using framework adapters (React/Solid), state is accessed from `batcher.state`
99
- *
100
- * @example
101
- * ```ts
102
- * const batcher = new Batcher<number>(
103
- * (items) => console.log('Processing batch:', items),
104
- * {
105
- * maxSize: 5,
106
- * wait: 2000,
107
- * onExecute: (batch, batcher) => console.log('Batch executed:', batch)
108
- * }
109
- * );
110
- *
111
- * batcher.addItem(1);
112
- * batcher.addItem(2);
113
- * // After 2 seconds or when 5 items are added, whichever comes first,
114
- * // the batch will be processed
115
- * // batcher.flush() // manually trigger a batch
116
- * ```
117
- */
118
- declare class Batcher<TValue> {
119
- #private;
120
- fn: (items: Array<TValue>) => void;
121
- readonly store: Store<Readonly<BatcherState<TValue>>>;
122
- key: string | undefined;
123
- options: BatcherOptionsWithOptionalCallbacks<TValue>;
124
- constructor(fn: (items: Array<TValue>) => void, initialOptions: BatcherOptions<TValue>);
125
- /**
126
- * Updates the batcher options
127
- */
128
- setOptions: (newOptions: Partial<BatcherOptions<TValue>>) => void;
129
- /**
130
- * Adds an item to the batcher
131
- * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed
132
- */
133
- addItem: (item: TValue) => void;
134
- /**
135
- * Processes the current batch of items immediately
136
- */
137
- flush: () => void;
138
- /**
139
- * Returns a copy of all items in the batcher
140
- */
141
- peekAllItems: () => Array<TValue>;
142
- /**
143
- * Removes all items from the batcher
144
- */
145
- clear: () => void;
146
- /**
147
- * Cancels any pending execution that was scheduled.
148
- * Does NOT clear out the items.
149
- */
150
- cancel: () => void;
151
- /**
152
- * Resets the batcher state to its default values
153
- */
154
- reset: () => void;
155
- }
156
- /**
157
- * Creates a batcher that processes items in batches.
158
- *
159
- * This synchronous version is lighter weight and often all you need - upgrade to asyncBatch when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
160
- *
161
- * @example
162
- * ```ts
163
- * const batchItems = batch<number>(
164
- * (items) => console.log('Processing:', items),
165
- * {
166
- * maxSize: 3,
167
- * onExecute: (batch, batcher) => console.log('Batch executed:', batch)
168
- * }
169
- * );
170
- *
171
- * batchItems(1);
172
- * batchItems(2);
173
- * batchItems(3); // Triggers batch processing
174
- * ```
175
- */
176
- declare function batch<TValue>(fn: (items: Array<TValue>) => void, options: BatcherOptions<TValue>): (item: TValue) => void;
177
- //#endregion
178
- export { Batcher, BatcherOptions, BatcherState, batch };
179
- //# sourceMappingURL=batcher.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"batcher.js","names":["#setState","#execute","#clearTimeout","#timeoutId","#getWait"],"sources":["../src/batcher.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { OptionalKeys } from './types'\n\nexport interface BatcherState<TValue> {\n /**\n * Number of batch executions that have been completed\n */\n executionCount: number\n /**\n * Whether the batcher has no items to process (items array is empty)\n */\n isEmpty: boolean\n /**\n * Whether the batcher is waiting for the timeout to trigger batch processing\n */\n isPending: boolean\n /**\n * Array of items currently queued for batch processing\n */\n items: Array<TValue>\n /**\n * Number of items currently in the batch queue\n */\n size: number\n /**\n * Current processing status - 'idle' when not processing, 'pending' when waiting for timeout\n */\n status: 'idle' | 'pending'\n /**\n * Total number of items that have been processed across all batches\n */\n totalItemsProcessed: number\n}\n\nfunction getDefaultBatcherState<TValue>(): BatcherState<TValue> {\n return {\n executionCount: 0,\n isEmpty: true,\n isPending: false,\n totalItemsProcessed: 0,\n items: [],\n size: 0,\n status: 'idle',\n }\n}\n\n/**\n * Options for configuring a Batcher instance\n */\nexport interface BatcherOptions<TValue> {\n /**\n * Custom function to determine if a batch should be processed\n * Return true to process the batch immediately\n */\n getShouldExecute?: (items: Array<TValue>, batcher: Batcher<TValue>) => boolean\n /**\n * Initial state for the batcher\n */\n initialState?: Partial<BatcherState<TValue>>\n /**\n * Optional key to identify this batcher instance.\n * If provided, the batcher will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of items in a batch\n * @default Infinity\n */\n maxSize?: number\n /**\n * Callback fired after a batch is processed\n */\n onExecute?: (batch: Array<TValue>, batcher: Batcher<TValue>) => void\n /**\n * Callback fired after items are added to the batcher\n */\n onItemsChange?: (batcher: Batcher<TValue>) => void\n /**\n * Whether the batcher should start processing immediately\n * @default true\n */\n started?: boolean\n /**\n * Maximum time in milliseconds to wait before processing a batch.\n * If the wait duration has elapsed, the batch will be processed.\n * If not provided, the batch will not be triggered by a timeout.\n * @default Infinity\n */\n wait?: number | ((batcher: Batcher<TValue>) => number)\n}\n\ntype BatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<\n Required<BatcherOptions<TValue>>,\n 'initialState' | 'onExecute' | 'onItemsChange' | 'key'\n>\n\nconst defaultOptions: BatcherOptionsWithOptionalCallbacks<any> = {\n getShouldExecute: () => false,\n maxSize: Infinity,\n started: true,\n wait: Infinity,\n}\n\n/**\n * A class that collects items and processes them in batches.\n *\n * Batching is a technique for grouping multiple operations together to be processed as a single unit.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncBatcher when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * The Batcher provides a flexible way to implement batching with configurable:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the batcher\n * - Use `onExecute` callback to react to batch execution and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the batcher\n * - The state includes batch execution count, total items processed, items, and running status\n * - State can be accessed via `batcher.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `batcher.state`\n *\n * @example\n * ```ts\n * const batcher = new Batcher<number>(\n * (items) => console.log('Processing batch:', items),\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batch, batcher) => console.log('Batch executed:', batch)\n * }\n * );\n *\n * batcher.addItem(1);\n * batcher.addItem(2);\n * // After 2 seconds or when 5 items are added, whichever comes first,\n * // the batch will be processed\n * // batcher.flush() // manually trigger a batch\n * ```\n */\nexport class Batcher<TValue> {\n readonly store: Store<Readonly<BatcherState<TValue>>> = new Store(\n getDefaultBatcherState<TValue>(),\n )\n key: string | undefined\n options: BatcherOptionsWithOptionalCallbacks<TValue>\n #timeoutId: ReturnType<typeof setTimeout> | null = null\n\n constructor(\n public fn: (items: Array<TValue>) => void,\n initialOptions: BatcherOptions<TValue>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-Batcher', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<BatcherState<TValue>>,\n )\n this.setOptions(\n event.payload.options as Partial<BatcherOptions<TValue>>,\n )\n })\n }\n }\n\n /**\n * Updates the batcher options\n */\n setOptions = (newOptions: Partial<BatcherOptions<TValue>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<BatcherState<TValue>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending, items } = combinedState\n const size = items.length\n const isEmpty = size === 0\n return {\n ...combinedState,\n isEmpty,\n size,\n status: isPending ? 'pending' : 'idle',\n }\n })\n emitChange('Batcher', this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Adds an item to the batcher\n * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed\n */\n addItem = (item: TValue): void => {\n this.#setState({\n items: [...this.store.state.items, item],\n isPending: this.options.wait !== Infinity,\n })\n this.options.onItemsChange?.(this)\n\n const shouldProcess =\n this.store.state.items.length >= this.options.maxSize ||\n this.options.getShouldExecute(this.store.state.items, this)\n\n if (shouldProcess) {\n this.#execute()\n } else if (this.options.wait !== Infinity) {\n this.#clearTimeout() // clear any pending timeout to replace it with a new one\n this.#timeoutId = setTimeout(() => this.#execute(), this.#getWait())\n }\n }\n\n /**\n * Processes the current batch of items.\n * This method will automatically be triggered if the batcher is running and any of these conditions are met:\n * - The number of items reaches batchSize\n * - The wait duration has elapsed\n * - The getShouldExecute function returns true upon adding an item\n *\n * You can also call this method manually to process the current batch at any time.\n */\n #execute = (): void => {\n if (this.store.state.items.length === 0) {\n return\n }\n\n const batch = this.peekAllItems() // copy of the items to be processed (to prevent race conditions)\n this.clear() // Clear items before processing to prevent race conditions\n this.options.onItemsChange?.(this) // Call onItemsChange to notify listeners that the items have changed\n\n this.fn(batch) // EXECUTE\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n totalItemsProcessed: this.store.state.totalItemsProcessed + batch.length,\n })\n this.options.onExecute?.(batch, this)\n }\n\n /**\n * Processes the current batch of items immediately\n */\n flush = (): void => {\n this.#clearTimeout() // clear any pending timeout\n this.#execute() // execute immediately\n }\n\n /**\n * Returns a copy of all items in the batcher\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.store.state.items]\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = null\n }\n }\n\n /**\n * Removes all items from the batcher\n */\n clear = (): void => {\n this.#setState({ items: [], isPending: false })\n }\n\n /**\n * Cancels any pending execution that was scheduled.\n * Does NOT clear out the items.\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({ isPending: false })\n }\n\n /**\n * Resets the batcher state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultBatcherState<TValue>())\n this.options.onItemsChange?.(this)\n }\n}\n\n/**\n * Creates a batcher that processes items in batches.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncBatch when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * @example\n * ```ts\n * const batchItems = batch<number>(\n * (items) => console.log('Processing:', items),\n * {\n * maxSize: 3,\n * onExecute: (batch, batcher) => console.log('Batch executed:', batch)\n * }\n * );\n *\n * batchItems(1);\n * batchItems(2);\n * batchItems(3); // Triggers batch processing\n * ```\n */\nexport function batch<TValue>(\n fn: (items: Array<TValue>) => void,\n options: BatcherOptions<TValue>,\n) {\n const batcher = new Batcher<TValue>(fn, options)\n return batcher.addItem\n}\n"],"mappings":";;;;;AAoCA,SAAS,yBAAuD;CAC9D,OAAO;EACL,gBAAgB;EAChB,SAAS;EACT,WAAW;EACX,qBAAqB;EACrB,OAAO,CAAC;EACR,MAAM;EACN,QAAQ;CACV;AACF;AAoDA,MAAM,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,KAAKJ,UAAU;IACb,gBAAgB,KAAK,MAAM,MAAM,iBAAiB;IAClD,qBAAqB,KAAK,MAAM,MAAM,sBAAsB,MAAM;GACpE,CAAC;GACD,KAAK,QAAQ,YAAY,OAAO,IAAI;EACtC;qBAKoB;GAClB,KAAKE,cAAc;GACnB,KAAKD,SAAS;EAChB;4BAKoC;GAClC,OAAO,CAAC,GAAG,KAAK,MAAM,MAAM,KAAK;EACnC;6BAE4B;GAC1B,IAAI,KAAKE,YAAY;IACnB,aAAa,KAAKA,UAAU;IAC5B,KAAKA,aAAa;GACpB;EACF;qBAKoB;GAClB,KAAKH,UAAU;IAAE,OAAO,CAAC;IAAG,WAAW;GAAM,CAAC;EAChD;sBAMqB;GACnB,KAAKE,cAAc;GACnB,KAAKF,UAAU,EAAE,WAAW,MAAM,CAAC;EACrC;qBAKoB;GAClB,KAAKA,UAAU,uBAA+B,CAAC;GAC/C,KAAK,QAAQ,gBAAgB,IAAI;EACnC;EA/IE,KAAK,MAAM,eAAe;EAC1B,KAAK,UAAU;GACb,GAAG;GACH,GAAG;EACL;EACA,KAAKA,UAAU,KAAK,QAAQ,gBAAgB,CAAC,CAAC;EAE9C,IAAI,KAAK,KACP,iBAAiB,GAAG,cAAc,UAAU;GAC1C,IAAI,MAAM,QAAQ,QAAQ,KAAK,KAAK;GACpC,KAAKA,UACH,MAAM,QAAQ,MAAM,KACtB;GACA,KAAK,WACH,MAAM,QAAQ,OAChB;EACF,CAAC;CAEL;CASA;CAmBA;;;;;;;;;;CAoCA;CAgCA;AA8BF;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,MACd,IACA,SACA;CAEA,OAAO,IADa,QAAgB,IAAI,OAC3B,CAAC,CAAC;AACjB"}
@@ -1,203 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_utils = require('./utils.cjs');
3
- const require_event_client = require('./event-client.cjs');
4
- let _tanstack_store = require("@tanstack/store");
5
-
6
- //#region src/debouncer.ts
7
- function getDefaultDebouncerState() {
8
- return {
9
- canLeadingExecute: true,
10
- executionCount: 0,
11
- isPending: false,
12
- lastArgs: void 0,
13
- status: "idle",
14
- maybeExecuteCount: 0
15
- };
16
- }
17
- /**
18
- * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.
19
- */
20
- function debouncerOptions(options) {
21
- return options;
22
- }
23
- const defaultOptions = {
24
- enabled: true,
25
- leading: false,
26
- trailing: true,
27
- wait: 0
28
- };
29
- /**
30
- * A class that creates a debounced function.
31
- *
32
- * Debouncing ensures that a function is only executed after a certain amount of time has passed
33
- * since its last invocation. This is useful for handling frequent events like window resizing,
34
- * scroll events, or input changes where you want to limit the rate of execution.
35
- * This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
36
- *
37
- * The debounced function can be configured to execute either at the start of the delay period
38
- * (leading edge) or at the end (trailing edge, default). Each new call during the wait period
39
- * will reset the timer.
40
- *
41
- * State Management:
42
- * - Uses TanStack Store for reactive state management
43
- * - Use `initialState` to provide initial state values when creating the debouncer
44
- * - Use `onExecute` callback to react to function execution and implement custom logic
45
- * - The state includes canLeadingExecute, execution count, and isPending status
46
- * - State can be accessed via `debouncer.store.state` when using the class directly
47
- * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`
48
- *
49
- * @example
50
- * ```ts
51
- * const debouncer = new Debouncer((value: string) => {
52
- * saveToDatabase(value);
53
- * }, { wait: 500 });
54
- *
55
- * // Will only save after 500ms of no new input
56
- * inputElement.addEventListener('input', () => {
57
- * debouncer.maybeExecute(inputElement.value);
58
- * });
59
- * ```
60
- */
61
- var Debouncer = class {
62
- #timeoutId;
63
- constructor(fn, initialOptions) {
64
- this.fn = fn;
65
- this.store = new _tanstack_store.Store(getDefaultDebouncerState());
66
- this.setOptions = (newOptions) => {
67
- this.options = {
68
- ...this.options,
69
- ...newOptions
70
- };
71
- if (!this.#getEnabled()) this.cancel();
72
- };
73
- this.#setState = (newState) => {
74
- this.store.setState((state) => {
75
- const combinedState = {
76
- ...state,
77
- ...newState
78
- };
79
- const { isPending } = combinedState;
80
- return {
81
- ...combinedState,
82
- status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
83
- };
84
- });
85
- require_event_client.emitChange("Debouncer", this);
86
- };
87
- this.#getEnabled = () => {
88
- return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
89
- };
90
- this.#getWait = () => {
91
- return require_utils.parseFunctionOrValue(this.options.wait, this);
92
- };
93
- this.maybeExecute = (...args) => {
94
- if (!this.#getEnabled()) return void 0;
95
- this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
96
- let _didLeadingExecute = false;
97
- if (this.options.leading && this.store.state.canLeadingExecute) {
98
- this.#setState({ canLeadingExecute: false });
99
- _didLeadingExecute = true;
100
- this.#execute(...args);
101
- }
102
- if (this.options.trailing) this.#setState({
103
- isPending: true,
104
- lastArgs: args
105
- });
106
- if (this.#timeoutId) clearTimeout(this.#timeoutId);
107
- this.#timeoutId = setTimeout(() => {
108
- this.#setState({ canLeadingExecute: true });
109
- if (this.options.trailing && !_didLeadingExecute) this.#execute(...args);
110
- }, this.#getWait());
111
- };
112
- this.#execute = (...args) => {
113
- if (!this.#getEnabled()) return void 0;
114
- this.fn(...args);
115
- this.#setState({
116
- executionCount: this.store.state.executionCount + 1,
117
- isPending: false,
118
- lastArgs: void 0
119
- });
120
- this.options.onExecute?.(args, this);
121
- };
122
- this.flush = () => {
123
- if (this.store.state.isPending && this.store.state.lastArgs) {
124
- this.#clearTimeout();
125
- this.#execute(...this.store.state.lastArgs);
126
- }
127
- };
128
- this.#clearTimeout = () => {
129
- if (this.#timeoutId) {
130
- clearTimeout(this.#timeoutId);
131
- this.#timeoutId = void 0;
132
- }
133
- };
134
- this.cancel = () => {
135
- this.#clearTimeout();
136
- this.#setState({
137
- canLeadingExecute: true,
138
- isPending: false
139
- });
140
- };
141
- this.reset = () => {
142
- this.#setState(getDefaultDebouncerState());
143
- };
144
- this.key = initialOptions.key;
145
- this.options = {
146
- ...defaultOptions,
147
- ...initialOptions
148
- };
149
- this.#setState(this.options.initialState ?? {});
150
- if (this.key) require_event_client.pacerEventClient.on("d-Debouncer", (event) => {
151
- if (event.payload.key !== this.key) return;
152
- this.#setState(event.payload.store.state);
153
- this.setOptions(event.payload.options);
154
- });
155
- }
156
- #setState;
157
- /**
158
- * Returns the current enabled state of the debouncer
159
- */
160
- #getEnabled;
161
- /**
162
- * Returns the current wait time in milliseconds
163
- */
164
- #getWait;
165
- #execute;
166
- #clearTimeout;
167
- };
168
- /**
169
- * Creates a debounced function that delays invoking the provided function until after a specified wait time.
170
- * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.
171
- *
172
- * This synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
173
- *
174
- * If leading option is true, the function will execute immediately on the first call, then wait the delay
175
- * before allowing another execution.
176
- *
177
- * State Management:
178
- * - Uses TanStack Store for reactive state management
179
- * - Use `initialState` to provide initial state values when creating the debouncer
180
- * - Use `onExecute` callback to react to function execution and implement custom logic
181
- * - The state includes canLeadingExecute, execution count, and isPending status
182
- * - State can be accessed via the underlying Debouncer instance's `store.state` property
183
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
184
- *
185
- * @example
186
- * ```ts
187
- * const debounced = debounce(() => {
188
- * saveChanges();
189
- * }, { wait: 1000 });
190
- *
191
- * // Called repeatedly but executes at most once per second
192
- * inputElement.addEventListener('input', debounced);
193
- * ```
194
- */
195
- function debounce(fn, initialOptions) {
196
- return new Debouncer(fn, initialOptions).maybeExecute;
197
- }
198
-
199
- //#endregion
200
- exports.Debouncer = Debouncer;
201
- exports.debounce = debounce;
202
- exports.debouncerOptions = debouncerOptions;
203
- //# sourceMappingURL=debouncer.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"debouncer.cjs","names":["Store","#getEnabled","parseFunctionOrValue","#setState","#execute","#timeoutId","#getWait","#clearTimeout"],"sources":["../src/debouncer.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AnyFunction } from './types'\n\nexport interface DebouncerState<TFn extends AnyFunction> {\n /**\n * Whether the debouncer can execute on the leading edge of the timeout\n */\n canLeadingExecute: boolean\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the debouncer is waiting for the timeout to trigger execution\n */\n isPending: boolean\n /**\n * The arguments from the most recent call to maybeExecute\n */\n lastArgs: Parameters<TFn> | undefined\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultDebouncerState<\n TFn extends AnyFunction,\n>(): DebouncerState<TFn> {\n return {\n canLeadingExecute: true,\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions<TFn extends AnyFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean)\n /**\n * Initial state for the debouncer\n */\n initialState?: Partial<DebouncerState<TFn>>\n /**\n * A key to identify the debouncer.\n * If provided, the debouncer will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\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: Debouncer<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 * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: Debouncer<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.\n */\nexport function debouncerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<DebouncerOptions<TFn>> = Partial<\n DebouncerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<DebouncerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a debounced function.\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 * This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\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 * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via `debouncer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`\n *\n * @example\n * ```ts\n * const debouncer = new Debouncer((value: string) => {\n * saveToDatabase(value);\n * }, { wait: 500 });\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 Debouncer<TFn extends AnyFunction> {\n readonly store: Store<Readonly<DebouncerState<TFn>>> = new Store(\n getDefaultDebouncerState<TFn>(),\n )\n key: string | undefined\n options: DebouncerOptions<TFn>\n #timeoutId: ReturnType<typeof setTimeout> | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-Debouncer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<DebouncerState<TFn>>,\n )\n this.setOptions(event.payload.options as Partial<DebouncerOptions<TFn>>)\n })\n }\n }\n\n /**\n * Updates the debouncer options\n */\n setOptions = (newOptions: Partial<DebouncerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the debouncer is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<DebouncerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isPending\n ? 'pending'\n : 'idle',\n }\n })\n emitChange('Debouncer', this)\n }\n\n /**\n * Returns the current enabled state of the debouncer\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current wait time in milliseconds\n */\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n let _didLeadingExecute = false\n\n // Handle leading execution\n if (this.options.leading && this.store.state.canLeadingExecute) {\n this.#setState({ canLeadingExecute: false })\n _didLeadingExecute = true\n this.#execute(...args)\n }\n\n // Start pending state to indicate that the debouncer is waiting for the trailing edge\n if (this.options.trailing) {\n this.#setState({ isPending: true, lastArgs: args })\n }\n\n // Clear any existing timeout\n if (this.#timeoutId) clearTimeout(this.#timeoutId)\n\n // Set new timeout that will reset canLeadingExecute and execute trailing only if enabled and did not execute leading\n this.#timeoutId = setTimeout(() => {\n this.#setState({ canLeadingExecute: true })\n if (this.options.trailing && !_didLeadingExecute) {\n this.#execute(...args)\n }\n }, this.#getWait())\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n this.fn(...args) // EXECUTE!\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, this)\n }\n\n /**\n * Processes the current pending execution immediately\n */\n flush = (): void => {\n if (this.store.state.isPending && this.store.state.lastArgs) {\n this.#clearTimeout() // clear any pending timeout\n this.#execute(...this.store.state.lastArgs) // execute immediately\n }\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = undefined\n }\n }\n\n /**\n * Cancels any pending execution\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n canLeadingExecute: true,\n isPending: false,\n })\n }\n\n /**\n * Resets the debouncer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultDebouncerState<TFn>())\n }\n}\n\n/**\n * Creates a 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 synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\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 * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via the underlying Debouncer instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * @example\n * ```ts\n * const debounced = debounce(() => {\n * saveChanges();\n * }, { wait: 1000 });\n *\n * // Called repeatedly but executes at most once per second\n * inputElement.addEventListener('input', debounced);\n * ```\n */\nexport function debounce<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n): (...args: Parameters<TFn>) => void {\n const debouncer = new Debouncer(fn, initialOptions)\n return debouncer.maybeExecute\n}\n"],"mappings":";;;;;;AAgCA,SAAS,2BAEgB;CACvB,OAAO;EACL,mBAAmB;EACnB,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,QAAQ;EACR,mBAAmB;CACrB;AACF;;;;AA+CA,SAAgB,iBAKd,SAA6B;CAC7B,OAAO;AACT;AAEA,MAAM,iBAGF;CACF,SAAS;CACT,SAAS;CACT,UAAU;CACV,MAAM;AACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAa,YAAb,MAAgD;CAM9C;CAEA,YACE,AAAO,IACP,gBACA;EAFO;eAR8C,IAAIA,sBACzD,yBAA8B,CAChC;qBA8Bc,eAAqD;GACjE,KAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;GAAW;GAGhD,IAAI,CAAC,KAAKC,YAAY,GACpB,KAAK,OAAO;EAEhB;oBAEa,aAAiD;GAC5D,KAAK,MAAM,UAAU,UAAU;IAC7B,MAAM,gBAAgB;KACpB,GAAG;KACH,GAAG;IACL;IACA,MAAM,EAAE,cAAc;IACtB,OAAO;KACL,GAAG;KACH,QAAQ,CAAC,KAAKA,YAAY,IACtB,aACA,YACE,YACA;IACR;GACF,CAAC;GACD,gCAAW,aAAa,IAAI;EAC9B;2BAK6B;GAC3B,OAAO,CAAC,CAACC,mCAAqB,KAAK,QAAQ,SAAS,IAAI;EAC1D;wBAKyB;GACvB,OAAOA,mCAAqB,KAAK,QAAQ,MAAM,IAAI;EACrD;uBAMgB,GAAG,SAAgC;GACjD,IAAI,CAAC,KAAKD,YAAY,GAAG,OAAO;GAEhC,KAAKE,UAAU,EACb,mBAAmB,KAAK,MAAM,MAAM,oBAAoB,EAC1D,CAAC;GAED,IAAI,qBAAqB;GAGzB,IAAI,KAAK,QAAQ,WAAW,KAAK,MAAM,MAAM,mBAAmB;IAC9D,KAAKA,UAAU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KA,UACH,MAAM,QAAQ,MAAM,KACtB;GACA,KAAK,WAAW,MAAM,QAAQ,OAAyC;EACzE,CAAC;CAEL;CAcA;;;;CAsBA;;;;CAOA;CAyCA;CAqBA;AAwBF;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,SACd,IACA,gBACoC;CAEpC,OAAO,IADe,UAAU,IAAI,cACrB,CAAC,CAAC;AACnB"}
@@ -1,166 +0,0 @@
1
- import { AnyFunction } from "./types.cjs";
2
- import { Store } from "@tanstack/store";
3
- //#region src/debouncer.d.ts
4
- interface DebouncerState<TFn extends AnyFunction> {
5
- /**
6
- * Whether the debouncer can execute on the leading edge of the timeout
7
- */
8
- canLeadingExecute: boolean;
9
- /**
10
- * Number of function executions that have been completed
11
- */
12
- executionCount: number;
13
- /**
14
- * Whether the debouncer is waiting for the timeout to trigger execution
15
- */
16
- isPending: boolean;
17
- /**
18
- * The arguments from the most recent call to maybeExecute
19
- */
20
- lastArgs: Parameters<TFn> | undefined;
21
- /**
22
- * Number of times maybeExecute has been called (for reduction calculations)
23
- */
24
- maybeExecuteCount: number;
25
- /**
26
- * Current execution status - 'idle' when not active, 'pending' when waiting for timeout
27
- */
28
- status: 'disabled' | 'idle' | 'pending';
29
- }
30
- /**
31
- * Options for configuring a debounced function
32
- */
33
- interface DebouncerOptions<TFn extends AnyFunction> {
34
- /**
35
- * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
36
- * Can be a boolean or a function that returns a boolean.
37
- * Defaults to true.
38
- */
39
- enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean);
40
- /**
41
- * Initial state for the debouncer
42
- */
43
- initialState?: Partial<DebouncerState<TFn>>;
44
- /**
45
- * A key to identify the debouncer.
46
- * If provided, the debouncer will be identified by this key in the devtools and PacerProvider if applicable.
47
- */
48
- key?: string;
49
- /**
50
- * Whether to execute on the leading edge of the timeout.
51
- * The first call will execute immediately and the rest will wait the delay.
52
- * Defaults to false.
53
- */
54
- leading?: boolean;
55
- /**
56
- * Callback function that is called after the function is executed
57
- */
58
- onExecute?: (args: Parameters<TFn>, debouncer: Debouncer<TFn>) => void;
59
- /**
60
- * Whether to execute on the trailing edge of the timeout.
61
- * Defaults to true.
62
- */
63
- trailing?: boolean;
64
- /**
65
- * Delay in milliseconds before executing the function.
66
- * Can be a number or a function that returns a number.
67
- * Defaults to 0ms
68
- */
69
- wait: number | ((debouncer: Debouncer<TFn>) => number);
70
- }
71
- /**
72
- * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.
73
- */
74
- declare function debouncerOptions<TFn extends AnyFunction = AnyFunction, TOptions extends Partial<DebouncerOptions<TFn>> = Partial<DebouncerOptions<TFn>>>(options: TOptions): TOptions;
75
- /**
76
- * A class that creates a debounced function.
77
- *
78
- * Debouncing ensures that a function is only executed after a certain amount of time has passed
79
- * since its last invocation. This is useful for handling frequent events like window resizing,
80
- * scroll events, or input changes where you want to limit the rate of execution.
81
- * This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
82
- *
83
- * The debounced function can be configured to execute either at the start of the delay period
84
- * (leading edge) or at the end (trailing edge, default). Each new call during the wait period
85
- * will reset the timer.
86
- *
87
- * State Management:
88
- * - Uses TanStack Store for reactive state management
89
- * - Use `initialState` to provide initial state values when creating the debouncer
90
- * - Use `onExecute` callback to react to function execution and implement custom logic
91
- * - The state includes canLeadingExecute, execution count, and isPending status
92
- * - State can be accessed via `debouncer.store.state` when using the class directly
93
- * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`
94
- *
95
- * @example
96
- * ```ts
97
- * const debouncer = new Debouncer((value: string) => {
98
- * saveToDatabase(value);
99
- * }, { wait: 500 });
100
- *
101
- * // Will only save after 500ms of no new input
102
- * inputElement.addEventListener('input', () => {
103
- * debouncer.maybeExecute(inputElement.value);
104
- * });
105
- * ```
106
- */
107
- declare class Debouncer<TFn extends AnyFunction> {
108
- #private;
109
- fn: TFn;
110
- readonly store: Store<Readonly<DebouncerState<TFn>>>;
111
- key: string | undefined;
112
- options: DebouncerOptions<TFn>;
113
- constructor(fn: TFn, initialOptions: DebouncerOptions<TFn>);
114
- /**
115
- * Updates the debouncer options
116
- */
117
- setOptions: (newOptions: Partial<DebouncerOptions<TFn>>) => void;
118
- /**
119
- * Attempts to execute the debounced function
120
- * If a call is already in progress, it will be queued
121
- */
122
- maybeExecute: (...args: Parameters<TFn>) => void;
123
- /**
124
- * Processes the current pending execution immediately
125
- */
126
- flush: () => void;
127
- /**
128
- * Cancels any pending execution
129
- */
130
- cancel: () => void;
131
- /**
132
- * Resets the debouncer state to its default values
133
- */
134
- reset: () => void;
135
- }
136
- /**
137
- * Creates a debounced function that delays invoking the provided function until after a specified wait time.
138
- * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.
139
- *
140
- * This synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
141
- *
142
- * If leading option is true, the function will execute immediately on the first call, then wait the delay
143
- * before allowing another execution.
144
- *
145
- * State Management:
146
- * - Uses TanStack Store for reactive state management
147
- * - Use `initialState` to provide initial state values when creating the debouncer
148
- * - Use `onExecute` callback to react to function execution and implement custom logic
149
- * - The state includes canLeadingExecute, execution count, and isPending status
150
- * - State can be accessed via the underlying Debouncer instance's `store.state` property
151
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
152
- *
153
- * @example
154
- * ```ts
155
- * const debounced = debounce(() => {
156
- * saveChanges();
157
- * }, { wait: 1000 });
158
- *
159
- * // Called repeatedly but executes at most once per second
160
- * inputElement.addEventListener('input', debounced);
161
- * ```
162
- */
163
- declare function debounce<TFn extends AnyFunction>(fn: TFn, initialOptions: DebouncerOptions<TFn>): (...args: Parameters<TFn>) => void;
164
- //#endregion
165
- export { Debouncer, DebouncerOptions, DebouncerState, debounce, debouncerOptions };
166
- //# sourceMappingURL=debouncer.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"debouncer.js","names":["#getEnabled","#setState","#execute","#timeoutId","#getWait","#clearTimeout"],"sources":["../src/debouncer.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AnyFunction } from './types'\n\nexport interface DebouncerState<TFn extends AnyFunction> {\n /**\n * Whether the debouncer can execute on the leading edge of the timeout\n */\n canLeadingExecute: boolean\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the debouncer is waiting for the timeout to trigger execution\n */\n isPending: boolean\n /**\n * The arguments from the most recent call to maybeExecute\n */\n lastArgs: Parameters<TFn> | undefined\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultDebouncerState<\n TFn extends AnyFunction,\n>(): DebouncerState<TFn> {\n return {\n canLeadingExecute: true,\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions<TFn extends AnyFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean)\n /**\n * Initial state for the debouncer\n */\n initialState?: Partial<DebouncerState<TFn>>\n /**\n * A key to identify the debouncer.\n * If provided, the debouncer will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\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: Debouncer<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 * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: Debouncer<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.\n */\nexport function debouncerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<DebouncerOptions<TFn>> = Partial<\n DebouncerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<DebouncerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a debounced function.\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 * This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\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 * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via `debouncer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`\n *\n * @example\n * ```ts\n * const debouncer = new Debouncer((value: string) => {\n * saveToDatabase(value);\n * }, { wait: 500 });\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 Debouncer<TFn extends AnyFunction> {\n readonly store: Store<Readonly<DebouncerState<TFn>>> = new Store(\n getDefaultDebouncerState<TFn>(),\n )\n key: string | undefined\n options: DebouncerOptions<TFn>\n #timeoutId: ReturnType<typeof setTimeout> | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n ) {\n this.key = initialOptions.key\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n if (this.key) {\n pacerEventClient.on('d-Debouncer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<DebouncerState<TFn>>,\n )\n this.setOptions(event.payload.options as Partial<DebouncerOptions<TFn>>)\n })\n }\n }\n\n /**\n * Updates the debouncer options\n */\n setOptions = (newOptions: Partial<DebouncerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the debouncer is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<DebouncerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isPending\n ? 'pending'\n : 'idle',\n }\n })\n emitChange('Debouncer', this)\n }\n\n /**\n * Returns the current enabled state of the debouncer\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current wait time in milliseconds\n */\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n let _didLeadingExecute = false\n\n // Handle leading execution\n if (this.options.leading && this.store.state.canLeadingExecute) {\n this.#setState({ canLeadingExecute: false })\n _didLeadingExecute = true\n this.#execute(...args)\n }\n\n // Start pending state to indicate that the debouncer is waiting for the trailing edge\n if (this.options.trailing) {\n this.#setState({ isPending: true, lastArgs: args })\n }\n\n // Clear any existing timeout\n if (this.#timeoutId) clearTimeout(this.#timeoutId)\n\n // Set new timeout that will reset canLeadingExecute and execute trailing only if enabled and did not execute leading\n this.#timeoutId = setTimeout(() => {\n this.#setState({ canLeadingExecute: true })\n if (this.options.trailing && !_didLeadingExecute) {\n this.#execute(...args)\n }\n }, this.#getWait())\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n this.fn(...args) // EXECUTE!\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, this)\n }\n\n /**\n * Processes the current pending execution immediately\n */\n flush = (): void => {\n if (this.store.state.isPending && this.store.state.lastArgs) {\n this.#clearTimeout() // clear any pending timeout\n this.#execute(...this.store.state.lastArgs) // execute immediately\n }\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = undefined\n }\n }\n\n /**\n * Cancels any pending execution\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n canLeadingExecute: true,\n isPending: false,\n })\n }\n\n /**\n * Resets the debouncer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultDebouncerState<TFn>())\n }\n}\n\n/**\n * Creates a 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 synchronous version is lighter weight and often all you need - upgrade to asyncDebounce when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\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 * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via the underlying Debouncer instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * @example\n * ```ts\n * const debounced = debounce(() => {\n * saveChanges();\n * }, { wait: 1000 });\n *\n * // Called repeatedly but executes at most once per second\n * inputElement.addEventListener('input', debounced);\n * ```\n */\nexport function debounce<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n): (...args: Parameters<TFn>) => void {\n const debouncer = new Debouncer(fn, initialOptions)\n return debouncer.maybeExecute\n}\n"],"mappings":";;;;;AAgCA,SAAS,2BAEgB;CACvB,OAAO;EACL,mBAAmB;EACnB,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,QAAQ;EACR,mBAAmB;CACrB;AACF;;;;AA+CA,SAAgB,iBAKd,SAA6B;CAC7B,OAAO;AACT;AAEA,MAAM,iBAGF;CACF,SAAS;CACT,SAAS;CACT,UAAU;CACV,MAAM;AACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAa,YAAb,MAAgD;CAM9C;CAEA,YACE,AAAO,IACP,gBACA;EAFO;eAR8C,IAAI,MACzD,yBAA8B,CAChC;qBA8Bc,eAAqD;GACjE,KAAK,UAAU;IAAE,GAAG,KAAK;IAAS,GAAG;GAAW;GAGhD,IAAI,CAAC,KAAKA,YAAY,GACpB,KAAK,OAAO;EAEhB;oBAEa,aAAiD;GAC5D,KAAK,MAAM,UAAU,UAAU;IAC7B,MAAM,gBAAgB;KACpB,GAAG;KACH,GAAG;IACL;IACA,MAAM,EAAE,cAAc;IACtB,OAAO;KACL,GAAG;KACH,QAAQ,CAAC,KAAKA,YAAY,IACtB,aACA,YACE,YACA;IACR;GACF,CAAC;GACD,WAAW,aAAa,IAAI;EAC9B;2BAK6B;GAC3B,OAAO,CAAC,CAAC,qBAAqB,KAAK,QAAQ,SAAS,IAAI;EAC1D;wBAKyB;GACvB,OAAO,qBAAqB,KAAK,QAAQ,MAAM,IAAI;EACrD;uBAMgB,GAAG,SAAgC;GACjD,IAAI,CAAC,KAAKA,YAAY,GAAG,OAAO;GAEhC,KAAKC,UAAU,EACb,mBAAmB,KAAK,MAAM,MAAM,oBAAoB,EAC1D,CAAC;GAED,IAAI,qBAAqB;GAGzB,IAAI,KAAK,QAAQ,WAAW,KAAK,MAAM,MAAM,mBAA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