@avatijs/debounce 0.1.1 → 0.1.3

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/umd/index.js CHANGED
@@ -1,8 +1,384 @@
1
1
  /*!
2
- * @avatijs/debounce 0.1.1
2
+ * @avatijs/debounce 0.1.3
3
3
  * Copyright (c) 2024 Khaled Sameer <khaled.smq@hotmail.com>
4
4
  * Licensed under MIT, https://opensource.org/licenses/MIT/
5
5
  * Please visit https://avati.io/ for details.
6
6
  */
7
- !function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define("Avati",[],n):"object"==typeof exports?exports.Avati=n():e.Avati=n()}("undefined"!=typeof self?self:this,(()=>(()=>{"use strict";var e={d:(n,o)=>{for(var t in o)e.o(o,t)&&!e.o(n,t)&&Object.defineProperty(n,t,{enumerable:!0,get:o[t]})},o:(e,n)=>Object.prototype.hasOwnProperty.call(e,n),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"t",{value:!0})}},n={};e.r(n),e.d(n,{debounce:()=>i});const o=new WeakMap,t=e=>({log:(...n)=>e&&void 0,warn:(...n)=>e&&void 0,error:(...n)=>e&&void 0});function i(e,n={}){if("function"!=typeof e)throw new TypeError("Expected a function");const{wait:i=0,leading:r=!1,trailing:c=!0,maxWait:a,debug:u=!1,signal:d,onError:l}=n;if(0>i||void 0!==a&&i>a)throw new RangeError("Invalid wait/maxWait values");if(!r&&!c)throw Error("At least one of leading or trailing must be true");const f=t(u),s={lastInvokeTime:0,pendingPromises:[],aborted:!1};function v(){void 0!==s.timerId&&(clearTimeout(s.timerId),s.timerId=void 0,f.log("Cleared debounce timer")),void 0!==s.maxTimerId&&(clearTimeout(s.maxTimerId),s.maxTimerId=void 0,f.log("Cleared max wait timer"))}function b(){f.log("Cancelling pending invocations"),v(),s.lastInvokeTime=0,s.lastArgs=void 0,s.lastThis=void 0,s.lastCallTime=void 0,g(Error("Debounced function cancelled")),s.pendingPromises.forEach((({reject:e})=>e(Error("Debounced function cancelled")))),s.pendingPromises=[]}function g(e){if(f.error("Error occurred:",e),l)try{l(e)}catch(e){f.error("Error in onError callback:",e)}}function m(){return void 0!==s.timerId}function p(e){if(s.aborted)return!1;const n=void 0===s.lastCallTime?0:e-s.lastCallTime;return void 0===s.lastCallTime||n>=i||0>n||void 0!==a&&e-s.lastInvokeTime>=a}async function w(n){f.log("Invoking function at "+n),s.lastInvokeTime=n;const o=s.lastArgs,t=s.lastThis;s.lastArgs=void 0,s.lastThis=void 0;try{const n=await e.apply(t,o);return s.result=n,s.pendingPromises.forEach((({resolve:e})=>e(n))),s.pendingPromises=[],f.log("Function invoked successfully",n),n}catch(e){const n=e instanceof Error?e:Error(e+"");f.error("Error in function invocation:",n),g(n);const o=[...s.pendingPromises];s.pendingPromises=[],o.forEach((({reject:e})=>e(n)))}}function y(e){const n=function(e){return Math.max(0,i-(s.lastCallTime?e-s.lastCallTime:0))}(e);if(s.timerId=setTimeout(E,n),f.log(`Started debounce timer for ${n}ms`),void 0!==a&&!s.maxTimerId){const n=a-(e-s.lastCallTime);s.maxTimerId=setTimeout((()=>{f.log("Max wait timer expired"),v(),w(Date.now())}),Math.max(0,n)),f.log(`Started max wait timer for ${n}ms`)}}function E(){const e=Date.now();if(f.log("Debounce timer expired"),p(e))return function(e){f.log("Trailing edge triggered"),v(),c&&s.lastArgs?w(e):(s.pendingPromises.forEach((({resolve:e})=>{e(s.result)})),s.pendingPromises=[])}(e);y(e)}d&&d.addEventListener("abort",(()=>{s.aborted=!0,b()}));const h=function(...e){if(s.aborted)return Promise.reject(Error("Debounced function aborted"));const n=Date.now(),o=p(n);return s.lastArgs=e,s.lastThis=this,s.lastCallTime=n,f.log("Function called",{time:n,isInvoking:o,args:e,pending:m()}),new Promise(((e,o)=>{s.pendingPromises.push({resolve:e,reject:o}),void 0===s.timerId?function(e){f.log("Leading edge triggered"),s.lastInvokeTime=e,y(e),r&&w(e)}(n):(v(),y(n))}))};return o.set(h,s),Object.defineProperties(h,{cancel:{value:b,writable:!1,configurable:!1},flush:{value:async function(...e){f.log("Flush requested");const n=e.length>0?e:s.lastArgs,o=s.lastThis;return v(),n?(s.lastArgs=n,s.lastThis=o,w(Date.now())):Promise.resolve(s.result)},writable:!1,configurable:!1},pending:{value:m,writable:!1,configurable:!1},cleanup:{value:function(){f.log("Cleanup initiated"),b(),o.delete(h)},writable:!1,configurable:!1}}),h}return n})()));
7
+
8
+ /* eslint-disable */
9
+
10
+ (function webpackUniversalModuleDefinition(root, factory) {
11
+ if(typeof exports === 'object' && typeof module === 'object')
12
+ module.exports = factory();
13
+ else if(typeof define === 'function' && define.amd)
14
+ define("Avati", [], factory);
15
+ else if(typeof exports === 'object')
16
+ exports["Avati"] = factory();
17
+ else
18
+ root["Avati"] = root["Avati"] || {}, root["Avati"]["Debounce"] = factory();
19
+ })(typeof self !== 'undefined' ? self : this, () => {
20
+ return /******/ (() => { // webpackBootstrap
21
+ /******/ "use strict";
22
+ /******/ // The require scope
23
+ /******/ var __webpack_require__ = {};
24
+ /******/
25
+ /************************************************************************/
26
+ /******/ /* webpack/runtime/define property getters */
27
+ /******/ (() => {
28
+ /******/ // define getter functions for harmony exports
29
+ /******/ __webpack_require__.d = (exports, definition) => {
30
+ /******/ for(var key in definition) {
31
+ /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
32
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
33
+ /******/ }
34
+ /******/ }
35
+ /******/ };
36
+ /******/ })();
37
+ /******/
38
+ /******/ /* webpack/runtime/hasOwnProperty shorthand */
39
+ /******/ (() => {
40
+ /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
41
+ /******/ })();
42
+ /******/
43
+ /******/ /* webpack/runtime/make namespace object */
44
+ /******/ (() => {
45
+ /******/ // define __esModule on exports
46
+ /******/ __webpack_require__.r = (exports) => {
47
+ /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
48
+ /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
49
+ /******/ }
50
+ /******/ Object.defineProperty(exports, '__esModule', { value: true });
51
+ /******/ };
52
+ /******/ })();
53
+ /******/
54
+ /************************************************************************/
55
+ var __webpack_exports__ = {};
56
+ // ESM COMPAT FLAG
57
+ __webpack_require__.r(__webpack_exports__);
58
+
59
+ // EXPORTS
60
+ __webpack_require__.d(__webpack_exports__, {
61
+ debounce: () => (/* reexport */ debounce)
62
+ });
63
+
64
+ ;// ./src/debouce.ts
65
+ /**
66
+ * Advanced debounce utility with TypeScript support
67
+ * Provides a way to limit the rate at which a function can fire by delaying its execution
68
+ * until after a specified amount of time has elapsed since its last invocation.
69
+ * @module debounce
70
+ */
71
+ /** WeakMap to store private state for each debounced function */
72
+ const privateState = new WeakMap();
73
+ /**
74
+ * Creates a logger instance based on debug flag
75
+ * @param debug - Whether debug logging is enabled
76
+ * @returns Object with logging methods
77
+ * @private
78
+ */
79
+ const createLogger = (debug) => ({
80
+ log: (...args) => debug && console.log('[Debounce]', ...args),
81
+ warn: (...args) => debug && console.warn('[Debounce]', ...args),
82
+ error: (...args) => debug && console.error('[Debounce]', ...args),
83
+ });
84
+ /**
85
+ * Creates a debounced version of the provided function that delays invoking func until after
86
+ * wait milliseconds have elapsed since the last time the debounced function was invoked.
87
+ *
88
+ * @template T - The type of the function to debounce
89
+ * @param {T} func - The function to debounce
90
+ * @param {DebounceOptions} [options={}] - Configuration options
91
+ * @returns {DebouncedFunction<T>} The debounced function
92
+ * @throws {TypeError} If func is not a function
93
+ * @throws {RangeError} If wait or maxWait values are invalid
94
+ * @throws {Error} If neither leading nor trailing is true
95
+ *
96
+ * @example
97
+ * const debouncedFn = debounce(async (x: number) => x * 2, { wait: 1000 });
98
+ * await debouncedFn(5); // Will execute after 1000ms of inactivity
99
+ * const debouncedFn = debounce(
100
+ * async (x: number) => x * 2,
101
+ * {
102
+ * wait: 1000,
103
+ * onError: (error) => console.error('Error in debounced function:', error)
104
+ * }
105
+ * );
106
+ */
107
+ function debounce(func, options = {}) {
108
+ // Input validation
109
+ if (typeof func !== 'function') {
110
+ throw new TypeError('Expected a function');
111
+ }
112
+ const { wait = 0, leading = false, trailing = true, maxWait, debug = false, signal, onError, } = options;
113
+ // Validate options
114
+ if (wait < 0 || (maxWait !== undefined && maxWait < wait)) {
115
+ throw new RangeError('Invalid wait/maxWait values');
116
+ }
117
+ if (!leading && !trailing) {
118
+ throw new Error('At least one of leading or trailing must be true');
119
+ }
120
+ const logger = createLogger(debug);
121
+ const state = {
122
+ lastInvokeTime: 0,
123
+ pendingPromises: [],
124
+ aborted: false,
125
+ };
126
+ // Setup abort controller handling
127
+ if (signal) {
128
+ signal.addEventListener('abort', () => {
129
+ state.aborted = true;
130
+ cancel();
131
+ });
132
+ }
133
+ /**
134
+ * Cancels all active timers
135
+ * @private
136
+ */
137
+ function cancelTimers() {
138
+ if (state.timerId !== undefined) {
139
+ clearTimeout(state.timerId);
140
+ state.timerId = undefined;
141
+ logger.log('Cleared debounce timer');
142
+ }
143
+ if (state.maxTimerId !== undefined) {
144
+ clearTimeout(state.maxTimerId);
145
+ state.maxTimerId = undefined;
146
+ logger.log('Cleared max wait timer');
147
+ }
148
+ }
149
+ /**
150
+ * Cancels any pending function invocations
151
+ * Rejects all pending promises and resets internal state
152
+ */
153
+ function cancel() {
154
+ logger.log('Cancelling pending invocations');
155
+ cancelTimers();
156
+ state.lastInvokeTime = 0;
157
+ state.lastArgs = undefined;
158
+ state.lastThis = undefined;
159
+ state.lastCallTime = undefined;
160
+ const error = new Error('Debounced function cancelled');
161
+ handleError(error);
162
+ state.pendingPromises.forEach(({ reject }) => reject(new Error('Debounced function cancelled')));
163
+ state.pendingPromises = [];
164
+ }
165
+ /**
166
+ * Handles errors during function execution
167
+ * @param {Error} error - The error that occurred
168
+ * @private
169
+ */
170
+ function handleError(error) {
171
+ logger.error('Error occurred:', error);
172
+ if (onError) {
173
+ try {
174
+ onError(error);
175
+ }
176
+ catch (callbackError) {
177
+ logger.error('Error in onError callback:', callbackError);
178
+ }
179
+ }
180
+ }
181
+ /**
182
+ * Checks if there are any pending function invocations
183
+ * @returns {boolean} True if there are pending invocations
184
+ */
185
+ function pending() {
186
+ return state.timerId !== undefined;
187
+ }
188
+ /**
189
+ * Determines if the function should be invoked based on timing conditions
190
+ * @param {number} time - Current timestamp
191
+ * @returns {boolean} True if function should be invoked
192
+ * @private
193
+ */
194
+ function shouldInvoke(time) {
195
+ if (state.aborted)
196
+ return false;
197
+ const timeSinceLastCall = state.lastCallTime === undefined ? 0 : time - state.lastCallTime;
198
+ const timeSinceLastInvoke = time - state.lastInvokeTime;
199
+ return (state.lastCallTime === undefined ||
200
+ timeSinceLastCall >= wait ||
201
+ timeSinceLastCall < 0 ||
202
+ (maxWait !== undefined && timeSinceLastInvoke >= maxWait));
203
+ }
204
+ /**
205
+ * Executes the underlying function and manages promise resolution
206
+ * @param {number} time - Current timestamp
207
+ * @returns {Promise} Promise resolving to function result
208
+ * @private
209
+ */
210
+ async function invokeFunc(time) {
211
+ logger.log(`Invoking function at ${time}`);
212
+ state.lastInvokeTime = time;
213
+ const args = state.lastArgs;
214
+ const thisArg = state.lastThis;
215
+ state.lastArgs = undefined;
216
+ state.lastThis = undefined;
217
+ try {
218
+ const result = await func.apply(thisArg, args);
219
+ state.result = result;
220
+ state.pendingPromises.forEach(({ resolve }) => resolve(result));
221
+ state.pendingPromises = [];
222
+ logger.log('Function invoked successfully', result);
223
+ return result;
224
+ }
225
+ catch (error) {
226
+ const wrappedError = error instanceof Error ? error : new Error(String(error));
227
+ logger.error('Error in function invocation:', wrappedError);
228
+ handleError(wrappedError);
229
+ // Clear pending promises after handling error
230
+ const currentPromises = [...state.pendingPromises];
231
+ state.pendingPromises = [];
232
+ // Reject all pending promises
233
+ currentPromises.forEach(({ reject }) => reject(wrappedError));
234
+ }
235
+ }
236
+ /**
237
+ * Starts both the debounce timer and maxWait timer if configured
238
+ * @param {number} time - Current timestamp
239
+ * @private
240
+ */
241
+ function startTimer(time) {
242
+ const remainingTime = remainingWait(time);
243
+ state.timerId = setTimeout(timerExpired, remainingTime);
244
+ logger.log(`Started debounce timer for ${remainingTime}ms`);
245
+ if (maxWait !== undefined && !state.maxTimerId) {
246
+ const timeToMaxWait = maxWait - (time - state.lastCallTime);
247
+ state.maxTimerId = setTimeout(() => {
248
+ logger.log('Max wait timer expired');
249
+ cancelTimers();
250
+ invokeFunc(Date.now());
251
+ }, Math.max(0, timeToMaxWait));
252
+ logger.log(`Started max wait timer for ${timeToMaxWait}ms`);
253
+ }
254
+ }
255
+ /**
256
+ * Calculates remaining wait time before next execution
257
+ * @param {number} time - Current timestamp
258
+ * @returns {number} Milliseconds until next allowed execution
259
+ * @private
260
+ */
261
+ function remainingWait(time) {
262
+ const timeSinceLastCall = state.lastCallTime ? time - state.lastCallTime : 0;
263
+ return Math.max(0, wait - timeSinceLastCall);
264
+ }
265
+ /**
266
+ * Handles timer expiration
267
+ * @private
268
+ */
269
+ function timerExpired() {
270
+ const time = Date.now();
271
+ logger.log('Debounce timer expired');
272
+ if (shouldInvoke(time)) {
273
+ return trailingEdge(time);
274
+ }
275
+ startTimer(time);
276
+ }
277
+ /**
278
+ * Handles leading edge execution
279
+ * @param {number} time - Current timestamp
280
+ * @private
281
+ */
282
+ function leadingEdge(time) {
283
+ logger.log('Leading edge triggered');
284
+ state.lastInvokeTime = time;
285
+ startTimer(time);
286
+ if (leading) {
287
+ invokeFunc(time);
288
+ }
289
+ }
290
+ /**
291
+ * Handles trailing edge execution
292
+ * @param {number} time - Current timestamp
293
+ * @private
294
+ */
295
+ function trailingEdge(time) {
296
+ logger.log('Trailing edge triggered');
297
+ cancelTimers();
298
+ if (trailing && state.lastArgs) {
299
+ invokeFunc(time);
300
+ }
301
+ else {
302
+ state.pendingPromises.forEach(({ resolve }) => {
303
+ resolve(state.result);
304
+ });
305
+ state.pendingPromises = [];
306
+ }
307
+ }
308
+ /**
309
+ * Immediately executes the debounced function
310
+ * @param {...Parameters<T>} args - Function arguments
311
+ * @returns {Promise<ReturnType<T>>} Promise resolving to function result
312
+ */
313
+ async function flush(...args) {
314
+ logger.log('Flush requested');
315
+ const argsToUse = args.length > 0 ? args : state.lastArgs;
316
+ const thisArg = state.lastThis;
317
+ cancelTimers();
318
+ if (argsToUse) {
319
+ state.lastArgs = argsToUse;
320
+ state.lastThis = thisArg;
321
+ return invokeFunc(Date.now());
322
+ }
323
+ return Promise.resolve(state.result);
324
+ }
325
+ /**
326
+ * Cleans up resources used by the debounced function
327
+ */
328
+ function cleanup() {
329
+ logger.log('Cleanup initiated');
330
+ cancel();
331
+ privateState.delete(debounced);
332
+ }
333
+ /**
334
+ * The debounced function that wraps the original
335
+ * @param {...Parameters<T>} args - Function arguments
336
+ * @returns {Promise<ReturnType<T>>} Promise resolving to function result
337
+ */
338
+ const debounced = function (...args) {
339
+ if (state.aborted) {
340
+ return Promise.reject(new Error('Debounced function aborted'));
341
+ }
342
+ const time = Date.now();
343
+ const isInvoking = shouldInvoke(time);
344
+ state.lastArgs = args;
345
+ state.lastThis = this;
346
+ state.lastCallTime = time;
347
+ logger.log('Function called', {
348
+ time,
349
+ isInvoking,
350
+ args,
351
+ pending: pending(),
352
+ });
353
+ return new Promise((resolve, reject) => {
354
+ state.pendingPromises.push({ resolve, reject });
355
+ if (state.timerId === undefined) {
356
+ leadingEdge(time);
357
+ }
358
+ else {
359
+ cancelTimers();
360
+ startTimer(time);
361
+ }
362
+ });
363
+ };
364
+ // Store private state
365
+ privateState.set(debounced, state);
366
+ // Add utility methods
367
+ Object.defineProperties(debounced, {
368
+ cancel: { value: cancel, writable: false, configurable: false },
369
+ flush: { value: flush, writable: false, configurable: false },
370
+ pending: { value: pending, writable: false, configurable: false },
371
+ cleanup: { value: cleanup, writable: false, configurable: false },
372
+ });
373
+ return debounced;
374
+ }
375
+
376
+
377
+ ;// ./src/index.ts
378
+
379
+
380
+ /******/ return __webpack_exports__;
381
+ /******/ })()
382
+ ;
383
+ });
8
384
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","mappings":";;;;;;CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,QAAS,GAAIH,GACM,iBAAZC,QACdA,QAAe,MAAID,IAEnBD,EAAY,MAAIC,GACjB,CATD,CASmB,oBAATK,KAAuBA,KAAOC,MAAM,IAC9C,M,aCTA,IAAIC,EAAsB,CCA1BA,EAAwB,CAACN,EAASO,KACjC,IAAI,IAAIC,KAAOD,EACXD,EAAoBG,EAAEF,EAAYC,KAASF,EAAoBG,EAAET,EAASQ,IAC5EE,OAAOC,eAAeX,EAASQ,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,IAE1E,ECNDF,EAAwB,CAACQ,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFT,EAAyBN,IACH,oBAAXmB,QAA0BA,OAAOC,aAC1CV,OAAOC,eAAeX,EAASmB,OAAOC,YAAa,CAAEC,MAAO,WAE7DX,OAAOC,eAAeX,EAAS,IAAc,CAAEqB,OAAO,GAAO,G,oCCqF9D,MAAMC,EAAe,IAAIC,QAQnBC,EAAgBC,IAAmB,CACrCC,IAAK,IAAIC,IAAgBF,QAASG,EAClCC,KAAM,IAAIF,IAAgBF,QAASG,EACnCE,MAAO,IAAIH,IAAgBF,QAASG,IA0BxC,SAASG,EACLC,EACAC,EAA2B,CAAC,GAG5B,GAAoB,mBAATD,EACP,MAAM,IAAIE,UAAU,uBAGxB,MAAM,KACFC,EAAO,EAAC,QACRC,GAAU,EAAK,SACfC,GAAW,EAAI,QACfC,EAAO,MACPb,GAAQ,EAAK,OACbc,EAAM,QACNC,GACAP,EAGJ,GAAW,EAAPE,QAAyBM,IA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AAOC,cAAc,KAGvDR,CACX,C,ULzbA","sources":["webpack://Avati/webpack/universalModuleDefinition","webpack://Avati/webpack/bootstrap","webpack://Avati/webpack/runtime/define property getters","webpack://Avati/webpack/runtime/hasOwnProperty shorthand","webpack://Avati/webpack/runtime/make namespace object","webpack://Avati/./src/debouce.ts"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"Avati\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Avati\"] = factory();\n\telse\n\t\troot[\"Avati\"] = factory();\n})(typeof self !== 'undefined' ? self : this, () => {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Advanced debounce utility with TypeScript support\n * Provides a way to limit the rate at which a function can fire by delaying its execution\n * until after a specified amount of time has elapsed since its last invocation.\n * @module debounce\n */\n\n/**\n * Timer ID type returned by setTimeout\n * Used for managing timers internally\n */\ntype TimerId = ReturnType<typeof setTimeout>;\n\n/**\n * Generic function type that can accept any arguments and return any value\n * Used as a constraint for functions that can be debounced\n */\ntype AnyFunction = (...args: any[]) => any;\n\n/**\n * Configuration options for the debounce function\n * @interface DebounceOptions\n */\ninterface DebounceOptions {\n /** Number of milliseconds to delay execution (default: 0) */\n readonly wait?: number;\n /** Whether to execute on the leading edge of the timeout (default: false) */\n readonly leading?: boolean;\n /** Whether to execute on the trailing edge of the timeout (default: true) */\n readonly trailing?: boolean;\n /** Maximum time the function can be delayed before forced execution */\n readonly maxWait?: number;\n /** Enable debug logging for troubleshooting */\n readonly debug?: boolean;\n /** AbortController signal for cancellation */\n readonly signal?: AbortSignal;\n\n onError?: (error: Error) => void;\n}\n\n/**\n * Interface for the debounced function, including utility methods\n * @interface DebouncedFunction\n * @template T - The type of the original function\n */\ninterface DebouncedFunction<T extends AnyFunction> {\n /** Cancels any pending function invocations */\n readonly cancel: () => void;\n /** Immediately executes any pending function call */\n readonly flush: (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>;\n /** Checks if there are any pending invocations */\n readonly pending: () => boolean;\n /** Cleans up resources used by the debounced function */\n readonly cleanup: () => void;\n\n /** The debounced function that wraps the original */\n (...args: Parameters<T>): Promise<Awaited<ReturnType<T>>>;\n}\n\n/**\n * Internal state management for the debounced function\n * @interface PrivateState\n * @template T - The type of the original function\n * @private\n */\ninterface PrivateState<T extends AnyFunction> {\n /** Current timer ID for the debounce delay */\n timerId?: TimerId;\n /** Timer ID for the maximum wait limit */\n maxTimerId?: TimerId;\n /** Timestamp of the last function call */\n lastCallTime?: number;\n /** Timestamp of the last successful function invocation */\n lastInvokeTime: number;\n /** Arguments from the most recent function call */\n lastArgs?: Parameters<T>;\n /** Execution context (this) from the most recent call */\n lastThis?: any;\n /** Result from the last function execution */\n result?: Awaited<ReturnType<T>>;\n /** Array of pending promises waiting for resolution */\n pendingPromises: Array<{\n resolve: (value: Awaited<ReturnType<T>>) => void;\n reject: (reason?: any) => void;\n }>;\n /** Flag indicating if the function has been aborted */\n aborted: boolean;\n}\n\n/** WeakMap to store private state for each debounced function */\nconst privateState = new WeakMap<DebouncedFunction<any>, PrivateState<any>>();\n\n/**\n * Creates a logger instance based on debug flag\n * @param debug - Whether debug logging is enabled\n * @returns Object with logging methods\n * @private\n */\nconst createLogger = (debug: boolean) => ({\n log: (...args: any[]) => debug && console.log('[Debounce]', ...args),\n warn: (...args: any[]) => debug && console.warn('[Debounce]', ...args),\n error: (...args: any[]) => debug && console.error('[Debounce]', ...args),\n});\n\n/**\n * Creates a debounced version of the provided function that delays invoking func until after\n * wait milliseconds have elapsed since the last time the debounced function was invoked.\n *\n * @template T - The type of the function to debounce\n * @param {T} func - The function to debounce\n * @param {DebounceOptions} [options={}] - Configuration options\n * @returns {DebouncedFunction<T>} The debounced function\n * @throws {TypeError} If func is not a function\n * @throws {RangeError} If wait or maxWait values are invalid\n * @throws {Error} If neither leading nor trailing is true\n *\n * @example\n * const debouncedFn = debounce(async (x: number) => x * 2, { wait: 1000 });\n * await debouncedFn(5); // Will execute after 1000ms of inactivity\n * const debouncedFn = debounce(\n * async (x: number) => x * 2,\n * {\n * wait: 1000,\n * onError: (error) => console.error('Error in debounced function:', error)\n * }\n * );\n */\nfunction debounce<T extends AnyFunction>(\n func: T,\n options: DebounceOptions = {},\n): DebouncedFunction<T> {\n // Input validation\n if (typeof func !== 'function') {\n throw new TypeError('Expected a function');\n }\n\n const {\n wait = 0,\n leading = false,\n trailing = true,\n maxWait,\n debug = false,\n signal,\n onError,\n } = options;\n\n // Validate options\n if (wait < 0 || (maxWait !== undefined && maxWait < wait)) {\n throw new RangeError('Invalid wait/maxWait values');\n }\n\n if (!leading && !trailing) {\n throw new Error('At least one of leading or trailing must be true');\n }\n\n const logger = createLogger(debug);\n const state: PrivateState<T> = {\n lastInvokeTime: 0,\n pendingPromises: [],\n aborted: false,\n };\n\n // Setup abort controller handling\n if (signal) {\n signal.addEventListener('abort', () => {\n state.aborted = true;\n cancel();\n });\n }\n\n /**\n * Cancels all active timers\n * @private\n */\n function cancelTimers(): void {\n if (state.timerId !== undefined) {\n clearTimeout(state.timerId);\n state.timerId = undefined;\n logger.log('Cleared debounce timer');\n }\n if (state.maxTimerId !== undefined) {\n clearTimeout(state.maxTimerId);\n state.maxTimerId = undefined;\n logger.log('Cleared max wait timer');\n }\n }\n\n /**\n * Cancels any pending function invocations\n * Rejects all pending promises and resets internal state\n */\n function cancel(): void {\n logger.log('Cancelling pending invocations');\n cancelTimers();\n state.lastInvokeTime = 0;\n state.lastArgs = undefined;\n state.lastThis = undefined;\n state.lastCallTime = undefined;\n const error = new Error('Debounced function cancelled');\n handleError(error);\n state.pendingPromises.forEach(({ reject }) =>\n reject(new Error('Debounced function cancelled')),\n );\n state.pendingPromises = [];\n }\n\n /**\n * Handles errors during function execution\n * @param {Error} error - The error that occurred\n * @private\n */\n function handleError(error: Error): void {\n logger.error('Error occurred:', error);\n if (onError) {\n try {\n onError(error);\n } catch (callbackError) {\n logger.error('Error in onError callback:', callbackError);\n }\n }\n }\n\n /**\n * Checks if there are any pending function invocations\n * @returns {boolean} True if there are pending invocations\n */\n function pending(): boolean {\n return state.timerId !== undefined;\n }\n\n /**\n * Determines if the function should be invoked based on timing conditions\n * @param {number} time - Current timestamp\n * @returns {boolean} True if function should be invoked\n * @private\n */\n function shouldInvoke(time: number): boolean {\n if (state.aborted) return false;\n\n const timeSinceLastCall = state.lastCallTime === undefined ? 0 : time - state.lastCallTime;\n const timeSinceLastInvoke = time - state.lastInvokeTime;\n\n return (\n state.lastCallTime === undefined ||\n timeSinceLastCall >= wait ||\n timeSinceLastCall < 0 ||\n (maxWait !== undefined && timeSinceLastInvoke >= maxWait)\n );\n }\n\n /**\n * Executes the underlying function and manages promise resolution\n * @param {number} time - Current timestamp\n * @returns {Promise} Promise resolving to function result\n * @private\n */\n async function invokeFunc(time: number): Promise<Awaited<ReturnType<T>> | void> {\n logger.log(`Invoking function at ${time}`);\n state.lastInvokeTime = time;\n const args = state.lastArgs!;\n const thisArg = state.lastThis;\n\n state.lastArgs = undefined;\n state.lastThis = undefined;\n\n try {\n const result = await func.apply(thisArg, args);\n state.result = result;\n state.pendingPromises.forEach(({ resolve }) => resolve(result));\n state.pendingPromises = [];\n logger.log('Function invoked successfully', result);\n return result;\n } catch (error) {\n const wrappedError = error instanceof Error ? error : new Error(String(error));\n logger.error('Error in function invocation:', wrappedError);\n handleError(wrappedError);\n\n // Clear pending promises after handling error\n const currentPromises = [...state.pendingPromises];\n state.pendingPromises = [];\n\n // Reject all pending promises\n currentPromises.forEach(({ reject }) => reject(wrappedError));\n }\n }\n\n /**\n * Starts both the debounce timer and maxWait timer if configured\n * @param {number} time - Current timestamp\n * @private\n */\n function startTimer(time: number): void {\n const remainingTime = remainingWait(time);\n state.timerId = setTimeout(timerExpired, remainingTime);\n logger.log(`Started debounce timer for ${remainingTime}ms`);\n\n if (maxWait !== undefined && !state.maxTimerId) {\n const timeToMaxWait = maxWait - (time - state.lastCallTime!);\n state.maxTimerId = setTimeout(\n () => {\n logger.log('Max wait timer expired');\n cancelTimers();\n invokeFunc(Date.now());\n },\n Math.max(0, timeToMaxWait),\n );\n logger.log(`Started max wait timer for ${timeToMaxWait}ms`);\n }\n }\n\n /**\n * Calculates remaining wait time before next execution\n * @param {number} time - Current timestamp\n * @returns {number} Milliseconds until next allowed execution\n * @private\n */\n function remainingWait(time: number): number {\n const timeSinceLastCall = state.lastCallTime ? time - state.lastCallTime : 0;\n return Math.max(0, wait - timeSinceLastCall);\n }\n\n /**\n * Handles timer expiration\n * @private\n */\n function timerExpired(): void {\n const time = Date.now();\n logger.log('Debounce timer expired');\n\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n\n startTimer(time);\n }\n\n /**\n * Handles leading edge execution\n * @param {number} time - Current timestamp\n * @private\n */\n function leadingEdge(time: number): void {\n logger.log('Leading edge triggered');\n state.lastInvokeTime = time;\n startTimer(time);\n\n if (leading) {\n invokeFunc(time);\n }\n }\n\n /**\n * Handles trailing edge execution\n * @param {number} time - Current timestamp\n * @private\n */\n function trailingEdge(time: number): void {\n logger.log('Trailing edge triggered');\n cancelTimers();\n\n if (trailing && state.lastArgs) {\n invokeFunc(time);\n } else {\n state.pendingPromises.forEach(({ resolve }) => {\n resolve(state.result as Awaited<ReturnType<T>>);\n });\n state.pendingPromises = [];\n }\n }\n\n /**\n * Immediately executes the debounced function\n * @param {...Parameters<T>} args - Function arguments\n * @returns {Promise<ReturnType<T>>} Promise resolving to function result\n */\n async function flush(...args: Parameters<T>): Promise<Awaited<ReturnType<T>> | void> {\n logger.log('Flush requested');\n const argsToUse = args.length > 0 ? args : state.lastArgs;\n const thisArg = state.lastThis;\n\n cancelTimers();\n\n if (argsToUse) {\n state.lastArgs = argsToUse;\n state.lastThis = thisArg;\n return invokeFunc(Date.now());\n }\n\n return Promise.resolve(state.result!);\n }\n\n /**\n * Cleans up resources used by the debounced function\n */\n function cleanup(): void {\n logger.log('Cleanup initiated');\n cancel();\n privateState.delete(debounced);\n }\n\n /**\n * The debounced function that wraps the original\n * @param {...Parameters<T>} args - Function arguments\n * @returns {Promise<ReturnType<T>>} Promise resolving to function result\n */\n const debounced = function(\n this: any,\n ...args: Parameters<T>\n ): Promise<Awaited<ReturnType<T>>> {\n if (state.aborted) {\n return Promise.reject(new Error('Debounced function aborted'));\n }\n\n const time = Date.now();\n const isInvoking = shouldInvoke(time);\n\n state.lastArgs = args;\n state.lastThis = this;\n state.lastCallTime = time;\n\n logger.log('Function called', {\n time,\n isInvoking,\n args,\n pending: pending(),\n });\n\n return new Promise((resolve, reject) => {\n state.pendingPromises.push({ resolve, reject });\n\n if (state.timerId === undefined) {\n leadingEdge(time);\n } else {\n cancelTimers();\n startTimer(time);\n }\n });\n } as DebouncedFunction<T>;\n\n // Store private state\n privateState.set(debounced, state);\n\n // Add utility methods\n Object.defineProperties(debounced, {\n cancel: { value: cancel, writable: false, configurable: false },\n flush: { value: flush, writable: false, configurable: false },\n pending: { value: pending, writable: false, configurable: false },\n cleanup: { value: cleanup, writable: false, configurable: false },\n });\n\n return debounced;\n}\n\nexport { debounce, type DebouncedFunction, type DebounceOptions };\n"],"names":["root","factory","exports","module","define","amd","self","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","privateState","WeakMap","createLogger","debug","log","args","console","warn","error","debounce","func","options","TypeError","wait","leading","trailing","maxWait","signal","onError","undefined","RangeError","Error","logger","state","lastInvokeTime","pendingPromises","aborted","cancelTimers","timerId","clearTimeout","maxTimerId","cancel","lastArgs","lastThis","lastCallTime","handleError","forEach","reject","callbackError","pending","shouldInvoke","time","timeSinceLastCall","async","invokeFunc","thisArg","result","apply","resolve","wrappedError","String","currentPromises","startTimer","remainingTime","Math","max","remainingWait","setTimeout","timerExpired","timeToMaxWait","Date","now","trailingEdge","addEventListener","debounced","Promise","isInvoking","push","leadingEdge","set","defineProperties","writable","configurable","flush","argsToUse","length","cleanup","delete"],"sourceRoot":""}
1
+ {"version":3,"file":"index.js","mappings":";;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC;AACrC,CAAC;AACD;;UCVA;UACA;;;;;WCDA;WACA;WACA;WACA;WACA,yCAAyC,wCAAwC;WACjF;WACA;WACA;;;;;WCPA;;;;;WCAA;WACA;WACA;WACA,uDAAuD,iBAAiB;WACxE;WACA,gDAAgD,aAAa;WAC7D;;;;;;;;;;;;;;ACNA;;;;;GAKG;AAoFH,iEAAiE;AACjE,MAAM,YAAY,GAAG,IAAI,OAAO,EAA6C,CAAC;AAE9E;;;;;GAKG;AACH,MAAM,YAAY,GAAG,CAAC,KAAc,EAAE,EAAE,CAAC,CAAC;IACtC,GAAG,EAAE,CAAC,GAAG,IAAW,EAAE,EAAE,CAAC,KAAK,IAAI,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,GAAG,IAAI,CAAC;IACpE,IAAI,EAAE,CAAC,GAAG,IAAW,EAAE,EAAE,CAAC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,YAAY,EAAE,GAAG,IAAI,CAAC;IACtE,KAAK,EAAE,CAAC,GAAG,IAAW,EAAE,EAAE,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,IAAI,CAAC;CAC3E,C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ce/webpack/bootstrap","webpack://Avati.Debounce/webpack/runtime/define property getters","webpack://Avati.Debounce/webpack/runtime/hasOwnProperty shorthand","webpack://Avati.Debounce/webpack/runtime/make namespace object","webpack://Avati.Debounce/./src/debouce.ts","webpack://Avati.Debounce/./src/index.ts"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"Avati\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Avati\"] = factory();\n\telse\n\t\troot[\"Avati\"] = root[\"Avati\"] || {}, root[\"Avati\"][\"Debounce\"] = factory();\n})(typeof self !== 'undefined' ? self : this, () => {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Advanced debounce utility with TypeScript support\n * Provides a way to limit the rate at which a function can fire by delaying its execution\n * until after a specified amount of time has elapsed since its last invocation.\n * @module debounce\n */\n\n/**\n * Timer ID type returned by setTimeout\n * Used for managing timers internally\n */\ntype TimerId = ReturnType<typeof setTimeout>;\n\n/**\n * Generic function type that can accept any arguments and return any value\n * Used as a constraint for functions that can be debounced\n */\ntype AnyFunction = (...args: any[]) => any;\n\n/**\n * Configuration options for the debounce function\n * @interface DebounceOptions\n */\ninterface DebounceOptions {\n /** Number of milliseconds to delay execution (default: 0) */\n readonly wait?: number;\n /** Whether to execute on the leading edge of the timeout (default: false) */\n readonly leading?: boolean;\n /** Whether to execute on the trailing edge of the timeout (default: true) */\n readonly trailing?: boolean;\n /** Maximum time the function can be delayed before forced execution */\n readonly maxWait?: number;\n /** Enable debug logging for troubleshooting */\n readonly debug?: boolean;\n /** AbortController signal for cancellation */\n readonly signal?: AbortSignal;\n\n onError?: (error: Error) => void;\n}\n\n/**\n * Interface for the debounced function, including utility methods\n * @interface DebouncedFunction\n * @template T - The type of the original function\n */\ninterface DebouncedFunction<T extends AnyFunction> {\n /** Cancels any pending function invocations */\n readonly cancel: () => void;\n /** Immediately executes any pending function call */\n readonly flush: (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>;\n /** Checks if there are any pending invocations */\n readonly pending: () => boolean;\n /** Cleans up resources used by the debounced function */\n readonly cleanup: () => void;\n\n /** The debounced function that wraps the original */\n (...args: Parameters<T>): Promise<Awaited<ReturnType<T>>>;\n}\n\n/**\n * Internal state management for the debounced function\n * @interface PrivateState\n * @template T - The type of the original function\n * @private\n */\ninterface PrivateState<T extends AnyFunction> {\n /** Current timer ID for the debounce delay */\n timerId?: TimerId;\n /** Timer ID for the maximum wait limit */\n maxTimerId?: TimerId;\n /** Timestamp of the last function call */\n lastCallTime?: number;\n /** Timestamp of the last successful function invocation */\n lastInvokeTime: number;\n /** Arguments from the most recent function call */\n lastArgs?: Parameters<T>;\n /** Execution context (this) from the most recent call */\n lastThis?: any;\n /** Result from the last function execution */\n result?: Awaited<ReturnType<T>>;\n /** Array of pending promises waiting for resolution */\n pendingPromises: Array<{\n resolve: (value: Awaited<ReturnType<T>>) => void;\n reject: (reason?: any) => void;\n }>;\n /** Flag indicating if the function has been aborted */\n aborted: boolean;\n}\n\n/** WeakMap to store private state for each debounced function */\nconst privateState = new WeakMap<DebouncedFunction<any>, PrivateState<any>>();\n\n/**\n * Creates a logger instance based on debug flag\n * @param debug - Whether debug logging is enabled\n * @returns Object with logging methods\n * @private\n */\nconst createLogger = (debug: boolean) => ({\n log: (...args: any[]) => debug && console.log('[Debounce]', ...args),\n warn: (...args: any[]) => debug && console.warn('[Debounce]', ...args),\n error: (...args: any[]) => debug && console.error('[Debounce]', ...args),\n});\n\n/**\n * Creates a debounced version of the provided function that delays invoking func until after\n * wait milliseconds have elapsed since the last time the debounced function was invoked.\n *\n * @template T - The type of the function to debounce\n * @param {T} func - The function to debounce\n * @param {DebounceOptions} [options={}] - Configuration options\n * @returns {DebouncedFunction<T>} The debounced function\n * @throws {TypeError} If func is not a function\n * @throws {RangeError} If wait or maxWait values are invalid\n * @throws {Error} If neither leading nor trailing is true\n *\n * @example\n * const debouncedFn = debounce(async (x: number) => x * 2, { wait: 1000 });\n * await debouncedFn(5); // Will execute after 1000ms of inactivity\n * const debouncedFn = debounce(\n * async (x: number) => x * 2,\n * {\n * wait: 1000,\n * onError: (error) => console.error('Error in debounced function:', error)\n * }\n * );\n */\nfunction debounce<T extends AnyFunction>(\n func: T,\n options: DebounceOptions = {},\n): DebouncedFunction<T> {\n // Input validation\n if (typeof func !== 'function') {\n throw new TypeError('Expected a function');\n }\n\n const {\n wait = 0,\n leading = false,\n trailing = true,\n maxWait,\n debug = false,\n signal,\n onError,\n } = options;\n\n // Validate options\n if (wait < 0 || (maxWait !== undefined && maxWait < wait)) {\n throw new RangeError('Invalid wait/maxWait values');\n }\n\n if (!leading && !trailing) {\n throw new Error('At least one of leading or trailing must be true');\n }\n\n const logger = createLogger(debug);\n const state: PrivateState<T> = {\n lastInvokeTime: 0,\n pendingPromises: [],\n aborted: false,\n };\n\n // Setup abort controller handling\n if (signal) {\n signal.addEventListener('abort', () => {\n state.aborted = true;\n cancel();\n });\n }\n\n /**\n * Cancels all active timers\n * @private\n */\n function cancelTimers(): void {\n if (state.timerId !== undefined) {\n clearTimeout(state.timerId);\n state.timerId = undefined;\n logger.log('Cleared debounce timer');\n }\n if (state.maxTimerId !== undefined) {\n clearTimeout(state.maxTimerId);\n state.maxTimerId = undefined;\n logger.log('Cleared max wait timer');\n }\n }\n\n /**\n * Cancels any pending function invocations\n * Rejects all pending promises and resets internal state\n */\n function cancel(): void {\n logger.log('Cancelling pending invocations');\n cancelTimers();\n state.lastInvokeTime = 0;\n state.lastArgs = undefined;\n state.lastThis = undefined;\n state.lastCallTime = undefined;\n const error = new Error('Debounced function cancelled');\n handleError(error);\n state.pendingPromises.forEach(({ reject }) =>\n reject(new Error('Debounced function cancelled')),\n );\n state.pendingPromises = [];\n }\n\n /**\n * Handles errors during function execution\n * @param {Error} error - The error that occurred\n * @private\n */\n function handleError(error: Error): void {\n logger.error('Error occurred:', error);\n if (onError) {\n try {\n onError(error);\n } catch (callbackError) {\n logger.error('Error in onError callback:', callbackError);\n }\n }\n }\n\n /**\n * Checks if there are any pending function invocations\n * @returns {boolean} True if there are pending invocations\n */\n function pending(): boolean {\n return state.timerId !== undefined;\n }\n\n /**\n * Determines if the function should be invoked based on timing conditions\n * @param {number} time - Current timestamp\n * @returns {boolean} True if function should be invoked\n * @private\n */\n function shouldInvoke(time: number): boolean {\n if (state.aborted) return false;\n\n const timeSinceLastCall = state.lastCallTime === undefined ? 0 : time - state.lastCallTime;\n const timeSinceLastInvoke = time - state.lastInvokeTime;\n\n return (\n state.lastCallTime === undefined ||\n timeSinceLastCall >= wait ||\n timeSinceLastCall < 0 ||\n (maxWait !== undefined && timeSinceLastInvoke >= maxWait)\n );\n }\n\n /**\n * Executes the underlying function and manages promise resolution\n * @param {number} time - Current timestamp\n * @returns {Promise} Promise resolving to function result\n * @private\n */\n async function invokeFunc(time: number): Promise<Awaited<ReturnType<T>> | void> {\n logger.log(`Invoking function at ${time}`);\n state.lastInvokeTime = time;\n const args = state.lastArgs!;\n const thisArg = state.lastThis;\n\n state.lastArgs = undefined;\n state.lastThis = undefined;\n\n try {\n const result = await func.apply(thisArg, args);\n state.result = result;\n state.pendingPromises.forEach(({ resolve }) => resolve(result));\n state.pendingPromises = [];\n logger.log('Function invoked successfully', result);\n return result;\n } catch (error) {\n const wrappedError = error instanceof Error ? error : new Error(String(error));\n logger.error('Error in function invocation:', wrappedError);\n handleError(wrappedError);\n\n // Clear pending promises after handling error\n const currentPromises = [...state.pendingPromises];\n state.pendingPromises = [];\n\n // Reject all pending promises\n currentPromises.forEach(({ reject }) => reject(wrappedError));\n }\n }\n\n /**\n * Starts both the debounce timer and maxWait timer if configured\n * @param {number} time - Current timestamp\n * @private\n */\n function startTimer(time: number): void {\n const remainingTime = remainingWait(time);\n state.timerId = setTimeout(timerExpired, remainingTime);\n logger.log(`Started debounce timer for ${remainingTime}ms`);\n\n if (maxWait !== undefined && !state.maxTimerId) {\n const timeToMaxWait = maxWait - (time - state.lastCallTime!);\n state.maxTimerId = setTimeout(\n () => {\n logger.log('Max wait timer expired');\n cancelTimers();\n invokeFunc(Date.now());\n },\n Math.max(0, timeToMaxWait),\n );\n logger.log(`Started max wait timer for ${timeToMaxWait}ms`);\n }\n }\n\n /**\n * Calculates remaining wait time before next execution\n * @param {number} time - Current timestamp\n * @returns {number} Milliseconds until next allowed execution\n * @private\n */\n function remainingWait(time: number): number {\n const timeSinceLastCall = state.lastCallTime ? time - state.lastCallTime : 0;\n return Math.max(0, wait - timeSinceLastCall);\n }\n\n /**\n * Handles timer expiration\n * @private\n */\n function timerExpired(): void {\n const time = Date.now();\n logger.log('Debounce timer expired');\n\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n\n startTimer(time);\n }\n\n /**\n * Handles leading edge execution\n * @param {number} time - Current timestamp\n * @private\n */\n function leadingEdge(time: number): void {\n logger.log('Leading edge triggered');\n state.lastInvokeTime = time;\n startTimer(time);\n\n if (leading) {\n invokeFunc(time);\n }\n }\n\n /**\n * Handles trailing edge execution\n * @param {number} time - Current timestamp\n * @private\n */\n function trailingEdge(time: number): void {\n logger.log('Trailing edge triggered');\n cancelTimers();\n\n if (trailing && state.lastArgs) {\n invokeFunc(time);\n } else {\n state.pendingPromises.forEach(({ resolve }) => {\n resolve(state.result as Awaited<ReturnType<T>>);\n });\n state.pendingPromises = [];\n }\n }\n\n /**\n * Immediately executes the debounced function\n * @param {...Parameters<T>} args - Function arguments\n * @returns {Promise<ReturnType<T>>} Promise resolving to function result\n */\n async function flush(...args: Parameters<T>): Promise<Awaited<ReturnType<T>> | void> {\n logger.log('Flush requested');\n const argsToUse = args.length > 0 ? args : state.lastArgs;\n const thisArg = state.lastThis;\n\n cancelTimers();\n\n if (argsToUse) {\n state.lastArgs = argsToUse;\n state.lastThis = thisArg;\n return invokeFunc(Date.now());\n }\n\n return Promise.resolve(state.result!);\n }\n\n /**\n * Cleans up resources used by the debounced function\n */\n function cleanup(): void {\n logger.log('Cleanup initiated');\n cancel();\n privateState.delete(debounced);\n }\n\n /**\n * The debounced function that wraps the original\n * @param {...Parameters<T>} args - Function arguments\n * @returns {Promise<ReturnType<T>>} Promise resolving to function result\n */\n const debounced = function(\n this: any,\n ...args: Parameters<T>\n ): Promise<Awaited<ReturnType<T>>> {\n if (state.aborted) {\n return Promise.reject(new Error('Debounced function aborted'));\n }\n\n const time = Date.now();\n const isInvoking = shouldInvoke(time);\n\n state.lastArgs = args;\n state.lastThis = this;\n state.lastCallTime = time;\n\n logger.log('Function called', {\n time,\n isInvoking,\n args,\n pending: pending(),\n });\n\n return new Promise((resolve, reject) => {\n state.pendingPromises.push({ resolve, reject });\n\n if (state.timerId === undefined) {\n leadingEdge(time);\n } else {\n cancelTimers();\n startTimer(time);\n }\n });\n } as DebouncedFunction<T>;\n\n // Store private state\n privateState.set(debounced, state);\n\n // Add utility methods\n Object.defineProperties(debounced, {\n cancel: { value: cancel, writable: false, configurable: false },\n flush: { value: flush, writable: false, configurable: false },\n pending: { value: pending, writable: false, configurable: false },\n cleanup: { value: cleanup, writable: false, configurable: false },\n });\n\n return debounced;\n}\n\nexport { debounce, type DebouncedFunction, type DebounceOptions };\n","export * from './debouce';\n"],"names":[],"sourceRoot":""}
@@ -0,0 +1,8 @@
1
+ /*!
2
+ * @avatijs/debounce 0.1.3
3
+ * Copyright (c) 2024 Khaled Sameer <khaled.smq@hotmail.com>
4
+ * Licensed under MIT, https://opensource.org/licenses/MIT/
5
+ * Please visit https://avati.io/ for details.
6
+ */
7
+ !function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define("Avati",[],n):"object"==typeof exports?exports.Avati=n():(e.Avati=e.Avati||{},e.Avati.Debounce=n())}("undefined"!=typeof self?self:this,(()=>(()=>{"use strict";var e={d:(n,o)=>{for(var t in o)e.o(o,t)&&!e.o(n,t)&&Object.defineProperty(n,t,{enumerable:!0,get:o[t]})},o:(e,n)=>Object.prototype.hasOwnProperty.call(e,n),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"t",{value:!0})}},n={};e.r(n),e.d(n,{debounce:()=>i});const o=new WeakMap,t=e=>({log:(...n)=>e&&void 0,warn:(...n)=>e&&void 0,error:(...n)=>e&&void 0});function i(e,n={}){if("function"!=typeof e)throw new TypeError("Expected a function");const{wait:i=0,leading:r=!1,trailing:c=!0,maxWait:a,debug:u=!1,signal:d,onError:l}=n;if(0>i||void 0!==a&&i>a)throw new RangeError("Invalid wait/maxWait values");if(!r&&!c)throw Error("At least one of leading or trailing must be true");const f=t(u),s={lastInvokeTime:0,pendingPromises:[],aborted:!1};function v(){void 0!==s.timerId&&(clearTimeout(s.timerId),s.timerId=void 0,f.log("Cleared debounce timer")),void 0!==s.maxTimerId&&(clearTimeout(s.maxTimerId),s.maxTimerId=void 0,f.log("Cleared max wait timer"))}function b(){f.log("Cancelling pending invocations"),v(),s.lastInvokeTime=0,s.lastArgs=void 0,s.lastThis=void 0,s.lastCallTime=void 0,g(Error("Debounced function cancelled")),s.pendingPromises.forEach((({reject:e})=>e(Error("Debounced function cancelled")))),s.pendingPromises=[]}function g(e){if(f.error("Error occurred:",e),l)try{l(e)}catch(e){f.error("Error in onError callback:",e)}}function m(){return void 0!==s.timerId}function p(e){if(s.aborted)return!1;const n=void 0===s.lastCallTime?0:e-s.lastCallTime;return void 0===s.lastCallTime||n>=i||0>n||void 0!==a&&e-s.lastInvokeTime>=a}async function w(n){f.log("Invoking function at "+n),s.lastInvokeTime=n;const o=s.lastArgs,t=s.lastThis;s.lastArgs=void 0,s.lastThis=void 0;try{const n=await e.apply(t,o);return s.result=n,s.pendingPromises.forEach((({resolve:e})=>e(n))),s.pendingPromises=[],f.log("Function invoked successfully",n),n}catch(e){const n=e instanceof Error?e:Error(e+"");f.error("Error in function invocation:",n),g(n);const o=[...s.pendingPromises];s.pendingPromises=[],o.forEach((({reject:e})=>e(n)))}}function y(e){const n=function(e){return Math.max(0,i-(s.lastCallTime?e-s.lastCallTime:0))}(e);if(s.timerId=setTimeout(E,n),f.log(`Started debounce timer for ${n}ms`),void 0!==a&&!s.maxTimerId){const n=a-(e-s.lastCallTime);s.maxTimerId=setTimeout((()=>{f.log("Max wait timer expired"),v(),w(Date.now())}),Math.max(0,n)),f.log(`Started max wait timer for ${n}ms`)}}function E(){const e=Date.now();if(f.log("Debounce timer expired"),p(e))return function(e){f.log("Trailing edge triggered"),v(),c&&s.lastArgs?w(e):(s.pendingPromises.forEach((({resolve:e})=>{e(s.result)})),s.pendingPromises=[])}(e);y(e)}d&&d.addEventListener("abort",(()=>{s.aborted=!0,b()}));const h=function(...e){if(s.aborted)return Promise.reject(Error("Debounced function aborted"));const n=Date.now(),o=p(n);return s.lastArgs=e,s.lastThis=this,s.lastCallTime=n,f.log("Function called",{time:n,isInvoking:o,args:e,pending:m()}),new Promise(((e,o)=>{s.pendingPromises.push({resolve:e,reject:o}),void 0===s.timerId?function(e){f.log("Leading edge triggered"),s.lastInvokeTime=e,y(e),r&&w(e)}(n):(v(),y(n))}))};return o.set(h,s),Object.defineProperties(h,{cancel:{value:b,writable:!1,configurable:!1},flush:{value:async function(...e){f.log("Flush requested");const n=e.length>0?e:s.lastArgs,o=s.lastThis;return v(),n?(s.lastArgs=n,s.lastThis=o,w(Date.now())):Promise.resolve(s.result)},writable:!1,configurable:!1},pending:{value:m,writable:!1,configurable:!1},cleanup:{value:function(){f.log("Cleanup initiated"),b(),o.delete(h)},writable:!1,configurable:!1}}),h}return n})()));
8
+ //# sourceMappingURL=index.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.min.js","mappings":";;;;;;CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,QAAS,GAAIH,GACM,iBAAZC,QACdA,QAAe,MAAID,KAEnBD,EAAY,MAAIA,EAAY,OAAK,CAAC,EAAGA,EAAY,MAAY,SAAIC,IAClE,CATD,CASmB,oBAATK,KAAuBA,KAAOC,MAAM,IAC9C,M,aCTA,IAAIC,EAAsB,CCA1BA,EAAwB,CAACN,EAASO,KACjC,IAAI,IAAIC,KAAOD,EACXD,EAAoBG,EAAEF,EAAYC,KAASF,EAAoBG,EAAET,EAASQ,IAC5EE,OAAOC,eAAeX,EAASQ,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,IAE1E,ECNDF,EAAwB,CAACQ,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFT,EAAyBN,IACH,oBAAXmB,QAA0BA,OAAOC,aAC1CV,OAAOC,eAAeX,EAASmB,OAAOC,YAAa,CAAEC,MAAO,WAE7DX,OAAOC,eAAeX,EAAS,IAAc,CAAEqB,OAAO,GAAO,G,oCCqF9D,MAAMC,EAAe,IAAIC,QAQnBC,EAAgBC,IAAmB,CACrCC,IAAK,IAAIC,IAAgBF,QAASG,EAClCC,KAAM,IAAIF,IAAgBF,QAASG,EACnCE,MAAO,IAAIH,IAAgBF,QAASG,IA0BxC,SAASG,EACLC,EACAC,EAA2B,CAAC,GAG5B,GAAoB,mBAATD,EACP,MAAM,IAAIE,UAAU,uBAGxB,MAAM,KACFC,EAAO,EAAC,QACRC,G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AOC,cAAc,GAC1DI,QAAS,CAAE7E,MArDf,WACIuB,EAAOlB,IAAI,qBACX2B,IACA/B,EAAa6E,OAAOb,EACxB,EAiD+BO,UAAU,EAAOC,cAAc,KAGvDR,CACX,C,ULzbA","sources":["webpack://Avati.Debounce/webpack/universalModuleDefinition","webpack://Avati.Debounce/webpack/bootstrap","webpack://Avati.Debounce/webpack/runtime/define property getters","webpack://Avati.Debounce/webpack/runtime/hasOwnProperty shorthand","webpack://Avati.Debounce/webpack/runtime/make namespace object","webpack://Avati.Debounce/./src/debouce.ts"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"Avati\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Avati\"] = factory();\n\telse\n\t\troot[\"Avati\"] = root[\"Avati\"] || {}, root[\"Avati\"][\"Debounce\"] = factory();\n})(typeof self !== 'undefined' ? self : this, () => {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Advanced debounce utility with TypeScript support\n * Provides a way to limit the rate at which a function can fire by delaying its execution\n * until after a specified amount of time has elapsed since its last invocation.\n * @module debounce\n */\n\n/**\n * Timer ID type returned by setTimeout\n * Used for managing timers internally\n */\ntype TimerId = ReturnType<typeof setTimeout>;\n\n/**\n * Generic function type that can accept any arguments and return any value\n * Used as a constraint for functions that can be debounced\n */\ntype AnyFunction = (...args: any[]) => any;\n\n/**\n * Configuration options for the debounce function\n * @interface DebounceOptions\n */\ninterface DebounceOptions {\n /** Number of milliseconds to delay execution (default: 0) */\n readonly wait?: number;\n /** Whether to execute on the leading edge of the timeout (default: false) */\n readonly leading?: boolean;\n /** Whether to execute on the trailing edge of the timeout (default: true) */\n readonly trailing?: boolean;\n /** Maximum time the function can be delayed before forced execution */\n readonly maxWait?: number;\n /** Enable debug logging for troubleshooting */\n readonly debug?: boolean;\n /** AbortController signal for cancellation */\n readonly signal?: AbortSignal;\n\n onError?: (error: Error) => void;\n}\n\n/**\n * Interface for the debounced function, including utility methods\n * @interface DebouncedFunction\n * @template T - The type of the original function\n */\ninterface DebouncedFunction<T extends AnyFunction> {\n /** Cancels any pending function invocations */\n readonly cancel: () => void;\n /** Immediately executes any pending function call */\n readonly flush: (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>;\n /** Checks if there are any pending invocations */\n readonly pending: () => boolean;\n /** Cleans up resources used by the debounced function */\n readonly cleanup: () => void;\n\n /** The debounced function that wraps the original */\n (...args: Parameters<T>): Promise<Awaited<ReturnType<T>>>;\n}\n\n/**\n * Internal state management for the debounced function\n * @interface PrivateState\n * @template T - The type of the original function\n * @private\n */\ninterface PrivateState<T extends AnyFunction> {\n /** Current timer ID for the debounce delay */\n timerId?: TimerId;\n /** Timer ID for the maximum wait limit */\n maxTimerId?: TimerId;\n /** Timestamp of the last function call */\n lastCallTime?: number;\n /** Timestamp of the last successful function invocation */\n lastInvokeTime: number;\n /** Arguments from the most recent function call */\n lastArgs?: Parameters<T>;\n /** Execution context (this) from the most recent call */\n lastThis?: any;\n /** Result from the last function execution */\n result?: Awaited<ReturnType<T>>;\n /** Array of pending promises waiting for resolution */\n pendingPromises: Array<{\n resolve: (value: Awaited<ReturnType<T>>) => void;\n reject: (reason?: any) => void;\n }>;\n /** Flag indicating if the function has been aborted */\n aborted: boolean;\n}\n\n/** WeakMap to store private state for each debounced function */\nconst privateState = new WeakMap<DebouncedFunction<any>, PrivateState<any>>();\n\n/**\n * Creates a logger instance based on debug flag\n * @param debug - Whether debug logging is enabled\n * @returns Object with logging methods\n * @private\n */\nconst createLogger = (debug: boolean) => ({\n log: (...args: any[]) => debug && console.log('[Debounce]', ...args),\n warn: (...args: any[]) => debug && console.warn('[Debounce]', ...args),\n error: (...args: any[]) => debug && console.error('[Debounce]', ...args),\n});\n\n/**\n * Creates a debounced version of the provided function that delays invoking func until after\n * wait milliseconds have elapsed since the last time the debounced function was invoked.\n *\n * @template T - The type of the function to debounce\n * @param {T} func - The function to debounce\n * @param {DebounceOptions} [options={}] - Configuration options\n * @returns {DebouncedFunction<T>} The debounced function\n * @throws {TypeError} If func is not a function\n * @throws {RangeError} If wait or maxWait values are invalid\n * @throws {Error} If neither leading nor trailing is true\n *\n * @example\n * const debouncedFn = debounce(async (x: number) => x * 2, { wait: 1000 });\n * await debouncedFn(5); // Will execute after 1000ms of inactivity\n * const debouncedFn = debounce(\n * async (x: number) => x * 2,\n * {\n * wait: 1000,\n * onError: (error) => console.error('Error in debounced function:', error)\n * }\n * );\n */\nfunction debounce<T extends AnyFunction>(\n func: T,\n options: DebounceOptions = {},\n): DebouncedFunction<T> {\n // Input validation\n if (typeof func !== 'function') {\n throw new TypeError('Expected a function');\n }\n\n const {\n wait = 0,\n leading = false,\n trailing = true,\n maxWait,\n debug = false,\n signal,\n onError,\n } = options;\n\n // Validate options\n if (wait < 0 || (maxWait !== undefined && maxWait < wait)) {\n throw new RangeError('Invalid wait/maxWait values');\n }\n\n if (!leading && !trailing) {\n throw new Error('At least one of leading or trailing must be true');\n }\n\n const logger = createLogger(debug);\n const state: PrivateState<T> = {\n lastInvokeTime: 0,\n pendingPromises: [],\n aborted: false,\n };\n\n // Setup abort controller handling\n if (signal) {\n signal.addEventListener('abort', () => {\n state.aborted = true;\n cancel();\n });\n }\n\n /**\n * Cancels all active timers\n * @private\n */\n function cancelTimers(): void {\n if (state.timerId !== undefined) {\n clearTimeout(state.timerId);\n state.timerId = undefined;\n logger.log('Cleared debounce timer');\n }\n if (state.maxTimerId !== undefined) {\n clearTimeout(state.maxTimerId);\n state.maxTimerId = undefined;\n logger.log('Cleared max wait timer');\n }\n }\n\n /**\n * Cancels any pending function invocations\n * Rejects all pending promises and resets internal state\n */\n function cancel(): void {\n logger.log('Cancelling pending invocations');\n cancelTimers();\n state.lastInvokeTime = 0;\n state.lastArgs = undefined;\n state.lastThis = undefined;\n state.lastCallTime = undefined;\n const error = new Error('Debounced function cancelled');\n handleError(error);\n state.pendingPromises.forEach(({ reject }) =>\n reject(new Error('Debounced function cancelled')),\n );\n state.pendingPromises = [];\n }\n\n /**\n * Handles errors during function execution\n * @param {Error} error - The error that occurred\n * @private\n */\n function handleError(error: Error): void {\n logger.error('Error occurred:', error);\n if (onError) {\n try {\n onError(error);\n } catch (callbackError) {\n logger.error('Error in onError callback:', callbackError);\n }\n }\n }\n\n /**\n * Checks if there are any pending function invocations\n * @returns {boolean} True if there are pending invocations\n */\n function pending(): boolean {\n return state.timerId !== undefined;\n }\n\n /**\n * Determines if the function should be invoked based on timing conditions\n * @param {number} time - Current timestamp\n * @returns {boolean} True if function should be invoked\n * @private\n */\n function shouldInvoke(time: number): boolean {\n if (state.aborted) return false;\n\n const timeSinceLastCall = state.lastCallTime === undefined ? 0 : time - state.lastCallTime;\n const timeSinceLastInvoke = time - state.lastInvokeTime;\n\n return (\n state.lastCallTime === undefined ||\n timeSinceLastCall >= wait ||\n timeSinceLastCall < 0 ||\n (maxWait !== undefined && timeSinceLastInvoke >= maxWait)\n );\n }\n\n /**\n * Executes the underlying function and manages promise resolution\n * @param {number} time - Current timestamp\n * @returns {Promise} Promise resolving to function result\n * @private\n */\n async function invokeFunc(time: number): Promise<Awaited<ReturnType<T>> | void> {\n logger.log(`Invoking function at ${time}`);\n state.lastInvokeTime = time;\n const args = state.lastArgs!;\n const thisArg = state.lastThis;\n\n state.lastArgs = undefined;\n state.lastThis = undefined;\n\n try {\n const result = await func.apply(thisArg, args);\n state.result = result;\n state.pendingPromises.forEach(({ resolve }) => resolve(result));\n state.pendingPromises = [];\n logger.log('Function invoked successfully', result);\n return result;\n } catch (error) {\n const wrappedError = error instanceof Error ? error : new Error(String(error));\n logger.error('Error in function invocation:', wrappedError);\n handleError(wrappedError);\n\n // Clear pending promises after handling error\n const currentPromises = [...state.pendingPromises];\n state.pendingPromises = [];\n\n // Reject all pending promises\n currentPromises.forEach(({ reject }) => reject(wrappedError));\n }\n }\n\n /**\n * Starts both the debounce timer and maxWait timer if configured\n * @param {number} time - Current timestamp\n * @private\n */\n function startTimer(time: number): void {\n const remainingTime = remainingWait(time);\n state.timerId = setTimeout(timerExpired, remainingTime);\n logger.log(`Started debounce timer for ${remainingTime}ms`);\n\n if (maxWait !== undefined && !state.maxTimerId) {\n const timeToMaxWait = maxWait - (time - state.lastCallTime!);\n state.maxTimerId = setTimeout(\n () => {\n logger.log('Max wait timer expired');\n cancelTimers();\n invokeFunc(Date.now());\n },\n Math.max(0, timeToMaxWait),\n );\n logger.log(`Started max wait timer for ${timeToMaxWait}ms`);\n }\n }\n\n /**\n * Calculates remaining wait time before next execution\n * @param {number} time - Current timestamp\n * @returns {number} Milliseconds until next allowed execution\n * @private\n */\n function remainingWait(time: number): number {\n const timeSinceLastCall = state.lastCallTime ? time - state.lastCallTime : 0;\n return Math.max(0, wait - timeSinceLastCall);\n }\n\n /**\n * Handles timer expiration\n * @private\n */\n function timerExpired(): void {\n const time = Date.now();\n logger.log('Debounce timer expired');\n\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n\n startTimer(time);\n }\n\n /**\n * Handles leading edge execution\n * @param {number} time - Current timestamp\n * @private\n */\n function leadingEdge(time: number): void {\n logger.log('Leading edge triggered');\n state.lastInvokeTime = time;\n startTimer(time);\n\n if (leading) {\n invokeFunc(time);\n }\n }\n\n /**\n * Handles trailing edge execution\n * @param {number} time - Current timestamp\n * @private\n */\n function trailingEdge(time: number): void {\n logger.log('Trailing edge triggered');\n cancelTimers();\n\n if (trailing && state.lastArgs) {\n invokeFunc(time);\n } else {\n state.pendingPromises.forEach(({ resolve }) => {\n resolve(state.result as Awaited<ReturnType<T>>);\n });\n state.pendingPromises = [];\n }\n }\n\n /**\n * Immediately executes the debounced function\n * @param {...Parameters<T>} args - Function arguments\n * @returns {Promise<ReturnType<T>>} Promise resolving to function result\n */\n async function flush(...args: Parameters<T>): Promise<Awaited<ReturnType<T>> | void> {\n logger.log('Flush requested');\n const argsToUse = args.length > 0 ? args : state.lastArgs;\n const thisArg = state.lastThis;\n\n cancelTimers();\n\n if (argsToUse) {\n state.lastArgs = argsToUse;\n state.lastThis = thisArg;\n return invokeFunc(Date.now());\n }\n\n return Promise.resolve(state.result!);\n }\n\n /**\n * Cleans up resources used by the debounced function\n */\n function cleanup(): void {\n logger.log('Cleanup initiated');\n cancel();\n privateState.delete(debounced);\n }\n\n /**\n * The debounced function that wraps the original\n * @param {...Parameters<T>} args - Function arguments\n * @returns {Promise<ReturnType<T>>} Promise resolving to function result\n */\n const debounced = function(\n this: any,\n ...args: Parameters<T>\n ): Promise<Awaited<ReturnType<T>>> {\n if (state.aborted) {\n return Promise.reject(new Error('Debounced function aborted'));\n }\n\n const time = Date.now();\n const isInvoking = shouldInvoke(time);\n\n state.lastArgs = args;\n state.lastThis = this;\n state.lastCallTime = time;\n\n logger.log('Function called', {\n time,\n isInvoking,\n args,\n pending: pending(),\n });\n\n return new Promise((resolve, reject) => {\n state.pendingPromises.push({ resolve, reject });\n\n if (state.timerId === undefined) {\n leadingEdge(time);\n } else {\n cancelTimers();\n startTimer(time);\n }\n });\n } as DebouncedFunction<T>;\n\n // Store private state\n privateState.set(debounced, state);\n\n // Add utility methods\n Object.defineProperties(debounced, {\n cancel: { value: cancel, writable: false, configurable: false },\n flush: { value: flush, writable: false, configurable: false },\n pending: { value: pending, writable: false, configurable: false },\n cleanup: { value: cleanup, writable: false, configurable: false },\n });\n\n return debounced;\n}\n\nexport { debounce, type DebouncedFunction, type DebounceOptions };\n"],"names":["root","factory","exports","module","define","amd","self","this","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","privateState","WeakMap","createLogger","debug","log","args","console","warn","error","debounce","func","options","TypeError","wait","leading","trailing","maxWait","signal","onError","undefined","RangeError","Error","logger","state","lastInvokeTime","pendingPromises","aborted","cancelTimers","timerId","clearTimeout","maxTimerId","cancel","lastArgs","lastThis","lastCallTime","handleError","forEach","reject","callbackError","pending","shouldInvoke","time","timeSinceLastCall","async","invokeFunc","thisArg","result","apply","resolve","wrappedError","String","currentPromises","startTimer","remainingTime","Math","max","remainingWait","setTimeout","timerExpired","timeToMaxWait","Date","now","trailingEdge","addEventListener","debounced","Promise","isInvoking","push","leadingEdge","set","defineProperties","writable","configurable","flush","argsToUse","length","cleanup","delete"],"sourceRoot":""}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avatijs/debounce",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Debounce package part of Avati project",
5
5
  "main": "./dist/cjs/index.js",
6
6
  "module": "./dist/esm/index.js",
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "sideEffects": false,
21
21
  "engines": {
22
- "node": ">=14.0.0"
22
+ "node": ">=18.20.5"
23
23
  },
24
24
  "bundlesize": [
25
25
  {
@@ -41,19 +41,20 @@
41
41
  "scripts": {
42
42
  "build": "npm run clean && npm run build:types && npm run build:prod",
43
43
  "build:dev": "webpack --mode development --progress",
44
- "build:prod": "webpack --mode production --progress",
45
- "build:types": "tsc --emitDeclarationOnly --outDir dist/types",
44
+ "build:prod": "webpack --mode production",
45
+ "build:types": "tsc --emitDeclarationOnly",
46
46
  "watch": "webpack --mode=development --watch",
47
47
  "watch:silent": "webpack --mode=development --watch --silent",
48
48
  "clean": "rimraf dist",
49
49
  "prepublishOnly": "npm run build",
50
- "test": "jest",
50
+ "test": "jest --config jest.config.js",
51
51
  "typecheck": "tsc --noEmit",
52
52
  "size": "webpack --mode production --json > stats.json && webpack-bundle-analyzer stats.json",
53
53
  "analyze:deps": "madge --circular --extensions ts ./src/index.ts",
54
54
  "size:check": "bundlesize",
55
55
  "size:watch": "bundlesize --watch",
56
56
  "size:compression": "bundlesize --compression",
57
+ "check-deps": "depcheck --config .depcheckrc",
57
58
  "analyze": "npm run analyze:size && npm run analyze:deps && npm run analyze:duplicates",
58
59
  "analyze:size": "webpack --mode production --json > stats.json && webpack-bundle-analyzer stats.json",
59
60
  "analyze:detailed": "webpack --config webpack.analysis.config.js",
@@ -90,6 +91,11 @@
90
91
  },
91
92
  "keywords": [
92
93
  "avati",
94
+ "scheduler",
95
+ "batch",
96
+ "task-queue",
97
+ "priority-queue",
98
+ "async",
93
99
  "typescript",
94
100
  "debounce",
95
101
  "debouncer",
@@ -117,6 +123,7 @@
117
123
  "@typescript-eslint/eslint-plugin": "^8.15.0",
118
124
  "@typescript-eslint/parser": "^8.15.0",
119
125
  "bundlesize": "^0.18.2",
126
+ "depcheck": "^1.4.7",
120
127
  "dependency-cruiser": "^16.6.0",
121
128
  "eslint": "^8.57.1",
122
129
  "jest": "^29.7.0",