@tanstack/pacer 0.16.2 → 0.16.4

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 (180) hide show
  1. package/README.md +165 -0
  2. package/dist/async-batcher.cjs +355 -0
  3. package/dist/async-batcher.cjs.map +1 -0
  4. package/dist/async-batcher.d.cts +344 -0
  5. package/dist/async-batcher.d.ts +344 -0
  6. package/dist/async-batcher.js +353 -0
  7. package/dist/async-batcher.js.map +1 -0
  8. package/dist/async-debouncer.cjs +340 -0
  9. package/dist/async-debouncer.cjs.map +1 -0
  10. package/dist/async-debouncer.d.cts +300 -0
  11. package/dist/async-debouncer.d.ts +300 -0
  12. package/dist/async-debouncer.js +338 -0
  13. package/dist/async-debouncer.js.map +1 -0
  14. package/dist/async-queuer.cjs +496 -0
  15. package/dist/async-queuer.cjs.map +1 -0
  16. package/dist/async-queuer.d.cts +440 -0
  17. package/dist/async-queuer.d.ts +440 -0
  18. package/dist/async-queuer.js +494 -0
  19. package/dist/async-queuer.js.map +1 -0
  20. package/dist/async-rate-limiter.cjs +381 -0
  21. package/dist/async-rate-limiter.cjs.map +1 -0
  22. package/dist/{cjs/async-rate-limiter.d.cts → async-rate-limiter.d.cts} +190 -185
  23. package/dist/{esm/async-rate-limiter.d.ts → async-rate-limiter.d.ts} +190 -185
  24. package/dist/async-rate-limiter.js +379 -0
  25. package/dist/async-rate-limiter.js.map +1 -0
  26. package/dist/async-retryer.cjs +378 -0
  27. package/dist/async-retryer.cjs.map +1 -0
  28. package/dist/async-retryer.d.cts +312 -0
  29. package/dist/async-retryer.d.ts +312 -0
  30. package/dist/async-retryer.js +376 -0
  31. package/dist/async-retryer.js.map +1 -0
  32. package/dist/async-throttler.cjs +362 -0
  33. package/dist/async-throttler.cjs.map +1 -0
  34. package/dist/async-throttler.d.cts +320 -0
  35. package/dist/async-throttler.d.ts +320 -0
  36. package/dist/async-throttler.js +360 -0
  37. package/dist/async-throttler.js.map +1 -0
  38. package/dist/batcher.cjs +194 -0
  39. package/dist/batcher.cjs.map +1 -0
  40. package/dist/batcher.d.cts +180 -0
  41. package/dist/batcher.d.ts +180 -0
  42. package/dist/batcher.js +193 -0
  43. package/dist/batcher.js.map +1 -0
  44. package/dist/debouncer.cjs +197 -0
  45. package/dist/debouncer.cjs.map +1 -0
  46. package/dist/debouncer.d.cts +167 -0
  47. package/dist/debouncer.d.ts +167 -0
  48. package/dist/debouncer.js +195 -0
  49. package/dist/debouncer.js.map +1 -0
  50. package/dist/event-client.cjs +20 -0
  51. package/dist/event-client.cjs.map +1 -0
  52. package/dist/event-client.d.cts +49 -0
  53. package/dist/event-client.d.ts +49 -0
  54. package/dist/event-client.js +19 -0
  55. package/dist/event-client.js.map +1 -0
  56. package/dist/index.cjs +49 -0
  57. package/dist/index.d.cts +15 -0
  58. package/dist/index.d.ts +15 -0
  59. package/dist/{esm/index.js → index.js} +5 -41
  60. package/dist/queuer.cjs +393 -0
  61. package/dist/queuer.cjs.map +1 -0
  62. package/dist/queuer.d.cts +345 -0
  63. package/dist/queuer.d.ts +345 -0
  64. package/dist/queuer.js +391 -0
  65. package/dist/queuer.js.map +1 -0
  66. package/dist/rate-limiter.cjs +251 -0
  67. package/dist/rate-limiter.cjs.map +1 -0
  68. package/dist/{cjs/rate-limiter.d.cts → rate-limiter.d.cts} +113 -108
  69. package/dist/{esm/rate-limiter.d.ts → rate-limiter.d.ts} +113 -108
  70. package/dist/rate-limiter.js +249 -0
  71. package/dist/rate-limiter.js.map +1 -0
  72. package/dist/throttler.cjs +209 -0
  73. package/dist/throttler.cjs.map +1 -0
  74. package/dist/throttler.d.cts +207 -0
  75. package/dist/throttler.d.ts +207 -0
  76. package/dist/throttler.js +207 -0
  77. package/dist/throttler.js.map +1 -0
  78. package/dist/types.cjs +0 -0
  79. package/dist/types.d.cts +13 -0
  80. package/dist/types.d.ts +13 -0
  81. package/dist/types.js +1 -0
  82. package/dist/utils.cjs +13 -0
  83. package/dist/utils.cjs.map +1 -0
  84. package/dist/utils.d.cts +8 -0
  85. package/dist/utils.d.ts +8 -0
  86. package/dist/utils.js +11 -0
  87. package/dist/utils.js.map +1 -0
  88. package/package.json +38 -122
  89. package/src/async-batcher.ts +7 -5
  90. package/src/async-debouncer.ts +7 -5
  91. package/src/async-queuer.ts +7 -5
  92. package/src/async-rate-limiter.ts +7 -5
  93. package/src/async-retryer.ts +7 -5
  94. package/src/async-throttler.ts +7 -5
  95. package/src/batcher.ts +7 -5
  96. package/src/debouncer.ts +7 -5
  97. package/src/queuer.ts +7 -5
  98. package/src/rate-limiter.ts +7 -5
  99. package/src/throttler.ts +7 -5
  100. package/dist/cjs/async-batcher.cjs +0 -220
  101. package/dist/cjs/async-batcher.cjs.map +0 -1
  102. package/dist/cjs/async-batcher.d.cts +0 -340
  103. package/dist/cjs/async-debouncer.cjs +0 -231
  104. package/dist/cjs/async-debouncer.cjs.map +0 -1
  105. package/dist/cjs/async-debouncer.d.cts +0 -295
  106. package/dist/cjs/async-queuer.cjs +0 -397
  107. package/dist/cjs/async-queuer.cjs.map +0 -1
  108. package/dist/cjs/async-queuer.d.cts +0 -435
  109. package/dist/cjs/async-rate-limiter.cjs +0 -252
  110. package/dist/cjs/async-rate-limiter.cjs.map +0 -1
  111. package/dist/cjs/async-retryer.cjs +0 -285
  112. package/dist/cjs/async-retryer.cjs.map +0 -1
  113. package/dist/cjs/async-retryer.d.cts +0 -308
  114. package/dist/cjs/async-throttler.cjs +0 -261
  115. package/dist/cjs/async-throttler.cjs.map +0 -1
  116. package/dist/cjs/async-throttler.d.cts +0 -315
  117. package/dist/cjs/batcher.cjs +0 -130
  118. package/dist/cjs/batcher.cjs.map +0 -1
  119. package/dist/cjs/batcher.d.cts +0 -176
  120. package/dist/cjs/debouncer.cjs +0 -137
  121. package/dist/cjs/debouncer.cjs.map +0 -1
  122. package/dist/cjs/debouncer.d.cts +0 -162
  123. package/dist/cjs/event-client.cjs +0 -20
  124. package/dist/cjs/event-client.cjs.map +0 -1
  125. package/dist/cjs/event-client.d.cts +0 -45
  126. package/dist/cjs/index.cjs +0 -51
  127. package/dist/cjs/index.cjs.map +0 -1
  128. package/dist/cjs/index.d.cts +0 -15
  129. package/dist/cjs/queuer.cjs +0 -306
  130. package/dist/cjs/queuer.cjs.map +0 -1
  131. package/dist/cjs/queuer.d.cts +0 -340
  132. package/dist/cjs/rate-limiter.cjs +0 -179
  133. package/dist/cjs/rate-limiter.cjs.map +0 -1
  134. package/dist/cjs/throttler.cjs +0 -151
  135. package/dist/cjs/throttler.cjs.map +0 -1
  136. package/dist/cjs/throttler.d.cts +0 -202
  137. package/dist/cjs/types.d.cts +0 -9
  138. package/dist/cjs/utils.cjs +0 -11
  139. package/dist/cjs/utils.cjs.map +0 -1
  140. package/dist/cjs/utils.d.cts +0 -3
  141. package/dist/esm/async-batcher.d.ts +0 -340
  142. package/dist/esm/async-batcher.js +0 -220
  143. package/dist/esm/async-batcher.js.map +0 -1
  144. package/dist/esm/async-debouncer.d.ts +0 -295
  145. package/dist/esm/async-debouncer.js +0 -231
  146. package/dist/esm/async-debouncer.js.map +0 -1
  147. package/dist/esm/async-queuer.d.ts +0 -435
  148. package/dist/esm/async-queuer.js +0 -397
  149. package/dist/esm/async-queuer.js.map +0 -1
  150. package/dist/esm/async-rate-limiter.js +0 -252
  151. package/dist/esm/async-rate-limiter.js.map +0 -1
  152. package/dist/esm/async-retryer.d.ts +0 -308
  153. package/dist/esm/async-retryer.js +0 -285
  154. package/dist/esm/async-retryer.js.map +0 -1
  155. package/dist/esm/async-throttler.d.ts +0 -315
  156. package/dist/esm/async-throttler.js +0 -261
  157. package/dist/esm/async-throttler.js.map +0 -1
  158. package/dist/esm/batcher.d.ts +0 -176
  159. package/dist/esm/batcher.js +0 -130
  160. package/dist/esm/batcher.js.map +0 -1
  161. package/dist/esm/debouncer.d.ts +0 -162
  162. package/dist/esm/debouncer.js +0 -137
  163. package/dist/esm/debouncer.js.map +0 -1
  164. package/dist/esm/event-client.d.ts +0 -45
  165. package/dist/esm/event-client.js +0 -20
  166. package/dist/esm/event-client.js.map +0 -1
  167. package/dist/esm/index.d.ts +0 -15
  168. package/dist/esm/index.js.map +0 -1
  169. package/dist/esm/queuer.d.ts +0 -340
  170. package/dist/esm/queuer.js +0 -306
  171. package/dist/esm/queuer.js.map +0 -1
  172. package/dist/esm/rate-limiter.js +0 -179
  173. package/dist/esm/rate-limiter.js.map +0 -1
  174. package/dist/esm/throttler.d.ts +0 -202
  175. package/dist/esm/throttler.js +0 -151
  176. package/dist/esm/throttler.js.map +0 -1
  177. package/dist/esm/types.d.ts +0 -9
  178. package/dist/esm/utils.d.ts +0 -3
  179. package/dist/esm/utils.js +0 -11
  180. package/dist/esm/utils.js.map +0 -1
@@ -1,162 +0,0 @@
1
- import { Store } from '@tanstack/store';
2
- import { AnyFunction } from './types.js';
3
- export interface DebouncerState<TFn extends AnyFunction> {
4
- /**
5
- * Whether the debouncer can execute on the leading edge of the timeout
6
- */
7
- canLeadingExecute: boolean;
8
- /**
9
- * Number of function executions that have been completed
10
- */
11
- executionCount: number;
12
- /**
13
- * Whether the debouncer is waiting for the timeout to trigger execution
14
- */
15
- isPending: boolean;
16
- /**
17
- * The arguments from the most recent call to maybeExecute
18
- */
19
- lastArgs: Parameters<TFn> | undefined;
20
- /**
21
- * Number of times maybeExecute has been called (for reduction calculations)
22
- */
23
- maybeExecuteCount: number;
24
- /**
25
- * Current execution status - 'idle' when not active, 'pending' when waiting for timeout
26
- */
27
- status: 'disabled' | 'idle' | 'pending';
28
- }
29
- /**
30
- * Options for configuring a debounced function
31
- */
32
- export interface DebouncerOptions<TFn extends AnyFunction> {
33
- /**
34
- * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
35
- * Can be a boolean or a function that returns a boolean.
36
- * Defaults to true.
37
- */
38
- enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean);
39
- /**
40
- * Initial state for the debouncer
41
- */
42
- initialState?: Partial<DebouncerState<TFn>>;
43
- /**
44
- * A key to identify the debouncer.
45
- * If provided, the debouncer will be identified by this key in the devtools and PacerProvider if applicable.
46
- */
47
- key?: string;
48
- /**
49
- * Whether to execute on the leading edge of the timeout.
50
- * The first call will execute immediately and the rest will wait the delay.
51
- * Defaults to false.
52
- */
53
- leading?: boolean;
54
- /**
55
- * Callback function that is called after the function is executed
56
- */
57
- onExecute?: (args: Parameters<TFn>, debouncer: Debouncer<TFn>) => void;
58
- /**
59
- * Whether to execute on the trailing edge of the timeout.
60
- * Defaults to true.
61
- */
62
- trailing?: boolean;
63
- /**
64
- * Delay in milliseconds before executing the function.
65
- * Can be a number or a function that returns a number.
66
- * Defaults to 0ms
67
- */
68
- wait: number | ((debouncer: Debouncer<TFn>) => number);
69
- }
70
- /**
71
- * Utility function for sharing common `DebouncerOptions` options between different `Debouncer` instances.
72
- */
73
- export declare function debouncerOptions<TFn extends AnyFunction = AnyFunction, TOptions extends Partial<DebouncerOptions<TFn>> = Partial<DebouncerOptions<TFn>>>(options: TOptions): TOptions;
74
- /**
75
- * A class that creates a debounced function.
76
- *
77
- * Debouncing ensures that a function is only executed after a certain amount of time has passed
78
- * since its last invocation. This is useful for handling frequent events like window resizing,
79
- * scroll events, or input changes where you want to limit the rate of execution.
80
- * 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.
81
- *
82
- * The debounced function can be configured to execute either at the start of the delay period
83
- * (leading edge) or at the end (trailing edge, default). Each new call during the wait period
84
- * will reset the timer.
85
- *
86
- * State Management:
87
- * - Uses TanStack Store for reactive state management
88
- * - Use `initialState` to provide initial state values when creating the debouncer
89
- * - Use `onExecute` callback to react to function execution and implement custom logic
90
- * - The state includes canLeadingExecute, execution count, and isPending status
91
- * - State can be accessed via `debouncer.store.state` when using the class directly
92
- * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`
93
- *
94
- * @example
95
- * ```ts
96
- * const debouncer = new Debouncer((value: string) => {
97
- * saveToDatabase(value);
98
- * }, { wait: 500 });
99
- *
100
- * // Will only save after 500ms of no new input
101
- * inputElement.addEventListener('input', () => {
102
- * debouncer.maybeExecute(inputElement.value);
103
- * });
104
- * ```
105
- */
106
- export declare class Debouncer<TFn extends AnyFunction> {
107
- #private;
108
- fn: TFn;
109
- readonly store: Store<Readonly<DebouncerState<TFn>>>;
110
- key: string | undefined;
111
- options: DebouncerOptions<TFn>;
112
- constructor(fn: TFn, initialOptions: DebouncerOptions<TFn>);
113
- /**
114
- * Updates the debouncer options
115
- */
116
- setOptions: (newOptions: Partial<DebouncerOptions<TFn>>) => void;
117
- /**
118
- * Attempts to execute the debounced function
119
- * If a call is already in progress, it will be queued
120
- */
121
- maybeExecute: (...args: Parameters<TFn>) => void;
122
- /**
123
- * Processes the current pending execution immediately
124
- */
125
- flush: () => void;
126
- /**
127
- * Cancels any pending execution
128
- */
129
- cancel: () => void;
130
- /**
131
- * Resets the debouncer state to its default values
132
- */
133
- reset: () => void;
134
- }
135
- /**
136
- * Creates a debounced function that delays invoking the provided function until after a specified wait time.
137
- * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.
138
- *
139
- * 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.
140
- *
141
- * If leading option is true, the function will execute immediately on the first call, then wait the delay
142
- * before allowing another execution.
143
- *
144
- * State Management:
145
- * - Uses TanStack Store for reactive state management
146
- * - Use `initialState` to provide initial state values when creating the debouncer
147
- * - Use `onExecute` callback to react to function execution and implement custom logic
148
- * - The state includes canLeadingExecute, execution count, and isPending status
149
- * - State can be accessed via the underlying Debouncer instance's `store.state` property
150
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
151
- *
152
- * @example
153
- * ```ts
154
- * const debounced = debounce(() => {
155
- * saveChanges();
156
- * }, { wait: 1000 });
157
- *
158
- * // Called repeatedly but executes at most once per second
159
- * inputElement.addEventListener('input', debounced);
160
- * ```
161
- */
162
- export declare function debounce<TFn extends AnyFunction>(fn: TFn, initialOptions: DebouncerOptions<TFn>): (...args: Parameters<TFn>) => void;
@@ -1,137 +0,0 @@
1
- import { Store } from "@tanstack/store";
2
- import { parseFunctionOrValue } from "./utils.js";
3
- import { emitChange, pacerEventClient } from "./event-client.js";
4
- function getDefaultDebouncerState() {
5
- return {
6
- canLeadingExecute: true,
7
- executionCount: 0,
8
- isPending: false,
9
- lastArgs: void 0,
10
- status: "idle",
11
- maybeExecuteCount: 0
12
- };
13
- }
14
- function debouncerOptions(options) {
15
- return options;
16
- }
17
- const defaultOptions = {
18
- enabled: true,
19
- leading: false,
20
- trailing: true,
21
- wait: 0
22
- };
23
- class Debouncer {
24
- constructor(fn, initialOptions) {
25
- this.fn = fn;
26
- this.store = new Store(
27
- getDefaultDebouncerState()
28
- );
29
- this.setOptions = (newOptions) => {
30
- this.options = { ...this.options, ...newOptions };
31
- if (!this.#getEnabled()) {
32
- this.cancel();
33
- }
34
- };
35
- this.#setState = (newState) => {
36
- this.store.setState((state) => {
37
- const combinedState = {
38
- ...state,
39
- ...newState
40
- };
41
- const { isPending } = combinedState;
42
- return {
43
- ...combinedState,
44
- status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
45
- };
46
- });
47
- emitChange("Debouncer", this);
48
- };
49
- this.#getEnabled = () => {
50
- return !!parseFunctionOrValue(this.options.enabled, this);
51
- };
52
- this.#getWait = () => {
53
- return parseFunctionOrValue(this.options.wait, this);
54
- };
55
- this.maybeExecute = (...args) => {
56
- if (!this.#getEnabled()) return void 0;
57
- this.#setState({
58
- maybeExecuteCount: this.store.state.maybeExecuteCount + 1
59
- });
60
- let _didLeadingExecute = false;
61
- if (this.options.leading && this.store.state.canLeadingExecute) {
62
- this.#setState({ canLeadingExecute: false });
63
- _didLeadingExecute = true;
64
- this.#execute(...args);
65
- }
66
- if (this.options.trailing) {
67
- this.#setState({ isPending: true, lastArgs: args });
68
- }
69
- if (this.#timeoutId) clearTimeout(this.#timeoutId);
70
- this.#timeoutId = setTimeout(() => {
71
- this.#setState({ canLeadingExecute: true });
72
- if (this.options.trailing && !_didLeadingExecute) {
73
- this.#execute(...args);
74
- }
75
- }, this.#getWait());
76
- };
77
- this.#execute = (...args) => {
78
- if (!this.#getEnabled()) return void 0;
79
- this.fn(...args);
80
- this.#setState({
81
- executionCount: this.store.state.executionCount + 1,
82
- isPending: false,
83
- lastArgs: void 0
84
- });
85
- this.options.onExecute?.(args, this);
86
- };
87
- this.flush = () => {
88
- if (this.store.state.isPending && this.store.state.lastArgs) {
89
- this.#clearTimeout();
90
- this.#execute(...this.store.state.lastArgs);
91
- }
92
- };
93
- this.#clearTimeout = () => {
94
- if (this.#timeoutId) {
95
- clearTimeout(this.#timeoutId);
96
- this.#timeoutId = void 0;
97
- }
98
- };
99
- this.cancel = () => {
100
- this.#clearTimeout();
101
- this.#setState({
102
- canLeadingExecute: true,
103
- isPending: false
104
- });
105
- };
106
- this.reset = () => {
107
- this.#setState(getDefaultDebouncerState());
108
- };
109
- this.key = initialOptions.key;
110
- this.options = {
111
- ...defaultOptions,
112
- ...initialOptions
113
- };
114
- this.#setState(this.options.initialState ?? {});
115
- pacerEventClient.on("d-Debouncer", (event) => {
116
- if (event.payload.key !== this.key) return;
117
- this.#setState(event.payload.store.state);
118
- this.setOptions(event.payload.options);
119
- });
120
- }
121
- #timeoutId;
122
- #setState;
123
- #getEnabled;
124
- #getWait;
125
- #execute;
126
- #clearTimeout;
127
- }
128
- function debounce(fn, initialOptions) {
129
- const debouncer = new Debouncer(fn, initialOptions);
130
- return debouncer.maybeExecute;
131
- }
132
- export {
133
- Debouncer,
134
- debounce,
135
- debouncerOptions
136
- };
137
- //# sourceMappingURL=debouncer.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"debouncer.js","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: NodeJS.Timeout | 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 pacerEventClient.on('d-Debouncer', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state as DebouncerState<TFn>)\n this.setOptions(event.payload.options)\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"],"names":[],"mappings":";;;AAgCA,SAAS,2BAEgB;AACvB,SAAO;AAAA,IACL,mBAAmB;AAAA,IACnB,gBAAgB;AAAA,IAChB,WAAW;AAAA,IACX,UAAU;AAAA,IACV,Q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IAAA;AAEL,SAAK,UAAU,KAAK,QAAQ,gBAAgB,CAAA,CAAE;AAE9C,qBAAiB,GAAG,eAAe,CAAC,UAAU;AAC5C,UAAI,MAAM,QAAQ,QAAQ,KAAK,IAAK;AACpC,WAAK,UAAU,MAAM,QAAQ,MAAM,KAA4B;AAC/D,WAAK,WAAW,MAAM,QAAQ,OAAO;AAAA,IACvC,CAAC;AAAA,EACH;AAAA,EAlBA;AAAA,EAgCA;AAAA,EAsBA;AAAA,EAOA;AAAA,EAyCA;AAAA,EAqBA;AAwBF;AA6BO,SAAS,SACd,IACA,gBACoC;AACpC,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAClD,SAAO,UAAU;AACnB;"}
@@ -1,45 +0,0 @@
1
- import { EventClient } from '@tanstack/devtools-event-client';
2
- import { AsyncBatcher } from './async-batcher.js';
3
- import { AsyncDebouncer } from './async-debouncer.js';
4
- import { AsyncQueuer } from './async-queuer.js';
5
- import { AsyncRateLimiter } from './async-rate-limiter.js';
6
- import { AsyncRetryer } from './async-retryer.js';
7
- import { AsyncThrottler } from './async-throttler.js';
8
- import { Debouncer } from './debouncer.js';
9
- import { Batcher } from './batcher.js';
10
- import { Queuer } from './queuer.js';
11
- import { RateLimiter } from './rate-limiter.js';
12
- import { Throttler } from './throttler.js';
13
- export interface PacerEventMap {
14
- 'pacer:d-AsyncBatcher': AsyncBatcher<any>;
15
- 'pacer:d-AsyncDebouncer': AsyncDebouncer<any>;
16
- 'pacer:d-AsyncQueuer': AsyncQueuer<any>;
17
- 'pacer:d-AsyncRateLimiter': AsyncRateLimiter<any>;
18
- 'pacer:d-AsyncRetryer': AsyncRetryer<any>;
19
- 'pacer:d-AsyncThrottler': AsyncThrottler<any>;
20
- 'pacer:d-Batcher': Batcher<any>;
21
- 'pacer:d-Debouncer': Debouncer<any>;
22
- 'pacer:d-Queuer': Queuer<any>;
23
- 'pacer:d-RateLimiter': RateLimiter<any>;
24
- 'pacer:d-Throttler': Throttler<any>;
25
- 'pacer:AsyncBatcher': AsyncBatcher<any>;
26
- 'pacer:AsyncDebouncer': AsyncDebouncer<any>;
27
- 'pacer:AsyncQueuer': AsyncQueuer<any>;
28
- 'pacer:AsyncRateLimiter': AsyncRateLimiter<any>;
29
- 'pacer:AsyncRetryer': AsyncRetryer<any>;
30
- 'pacer:AsyncThrottler': AsyncThrottler<any>;
31
- 'pacer:Batcher': Batcher<any>;
32
- 'pacer:Debouncer': Debouncer<any>;
33
- 'pacer:Queuer': Queuer<any>;
34
- 'pacer:RateLimiter': RateLimiter<any>;
35
- 'pacer:Throttler': Throttler<any>;
36
- }
37
- export type PacerEventName = keyof PacerEventMap extends `pacer:${infer T}` ? T : never;
38
- declare class PacerEventClient extends EventClient<PacerEventMap> {
39
- constructor(props?: {
40
- debug: boolean;
41
- });
42
- }
43
- export declare const emitChange: <TSuffix extends Extract<keyof PacerEventMap, `${string}:${string}`> extends `${string}:${infer S}` ? S : never>(event: TSuffix, payload: PacerEventMap[`pacer:${TSuffix}`]) => void;
44
- export declare const pacerEventClient: PacerEventClient;
45
- export {};
@@ -1,20 +0,0 @@
1
- import { EventClient } from "@tanstack/devtools-event-client";
2
- class PacerEventClient extends EventClient {
3
- constructor(props) {
4
- super({
5
- pluginId: "pacer",
6
- debug: props?.debug
7
- });
8
- }
9
- }
10
- const emitChange = (event, payload) => {
11
- if (payload.key) {
12
- pacerEventClient.emit(event, payload);
13
- }
14
- };
15
- const pacerEventClient = new PacerEventClient();
16
- export {
17
- emitChange,
18
- pacerEventClient
19
- };
20
- //# sourceMappingURL=event-client.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"event-client.js","sources":["../../src/event-client.ts"],"sourcesContent":["import { EventClient } from '@tanstack/devtools-event-client'\nimport type { AsyncBatcher } from './async-batcher'\nimport type { AsyncDebouncer } from './async-debouncer'\nimport type { AsyncQueuer } from './async-queuer'\nimport type { AsyncRateLimiter } from './async-rate-limiter'\nimport type { AsyncRetryer } from './async-retryer'\nimport type { AsyncThrottler } from './async-throttler'\nimport type { Debouncer } from './debouncer'\nimport type { Batcher } from './batcher'\nimport type { Queuer } from './queuer'\nimport type { RateLimiter } from './rate-limiter'\nimport type { Throttler } from './throttler'\n\nexport interface PacerEventMap {\n 'pacer:d-AsyncBatcher': AsyncBatcher<any>\n 'pacer:d-AsyncDebouncer': AsyncDebouncer<any>\n 'pacer:d-AsyncQueuer': AsyncQueuer<any>\n 'pacer:d-AsyncRateLimiter': AsyncRateLimiter<any>\n 'pacer:d-AsyncRetryer': AsyncRetryer<any>\n 'pacer:d-AsyncThrottler': AsyncThrottler<any>\n 'pacer:d-Batcher': Batcher<any>\n 'pacer:d-Debouncer': Debouncer<any>\n 'pacer:d-Queuer': Queuer<any>\n 'pacer:d-RateLimiter': RateLimiter<any>\n 'pacer:d-Throttler': Throttler<any>\n 'pacer:AsyncBatcher': AsyncBatcher<any>\n 'pacer:AsyncDebouncer': AsyncDebouncer<any>\n 'pacer:AsyncQueuer': AsyncQueuer<any>\n 'pacer:AsyncRateLimiter': AsyncRateLimiter<any>\n 'pacer:AsyncRetryer': AsyncRetryer<any>\n 'pacer:AsyncThrottler': AsyncThrottler<any>\n 'pacer:Batcher': Batcher<any>\n 'pacer:Debouncer': Debouncer<any>\n 'pacer:Queuer': Queuer<any>\n 'pacer:RateLimiter': RateLimiter<any>\n 'pacer:Throttler': Throttler<any>\n}\n\nexport type PacerEventName = keyof PacerEventMap extends `pacer:${infer T}`\n ? T\n : never\n\nclass PacerEventClient extends EventClient<PacerEventMap> {\n constructor(props?: { debug: boolean }) {\n super({\n pluginId: 'pacer',\n debug: props?.debug,\n })\n }\n}\n\nexport const emitChange = <\n TSuffix extends Extract<\n keyof PacerEventMap,\n `${string}:${string}`\n > extends `${string}:${infer S}`\n ? S\n : never,\n>(\n event: TSuffix,\n payload: PacerEventMap[`pacer:${TSuffix}`],\n) => {\n if (payload.key) {\n pacerEventClient.emit(event, payload)\n }\n}\n\nexport const pacerEventClient = new PacerEventClient()\n"],"names":[],"mappings":";AA0CA,MAAM,yBAAyB,YAA2B;AAAA,EACxD,YAAY,OAA4B;AACtC,UAAM;AAAA,MACJ,UAAU;AAAA,MACV,OAAO,OAAO;AAAA,IAAA,CACf;AAAA,EACH;AACF;AAEO,MAAM,aAAa,CAQxB,OACA,YACG;AACH,MAAI,QAAQ,KAAK;AACf,qBAAiB,KAAK,OAAO,OAAO;AAAA,EACtC;AACF;AAEO,MAAM,mBAAmB,IAAI,iBAAA;"}
@@ -1,15 +0,0 @@
1
- export * from './async-batcher.js';
2
- export * from './async-debouncer.js';
3
- export * from './async-queuer.js';
4
- export * from './async-rate-limiter.js';
5
- export * from './async-retryer.js';
6
- export * from './async-throttler.js';
7
- export * from './batcher.js';
8
- export * from './debouncer.js';
9
- export * from './queuer.js';
10
- export * from './rate-limiter.js';
11
- export * from './throttler.js';
12
- export * from './types.js';
13
- export * from './utils.js';
14
- export { pacerEventClient } from './event-client.js';
15
- export type { PacerEventMap, PacerEventName } from './event-client.js';
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;"}