{"version":3,"file":"useAsyncDebouncer.cjs","names":["useDefaultPacerOptions","AsyncDebouncer","shallow"],"sources":["../../src/async-debouncer/useAsyncDebouncer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'react'\nimport { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { shallow, useSelector } from '@tanstack/react-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/react-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n  AsyncDebouncerOptions,\n  AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { FunctionComponent, ReactNode } from 'react'\n\nexport interface ReactAsyncDebouncerOptions<\n  TFn extends AnyAsyncFunction,\n  TSelected = {},\n> extends AsyncDebouncerOptions<TFn> {\n  /**\n   * Optional callback invoked when the component unmounts. Receives the debouncer instance.\n   * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n   */\n  onUnmount?: (debouncer: ReactAsyncDebouncer<TFn, TSelected>) => void\n}\n\nexport interface ReactAsyncDebouncer<\n  TFn extends AnyAsyncFunction,\n  TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n  /**\n   * A React HOC (Higher Order Component) that allows you to subscribe to the debouncer state.\n   *\n   * This is useful for opting into state re-renders for specific parts of the debouncer state\n   * deep in your component tree without needing to pass a selector to the hook.\n   *\n   * @example\n   * <debouncer.Subscribe selector={(state) => ({ isExecuting: state.isExecuting })}>\n   *   {({ isExecuting }) => (\n   *     <div>{isExecuting ? 'Loading...' : 'Ready'}</div>\n   *   )}\n   * </debouncer.Subscribe>\n   */\n  Subscribe: <TSelected>(props: {\n    selector: (state: AsyncDebouncerState<TFn>) => TSelected\n    children: ((state: TSelected) => ReactNode) | ReactNode\n  }) => ReturnType<FunctionComponent>\n  /**\n   * Reactive state that will be updated and re-rendered when the debouncer state changes\n   *\n   * Use this instead of `debouncer.store.state`\n   */\n  readonly state: Readonly<TSelected>\n  /**\n   * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.\n   * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.\n   * Although, you can make the state reactive by using the `useSelector` in your own usage.\n   */\n  readonly store: Store<Readonly<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level React hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async debouncing ensures that an async function only executes 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 `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 * - 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 AsyncDebouncer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `debouncer.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `errorCount`: Number of function executions that have resulted in errors\n * - `isExecuting`: Whether the debounced function is currently executing asynchronously\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastResult`: The result from the most recent successful function execution\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')\n * - `successCount`: Number of function executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending execution and aborts any in-flight execution when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const debouncer = useAsyncDebouncer(fn, {\n *   wait: 500,\n *   onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your debounced function updates React state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const searchDebouncer = useAsyncDebouncer(\n *   async (query: string) => {\n *     const results = await api.search(query);\n *     return results;\n *   },\n *   { wait: 500 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <searchDebouncer.Subscribe selector={(state) => ({ isExecuting: state.isExecuting, isPending: state.isPending })}>\n *   {({ isExecuting, isPending }) => (\n *     <div>{isExecuting || isPending ? 'Loading...' : 'Ready'}</div>\n *   )}\n * </searchDebouncer.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const searchDebouncer = useAsyncDebouncer(\n *   async (query: string) => {\n *     const results = await api.search(query);\n *     return results;\n *   },\n *   { wait: 500 },\n *   (state) => ({\n *     isExecuting: state.isExecuting,\n *     isPending: state.isPending\n *   })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const searchDebouncer = useAsyncDebouncer(\n *   async (query: string) => {\n *     const results = await api.search(query);\n *     return results;\n *   },\n *   { wait: 500 },\n *   (state) => ({\n *     lastResult: state.lastResult,\n *     successCount: state.successCount\n *   })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const searchDebouncer = useAsyncDebouncer(\n *   async (query: string) => {\n *     const results = await api.search(query);\n *     return results;\n *   },\n *   {\n *     wait: 500,\n *     onError: (error) => console.error('Search failed:', error)\n *   },\n *   (state) => ({\n *     errorCount: state.errorCount,\n *     status: state.status\n *   })\n * );\n *\n * // With state management\n * const [results, setResults] = useState([]);\n * const { maybeExecute, state } = useAsyncDebouncer(\n *   async (searchTerm) => {\n *     const data = await searchAPI(searchTerm);\n *     setResults(data);\n *   },\n *   {\n *     wait: 300,\n *     leading: true,   // Execute immediately on first call\n *     trailing: false, // Skip trailing edge updates\n *     onError: (error) => {\n *       console.error('API call failed:', error);\n *     }\n *   }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(\n  fn: TFn,\n  options: ReactAsyncDebouncerOptions<TFn, TSelected>,\n  selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n    ({}) as TSelected,\n): ReactAsyncDebouncer<TFn, TSelected> {\n  const mergedOptions = {\n    ...useDefaultPacerOptions().asyncDebouncer,\n    ...options,\n  } as ReactAsyncDebouncerOptions<TFn, TSelected>\n  const [asyncDebouncer] = useState(() => {\n    const asyncDebouncerInstance = new AsyncDebouncer<TFn>(\n      fn,\n      mergedOptions,\n    ) as unknown as ReactAsyncDebouncer<TFn, TSelected>\n\n    /* eslint-disable-next-line @eslint-react/component-hook-factories -- Subscribe attached once in useState lazy init; stable per instance */\n    asyncDebouncerInstance.Subscribe = function Subscribe<TSelected>(props: {\n      selector: (state: AsyncDebouncerState<TFn>) => TSelected\n      children: ((state: TSelected) => ReactNode) | ReactNode\n    }) {\n      const selected = useSelector(\n        asyncDebouncerInstance.store,\n        props.selector,\n        { compare: shallow },\n      )\n\n      return typeof props.children === 'function'\n        ? props.children(selected)\n        : props.children\n    }\n\n    return asyncDebouncerInstance\n  })\n\n  asyncDebouncer.fn = fn\n  asyncDebouncer.setOptions(mergedOptions)\n\n  const state = useSelector(asyncDebouncer.store, selector, {\n    compare: shallow,\n  })\n\n  /* eslint-disable react-hooks/exhaustive-deps, @eslint-react/exhaustive-deps, react-compiler/react-compiler -- unmount cleanup only; empty deps keep teardown stable */\n  useEffect(() => {\n    return () => {\n      if (mergedOptions.onUnmount) {\n        mergedOptions.onUnmount(asyncDebouncer)\n      } else {\n        asyncDebouncer.cancel()\n        asyncDebouncer.abort()\n      }\n    }\n  }, [])\n  /* eslint-enable react-hooks/exhaustive-deps, @eslint-react/exhaustive-deps, react-compiler/react-compiler */\n\n  return useMemo(\n    () =>\n      ({\n        ...asyncDebouncer,\n        state,\n      }) as ReactAsyncDebouncer<TFn, TSelected>, // omit `store` in favor of `state`\n    [asyncDebouncer, state],\n  )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqNA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACgC;CACrC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,4CAAiC;EACtC,MAAM,yBAAyB,IAAIC,+CACjC,IACA,cACD;AAGD,yBAAuB,YAAY,SAAS,UAAqB,OAG9D;GACD,MAAM,kDACJ,uBAAuB,OACvB,MAAM,UACN,EAAE,SAASC,+BAAS,CACrB;AAED,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,gBAAe,KAAK;AACpB,gBAAe,WAAW,cAAc;CAExC,MAAM,+CAAoB,eAAe,OAAO,UAAU,EACxD,SAASA,+BACV,CAAC;AAGF,4BAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,eAAe;QAClC;AACL,mBAAe,QAAQ;AACvB,mBAAe,OAAO;;;IAGzB,EAAE,CAAC;AAGN,kCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}