@tanstack/pacer 0.14.0 → 0.15.1
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.
- package/dist/cjs/async-batcher.cjs +8 -0
- package/dist/cjs/async-batcher.cjs.map +1 -1
- package/dist/cjs/async-batcher.d.cts +7 -1
- package/dist/cjs/async-debouncer.cjs +15 -3
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +10 -0
- package/dist/cjs/async-queuer.cjs +13 -1
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +10 -0
- package/dist/cjs/async-rate-limiter.cjs +14 -2
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +10 -0
- package/dist/cjs/async-throttler.cjs +13 -1
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +10 -0
- package/dist/cjs/batcher.cjs +8 -0
- package/dist/cjs/batcher.cjs.map +1 -1
- package/dist/cjs/batcher.d.cts +7 -1
- package/dist/cjs/debouncer.cjs +13 -1
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +10 -0
- package/dist/cjs/event-client.cjs +18 -0
- package/dist/cjs/event-client.cjs.map +1 -0
- package/dist/cjs/event-client.d.cts +42 -0
- package/dist/cjs/index.cjs +3 -0
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +2 -0
- package/dist/cjs/queuer.cjs +14 -2
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +10 -0
- package/dist/cjs/rate-limiter.cjs +13 -1
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +10 -0
- package/dist/cjs/throttler.cjs +13 -1
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +10 -0
- package/dist/cjs/utils.cjs +10 -0
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +1 -0
- package/dist/esm/async-batcher.d.ts +7 -1
- package/dist/esm/async-batcher.js +9 -1
- package/dist/esm/async-batcher.js.map +1 -1
- package/dist/esm/async-debouncer.d.ts +10 -0
- package/dist/esm/async-debouncer.js +16 -4
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +10 -0
- package/dist/esm/async-queuer.js +14 -2
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +10 -0
- package/dist/esm/async-rate-limiter.js +15 -3
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +10 -0
- package/dist/esm/async-throttler.js +14 -2
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/batcher.d.ts +7 -1
- package/dist/esm/batcher.js +9 -1
- package/dist/esm/batcher.js.map +1 -1
- package/dist/esm/debouncer.d.ts +10 -0
- package/dist/esm/debouncer.js +14 -2
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/event-client.d.ts +42 -0
- package/dist/esm/event-client.js +18 -0
- package/dist/esm/event-client.js.map +1 -0
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +4 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/queuer.d.ts +10 -0
- package/dist/esm/queuer.js +15 -3
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +10 -0
- package/dist/esm/rate-limiter.js +14 -2
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +10 -0
- package/dist/esm/throttler.js +14 -2
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/utils.d.ts +1 -0
- package/dist/esm/utils.js +10 -0
- package/dist/esm/utils.js.map +1 -1
- package/package.json +12 -1
- package/src/async-batcher.ts +22 -2
- package/src/async-debouncer.ts +27 -4
- package/src/async-queuer.ts +32 -2
- package/src/async-rate-limiter.ts +27 -3
- package/src/async-throttler.ts +24 -2
- package/src/batcher.ts +17 -2
- package/src/debouncer.ts +27 -2
- package/src/event-client.ts +63 -0
- package/src/index.ts +2 -0
- package/src/queuer.ts +31 -2
- package/src/rate-limiter.ts +26 -2
- package/src/throttler.ts +26 -2
- package/src/utils.ts +15 -0
package/dist/esm/rate-limiter.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { Store } from "@tanstack/store";
|
|
2
|
-
import { parseFunctionOrValue } from "./utils.js";
|
|
2
|
+
import { parseFunctionOrValue, createKey } from "./utils.js";
|
|
3
|
+
import { emitChange, pacerEventClient } from "./event-client.js";
|
|
3
4
|
function getDefaultRateLimiterState() {
|
|
4
5
|
return {
|
|
5
6
|
executionCount: 0,
|
|
6
7
|
executionTimes: [],
|
|
7
8
|
isExceeded: false,
|
|
8
9
|
rejectionCount: 0,
|
|
9
|
-
status: "idle"
|
|
10
|
+
status: "idle",
|
|
11
|
+
maybeExecuteCount: 0
|
|
10
12
|
};
|
|
11
13
|
}
|
|
12
14
|
const defaultOptions = {
|
|
@@ -37,6 +39,7 @@ class RateLimiter {
|
|
|
37
39
|
status
|
|
38
40
|
};
|
|
39
41
|
});
|
|
42
|
+
emitChange("RateLimiter", this);
|
|
40
43
|
};
|
|
41
44
|
this.#getEnabled = () => {
|
|
42
45
|
return !!parseFunctionOrValue(this.options.enabled, this);
|
|
@@ -48,6 +51,9 @@ class RateLimiter {
|
|
|
48
51
|
return parseFunctionOrValue(this.options.window, this);
|
|
49
52
|
};
|
|
50
53
|
this.maybeExecute = (...args) => {
|
|
54
|
+
this.#setState({
|
|
55
|
+
maybeExecuteCount: this.store.state.maybeExecuteCount + 1
|
|
56
|
+
});
|
|
51
57
|
this.#cleanupOldExecutions();
|
|
52
58
|
const relevantExecutionTimes = this.#getExecutionTimesInWindow();
|
|
53
59
|
if (relevantExecutionTimes.length < this.#getLimit()) {
|
|
@@ -131,6 +137,7 @@ class RateLimiter {
|
|
|
131
137
|
this.#setState(getDefaultRateLimiterState());
|
|
132
138
|
this.#clearTimeouts();
|
|
133
139
|
};
|
|
140
|
+
this.key = createKey(initialOptions.key);
|
|
134
141
|
this.options = {
|
|
135
142
|
...defaultOptions,
|
|
136
143
|
...initialOptions
|
|
@@ -139,6 +146,11 @@ class RateLimiter {
|
|
|
139
146
|
for (const executionTime of this.#getExecutionTimesInWindow()) {
|
|
140
147
|
this.#setCleanupTimeout(executionTime);
|
|
141
148
|
}
|
|
149
|
+
pacerEventClient.on("d-RateLimiter", (event) => {
|
|
150
|
+
if (event.payload.key !== this.key) return;
|
|
151
|
+
this.#setState(event.payload.store.state);
|
|
152
|
+
this.setOptions(event.payload.options);
|
|
153
|
+
});
|
|
142
154
|
}
|
|
143
155
|
#timeoutIds;
|
|
144
156
|
#setState;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rate-limiter.js","sources":["../../src/rate-limiter.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport type { AnyFunction } from './types'\n\nexport interface RateLimiterState {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Array of timestamps when executions occurred for rate limiting calculations\n */\n executionTimes: Array<number>\n /**\n * Whether the rate limiter has exceeded the limit\n */\n isExceeded: boolean\n /**\n * Number of function executions that have been rejected due to rate limiting\n */\n rejectionCount: number\n /**\n * Current execution status - 'disabled' when not active, 'executing' when executing, 'idle' when not executing, 'exceeded' when rate limit is exceeded\n */\n status: 'disabled' | 'exceeded' | 'idle'\n}\n\nfunction getDefaultRateLimiterState(): RateLimiterState {\n return {\n executionCount: 0,\n executionTimes: [],\n isExceeded: false,\n rejectionCount: 0,\n status: 'idle',\n }\n}\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions<TFn extends AnyFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean)\n /**\n * Initial state for the rate limiter\n */\n initialState?: Partial<RateLimiterState>\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n limit: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, rateLimiter: RateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Time window in milliseconds within which the limit applies.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n window: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\nconst defaultOptions: Omit<\n Required<RateLimiterOptions<any>>,\n 'initialState' | 'onExecute' | 'onReject'\n> = {\n enabled: true,\n limit: 1,\n window: 0,\n windowType: 'fixed',\n}\n\n/**\n * A class that creates a rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution count, execution times, and rejection count\n * - State can be accessed via `rateLimiter.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `rateLimiter.state`\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(\n * (id: string) => api.getData(id),\n * {\n * limit: 5,\n * window: 1000,\n * windowType: 'sliding',\n * }\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<TFn extends AnyFunction> {\n readonly store: Store<Readonly<RateLimiterState>> =\n new Store<RateLimiterState>(getDefaultRateLimiterState())\n options: RateLimiterOptions<TFn>\n #timeoutIds: Set<NodeJS.Timeout> = new Set()\n\n constructor(\n public fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n for (const executionTime of this.#getExecutionTimesInWindow()) {\n this.#setCleanupTimeout(executionTime)\n }\n }\n\n /**\n * Updates the rate limiter options\n */\n setOptions = (newOptions: Partial<RateLimiterOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<RateLimiterState>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const isExceeded = combinedState.executionTimes.length >= this.#getLimit()\n const status = !this.#getEnabled()\n ? 'disabled'\n : isExceeded\n ? 'exceeded'\n : 'idle'\n return {\n ...combinedState,\n isExceeded,\n status,\n }\n })\n }\n\n /**\n * Returns the current enabled state of the rate limiter\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current limit of executions allowed within the time window\n */\n #getLimit = (): number => {\n return parseFunctionOrValue(this.options.limit, this)\n }\n\n /**\n * Returns the current time window in milliseconds\n */\n #getWindow = (): number => {\n return parseFunctionOrValue(this.options.window, this)\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute = (...args: Parameters<TFn>): boolean => {\n this.#cleanupOldExecutions()\n\n const relevantExecutionTimes = this.#getExecutionTimesInWindow()\n\n if (relevantExecutionTimes.length < this.#getLimit()) {\n this.#execute(...args)\n return true\n }\n\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(this)\n return false\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n const now = Date.now()\n this.fn(...args) // EXECUTE!\n this.store.state.executionTimes.push(now) // mutate state directly for performance\n\n this.#setCleanupTimeout(now)\n\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n })\n this.options.onExecute?.(args, this)\n }\n\n #getExecutionTimesInWindow = (): Array<number> => {\n if (this.options.windowType === 'sliding') {\n // For sliding window, return all executions within the current window\n return this.store.state.executionTimes.filter(\n (time) => time > Date.now() - this.#getWindow(),\n )\n } else {\n // For fixed window, return all executions in the current window\n // The window starts from the oldest execution time\n if (this.store.state.executionTimes.length === 0) {\n return []\n }\n const oldestExecution = Math.min(...this.store.state.executionTimes)\n const windowStart = oldestExecution\n const windowEnd = windowStart + this.#getWindow()\n const now = Date.now()\n\n // If the window has expired, return empty array\n if (now > windowEnd) {\n return []\n }\n\n // Otherwise, return all executions in the current window\n return this.store.state.executionTimes.filter(\n (time) => time >= windowStart && time <= windowEnd,\n )\n }\n }\n\n #setCleanupTimeout = (executionTime: number): void => {\n if (\n this.options.windowType === 'sliding' ||\n this.#timeoutIds.size === 0 // new fixed window\n ) {\n const now = Date.now()\n const timeUntilExpiration = executionTime - now + this.#getWindow() + 1\n const timeoutId = setTimeout(() => {\n this.#cleanupOldExecutions()\n this.#clearTimeout(timeoutId)\n }, timeUntilExpiration)\n this.#timeoutIds.add(timeoutId)\n }\n }\n\n #clearTimeout = (timeoutId: NodeJS.Timeout): void => {\n clearTimeout(timeoutId)\n this.#timeoutIds.delete(timeoutId)\n }\n\n #clearTimeouts = (): void => {\n this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))\n this.#timeoutIds.clear()\n }\n\n #cleanupOldExecutions = (): void => {\n this.#setState({\n executionTimes: this.#getExecutionTimesInWindow(),\n })\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow = (): number => {\n const relevantExecutionTimes = this.#getExecutionTimesInWindow()\n return Math.max(0, this.#getLimit() - relevantExecutionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow = (): number => {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = this.store.state.executionTimes[0] ?? Infinity\n return oldestExecution + this.#getWindow() - Date.now()\n }\n\n /**\n * Resets the rate limiter state\n */\n reset = (): void => {\n this.#setState(getDefaultRateLimiterState())\n this.#clearTimeouts()\n }\n}\n\n/**\n * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution count, execution times, and rejection count\n * - State can be accessed via the underlying RateLimiter instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function rateLimit<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute\n}\n"],"names":[],"mappings":";;AA2BA,SAAS,6BAA+C;AACtD,SAAO;AAAA,IACL,gBAAgB;AAAA,IAChB,gBAAgB,CAAA;AAAA,IAChB,YAAY;AAAA,IACZ,gBAAgB;AAAA,IAChB,QAAQ;AAAA,EAAA;AAEZ;AA0CA,MAAM,iBAGF;AAAA,EACF,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,YAAY;AACd;AA8CO,MAAM,YAAqC;AAAA,EAMhD,YACS,IACP,gBACA;AAFO,SAAA,KAAA;AANT,SAAS,QACP,IAAI,MAAwB,2BAAA,CAA4B;AAE1D,SAAA,kCAAuC,IAAA;AAmBvC,SAAA,aAAa,CAAC,eAAuD;AACnE,WAAK,UAAU,EAAE,GAAG,KAAK,SAAS,GAAG,WAAA;AAAA,IAAW;AAGlD,SAAA,YAAY,CAAC,aAA8C;AACzD,WAAK,MAAM,SAAS,CAAC,UAAU;AAC7B,cAAM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C,aAAO,KAAK,IAAI,GAAG,KAAK,UAAA,IAAc,uBAAuB,MAAM;AAAA,IAAA;AAMrE,SAAA,uBAAuB,MAAc;AACnC,UAAI,KAAK,qBAAA,IAAyB,GAAG;AACnC,eAAO;AAAA,MAAA;AAET,YAAM,kBAAkB,KAAK,MAAM,MAAM,eAAe,CAAC,KAAK;AAC9D,aAAO,kBAAkB,KAAK,WAAA,IAAe,KAAK,IAAA;AAAA,IAAI;AAMxD,SAAA,QAAQ,MAAY;AAClB,WAAK,UAAU,4BAA4B;AAC3C,WAAK,eAAA;AAAA,IAAe;AA5LpB,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IAAA;AAEL,SAAK,UAAU,KAAK,QAAQ,gBAAgB,CAAA,CAAE;AAC9C,eAAW,iBAAiB,KAAK,8BAA8B;AAC7D,WAAK,mBAAmB,aAAa;AAAA,IAAA;AAAA,EACvC;AAAA,EAbF;AAAA,EAuBA;AAAA,EAuBA;AAAA,EAOA;AAAA,EAOA;AAAA,EAoCA;AAAA,EAcA;AAAA,EA6BA;AAAA,EAeA;AAAA,EAKA;AAAA,EAKA;AAgCF;AAgDO,SAAS,UACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,YAAY,IAAI,cAAc;AACtD,SAAO,YAAY;AACrB;"}
|
|
1
|
+
{"version":3,"file":"rate-limiter.js","sources":["../../src/rate-limiter.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { createKey, parseFunctionOrValue } from './utils'\nimport { emitChange, pacerEventClient } from './event-client'\nimport type { AnyFunction } from './types'\n\nexport interface RateLimiterState {\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Array of timestamps when executions occurred for rate limiting calculations\n */\n executionTimes: Array<number>\n /**\n * Whether the rate limiter has exceeded the limit\n */\n isExceeded: boolean\n /**\n * Number of times maybeExecute has been called (for reduction calculations)\n */\n maybeExecuteCount: number\n /**\n * Number of function executions that have been rejected due to rate limiting\n */\n rejectionCount: number\n /**\n * Current execution status - 'disabled' when not active, 'executing' when executing, 'idle' when not executing, 'exceeded' when rate limit is exceeded\n */\n status: 'disabled' | 'exceeded' | 'idle'\n}\n\nfunction getDefaultRateLimiterState(): RateLimiterState {\n return {\n executionCount: 0,\n executionTimes: [],\n isExceeded: false,\n rejectionCount: 0,\n status: 'idle',\n maybeExecuteCount: 0,\n }\n}\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions<TFn extends AnyFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean)\n /**\n * Initial state for the rate limiter\n */\n initialState?: Partial<RateLimiterState>\n /**\n * Optional key to identify this rate limiter instance.\n * If provided, the rate limiter will be identified by this key in the devtools and PacerProvider if applicable.\n */\n key?: string\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n limit: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (args: Parameters<TFn>, rateLimiter: RateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Time window in milliseconds within which the limit applies.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n window: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\nconst defaultOptions: Omit<\n Required<RateLimiterOptions<any>>,\n 'initialState' | 'onExecute' | 'onReject' | 'key'\n> = {\n enabled: true,\n limit: 1,\n window: 0,\n windowType: 'fixed',\n}\n\n/**\n * A class that creates a rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution count, execution times, and rejection count\n * - State can be accessed via `rateLimiter.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `rateLimiter.state`\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(\n * (id: string) => api.getData(id),\n * {\n * limit: 5,\n * window: 1000,\n * windowType: 'sliding',\n * }\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<TFn extends AnyFunction> {\n readonly store: Store<Readonly<RateLimiterState>> =\n new Store<RateLimiterState>(getDefaultRateLimiterState())\n key: string\n options: RateLimiterOptions<TFn>\n #timeoutIds: Set<NodeJS.Timeout> = new Set()\n\n constructor(\n public fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n ) {\n this.key = createKey(initialOptions.key)\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n for (const executionTime of this.#getExecutionTimesInWindow()) {\n this.#setCleanupTimeout(executionTime)\n }\n\n pacerEventClient.on('d-RateLimiter', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state)\n this.setOptions(event.payload.options)\n })\n }\n\n /**\n * Updates the rate limiter options\n */\n setOptions = (newOptions: Partial<RateLimiterOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<RateLimiterState>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const isExceeded = combinedState.executionTimes.length >= this.#getLimit()\n const status = !this.#getEnabled()\n ? 'disabled'\n : isExceeded\n ? 'exceeded'\n : 'idle'\n return {\n ...combinedState,\n isExceeded,\n status,\n }\n })\n emitChange('RateLimiter', this)\n }\n\n /**\n * Returns the current enabled state of the rate limiter\n */\n #getEnabled = (): boolean => {\n return !!parseFunctionOrValue(this.options.enabled, this)\n }\n\n /**\n * Returns the current limit of executions allowed within the time window\n */\n #getLimit = (): number => {\n return parseFunctionOrValue(this.options.limit, this)\n }\n\n /**\n * Returns the current time window in milliseconds\n */\n #getWindow = (): number => {\n return parseFunctionOrValue(this.options.window, this)\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute = (...args: Parameters<TFn>): boolean => {\n this.#setState({\n maybeExecuteCount: this.store.state.maybeExecuteCount + 1,\n })\n\n this.#cleanupOldExecutions()\n\n const relevantExecutionTimes = this.#getExecutionTimesInWindow()\n\n if (relevantExecutionTimes.length < this.#getLimit()) {\n this.#execute(...args)\n return true\n }\n\n this.#setState({\n rejectionCount: this.store.state.rejectionCount + 1,\n })\n this.options.onReject?.(this)\n return false\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return\n const now = Date.now()\n this.fn(...args) // EXECUTE!\n this.store.state.executionTimes.push(now) // mutate state directly for performance\n\n this.#setCleanupTimeout(now)\n\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n })\n this.options.onExecute?.(args, this)\n }\n\n #getExecutionTimesInWindow = (): Array<number> => {\n if (this.options.windowType === 'sliding') {\n // For sliding window, return all executions within the current window\n return this.store.state.executionTimes.filter(\n (time) => time > Date.now() - this.#getWindow(),\n )\n } else {\n // For fixed window, return all executions in the current window\n // The window starts from the oldest execution time\n if (this.store.state.executionTimes.length === 0) {\n return []\n }\n const oldestExecution = Math.min(...this.store.state.executionTimes)\n const windowStart = oldestExecution\n const windowEnd = windowStart + this.#getWindow()\n const now = Date.now()\n\n // If the window has expired, return empty array\n if (now > windowEnd) {\n return []\n }\n\n // Otherwise, return all executions in the current window\n return this.store.state.executionTimes.filter(\n (time) => time >= windowStart && time <= windowEnd,\n )\n }\n }\n\n #setCleanupTimeout = (executionTime: number): void => {\n if (\n this.options.windowType === 'sliding' ||\n this.#timeoutIds.size === 0 // new fixed window\n ) {\n const now = Date.now()\n const timeUntilExpiration = executionTime - now + this.#getWindow() + 1\n const timeoutId = setTimeout(() => {\n this.#cleanupOldExecutions()\n this.#clearTimeout(timeoutId)\n }, timeUntilExpiration)\n this.#timeoutIds.add(timeoutId)\n }\n }\n\n #clearTimeout = (timeoutId: NodeJS.Timeout): void => {\n clearTimeout(timeoutId)\n this.#timeoutIds.delete(timeoutId)\n }\n\n #clearTimeouts = (): void => {\n this.#timeoutIds.forEach((timeoutId) => clearTimeout(timeoutId))\n this.#timeoutIds.clear()\n }\n\n #cleanupOldExecutions = (): void => {\n this.#setState({\n executionTimes: this.#getExecutionTimesInWindow(),\n })\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow = (): number => {\n const relevantExecutionTimes = this.#getExecutionTimesInWindow()\n return Math.max(0, this.#getLimit() - relevantExecutionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow = (): number => {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = this.store.state.executionTimes[0] ?? Infinity\n return oldestExecution + this.#getWindow() - Date.now()\n }\n\n /**\n * Resets the rate limiter state\n */\n reset = (): void => {\n this.#setState(getDefaultRateLimiterState())\n this.#clearTimeouts()\n }\n}\n\n/**\n * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the rate limiter\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - Use `onReject` callback to react to executions being rejected when rate limit is exceeded\n * - The state includes execution count, execution times, and rejection count\n * - State can be accessed via the underlying RateLimiter instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function rateLimit<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute\n}\n"],"names":[],"mappings":";;;AAgCA,SAAS,6BAA+C;AACtD,SAAO;AAAA,IACL,gBAAgB;AAAA,IAChB,gBAAgB,CAAA;AAAA,IAChB,YAAY;AAAA,IACZ,gBAAgB;AAAA,IAChB,QAAQ;AAAA,IACR,mBAAmB;AAAA,EAAA;AAEvB;AA+CA,MAAM,iBAGF;AAAA,EACF,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,YAAY;AACd;AA8CO,MAAM,YAAqC;AAAA,EAOhD,YACS,IACP,gBACA;AAFO,SAAA,KAAA;AAPT,SAAS,QACP,IAAI,MAAwB,2BAAA,CAA4B;AAG1D,SAAA,kCAAuC,IAAA;AA0BvC,SAAA,aAAa,CAAC,eAAuD;AACnE,WAAK,UAAU,EAAE,GAAG,KAAK,SAAS,GAAG,WAAA;AAAA,IAAW;AAGlD,SAAA,YAAY,CAAC,aAA8C;AACzD,WAAK,MAAM,SAAS,CAAC,UAAU;AAC7B,cAAM,gBAAgB;AAAA,UACpB,GAAG;AAAA,UACH,GAAG;AAAA,QAAA;AAEL,cAAM,aAAa,cAAc,eAAe,UAAU,KAAK,UAAA;AAC/D,cAAM,SAAS,CAAC,KAAK,gBACjB,aACA,aACE,aACA;AACN,eAAO;AAAA,UACL,GAAG;AAAA,UACH;AAAA,UACA;AAAA,QAAA;AAAA,MACF,CACD;AACD,iBAAW,eAAe,IAAI;AAAA,IAAA;AAMhC,SAAA,cAAc,MAAe;AAC3B,aAAO,CAAC,CAAC,qBAAqB,KAAK,QAAQ,SAAS,IAAI;AAAA,IAAA;AAM1D,SAAA,YAAY,MAAc;AACxB,aAAO,qBAAqB,KAAK,QAAQ,OAAO,IAAI;AAAA,IAAA;AAMtD,SAAA,aAAa,MAAc;AACzB,aAAO,qBAAqB,KAAK,QAAQ,QAAQ,IAAI;AAA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;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IAAA;AAEL,SAAK,UAAU,KAAK,QAAQ,gBAAgB,CAAA,CAAE;AAC9C,eAAW,iBAAiB,KAAK,8BAA8B;AAC7D,WAAK,mBAAmB,aAAa;AAAA,IAAA;AAGvC,qBAAiB,GAAG,iBAAiB,CAAC,UAAU;AAC9C,UAAI,MAAM,QAAQ,QAAQ,KAAK,IAAK;AACpC,WAAK,UAAU,MAAM,QAAQ,MAAM,KAAK;AACxC,WAAK,WAAW,MAAM,QAAQ,OAAO;AAAA,IAAA,CACtC;AAAA,EAAA;AAAA,EApBH;AAAA,EA8BA;AAAA,EAwBA;AAAA,EAOA;AAAA,EAOA;AAAA,EAwCA;AAAA,EAcA;AAAA,EA6BA;AAAA,EAeA;AAAA,EAKA;AAAA,EAKA;AAgCF;AAgDO,SAAS,UACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,YAAY,IAAI,cAAc;AACtD,SAAO,YAAY;AACrB;"}
|
package/dist/esm/throttler.d.ts
CHANGED
|
@@ -17,6 +17,10 @@ export interface ThrottlerState<TFn extends AnyFunction> {
|
|
|
17
17
|
* Timestamp of the last function execution in milliseconds
|
|
18
18
|
*/
|
|
19
19
|
lastExecutionTime: number;
|
|
20
|
+
/**
|
|
21
|
+
* Number of times maybeExecute has been called (for reduction calculations)
|
|
22
|
+
*/
|
|
23
|
+
maybeExecuteCount: number;
|
|
20
24
|
/**
|
|
21
25
|
* Timestamp when the next execution can occur in milliseconds
|
|
22
26
|
*/
|
|
@@ -40,6 +44,11 @@ export interface ThrottlerOptions<TFn extends AnyFunction> {
|
|
|
40
44
|
* Initial state for the throttler
|
|
41
45
|
*/
|
|
42
46
|
initialState?: Partial<ThrottlerState<TFn>>;
|
|
47
|
+
/**
|
|
48
|
+
* A key to identify the throttler.
|
|
49
|
+
* If provided, the throttler will be identified by this key in the devtools and PacerProvider if applicable.
|
|
50
|
+
*/
|
|
51
|
+
key?: string;
|
|
43
52
|
/**
|
|
44
53
|
* Whether to execute on the leading edge of the timeout.
|
|
45
54
|
* Defaults to true.
|
|
@@ -100,6 +109,7 @@ export declare class Throttler<TFn extends AnyFunction> {
|
|
|
100
109
|
#private;
|
|
101
110
|
fn: TFn;
|
|
102
111
|
readonly store: Store<Readonly<ThrottlerState<TFn>>>;
|
|
112
|
+
key: string | undefined;
|
|
103
113
|
options: ThrottlerOptions<TFn>;
|
|
104
114
|
constructor(fn: TFn, initialOptions: ThrottlerOptions<TFn>);
|
|
105
115
|
/**
|
package/dist/esm/throttler.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Store } from "@tanstack/store";
|
|
2
|
-
import { parseFunctionOrValue } from "./utils.js";
|
|
2
|
+
import { parseFunctionOrValue, createKey } from "./utils.js";
|
|
3
|
+
import { emitChange, pacerEventClient } from "./event-client.js";
|
|
3
4
|
function getDefaultThrottlerState() {
|
|
4
5
|
return {
|
|
5
6
|
executionCount: 0,
|
|
@@ -7,7 +8,8 @@ function getDefaultThrottlerState() {
|
|
|
7
8
|
lastArgs: void 0,
|
|
8
9
|
lastExecutionTime: 0,
|
|
9
10
|
nextExecutionTime: 0,
|
|
10
|
-
status: "idle"
|
|
11
|
+
status: "idle",
|
|
12
|
+
maybeExecuteCount: 0
|
|
11
13
|
};
|
|
12
14
|
}
|
|
13
15
|
const defaultOptions = {
|
|
@@ -40,6 +42,7 @@ class Throttler {
|
|
|
40
42
|
status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
|
|
41
43
|
};
|
|
42
44
|
});
|
|
45
|
+
emitChange("Throttler", this);
|
|
43
46
|
};
|
|
44
47
|
this.#getEnabled = () => {
|
|
45
48
|
return !!parseFunctionOrValue(this.options.enabled, this);
|
|
@@ -48,6 +51,9 @@ class Throttler {
|
|
|
48
51
|
return parseFunctionOrValue(this.options.wait, this);
|
|
49
52
|
};
|
|
50
53
|
this.maybeExecute = (...args) => {
|
|
54
|
+
this.#setState({
|
|
55
|
+
maybeExecuteCount: this.store.state.maybeExecuteCount + 1
|
|
56
|
+
});
|
|
51
57
|
const now = Date.now();
|
|
52
58
|
const timeSinceLastExecution = now - this.store.state.lastExecutionTime;
|
|
53
59
|
const wait = this.#getWait();
|
|
@@ -111,11 +117,17 @@ class Throttler {
|
|
|
111
117
|
this.reset = () => {
|
|
112
118
|
this.#setState(getDefaultThrottlerState());
|
|
113
119
|
};
|
|
120
|
+
this.key = createKey(initialOptions.key);
|
|
114
121
|
this.options = {
|
|
115
122
|
...defaultOptions,
|
|
116
123
|
...initialOptions
|
|
117
124
|
};
|
|
118
125
|
this.#setState(this.options.initialState ?? {});
|
|
126
|
+
pacerEventClient.on("d-Throttler", (event) => {
|
|
127
|
+
if (event.payload.key !== this.key) return;
|
|
128
|
+
this.#setState(event.payload.store.state);
|
|
129
|
+
this.setOptions(event.payload.options);
|
|
130
|
+
});
|
|
119
131
|
}
|
|
120
132
|
#timeoutId;
|
|
121
133
|
#setState;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"throttler.js","sources":["../../src/throttler.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\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 * 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 }\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 * 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\nconst defaultOptions: Omit<\n Required<ThrottlerOptions<any>>,\n 'initialState' | 'onExecute'\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 *\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(),\n )\n options: ThrottlerOptions<TFn>\n #timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\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 }\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 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 * 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"],"names":[],"mappings":";;AA+BA,SAAS,2BAEgB;AACvB,SAAO;AAAA,IACL,gBAAgB;AAAA,IAChB,WAAW;AAAA,IACX,UAAU;AAAA,IACV,mBAAmB;AAAA,IACnB,mBAAmB;AAAA,IACnB,QAAQ;AAAA,EAAA;AAEZ;AAsCA,MAAM,iBAGF;AAAA,EACF,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,MAAM;AACR;AAqCO,MAAM,UAAmC;AAAA,EAO9C,YACS,IACP,gBACA;AAFO,SAAA,KAAA;AAPT,SAAS,QAA8C,IAAI;AAAA,MACzD,yBAAA;AAAA,IAAyB;AAmB3B,SAAA,aAAa,CAAC,eAAqD;AACjE,WAAK,UAAU,EAAE,GAAG,KAAK,SAAS,GAAG,WAAA;AAGrC,UAAI,CAAC,KAAK,eAAe;AACvB,aAAK,OAAA;AAAA,MAAO;AAAA,IACd;AAGF,SAAA,YAAY,CAAC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ttler.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { createKey, 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\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 *\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(),\n )\n key: string | undefined\n options: ThrottlerOptions<TFn>\n #timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n public fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n ) {\n this.key = createKey(initialOptions.key)\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n\n pacerEventClient.on('d-Throttler', (event) => {\n if (event.payload.key !== this.key) return\n this.#setState(event.payload.store.state as ThrottlerState<TFn>)\n this.setOptions(event.payload.options)\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 * 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"],"names":[],"mappings":";;;AAoCA,SAAS,2BAEgB;AACvB,SAAO;AAAA,IACL,gBAAgB;AAAA,IAChB,WAAW;AAAA,IACX,UAAU;AAAA,IACV,mBAAmB;AAAA,IACnB,mBAAmB;AAAA,IACnB,QAAQ;AAAA,IACR,mBAAmB;AAAA,EAAA;AAEvB;AA2CA,MAAM,iBAGF;AAAA,EACF,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,MAAM;AACR;AAqCO,MAAM,UAAmC;AAAA,EAQ9C,YACS,IACP,gBACA;AAFO,SAAA,KAAA;AART,SAAS,QAA8C,IAAI;AAAA,MACzD,yBAAA;AAAA,IAAyB;AA2B3B,SAAA,aAAa,CAAC,eAAqD;AACjE,WAAK,UAAU,EAAE,GAAG,KAAK,SAAS,GAAG,WAAA;AAGrC,UAAI,CAAC,KAAK,eAAe;AACvB,aAAK,OAAA;AAAA,MAAO;AAAA,IACd;AAGF,SAAA,YAAY,CAAC,aAAiD;AAC5D,WAAK,MAAM,SAAS,CAAC,UAAU;AAC7B,cAAM,gBAAgB;AAAA,UACpB,GAAG;AAAA,UACH,GAAG;AAAA,QAAA;AAEL,cAAM,EAAE,cAAc;AACtB,eAAO;AAAA,UACL,GAAG;AAAA,UACH,QAAQ,CAAC,KAAK,gBACV,aACA,YACE,YACA;AAAA,QAAA;AAAA,MAC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I,UAAU,IAAI,cAAc;AAClD,SAAO,UAAU;AACnB;"}
|
package/dist/esm/utils.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import { AnyFunction } from './types.js';
|
|
2
2
|
export declare function isFunction<T extends AnyFunction>(value: any): value is T;
|
|
3
3
|
export declare function parseFunctionOrValue<T, TArgs extends Array<any>>(value: T | ((...args: TArgs) => T), ...args: TArgs): T;
|
|
4
|
+
export declare function createKey(key?: string): string;
|
package/dist/esm/utils.js
CHANGED
|
@@ -4,7 +4,17 @@ function isFunction(value) {
|
|
|
4
4
|
function parseFunctionOrValue(value, ...args) {
|
|
5
5
|
return isFunction(value) ? value(...args) : value;
|
|
6
6
|
}
|
|
7
|
+
function createKey(key) {
|
|
8
|
+
if (key) {
|
|
9
|
+
return key;
|
|
10
|
+
}
|
|
11
|
+
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
12
|
+
return crypto.randomUUID();
|
|
13
|
+
}
|
|
14
|
+
return "";
|
|
15
|
+
}
|
|
7
16
|
export {
|
|
17
|
+
createKey,
|
|
8
18
|
isFunction,
|
|
9
19
|
parseFunctionOrValue
|
|
10
20
|
};
|
package/dist/esm/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","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"],"names":[],"mappings":"AAEO,SAAS,WAAkC,OAAwB;AACxE,SAAO,OAAO,UAAU;AAC1B;AAEO,SAAS,qBACd,UACG,MACA;AACH,SAAO,WAAW,KAAK,IAAI,MAAM,GAAG,IAAI,IAAI;AAC9C;"}
|
|
1
|
+
{"version":3,"file":"utils.js","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\nexport function createKey(key?: string): string {\n if (key) {\n return key\n }\n\n if (\n typeof crypto !== 'undefined' &&\n typeof crypto.randomUUID === 'function'\n ) {\n return crypto.randomUUID()\n }\n\n return ''\n}\n"],"names":[],"mappings":"AAEO,SAAS,WAAkC,OAAwB;AACxE,SAAO,OAAO,UAAU;AAC1B;AAEO,SAAS,qBACd,UACG,MACA;AACH,SAAO,WAAW,KAAK,IAAI,MAAM,GAAG,IAAI,IAAI;AAC9C;AAEO,SAAS,UAAU,KAAsB;AAC9C,MAAI,KAAK;AACP,WAAO;AAAA,EAAA;AAGT,MACE,OAAO,WAAW,eAClB,OAAO,OAAO,eAAe,YAC7B;AACA,WAAO,OAAO,WAAA;AAAA,EAAW;AAG3B,SAAO;AACT;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/pacer",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.1",
|
|
4
4
|
"description": "Utilities for debouncing, throttling, rate-limiting, queuing, and more.",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -150,6 +150,16 @@
|
|
|
150
150
|
"default": "./dist/cjs/utils.cjs"
|
|
151
151
|
}
|
|
152
152
|
},
|
|
153
|
+
"./event-client": {
|
|
154
|
+
"import": {
|
|
155
|
+
"types": "./dist/esm/event-client.d.ts",
|
|
156
|
+
"default": "./dist/esm/event-client.js"
|
|
157
|
+
},
|
|
158
|
+
"require": {
|
|
159
|
+
"types": "./dist/cjs/event-client.d.cts",
|
|
160
|
+
"default": "./dist/cjs/event-client.cjs"
|
|
161
|
+
}
|
|
162
|
+
},
|
|
153
163
|
"./package.json": "./package.json"
|
|
154
164
|
},
|
|
155
165
|
"sideEffects": false,
|
|
@@ -161,6 +171,7 @@
|
|
|
161
171
|
"src"
|
|
162
172
|
],
|
|
163
173
|
"dependencies": {
|
|
174
|
+
"@tanstack/devtools-event-client": "^0.2.2",
|
|
164
175
|
"@tanstack/store": "^0.7.2"
|
|
165
176
|
},
|
|
166
177
|
"scripts": {
|
package/src/async-batcher.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Store } from '@tanstack/store'
|
|
2
|
-
import { parseFunctionOrValue } from './utils'
|
|
2
|
+
import { createKey, parseFunctionOrValue } from './utils'
|
|
3
|
+
import { emitChange, pacerEventClient } from './event-client'
|
|
3
4
|
import type { OptionalKeys } from './types'
|
|
4
5
|
|
|
5
6
|
export interface AsyncBatcherState<TValue> {
|
|
@@ -91,6 +92,11 @@ export interface AsyncBatcherOptions<TValue> {
|
|
|
91
92
|
* Initial state for the async batcher
|
|
92
93
|
*/
|
|
93
94
|
initialState?: Partial<AsyncBatcherState<TValue>>
|
|
95
|
+
/**
|
|
96
|
+
* Optional key to identify this async batcher instance.
|
|
97
|
+
* If provided, the async batcher will be identified by this key in the devtools and PacerProvider if applicable.
|
|
98
|
+
*/
|
|
99
|
+
key?: string
|
|
94
100
|
/**
|
|
95
101
|
* Maximum number of items in a batch
|
|
96
102
|
* @default Infinity
|
|
@@ -144,7 +150,12 @@ export interface AsyncBatcherOptions<TValue> {
|
|
|
144
150
|
|
|
145
151
|
type AsyncBatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<
|
|
146
152
|
Required<AsyncBatcherOptions<TValue>>,
|
|
147
|
-
|
|
153
|
+
| 'initialState'
|
|
154
|
+
| 'onError'
|
|
155
|
+
| 'onItemsChange'
|
|
156
|
+
| 'onSettled'
|
|
157
|
+
| 'onSuccess'
|
|
158
|
+
| 'key'
|
|
148
159
|
>
|
|
149
160
|
|
|
150
161
|
const defaultOptions: AsyncBatcherOptionsWithOptionalCallbacks<any> = {
|
|
@@ -220,6 +231,7 @@ export class AsyncBatcher<TValue> {
|
|
|
220
231
|
readonly store: Store<Readonly<AsyncBatcherState<TValue>>> = new Store(
|
|
221
232
|
getDefaultAsyncBatcherState<TValue>(),
|
|
222
233
|
)
|
|
234
|
+
key: string
|
|
223
235
|
options: AsyncBatcherOptionsWithOptionalCallbacks<TValue>
|
|
224
236
|
#timeoutId: NodeJS.Timeout | null = null
|
|
225
237
|
|
|
@@ -227,12 +239,19 @@ export class AsyncBatcher<TValue> {
|
|
|
227
239
|
public fn: (items: Array<TValue>) => Promise<any>,
|
|
228
240
|
initialOptions: AsyncBatcherOptions<TValue>,
|
|
229
241
|
) {
|
|
242
|
+
this.key = createKey(initialOptions.key)
|
|
230
243
|
this.options = {
|
|
231
244
|
...defaultOptions,
|
|
232
245
|
...initialOptions,
|
|
233
246
|
throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,
|
|
234
247
|
}
|
|
235
248
|
this.#setState(this.options.initialState ?? {})
|
|
249
|
+
|
|
250
|
+
pacerEventClient.on('d-AsyncBatcher', (event) => {
|
|
251
|
+
if (event.payload.key !== this.key) return
|
|
252
|
+
this.#setState(event.payload.store.state)
|
|
253
|
+
this.setOptions(event.payload.options)
|
|
254
|
+
})
|
|
236
255
|
}
|
|
237
256
|
|
|
238
257
|
/**
|
|
@@ -264,6 +283,7 @@ export class AsyncBatcher<TValue> {
|
|
|
264
283
|
: 'populated',
|
|
265
284
|
}
|
|
266
285
|
})
|
|
286
|
+
emitChange('AsyncBatcher', this)
|
|
267
287
|
}
|
|
268
288
|
|
|
269
289
|
#getWait = (): number => {
|
package/src/async-debouncer.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Store } from '@tanstack/store'
|
|
2
|
-
import { parseFunctionOrValue } from './utils'
|
|
2
|
+
import { createKey, parseFunctionOrValue } from './utils'
|
|
3
|
+
import { emitChange, pacerEventClient } from './event-client'
|
|
3
4
|
import type { AnyAsyncFunction, OptionalKeys } from './types'
|
|
4
5
|
|
|
5
6
|
export interface AsyncDebouncerState<TFn extends AnyAsyncFunction> {
|
|
@@ -27,6 +28,10 @@ export interface AsyncDebouncerState<TFn extends AnyAsyncFunction> {
|
|
|
27
28
|
* The result from the most recent successful function execution
|
|
28
29
|
*/
|
|
29
30
|
lastResult: ReturnType<TFn> | undefined
|
|
31
|
+
/**
|
|
32
|
+
* Number of times maybeExecute has been called (for reduction calculations)
|
|
33
|
+
*/
|
|
34
|
+
maybeExecuteCount: number
|
|
30
35
|
/**
|
|
31
36
|
* Number of function executions that have completed (either successfully or with errors)
|
|
32
37
|
*/
|
|
@@ -51,9 +56,10 @@ function getDefaultAsyncDebouncerState<
|
|
|
51
56
|
isPending: false,
|
|
52
57
|
lastArgs: undefined,
|
|
53
58
|
lastResult: undefined,
|
|
59
|
+
maybeExecuteCount: 0,
|
|
54
60
|
settleCount: 0,
|
|
55
|
-
successCount: 0,
|
|
56
61
|
status: 'idle',
|
|
62
|
+
successCount: 0,
|
|
57
63
|
}
|
|
58
64
|
}
|
|
59
65
|
|
|
@@ -71,6 +77,11 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
|
71
77
|
* Initial state for the async debouncer
|
|
72
78
|
*/
|
|
73
79
|
initialState?: Partial<AsyncDebouncerState<TFn>>
|
|
80
|
+
/**
|
|
81
|
+
* Optional key to identify this async debouncer instance.
|
|
82
|
+
* If provided, the async debouncer will be identified by this key in the devtools and PacerProvider if applicable.
|
|
83
|
+
*/
|
|
84
|
+
key?: string
|
|
74
85
|
/**
|
|
75
86
|
* Whether to execute on the leading edge of the timeout.
|
|
76
87
|
* Defaults to false.
|
|
@@ -119,7 +130,7 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
|
119
130
|
|
|
120
131
|
type AsyncDebouncerOptionsWithOptionalCallbacks = OptionalKeys<
|
|
121
132
|
AsyncDebouncerOptions<any>,
|
|
122
|
-
'initialState' | 'onError' | 'onSettled' | 'onSuccess'
|
|
133
|
+
'initialState' | 'onError' | 'onSettled' | 'onSuccess' | 'key'
|
|
123
134
|
>
|
|
124
135
|
|
|
125
136
|
const defaultOptions: AsyncDebouncerOptionsWithOptionalCallbacks = {
|
|
@@ -178,6 +189,7 @@ export class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
178
189
|
readonly store: Store<Readonly<AsyncDebouncerState<TFn>>> = new Store<
|
|
179
190
|
AsyncDebouncerState<TFn>
|
|
180
191
|
>(getDefaultAsyncDebouncerState<TFn>())
|
|
192
|
+
key: string
|
|
181
193
|
options: AsyncDebouncerOptions<TFn>
|
|
182
194
|
#abortController: AbortController | null = null
|
|
183
195
|
#timeoutId: NodeJS.Timeout | null = null
|
|
@@ -189,12 +201,19 @@ export class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
189
201
|
public fn: TFn,
|
|
190
202
|
initialOptions: AsyncDebouncerOptions<TFn>,
|
|
191
203
|
) {
|
|
204
|
+
this.key = createKey(initialOptions.key)
|
|
192
205
|
this.options = {
|
|
193
206
|
...defaultOptions,
|
|
194
207
|
...initialOptions,
|
|
195
208
|
throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,
|
|
196
209
|
}
|
|
197
210
|
this.#setState(this.options.initialState ?? {})
|
|
211
|
+
|
|
212
|
+
pacerEventClient.on('d-AsyncDebouncer', (event) => {
|
|
213
|
+
if (event.payload.key !== this.key) return
|
|
214
|
+
this.#setState(event.payload.store.state as AsyncDebouncerState<TFn>)
|
|
215
|
+
this.setOptions(event.payload.options)
|
|
216
|
+
})
|
|
198
217
|
}
|
|
199
218
|
|
|
200
219
|
/**
|
|
@@ -229,6 +248,7 @@ export class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
229
248
|
: 'idle',
|
|
230
249
|
}
|
|
231
250
|
})
|
|
251
|
+
emitChange('AsyncDebouncer', this)
|
|
232
252
|
}
|
|
233
253
|
|
|
234
254
|
/**
|
|
@@ -264,7 +284,10 @@ export class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
264
284
|
): Promise<ReturnType<TFn> | undefined> => {
|
|
265
285
|
if (!this.#getEnabled()) return undefined
|
|
266
286
|
this.#cancelPendingExecution()
|
|
267
|
-
this.#setState({
|
|
287
|
+
this.#setState({
|
|
288
|
+
lastArgs: args,
|
|
289
|
+
maybeExecuteCount: this.store.state.maybeExecuteCount + 1,
|
|
290
|
+
})
|
|
268
291
|
|
|
269
292
|
// Handle leading execution
|
|
270
293
|
if (this.options.leading && this.store.state.canLeadingExecute) {
|
package/src/async-queuer.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Store } from '@tanstack/store'
|
|
2
|
-
import { parseFunctionOrValue } from './utils'
|
|
2
|
+
import { createKey, parseFunctionOrValue } from './utils'
|
|
3
|
+
import { emitChange, pacerEventClient } from './event-client'
|
|
3
4
|
import type { OptionalKeys } from './types'
|
|
4
5
|
import type { QueuePosition } from './queuer'
|
|
5
6
|
|
|
@@ -8,6 +9,10 @@ export interface AsyncQueuerState<TValue> {
|
|
|
8
9
|
* Items currently being processed by the queuer
|
|
9
10
|
*/
|
|
10
11
|
activeItems: Array<TValue>
|
|
12
|
+
/**
|
|
13
|
+
* Number of times addItem has been called (for reduction calculations)
|
|
14
|
+
*/
|
|
15
|
+
addItemCount: number
|
|
11
16
|
/**
|
|
12
17
|
* Number of task executions that have resulted in errors
|
|
13
18
|
*/
|
|
@@ -73,6 +78,7 @@ export interface AsyncQueuerState<TValue> {
|
|
|
73
78
|
function getDefaultAsyncQueuerState<TValue>(): AsyncQueuerState<TValue> {
|
|
74
79
|
return {
|
|
75
80
|
activeItems: [],
|
|
81
|
+
addItemCount: 0,
|
|
76
82
|
errorCount: 0,
|
|
77
83
|
expirationCount: 0,
|
|
78
84
|
isEmpty: true,
|
|
@@ -132,6 +138,11 @@ export interface AsyncQueuerOptions<TValue> {
|
|
|
132
138
|
* Initial state for the async queuer
|
|
133
139
|
*/
|
|
134
140
|
initialState?: Partial<AsyncQueuerState<TValue>>
|
|
141
|
+
/**
|
|
142
|
+
* Optional key to identify this async queuer instance.
|
|
143
|
+
* If provided, the async queuer will be identified by this key in the devtools and PacerProvider if applicable.
|
|
144
|
+
*/
|
|
145
|
+
key?: string
|
|
135
146
|
/**
|
|
136
147
|
* Maximum number of items allowed in the queuer
|
|
137
148
|
*/
|
|
@@ -190,6 +201,7 @@ type AsyncQueuerOptionsWithOptionalCallbacks = OptionalKeys<
|
|
|
190
201
|
| 'onItemsChange'
|
|
191
202
|
| 'onExpire'
|
|
192
203
|
| 'onError'
|
|
204
|
+
| 'key'
|
|
193
205
|
>
|
|
194
206
|
|
|
195
207
|
const defaultOptions: AsyncQueuerOptionsWithOptionalCallbacks = {
|
|
@@ -260,6 +272,7 @@ export class AsyncQueuer<TValue> {
|
|
|
260
272
|
readonly store: Store<Readonly<AsyncQueuerState<TValue>>> = new Store<
|
|
261
273
|
AsyncQueuerState<TValue>
|
|
262
274
|
>(getDefaultAsyncQueuerState<TValue>())
|
|
275
|
+
key: string
|
|
263
276
|
options: AsyncQueuerOptions<TValue>
|
|
264
277
|
#timeoutIds: Set<NodeJS.Timeout> = new Set()
|
|
265
278
|
|
|
@@ -267,6 +280,7 @@ export class AsyncQueuer<TValue> {
|
|
|
267
280
|
public fn: (item: TValue) => Promise<any>,
|
|
268
281
|
initialOptions: AsyncQueuerOptions<TValue> = {},
|
|
269
282
|
) {
|
|
283
|
+
this.key = createKey(initialOptions.key)
|
|
270
284
|
this.options = {
|
|
271
285
|
...defaultOptions,
|
|
272
286
|
...initialOptions,
|
|
@@ -290,6 +304,12 @@ export class AsyncQueuer<TValue> {
|
|
|
290
304
|
this.addItem(item, this.options.addItemsTo ?? 'back', isLast)
|
|
291
305
|
}
|
|
292
306
|
}
|
|
307
|
+
|
|
308
|
+
pacerEventClient.on('d-AsyncQueuer', (e) => {
|
|
309
|
+
if (e.payload.key !== this.key) return
|
|
310
|
+
this.#setState(e.payload.store.state)
|
|
311
|
+
this.setOptions(e.payload.options)
|
|
312
|
+
})
|
|
293
313
|
}
|
|
294
314
|
|
|
295
315
|
/**
|
|
@@ -324,6 +344,7 @@ export class AsyncQueuer<TValue> {
|
|
|
324
344
|
status,
|
|
325
345
|
}
|
|
326
346
|
})
|
|
347
|
+
emitChange('AsyncQueuer', this)
|
|
327
348
|
}
|
|
328
349
|
|
|
329
350
|
/**
|
|
@@ -402,6 +423,10 @@ export class AsyncQueuer<TValue> {
|
|
|
402
423
|
position: QueuePosition = this.options.addItemsTo ?? 'back',
|
|
403
424
|
runOnItemsChange: boolean = true,
|
|
404
425
|
): boolean => {
|
|
426
|
+
this.#setState({
|
|
427
|
+
addItemCount: this.store.state.addItemCount + 1,
|
|
428
|
+
})
|
|
429
|
+
|
|
405
430
|
if (this.store.state.items.length >= (this.options.maxSize ?? Infinity)) {
|
|
406
431
|
this.#setState({
|
|
407
432
|
rejectionCount: this.store.state.rejectionCount + 1,
|
|
@@ -482,7 +507,12 @@ export class AsyncQueuer<TValue> {
|
|
|
482
507
|
const { items, itemTimestamps } = this.store.state
|
|
483
508
|
let item: TValue | undefined
|
|
484
509
|
|
|
485
|
-
|
|
510
|
+
// When priority function is provided or position is 'front', always get from front (highest priority)
|
|
511
|
+
// Priority takes precedence over FIFO/LIFO behavior
|
|
512
|
+
if (
|
|
513
|
+
this.options.getPriority !== defaultOptions.getPriority ||
|
|
514
|
+
position === 'front'
|
|
515
|
+
) {
|
|
486
516
|
item = items[0]
|
|
487
517
|
if (item !== undefined) {
|
|
488
518
|
this.#setState({
|