@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,215 +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/throttler.ts
7
- function getDefaultThrottlerState() {
8
- return {
9
- executionCount: 0,
10
- isPending: false,
11
- lastArgs: void 0,
12
- lastExecutionTime: 0,
13
- nextExecutionTime: 0,
14
- status: "idle",
15
- maybeExecuteCount: 0
16
- };
17
- }
18
- /**
19
- * Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.
20
- */
21
- function throttlerOptions(options) {
22
- return options;
23
- }
24
- const defaultOptions = {
25
- enabled: true,
26
- leading: true,
27
- trailing: true,
28
- wait: 0
29
- };
30
- /**
31
- * A class that creates a throttled function.
32
- *
33
- * Throttling ensures a function is called at most once within a specified time window.
34
- * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent
35
- * execution timing regardless of call frequency.
36
- * This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
37
- *
38
- * Supports both leading and trailing edge execution:
39
- * - Leading: Execute immediately on first call (default: true)
40
- * - Trailing: Execute after wait period if called during throttle (default: true)
41
- *
42
- * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.
43
- *
44
- * State Management:
45
- * - Uses TanStack Store for reactive state management
46
- * - Use `initialState` to provide initial state values when creating the throttler
47
- * - Use `onExecute` callback to react to function execution and implement custom logic
48
- * - The state includes execution count, last execution time, pending status, and more
49
- * - State can be accessed via `throttler.store.state` when using the class directly
50
- * - When using framework adapters (React/Solid), state is accessed from `throttler.state`
51
- *
52
- * @example
53
- * ```ts
54
- * const throttler = new Throttler(
55
- * (id: string) => api.getData(id),
56
- * { wait: 1000 } // Execute at most once per second
57
- * );
58
- *
59
- * // First call executes immediately
60
- * throttler.maybeExecute('123');
61
- *
62
- * // Subsequent calls within 1000ms are throttled
63
- * throttler.maybeExecute('123'); // Throttled
64
- * ```
65
- */
66
- var Throttler = class {
67
- #timeoutId;
68
- constructor(fn, initialOptions) {
69
- this.fn = fn;
70
- this.store = new _tanstack_store.Store(getDefaultThrottlerState());
71
- this.setOptions = (newOptions) => {
72
- this.options = {
73
- ...this.options,
74
- ...newOptions
75
- };
76
- if (!this.#getEnabled()) this.cancel();
77
- };
78
- this.#setState = (newState) => {
79
- this.store.setState((state) => {
80
- const combinedState = {
81
- ...state,
82
- ...newState
83
- };
84
- const { isPending } = combinedState;
85
- return {
86
- ...combinedState,
87
- status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
88
- };
89
- });
90
- require_event_client.emitChange("Throttler", this);
91
- };
92
- this.#getEnabled = () => {
93
- return !!require_utils.parseFunctionOrValue(this.options.enabled, this);
94
- };
95
- this.#getWait = () => {
96
- return require_utils.parseFunctionOrValue(this.options.wait, this);
97
- };
98
- this.maybeExecute = (...args) => {
99
- this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
100
- const now = Date.now();
101
- const timeSinceLastExecution = now - this.store.state.lastExecutionTime;
102
- const wait = this.#getWait();
103
- if (this.options.leading && timeSinceLastExecution >= wait) this.#execute(...args);
104
- else {
105
- this.#setState({ lastArgs: args });
106
- if (!this.#timeoutId && this.options.trailing) {
107
- const timeoutDuration = wait - (this.store.state.lastExecutionTime ? now - this.store.state.lastExecutionTime : 0);
108
- this.#setState({ isPending: true });
109
- this.#timeoutId = setTimeout(() => {
110
- const { lastArgs } = this.store.state;
111
- if (lastArgs !== void 0) this.#execute(...lastArgs);
112
- }, timeoutDuration);
113
- }
114
- }
115
- };
116
- this.#execute = (...args) => {
117
- if (!this.#getEnabled()) return;
118
- this.fn(...args);
119
- const lastExecutionTime = Date.now();
120
- const nextExecutionTime = lastExecutionTime + this.#getWait();
121
- this.#clearTimeout();
122
- this.#setState({
123
- executionCount: this.store.state.executionCount + 1,
124
- lastExecutionTime,
125
- nextExecutionTime,
126
- isPending: false,
127
- lastArgs: void 0
128
- });
129
- this.options.onExecute?.(args, this);
130
- setTimeout(() => {
131
- if (!this.store.state.isPending) this.#setState({ nextExecutionTime: void 0 });
132
- }, this.#getWait());
133
- };
134
- this.flush = () => {
135
- if (this.store.state.isPending && this.store.state.lastArgs) this.#execute(...this.store.state.lastArgs);
136
- };
137
- this.#clearTimeout = () => {
138
- if (this.#timeoutId) {
139
- clearTimeout(this.#timeoutId);
140
- this.#timeoutId = void 0;
141
- }
142
- };
143
- this.cancel = () => {
144
- this.#clearTimeout();
145
- this.#setState({
146
- lastArgs: void 0,
147
- isPending: false
148
- });
149
- };
150
- this.reset = () => {
151
- this.#setState(getDefaultThrottlerState());
152
- };
153
- this.key = initialOptions.key;
154
- this.options = {
155
- ...defaultOptions,
156
- ...initialOptions
157
- };
158
- this.#setState(this.options.initialState ?? {});
159
- if (this.key) require_event_client.pacerEventClient.on("d-Throttler", (event) => {
160
- if (event.payload.key !== this.key) return;
161
- this.#setState(event.payload.store.state);
162
- this.setOptions(event.payload.options);
163
- });
164
- }
165
- #setState;
166
- #getEnabled;
167
- #getWait;
168
- #execute;
169
- #clearTimeout;
170
- };
171
- /**
172
- * Creates a throttled function that limits how often the provided function can execute.
173
- *
174
- * This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
175
- *
176
- * Throttling ensures a function executes at most once within a specified time window,
177
- * regardless of how many times it is called. This is useful for rate-limiting
178
- * expensive operations or UI updates.
179
- *
180
- * The throttled function can be configured to execute on the leading and/or trailing
181
- * edge of the throttle window via options.
182
- *
183
- * For handling bursts of events, consider using debounce() instead. For hard execution
184
- * limits, consider using rateLimit().
185
- *
186
- * State Management:
187
- * - Uses TanStack Store for reactive state management
188
- * - Use `initialState` to provide initial state values when creating the throttler
189
- * - Use `onExecute` callback to react to function execution and implement custom logic
190
- * - The state includes execution count, last execution time, pending status, and more
191
- * - State can be accessed via the underlying Throttler instance's `store.state` property
192
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
193
- *
194
- * @example
195
- * ```ts
196
- * // Basic throttling - max once per second
197
- * const throttled = throttle(updateUI, { wait: 1000 });
198
- *
199
- * // Configure leading/trailing execution
200
- * const throttled = throttle(saveData, {
201
- * wait: 2000,
202
- * leading: true, // Execute immediately on first call
203
- * trailing: true // Execute again after delay if called during wait
204
- * });
205
- * ```
206
- */
207
- function throttle(fn, initialOptions) {
208
- return new Throttler(fn, initialOptions).maybeExecute;
209
- }
210
-
211
- //#endregion
212
- exports.Throttler = Throttler;
213
- exports.throttle = throttle;
214
- exports.throttlerOptions = throttlerOptions;
215
- //# sourceMappingURL=throttler.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"throttler.cjs","names":["Store","#getEnabled","parseFunctionOrValue","#setState","#getWait","#execute","#timeoutId","#clearTimeout"],"sources":["../src/throttler.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 ThrottlerState<TFn extends AnyFunction> {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the throttler 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 * Timestamp of the last function execution in milliseconds\n */\n lastExecutionTime: number\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Timestamp when the next execution can occur in milliseconds\n */\n nextExecutionTime: number | undefined\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultThrottlerState<\n TFn extends AnyFunction,\n>(): ThrottlerState<TFn> {\n return {\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n lastExecutionTime: 0,\n nextExecutionTime: 0,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions<TFn extends AnyFunction> {\n /**\n * Whether the throttler 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 | ((throttler: Throttler<TFn>) => boolean)\n /**\n * Initial state for the throttler\n */\n initialState?: Partial<ThrottlerState<TFn>>\n /**\n * A key to identify the throttler.\n * If provided, the throttler 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 * Defaults to true.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, throttler: Throttler<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Time window in milliseconds during which the function can only be executed once.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((throttler: Throttler<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.\n */\nexport function throttlerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<ThrottlerOptions<TFn>> = Partial<\n ThrottlerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<ThrottlerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\n enabled: true,\n leading: true,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a throttled function.\n *\n * Throttling ensures a function is called at most once within a specified time window.\n * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent\n * execution timing regardless of call frequency.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * Supports both leading and trailing edge execution:\n * - Leading: Execute immediately on first call (default: true)\n * - Trailing: Execute after wait period if called during throttle (default: true)\n *\n * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via `throttler.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `throttler.state`\n *\n * @example\n * ```ts\n * const throttler = new Throttler(\n * (id: string) => api.getData(id),\n * { wait: 1000 } // Execute at most once per second\n * );\n *\n * // First call executes immediately\n * throttler.maybeExecute('123');\n *\n * // Subsequent calls within 1000ms are throttled\n * throttler.maybeExecute('123'); // Throttled\n * ```\n */\nexport class Throttler<TFn extends AnyFunction> {\n readonly store: Store<Readonly<ThrottlerState<TFn>>> = new Store(\n getDefaultThrottlerState<TFn>(),\n )\n key: string | undefined\n options: ThrottlerOptions<TFn>\n #timeoutId: ReturnType<typeof setTimeout> | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: ThrottlerOptions<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-Throttler', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<ThrottlerState<TFn>>,\n )\n this.setOptions(event.payload.options as Partial<ThrottlerOptions<TFn>>)\n })\n }\n }\n\n /**\n * Updates the throttler options\n */\n setOptions = (newOptions: Partial<ThrottlerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the throttler is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<ThrottlerState<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('Throttler', this)\n }\n\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Attempts to execute the throttled function. The execution behavior depends on the throttler options:\n *\n * - If enough time has passed since the last execution (>= wait period):\n * - With leading=true: Executes immediately\n * - With leading=false: Waits for the next trailing execution\n *\n * - If within the wait period:\n * - With trailing=true: Schedules execution for end of wait period\n * - With trailing=false: Drops the execution\n *\n * @example\n * ```ts\n * const throttled = new Throttler(fn, { wait: 1000 });\n *\n * // First call executes immediately\n * throttled.maybeExecute('a', 'b');\n *\n * // Call during wait period - gets throttled\n * throttled.maybeExecute('c', 'd');\n * ```\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n const now = Date.now()\n const timeSinceLastExecution = now - this.store.state.lastExecutionTime\n const wait = this.#getWait()\n\n // Handle leading execution\n if (this.options.leading && timeSinceLastExecution >= wait) {\n this.#execute(...args)\n } else {\n // Store the most recent arguments for potential trailing execution\n this.#setState({\n lastArgs: args,\n })\n // Set up trailing execution if not already scheduled\n if (!this.#timeoutId && this.options.trailing) {\n // prevent large number if lastExecutionTime is undefined\n const _timeSinceLastExecution = this.store.state.lastExecutionTime\n ? now - this.store.state.lastExecutionTime\n : 0\n const timeoutDuration = wait - _timeSinceLastExecution\n this.#setState({ isPending: true })\n this.#timeoutId = setTimeout(() => {\n const { lastArgs } = this.store.state\n if (lastArgs !== undefined) {\n this.#execute(...lastArgs)\n }\n }, timeoutDuration)\n }\n }\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n this.fn(...args) // EXECUTE!\n const lastExecutionTime = Date.now()\n const nextExecutionTime = lastExecutionTime + this.#getWait()\n this.#clearTimeout()\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n lastExecutionTime,\n nextExecutionTime,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, this)\n setTimeout(() => {\n if (!this.store.state.isPending) {\n this.#setState({ nextExecutionTime: undefined })\n }\n }, this.#getWait())\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.#execute(...this.store.state.lastArgs)\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 trailing execution and clears internal state.\n *\n * If a trailing execution is scheduled (due to throttling with trailing=true),\n * this will prevent that execution from occurring. The internal timeout and\n * stored arguments will be cleared.\n *\n * Has no effect if there is no pending execution.\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n lastArgs: undefined,\n isPending: false,\n })\n }\n\n /**\n * Resets the throttler state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultThrottlerState<TFn>())\n }\n}\n\n/**\n * Creates a throttled function that limits how often the provided function can execute.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * The throttled function can be configured to execute on the leading and/or trailing\n * edge of the throttle window via options.\n *\n * For handling bursts of events, consider using debounce() instead. For hard execution\n * limits, consider using rateLimit().\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via the underlying Throttler 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 * // Basic throttling - max once per second\n * const throttled = throttle(updateUI, { wait: 1000 });\n *\n * // Configure leading/trailing execution\n * const throttled = throttle(saveData, {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: true // Execute again after delay if called during wait\n * });\n * ```\n */\nexport function throttle<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute\n}\n"],"mappings":";;;;;;AAoCA,SAAS,2BAEgB;CACvB,OAAO;EACL,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,mBAAmB;EACnB,mBAAmB;EACnB,QAAQ;EACR,mBAAmB;CACrB;AACF;;;;AA8CA,SAAgB,iBAKd,SAA6B;CAC7B,OAAO;AACT;AAEA,MAAM,iBAGF;CACF,SAAS;CACT,SAAS;CACT,UAAU;CACV,MAAM;AACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,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;2BAE6B;GAC3B,OAAO,CAAC,CAACC,mCAAqB,KAAK,QAAQ,SAAS,IAA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M,MAAM,UACjD,KAAKC,SAAS,GAAG,KAAK,MAAM,MAAM,QAAQ;EAE9C;6BAE4B;GAC1B,IAAI,KAAKC,YAAY;IACnB,aAAa,KAAKA,UAAU;IAC5B,KAAKA,aAAa;GACpB;EACF;sBAWqB;GACnB,KAAKC,cAAc;GACnB,KAAKJ,UAAU;IACb,UAAU;IACV,WAAW;GACb,CAAC;EACH;qBAKoB;GAClB,KAAKA,UAAU,yBAA8B,CAAC;EAChD;EA7KE,KAAK,MAAM,eAAe;EAC1B,KAAK,UAAU;GACb,GAAG;GACH,GAAG;EACL;EACA,KAAKA,UAAU,KAAK,QAAQ,gBAAgB,CAAC,CAAC;EAE9C,IAAI,KAAK,KACP,sCAAiB,GAAG,gBAAgB,UAAU;GAC5C,IAAI,MAAM,QAAQ,QAAQ,KAAK,KAAK;GACpC,KAAKA,UACH,MAAM,QAAQ,MAAM,KACtB;GACA,KAAK,WAAW,MAAM,QAAQ,OAAyC;EACzE,CAAC;CAEL;CAcA;CAmBA;CAIA;CA6DA;CA8BA;AA8BF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,SACd,IACA,gBACA;CAEA,OAAO,IADe,UAAU,IAAI,cACrB,CAAC,CAAC;AACnB"}
@@ -1,206 +0,0 @@
1
- import { AnyFunction } from "./types.cjs";
2
- import { Store } from "@tanstack/store";
3
- //#region src/throttler.d.ts
4
- interface ThrottlerState<TFn extends AnyFunction> {
5
- /**
6
- * Number of function executions that have been completed
7
- */
8
- executionCount: number;
9
- /**
10
- * Whether the throttler is waiting for the timeout to trigger execution
11
- */
12
- isPending: boolean;
13
- /**
14
- * The arguments from the most recent call to maybeExecute
15
- */
16
- lastArgs: Parameters<TFn> | undefined;
17
- /**
18
- * Timestamp of the last function execution in milliseconds
19
- */
20
- lastExecutionTime: number;
21
- /**
22
- * Number of times maybeExecute has been called (for reduction calculations)
23
- */
24
- maybeExecuteCount: number;
25
- /**
26
- * Timestamp when the next execution can occur in milliseconds
27
- */
28
- nextExecutionTime: number | undefined;
29
- /**
30
- * Current execution status - 'idle' when not active, 'pending' when waiting for timeout
31
- */
32
- status: 'disabled' | 'idle' | 'pending';
33
- }
34
- /**
35
- * Options for configuring a throttled function
36
- */
37
- interface ThrottlerOptions<TFn extends AnyFunction> {
38
- /**
39
- * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
40
- * Can be a boolean or a function that returns a boolean.
41
- * Defaults to true.
42
- */
43
- enabled?: boolean | ((throttler: Throttler<TFn>) => boolean);
44
- /**
45
- * Initial state for the throttler
46
- */
47
- initialState?: Partial<ThrottlerState<TFn>>;
48
- /**
49
- * A key to identify the throttler.
50
- * If provided, the throttler will be identified by this key in the devtools and PacerProvider if applicable.
51
- */
52
- key?: string;
53
- /**
54
- * Whether to execute on the leading edge of the timeout.
55
- * Defaults to true.
56
- */
57
- leading?: boolean;
58
- /**
59
- * Callback function that is called after the function is executed
60
- */
61
- onExecute?: (args: Parameters<TFn>, throttler: Throttler<TFn>) => void;
62
- /**
63
- * Whether to execute on the trailing edge of the timeout.
64
- * Defaults to true.
65
- */
66
- trailing?: boolean;
67
- /**
68
- * Time window in milliseconds during which the function can only be executed once.
69
- * Can be a number or a function that returns a number.
70
- * Defaults to 0ms
71
- */
72
- wait: number | ((throttler: Throttler<TFn>) => number);
73
- }
74
- /**
75
- * Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.
76
- */
77
- declare function throttlerOptions<TFn extends AnyFunction = AnyFunction, TOptions extends Partial<ThrottlerOptions<TFn>> = Partial<ThrottlerOptions<TFn>>>(options: TOptions): TOptions;
78
- /**
79
- * A class that creates a throttled function.
80
- *
81
- * Throttling ensures a function is called at most once within a specified time window.
82
- * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent
83
- * execution timing regardless of call frequency.
84
- * This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
85
- *
86
- * Supports both leading and trailing edge execution:
87
- * - Leading: Execute immediately on first call (default: true)
88
- * - Trailing: Execute after wait period if called during throttle (default: true)
89
- *
90
- * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.
91
- *
92
- * State Management:
93
- * - Uses TanStack Store for reactive state management
94
- * - Use `initialState` to provide initial state values when creating the throttler
95
- * - Use `onExecute` callback to react to function execution and implement custom logic
96
- * - The state includes execution count, last execution time, pending status, and more
97
- * - State can be accessed via `throttler.store.state` when using the class directly
98
- * - When using framework adapters (React/Solid), state is accessed from `throttler.state`
99
- *
100
- * @example
101
- * ```ts
102
- * const throttler = new Throttler(
103
- * (id: string) => api.getData(id),
104
- * { wait: 1000 } // Execute at most once per second
105
- * );
106
- *
107
- * // First call executes immediately
108
- * throttler.maybeExecute('123');
109
- *
110
- * // Subsequent calls within 1000ms are throttled
111
- * throttler.maybeExecute('123'); // Throttled
112
- * ```
113
- */
114
- declare class Throttler<TFn extends AnyFunction> {
115
- #private;
116
- fn: TFn;
117
- readonly store: Store<Readonly<ThrottlerState<TFn>>>;
118
- key: string | undefined;
119
- options: ThrottlerOptions<TFn>;
120
- constructor(fn: TFn, initialOptions: ThrottlerOptions<TFn>);
121
- /**
122
- * Updates the throttler options
123
- */
124
- setOptions: (newOptions: Partial<ThrottlerOptions<TFn>>) => void;
125
- /**
126
- * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
127
- *
128
- * - If enough time has passed since the last execution (>= wait period):
129
- * - With leading=true: Executes immediately
130
- * - With leading=false: Waits for the next trailing execution
131
- *
132
- * - If within the wait period:
133
- * - With trailing=true: Schedules execution for end of wait period
134
- * - With trailing=false: Drops the execution
135
- *
136
- * @example
137
- * ```ts
138
- * const throttled = new Throttler(fn, { wait: 1000 });
139
- *
140
- * // First call executes immediately
141
- * throttled.maybeExecute('a', 'b');
142
- *
143
- * // Call during wait period - gets throttled
144
- * throttled.maybeExecute('c', 'd');
145
- * ```
146
- */
147
- maybeExecute: (...args: Parameters<TFn>) => void;
148
- /**
149
- * Processes the current pending execution immediately
150
- */
151
- flush: () => void;
152
- /**
153
- * Cancels any pending trailing execution and clears internal state.
154
- *
155
- * If a trailing execution is scheduled (due to throttling with trailing=true),
156
- * this will prevent that execution from occurring. The internal timeout and
157
- * stored arguments will be cleared.
158
- *
159
- * Has no effect if there is no pending execution.
160
- */
161
- cancel: () => void;
162
- /**
163
- * Resets the throttler state to its default values
164
- */
165
- reset: () => void;
166
- }
167
- /**
168
- * Creates a throttled function that limits how often the provided function can execute.
169
- *
170
- * This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
171
- *
172
- * Throttling ensures a function executes at most once within a specified time window,
173
- * regardless of how many times it is called. This is useful for rate-limiting
174
- * expensive operations or UI updates.
175
- *
176
- * The throttled function can be configured to execute on the leading and/or trailing
177
- * edge of the throttle window via options.
178
- *
179
- * For handling bursts of events, consider using debounce() instead. For hard execution
180
- * limits, consider using rateLimit().
181
- *
182
- * State Management:
183
- * - Uses TanStack Store for reactive state management
184
- * - Use `initialState` to provide initial state values when creating the throttler
185
- * - Use `onExecute` callback to react to function execution and implement custom logic
186
- * - The state includes execution count, last execution time, pending status, and more
187
- * - State can be accessed via the underlying Throttler instance's `store.state` property
188
- * - When using framework adapters (React/Solid), state is accessed from the hook's state property
189
- *
190
- * @example
191
- * ```ts
192
- * // Basic throttling - max once per second
193
- * const throttled = throttle(updateUI, { wait: 1000 });
194
- *
195
- * // Configure leading/trailing execution
196
- * const throttled = throttle(saveData, {
197
- * wait: 2000,
198
- * leading: true, // Execute immediately on first call
199
- * trailing: true // Execute again after delay if called during wait
200
- * });
201
- * ```
202
- */
203
- declare function throttle<TFn extends AnyFunction>(fn: TFn, initialOptions: ThrottlerOptions<TFn>): (...args: Parameters<TFn>) => void;
204
- //#endregion
205
- export { Throttler, ThrottlerOptions, ThrottlerState, throttle, throttlerOptions };
206
- //# sourceMappingURL=throttler.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"throttler.js","names":["#getEnabled","#setState","#getWait","#execute","#timeoutId","#clearTimeout"],"sources":["../src/throttler.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 ThrottlerState<TFn extends AnyFunction> {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the throttler 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 * Timestamp of the last function execution in milliseconds\n */\n lastExecutionTime: number\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Timestamp when the next execution can occur in milliseconds\n */\n nextExecutionTime: number | undefined\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultThrottlerState<\n TFn extends AnyFunction,\n>(): ThrottlerState<TFn> {\n return {\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n lastExecutionTime: 0,\n nextExecutionTime: 0,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions<TFn extends AnyFunction> {\n /**\n * Whether the throttler 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 | ((throttler: Throttler<TFn>) => boolean)\n /**\n * Initial state for the throttler\n */\n initialState?: Partial<ThrottlerState<TFn>>\n /**\n * A key to identify the throttler.\n * If provided, the throttler 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 * Defaults to true.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, throttler: Throttler<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Time window in milliseconds during which the function can only be executed once.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((throttler: Throttler<TFn>) => number)\n}\n\n/**\n * Utility function for sharing common `ThrottlerOptions` options between different `Throttler` instances.\n */\nexport function throttlerOptions<\n TFn extends AnyFunction = AnyFunction,\n TOptions extends Partial<ThrottlerOptions<TFn>> = Partial<\n ThrottlerOptions<TFn>\n >,\n>(options: TOptions): TOptions {\n return options\n}\n\nconst defaultOptions: Omit<\n Required<ThrottlerOptions<any>>,\n 'initialState' | 'onExecute' | 'key'\n> = {\n enabled: true,\n leading: true,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a throttled function.\n *\n * Throttling ensures a function is called at most once within a specified time window.\n * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent\n * execution timing regardless of call frequency.\n * This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * Supports both leading and trailing edge execution:\n * - Leading: Execute immediately on first call (default: true)\n * - Trailing: Execute after wait period if called during throttle (default: true)\n *\n * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via `throttler.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `throttler.state`\n *\n * @example\n * ```ts\n * const throttler = new Throttler(\n * (id: string) => api.getData(id),\n * { wait: 1000 } // Execute at most once per second\n * );\n *\n * // First call executes immediately\n * throttler.maybeExecute('123');\n *\n * // Subsequent calls within 1000ms are throttled\n * throttler.maybeExecute('123'); // Throttled\n * ```\n */\nexport class Throttler<TFn extends AnyFunction> {\n readonly store: Store<Readonly<ThrottlerState<TFn>>> = new Store(\n getDefaultThrottlerState<TFn>(),\n )\n key: string | undefined\n options: ThrottlerOptions<TFn>\n #timeoutId: ReturnType<typeof setTimeout> | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: ThrottlerOptions<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-Throttler', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(\n event.payload.store.state as Partial<ThrottlerState<TFn>>,\n )\n this.setOptions(event.payload.options as Partial<ThrottlerOptions<TFn>>)\n })\n }\n }\n\n /**\n * Updates the throttler options\n */\n setOptions = (newOptions: Partial<ThrottlerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the throttler is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<ThrottlerState<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('Throttler', this)\n }\n\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Attempts to execute the throttled function. The execution behavior depends on the throttler options:\n *\n * - If enough time has passed since the last execution (>= wait period):\n * - With leading=true: Executes immediately\n * - With leading=false: Waits for the next trailing execution\n *\n * - If within the wait period:\n * - With trailing=true: Schedules execution for end of wait period\n * - With trailing=false: Drops the execution\n *\n * @example\n * ```ts\n * const throttled = new Throttler(fn, { wait: 1000 });\n *\n * // First call executes immediately\n * throttled.maybeExecute('a', 'b');\n *\n * // Call during wait period - gets throttled\n * throttled.maybeExecute('c', 'd');\n * ```\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n const now = Date.now()\n const timeSinceLastExecution = now - this.store.state.lastExecutionTime\n const wait = this.#getWait()\n\n // Handle leading execution\n if (this.options.leading && timeSinceLastExecution >= wait) {\n this.#execute(...args)\n } else {\n // Store the most recent arguments for potential trailing execution\n this.#setState({\n lastArgs: args,\n })\n // Set up trailing execution if not already scheduled\n if (!this.#timeoutId && this.options.trailing) {\n // prevent large number if lastExecutionTime is undefined\n const _timeSinceLastExecution = this.store.state.lastExecutionTime\n ? now - this.store.state.lastExecutionTime\n : 0\n const timeoutDuration = wait - _timeSinceLastExecution\n this.#setState({ isPending: true })\n this.#timeoutId = setTimeout(() => {\n const { lastArgs } = this.store.state\n if (lastArgs !== undefined) {\n this.#execute(...lastArgs)\n }\n }, timeoutDuration)\n }\n }\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n this.fn(...args) // EXECUTE!\n const lastExecutionTime = Date.now()\n const nextExecutionTime = lastExecutionTime + this.#getWait()\n this.#clearTimeout()\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n lastExecutionTime,\n nextExecutionTime,\n isPending: false,\n lastArgs: undefined,\n })\n this.options.onExecute?.(args, this)\n setTimeout(() => {\n if (!this.store.state.isPending) {\n this.#setState({ nextExecutionTime: undefined })\n }\n }, this.#getWait())\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.#execute(...this.store.state.lastArgs)\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 trailing execution and clears internal state.\n *\n * If a trailing execution is scheduled (due to throttling with trailing=true),\n * this will prevent that execution from occurring. The internal timeout and\n * stored arguments will be cleared.\n *\n * Has no effect if there is no pending execution.\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n lastArgs: undefined,\n isPending: false,\n })\n }\n\n /**\n * Resets the throttler state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultThrottlerState<TFn>())\n }\n}\n\n/**\n * Creates a throttled function that limits how often the provided function can execute.\n *\n * This synchronous version is lighter weight and often all you need - upgrade to asyncThrottle when you need promises, retry support, abort/cancel capabilities, or advanced error handling.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * The throttled function can be configured to execute on the leading and/or trailing\n * edge of the throttle window via options.\n *\n * For handling bursts of events, consider using debounce() instead. For hard execution\n * limits, consider using rateLimit().\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the throttler\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes execution count, last execution time, pending status, and more\n * - State can be accessed via the underlying Throttler 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 * // Basic throttling - max once per second\n * const throttled = throttle(updateUI, { wait: 1000 });\n *\n * // Configure leading/trailing execution\n * const throttled = throttle(saveData, {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: true // Execute again after delay if called during wait\n * });\n * ```\n */\nexport function throttle<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute\n}\n"],"mappings":";;;;;AAoCA,SAAS,2BAEgB;CACvB,OAAO;EACL,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,mBAAmB;EACnB,mBAAmB;EACnB,QAAQ;EACR,mBAAmB;CACrB;AACF;;;;AA8CA,SAAgB,iBAKd,SAA6B;CAC7B,OAAO;AACT;AAEA,MAAM,iBAGF;CACF,SAAS;CACT,SAAS;CACT,UAAU;CACV,MAAM;AACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,IAAa,YAAb,MAAgD;CAM9C;CAEA,YACE,AAAO,IACP,gBACA;EAFO;eAR8C,IAAI,MACzD,yB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js DELETED
File without changes
package/dist/types.d.cts DELETED
@@ -1,13 +0,0 @@
1
- //#region src/types.d.ts
2
- /**
3
- * Represents a function that can be called with any arguments and returns any value.
4
- */
5
- type AnyFunction = (...args: Array<any>) => any;
6
- /**
7
- * Represents an asynchronous function that can be called with any arguments and returns a promise.
8
- */
9
- type AnyAsyncFunction = (...args: Array<any>) => Promise<any>;
10
- type OptionalKeys<T, TKey extends keyof T> = Omit<T, TKey> & Partial<Pick<T, TKey>>;
11
- //#endregion
12
- export { AnyAsyncFunction, AnyFunction, OptionalKeys };
13
- //# sourceMappingURL=types.d.cts.map
package/dist/utils.cjs DELETED
@@ -1,13 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- //#region src/utils.ts
3
- function isFunction(value) {
4
- return typeof value === "function";
5
- }
6
- function parseFunctionOrValue(value, ...args) {
7
- return isFunction(value) ? value(...args) : value;
8
- }
9
-
10
- //#endregion
11
- exports.isFunction = isFunction;
12
- exports.parseFunctionOrValue = parseFunctionOrValue;
13
- //# sourceMappingURL=utils.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.cjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\nexport function isFunction<T extends AnyFunction>(value: any): value is T {\n return typeof value === 'function'\n}\n\nexport function parseFunctionOrValue<T, TArgs extends Array<any>>(\n value: T | ((...args: TArgs) => T),\n ...args: TArgs\n): T {\n return isFunction(value) ? value(...args) : value\n}\n"],"mappings":";;AAEA,SAAgB,WAAkC,OAAwB;CACxE,OAAO,OAAO,UAAU;AAC1B;AAEA,SAAgB,qBACd,OACA,GAAG,MACA;CACH,OAAO,WAAW,KAAK,IAAI,MAAM,GAAG,IAAI,IAAI;AAC9C"}
package/dist/utils.d.cts DELETED
@@ -1,7 +0,0 @@
1
- import { AnyFunction } from "./types.cjs";
2
- //#region src/utils.d.ts
3
- declare function isFunction<T extends AnyFunction>(value: any): value is T;
4
- declare function parseFunctionOrValue<T, TArgs extends Array<any>>(value: T | ((...args: TArgs) => T), ...args: TArgs): T;
5
- //#endregion
6
- export { isFunction, parseFunctionOrValue };
7
- //# sourceMappingURL=utils.d.cts.map
package/dist/utils.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\nexport function isFunction<T extends AnyFunction>(value: any): value is T {\n return typeof value === 'function'\n}\n\nexport function parseFunctionOrValue<T, TArgs extends Array<any>>(\n value: T | ((...args: TArgs) => T),\n ...args: TArgs\n): T {\n return isFunction(value) ? value(...args) : value\n}\n"],"mappings":";AAEA,SAAgB,WAAkC,OAAwB;CACxE,OAAO,OAAO,UAAU;AAC1B;AAEA,SAAgB,qBACd,OACA,GAAG,MACA;CACH,OAAO,WAAW,KAAK,IAAI,MAAM,GAAG,IAAI,IAAI;AAC9C"}