@tanstack/pacer 0.5.0 → 0.6.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.
- package/dist/cjs/async-debouncer.cjs +24 -13
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +49 -7
- package/dist/cjs/async-queuer.cjs +83 -114
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +79 -50
- package/dist/cjs/async-rate-limiter.cjs +20 -9
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +53 -3
- package/dist/cjs/async-throttler.cjs +24 -13
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +48 -6
- package/dist/cjs/types.d.cts +1 -0
- package/dist/esm/async-debouncer.d.ts +49 -7
- package/dist/esm/async-debouncer.js +24 -13
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +79 -50
- package/dist/esm/async-queuer.js +83 -114
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +53 -3
- package/dist/esm/async-rate-limiter.js +20 -9
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +48 -6
- package/dist/esm/async-throttler.js +24 -13
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/types.d.ts +1 -0
- package/package.json +1 -1
- package/src/async-debouncer.ts +66 -16
- package/src/async-queuer.ts +180 -169
- package/src/async-rate-limiter.ts +70 -12
- package/src/async-throttler.ts +66 -16
- package/src/types.ts +3 -0
|
@@ -4,12 +4,6 @@ const utils = require("./utils.cjs");
|
|
|
4
4
|
const defaultOptions = {
|
|
5
5
|
enabled: true,
|
|
6
6
|
leading: true,
|
|
7
|
-
onError: () => {
|
|
8
|
-
},
|
|
9
|
-
onSettled: () => {
|
|
10
|
-
},
|
|
11
|
-
onSuccess: () => {
|
|
12
|
-
},
|
|
13
7
|
trailing: true,
|
|
14
8
|
wait: 0
|
|
15
9
|
};
|
|
@@ -26,7 +20,8 @@ class AsyncThrottler {
|
|
|
26
20
|
this._timeoutId = null;
|
|
27
21
|
this._options = {
|
|
28
22
|
...defaultOptions,
|
|
29
|
-
...initialOptions
|
|
23
|
+
...initialOptions,
|
|
24
|
+
throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
|
|
30
25
|
};
|
|
31
26
|
}
|
|
32
27
|
/**
|
|
@@ -49,7 +44,7 @@ class AsyncThrottler {
|
|
|
49
44
|
* Returns the current enabled state of the throttler
|
|
50
45
|
*/
|
|
51
46
|
getEnabled() {
|
|
52
|
-
return utils.parseFunctionOrValue(this._options.enabled, this);
|
|
47
|
+
return !!utils.parseFunctionOrValue(this._options.enabled, this);
|
|
53
48
|
}
|
|
54
49
|
/**
|
|
55
50
|
* Returns the current wait time in milliseconds
|
|
@@ -58,8 +53,18 @@ class AsyncThrottler {
|
|
|
58
53
|
return utils.parseFunctionOrValue(this._options.wait, this);
|
|
59
54
|
}
|
|
60
55
|
/**
|
|
61
|
-
* Attempts to execute the throttled function
|
|
62
|
-
* If a call is already in progress, it may be blocked or queued depending on the `wait` option
|
|
56
|
+
* Attempts to execute the throttled function.
|
|
57
|
+
* If a call is already in progress, it may be blocked or queued depending on the `wait` option.
|
|
58
|
+
*
|
|
59
|
+
* Error Handling:
|
|
60
|
+
* - If the throttled function throws and no `onError` handler is configured,
|
|
61
|
+
* the error will be thrown from this method.
|
|
62
|
+
* - If an `onError` handler is configured, errors will be caught and passed to the handler,
|
|
63
|
+
* and this method will return undefined.
|
|
64
|
+
* - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
|
|
65
|
+
*
|
|
66
|
+
* @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
|
|
67
|
+
* @throws The error from the throttled function if no onError handler is configured
|
|
63
68
|
*/
|
|
64
69
|
async maybeExecute(...args) {
|
|
65
70
|
const now = Date.now();
|
|
@@ -88,23 +93,29 @@ class AsyncThrottler {
|
|
|
88
93
|
}
|
|
89
94
|
}
|
|
90
95
|
async executeFunction(...args) {
|
|
96
|
+
var _a, _b, _c, _d, _e, _f;
|
|
91
97
|
if (!this.getEnabled() || this._isExecuting) return void 0;
|
|
92
98
|
this._abortController = new AbortController();
|
|
93
99
|
try {
|
|
94
100
|
this._isExecuting = true;
|
|
95
101
|
this._lastResult = await this.fn(...args);
|
|
96
102
|
this._successCount++;
|
|
97
|
-
this._options.onSuccess(this._lastResult, this);
|
|
103
|
+
(_b = (_a = this._options).onSuccess) == null ? void 0 : _b.call(_a, this._lastResult, this);
|
|
98
104
|
} catch (error) {
|
|
99
105
|
this._errorCount++;
|
|
100
|
-
this._options.onError(error, this);
|
|
106
|
+
(_d = (_c = this._options).onError) == null ? void 0 : _d.call(_c, error, this);
|
|
107
|
+
if (this._options.throwOnError) {
|
|
108
|
+
throw error;
|
|
109
|
+
} else {
|
|
110
|
+
console.error(error);
|
|
111
|
+
}
|
|
101
112
|
} finally {
|
|
102
113
|
this._isExecuting = false;
|
|
103
114
|
this._settleCount++;
|
|
104
115
|
this._abortController = null;
|
|
105
116
|
this._lastExecutionTime = Date.now();
|
|
106
117
|
this._nextExecutionTime = this._lastExecutionTime + this.getWait();
|
|
107
|
-
this._options.onSettled(this);
|
|
118
|
+
(_f = (_e = this._options).onSettled) == null ? void 0 : _f.call(_e, this);
|
|
108
119
|
}
|
|
109
120
|
return this._lastResult;
|
|
110
121
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-throttler.cjs","sources":["../../src/async-throttler.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async throttled function\n */\nexport interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {\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: AsyncThrottler<TFn>) => boolean)\n /**\n * Whether to execute the function immediately when called\n * Defaults to true\n */\n leading?: boolean\n /**\n * Optional error handler for when the throttled function throws\n */\n onError?: (error: unknown, asyncThrottler: AsyncThrottler<TFn>) => void\n /**\n * Optional function to call when the throttled function is executed\n */\n onSettled?: (asyncThrottler: AsyncThrottler<TFn>) => void\n /**\n * Optional function to call when the throttled function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n asyncThrottler: AsyncThrottler<TFn>,\n ) => void\n /**\n * Whether to execute the function on the trailing edge of the wait period\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: AsyncThrottler<TFn>) => number)\n}\n\nconst defaultOptions: Required<AsyncThrottlerOptions<any>> = {\n enabled: true,\n leading: true,\n onError: () => {},\n onSettled: () => {},\n onSuccess: () => {},\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async throttled function.\n *\n * Throttling limits how often a function can be executed, allowing only one execution within a specified time window.\n * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a\n * regular interval regardless of how often it's called.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to\n * ensure a maximum execution frequency.\n *\n * @example\n * ```ts\n * const throttler = new AsyncThrottler(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, { wait: 1000 });\n *\n * // Will only execute once per second no matter how often called\n * // Returns the API response directly\n * const result = await throttler.maybeExecute(inputElement.value);\n * ```\n */\nexport class AsyncThrottler<TFn extends AnyAsyncFunction> {\n private _options: Required<AsyncThrottlerOptions<TFn>>\n private _abortController: AbortController | null = null\n private _errorCount = 0\n private _isExecuting = false\n private _lastArgs: Parameters<TFn> | undefined\n private _lastExecutionTime = 0\n private _lastResult: ReturnType<TFn> | undefined\n private _nextExecutionTime = 0\n private _settleCount = 0\n private _successCount = 0\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncThrottlerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the throttler options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncThrottlerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this.cancel()\n }\n }\n\n /**\n * Returns the current options\n */\n getOptions(): Required<AsyncThrottlerOptions<TFn>> {\n return this._options\n }\n\n /**\n * Returns the current enabled state of the throttler\n */\n getEnabled(): boolean {\n return parseFunctionOrValue(this._options.enabled, this)\n }\n\n /**\n * Returns the current wait time in milliseconds\n */\n getWait(): number {\n return parseFunctionOrValue(this._options.wait, this)\n }\n\n /**\n * Attempts to execute the throttled function\n * If a call is already in progress, it may be blocked or queued depending on the `wait` option\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n const now = Date.now()\n const timeSinceLastExecution = now - this._lastExecutionTime\n const wait = this.getWait()\n\n // Handle leading execution\n if (this._options.leading && timeSinceLastExecution >= wait) {\n await this.executeFunction(...args)\n return this._lastResult\n } else {\n // Store the most recent arguments for potential trailing execution\n this._lastArgs = args\n\n return new Promise((resolve) => {\n // Clear any existing timeout to ensure we use the latest arguments\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n }\n\n // Set up trailing execution if enabled\n if (this._options.trailing) {\n const _timeSinceLastExecution = this._lastExecutionTime\n ? now - this._lastExecutionTime\n : 0\n const timeoutDuration = wait - _timeSinceLastExecution\n this._timeoutId = setTimeout(async () => {\n if (this._lastArgs !== undefined) {\n await this.executeFunction(...this._lastArgs)\n }\n resolve(this._lastResult)\n }, timeoutDuration)\n }\n })\n }\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this.getEnabled() || this._isExecuting) return undefined\n this._abortController = new AbortController()\n try {\n this._isExecuting = true\n this._lastResult = await this.fn(...args) // EXECUTE!\n this._successCount++\n this._options.onSuccess(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError(error, this)\n } finally {\n this._isExecuting = false\n this._settleCount++\n this._abortController = null\n this._lastExecutionTime = Date.now()\n this._nextExecutionTime = this._lastExecutionTime + this.getWait()\n this._options.onSettled(this)\n }\n return this._lastResult\n }\n\n /**\n * Cancels any pending execution or aborts any execution in progress\n */\n cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n if (this._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._lastArgs = undefined\n }\n\n /**\n * Returns the last execution time\n */\n getLastExecutionTime(): number {\n return this._lastExecutionTime\n }\n\n /**\n * Returns the next execution time\n */\n getNextExecutionTime(): number {\n return this._nextExecutionTime\n }\n\n /**\n * Returns the last result of the debounced function\n */\n getLastResult(): ReturnType<TFn> | undefined {\n return this._lastResult\n }\n\n /**\n * Returns the number of times the function has been executed successfully\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has settled (completed or errored)\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns the current pending state\n */\n getIsPending(): boolean {\n return this.getEnabled() && !!this._timeoutId\n }\n\n /**\n * Returns the current executing state\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n}\n\n/**\n * Creates an async throttled function that limits how often the function can execute.\n * The throttled function will execute at most once per wait period, even if called multiple times.\n * If called while executing, it will wait until execution completes before scheduling the next call.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * @example\n * ```ts\n * const throttled = asyncThrottle(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, { wait: 1000 });\n *\n * // This will execute at most once per second\n * // Returns the API response directly\n * const result = await throttled(inputElement.value);\n * ```\n */\nexport function asyncThrottle<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncThrottlerOptions<TFn>,\n) {\n const asyncThrottler = new AsyncThrottler(fn, initialOptions)\n return asyncThrottler.maybeExecute.bind(asyncThrottler)\n}\n"],"names":["parseFunctionOrValue"],"mappings":";;;AA8CA,MAAM,iBAAuD;AAAA,EAC3D,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU;AAAA,EACV,MAAM;AACR;AA4BO,MAAM,eAA6C;AAAA,EAaxD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAZV,SAAQ,mBAA2C;AACnD,SAAQ,cAAc;AACtB,SAAQ,eAAe;AAEvB,SAAQ,qBAAqB;AAE7B,SAAQ,qBAAqB;AAC7B,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;AACxB,SAAQ,aAAoC;AAM1C,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAAuD;AAChE,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAG9C,QAAA,CAAC,KAAK,SAAS,SAAS;AAC1B,WAAK,OAAO;AAAA,IAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAMF,aAAmD;AACjD,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,aAAsB;AACpB,WAAOA,MAAqB,qBAAA,KAAK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AACnB,WAAA,qBAAqB,KAAK,IAAI;AACnC,WAAK,qBAAqB,KAAK,qBAAqB,KAAK,QAAQ;AAC5D,WAAA,SAAS,UAAU,IAAI;AAAA,IAAA;AAE9B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,SAAe;AACb,QAAI,KAAK,YAAY;AACnB,mBAAa,KAAK,UAAU;AAC5B,WAAK,aAAa;AAAA,IAAA;AAEpB,QAAI,KAAK,kBAAkB;AACzB,WAAK,iBAAiB,MAAM;AAC5B,WAAK,mBAAmB;AAAA,IAAA;AAE1B,SAAK,YAAY;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMnB,uBAA+B;AAC7B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AAC7B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,gBAA6C;AAC3C,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,kBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAAyB;AACvB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,gBAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACtB,WAAO,KAAK,WAAA,KAAgB,CAAC,CAAC,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMrC,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAEhB;AAuBgB,SAAA,cACd,IACA,gBACA;AACA,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;;;"}
|
|
1
|
+
{"version":3,"file":"async-throttler.cjs","sources":["../../src/async-throttler.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction, OptionalKeys } from './types'\n\n/**\n * Options for configuring an async throttled function\n */\nexport interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {\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: AsyncThrottler<TFn>) => boolean)\n /**\n * Whether to execute the function immediately when called\n * Defaults to true\n */\n leading?: boolean\n /**\n * Optional error handler for when the throttled function throws.\n * If provided, the handler will be called with the error and throttler instance.\n * This can be used alongside throwOnError - the handler will be called before any error is thrown.\n */\n onError?: (error: unknown, asyncThrottler: AsyncThrottler<TFn>) => void\n /**\n * Optional function to call when the throttled function is executed\n */\n onSettled?: (asyncThrottler: AsyncThrottler<TFn>) => void\n /**\n * Optional function to call when the throttled function is executed\n */\n onSuccess?: (\n result: ReturnType<TFn>,\n asyncThrottler: AsyncThrottler<TFn>,\n ) => void\n /**\n * Whether to throw errors when they occur.\n * Defaults to true if no onError handler is provided, false if an onError handler is provided.\n * Can be explicitly set to override these defaults.\n */\n throwOnError?: boolean\n /**\n * Whether to execute the function on the trailing edge of the wait period\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: AsyncThrottler<TFn>) => number)\n}\n\ntype AsyncThrottlerOptionsWithOptionalCallbacks = OptionalKeys<\n AsyncThrottlerOptions<any>,\n 'onError' | 'onSettled' | 'onSuccess'\n>\n\nconst defaultOptions: AsyncThrottlerOptionsWithOptionalCallbacks = {\n enabled: true,\n leading: true,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async throttled function.\n *\n * Throttling limits how often a function can be executed, allowing only one execution within a specified time window.\n * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a\n * regular interval regardless of how often it's called.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to\n * ensure a maximum execution frequency.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncThrottler instance\n *\n * @example\n * ```ts\n * const throttler = new AsyncThrottler(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, {\n * wait: 1000,\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * });\n *\n * // Will only execute once per second no matter how often called\n * // Returns the API response directly\n * const result = await throttler.maybeExecute(inputElement.value);\n * ```\n */\nexport class AsyncThrottler<TFn extends AnyAsyncFunction> {\n private _options: AsyncThrottlerOptionsWithOptionalCallbacks\n private _abortController: AbortController | null = null\n private _errorCount = 0\n private _isExecuting = false\n private _lastArgs: Parameters<TFn> | undefined\n private _lastExecutionTime = 0\n private _lastResult: ReturnType<TFn> | undefined\n private _nextExecutionTime = 0\n private _settleCount = 0\n private _successCount = 0\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncThrottlerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n }\n\n /**\n * Updates the throttler options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncThrottlerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this.cancel()\n }\n }\n\n /**\n * Returns the current options\n */\n getOptions(): AsyncThrottlerOptions<TFn> {\n return this._options\n }\n\n /**\n * Returns the current enabled state of the throttler\n */\n getEnabled(): boolean {\n return !!parseFunctionOrValue(this._options.enabled, this)\n }\n\n /**\n * Returns the current wait time in milliseconds\n */\n getWait(): number {\n return parseFunctionOrValue(this._options.wait, this)\n }\n\n /**\n * Attempts to execute the throttled function.\n * If a call is already in progress, it may be blocked or queued depending on the `wait` option.\n *\n * Error Handling:\n * - If the throttled function throws and no `onError` handler is configured,\n * the error will be thrown from this method.\n * - If an `onError` handler is configured, errors will be caught and passed to the handler,\n * and this method will return undefined.\n * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.\n *\n * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError\n * @throws The error from the throttled function if no onError handler is configured\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n const now = Date.now()\n const timeSinceLastExecution = now - this._lastExecutionTime\n const wait = this.getWait()\n\n // Handle leading execution\n if (this._options.leading && timeSinceLastExecution >= wait) {\n await this.executeFunction(...args)\n return this._lastResult\n } else {\n // Store the most recent arguments for potential trailing execution\n this._lastArgs = args\n\n return new Promise((resolve) => {\n // Clear any existing timeout to ensure we use the latest arguments\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n }\n\n // Set up trailing execution if enabled\n if (this._options.trailing) {\n const _timeSinceLastExecution = this._lastExecutionTime\n ? now - this._lastExecutionTime\n : 0\n const timeoutDuration = wait - _timeSinceLastExecution\n this._timeoutId = setTimeout(async () => {\n if (this._lastArgs !== undefined) {\n await this.executeFunction(...this._lastArgs)\n }\n resolve(this._lastResult)\n }, timeoutDuration)\n }\n })\n }\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this.getEnabled() || this._isExecuting) return undefined\n this._abortController = new AbortController()\n try {\n this._isExecuting = true\n this._lastResult = await this.fn(...args) // EXECUTE!\n this._successCount++\n this._options.onSuccess?.(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError?.(error, this)\n if (this._options.throwOnError) {\n throw error\n } else {\n console.error(error)\n }\n } finally {\n this._isExecuting = false\n this._settleCount++\n this._abortController = null\n this._lastExecutionTime = Date.now()\n this._nextExecutionTime = this._lastExecutionTime + this.getWait()\n this._options.onSettled?.(this)\n }\n return this._lastResult\n }\n\n /**\n * Cancels any pending execution or aborts any execution in progress\n */\n cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n if (this._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._lastArgs = undefined\n }\n\n /**\n * Returns the last execution time\n */\n getLastExecutionTime(): number {\n return this._lastExecutionTime\n }\n\n /**\n * Returns the next execution time\n */\n getNextExecutionTime(): number {\n return this._nextExecutionTime\n }\n\n /**\n * Returns the last result of the debounced function\n */\n getLastResult(): ReturnType<TFn> | undefined {\n return this._lastResult\n }\n\n /**\n * Returns the number of times the function has been executed successfully\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has settled (completed or errored)\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns the current pending state\n */\n getIsPending(): boolean {\n return this.getEnabled() && !!this._timeoutId\n }\n\n /**\n * Returns the current executing state\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n}\n\n/**\n * Creates an async throttled function that limits how often the function can execute.\n * The throttled function will execute at most once per wait period, even if called multiple times.\n * If called while executing, it will wait until execution completes before scheduling the next call.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncThrottler instance\n *\n * @example\n * ```ts\n * const throttled = asyncThrottle(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, {\n * wait: 1000,\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * });\n *\n * // This will execute at most once per second\n * // Returns the API response directly\n * const result = await throttled(inputElement.value);\n * ```\n */\nexport function asyncThrottle<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncThrottlerOptions<TFn>,\n) {\n const asyncThrottler = new AsyncThrottler(fn, initialOptions)\n return asyncThrottler.maybeExecute.bind(asyncThrottler)\n}\n"],"names":["parseFunctionOrValue"],"mappings":";;;AA2DA,MAAM,iBAA6D;AAAA,EACjE,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,MAAM;AACR;AAwCO,MAAM,eAA6C;AAAA,EAaxD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAZV,SAAQ,mBAA2C;AACnD,SAAQ,cAAc;AACtB,SAAQ,eAAe;AAEvB,SAAQ,qBAAqB;AAE7B,SAAQ,qBAAqB;AAC7B,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;AACxB,SAAQ,aAAoC;AAM1C,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,MACH,cAAc,eAAe,gBAAgB,CAAC,eAAe;AAAA,IAC/D;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAAuD;AAChE,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAG9C,QAAA,CAAC,KAAK,SAAS,SAAS;AAC1B,WAAK,OAAO;AAAA,IAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAMF,aAAyC;AACvC,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,aAAsB;AACpB,WAAO,CAAC,CAACA,MAAAA,qBAAqB,KAAK,SAAS,SAAS,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM3D,UAAkB;AAChB,WAAOA,MAAqB,qBAAA,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Function> {
|
|
|
15
15
|
*/
|
|
16
16
|
leading?: boolean;
|
|
17
17
|
/**
|
|
18
|
-
* Optional error handler for when the throttled function throws
|
|
18
|
+
* Optional error handler for when the throttled function throws.
|
|
19
|
+
* If provided, the handler will be called with the error and throttler instance.
|
|
20
|
+
* This can be used alongside throwOnError - the handler will be called before any error is thrown.
|
|
19
21
|
*/
|
|
20
22
|
onError?: (error: unknown, asyncThrottler: AsyncThrottler<TFn>) => void;
|
|
21
23
|
/**
|
|
@@ -26,6 +28,12 @@ export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {
|
|
|
26
28
|
* Optional function to call when the throttled function is executed
|
|
27
29
|
*/
|
|
28
30
|
onSuccess?: (result: ReturnType<TFn>, asyncThrottler: AsyncThrottler<TFn>) => void;
|
|
31
|
+
/**
|
|
32
|
+
* Whether to throw errors when they occur.
|
|
33
|
+
* Defaults to true if no onError handler is provided, false if an onError handler is provided.
|
|
34
|
+
* Can be explicitly set to override these defaults.
|
|
35
|
+
*/
|
|
36
|
+
throwOnError?: boolean;
|
|
29
37
|
/**
|
|
30
38
|
* Whether to execute the function on the trailing edge of the wait period
|
|
31
39
|
* Defaults to true
|
|
@@ -52,12 +60,24 @@ export interface AsyncThrottlerOptions<TFn extends AnyAsyncFunction> {
|
|
|
52
60
|
* This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to
|
|
53
61
|
* ensure a maximum execution frequency.
|
|
54
62
|
*
|
|
63
|
+
* Error Handling:
|
|
64
|
+
* - If an `onError` handler is provided, it will be called with the error and throttler instance
|
|
65
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
66
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
67
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
68
|
+
* - The error state can be checked using the underlying AsyncThrottler instance
|
|
69
|
+
*
|
|
55
70
|
* @example
|
|
56
71
|
* ```ts
|
|
57
72
|
* const throttler = new AsyncThrottler(async (value: string) => {
|
|
58
73
|
* const result = await saveToAPI(value);
|
|
59
74
|
* return result; // Return value is preserved
|
|
60
|
-
* }, {
|
|
75
|
+
* }, {
|
|
76
|
+
* wait: 1000,
|
|
77
|
+
* onError: (error) => {
|
|
78
|
+
* console.error('API call failed:', error);
|
|
79
|
+
* }
|
|
80
|
+
* });
|
|
61
81
|
*
|
|
62
82
|
* // Will only execute once per second no matter how often called
|
|
63
83
|
* // Returns the API response directly
|
|
@@ -86,7 +106,7 @@ export declare class AsyncThrottler<TFn extends AnyAsyncFunction> {
|
|
|
86
106
|
/**
|
|
87
107
|
* Returns the current options
|
|
88
108
|
*/
|
|
89
|
-
getOptions():
|
|
109
|
+
getOptions(): AsyncThrottlerOptions<TFn>;
|
|
90
110
|
/**
|
|
91
111
|
* Returns the current enabled state of the throttler
|
|
92
112
|
*/
|
|
@@ -96,8 +116,18 @@ export declare class AsyncThrottler<TFn extends AnyAsyncFunction> {
|
|
|
96
116
|
*/
|
|
97
117
|
getWait(): number;
|
|
98
118
|
/**
|
|
99
|
-
* Attempts to execute the throttled function
|
|
100
|
-
* If a call is already in progress, it may be blocked or queued depending on the `wait` option
|
|
119
|
+
* Attempts to execute the throttled function.
|
|
120
|
+
* If a call is already in progress, it may be blocked or queued depending on the `wait` option.
|
|
121
|
+
*
|
|
122
|
+
* Error Handling:
|
|
123
|
+
* - If the throttled function throws and no `onError` handler is configured,
|
|
124
|
+
* the error will be thrown from this method.
|
|
125
|
+
* - If an `onError` handler is configured, errors will be caught and passed to the handler,
|
|
126
|
+
* and this method will return undefined.
|
|
127
|
+
* - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
|
|
128
|
+
*
|
|
129
|
+
* @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
|
|
130
|
+
* @throws The error from the throttled function if no onError handler is configured
|
|
101
131
|
*/
|
|
102
132
|
maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
|
|
103
133
|
private executeFunction;
|
|
@@ -147,12 +177,24 @@ export declare class AsyncThrottler<TFn extends AnyAsyncFunction> {
|
|
|
147
177
|
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
148
178
|
* instead of setting the result on a state variable from within the throttled function.
|
|
149
179
|
*
|
|
180
|
+
* Error Handling:
|
|
181
|
+
* - If an `onError` handler is provided, it will be called with the error and throttler instance
|
|
182
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
183
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
184
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
185
|
+
* - The error state can be checked using the underlying AsyncThrottler instance
|
|
186
|
+
*
|
|
150
187
|
* @example
|
|
151
188
|
* ```ts
|
|
152
189
|
* const throttled = asyncThrottle(async (value: string) => {
|
|
153
190
|
* const result = await saveToAPI(value);
|
|
154
191
|
* return result; // Return value is preserved
|
|
155
|
-
* }, {
|
|
192
|
+
* }, {
|
|
193
|
+
* wait: 1000,
|
|
194
|
+
* onError: (error) => {
|
|
195
|
+
* console.error('API call failed:', error);
|
|
196
|
+
* }
|
|
197
|
+
* });
|
|
156
198
|
*
|
|
157
199
|
* // This will execute at most once per second
|
|
158
200
|
* // Returns the API response directly
|
package/dist/cjs/types.d.cts
CHANGED
|
@@ -6,3 +6,4 @@ export type AnyFunction = (...args: Array<any>) => any;
|
|
|
6
6
|
* Represents an asynchronous function that can be called with any arguments and returns a promise.
|
|
7
7
|
*/
|
|
8
8
|
export type AnyAsyncFunction = (...args: Array<any>) => Promise<any>;
|
|
9
|
+
export type OptionalKeys<T, TKey extends keyof T> = Omit<T, TKey> & Partial<Pick<T, TKey>>;
|
|
@@ -15,7 +15,9 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
|
15
15
|
*/
|
|
16
16
|
leading?: boolean;
|
|
17
17
|
/**
|
|
18
|
-
* Optional error handler for when the debounced function throws
|
|
18
|
+
* Optional error handler for when the debounced function throws.
|
|
19
|
+
* If provided, the handler will be called with the error and debouncer instance.
|
|
20
|
+
* This can be used alongside throwOnError - the handler will be called before any error is thrown.
|
|
19
21
|
*/
|
|
20
22
|
onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void;
|
|
21
23
|
/**
|
|
@@ -26,6 +28,12 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
|
26
28
|
* Optional callback to call when the debounced function is executed
|
|
27
29
|
*/
|
|
28
30
|
onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<TFn>) => void;
|
|
31
|
+
/**
|
|
32
|
+
* Whether to throw errors when they occur.
|
|
33
|
+
* Defaults to true if no onError handler is provided, false if an onError handler is provided.
|
|
34
|
+
* Can be explicitly set to override these defaults.
|
|
35
|
+
*/
|
|
36
|
+
throwOnError?: boolean;
|
|
29
37
|
/**
|
|
30
38
|
* Whether to execute on the trailing edge of the timeout.
|
|
31
39
|
* Defaults to true.
|
|
@@ -52,12 +60,23 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
|
52
60
|
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
53
61
|
* instead of setting the result on a state variable from within the debounced function.
|
|
54
62
|
*
|
|
63
|
+
* Error Handling:
|
|
64
|
+
* - If an error occurs during execution and no `onError` handler is provided, the error will be thrown and propagate up to the caller.
|
|
65
|
+
* - If an `onError` handler is provided, errors will be caught and passed to the handler instead of being thrown.
|
|
66
|
+
* - The error count can be tracked using `getErrorCount()`.
|
|
67
|
+
* - The debouncer maintains its state and can continue to be used after an error occurs.
|
|
68
|
+
*
|
|
55
69
|
* @example
|
|
56
70
|
* ```ts
|
|
57
71
|
* const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
|
|
58
72
|
* const results = await searchAPI(value);
|
|
59
73
|
* return results; // Return value is preserved
|
|
60
|
-
* }, {
|
|
74
|
+
* }, {
|
|
75
|
+
* wait: 500,
|
|
76
|
+
* onError: (error) => {
|
|
77
|
+
* console.error('Search failed:', error);
|
|
78
|
+
* }
|
|
79
|
+
* });
|
|
61
80
|
*
|
|
62
81
|
* // Called on each keystroke but only executes after 500ms of no typing
|
|
63
82
|
* // Returns the API response directly
|
|
@@ -66,6 +85,7 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
|
66
85
|
*/
|
|
67
86
|
export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
68
87
|
private fn;
|
|
88
|
+
private _options;
|
|
69
89
|
private _abortController;
|
|
70
90
|
private _canLeadingExecute;
|
|
71
91
|
private _errorCount;
|
|
@@ -73,7 +93,6 @@ export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
73
93
|
private _isPending;
|
|
74
94
|
private _lastArgs;
|
|
75
95
|
private _lastResult;
|
|
76
|
-
private _options;
|
|
77
96
|
private _settleCount;
|
|
78
97
|
private _successCount;
|
|
79
98
|
private _timeoutId;
|
|
@@ -86,7 +105,7 @@ export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
86
105
|
/**
|
|
87
106
|
* Returns the current debouncer options
|
|
88
107
|
*/
|
|
89
|
-
getOptions():
|
|
108
|
+
getOptions(): AsyncDebouncerOptions<TFn>;
|
|
90
109
|
/**
|
|
91
110
|
* Returns the current debouncer enabled state
|
|
92
111
|
*/
|
|
@@ -96,8 +115,18 @@ export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
96
115
|
*/
|
|
97
116
|
getWait(): number;
|
|
98
117
|
/**
|
|
99
|
-
* Attempts to execute the debounced function
|
|
100
|
-
* If a call is already in progress, it will be queued
|
|
118
|
+
* Attempts to execute the debounced function.
|
|
119
|
+
* If a call is already in progress, it will be queued.
|
|
120
|
+
*
|
|
121
|
+
* Error Handling:
|
|
122
|
+
* - If the debounced function throws and no `onError` handler is configured,
|
|
123
|
+
* the error will be thrown from this method.
|
|
124
|
+
* - If an `onError` handler is configured, errors will be caught and passed to the handler,
|
|
125
|
+
* and this method will return undefined.
|
|
126
|
+
* - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
|
|
127
|
+
*
|
|
128
|
+
* @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
|
|
129
|
+
* @throws The error from the debounced function if no onError handler is configured
|
|
101
130
|
*/
|
|
102
131
|
maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
|
|
103
132
|
private executeFunction;
|
|
@@ -143,12 +172,25 @@ export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
143
172
|
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
144
173
|
* instead of setting the result on a state variable from within the debounced function.
|
|
145
174
|
*
|
|
175
|
+
* Error Handling:
|
|
176
|
+
* - If an `onError` handler is provided, it will be called with the error and debouncer instance
|
|
177
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
178
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
179
|
+
* - The error state can be checked using the underlying AsyncDebouncer instance
|
|
180
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
181
|
+
*
|
|
146
182
|
* @example
|
|
147
183
|
* ```ts
|
|
148
184
|
* const debounced = asyncDebounce(async (value: string) => {
|
|
149
185
|
* const result = await saveToAPI(value);
|
|
150
186
|
* return result; // Return value is preserved
|
|
151
|
-
* }, {
|
|
187
|
+
* }, {
|
|
188
|
+
* wait: 1000,
|
|
189
|
+
* onError: (error) => {
|
|
190
|
+
* console.error('API call failed:', error);
|
|
191
|
+
* },
|
|
192
|
+
* throwOnError: true // Will both log the error and throw it
|
|
193
|
+
* });
|
|
152
194
|
*
|
|
153
195
|
* // Will only execute once, 1 second after the last call
|
|
154
196
|
* // Returns the API response directly
|
|
@@ -2,12 +2,6 @@ import { parseFunctionOrValue } from "./utils.js";
|
|
|
2
2
|
const defaultOptions = {
|
|
3
3
|
enabled: true,
|
|
4
4
|
leading: false,
|
|
5
|
-
onError: () => {
|
|
6
|
-
},
|
|
7
|
-
onSettled: () => {
|
|
8
|
-
},
|
|
9
|
-
onSuccess: () => {
|
|
10
|
-
},
|
|
11
5
|
trailing: true,
|
|
12
6
|
wait: 0
|
|
13
7
|
};
|
|
@@ -24,7 +18,8 @@ class AsyncDebouncer {
|
|
|
24
18
|
this._timeoutId = null;
|
|
25
19
|
this._options = {
|
|
26
20
|
...defaultOptions,
|
|
27
|
-
...initialOptions
|
|
21
|
+
...initialOptions,
|
|
22
|
+
throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
|
|
28
23
|
};
|
|
29
24
|
}
|
|
30
25
|
/**
|
|
@@ -47,7 +42,7 @@ class AsyncDebouncer {
|
|
|
47
42
|
* Returns the current debouncer enabled state
|
|
48
43
|
*/
|
|
49
44
|
getEnabled() {
|
|
50
|
-
return parseFunctionOrValue(this._options.enabled, this);
|
|
45
|
+
return !!parseFunctionOrValue(this._options.enabled, this);
|
|
51
46
|
}
|
|
52
47
|
/**
|
|
53
48
|
* Returns the current debouncer wait state
|
|
@@ -56,8 +51,18 @@ class AsyncDebouncer {
|
|
|
56
51
|
return parseFunctionOrValue(this._options.wait, this);
|
|
57
52
|
}
|
|
58
53
|
/**
|
|
59
|
-
* Attempts to execute the debounced function
|
|
60
|
-
* If a call is already in progress, it will be queued
|
|
54
|
+
* Attempts to execute the debounced function.
|
|
55
|
+
* If a call is already in progress, it will be queued.
|
|
56
|
+
*
|
|
57
|
+
* Error Handling:
|
|
58
|
+
* - If the debounced function throws and no `onError` handler is configured,
|
|
59
|
+
* the error will be thrown from this method.
|
|
60
|
+
* - If an `onError` handler is configured, errors will be caught and passed to the handler,
|
|
61
|
+
* and this method will return undefined.
|
|
62
|
+
* - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
|
|
63
|
+
*
|
|
64
|
+
* @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
|
|
65
|
+
* @throws The error from the debounced function if no onError handler is configured
|
|
61
66
|
*/
|
|
62
67
|
async maybeExecute(...args) {
|
|
63
68
|
this._cancel();
|
|
@@ -81,22 +86,28 @@ class AsyncDebouncer {
|
|
|
81
86
|
});
|
|
82
87
|
}
|
|
83
88
|
async executeFunction(...args) {
|
|
89
|
+
var _a, _b, _c, _d, _e, _f;
|
|
84
90
|
if (!this.getEnabled()) return void 0;
|
|
85
91
|
this._abortController = new AbortController();
|
|
86
92
|
try {
|
|
87
93
|
this._isExecuting = true;
|
|
88
94
|
this._lastResult = await this.fn(...args);
|
|
89
95
|
this._successCount++;
|
|
90
|
-
this._options.onSuccess(this._lastResult, this);
|
|
96
|
+
(_b = (_a = this._options).onSuccess) == null ? void 0 : _b.call(_a, this._lastResult, this);
|
|
91
97
|
} catch (error) {
|
|
92
98
|
this._errorCount++;
|
|
93
|
-
this._options.onError(error, this);
|
|
99
|
+
(_d = (_c = this._options).onError) == null ? void 0 : _d.call(_c, error, this);
|
|
100
|
+
if (this._options.throwOnError) {
|
|
101
|
+
throw error;
|
|
102
|
+
} else {
|
|
103
|
+
console.error(error);
|
|
104
|
+
}
|
|
94
105
|
} finally {
|
|
95
106
|
this._isExecuting = false;
|
|
96
107
|
this._isPending = false;
|
|
97
108
|
this._settleCount++;
|
|
98
109
|
this._abortController = null;
|
|
99
|
-
this._options.onSettled(this);
|
|
110
|
+
(_f = (_e = this._options).onSettled) == null ? void 0 : _f.call(_e, this);
|
|
100
111
|
}
|
|
101
112
|
return this._lastResult;
|
|
102
113
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-debouncer.js","sources":["../../src/async-debouncer.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: AsyncDebouncer<TFn>) => boolean)\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Optional error handler for when the debounced function throws\n */\n onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSettled?: (debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds to wait after the last call before executing.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: AsyncDebouncer<TFn>) => number)\n}\n\nconst defaultOptions: Required<AsyncDebouncerOptions<any>> = {\n enabled: true,\n leading: false,\n onError: () => {},\n onSettled: () => {},\n onSuccess: () => {},\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * @example\n * ```ts\n * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {\n * const results = await searchAPI(value);\n * return results; // Return value is preserved\n * }, { wait: 500 });\n *\n * // Called on each keystroke but only executes after 500ms of no typing\n * // Returns the API response directly\n * const results = await asyncDebouncer.maybeExecute(inputElement.value);\n * ```\n */\nexport class AsyncDebouncer<TFn extends AnyAsyncFunction> {\n private _abortController: AbortController | null = null\n private _canLeadingExecute = true\n private _errorCount = 0\n private _isExecuting = false\n private _isPending = false\n private _lastArgs: Parameters<TFn> | undefined\n private _lastResult: ReturnType<TFn> | undefined\n private _options: Required<AsyncDebouncerOptions<TFn>>\n private _settleCount = 0\n private _successCount = 0\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the debouncer options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this._isPending = false\n }\n }\n\n /**\n * Returns the current debouncer options\n */\n getOptions(): Required<AsyncDebouncerOptions<TFn>> {\n return this._options\n }\n\n /**\n * Returns the current debouncer enabled state\n */\n getEnabled(): boolean {\n return parseFunctionOrValue(this._options.enabled, this)\n }\n\n /**\n * Returns the current debouncer wait state\n */\n getWait(): number {\n return parseFunctionOrValue(this._options.wait, this)\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this._cancel()\n this._lastArgs = args\n\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this._canLeadingExecute = false\n await this.executeFunction(...args)\n return this._lastResult\n }\n\n // Handle trailing execution\n if (this._options.trailing) {\n this._isPending = true\n }\n\n return new Promise((resolve) => {\n this._timeoutId = setTimeout(async () => {\n // Execute trailing if enabled\n if (this._options.trailing && this._lastArgs) {\n await this.executeFunction(...this._lastArgs)\n }\n\n // Reset state and resolve\n this._canLeadingExecute = true\n resolve(this._lastResult)\n }, this.getWait())\n })\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this.getEnabled()) return undefined\n this._abortController = new AbortController()\n try {\n this._isExecuting = true\n this._lastResult = await this.fn(...args) // EXECUTE!\n this._successCount++\n this._options.onSuccess(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError(error, this)\n } finally {\n this._isExecuting = false\n this._isPending = false\n this._settleCount++\n this._abortController = null\n this._options.onSettled(this)\n }\n return this._lastResult\n }\n\n /**\n * Cancel without resetting _canLeadingExecute\n */\n private _cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n if (this._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._lastArgs = undefined\n this._isPending = false\n this._isExecuting = false\n }\n\n /**\n * Cancels any pending execution or aborts any execution in progress\n */\n cancel(): void {\n this._canLeadingExecute = true\n this._cancel()\n }\n\n /**\n * Returns the last result of the debounced function\n */\n getLastResult(): ReturnType<TFn> | undefined {\n return this._lastResult\n }\n\n /**\n * Returns the number of times the function has been executed successfully\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has settled (completed or errored)\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns `true` if there is a pending execution queued up for trailing execution\n */\n getIsPending(): boolean {\n return this.getEnabled() && this._isPending\n }\n\n /**\n * Returns `true` if there is currently an execution in progress\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n}\n\n/**\n * Creates an async debounced function that delays execution until after a specified wait time.\n * The debounced function will only execute once the wait period has elapsed without any new calls.\n * If called again during the wait period, the timer resets and a new wait period begins.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * @example\n * ```ts\n * const debounced = asyncDebounce(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, { wait: 1000 });\n *\n * // Will only execute once, 1 second after the last call\n * // Returns the API response directly\n * const result = await debounced(\"third\");\n * ```\n */\nexport function asyncDebounce<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n) {\n const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)\n return asyncDebouncer.maybeExecute.bind(asyncDebouncer)\n}\n"],"names":[],"mappings":";AA2CA,MAAM,iBAAuD;AAAA,EAC3D,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU;AAAA,EACV,MAAM;AACR;AA4BO,MAAM,eAA6C;AAAA,EAaxD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAbV,SAAQ,mBAA2C;AACnD,SAAQ,qBAAqB;AAC7B,SAAQ,cAAc;AACtB,SAAQ,eAAe;AACvB,SAAQ,aAAa;AAIrB,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;AACxB,SAAQ,aAAoC;AAM1C,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAAuD;AAChE,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAG9C,QAAA,CAAC,KAAK,SAAS,SAAS;AAC1B,WAAK,aAAa;AAAA,IAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAMF,aAAmD;AACjD,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,aAAsB;AACpB,WAAO,qBAAqB,KAAK,SAAS,SAAS,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMzD,UAAkB;AAChB,WAAO,qBAAqB,KAAK,SAAS,MAAM,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOtD,MAAM,gBACD,MACmC;AACtC,SAAK,QAAQ;AACb,SAAK,YAAY;AAGjB,QAAI,KAAK,SA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K,qBAAqB;AAC1B,SAAK,QAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMf,gBAA6C;AAC3C,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,kBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAAyB;AACvB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,gBAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACf,WAAA,KAAK,gBAAgB,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMnC,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAEhB;AAuBgB,SAAA,cACd,IACA,gBACA;AACA,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;"}
|
|
1
|
+
{"version":3,"file":"async-debouncer.js","sources":["../../src/async-debouncer.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction, OptionalKeys } from './types'\n\n/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: AsyncDebouncer<TFn>) => boolean)\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Optional error handler for when the debounced function throws.\n * If provided, the handler will be called with the error and debouncer instance.\n * This can be used alongside throwOnError - the handler will be called before any error is thrown.\n */\n onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSettled?: (debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Whether to throw errors when they occur.\n * Defaults to true if no onError handler is provided, false if an onError handler is provided.\n * Can be explicitly set to override these defaults.\n */\n throwOnError?: boolean\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds to wait after the last call before executing.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: AsyncDebouncer<TFn>) => number)\n}\n\ntype AsyncDebouncerOptionsWithOptionalCallbacks = OptionalKeys<\n AsyncDebouncerOptions<any>,\n 'onError' | 'onSettled' | 'onSuccess'\n>\n\nconst defaultOptions: AsyncDebouncerOptionsWithOptionalCallbacks = {\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an error occurs during execution and no `onError` handler is provided, the error will be thrown and propagate up to the caller.\n * - If an `onError` handler is provided, errors will be caught and passed to the handler instead of being thrown.\n * - The error count can be tracked using `getErrorCount()`.\n * - The debouncer maintains its state and can continue to be used after an error occurs.\n *\n * @example\n * ```ts\n * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {\n * const results = await searchAPI(value);\n * return results; // Return value is preserved\n * }, {\n * wait: 500,\n * onError: (error) => {\n * console.error('Search failed:', error);\n * }\n * });\n *\n * // Called on each keystroke but only executes after 500ms of no typing\n * // Returns the API response directly\n * const results = await asyncDebouncer.maybeExecute(inputElement.value);\n * ```\n */\nexport class AsyncDebouncer<TFn extends AnyAsyncFunction> {\n private _options: AsyncDebouncerOptionsWithOptionalCallbacks\n private _abortController: AbortController | null = null\n private _canLeadingExecute = true\n private _errorCount = 0\n private _isExecuting = false\n private _isPending = false\n private _lastArgs: Parameters<TFn> | undefined\n private _lastResult: ReturnType<TFn> | undefined\n private _settleCount = 0\n private _successCount = 0\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n }\n\n /**\n * Updates the debouncer options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this._isPending = false\n }\n }\n\n /**\n * Returns the current debouncer options\n */\n getOptions(): AsyncDebouncerOptions<TFn> {\n return this._options\n }\n\n /**\n * Returns the current debouncer enabled state\n */\n getEnabled(): boolean {\n return !!parseFunctionOrValue(this._options.enabled, this)\n }\n\n /**\n * Returns the current debouncer wait state\n */\n getWait(): number {\n return parseFunctionOrValue(this._options.wait, this)\n }\n\n /**\n * Attempts to execute the debounced function.\n * If a call is already in progress, it will be queued.\n *\n * Error Handling:\n * - If the debounced function throws and no `onError` handler is configured,\n * the error will be thrown from this method.\n * - If an `onError` handler is configured, errors will be caught and passed to the handler,\n * and this method will return undefined.\n * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.\n *\n * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError\n * @throws The error from the debounced function if no onError handler is configured\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this._cancel()\n this._lastArgs = args\n\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this._canLeadingExecute = false\n await this.executeFunction(...args)\n return this._lastResult\n }\n\n // Handle trailing execution\n if (this._options.trailing) {\n this._isPending = true\n }\n\n return new Promise((resolve) => {\n this._timeoutId = setTimeout(async () => {\n // Execute trailing if enabled\n if (this._options.trailing && this._lastArgs) {\n await this.executeFunction(...this._lastArgs)\n }\n\n // Reset state and resolve\n this._canLeadingExecute = true\n resolve(this._lastResult)\n }, this.getWait())\n })\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this.getEnabled()) return undefined\n this._abortController = new AbortController()\n try {\n this._isExecuting = true\n this._lastResult = await this.fn(...args) // EXECUTE!\n this._successCount++\n this._options.onSuccess?.(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError?.(error, this)\n if (this._options.throwOnError) {\n throw error\n } else {\n console.error(error)\n }\n } finally {\n this._isExecuting = false\n this._isPending = false\n this._settleCount++\n this._abortController = null\n this._options.onSettled?.(this)\n }\n return this._lastResult\n }\n\n /**\n * Cancel without resetting _canLeadingExecute\n */\n private _cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n if (this._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._lastArgs = undefined\n this._isPending = false\n this._isExecuting = false\n }\n\n /**\n * Cancels any pending execution or aborts any execution in progress\n */\n cancel(): void {\n this._canLeadingExecute = true\n this._cancel()\n }\n\n /**\n * Returns the last result of the debounced function\n */\n getLastResult(): ReturnType<TFn> | undefined {\n return this._lastResult\n }\n\n /**\n * Returns the number of times the function has been executed successfully\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has settled (completed or errored)\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns `true` if there is a pending execution queued up for trailing execution\n */\n getIsPending(): boolean {\n return this.getEnabled() && this._isPending\n }\n\n /**\n * Returns `true` if there is currently an execution in progress\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n}\n\n/**\n * Creates an async debounced function that delays execution until after a specified wait time.\n * The debounced function will only execute once the wait period has elapsed without any new calls.\n * If called again during the wait period, the timer resets and a new wait period begins.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - The error state can be checked using the underlying AsyncDebouncer instance\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n *\n * @example\n * ```ts\n * const debounced = asyncDebounce(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, {\n * wait: 1000,\n * onError: (error) => {\n * console.error('API call failed:', error);\n * },\n * throwOnError: true // Will both log the error and throw it\n * });\n *\n * // Will only execute once, 1 second after the last call\n * // Returns the API response directly\n * const result = await debounced(\"third\");\n * ```\n */\nexport function asyncDebounce<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n) {\n const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)\n return asyncDebouncer.maybeExecute.bind(asyncDebouncer)\n}\n"],"names":[],"mappings":";AAwDA,MAAM,iBAA6D;AAAA,EACjE,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,MAAM;AACR;AAuCO,MAAM,eAA6C;AAAA,EAaxD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAZV,SAAQ,mBAA2C;AACnD,SAAQ,qBAAqB;AAC7B,SAAQ,cAAc;AACtB,SAAQ,eAAe;AACvB,SAAQ,aAAa;AAGrB,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;AACxB,SAAQ,aAAoC;AAM1C,SAAK,WAAW;AAAA,MACd,GAAG;AA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