@tanstack/preact-pacer 0.21.1 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/async-batcher/useAsyncBatcher.cjs +2 -2
  2. package/dist/async-batcher/useAsyncBatcher.cjs.map +1 -1
  3. package/dist/async-batcher/useAsyncBatcher.d.cts +2 -2
  4. package/dist/async-batcher/useAsyncBatcher.d.ts +2 -2
  5. package/dist/async-batcher/useAsyncBatcher.js +3 -3
  6. package/dist/async-batcher/useAsyncBatcher.js.map +1 -1
  7. package/dist/async-debouncer/useAsyncDebouncer.cjs +2 -2
  8. package/dist/async-debouncer/useAsyncDebouncer.cjs.map +1 -1
  9. package/dist/async-debouncer/useAsyncDebouncer.d.cts +2 -2
  10. package/dist/async-debouncer/useAsyncDebouncer.d.ts +2 -2
  11. package/dist/async-debouncer/useAsyncDebouncer.js +3 -3
  12. package/dist/async-debouncer/useAsyncDebouncer.js.map +1 -1
  13. package/dist/async-queuer/useAsyncQueuer.cjs +2 -2
  14. package/dist/async-queuer/useAsyncQueuer.cjs.map +1 -1
  15. package/dist/async-queuer/useAsyncQueuer.d.cts +2 -2
  16. package/dist/async-queuer/useAsyncQueuer.d.ts +2 -2
  17. package/dist/async-queuer/useAsyncQueuer.js +3 -3
  18. package/dist/async-queuer/useAsyncQueuer.js.map +1 -1
  19. package/dist/async-rate-limiter/useAsyncRateLimiter.cjs +2 -2
  20. package/dist/async-rate-limiter/useAsyncRateLimiter.cjs.map +1 -1
  21. package/dist/async-rate-limiter/useAsyncRateLimiter.d.cts +2 -2
  22. package/dist/async-rate-limiter/useAsyncRateLimiter.d.ts +2 -2
  23. package/dist/async-rate-limiter/useAsyncRateLimiter.js +3 -3
  24. package/dist/async-rate-limiter/useAsyncRateLimiter.js.map +1 -1
  25. package/dist/async-throttler/useAsyncThrottler.cjs +2 -2
  26. package/dist/async-throttler/useAsyncThrottler.cjs.map +1 -1
  27. package/dist/async-throttler/useAsyncThrottler.d.cts +2 -2
  28. package/dist/async-throttler/useAsyncThrottler.d.ts +2 -2
  29. package/dist/async-throttler/useAsyncThrottler.js +3 -3
  30. package/dist/async-throttler/useAsyncThrottler.js.map +1 -1
  31. package/dist/batcher/useBatcher.cjs +2 -2
  32. package/dist/batcher/useBatcher.cjs.map +1 -1
  33. package/dist/batcher/useBatcher.d.cts +2 -2
  34. package/dist/batcher/useBatcher.d.ts +2 -2
  35. package/dist/batcher/useBatcher.js +3 -3
  36. package/dist/batcher/useBatcher.js.map +1 -1
  37. package/dist/debouncer/useDebouncer.cjs +2 -2
  38. package/dist/debouncer/useDebouncer.cjs.map +1 -1
  39. package/dist/debouncer/useDebouncer.d.cts +2 -2
  40. package/dist/debouncer/useDebouncer.d.ts +2 -2
  41. package/dist/debouncer/useDebouncer.js +3 -3
  42. package/dist/debouncer/useDebouncer.js.map +1 -1
  43. package/dist/queuer/useQueuer.cjs +2 -2
  44. package/dist/queuer/useQueuer.cjs.map +1 -1
  45. package/dist/queuer/useQueuer.d.cts +2 -2
  46. package/dist/queuer/useQueuer.d.ts +2 -2
  47. package/dist/queuer/useQueuer.js +3 -3
  48. package/dist/queuer/useQueuer.js.map +1 -1
  49. package/dist/rate-limiter/useRateLimiter.cjs +2 -2
  50. package/dist/rate-limiter/useRateLimiter.cjs.map +1 -1
  51. package/dist/rate-limiter/useRateLimiter.d.cts +2 -2
  52. package/dist/rate-limiter/useRateLimiter.d.ts +2 -2
  53. package/dist/rate-limiter/useRateLimiter.js +3 -3
  54. package/dist/rate-limiter/useRateLimiter.js.map +1 -1
  55. package/dist/throttler/useThrottler.cjs +2 -2
  56. package/dist/throttler/useThrottler.cjs.map +1 -1
  57. package/dist/throttler/useThrottler.d.cts +2 -2
  58. package/dist/throttler/useThrottler.d.ts +2 -2
  59. package/dist/throttler/useThrottler.js +3 -3
  60. package/dist/throttler/useThrottler.js.map +1 -1
  61. package/package.json +5 -5
  62. package/src/async-batcher/useAsyncBatcher.ts +6 -6
  63. package/src/async-debouncer/useAsyncDebouncer.ts +8 -6
  64. package/src/async-queuer/useAsyncQueuer.ts +6 -6
  65. package/src/async-rate-limiter/useAsyncRateLimiter.ts +8 -6
  66. package/src/async-throttler/useAsyncThrottler.ts +8 -6
  67. package/src/batcher/useBatcher.ts +6 -6
  68. package/src/debouncer/useDebouncer.ts +6 -6
  69. package/src/queuer/useQueuer.ts +6 -6
  70. package/src/rate-limiter/useRateLimiter.ts +6 -6
  71. package/src/throttler/useThrottler.ts +6 -6
@@ -184,7 +184,7 @@ function useAsyncRateLimiter(fn, options, selector = () => ({})) {
184
184
  const [asyncRateLimiter] = (0, preact_hooks.useState)(() => {
185
185
  const rateLimiterInstance = new _tanstack_pacer_async_rate_limiter.AsyncRateLimiter(fn, mergedOptions);
186
186
  rateLimiterInstance.Subscribe = function Subscribe(props) {
187
- const selected = (0, _tanstack_preact_store.useStore)(rateLimiterInstance.store, props.selector, { equal: _tanstack_preact_store.shallow });
187
+ const selected = (0, _tanstack_preact_store.useSelector)(rateLimiterInstance.store, props.selector, { compare: _tanstack_preact_store.shallow });
188
188
  return typeof props.children === "function" ? props.children(selected) : props.children;
189
189
  };
190
190
  return rateLimiterInstance;
@@ -197,7 +197,7 @@ function useAsyncRateLimiter(fn, options, selector = () => ({})) {
197
197
  else asyncRateLimiter.abort();
198
198
  };
199
199
  }, []);
200
- const state = (0, _tanstack_preact_store.useStore)(asyncRateLimiter.store, selector, { equal: _tanstack_preact_store.shallow });
200
+ const state = (0, _tanstack_preact_store.useSelector)(asyncRateLimiter.store, selector, { compare: _tanstack_preact_store.shallow });
201
201
  return (0, preact_hooks.useMemo)(() => ({
202
202
  ...asyncRateLimiter,
203
203
  state
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncRateLimiter.cjs","names":["useDefaultPacerOptions","AsyncRateLimiter","shallow"],"sources":["../../src/async-rate-limiter/useAsyncRateLimiter.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { shallow, useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncRateLimiterOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncRateLimiterOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the rate limiter instance.\n * When provided, replaces the default cleanup (abort); use it to call reset(), add logging, etc.\n */\n onUnmount?: (rateLimiter: PreactAsyncRateLimiter<TFn, TSelected>) => void\n}\n\nexport interface PreactAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async 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>Rejections: {rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\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 `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.\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 allows an async function to execute up to a specified limit within a time window,\n * then blocks subsequent calls until the window passes. This is useful for respecting API rate limits,\n * managing resource constraints, or controlling bursts of async operations.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited 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 rate-limited function.\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 * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter 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 AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\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 * - `errorCount`: Number of function executions that have resulted in errors\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `isExecuting`: Whether the rate-limited function is currently executing asynchronously\n * - `lastResult`: The result from the most recent successful function execution\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `successCount`: Number of function executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook 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.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n * {({ rejectionCount }) => (\n * <div>Rejections: {rejectionCount}</div>\n * )}\n * </asyncRateLimiter.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Opt-in to re-render when error/rejection state changes (optimized for error handling)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * limit: 5,\n * window: 1000,\n * onError: (error) => console.error('API call failed:', error),\n * onReject: (rateLimiter) => console.log('Rate limit exceeded')\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settleCount: state.settleCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when execution times change (optimized for window calculations)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // With state management and return value\n * const [data, setData] = useState(null);\n * const { maybeExecute, state } = useAsyncRateLimiter(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * limit: 10,\n * window: 60000, // 10 calls per minute\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * },\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, rejectionCount } = state;\n * ```\n */\nexport function useAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: PreactAsyncRateLimiterOptions<TFn, TSelected>,\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncRateLimiter,\n ...options,\n } as PreactAsyncRateLimiterOptions<TFn, TSelected>\n\n const [asyncRateLimiter] = useState(() => {\n const rateLimiterInstance = new AsyncRateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncRateLimiter<TFn, TSelected>\n\n rateLimiterInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(rateLimiterInstance.store, props.selector, {\n equal: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return rateLimiterInstance\n })\n\n asyncRateLimiter.fn = fn\n asyncRateLimiter.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncRateLimiter)\n } else {\n asyncRateLimiter.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(asyncRateLimiter.store, selector, { equal: shallow })\n\n return useMemo(\n () =>\n ({\n ...asyncRateLimiter,\n state,\n }) as PreactAsyncRateLimiter<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncRateLimiter, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsOA,SAAgB,oBAId,IACA,SACA,kBACG,EAAE,GACmC;CACxC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,qDAAmC;EACxC,MAAM,sBAAsB,IAAIC,oDAC9B,IACA,cACD;AAED,sBAAoB,YAAY,SAAS,UAAqB,OAG3D;GACD,MAAM,gDAAoB,oBAAoB,OAAO,MAAM,UAAU,EACnE,OAAOC,gCACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,kBAAiB,KAAK;AACtB,kBAAiB,WAAW,cAAc;AAG1C,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,iBAAiB;OAEzC,kBAAiB,OAAO;;IAG3B,EAAE,CAAC;CAGN,MAAM,6CAAiB,iBAAiB,OAAO,UAAU,EAAE,OAAOA,gCAAS,CAAC;AAE5E,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,kBAAkB,MAAM,CAC1B"}
1
+ {"version":3,"file":"useAsyncRateLimiter.cjs","names":["useDefaultPacerOptions","AsyncRateLimiter","shallow"],"sources":["../../src/async-rate-limiter/useAsyncRateLimiter.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { shallow, useSelector } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncRateLimiterOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncRateLimiterOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the rate limiter instance.\n * When provided, replaces the default cleanup (abort); use it to call reset(), add logging, etc.\n */\n onUnmount?: (rateLimiter: PreactAsyncRateLimiter<TFn, TSelected>) => void\n}\n\nexport interface PreactAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async 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>Rejections: {rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\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<AsyncRateLimiterState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.\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 allows an async function to execute up to a specified limit within a time window,\n * then blocks subsequent calls until the window passes. This is useful for respecting API rate limits,\n * managing resource constraints, or controlling bursts of async operations.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited 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 rate-limited function.\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 * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter 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 AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\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 * - `errorCount`: Number of function executions that have resulted in errors\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `isExecuting`: Whether the rate-limited function is currently executing asynchronously\n * - `lastResult`: The result from the most recent successful function execution\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `successCount`: Number of function executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook 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.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n * {({ rejectionCount }) => (\n * <div>Rejections: {rejectionCount}</div>\n * )}\n * </asyncRateLimiter.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Opt-in to re-render when error/rejection state changes (optimized for error handling)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * limit: 5,\n * window: 1000,\n * onError: (error) => console.error('API call failed:', error),\n * onReject: (rateLimiter) => console.log('Rate limit exceeded')\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settleCount: state.settleCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when execution times change (optimized for window calculations)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // With state management and return value\n * const [data, setData] = useState(null);\n * const { maybeExecute, state } = useAsyncRateLimiter(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * limit: 10,\n * window: 60000, // 10 calls per minute\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * },\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, rejectionCount } = state;\n * ```\n */\nexport function useAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: PreactAsyncRateLimiterOptions<TFn, TSelected>,\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncRateLimiter,\n ...options,\n } as PreactAsyncRateLimiterOptions<TFn, TSelected>\n\n const [asyncRateLimiter] = useState(() => {\n const rateLimiterInstance = new AsyncRateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncRateLimiter<TFn, TSelected>\n\n rateLimiterInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\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 asyncRateLimiter.fn = fn\n asyncRateLimiter.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncRateLimiter)\n } else {\n asyncRateLimiter.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useSelector(asyncRateLimiter.store, selector, {\n compare: shallow,\n })\n\n return useMemo(\n () =>\n ({\n ...asyncRateLimiter,\n state,\n }) as PreactAsyncRateLimiter<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncRateLimiter, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsOA,SAAgB,oBAId,IACA,SACA,kBACG,EAAE,GACmC;CACxC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,qDAAmC;EACxC,MAAM,sBAAsB,IAAIC,oDAC9B,IACA,cACD;AAED,sBAAoB,YAAY,SAAS,UAAqB,OAG3D;GACD,MAAM,mDAAuB,oBAAoB,OAAO,MAAM,UAAU,EACtE,SAASC,gCACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,kBAAiB,KAAK;AACtB,kBAAiB,WAAW,cAAc;AAG1C,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,iBAAiB;OAEzC,kBAAiB,OAAO;;IAG3B,EAAE,CAAC;CAGN,MAAM,gDAAoB,iBAAiB,OAAO,UAAU,EAC1D,SAASA,gCACV,CAAC;AAEF,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,kBAAkB,MAAM,CAC1B"}
@@ -37,8 +37,8 @@ interface PreactAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}> e
37
37
  readonly state: Readonly<TSelected>;
38
38
  /**
39
39
  * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.
40
- * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
41
- * Although, you can make the state reactive by using the `useStore` in your own usage.
40
+ * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
41
+ * Although, you can make the state reactive by using the `useSelector` in your own usage.
42
42
  */
43
43
  readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>;
44
44
  }
@@ -37,8 +37,8 @@ interface PreactAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}> e
37
37
  readonly state: Readonly<TSelected>;
38
38
  /**
39
39
  * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.
40
- * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
41
- * Although, you can make the state reactive by using the `useStore` in your own usage.
40
+ * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
41
+ * Although, you can make the state reactive by using the `useSelector` in your own usage.
42
42
  */
43
43
  readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>;
44
44
  }
@@ -1,6 +1,6 @@
1
1
  import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
2
2
  import { useEffect, useMemo, useState } from "preact/hooks";
3
- import { shallow, useStore } from "@tanstack/preact-store";
3
+ import { shallow, useSelector } from "@tanstack/preact-store";
4
4
  import { AsyncRateLimiter } from "@tanstack/pacer/async-rate-limiter";
5
5
 
6
6
  //#region src/async-rate-limiter/useAsyncRateLimiter.ts
@@ -184,7 +184,7 @@ function useAsyncRateLimiter(fn, options, selector = () => ({})) {
184
184
  const [asyncRateLimiter] = useState(() => {
185
185
  const rateLimiterInstance = new AsyncRateLimiter(fn, mergedOptions);
186
186
  rateLimiterInstance.Subscribe = function Subscribe(props) {
187
- const selected = useStore(rateLimiterInstance.store, props.selector, { equal: shallow });
187
+ const selected = useSelector(rateLimiterInstance.store, props.selector, { compare: shallow });
188
188
  return typeof props.children === "function" ? props.children(selected) : props.children;
189
189
  };
190
190
  return rateLimiterInstance;
@@ -197,7 +197,7 @@ function useAsyncRateLimiter(fn, options, selector = () => ({})) {
197
197
  else asyncRateLimiter.abort();
198
198
  };
199
199
  }, []);
200
- const state = useStore(asyncRateLimiter.store, selector, { equal: shallow });
200
+ const state = useSelector(asyncRateLimiter.store, selector, { compare: shallow });
201
201
  return useMemo(() => ({
202
202
  ...asyncRateLimiter,
203
203
  state
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncRateLimiter.js","names":[],"sources":["../../src/async-rate-limiter/useAsyncRateLimiter.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { shallow, useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncRateLimiterOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncRateLimiterOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the rate limiter instance.\n * When provided, replaces the default cleanup (abort); use it to call reset(), add logging, etc.\n */\n onUnmount?: (rateLimiter: PreactAsyncRateLimiter<TFn, TSelected>) => void\n}\n\nexport interface PreactAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async 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>Rejections: {rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\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 `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.\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 allows an async function to execute up to a specified limit within a time window,\n * then blocks subsequent calls until the window passes. This is useful for respecting API rate limits,\n * managing resource constraints, or controlling bursts of async operations.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited 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 rate-limited function.\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 * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter 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 AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\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 * - `errorCount`: Number of function executions that have resulted in errors\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `isExecuting`: Whether the rate-limited function is currently executing asynchronously\n * - `lastResult`: The result from the most recent successful function execution\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `successCount`: Number of function executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook 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.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n * {({ rejectionCount }) => (\n * <div>Rejections: {rejectionCount}</div>\n * )}\n * </asyncRateLimiter.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Opt-in to re-render when error/rejection state changes (optimized for error handling)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * limit: 5,\n * window: 1000,\n * onError: (error) => console.error('API call failed:', error),\n * onReject: (rateLimiter) => console.log('Rate limit exceeded')\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settleCount: state.settleCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when execution times change (optimized for window calculations)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // With state management and return value\n * const [data, setData] = useState(null);\n * const { maybeExecute, state } = useAsyncRateLimiter(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * limit: 10,\n * window: 60000, // 10 calls per minute\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * },\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, rejectionCount } = state;\n * ```\n */\nexport function useAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: PreactAsyncRateLimiterOptions<TFn, TSelected>,\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncRateLimiter,\n ...options,\n } as PreactAsyncRateLimiterOptions<TFn, TSelected>\n\n const [asyncRateLimiter] = useState(() => {\n const rateLimiterInstance = new AsyncRateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncRateLimiter<TFn, TSelected>\n\n rateLimiterInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(rateLimiterInstance.store, props.selector, {\n equal: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return rateLimiterInstance\n })\n\n asyncRateLimiter.fn = fn\n asyncRateLimiter.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncRateLimiter)\n } else {\n asyncRateLimiter.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(asyncRateLimiter.store, selector, { equal: shallow })\n\n return useMemo(\n () =>\n ({\n ...asyncRateLimiter,\n state,\n }) as PreactAsyncRateLimiter<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncRateLimiter, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsOA,SAAgB,oBAId,IACA,SACA,kBACG,EAAE,GACmC;CACxC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,oBAAoB,eAAe;EACxC,MAAM,sBAAsB,IAAI,iBAC9B,IACA,cACD;AAED,sBAAoB,YAAY,SAAS,UAAqB,OAG3D;GACD,MAAM,WAAW,SAAS,oBAAoB,OAAO,MAAM,UAAU,EACnE,OAAO,SACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,kBAAiB,KAAK;AACtB,kBAAiB,WAAW,cAAc;AAG1C,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,iBAAiB;OAEzC,kBAAiB,OAAO;;IAG3B,EAAE,CAAC;CAGN,MAAM,QAAQ,SAAS,iBAAiB,OAAO,UAAU,EAAE,OAAO,SAAS,CAAC;AAE5E,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,kBAAkB,MAAM,CAC1B"}
1
+ {"version":3,"file":"useAsyncRateLimiter.js","names":[],"sources":["../../src/async-rate-limiter/useAsyncRateLimiter.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { shallow, useSelector } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncRateLimiterOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncRateLimiterOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the rate limiter instance.\n * When provided, replaces the default cleanup (abort); use it to call reset(), add logging, etc.\n */\n onUnmount?: (rateLimiter: PreactAsyncRateLimiter<TFn, TSelected>) => void\n}\n\nexport interface PreactAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async 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>Rejections: {rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\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<AsyncRateLimiterState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.\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 allows an async function to execute up to a specified limit within a time window,\n * then blocks subsequent calls until the window passes. This is useful for respecting API rate limits,\n * managing resource constraints, or controlling bursts of async operations.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited 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 rate-limited function.\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 * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter 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 AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\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 * - `errorCount`: Number of function executions that have resulted in errors\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `isExecuting`: Whether the rate-limited function is currently executing asynchronously\n * - `lastResult`: The result from the most recent successful function execution\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `successCount`: Number of function executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook 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.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n * {({ rejectionCount }) => (\n * <div>Rejections: {rejectionCount}</div>\n * )}\n * </asyncRateLimiter.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Opt-in to re-render when error/rejection state changes (optimized for error handling)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * limit: 5,\n * window: 1000,\n * onError: (error) => console.error('API call failed:', error),\n * onReject: (rateLimiter) => console.log('Rate limit exceeded')\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settleCount: state.settleCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when execution times change (optimized for window calculations)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // With state management and return value\n * const [data, setData] = useState(null);\n * const { maybeExecute, state } = useAsyncRateLimiter(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * limit: 10,\n * window: 60000, // 10 calls per minute\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * },\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, rejectionCount } = state;\n * ```\n */\nexport function useAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: PreactAsyncRateLimiterOptions<TFn, TSelected>,\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncRateLimiter,\n ...options,\n } as PreactAsyncRateLimiterOptions<TFn, TSelected>\n\n const [asyncRateLimiter] = useState(() => {\n const rateLimiterInstance = new AsyncRateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncRateLimiter<TFn, TSelected>\n\n rateLimiterInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\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 asyncRateLimiter.fn = fn\n asyncRateLimiter.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncRateLimiter)\n } else {\n asyncRateLimiter.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useSelector(asyncRateLimiter.store, selector, {\n compare: shallow,\n })\n\n return useMemo(\n () =>\n ({\n ...asyncRateLimiter,\n state,\n }) as PreactAsyncRateLimiter<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncRateLimiter, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsOA,SAAgB,oBAId,IACA,SACA,kBACG,EAAE,GACmC;CACxC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,oBAAoB,eAAe;EACxC,MAAM,sBAAsB,IAAI,iBAC9B,IACA,cACD;AAED,sBAAoB,YAAY,SAAS,UAAqB,OAG3D;GACD,MAAM,WAAW,YAAY,oBAAoB,OAAO,MAAM,UAAU,EACtE,SAAS,SACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,kBAAiB,KAAK;AACtB,kBAAiB,WAAW,cAAc;AAG1C,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,iBAAiB;OAEzC,kBAAiB,OAAO;;IAG3B,EAAE,CAAC;CAGN,MAAM,QAAQ,YAAY,iBAAiB,OAAO,UAAU,EAC1D,SAAS,SACV,CAAC;AAEF,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,kBAAkB,MAAM,CAC1B"}
@@ -178,14 +178,14 @@ function useAsyncThrottler(fn, options, selector = () => ({})) {
178
178
  const [asyncThrottler] = (0, preact_hooks.useState)(() => {
179
179
  const throttlerInstance = new _tanstack_pacer_async_throttler.AsyncThrottler(fn, mergedOptions);
180
180
  throttlerInstance.Subscribe = function Subscribe(props) {
181
- const selected = (0, _tanstack_preact_store.useStore)(throttlerInstance.store, props.selector, { equal: _tanstack_preact_store.shallow });
181
+ const selected = (0, _tanstack_preact_store.useSelector)(throttlerInstance.store, props.selector, { compare: _tanstack_preact_store.shallow });
182
182
  return typeof props.children === "function" ? props.children(selected) : props.children;
183
183
  };
184
184
  return throttlerInstance;
185
185
  });
186
186
  asyncThrottler.fn = fn;
187
187
  asyncThrottler.setOptions(mergedOptions);
188
- const state = (0, _tanstack_preact_store.useStore)(asyncThrottler.store, selector, { equal: _tanstack_preact_store.shallow });
188
+ const state = (0, _tanstack_preact_store.useSelector)(asyncThrottler.store, selector, { compare: _tanstack_preact_store.shallow });
189
189
  (0, preact_hooks.useEffect)(() => {
190
190
  return () => {
191
191
  if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncThrottler);
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncThrottler.cjs","names":["useDefaultPacerOptions","AsyncThrottler","shallow"],"sources":["../../src/async-throttler/useAsyncThrottler.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { shallow, useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncThrottlerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: PreactAsyncThrottler<TFn, TSelected>) => void\n}\n\nexport interface PreactAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async throttler state.\n *\n * This is useful for opting into state re-renders for specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.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 `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncThrottler instance\n *\n * ## 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 `throttler.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 * - `errorCount`: Number of function executions that have resulted in errors\n * - `isExecuting`: Whether the throttled function is currently executing asynchronously\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last function execution in milliseconds\n * - `lastResult`: The result from the most recent successful function execution\n * - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds\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 throttler = useAsyncThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your throttled function updates Preact 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 asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { wait: 1000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncThrottler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Processing...' : 'Ready'}</div>\n * )}\n * </asyncThrottler.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount,\n * settleCount: state.settleCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * wait: 1000,\n * onError: (error) => console.error('API call failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when timing information changes (optimized for timing displays)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // With state management and return value\n * const [data, setData] = useState(null);\n * const { maybeExecute, state } = useAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(\n fn: TFn,\n options: PreactAsyncThrottlerOptions<TFn, TSelected>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as PreactAsyncThrottlerOptions<TFn, TSelected>\n const [asyncThrottler] = useState(() => {\n const throttlerInstance = new AsyncThrottler<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncThrottler<TFn, TSelected>\n\n throttlerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(throttlerInstance.store, props.selector, {\n equal: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return throttlerInstance\n })\n\n asyncThrottler.fn = fn\n asyncThrottler.setOptions(mergedOptions)\n\n const state = useStore(asyncThrottler.store, selector, { equal: shallow })\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n asyncThrottler.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n return useMemo(\n () =>\n ({\n ...asyncThrottler,\n state,\n }) as PreactAsyncThrottler<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncThrottler, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgOA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,mDAAiC;EACtC,MAAM,oBAAoB,IAAIC,+CAC5B,IACA,cACD;AAED,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,gDAAoB,kBAAkB,OAAO,MAAM,UAAU,EACjE,OAAOC,gCACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,gBAAe,KAAK;AACpB,gBAAe,WAAW,cAAc;CAExC,MAAM,6CAAiB,eAAe,OAAO,UAAU,EAAE,OAAOA,gCAAS,CAAC;AAG1E,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,eAAe;QAClC;AACL,mBAAe,QAAQ;AACvB,mBAAe,OAAO;;;IAGzB,EAAE,CAAC;AAGN,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
1
+ {"version":3,"file":"useAsyncThrottler.cjs","names":["useDefaultPacerOptions","AsyncThrottler","shallow"],"sources":["../../src/async-throttler/useAsyncThrottler.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { shallow, useSelector } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncThrottlerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: PreactAsyncThrottler<TFn, TSelected>) => void\n}\n\nexport interface PreactAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async throttler state.\n *\n * This is useful for opting into state re-renders for specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.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<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncThrottler instance\n *\n * ## 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 `throttler.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 * - `errorCount`: Number of function executions that have resulted in errors\n * - `isExecuting`: Whether the throttled function is currently executing asynchronously\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last function execution in milliseconds\n * - `lastResult`: The result from the most recent successful function execution\n * - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds\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 throttler = useAsyncThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your throttled function updates Preact 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 asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { wait: 1000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncThrottler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Processing...' : 'Ready'}</div>\n * )}\n * </asyncThrottler.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount,\n * settleCount: state.settleCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * wait: 1000,\n * onError: (error) => console.error('API call failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when timing information changes (optimized for timing displays)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // With state management and return value\n * const [data, setData] = useState(null);\n * const { maybeExecute, state } = useAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(\n fn: TFn,\n options: PreactAsyncThrottlerOptions<TFn, TSelected>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as PreactAsyncThrottlerOptions<TFn, TSelected>\n const [asyncThrottler] = useState(() => {\n const throttlerInstance = new AsyncThrottler<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncThrottler<TFn, TSelected>\n\n throttlerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useSelector(throttlerInstance.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 throttlerInstance\n })\n\n asyncThrottler.fn = fn\n asyncThrottler.setOptions(mergedOptions)\n\n const state = useSelector(asyncThrottler.store, selector, {\n compare: shallow,\n })\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n asyncThrottler.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n return useMemo(\n () =>\n ({\n ...asyncThrottler,\n state,\n }) as PreactAsyncThrottler<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncThrottler, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgOA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,mDAAiC;EACtC,MAAM,oBAAoB,IAAIC,+CAC5B,IACA,cACD;AAED,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,mDAAuB,kBAAkB,OAAO,MAAM,UAAU,EACpE,SAASC,gCACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,gBAAe,KAAK;AACpB,gBAAe,WAAW,cAAc;CAExC,MAAM,gDAAoB,eAAe,OAAO,UAAU,EACxD,SAASA,gCACV,CAAC;AAGF,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,eAAe;QAClC;AACL,mBAAe,QAAQ;AACvB,mBAAe,OAAO;;;IAGzB,EAAE,CAAC;AAGN,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
@@ -37,8 +37,8 @@ interface PreactAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> ext
37
37
  readonly state: Readonly<TSelected>;
38
38
  /**
39
39
  * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.
40
- * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
41
- * Although, you can make the state reactive by using the `useStore` in your own usage.
40
+ * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
41
+ * Although, you can make the state reactive by using the `useSelector` in your own usage.
42
42
  */
43
43
  readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>;
44
44
  }
@@ -37,8 +37,8 @@ interface PreactAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> ext
37
37
  readonly state: Readonly<TSelected>;
38
38
  /**
39
39
  * @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.
40
- * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
41
- * Although, you can make the state reactive by using the `useStore` in your own usage.
40
+ * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
41
+ * Although, you can make the state reactive by using the `useSelector` in your own usage.
42
42
  */
43
43
  readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>;
44
44
  }
@@ -1,6 +1,6 @@
1
1
  import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
2
2
  import { useEffect, useMemo, useState } from "preact/hooks";
3
- import { shallow, useStore } from "@tanstack/preact-store";
3
+ import { shallow, useSelector } from "@tanstack/preact-store";
4
4
  import { AsyncThrottler } from "@tanstack/pacer/async-throttler";
5
5
 
6
6
  //#region src/async-throttler/useAsyncThrottler.ts
@@ -178,14 +178,14 @@ function useAsyncThrottler(fn, options, selector = () => ({})) {
178
178
  const [asyncThrottler] = useState(() => {
179
179
  const throttlerInstance = new AsyncThrottler(fn, mergedOptions);
180
180
  throttlerInstance.Subscribe = function Subscribe(props) {
181
- const selected = useStore(throttlerInstance.store, props.selector, { equal: shallow });
181
+ const selected = useSelector(throttlerInstance.store, props.selector, { compare: shallow });
182
182
  return typeof props.children === "function" ? props.children(selected) : props.children;
183
183
  };
184
184
  return throttlerInstance;
185
185
  });
186
186
  asyncThrottler.fn = fn;
187
187
  asyncThrottler.setOptions(mergedOptions);
188
- const state = useStore(asyncThrottler.store, selector, { equal: shallow });
188
+ const state = useSelector(asyncThrottler.store, selector, { compare: shallow });
189
189
  useEffect(() => {
190
190
  return () => {
191
191
  if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncThrottler);
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncThrottler.js","names":[],"sources":["../../src/async-throttler/useAsyncThrottler.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { shallow, useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncThrottlerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: PreactAsyncThrottler<TFn, TSelected>) => void\n}\n\nexport interface PreactAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async throttler state.\n *\n * This is useful for opting into state re-renders for specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.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 `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncThrottler instance\n *\n * ## 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 `throttler.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 * - `errorCount`: Number of function executions that have resulted in errors\n * - `isExecuting`: Whether the throttled function is currently executing asynchronously\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last function execution in milliseconds\n * - `lastResult`: The result from the most recent successful function execution\n * - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds\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 throttler = useAsyncThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your throttled function updates Preact 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 asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { wait: 1000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncThrottler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Processing...' : 'Ready'}</div>\n * )}\n * </asyncThrottler.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount,\n * settleCount: state.settleCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * wait: 1000,\n * onError: (error) => console.error('API call failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when timing information changes (optimized for timing displays)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // With state management and return value\n * const [data, setData] = useState(null);\n * const { maybeExecute, state } = useAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(\n fn: TFn,\n options: PreactAsyncThrottlerOptions<TFn, TSelected>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as PreactAsyncThrottlerOptions<TFn, TSelected>\n const [asyncThrottler] = useState(() => {\n const throttlerInstance = new AsyncThrottler<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncThrottler<TFn, TSelected>\n\n throttlerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(throttlerInstance.store, props.selector, {\n equal: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return throttlerInstance\n })\n\n asyncThrottler.fn = fn\n asyncThrottler.setOptions(mergedOptions)\n\n const state = useStore(asyncThrottler.store, selector, { equal: shallow })\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n asyncThrottler.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n return useMemo(\n () =>\n ({\n ...asyncThrottler,\n state,\n }) as PreactAsyncThrottler<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncThrottler, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgOA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,kBAAkB,eAAe;EACtC,MAAM,oBAAoB,IAAI,eAC5B,IACA,cACD;AAED,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,WAAW,SAAS,kBAAkB,OAAO,MAAM,UAAU,EACjE,OAAO,SACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,gBAAe,KAAK;AACpB,gBAAe,WAAW,cAAc;CAExC,MAAM,QAAQ,SAAS,eAAe,OAAO,UAAU,EAAE,OAAO,SAAS,CAAC;AAG1E,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,eAAe;QAClC;AACL,mBAAe,QAAQ;AACvB,mBAAe,OAAO;;;IAGzB,EAAE,CAAC;AAGN,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
1
+ {"version":3,"file":"useAsyncThrottler.js","names":[],"sources":["../../src/async-throttler/useAsyncThrottler.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { shallow, useSelector } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncThrottlerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncThrottlerOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the throttler instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (throttler: PreactAsyncThrottler<TFn, TSelected>) => void\n}\n\nexport interface PreactAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async throttler state.\n *\n * This is useful for opting into state re-renders for specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.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<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncThrottler instance\n *\n * ## 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 `throttler.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 * - `errorCount`: Number of function executions that have resulted in errors\n * - `isExecuting`: Whether the throttled function is currently executing asynchronously\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last function execution in milliseconds\n * - `lastResult`: The result from the most recent successful function execution\n * - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds\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 throttler = useAsyncThrottler(fn, {\n * wait: 1000,\n * onUnmount: (t) => t.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your throttled function updates Preact 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 asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { wait: 1000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncThrottler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Processing...' : 'Ready'}</div>\n * )}\n * </asyncThrottler.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount,\n * settleCount: state.settleCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * wait: 1000,\n * onError: (error) => console.error('API call failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when timing information changes (optimized for timing displays)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // With state management and return value\n * const [data, setData] = useState(null);\n * const { maybeExecute, state } = useAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(\n fn: TFn,\n options: PreactAsyncThrottlerOptions<TFn, TSelected>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as PreactAsyncThrottlerOptions<TFn, TSelected>\n const [asyncThrottler] = useState(() => {\n const throttlerInstance = new AsyncThrottler<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncThrottler<TFn, TSelected>\n\n throttlerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useSelector(throttlerInstance.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 throttlerInstance\n })\n\n asyncThrottler.fn = fn\n asyncThrottler.setOptions(mergedOptions)\n\n const state = useSelector(asyncThrottler.store, selector, {\n compare: shallow,\n })\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncThrottler)\n } else {\n asyncThrottler.cancel()\n asyncThrottler.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n return useMemo(\n () =>\n ({\n ...asyncThrottler,\n state,\n }) as PreactAsyncThrottler<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncThrottler, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgOA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,kBAAkB,eAAe;EACtC,MAAM,oBAAoB,IAAI,eAC5B,IACA,cACD;AAED,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,WAAW,YAAY,kBAAkB,OAAO,MAAM,UAAU,EACpE,SAAS,SACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,gBAAe,KAAK;AACpB,gBAAe,WAAW,cAAc;CAExC,MAAM,QAAQ,YAAY,eAAe,OAAO,UAAU,EACxD,SAAS,SACV,CAAC;AAGF,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,eAAe;QAClC;AACL,mBAAe,QAAQ;AACvB,mBAAe,OAAO;;;IAGzB,EAAE,CAAC;AAGN,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
@@ -140,7 +140,7 @@ function useBatcher(fn, options = {}, selector = () => ({})) {
140
140
  const [batcher] = (0, preact_hooks.useState)(() => {
141
141
  const batcherInstance = new _tanstack_pacer_batcher.Batcher(fn, mergedOptions);
142
142
  batcherInstance.Subscribe = function Subscribe(props) {
143
- const selected = (0, _tanstack_preact_store.useStore)(batcherInstance.store, props.selector, { equal: _tanstack_preact_store.shallow });
143
+ const selected = (0, _tanstack_preact_store.useSelector)(batcherInstance.store, props.selector, { compare: _tanstack_preact_store.shallow });
144
144
  return typeof props.children === "function" ? props.children(selected) : props.children;
145
145
  };
146
146
  return batcherInstance;
@@ -153,7 +153,7 @@ function useBatcher(fn, options = {}, selector = () => ({})) {
153
153
  else batcher.cancel();
154
154
  };
155
155
  }, []);
156
- const state = (0, _tanstack_preact_store.useStore)(batcher.store, selector, { equal: _tanstack_preact_store.shallow });
156
+ const state = (0, _tanstack_preact_store.useSelector)(batcher.store, selector, { compare: _tanstack_preact_store.shallow });
157
157
  return (0, preact_hooks.useMemo)(() => ({
158
158
  ...batcher,
159
159
  state
@@ -1 +1 @@
1
- {"version":3,"file":"useBatcher.cjs","names":["useDefaultPacerOptions","Batcher","shallow"],"sources":["../../src/batcher/useBatcher.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Batcher } from '@tanstack/pacer/batcher'\nimport { shallow, useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactBatcherOptions<\n TValue,\n TSelected = {},\n> extends BatcherOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: PreactBatcher<TValue, TSelected>) => void\n}\n\nexport interface PreactBatcher<TValue, TSelected = {}> extends Omit<\n Batcher<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the batcher state.\n *\n * This is useful for opting into state re-renders for specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.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 `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<BatcherState<TValue>>>\n}\n\n/**\n * A Preact hook that creates and manages a Batcher instance.\n *\n * This is a lower-level hook that provides direct access to the Batcher's functionality without\n * any built-in state management. This allows you to integrate it with any state management solution\n * you prefer (useState, Redux, Zustand, etc.) by utilizing the onItemsChange callback.\n *\n * The Batcher collects items and processes them in batches based on configurable conditions:\n * - Maximum batch size\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\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 `batcher.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 batch executions that have been completed\n * - `isEmpty`: Whether the batcher has no items to process\n * - `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing\n * - `isRunning`: Whether the batcher is active and will process items automatically\n * - `items`: Array of items currently queued for batch processing\n * - `size`: Number of items currently in the batch queue\n * - `status`: Current processing status ('idle' | 'pending')\n * - `totalItemsProcessed`: Total number of items processed across all batches\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending batch when the component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = useBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <batcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </batcher.Subscribe>\n *\n * // Opt-in to re-render when batch size changes at hook level (optimized for displaying queue size)\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * size: state.size,\n * isEmpty: state.isEmpty\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Opt-in to re-render when processing state changes (optimized for loading indicators)\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * isPending: state.isPending,\n * isRunning: state.isRunning,\n * status: state.status\n * })\n * );\n *\n * // Example with custom state management and batching\n * const [items, setItems] = useState([]);\n *\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * {\n * maxSize: 5,\n * wait: 2000,\n * onItemsChange: (batcher) => setItems(batcher.peekAllItems()),\n * getShouldExecute: (items) => items.length >= 3\n * }\n * );\n *\n * // Add items to batch - they'll be processed when conditions are met\n * batcher.addItem(1);\n * batcher.addItem(2);\n * batcher.addItem(3); // Triggers batch processing\n *\n * // Control the batcher\n * batcher.stop(); // Pause batching\n * batcher.start(); // Resume batching\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { size, isPending } = batcher.state;\n * ```\n */\nexport function useBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => void,\n options: PreactBatcherOptions<TValue, TSelected> = {},\n selector: (state: BatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().batcher,\n ...options,\n } as PreactBatcherOptions<TValue, TSelected>\n\n const [batcher] = useState(() => {\n const batcherInstance = new Batcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactBatcher<TValue, TSelected>\n\n batcherInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(batcherInstance.store, props.selector, {\n equal: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return batcherInstance\n })\n\n batcher.fn = fn\n batcher.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(batcher)\n } else {\n batcher.cancel()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(batcher.store, selector, { equal: shallow })\n\n return useMemo(\n () =>\n ({\n ...batcher,\n state,\n }) as PreactBatcher<TValue, TSelected>, // omit `store` in favor of `state`\n [batcher, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsLA,SAAgB,WACd,IACA,UAAmD,EAAE,EACrD,kBACG,EAAE,GAC6B;CAClC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,4CAA0B;EAC/B,MAAM,kBAAkB,IAAIC,gCAC1B,IACA,cACD;AAED,kBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,gDAAoB,gBAAgB,OAAO,MAAM,UAAU,EAC/D,OAAOC,gCACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,SAAQ,KAAK;AACb,SAAQ,WAAW,cAAc;AAGjC,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,QAAQ;OAEhC,SAAQ,QAAQ;;IAGnB,EAAE,CAAC;CAGN,MAAM,6CAAiB,QAAQ,OAAO,UAAU,EAAE,OAAOA,gCAAS,CAAC;AAEnE,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,SAAS,MAAM,CACjB"}
1
+ {"version":3,"file":"useBatcher.cjs","names":["useDefaultPacerOptions","Batcher","shallow"],"sources":["../../src/batcher/useBatcher.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Batcher } from '@tanstack/pacer/batcher'\nimport { shallow, useSelector } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactBatcherOptions<\n TValue,\n TSelected = {},\n> extends BatcherOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: PreactBatcher<TValue, TSelected>) => void\n}\n\nexport interface PreactBatcher<TValue, TSelected = {}> extends Omit<\n Batcher<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the batcher state.\n *\n * This is useful for opting into state re-renders for specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.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<BatcherState<TValue>>>\n}\n\n/**\n * A Preact hook that creates and manages a Batcher instance.\n *\n * This is a lower-level hook that provides direct access to the Batcher's functionality without\n * any built-in state management. This allows you to integrate it with any state management solution\n * you prefer (useState, Redux, Zustand, etc.) by utilizing the onItemsChange callback.\n *\n * The Batcher collects items and processes them in batches based on configurable conditions:\n * - Maximum batch size\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\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 `batcher.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 batch executions that have been completed\n * - `isEmpty`: Whether the batcher has no items to process\n * - `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing\n * - `isRunning`: Whether the batcher is active and will process items automatically\n * - `items`: Array of items currently queued for batch processing\n * - `size`: Number of items currently in the batch queue\n * - `status`: Current processing status ('idle' | 'pending')\n * - `totalItemsProcessed`: Total number of items processed across all batches\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending batch when the component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = useBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <batcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </batcher.Subscribe>\n *\n * // Opt-in to re-render when batch size changes at hook level (optimized for displaying queue size)\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * size: state.size,\n * isEmpty: state.isEmpty\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Opt-in to re-render when processing state changes (optimized for loading indicators)\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * isPending: state.isPending,\n * isRunning: state.isRunning,\n * status: state.status\n * })\n * );\n *\n * // Example with custom state management and batching\n * const [items, setItems] = useState([]);\n *\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * {\n * maxSize: 5,\n * wait: 2000,\n * onItemsChange: (batcher) => setItems(batcher.peekAllItems()),\n * getShouldExecute: (items) => items.length >= 3\n * }\n * );\n *\n * // Add items to batch - they'll be processed when conditions are met\n * batcher.addItem(1);\n * batcher.addItem(2);\n * batcher.addItem(3); // Triggers batch processing\n *\n * // Control the batcher\n * batcher.stop(); // Pause batching\n * batcher.start(); // Resume batching\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { size, isPending } = batcher.state;\n * ```\n */\nexport function useBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => void,\n options: PreactBatcherOptions<TValue, TSelected> = {},\n selector: (state: BatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().batcher,\n ...options,\n } as PreactBatcherOptions<TValue, TSelected>\n\n const [batcher] = useState(() => {\n const batcherInstance = new Batcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactBatcher<TValue, TSelected>\n\n batcherInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useSelector(batcherInstance.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 batcherInstance\n })\n\n batcher.fn = fn\n batcher.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(batcher)\n } else {\n batcher.cancel()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useSelector(batcher.store, selector, { compare: shallow })\n\n return useMemo(\n () =>\n ({\n ...batcher,\n state,\n }) as PreactBatcher<TValue, TSelected>, // omit `store` in favor of `state`\n [batcher, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsLA,SAAgB,WACd,IACA,UAAmD,EAAE,EACrD,kBACG,EAAE,GAC6B;CAClC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,4CAA0B;EAC/B,MAAM,kBAAkB,IAAIC,gCAC1B,IACA,cACD;AAED,kBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,mDAAuB,gBAAgB,OAAO,MAAM,UAAU,EAClE,SAASC,gCACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,SAAQ,KAAK;AACb,SAAQ,WAAW,cAAc;AAGjC,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,QAAQ;OAEhC,SAAQ,QAAQ;;IAGnB,EAAE,CAAC;CAGN,MAAM,gDAAoB,QAAQ,OAAO,UAAU,EAAE,SAASA,gCAAS,CAAC;AAExE,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,SAAS,MAAM,CACjB"}
@@ -36,8 +36,8 @@ interface PreactBatcher<TValue, TSelected = {}> extends Omit<Batcher<TValue>, 's
36
36
  readonly state: Readonly<TSelected>;
37
37
  /**
38
38
  * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.
39
- * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
40
- * Although, you can make the state reactive by using the `useStore` in your own usage.
39
+ * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
40
+ * Although, you can make the state reactive by using the `useSelector` in your own usage.
41
41
  */
42
42
  readonly store: Store<Readonly<BatcherState<TValue>>>;
43
43
  }
@@ -36,8 +36,8 @@ interface PreactBatcher<TValue, TSelected = {}> extends Omit<Batcher<TValue>, 's
36
36
  readonly state: Readonly<TSelected>;
37
37
  /**
38
38
  * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.
39
- * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
40
- * Although, you can make the state reactive by using the `useStore` in your own usage.
39
+ * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
40
+ * Although, you can make the state reactive by using the `useSelector` in your own usage.
41
41
  */
42
42
  readonly store: Store<Readonly<BatcherState<TValue>>>;
43
43
  }
@@ -1,6 +1,6 @@
1
1
  import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
2
2
  import { useEffect, useMemo, useState } from "preact/hooks";
3
- import { shallow, useStore } from "@tanstack/preact-store";
3
+ import { shallow, useSelector } from "@tanstack/preact-store";
4
4
  import { Batcher } from "@tanstack/pacer/batcher";
5
5
 
6
6
  //#region src/batcher/useBatcher.ts
@@ -140,7 +140,7 @@ function useBatcher(fn, options = {}, selector = () => ({})) {
140
140
  const [batcher] = useState(() => {
141
141
  const batcherInstance = new Batcher(fn, mergedOptions);
142
142
  batcherInstance.Subscribe = function Subscribe(props) {
143
- const selected = useStore(batcherInstance.store, props.selector, { equal: shallow });
143
+ const selected = useSelector(batcherInstance.store, props.selector, { compare: shallow });
144
144
  return typeof props.children === "function" ? props.children(selected) : props.children;
145
145
  };
146
146
  return batcherInstance;
@@ -153,7 +153,7 @@ function useBatcher(fn, options = {}, selector = () => ({})) {
153
153
  else batcher.cancel();
154
154
  };
155
155
  }, []);
156
- const state = useStore(batcher.store, selector, { equal: shallow });
156
+ const state = useSelector(batcher.store, selector, { compare: shallow });
157
157
  return useMemo(() => ({
158
158
  ...batcher,
159
159
  state
@@ -1 +1 @@
1
- {"version":3,"file":"useBatcher.js","names":[],"sources":["../../src/batcher/useBatcher.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Batcher } from '@tanstack/pacer/batcher'\nimport { shallow, useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactBatcherOptions<\n TValue,\n TSelected = {},\n> extends BatcherOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: PreactBatcher<TValue, TSelected>) => void\n}\n\nexport interface PreactBatcher<TValue, TSelected = {}> extends Omit<\n Batcher<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the batcher state.\n *\n * This is useful for opting into state re-renders for specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.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 `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<BatcherState<TValue>>>\n}\n\n/**\n * A Preact hook that creates and manages a Batcher instance.\n *\n * This is a lower-level hook that provides direct access to the Batcher's functionality without\n * any built-in state management. This allows you to integrate it with any state management solution\n * you prefer (useState, Redux, Zustand, etc.) by utilizing the onItemsChange callback.\n *\n * The Batcher collects items and processes them in batches based on configurable conditions:\n * - Maximum batch size\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\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 `batcher.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 batch executions that have been completed\n * - `isEmpty`: Whether the batcher has no items to process\n * - `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing\n * - `isRunning`: Whether the batcher is active and will process items automatically\n * - `items`: Array of items currently queued for batch processing\n * - `size`: Number of items currently in the batch queue\n * - `status`: Current processing status ('idle' | 'pending')\n * - `totalItemsProcessed`: Total number of items processed across all batches\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending batch when the component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = useBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <batcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </batcher.Subscribe>\n *\n * // Opt-in to re-render when batch size changes at hook level (optimized for displaying queue size)\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * size: state.size,\n * isEmpty: state.isEmpty\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Opt-in to re-render when processing state changes (optimized for loading indicators)\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * isPending: state.isPending,\n * isRunning: state.isRunning,\n * status: state.status\n * })\n * );\n *\n * // Example with custom state management and batching\n * const [items, setItems] = useState([]);\n *\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * {\n * maxSize: 5,\n * wait: 2000,\n * onItemsChange: (batcher) => setItems(batcher.peekAllItems()),\n * getShouldExecute: (items) => items.length >= 3\n * }\n * );\n *\n * // Add items to batch - they'll be processed when conditions are met\n * batcher.addItem(1);\n * batcher.addItem(2);\n * batcher.addItem(3); // Triggers batch processing\n *\n * // Control the batcher\n * batcher.stop(); // Pause batching\n * batcher.start(); // Resume batching\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { size, isPending } = batcher.state;\n * ```\n */\nexport function useBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => void,\n options: PreactBatcherOptions<TValue, TSelected> = {},\n selector: (state: BatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().batcher,\n ...options,\n } as PreactBatcherOptions<TValue, TSelected>\n\n const [batcher] = useState(() => {\n const batcherInstance = new Batcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactBatcher<TValue, TSelected>\n\n batcherInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(batcherInstance.store, props.selector, {\n equal: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return batcherInstance\n })\n\n batcher.fn = fn\n batcher.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(batcher)\n } else {\n batcher.cancel()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useStore(batcher.store, selector, { equal: shallow })\n\n return useMemo(\n () =>\n ({\n ...batcher,\n state,\n }) as PreactBatcher<TValue, TSelected>, // omit `store` in favor of `state`\n [batcher, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsLA,SAAgB,WACd,IACA,UAAmD,EAAE,EACrD,kBACG,EAAE,GAC6B;CAClC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,WAAW,eAAe;EAC/B,MAAM,kBAAkB,IAAI,QAC1B,IACA,cACD;AAED,kBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,WAAW,SAAS,gBAAgB,OAAO,MAAM,UAAU,EAC/D,OAAO,SACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,SAAQ,KAAK;AACb,SAAQ,WAAW,cAAc;AAGjC,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,QAAQ;OAEhC,SAAQ,QAAQ;;IAGnB,EAAE,CAAC;CAGN,MAAM,QAAQ,SAAS,QAAQ,OAAO,UAAU,EAAE,OAAO,SAAS,CAAC;AAEnE,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,SAAS,MAAM,CACjB"}
1
+ {"version":3,"file":"useBatcher.js","names":[],"sources":["../../src/batcher/useBatcher.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { Batcher } from '@tanstack/pacer/batcher'\nimport { shallow, useSelector } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactBatcherOptions<\n TValue,\n TSelected = {},\n> extends BatcherOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: PreactBatcher<TValue, TSelected>) => void\n}\n\nexport interface PreactBatcher<TValue, TSelected = {}> extends Omit<\n Batcher<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the batcher state.\n *\n * This is useful for opting into state re-renders for specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.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<BatcherState<TValue>>>\n}\n\n/**\n * A Preact hook that creates and manages a Batcher instance.\n *\n * This is a lower-level hook that provides direct access to the Batcher's functionality without\n * any built-in state management. This allows you to integrate it with any state management solution\n * you prefer (useState, Redux, Zustand, etc.) by utilizing the onItemsChange callback.\n *\n * The Batcher collects items and processes them in batches based on configurable conditions:\n * - Maximum batch size\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\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 `batcher.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 batch executions that have been completed\n * - `isEmpty`: Whether the batcher has no items to process\n * - `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing\n * - `isRunning`: Whether the batcher is active and will process items automatically\n * - `items`: Array of items currently queued for batch processing\n * - `size`: Number of items currently in the batch queue\n * - `status`: Current processing status ('idle' | 'pending')\n * - `totalItemsProcessed`: Total number of items processed across all batches\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending batch when the component unmounts.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = useBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <batcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </batcher.Subscribe>\n *\n * // Opt-in to re-render when batch size changes at hook level (optimized for displaying queue size)\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * size: state.size,\n * isEmpty: state.isEmpty\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * executionCount: state.executionCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Opt-in to re-render when processing state changes (optimized for loading indicators)\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * { maxSize: 5, wait: 2000 },\n * (state) => ({\n * isPending: state.isPending,\n * isRunning: state.isRunning,\n * status: state.status\n * })\n * );\n *\n * // Example with custom state management and batching\n * const [items, setItems] = useState([]);\n *\n * const batcher = useBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * {\n * maxSize: 5,\n * wait: 2000,\n * onItemsChange: (batcher) => setItems(batcher.peekAllItems()),\n * getShouldExecute: (items) => items.length >= 3\n * }\n * );\n *\n * // Add items to batch - they'll be processed when conditions are met\n * batcher.addItem(1);\n * batcher.addItem(2);\n * batcher.addItem(3); // Triggers batch processing\n *\n * // Control the batcher\n * batcher.stop(); // Pause batching\n * batcher.start(); // Resume batching\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { size, isPending } = batcher.state;\n * ```\n */\nexport function useBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => void,\n options: PreactBatcherOptions<TValue, TSelected> = {},\n selector: (state: BatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().batcher,\n ...options,\n } as PreactBatcherOptions<TValue, TSelected>\n\n const [batcher] = useState(() => {\n const batcherInstance = new Batcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactBatcher<TValue, TSelected>\n\n batcherInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: BatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useSelector(batcherInstance.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 batcherInstance\n })\n\n batcher.fn = fn\n batcher.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(batcher)\n } else {\n batcher.cancel()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useSelector(batcher.store, selector, { compare: shallow })\n\n return useMemo(\n () =>\n ({\n ...batcher,\n state,\n }) as PreactBatcher<TValue, TSelected>, // omit `store` in favor of `state`\n [batcher, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsLA,SAAgB,WACd,IACA,UAAmD,EAAE,EACrD,kBACG,EAAE,GAC6B;CAClC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,WAAW,eAAe;EAC/B,MAAM,kBAAkB,IAAI,QAC1B,IACA,cACD;AAED,kBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,WAAW,YAAY,gBAAgB,OAAO,MAAM,UAAU,EAClE,SAAS,SACV,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,SAAQ,KAAK;AACb,SAAQ,WAAW,cAAc;AAGjC,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,QAAQ;OAEhC,SAAQ,QAAQ;;IAGnB,EAAE,CAAC;CAGN,MAAM,QAAQ,YAAY,QAAQ,OAAO,UAAU,EAAE,SAAS,SAAS,CAAC;AAExE,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,SAAS,MAAM,CACjB"}
@@ -116,7 +116,7 @@ function useDebouncer(fn, options, selector = () => ({})) {
116
116
  const [debouncer] = (0, preact_hooks.useState)(() => {
117
117
  const debouncerInstance = new _tanstack_pacer_debouncer.Debouncer(fn, mergedOptions);
118
118
  debouncerInstance.Subscribe = function Subscribe(props) {
119
- const selected = (0, _tanstack_preact_store.useStore)(debouncerInstance.store, props.selector, { equal: _tanstack_preact_store.shallow });
119
+ const selected = (0, _tanstack_preact_store.useSelector)(debouncerInstance.store, props.selector, { compare: _tanstack_preact_store.shallow });
120
120
  return typeof props.children === "function" ? props.children(selected) : props.children;
121
121
  };
122
122
  return debouncerInstance;
@@ -129,7 +129,7 @@ function useDebouncer(fn, options, selector = () => ({})) {
129
129
  else debouncer.cancel();
130
130
  };
131
131
  }, []);
132
- const state = (0, _tanstack_preact_store.useStore)(debouncer.store, selector, { equal: _tanstack_preact_store.shallow });
132
+ const state = (0, _tanstack_preact_store.useSelector)(debouncer.store, selector, { compare: _tanstack_preact_store.shallow });
133
133
  return (0, preact_hooks.useMemo)(() => ({
134
134
  ...debouncer,
135
135
  state