{"version":3,"file":"useRateLimiter.cjs","names":["useDefaultPacerOptions","RateLimiter","shallow"],"sources":["../../src/rate-limiter/useRateLimiter.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'react'\nimport { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { shallow, useSelector } from '@tanstack/react-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/react-store'\nimport type {\n  RateLimiterOptions,\n  RateLimiterState,\n} from '@tanstack/pacer/rate-limiter'\nimport type { AnyFunction } from '@tanstack/pacer/types'\nimport type { FunctionComponent, ReactNode } from 'react'\n\nexport interface ReactRateLimiterOptions<\n  TFn extends AnyFunction,\n  TSelected = {},\n> extends RateLimiterOptions<TFn> {\n  /**\n   * Optional callback invoked when the component unmounts. Receives the rate limiter instance.\n   * When provided, replaces the default cleanup; use it to call reset(), add logging, etc.\n   */\n  onUnmount?: (rateLimiter: ReactRateLimiter<TFn, TSelected>) => void\n}\n\nexport interface ReactRateLimiter<\n  TFn extends AnyFunction,\n  TSelected = {},\n> extends Omit<RateLimiter<TFn>, 'store'> {\n  /**\n   * A React HOC (Higher Order Component) that allows you to subscribe to the rate limiter state.\n   *\n   * This is useful for opting into state re-renders for specific parts of the rate limiter state\n   * deep in your component tree without needing to pass a selector to the hook.\n   *\n   * @example\n   * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n   *   {({ rejectionCount }) => (\n   *     <div>Rejected: {rejectionCount} requests</div>\n   *   )}\n   * </rateLimiter.Subscribe>\n   */\n  Subscribe: <TSelected>(props: {\n    selector: (state: RateLimiterState) => TSelected\n    children: ((state: TSelected) => ReactNode) | ReactNode\n  }) => ReturnType<FunctionComponent>\n  /**\n   * Reactive state that will be updated and re-rendered when the rate limiter state changes\n   *\n   * Use this instead of `rateLimiter.store.state`\n   */\n  readonly state: Readonly<TSelected>\n  /**\n   * @deprecated Use `rateLimiter.state` instead of `rateLimiter.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<RateLimiterState>>\n}\n\n/**\n * A low-level React hook that creates a `RateLimiter` instance to enforce rate limits on function execution.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Rate limiting is a simple \"hard limit\" approach that allows executions until a maximum count is reached within\n * a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,\n * it does not attempt to space out or collapse executions intelligently.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n *   towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n *   consistent rate of execution over time.\n *\n * For smoother execution patterns:\n * - Use throttling when you want consistent spacing between executions (e.g. UI updates)\n * - Use debouncing when you want to collapse rapid-fire events (e.g. search input)\n * - Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)\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 `rateLimiter.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 * - `executionCount`: Number of function executions that have been completed\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n *\n * The hook returns an object containing:\n * - maybeExecute: The rate-limited function that respects the configured limits\n * - getExecutionCount: Returns the number of successful executions\n * - getRejectionCount: Returns the number of rejected executions due to rate limiting\n * - getRemainingInWindow: Returns how many more executions are allowed in the current window\n * - reset: Resets the execution counts and window timing\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const rateLimiter = useRateLimiter(apiCall, {\n *   limit: 5,\n *   window: 60000,\n *   windowType: 'sliding',\n * });\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n *   {({ rejectionCount }) => (\n *     <div>Rejected: {rejectionCount} requests</div>\n *   )}\n * </rateLimiter.Subscribe>\n *\n * // Opt-in to re-render when execution count changes at hook level (optimized for tracking successful executions)\n * const rateLimiter = useRateLimiter(\n *   apiCall,\n *   {\n *     limit: 5,\n *     window: 60000,\n *     windowType: 'sliding',\n *   },\n *   (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)\n * const rateLimiter = useRateLimiter(\n *   apiCall,\n *   {\n *     limit: 5,\n *     window: 60000,\n *     windowType: 'sliding',\n *   },\n *   (state) => ({ rejectionCount: state.rejectionCount })\n * );\n *\n * // Opt-in to re-render when execution times change (optimized for window calculations)\n * const rateLimiter = useRateLimiter(\n *   apiCall,\n *   {\n *     limit: 5,\n *     window: 60000,\n *     windowType: 'sliding',\n *   },\n *   (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // Multiple state properties - re-render when any of these change\n * const rateLimiter = useRateLimiter(\n *   apiCall,\n *   {\n *     limit: 5,\n *     window: 60000,\n *     windowType: 'sliding',\n *   },\n *   (state) => ({\n *     executionCount: state.executionCount,\n *     rejectionCount: state.rejectionCount\n *   })\n * );\n *\n * // Monitor rate limit status\n * const handleClick = () => {\n *   const remaining = rateLimiter.getRemainingInWindow();\n *   if (remaining > 0) {\n *     rateLimiter.maybeExecute(data);\n *   } else {\n *     showRateLimitWarning();\n *   }\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { executionCount, rejectionCount } = rateLimiter.state;\n * ```\n */\nexport function useRateLimiter<TFn extends AnyFunction, TSelected = {}>(\n  fn: TFn,\n  options: ReactRateLimiterOptions<TFn, TSelected>,\n  selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,\n): ReactRateLimiter<TFn, TSelected> {\n  const mergedOptions = {\n    ...useDefaultPacerOptions().rateLimiter,\n    ...options,\n  } as ReactRateLimiterOptions<TFn, TSelected>\n  const [rateLimiter] = useState(() => {\n    const rateLimiterInstance = new RateLimiter<TFn>(\n      fn,\n      mergedOptions,\n    ) as unknown as ReactRateLimiter<TFn, TSelected>\n\n    /* eslint-disable-next-line @eslint-react/component-hook-factories -- Subscribe attached once in useState lazy init; stable per instance */\n    rateLimiterInstance.Subscribe = function Subscribe<TSelected>(props: {\n      selector: (state: RateLimiterState) => TSelected\n      children: ((state: TSelected) => ReactNode) | ReactNode\n    }) {\n      const selected = useSelector(rateLimiterInstance.store, props.selector, {\n        compare: shallow,\n      })\n\n      return typeof props.children === 'function'\n        ? props.children(selected)\n        : props.children\n    }\n\n    return rateLimiterInstance\n  })\n\n  rateLimiter.fn = fn\n  rateLimiter.setOptions(mergedOptions)\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(rateLimiter)\n      }\n    }\n  }, [])\n  /* eslint-enable react-hooks/exhaustive-deps, @eslint-react/exhaustive-deps, react-compiler/react-compiler */\n\n  const state = useSelector(rateLimiter.store, selector, { compare: shallow })\n\n  return useMemo(\n    () =>\n      ({\n        ...rateLimiter,\n        state,\n      }) as ReactRateLimiter<TFn, TSelected>, // omit `store` in favor of `state`\n    [rateLimiter, state],\n  )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6LA,SAAgB,eACd,IACA,SACA,kBAA0D,EAAE,GAC1B;CAClC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,yCAA8B;EACnC,MAAM,sBAAsB,IAAIC,yCAC9B,IACA,cACD;AAGD,sBAAoB,YAAY,SAAS,UAAqB,OAG3D;GACD,MAAM,kDAAuB,oBAAoB,OAAO,MAAM,UAAU,EACtE,SAASC,+BACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,aAAY,KAAK;AACjB,aAAY,WAAW,cAAc;AAGrC,4BAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,YAAY;;IAGvC,EAAE,CAAC;CAGN,MAAM,+CAAoB,YAAY,OAAO,UAAU,EAAE,SAASA,+BAAS,CAAC;AAE5E,kCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,aAAa,MAAM,CACrB"}