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AAGH,GAGrBpD,EAAYmD,WAAWV,EAAsBW,EAC/C,CAEA,OAAOH,CAET,EAkBA,OAfAN,EAAUa,OAAS,WACbxD,GAAakD,aAAalD,GAC9BO,EAAiB,EACjBP,EAAY,KACZI,EAAW,KACXC,EAAW,KAEPK,GACFA,EAAe,IAAI+C,MAAM,2CAE3BjD,EAAkB,KAClBC,EAAkB,KAClBC,EAAiB,IACnB,EAEOiC,CACT","sources":["webpack://@danielhaim/modulator/./src/index.ts"],"sourcesContent":["/**\n * Creates a debounced function with a configurable cache and maximum wait time. \n * The debounced function delays invoking `func` until after `wait` milliseconds \n * have elapsed since the last time the debounced function was invoked. \n * The function also caches its results based on the arguments passed.\n * If `immediate` is true, it triggers the function on the leading edge, instead of the trailing.\n * \n * @param {Function} func - The function to debounce.\n * @param {number} wait - The debouncing wait time in milliseconds.\n * @param {boolean} [immediate=false] - Flag to determine if the function should be executed immediately.\n * @param {Object} [context=null] - The context in which the function should be executed.\n * @param {number} [maxCacheSize=100] - The maximum cache size for storing results.\n * @param {number|null} [maxWait=null] - The maximum wait time in milliseconds that the function can be delayed.\n * \n * @returns {Function} A new debounced function that returns a Promise resolving with the result of `func`.\n *\n * @example\n * // Define a function to be debounced\n * async function fetchData(query) {\n *     console.log('Fetching data for:', query);\n *     // Simulate async operation\n *     await new Promise(resolve => setTimeout(resolve, 100));\n *     if (query === 'error') throw new Error('Failed to fetch');\n *     return `Data for ${query}`;\n * }\n * \n * // Create a debounced version of the function\n * const debouncedFetch = modulate(fetchData, 200);\n * \n * // Call the debounced function\n * debouncedFetch('query1').then(console.log).catch(console.error);\n * debouncedFetch('error').then(console.log).catch(console.error); // Will log error after delay\n */\n\n// Define interfaces and types\ninterface CacheEntry<T> {\n  value: T;\n  timestamp: number;\n}\n\ntype TimerId = ReturnType<typeof setTimeout> | null;\n\n// Define the structure of the debounced function, including the cancel method\ninterface DebouncedFunction<T extends (...args: any[]) => any> {\n  (...args: Parameters<T>): Promise<ReturnType<T>>;\n  cancel(): void;\n  // flush(): Promise<ReturnType<T> | undefined>; // Add later if implementing flush\n}\n\nexport function modulate<T extends (...args: any[]) => any>(\n  func: T,\n  wait: number,\n  immediate: boolean = false,\n  context: ThisParameterType<T> | null = null,\n  maxCacheSize: number = 100,\n  maxWait: number | null = null\n): DebouncedFunction<T> {\n\n  /**\n   * console.log('modulate called');\n   * console.log('First parameter received: ', func);\n   * console.log('Second parameter received: ', wait);\n   * console.log('Third parameter received: ', immediate);\n   * console.log('Fourth parameter received: ', context);\n   * console.log('Fifth parameter received: ', maxCacheSize);\n   * console.log('Sixth parameter received: ', maxWait);\n   */\n\n  // Parameter Validation\n  if (typeof func !== \"function\") {\n    throw new TypeError(\"Expected a function for the first parameter\");\n  }\n  if (typeof wait !== \"number\" || isNaN(wait) || wait < 0) {\n    throw new TypeError(\"Expected a non-negative number for the second parameter (wait)\");\n  }\n  if (typeof immediate !== \"boolean\") {\n    throw new TypeError(\"Expected a boolean for the third parameter\");\n  }\n  if (typeof maxCacheSize !== \"number\" || isNaN(maxCacheSize) || maxCacheSize < 0) {\n    throw new TypeError(\"Expected a non-negative number for the fifth parameter (maxCacheSize)\");\n  }\n  if (maxWait !== null && (typeof maxWait !== \"number\" || isNaN(maxWait) || maxWait < 0)) {\n    throw new TypeError(\"Expected null or a non-negative number for the sixth parameter (maxWait)\");\n  }\n  if (maxWait !== null && maxWait < wait) {\n    throw new TypeError(\n      \"maxWait must be greater than or equal to wait\"\n    );\n  }\n\n  let timeoutId: TimerId = null;\n  let cache = new Map<string, ReturnType<T>>();\n  let cacheKeys: string[] = [];\n\n  // State related to the *last* call attempt\n  let lastArgs: Parameters<T> | null = null; // Args from the last call\n  let lastThis: ThisParameterType<T> | null = null; // Context from the last call\n  let lastCallTime: number = 0; // Time of the last call\n\n  // State related to the *last actual function invocation*\n  let lastInvokeTime: number = 0;\n\n  // State for the promise of the current debounce sequence\n  let sequencePromise: Promise<ReturnType<T>> | null = null;\n  let sequenceResolve: ((value: ReturnType<T> | PromiseLike<ReturnType<T>>) => void) | null = null;\n  let sequenceReject: ((reason?: any) => void) | null = null;\n\n  // Helper Functions\n\n  // Clear cache entry and its key tracking\n  const clearCacheEntry = (key: string) => {\n      cache.delete(key);\n      const index = cacheKeys.indexOf(key);\n      if (index > -1) {\n          cacheKeys.splice(index, 1);\n      }\n  }\n\n  // Add to cache and handle eviction\n  const addToCache = (key: string, value: ReturnType<T>) => {\n      if (maxCacheSize <= 0) return; // Caching disabled\n\n      if (!cache.has(key)) {\n           // Evict oldest if size exceeded\n           if (cache.size >= maxCacheSize) {\n               const oldestKey = cacheKeys.shift(); // Remove oldest key from tracking\n               if (oldestKey) {\n                  cache.delete(oldestKey); // Remove from cache map\n               }\n           }\n           cacheKeys.push(key); // Add new key to tracking\n      } else {\n           // Refresh key position if it exists (treat as most recently used)\n           const index = cacheKeys.indexOf(key);\n           if (index > -1) {\n              cacheKeys.splice(index, 1);\n              cacheKeys.push(key);\n           }\n      }\n      cache.set(key, value);\n  }\n\n  // Invokes the target function and resolves/rejects the sequence promise\n  const invokeFuncAndResolve = (\n      args: Parameters<T>,\n      ctx: ThisParameterType<T> | null\n  ) => {\n    const invokeTime = Date.now();\n    lastInvokeTime = invokeTime; // Record invocation time\n\n    // Capture promise handlers before potential async operations clear them\n    const resolve = sequenceResolve;\n    const reject = sequenceReject;\n\n    // Reset sequence promise state immediately *before* calling func\n    sequencePromise = null;\n    sequenceResolve = null;\n    sequenceReject = null;\n\n    try {\n      const effectiveContext = context ?? ctx ?? null;\n      const result = func.apply(effectiveContext as ThisParameterType<T>, args);\n\n      Promise.resolve(result).then(\n        (value) => {\n          const cacheKey = JSON.stringify(args);\n          addToCache(cacheKey, value);\n          if (resolve) { resolve(value); }\n        },\n        (error) => {\n          if (reject) { reject(error); }\n        }\n      );\n    } catch (error) {\n      if (reject) { reject(error); }\n    }\n  };\n\n  // Timer callback for the trailing edge\n  const trailingEdgeCallback = () => {\n    timeoutId = null; // Timer done\n\n    // Invoke only if enough time passed since the last call (standard wait)\n    // AND maxWait condition (if applicable) is met relative to last *invocation*\n    const time = Date.now();\n    const timeSinceLastCall = time - lastCallTime;\n    const timeSinceLastInvoke = time - lastInvokeTime;\n\n    let shouldInvoke = timeSinceLastCall >= wait;\n\n    if (shouldInvoke && maxWait !== null) {\n         // If maxWait is set, we only *really* invoke if maxWait time has passed since last invoke\n         // (The timer delay already accounted for the minimum wait)\n         // This handles the case where the timer was set based on maxWait, but we might have been called again since.\n         // Re-evaluate: This check might be redundant if the delay calculation is correct.\n         // Let's simplify: if the timer fires, the conditions were met when it was *set*.\n    }\n\n    if (lastArgs) { // Ensure we have args to invoke with\n        invokeFuncAndResolve(lastArgs, lastThis);\n    }\n     // else: Should not happen if timer was set correctly with args stored\n  };\n\n  // Timer callback for when cooldown period ends (does nothing)\n  const cooldownCallback = () => {\n    timeoutId = null; // Cooldown timer is done\n    // If a call came during cooldown, its trailing timer should already be set.\n  };\n\n  // --- The Debounced Function ---\n  const debounced = function (this: ThisParameterType<T>, ...args: Parameters<T>): Promise<ReturnType<T>> {\n    const time = Date.now();\n    lastCallTime = time; // Record time of this call\n    lastArgs = args; // Store args & context from *this* call\n    lastThis = context ?? this;\n\n    // --- Cache Check ---\n    const cacheKey = JSON.stringify(args);\n    if (maxCacheSize > 0 && cache.has(cacheKey)) {\n      const index = cacheKeys.indexOf(cacheKey);\n      if (index > -1) { cacheKeys.splice(index, 1); cacheKeys.push(cacheKey); }\n      return Promise.resolve(cache.get(cacheKey)!); // Return cached value immediately\n    }\n\n    // --- Determine invocation strategy ---\n    const isTimerRunning = !!timeoutId;\n    const shouldCallNow = immediate && !isTimerRunning; // Only immediate if no timer is active\n\n    // --- Promise Handling ---\n    // Reuse or create a promise for this sequence\n    if (!sequencePromise) {\n       sequencePromise = new Promise((resolve, reject) => {\n          sequenceResolve = resolve;\n          sequenceReject = reject;\n       });\n    }\n    const currentSequencePromise = sequencePromise; // Capture for return\n\n    // --- Timer Management ---\n    if (timeoutId) { // Clear any existing timer\n      clearTimeout(timeoutId);\n      timeoutId = null;\n    }\n\n    if (shouldCallNow) {\n      // --- Immediate Invocation ---\n      invokeFuncAndResolve(args, lastThis);\n      // Set cooldown timer - does nothing on expiry, just blocks immediate calls\n      timeoutId = setTimeout(cooldownCallback, wait);\n    } else {\n      // --- Delayed (Trailing) Invocation ---\n      // Calculate delay based on 'wait' and 'maxWait'\n      let delay = wait;\n      if (maxWait !== null) {\n           const timeSinceInvoke = time - lastInvokeTime;\n           // Time until maxWait would expire from last successful invocation\n           const timeUntilMaxWait = maxWait - timeSinceInvoke;\n\n           // We should invoke after 'delay' ms OR when maxWait is hit, whichever is sooner.\n           // But the delay should not be *less* than the remaining standard wait time.\n           // Wait time remaining based on *this* call: wait - (time - lastCallTime) is complex.\n           // Simpler: Use standard wait, but bounded by maxWait limit from last invoke.\n           if (timeUntilMaxWait < delay) {\n              delay = timeUntilMaxWait > 0 ? timeUntilMaxWait : 0;\n           }\n      }\n       // Ensure delay isn't negative if clocks/times are weird\n       delay = Math.max(0, delay);\n\n      // Set trailing edge timer\n      timeoutId = setTimeout(trailingEdgeCallback, delay);\n    }\n\n    return currentSequencePromise; // Return the promise for this sequence\n\n  } as DebouncedFunction<T>;\n\n  // --- Cancel Method ---\n  debounced.cancel = function () {\n    if (timeoutId) { clearTimeout(timeoutId); }\n    lastInvokeTime = 0; // Reset invoke time to allow immediate next time\n    timeoutId = null;\n    lastArgs = null;\n    lastThis = null;\n    // Reject the pending sequence promise, if it exists\n    if (sequenceReject) {\n      sequenceReject(new Error('Debounced function call was cancelled.'));\n    }\n    sequencePromise = null;\n    sequenceResolve = null;\n    sequenceReject = null;\n  };\n\n  return debounced;\n}"],"names":["exports","modulate","func","wait","immediate","context","maxCacheSize","maxWait","TypeError","isNaN","timeoutId","cache","Map","cacheKeys","lastArgs","lastThis","lastCallTime","lastInvokeTime","sequencePromise","sequenceResolve","sequenceReject","invokeFuncAndResolve","args","ctx","invokeTime","Date","now","resolve","reject","effectiveContext","_a","result","apply","Promise","then","value","key","has","index","indexOf","splice","push","size","oldestKey","shift","delete","set","addToCache","JSON","stringify","error","trailingEdgeCallback","cooldownCallback","debounced","time","this","cacheKey","get","shouldCallNow","currentSequencePromise","clearTimeout","setTimeout","delay","timeUntilMaxWait","Math","max","cancel","Error"],"sourceRoot":""}