@tanstack/solid-pacer 0.18.4 → 0.20.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 (141) hide show
  1. package/README.md +8 -8
  2. package/dist/async-batcher/createAsyncBatcher.cjs +32 -2
  3. package/dist/async-batcher/createAsyncBatcher.cjs.map +1 -1
  4. package/dist/async-batcher/createAsyncBatcher.d.cts +28 -2
  5. package/dist/async-batcher/createAsyncBatcher.d.ts +28 -2
  6. package/dist/async-batcher/createAsyncBatcher.js +32 -2
  7. package/dist/async-batcher/createAsyncBatcher.js.map +1 -1
  8. package/dist/async-batcher/index.cjs +1 -0
  9. package/dist/async-batcher/index.d.cts +2 -2
  10. package/dist/async-batcher/index.d.ts +2 -2
  11. package/dist/async-debouncer/createAsyncDebouncer.cjs +26 -3
  12. package/dist/async-debouncer/createAsyncDebouncer.cjs.map +1 -1
  13. package/dist/async-debouncer/createAsyncDebouncer.d.cts +27 -2
  14. package/dist/async-debouncer/createAsyncDebouncer.d.ts +27 -2
  15. package/dist/async-debouncer/createAsyncDebouncer.js +26 -3
  16. package/dist/async-debouncer/createAsyncDebouncer.js.map +1 -1
  17. package/dist/async-debouncer/index.cjs +1 -0
  18. package/dist/async-debouncer/index.d.cts +2 -2
  19. package/dist/async-debouncer/index.d.ts +2 -2
  20. package/dist/async-queuer/createAsyncQueuer.cjs +32 -2
  21. package/dist/async-queuer/createAsyncQueuer.cjs.map +1 -1
  22. package/dist/async-queuer/createAsyncQueuer.d.cts +28 -2
  23. package/dist/async-queuer/createAsyncQueuer.d.ts +28 -2
  24. package/dist/async-queuer/createAsyncQueuer.js +32 -2
  25. package/dist/async-queuer/createAsyncQueuer.js.map +1 -1
  26. package/dist/async-queuer/index.cjs +1 -0
  27. package/dist/async-queuer/index.d.cts +2 -2
  28. package/dist/async-queuer/index.d.ts +2 -2
  29. package/dist/async-rate-limiter/createAsyncRateLimiter.cjs +16 -2
  30. package/dist/async-rate-limiter/createAsyncRateLimiter.cjs.map +1 -1
  31. package/dist/async-rate-limiter/createAsyncRateLimiter.d.cts +15 -2
  32. package/dist/async-rate-limiter/createAsyncRateLimiter.d.ts +15 -2
  33. package/dist/async-rate-limiter/createAsyncRateLimiter.js +16 -2
  34. package/dist/async-rate-limiter/createAsyncRateLimiter.js.map +1 -1
  35. package/dist/async-rate-limiter/index.cjs +1 -0
  36. package/dist/async-rate-limiter/index.d.cts +2 -2
  37. package/dist/async-rate-limiter/index.d.ts +2 -2
  38. package/dist/async-throttler/createAsyncThrottler.cjs +31 -2
  39. package/dist/async-throttler/createAsyncThrottler.cjs.map +1 -1
  40. package/dist/async-throttler/createAsyncThrottler.d.cts +27 -2
  41. package/dist/async-throttler/createAsyncThrottler.d.ts +27 -2
  42. package/dist/async-throttler/createAsyncThrottler.js +31 -2
  43. package/dist/async-throttler/createAsyncThrottler.js.map +1 -1
  44. package/dist/async-throttler/index.cjs +1 -0
  45. package/dist/async-throttler/index.d.cts +2 -2
  46. package/dist/async-throttler/index.d.ts +2 -2
  47. package/dist/batcher/createBatcher.cjs +23 -2
  48. package/dist/batcher/createBatcher.cjs.map +1 -1
  49. package/dist/batcher/createBatcher.d.cts +22 -2
  50. package/dist/batcher/createBatcher.d.ts +22 -2
  51. package/dist/batcher/createBatcher.js +23 -2
  52. package/dist/batcher/createBatcher.js.map +1 -1
  53. package/dist/batcher/index.cjs +1 -0
  54. package/dist/batcher/index.d.cts +2 -2
  55. package/dist/batcher/index.d.ts +2 -2
  56. package/dist/debouncer/createDebouncedSignal.cjs.map +1 -1
  57. package/dist/debouncer/createDebouncedSignal.d.cts +3 -3
  58. package/dist/debouncer/createDebouncedSignal.d.ts +3 -3
  59. package/dist/debouncer/createDebouncedSignal.js.map +1 -1
  60. package/dist/debouncer/createDebouncedValue.cjs.map +1 -1
  61. package/dist/debouncer/createDebouncedValue.d.cts +3 -3
  62. package/dist/debouncer/createDebouncedValue.d.ts +3 -3
  63. package/dist/debouncer/createDebouncedValue.js.map +1 -1
  64. package/dist/debouncer/createDebouncer.cjs +17 -3
  65. package/dist/debouncer/createDebouncer.cjs.map +1 -1
  66. package/dist/debouncer/createDebouncer.d.cts +21 -2
  67. package/dist/debouncer/createDebouncer.d.ts +21 -2
  68. package/dist/debouncer/createDebouncer.js +17 -3
  69. package/dist/debouncer/createDebouncer.js.map +1 -1
  70. package/dist/debouncer/index.cjs +1 -0
  71. package/dist/debouncer/index.d.cts +2 -2
  72. package/dist/debouncer/index.d.ts +2 -2
  73. package/dist/index.cjs +1 -0
  74. package/dist/index.d.cts +11 -11
  75. package/dist/index.d.ts +11 -11
  76. package/dist/provider/index.cjs +1 -0
  77. package/dist/queuer/createQueuedSignal.cjs.map +1 -1
  78. package/dist/queuer/createQueuedSignal.d.cts +3 -3
  79. package/dist/queuer/createQueuedSignal.d.ts +3 -3
  80. package/dist/queuer/createQueuedSignal.js.map +1 -1
  81. package/dist/queuer/createQueuer.cjs +23 -2
  82. package/dist/queuer/createQueuer.cjs.map +1 -1
  83. package/dist/queuer/createQueuer.d.cts +22 -2
  84. package/dist/queuer/createQueuer.d.ts +22 -2
  85. package/dist/queuer/createQueuer.js +23 -2
  86. package/dist/queuer/createQueuer.js.map +1 -1
  87. package/dist/queuer/index.cjs +1 -0
  88. package/dist/queuer/index.d.cts +2 -2
  89. package/dist/queuer/index.d.ts +2 -2
  90. package/dist/rate-limiter/createRateLimitedSignal.cjs.map +1 -1
  91. package/dist/rate-limiter/createRateLimitedSignal.d.cts +3 -3
  92. package/dist/rate-limiter/createRateLimitedSignal.d.ts +3 -3
  93. package/dist/rate-limiter/createRateLimitedSignal.js.map +1 -1
  94. package/dist/rate-limiter/createRateLimitedValue.cjs.map +1 -1
  95. package/dist/rate-limiter/createRateLimitedValue.d.cts +3 -3
  96. package/dist/rate-limiter/createRateLimitedValue.d.ts +3 -3
  97. package/dist/rate-limiter/createRateLimitedValue.js.map +1 -1
  98. package/dist/rate-limiter/createRateLimiter.cjs +9 -2
  99. package/dist/rate-limiter/createRateLimiter.cjs.map +1 -1
  100. package/dist/rate-limiter/createRateLimiter.d.cts +9 -2
  101. package/dist/rate-limiter/createRateLimiter.d.ts +9 -2
  102. package/dist/rate-limiter/createRateLimiter.js +9 -2
  103. package/dist/rate-limiter/createRateLimiter.js.map +1 -1
  104. package/dist/rate-limiter/index.cjs +1 -0
  105. package/dist/rate-limiter/index.d.cts +2 -2
  106. package/dist/rate-limiter/index.d.ts +2 -2
  107. package/dist/throttler/createThrottledSignal.cjs.map +1 -1
  108. package/dist/throttler/createThrottledSignal.d.cts +3 -3
  109. package/dist/throttler/createThrottledSignal.d.ts +3 -3
  110. package/dist/throttler/createThrottledSignal.js.map +1 -1
  111. package/dist/throttler/createThrottledValue.cjs.map +1 -1
  112. package/dist/throttler/createThrottledValue.d.cts +3 -3
  113. package/dist/throttler/createThrottledValue.d.ts +3 -3
  114. package/dist/throttler/createThrottledValue.js.map +1 -1
  115. package/dist/throttler/createThrottler.cjs +17 -3
  116. package/dist/throttler/createThrottler.cjs.map +1 -1
  117. package/dist/throttler/createThrottler.d.cts +21 -2
  118. package/dist/throttler/createThrottler.d.ts +21 -2
  119. package/dist/throttler/createThrottler.js +17 -3
  120. package/dist/throttler/createThrottler.js.map +1 -1
  121. package/dist/throttler/index.cjs +1 -0
  122. package/dist/throttler/index.d.cts +2 -2
  123. package/dist/throttler/index.d.ts +2 -2
  124. package/package.json +33 -32
  125. package/src/async-batcher/createAsyncBatcher.ts +44 -3
  126. package/src/async-debouncer/createAsyncDebouncer.ts +37 -4
  127. package/src/async-queuer/createAsyncQueuer.ts +44 -3
  128. package/src/async-rate-limiter/createAsyncRateLimiter.ts +30 -3
  129. package/src/async-throttler/createAsyncThrottler.ts +43 -3
  130. package/src/batcher/createBatcher.ts +38 -3
  131. package/src/debouncer/createDebouncedSignal.ts +3 -6
  132. package/src/debouncer/createDebouncedValue.ts +3 -6
  133. package/src/debouncer/createDebouncer.ts +30 -4
  134. package/src/queuer/createQueuedSignal.ts +3 -3
  135. package/src/queuer/createQueuer.ts +37 -3
  136. package/src/rate-limiter/createRateLimitedSignal.ts +6 -6
  137. package/src/rate-limiter/createRateLimitedValue.ts +6 -6
  138. package/src/rate-limiter/createRateLimiter.ts +22 -3
  139. package/src/throttler/createThrottledSignal.ts +3 -6
  140. package/src/throttler/createThrottledValue.ts +3 -6
  141. package/src/throttler/createThrottler.ts +30 -4
@@ -1 +1 @@
1
- {"version":3,"file":"createAsyncDebouncer.js","names":[],"sources":["../../src/async-debouncer/createAsyncDebouncer.ts"],"sourcesContent":["import { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { useStore } from '@tanstack/solid-store'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type {\n AsyncDebouncerOptions,\n AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\n\nexport interface SolidAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the debouncer state.\n *\n * This is useful for tracking specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Waiting...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncDebouncer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `debouncer.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastResult`: The result from the most recent successful execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const debouncer = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const debouncer = createAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * return data;\n * },\n * {\n * wait: 300,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, isExecuting } = debouncer.state();\n * ```\n */\nexport function createAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: AsyncDebouncerOptions<TFn>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as AsyncDebouncerOptions<TFn>\n\n const asyncDebouncer = new AsyncDebouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncDebouncer<TFn, TSelected>\n\n asyncDebouncer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncDebouncer.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncDebouncer.cancel()\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidAsyncDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiJA,SAAgB,qBAId,IACA,SACA,kBACG,EAAE,GACgC;CAMrC,MAAM,iBAAiB,IAAI,eACzB,IANoB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ,CAKA;AAED,gBAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,WAAW,SAAS,eAAe,OAAO,MAAM,SAAS;AAE/D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,SAAS,eAAe,OAAO,SAAS;AAEtD,oBAAmB;AACjB,kBAAgB;AACd,kBAAe,QAAQ;IACvB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
1
+ {"version":3,"file":"createAsyncDebouncer.js","names":[],"sources":["../../src/async-debouncer/createAsyncDebouncer.ts"],"sourcesContent":["import { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { useStore } from '@tanstack/solid-store'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type {\n AsyncDebouncerOptions,\n AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\n\nexport interface SolidAsyncDebouncerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncDebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: SolidAsyncDebouncer<TFn, TSelected>) => void\n}\n\nexport interface SolidAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the debouncer state.\n *\n * This is useful for tracking specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Waiting...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncDebouncer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `debouncer.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastResult`: The result from the most recent successful execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const debouncer = createAsyncDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your debounced function updates Solid signals, those updates may run after the component has\n * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when\n * using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const debouncer = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const debouncer = createAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * return data;\n * },\n * {\n * wait: 300,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, isExecuting } = debouncer.state();\n * ```\n */\nexport function createAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: SolidAsyncDebouncerOptions<TFn, TSelected>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as SolidAsyncDebouncerOptions<TFn, TSelected>\n const asyncDebouncer = new AsyncDebouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncDebouncer<TFn, TSelected>\n\n asyncDebouncer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncDebouncer.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncDebouncer)\n } else {\n asyncDebouncer.cancel()\n asyncDebouncer.abort()\n }\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidAsyncDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8KA,SAAgB,qBAId,IACA,SACA,kBACG,EAAE,GACgC;CACrC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,iBAAiB,IAAI,eACzB,IACA,cACD;AAED,gBAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,WAAW,SAAS,eAAe,OAAO,MAAM,SAAS;AAE/D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,SAAS,eAAe,OAAO,SAAS;AAEtD,oBAAmB;AACjB,kBAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,eAAe;QAClC;AACL,mBAAe,QAAQ;AACvB,mBAAe,OAAO;;IAExB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
@@ -1,3 +1,4 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1
2
  const require_createAsyncDebouncer = require('./createAsyncDebouncer.cjs');
2
3
 
3
4
  exports.createAsyncDebouncer = require_createAsyncDebouncer.createAsyncDebouncer;
@@ -1,3 +1,3 @@
1
- import { SolidAsyncDebouncer, createAsyncDebouncer } from "./createAsyncDebouncer.cjs";
1
+ import { SolidAsyncDebouncer, SolidAsyncDebouncerOptions, createAsyncDebouncer } from "./createAsyncDebouncer.cjs";
2
2
  export * from "@tanstack/pacer/async-debouncer";
3
- export { SolidAsyncDebouncer, createAsyncDebouncer };
3
+ export { SolidAsyncDebouncer, SolidAsyncDebouncerOptions, createAsyncDebouncer };
@@ -1,3 +1,3 @@
1
- import { SolidAsyncDebouncer, createAsyncDebouncer } from "./createAsyncDebouncer.js";
1
+ import { SolidAsyncDebouncer, SolidAsyncDebouncerOptions, createAsyncDebouncer } from "./createAsyncDebouncer.js";
2
2
  export * from "@tanstack/pacer/async-debouncer";
3
- export { SolidAsyncDebouncer, createAsyncDebouncer };
3
+ export { SolidAsyncDebouncer, SolidAsyncDebouncerOptions, createAsyncDebouncer };
@@ -1,4 +1,5 @@
1
1
  const require_PacerProvider = require('../provider/PacerProvider.cjs');
2
+ let solid_js = require("solid-js");
2
3
  let _tanstack_solid_store = require("@tanstack/solid-store");
3
4
  let _tanstack_pacer_async_queuer = require("@tanstack/pacer/async-queuer");
4
5
 
@@ -56,6 +57,25 @@ let _tanstack_pacer_async_queuer = require("@tanstack/pacer/async-queuer");
56
57
  * - `settleCount`: Number of items that have completed processing (successful or failed)
57
58
  * - `successCount`: Number of items that were processed successfully
58
59
  *
60
+ * ## Unmount behavior
61
+ *
62
+ * By default, the primitive stops the queuer and aborts any in-flight task executions when the owning component unmounts.
63
+ * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
64
+ * Use the `onUnmount` option to customize this. For example, to flush pending items instead:
65
+ *
66
+ * ```tsx
67
+ * const queuer = createAsyncQueuer(fn, {
68
+ * concurrency: 2,
69
+ * started: false,
70
+ * onUnmount: (q) => q.flush()
71
+ * });
72
+ * ```
73
+ *
74
+ * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
75
+ * If your task function updates Solid signals, those updates may run after the component has
76
+ * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
77
+ * using onUnmount with flush.
78
+ *
59
79
  * Example usage:
60
80
  * ```tsx
61
81
  * // Default behavior - no reactive state subscriptions
@@ -108,15 +128,25 @@ let _tanstack_pacer_async_queuer = require("@tanstack/pacer/async-queuer");
108
128
  * ```
109
129
  */
110
130
  function createAsyncQueuer(fn, options = {}, selector = () => ({})) {
111
- const asyncQueuer = new _tanstack_pacer_async_queuer.AsyncQueuer(fn, {
131
+ const mergedOptions = {
112
132
  ...require_PacerProvider.useDefaultPacerOptions().asyncQueuer,
113
133
  ...options
114
- });
134
+ };
135
+ const asyncQueuer = new _tanstack_pacer_async_queuer.AsyncQueuer(fn, mergedOptions);
115
136
  asyncQueuer.Subscribe = function Subscribe(props) {
116
137
  const selected = (0, _tanstack_solid_store.useStore)(asyncQueuer.store, props.selector);
117
138
  return typeof props.children === "function" ? props.children(selected) : props.children;
118
139
  };
119
140
  const state = (0, _tanstack_solid_store.useStore)(asyncQueuer.store, selector);
141
+ (0, solid_js.createEffect)(() => {
142
+ (0, solid_js.onCleanup)(() => {
143
+ if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncQueuer);
144
+ else {
145
+ asyncQueuer.stop();
146
+ asyncQueuer.abort();
147
+ }
148
+ });
149
+ });
120
150
  return {
121
151
  ...asyncQueuer,
122
152
  state
@@ -1 +1 @@
1
- {"version":3,"file":"createAsyncQueuer.cjs","names":["AsyncQueuer","useDefaultPacerOptions"],"sources":["../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { useStore } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type {\n AsyncQueuerOptions,\n AsyncQueuerState,\n} from '@tanstack/pacer/async-queuer'\n\nexport interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<\n AsyncQueuer<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the queuer state.\n *\n * This is useful for tracking specific parts of the queuer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <queuer.Subscribe selector={(state) => ({ pendingItems: state.pendingItems, activeItems: state.activeItems })}>\n * {(state) => (\n * <div>Pending: {state().pendingItems.length}, Active: {state().activeItems.length}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the queuer state changes\n *\n * Use this instead of `queuer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `queuer.state` instead of `queuer.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<AsyncQueuerState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible AsyncQueuer instance for managing an asynchronous queue of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Priority queueing via `getPriority` or item `priority` property\n * - Configurable concurrency limit\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause/resume processing\n * - Task cancellation\n * - Item expiration\n * - Lifecycle callbacks for success, error, settled, items change, etc.\n * - All stateful properties (active items, pending items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if the concurrency limit allows.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer 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 AsyncQueuer 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 `queuer.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `activeItems`: Array of items currently being processed\n * - `errorCount`: Number of items that failed processing\n * - `isRunning`: Whether the queuer is currently running (not stopped)\n * - `pendingItems`: Array of items waiting to be processed\n * - `rejectionCount`: Number of items that were rejected (expired or failed validation)\n * - `settleCount`: Number of items that have completed processing (successful or failed)\n * - `successCount`: Number of items that were processed successfully\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncQueuer = createAsyncQueuer(async (item) => {\n * // process item\n * return await fetchData(item);\n * }, {\n * initialItems: [],\n * concurrency: 2,\n * maxSize: 100,\n * started: false,\n * onSuccess: (result) => {\n * console.log('Item processed:', result);\n * },\n * onError: (error) => {\n * console.error('Processing failed:', error);\n * }\n * });\n *\n * // Opt-in to track queue state changes (optimized for UI updates)\n * const asyncQueuer = createAsyncQueuer(\n * async (item) => await fetchData(item),\n * { concurrency: 2, started: true },\n * (state) => ({\n * pendingItems: state.pendingItems,\n * activeItems: state.activeItems,\n * isRunning: state.isRunning\n * })\n * );\n *\n * // Opt-in to track processing metrics changes (optimized for tracking progress)\n * const asyncQueuer = createAsyncQueuer(\n * async (item) => await fetchData(item),\n * { concurrency: 2, started: true },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settleCount: state.settleCount\n * })\n * );\n *\n * // Add items to queue\n * asyncQueuer.addItem(newItem);\n *\n * // Start processing\n * asyncQueuer.start();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { pendingItems, activeItems } = asyncQueuer.state();\n * ```\n */\nexport function createAsyncQueuer<TValue, TSelected = {}>(\n fn: (value: TValue) => Promise<any>,\n options: AsyncQueuerOptions<TValue> = {},\n selector: (state: AsyncQueuerState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncQueuer,\n ...options,\n } as AsyncQueuerOptions<TValue>\n\n const asyncQueuer = new AsyncQueuer<TValue>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncQueuer<TValue, TSelected>\n\n asyncQueuer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncQueuer.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncQueuer.store, selector)\n\n return {\n ...asyncQueuer,\n state,\n } as SolidAsyncQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqJA,SAAgB,kBACd,IACA,UAAsC,EAAE,EACxC,kBACG,EAAE,GACgC;CAMrC,MAAM,cAAc,IAAIA,yCACtB,IANoB;EACpB,GAAGC,8CAAwB,CAAC;EAC5B,GAAG;EACJ,CAKA;AAED,aAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,+CAAoB,YAAY,OAAO,MAAM,SAAS;AAE5D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,4CAAiB,YAAY,OAAO,SAAS;AAEnD,QAAO;EACL,GAAG;EACH;EACD"}
1
+ {"version":3,"file":"createAsyncQueuer.cjs","names":["useDefaultPacerOptions","AsyncQueuer"],"sources":["../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { useStore } from '@tanstack/solid-store'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type {\n AsyncQueuerOptions,\n AsyncQueuerState,\n} from '@tanstack/pacer/async-queuer'\n\nexport interface SolidAsyncQueuerOptions<\n TValue,\n TSelected = {},\n> extends AsyncQueuerOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop + abort); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: SolidAsyncQueuer<TValue, TSelected>) => void\n}\n\nexport interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<\n AsyncQueuer<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the queuer state.\n *\n * This is useful for tracking specific parts of the queuer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <queuer.Subscribe selector={(state) => ({ pendingItems: state.pendingItems, activeItems: state.activeItems })}>\n * {(state) => (\n * <div>Pending: {state().pendingItems.length}, Active: {state().activeItems.length}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the queuer state changes\n *\n * Use this instead of `queuer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `queuer.state` instead of `queuer.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<AsyncQueuerState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible AsyncQueuer instance for managing an asynchronous queue of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Priority queueing via `getPriority` or item `priority` property\n * - Configurable concurrency limit\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause/resume processing\n * - Task cancellation\n * - Item expiration\n * - Lifecycle callbacks for success, error, settled, items change, etc.\n * - All stateful properties (active items, pending items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if the concurrency limit allows.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer 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 AsyncQueuer 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 `queuer.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `activeItems`: Array of items currently being processed\n * - `errorCount`: Number of items that failed processing\n * - `isRunning`: Whether the queuer is currently running (not stopped)\n * - `pendingItems`: Array of items waiting to be processed\n * - `rejectionCount`: Number of items that were rejected (expired or failed validation)\n * - `settleCount`: Number of items that have completed processing (successful or failed)\n * - `successCount`: Number of items that were processed successfully\n *\n * ## Unmount behavior\n *\n * By default, the primitive stops the queuer and aborts any in-flight task executions when the owning 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 items instead:\n *\n * ```tsx\n * const queuer = createAsyncQueuer(fn, {\n * concurrency: 2,\n * started: false,\n * onUnmount: (q) => q.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your task function updates Solid signals, those updates may run after the component has\n * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when\n * using onUnmount with flush.\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncQueuer = createAsyncQueuer(async (item) => {\n * // process item\n * return await fetchData(item);\n * }, {\n * initialItems: [],\n * concurrency: 2,\n * maxSize: 100,\n * started: false,\n * onSuccess: (result) => {\n * console.log('Item processed:', result);\n * },\n * onError: (error) => {\n * console.error('Processing failed:', error);\n * }\n * });\n *\n * // Opt-in to track queue state changes (optimized for UI updates)\n * const asyncQueuer = createAsyncQueuer(\n * async (item) => await fetchData(item),\n * { concurrency: 2, started: true },\n * (state) => ({\n * pendingItems: state.pendingItems,\n * activeItems: state.activeItems,\n * isRunning: state.isRunning\n * })\n * );\n *\n * // Opt-in to track processing metrics changes (optimized for tracking progress)\n * const asyncQueuer = createAsyncQueuer(\n * async (item) => await fetchData(item),\n * { concurrency: 2, started: true },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settleCount: state.settleCount\n * })\n * );\n *\n * // Add items to queue\n * asyncQueuer.addItem(newItem);\n *\n * // Start processing\n * asyncQueuer.start();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { pendingItems, activeItems } = asyncQueuer.state();\n * ```\n */\nexport function createAsyncQueuer<TValue, TSelected = {}>(\n fn: (value: TValue) => Promise<any>,\n options: SolidAsyncQueuerOptions<TValue, TSelected> = {},\n selector: (state: AsyncQueuerState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncQueuer,\n ...options,\n } as SolidAsyncQueuerOptions<TValue, TSelected>\n const asyncQueuer = new AsyncQueuer<TValue>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncQueuer<TValue, TSelected>\n\n asyncQueuer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncQueuer.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncQueuer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncQueuer)\n } else {\n asyncQueuer.stop()\n asyncQueuer.abort()\n }\n })\n })\n\n return {\n ...asyncQueuer,\n state,\n } as SolidAsyncQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoLA,SAAgB,kBACd,IACA,UAAsD,EAAE,EACxD,kBACG,EAAE,GACgC;CACrC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,cAAc,IAAIC,yCACtB,IACA,cACD;AAED,aAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,+CAAoB,YAAY,OAAO,MAAM,SAAS;AAE5D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,4CAAiB,YAAY,OAAO,SAAS;AAEnD,kCAAmB;AACjB,gCAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,YAAY;QAC/B;AACL,gBAAY,MAAM;AAClB,gBAAY,OAAO;;IAErB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
@@ -3,6 +3,13 @@ import { Accessor, JSX } from "solid-js";
3
3
  import { AsyncQueuer, AsyncQueuerOptions, AsyncQueuerState } from "@tanstack/pacer/async-queuer";
4
4
 
5
5
  //#region src/async-queuer/createAsyncQueuer.d.ts
6
+ interface SolidAsyncQueuerOptions<TValue, TSelected = {}> extends AsyncQueuerOptions<TValue> {
7
+ /**
8
+ * Optional callback invoked when the owning component unmounts. Receives the queuer instance.
9
+ * When provided, replaces the default cleanup (stop + abort); use it to call flush(), flushAsBatch(), stop(), add logging, etc.
10
+ */
11
+ onUnmount?: (queuer: SolidAsyncQueuer<TValue, TSelected>) => void;
12
+ }
6
13
  interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<AsyncQueuer<TValue>, 'store'> {
7
14
  /**
8
15
  * A Solid component that allows you to subscribe to the queuer state.
@@ -87,6 +94,25 @@ interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<AsyncQueuer<TVal
87
94
  * - `settleCount`: Number of items that have completed processing (successful or failed)
88
95
  * - `successCount`: Number of items that were processed successfully
89
96
  *
97
+ * ## Unmount behavior
98
+ *
99
+ * By default, the primitive stops the queuer and aborts any in-flight task executions when the owning component unmounts.
100
+ * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
101
+ * Use the `onUnmount` option to customize this. For example, to flush pending items instead:
102
+ *
103
+ * ```tsx
104
+ * const queuer = createAsyncQueuer(fn, {
105
+ * concurrency: 2,
106
+ * started: false,
107
+ * onUnmount: (q) => q.flush()
108
+ * });
109
+ * ```
110
+ *
111
+ * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
112
+ * If your task function updates Solid signals, those updates may run after the component has
113
+ * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
114
+ * using onUnmount with flush.
115
+ *
90
116
  * Example usage:
91
117
  * ```tsx
92
118
  * // Default behavior - no reactive state subscriptions
@@ -138,7 +164,7 @@ interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<AsyncQueuer<TVal
138
164
  * const { pendingItems, activeItems } = asyncQueuer.state();
139
165
  * ```
140
166
  */
141
- declare function createAsyncQueuer<TValue, TSelected = {}>(fn: (value: TValue) => Promise<any>, options?: AsyncQueuerOptions<TValue>, selector?: (state: AsyncQueuerState<TValue>) => TSelected): SolidAsyncQueuer<TValue, TSelected>;
167
+ declare function createAsyncQueuer<TValue, TSelected = {}>(fn: (value: TValue) => Promise<any>, options?: SolidAsyncQueuerOptions<TValue, TSelected>, selector?: (state: AsyncQueuerState<TValue>) => TSelected): SolidAsyncQueuer<TValue, TSelected>;
142
168
  //#endregion
143
- export { SolidAsyncQueuer, createAsyncQueuer };
169
+ export { SolidAsyncQueuer, SolidAsyncQueuerOptions, createAsyncQueuer };
144
170
  //# sourceMappingURL=createAsyncQueuer.d.cts.map
@@ -3,6 +3,13 @@ import { Store } from "@tanstack/solid-store";
3
3
  import { AsyncQueuer, AsyncQueuerOptions, AsyncQueuerState } from "@tanstack/pacer/async-queuer";
4
4
 
5
5
  //#region src/async-queuer/createAsyncQueuer.d.ts
6
+ interface SolidAsyncQueuerOptions<TValue, TSelected = {}> extends AsyncQueuerOptions<TValue> {
7
+ /**
8
+ * Optional callback invoked when the owning component unmounts. Receives the queuer instance.
9
+ * When provided, replaces the default cleanup (stop + abort); use it to call flush(), flushAsBatch(), stop(), add logging, etc.
10
+ */
11
+ onUnmount?: (queuer: SolidAsyncQueuer<TValue, TSelected>) => void;
12
+ }
6
13
  interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<AsyncQueuer<TValue>, 'store'> {
7
14
  /**
8
15
  * A Solid component that allows you to subscribe to the queuer state.
@@ -87,6 +94,25 @@ interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<AsyncQueuer<TVal
87
94
  * - `settleCount`: Number of items that have completed processing (successful or failed)
88
95
  * - `successCount`: Number of items that were processed successfully
89
96
  *
97
+ * ## Unmount behavior
98
+ *
99
+ * By default, the primitive stops the queuer and aborts any in-flight task executions when the owning component unmounts.
100
+ * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
101
+ * Use the `onUnmount` option to customize this. For example, to flush pending items instead:
102
+ *
103
+ * ```tsx
104
+ * const queuer = createAsyncQueuer(fn, {
105
+ * concurrency: 2,
106
+ * started: false,
107
+ * onUnmount: (q) => q.flush()
108
+ * });
109
+ * ```
110
+ *
111
+ * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
112
+ * If your task function updates Solid signals, those updates may run after the component has
113
+ * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
114
+ * using onUnmount with flush.
115
+ *
90
116
  * Example usage:
91
117
  * ```tsx
92
118
  * // Default behavior - no reactive state subscriptions
@@ -138,7 +164,7 @@ interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<AsyncQueuer<TVal
138
164
  * const { pendingItems, activeItems } = asyncQueuer.state();
139
165
  * ```
140
166
  */
141
- declare function createAsyncQueuer<TValue, TSelected = {}>(fn: (value: TValue) => Promise<any>, options?: AsyncQueuerOptions<TValue>, selector?: (state: AsyncQueuerState<TValue>) => TSelected): SolidAsyncQueuer<TValue, TSelected>;
167
+ declare function createAsyncQueuer<TValue, TSelected = {}>(fn: (value: TValue) => Promise<any>, options?: SolidAsyncQueuerOptions<TValue, TSelected>, selector?: (state: AsyncQueuerState<TValue>) => TSelected): SolidAsyncQueuer<TValue, TSelected>;
142
168
  //#endregion
143
- export { SolidAsyncQueuer, createAsyncQueuer };
169
+ export { SolidAsyncQueuer, SolidAsyncQueuerOptions, createAsyncQueuer };
144
170
  //# sourceMappingURL=createAsyncQueuer.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
2
+ import { createEffect, onCleanup } from "solid-js";
2
3
  import { useStore } from "@tanstack/solid-store";
3
4
  import { AsyncQueuer } from "@tanstack/pacer/async-queuer";
4
5
 
@@ -56,6 +57,25 @@ import { AsyncQueuer } from "@tanstack/pacer/async-queuer";
56
57
  * - `settleCount`: Number of items that have completed processing (successful or failed)
57
58
  * - `successCount`: Number of items that were processed successfully
58
59
  *
60
+ * ## Unmount behavior
61
+ *
62
+ * By default, the primitive stops the queuer and aborts any in-flight task executions when the owning component unmounts.
63
+ * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
64
+ * Use the `onUnmount` option to customize this. For example, to flush pending items instead:
65
+ *
66
+ * ```tsx
67
+ * const queuer = createAsyncQueuer(fn, {
68
+ * concurrency: 2,
69
+ * started: false,
70
+ * onUnmount: (q) => q.flush()
71
+ * });
72
+ * ```
73
+ *
74
+ * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
75
+ * If your task function updates Solid signals, those updates may run after the component has
76
+ * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
77
+ * using onUnmount with flush.
78
+ *
59
79
  * Example usage:
60
80
  * ```tsx
61
81
  * // Default behavior - no reactive state subscriptions
@@ -108,15 +128,25 @@ import { AsyncQueuer } from "@tanstack/pacer/async-queuer";
108
128
  * ```
109
129
  */
110
130
  function createAsyncQueuer(fn, options = {}, selector = () => ({})) {
111
- const asyncQueuer = new AsyncQueuer(fn, {
131
+ const mergedOptions = {
112
132
  ...useDefaultPacerOptions().asyncQueuer,
113
133
  ...options
114
- });
134
+ };
135
+ const asyncQueuer = new AsyncQueuer(fn, mergedOptions);
115
136
  asyncQueuer.Subscribe = function Subscribe(props) {
116
137
  const selected = useStore(asyncQueuer.store, props.selector);
117
138
  return typeof props.children === "function" ? props.children(selected) : props.children;
118
139
  };
119
140
  const state = useStore(asyncQueuer.store, selector);
141
+ createEffect(() => {
142
+ onCleanup(() => {
143
+ if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncQueuer);
144
+ else {
145
+ asyncQueuer.stop();
146
+ asyncQueuer.abort();
147
+ }
148
+ });
149
+ });
120
150
  return {
121
151
  ...asyncQueuer,
122
152
  state
@@ -1 +1 @@
1
- {"version":3,"file":"createAsyncQueuer.js","names":[],"sources":["../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { useStore } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type {\n AsyncQueuerOptions,\n AsyncQueuerState,\n} from '@tanstack/pacer/async-queuer'\n\nexport interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<\n AsyncQueuer<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the queuer state.\n *\n * This is useful for tracking specific parts of the queuer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <queuer.Subscribe selector={(state) => ({ pendingItems: state.pendingItems, activeItems: state.activeItems })}>\n * {(state) => (\n * <div>Pending: {state().pendingItems.length}, Active: {state().activeItems.length}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the queuer state changes\n *\n * Use this instead of `queuer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `queuer.state` instead of `queuer.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<AsyncQueuerState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible AsyncQueuer instance for managing an asynchronous queue of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Priority queueing via `getPriority` or item `priority` property\n * - Configurable concurrency limit\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause/resume processing\n * - Task cancellation\n * - Item expiration\n * - Lifecycle callbacks for success, error, settled, items change, etc.\n * - All stateful properties (active items, pending items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if the concurrency limit allows.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer 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 AsyncQueuer 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 `queuer.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `activeItems`: Array of items currently being processed\n * - `errorCount`: Number of items that failed processing\n * - `isRunning`: Whether the queuer is currently running (not stopped)\n * - `pendingItems`: Array of items waiting to be processed\n * - `rejectionCount`: Number of items that were rejected (expired or failed validation)\n * - `settleCount`: Number of items that have completed processing (successful or failed)\n * - `successCount`: Number of items that were processed successfully\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncQueuer = createAsyncQueuer(async (item) => {\n * // process item\n * return await fetchData(item);\n * }, {\n * initialItems: [],\n * concurrency: 2,\n * maxSize: 100,\n * started: false,\n * onSuccess: (result) => {\n * console.log('Item processed:', result);\n * },\n * onError: (error) => {\n * console.error('Processing failed:', error);\n * }\n * });\n *\n * // Opt-in to track queue state changes (optimized for UI updates)\n * const asyncQueuer = createAsyncQueuer(\n * async (item) => await fetchData(item),\n * { concurrency: 2, started: true },\n * (state) => ({\n * pendingItems: state.pendingItems,\n * activeItems: state.activeItems,\n * isRunning: state.isRunning\n * })\n * );\n *\n * // Opt-in to track processing metrics changes (optimized for tracking progress)\n * const asyncQueuer = createAsyncQueuer(\n * async (item) => await fetchData(item),\n * { concurrency: 2, started: true },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settleCount: state.settleCount\n * })\n * );\n *\n * // Add items to queue\n * asyncQueuer.addItem(newItem);\n *\n * // Start processing\n * asyncQueuer.start();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { pendingItems, activeItems } = asyncQueuer.state();\n * ```\n */\nexport function createAsyncQueuer<TValue, TSelected = {}>(\n fn: (value: TValue) => Promise<any>,\n options: AsyncQueuerOptions<TValue> = {},\n selector: (state: AsyncQueuerState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncQueuer,\n ...options,\n } as AsyncQueuerOptions<TValue>\n\n const asyncQueuer = new AsyncQueuer<TValue>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncQueuer<TValue, TSelected>\n\n asyncQueuer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncQueuer.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncQueuer.store, selector)\n\n return {\n ...asyncQueuer,\n state,\n } as SolidAsyncQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqJA,SAAgB,kBACd,IACA,UAAsC,EAAE,EACxC,kBACG,EAAE,GACgC;CAMrC,MAAM,cAAc,IAAI,YACtB,IANoB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ,CAKA;AAED,aAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,WAAW,SAAS,YAAY,OAAO,MAAM,SAAS;AAE5D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,SAAS,YAAY,OAAO,SAAS;AAEnD,QAAO;EACL,GAAG;EACH;EACD"}
1
+ {"version":3,"file":"createAsyncQueuer.js","names":[],"sources":["../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { useStore } from '@tanstack/solid-store'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type {\n AsyncQueuerOptions,\n AsyncQueuerState,\n} from '@tanstack/pacer/async-queuer'\n\nexport interface SolidAsyncQueuerOptions<\n TValue,\n TSelected = {},\n> extends AsyncQueuerOptions<TValue> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the queuer instance.\n * When provided, replaces the default cleanup (stop + abort); use it to call flush(), flushAsBatch(), stop(), add logging, etc.\n */\n onUnmount?: (queuer: SolidAsyncQueuer<TValue, TSelected>) => void\n}\n\nexport interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<\n AsyncQueuer<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the queuer state.\n *\n * This is useful for tracking specific parts of the queuer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <queuer.Subscribe selector={(state) => ({ pendingItems: state.pendingItems, activeItems: state.activeItems })}>\n * {(state) => (\n * <div>Pending: {state().pendingItems.length}, Active: {state().activeItems.length}</div>\n * )}\n * </queuer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the queuer state changes\n *\n * Use this instead of `queuer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `queuer.state` instead of `queuer.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<AsyncQueuerState<TValue>>>\n}\n\n/**\n * Creates a Solid-compatible AsyncQueuer instance for managing an asynchronous queue of items, exposing Solid signals for all stateful properties.\n *\n * Features:\n * - Priority queueing via `getPriority` or item `priority` property\n * - Configurable concurrency limit\n * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior\n * - Pause/resume processing\n * - Task cancellation\n * - Item expiration\n * - Lifecycle callbacks for success, error, settled, items change, etc.\n * - All stateful properties (active items, pending items, counts, etc.) are exposed as Solid signals for reactivity\n *\n * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,\n * the next pending task is processed if the concurrency limit allows.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and queuer 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 AsyncQueuer 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 `queuer.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `activeItems`: Array of items currently being processed\n * - `errorCount`: Number of items that failed processing\n * - `isRunning`: Whether the queuer is currently running (not stopped)\n * - `pendingItems`: Array of items waiting to be processed\n * - `rejectionCount`: Number of items that were rejected (expired or failed validation)\n * - `settleCount`: Number of items that have completed processing (successful or failed)\n * - `successCount`: Number of items that were processed successfully\n *\n * ## Unmount behavior\n *\n * By default, the primitive stops the queuer and aborts any in-flight task executions when the owning 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 items instead:\n *\n * ```tsx\n * const queuer = createAsyncQueuer(fn, {\n * concurrency: 2,\n * started: false,\n * onUnmount: (q) => q.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your task function updates Solid signals, those updates may run after the component has\n * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when\n * using onUnmount with flush.\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncQueuer = createAsyncQueuer(async (item) => {\n * // process item\n * return await fetchData(item);\n * }, {\n * initialItems: [],\n * concurrency: 2,\n * maxSize: 100,\n * started: false,\n * onSuccess: (result) => {\n * console.log('Item processed:', result);\n * },\n * onError: (error) => {\n * console.error('Processing failed:', error);\n * }\n * });\n *\n * // Opt-in to track queue state changes (optimized for UI updates)\n * const asyncQueuer = createAsyncQueuer(\n * async (item) => await fetchData(item),\n * { concurrency: 2, started: true },\n * (state) => ({\n * pendingItems: state.pendingItems,\n * activeItems: state.activeItems,\n * isRunning: state.isRunning\n * })\n * );\n *\n * // Opt-in to track processing metrics changes (optimized for tracking progress)\n * const asyncQueuer = createAsyncQueuer(\n * async (item) => await fetchData(item),\n * { concurrency: 2, started: true },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settleCount: state.settleCount\n * })\n * );\n *\n * // Add items to queue\n * asyncQueuer.addItem(newItem);\n *\n * // Start processing\n * asyncQueuer.start();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { pendingItems, activeItems } = asyncQueuer.state();\n * ```\n */\nexport function createAsyncQueuer<TValue, TSelected = {}>(\n fn: (value: TValue) => Promise<any>,\n options: SolidAsyncQueuerOptions<TValue, TSelected> = {},\n selector: (state: AsyncQueuerState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncQueuer<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncQueuer,\n ...options,\n } as SolidAsyncQueuerOptions<TValue, TSelected>\n const asyncQueuer = new AsyncQueuer<TValue>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncQueuer<TValue, TSelected>\n\n asyncQueuer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncQueuerState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncQueuer.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncQueuer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncQueuer)\n } else {\n asyncQueuer.stop()\n asyncQueuer.abort()\n }\n })\n })\n\n return {\n ...asyncQueuer,\n state,\n } as SolidAsyncQueuer<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoLA,SAAgB,kBACd,IACA,UAAsD,EAAE,EACxD,kBACG,EAAE,GACgC;CACrC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,cAAc,IAAI,YACtB,IACA,cACD;AAED,aAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,WAAW,SAAS,YAAY,OAAO,MAAM,SAAS;AAE5D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,SAAS,YAAY,OAAO,SAAS;AAEnD,oBAAmB;AACjB,kBAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,YAAY;QAC/B;AACL,gBAAY,MAAM;AAClB,gBAAY,OAAO;;IAErB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
@@ -1,3 +1,4 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1
2
  const require_createAsyncQueuer = require('./createAsyncQueuer.cjs');
2
3
 
3
4
  exports.createAsyncQueuer = require_createAsyncQueuer.createAsyncQueuer;
@@ -1,3 +1,3 @@
1
- import { SolidAsyncQueuer, createAsyncQueuer } from "./createAsyncQueuer.cjs";
1
+ import { SolidAsyncQueuer, SolidAsyncQueuerOptions, createAsyncQueuer } from "./createAsyncQueuer.cjs";
2
2
  export * from "@tanstack/pacer/async-queuer";
3
- export { SolidAsyncQueuer, createAsyncQueuer };
3
+ export { SolidAsyncQueuer, SolidAsyncQueuerOptions, createAsyncQueuer };
@@ -1,3 +1,3 @@
1
- import { SolidAsyncQueuer, createAsyncQueuer } from "./createAsyncQueuer.js";
1
+ import { SolidAsyncQueuer, SolidAsyncQueuerOptions, createAsyncQueuer } from "./createAsyncQueuer.js";
2
2
  export * from "@tanstack/pacer/async-queuer";
3
- export { SolidAsyncQueuer, createAsyncQueuer };
3
+ export { SolidAsyncQueuer, SolidAsyncQueuerOptions, createAsyncQueuer };
@@ -1,4 +1,5 @@
1
1
  const require_PacerProvider = require('../provider/PacerProvider.cjs');
2
+ let solid_js = require("solid-js");
2
3
  let _tanstack_solid_store = require("@tanstack/solid-store");
3
4
  let _tanstack_pacer_async_rate_limiter = require("@tanstack/pacer/async-rate-limiter");
4
5
 
@@ -70,6 +71,12 @@ let _tanstack_pacer_async_rate_limiter = require("@tanstack/pacer/async-rate-lim
70
71
  * - `rejectionCount`: Number of function calls that were rejected due to rate limiting
71
72
  * - `remainingInWindow`: Number of executions remaining in the current window
72
73
  *
74
+ * ## Unmount behavior
75
+ *
76
+ * By default, the primitive aborts any in-flight execution when the owning component unmounts.
77
+ * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
78
+ * Use the `onUnmount` option to customize this.
79
+ *
73
80
  * @example
74
81
  * ```tsx
75
82
  * // Default behavior - no reactive state subscriptions
@@ -159,15 +166,22 @@ let _tanstack_pacer_async_rate_limiter = require("@tanstack/pacer/async-rate-lim
159
166
  * ```
160
167
  */
161
168
  function createAsyncRateLimiter(fn, options, selector = () => ({})) {
162
- const asyncRateLimiter = new _tanstack_pacer_async_rate_limiter.AsyncRateLimiter(fn, {
169
+ const mergedOptions = {
163
170
  ...require_PacerProvider.useDefaultPacerOptions().asyncRateLimiter,
164
171
  ...options
165
- });
172
+ };
173
+ const asyncRateLimiter = new _tanstack_pacer_async_rate_limiter.AsyncRateLimiter(fn, mergedOptions);
166
174
  asyncRateLimiter.Subscribe = function Subscribe(props) {
167
175
  const selected = (0, _tanstack_solid_store.useStore)(asyncRateLimiter.store, props.selector);
168
176
  return typeof props.children === "function" ? props.children(selected) : props.children;
169
177
  };
170
178
  const state = (0, _tanstack_solid_store.useStore)(asyncRateLimiter.store, selector);
179
+ (0, solid_js.createEffect)(() => {
180
+ (0, solid_js.onCleanup)(() => {
181
+ if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncRateLimiter);
182
+ else asyncRateLimiter.abort();
183
+ });
184
+ });
171
185
  return {
172
186
  ...asyncRateLimiter,
173
187
  state
@@ -1 +1 @@
1
- {"version":3,"file":"createAsyncRateLimiter.cjs","names":["AsyncRateLimiter","useDefaultPacerOptions"],"sources":["../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { useStore } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\n\nexport interface SolidAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the rate limiter state.\n *\n * This is useful for tracking 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, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Rejected: {state().rejectionCount}, {state().isExecuting ? 'Executing' : 'Idle'}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Accessor<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 Solid 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 (createSignal, etc).\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\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 * 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 * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\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` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `currentWindowStart`: Timestamp when the current window started\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastResult`: The result from the most recent successful execution\n * - `nextWindowTime`: Timestamp when the next window begins\n * - `rejectionCount`: Number of function calls that were rejected due to rate limiting\n * - `remainingInWindow`: Number of executions remaining in the current window\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncRateLimiter = createAsyncRateLimiter(\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 component\n * <asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Rejected: {state().rejectionCount}, {state().isExecuting ? 'Executing' : 'Idle'}</div>\n * )}\n * </asyncRateLimiter.Subscribe>\n *\n * // Opt-in to track execution state changes at hook level (optimized for loading indicators)\n * const asyncRateLimiter = createAsyncRateLimiter(\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 track results when available (optimized for data display)\n * const asyncRateLimiter = createAsyncRateLimiter(\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 track error/rejection state changes (optimized for error handling)\n * const asyncRateLimiter = createAsyncRateLimiter(\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 track execution metrics changes (optimized for stats display)\n * const asyncRateLimiter = createAsyncRateLimiter(\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 track execution times changes (optimized for window calculations)\n * const asyncRateLimiter = createAsyncRateLimiter(\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 * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult, rejectionCount } = asyncRateLimiter.state();\n * ```\n */\nexport function createAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: AsyncRateLimiterOptions<TFn>,\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncRateLimiter,\n ...options,\n } as AsyncRateLimiterOptions<TFn>\n\n const asyncRateLimiter = new AsyncRateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncRateLimiter<TFn, TSelected>\n\n asyncRateLimiter.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncRateLimiter.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncRateLimiter.store, selector)\n\n return {\n ...asyncRateLimiter,\n state,\n } as SolidAsyncRateLimiter<TFn, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyMA,SAAgB,uBAId,IACA,SACA,kBACG,EAAE,GACkC;CAMvC,MAAM,mBAAmB,IAAIA,oDAC3B,IANoB;EACpB,GAAGC,8CAAwB,CAAC;EAC5B,GAAG;EACJ,CAKA;AAED,kBAAiB,YAAY,SAAS,UAAqB,OAGxD;EACD,MAAM,+CAAoB,iBAAiB,OAAO,MAAM,SAAS;AAEjE,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,4CAAiB,iBAAiB,OAAO,SAAS;AAExD,QAAO;EACL,GAAG;EACH;EACD"}
1
+ {"version":3,"file":"createAsyncRateLimiter.cjs","names":["useDefaultPacerOptions","AsyncRateLimiter"],"sources":["../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useStore } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\n\nexport interface SolidAsyncRateLimiterOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncRateLimiterOptions<TFn> {\n /**\n * Optional callback invoked when the owning 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: SolidAsyncRateLimiter<TFn, TSelected>) => void\n}\n\nexport interface SolidAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the rate limiter state.\n *\n * This is useful for tracking 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, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Rejected: {state().rejectionCount}, {state().isExecuting ? 'Executing' : 'Idle'}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Accessor<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 Solid 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 (createSignal, etc).\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\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 * 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 * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\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` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `currentWindowStart`: Timestamp when the current window started\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastResult`: The result from the most recent successful execution\n * - `nextWindowTime`: Timestamp when the next window begins\n * - `rejectionCount`: Number of function calls that were rejected due to rate limiting\n * - `remainingInWindow`: Number of executions remaining in the current window\n *\n * ## Unmount behavior\n *\n * By default, the primitive aborts any in-flight execution when the owning 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 = createAsyncRateLimiter(\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 component\n * <asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Rejected: {state().rejectionCount}, {state().isExecuting ? 'Executing' : 'Idle'}</div>\n * )}\n * </asyncRateLimiter.Subscribe>\n *\n * // Opt-in to track execution state changes at hook level (optimized for loading indicators)\n * const asyncRateLimiter = createAsyncRateLimiter(\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 track results when available (optimized for data display)\n * const asyncRateLimiter = createAsyncRateLimiter(\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 track error/rejection state changes (optimized for error handling)\n * const asyncRateLimiter = createAsyncRateLimiter(\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 track execution metrics changes (optimized for stats display)\n * const asyncRateLimiter = createAsyncRateLimiter(\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 track execution times changes (optimized for window calculations)\n * const asyncRateLimiter = createAsyncRateLimiter(\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 * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult, rejectionCount } = asyncRateLimiter.state();\n * ```\n */\nexport function createAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: SolidAsyncRateLimiterOptions<TFn, TSelected>,\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncRateLimiter,\n ...options,\n } as SolidAsyncRateLimiterOptions<TFn, TSelected>\n const asyncRateLimiter = new AsyncRateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncRateLimiter<TFn, TSelected>\n\n asyncRateLimiter.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncRateLimiter.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncRateLimiter.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncRateLimiter)\n } else {\n asyncRateLimiter.abort()\n }\n })\n })\n\n return {\n ...asyncRateLimiter,\n state,\n } as SolidAsyncRateLimiter<TFn, TSelected>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2NA,SAAgB,uBAId,IACA,SACA,kBACG,EAAE,GACkC;CACvC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,mBAAmB,IAAIC,oDAC3B,IACA,cACD;AAED,kBAAiB,YAAY,SAAS,UAAqB,OAGxD;EACD,MAAM,+CAAoB,iBAAiB,OAAO,MAAM,SAAS;AAEjE,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,4CAAiB,iBAAiB,OAAO,SAAS;AAExD,kCAAmB;AACjB,gCAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,iBAAiB;OAEzC,kBAAiB,OAAO;IAE1B;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
@@ -4,6 +4,13 @@ import { AnyAsyncFunction } from "@tanstack/pacer/types";
4
4
  import { AsyncRateLimiter, AsyncRateLimiterOptions, AsyncRateLimiterState } from "@tanstack/pacer/async-rate-limiter";
5
5
 
6
6
  //#region src/async-rate-limiter/createAsyncRateLimiter.d.ts
7
+ interface SolidAsyncRateLimiterOptions<TFn extends AnyAsyncFunction, TSelected = {}> extends AsyncRateLimiterOptions<TFn> {
8
+ /**
9
+ * Optional callback invoked when the owning component unmounts. Receives the rate limiter instance.
10
+ * When provided, replaces the default cleanup (abort); use it to call reset(), add logging, etc.
11
+ */
12
+ onUnmount?: (rateLimiter: SolidAsyncRateLimiter<TFn, TSelected>) => void;
13
+ }
7
14
  interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncRateLimiter<TFn>, 'store'> {
8
15
  /**
9
16
  * A Solid component that allows you to subscribe to the rate limiter state.
@@ -102,6 +109,12 @@ interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}> ex
102
109
  * - `rejectionCount`: Number of function calls that were rejected due to rate limiting
103
110
  * - `remainingInWindow`: Number of executions remaining in the current window
104
111
  *
112
+ * ## Unmount behavior
113
+ *
114
+ * By default, the primitive aborts any in-flight execution when the owning component unmounts.
115
+ * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
116
+ * Use the `onUnmount` option to customize this.
117
+ *
105
118
  * @example
106
119
  * ```tsx
107
120
  * // Default behavior - no reactive state subscriptions
@@ -190,7 +203,7 @@ interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}> ex
190
203
  * const { isExecuting, lastResult, rejectionCount } = asyncRateLimiter.state();
191
204
  * ```
192
205
  */
193
- declare function createAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: AsyncRateLimiterOptions<TFn>, selector?: (state: AsyncRateLimiterState<TFn>) => TSelected): SolidAsyncRateLimiter<TFn, TSelected>;
206
+ declare function createAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: SolidAsyncRateLimiterOptions<TFn, TSelected>, selector?: (state: AsyncRateLimiterState<TFn>) => TSelected): SolidAsyncRateLimiter<TFn, TSelected>;
194
207
  //#endregion
195
- export { SolidAsyncRateLimiter, createAsyncRateLimiter };
208
+ export { SolidAsyncRateLimiter, SolidAsyncRateLimiterOptions, createAsyncRateLimiter };
196
209
  //# sourceMappingURL=createAsyncRateLimiter.d.cts.map
@@ -4,6 +4,13 @@ import { AsyncRateLimiter, AsyncRateLimiterOptions, AsyncRateLimiterState } from
4
4
  import { AnyAsyncFunction } from "@tanstack/pacer/types";
5
5
 
6
6
  //#region src/async-rate-limiter/createAsyncRateLimiter.d.ts
7
+ interface SolidAsyncRateLimiterOptions<TFn extends AnyAsyncFunction, TSelected = {}> extends AsyncRateLimiterOptions<TFn> {
8
+ /**
9
+ * Optional callback invoked when the owning component unmounts. Receives the rate limiter instance.
10
+ * When provided, replaces the default cleanup (abort); use it to call reset(), add logging, etc.
11
+ */
12
+ onUnmount?: (rateLimiter: SolidAsyncRateLimiter<TFn, TSelected>) => void;
13
+ }
7
14
  interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncRateLimiter<TFn>, 'store'> {
8
15
  /**
9
16
  * A Solid component that allows you to subscribe to the rate limiter state.
@@ -102,6 +109,12 @@ interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}> ex
102
109
  * - `rejectionCount`: Number of function calls that were rejected due to rate limiting
103
110
  * - `remainingInWindow`: Number of executions remaining in the current window
104
111
  *
112
+ * ## Unmount behavior
113
+ *
114
+ * By default, the primitive aborts any in-flight execution when the owning component unmounts.
115
+ * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
116
+ * Use the `onUnmount` option to customize this.
117
+ *
105
118
  * @example
106
119
  * ```tsx
107
120
  * // Default behavior - no reactive state subscriptions
@@ -190,7 +203,7 @@ interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}> ex
190
203
  * const { isExecuting, lastResult, rejectionCount } = asyncRateLimiter.state();
191
204
  * ```
192
205
  */
193
- declare function createAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: AsyncRateLimiterOptions<TFn>, selector?: (state: AsyncRateLimiterState<TFn>) => TSelected): SolidAsyncRateLimiter<TFn, TSelected>;
206
+ declare function createAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: SolidAsyncRateLimiterOptions<TFn, TSelected>, selector?: (state: AsyncRateLimiterState<TFn>) => TSelected): SolidAsyncRateLimiter<TFn, TSelected>;
194
207
  //#endregion
195
- export { SolidAsyncRateLimiter, createAsyncRateLimiter };
208
+ export { SolidAsyncRateLimiter, SolidAsyncRateLimiterOptions, createAsyncRateLimiter };
196
209
  //# sourceMappingURL=createAsyncRateLimiter.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
2
+ import { createEffect, onCleanup } from "solid-js";
2
3
  import { useStore } from "@tanstack/solid-store";
3
4
  import { AsyncRateLimiter } from "@tanstack/pacer/async-rate-limiter";
4
5
 
@@ -70,6 +71,12 @@ import { AsyncRateLimiter } from "@tanstack/pacer/async-rate-limiter";
70
71
  * - `rejectionCount`: Number of function calls that were rejected due to rate limiting
71
72
  * - `remainingInWindow`: Number of executions remaining in the current window
72
73
  *
74
+ * ## Unmount behavior
75
+ *
76
+ * By default, the primitive aborts any in-flight execution when the owning component unmounts.
77
+ * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
78
+ * Use the `onUnmount` option to customize this.
79
+ *
73
80
  * @example
74
81
  * ```tsx
75
82
  * // Default behavior - no reactive state subscriptions
@@ -159,15 +166,22 @@ import { AsyncRateLimiter } from "@tanstack/pacer/async-rate-limiter";
159
166
  * ```
160
167
  */
161
168
  function createAsyncRateLimiter(fn, options, selector = () => ({})) {
162
- const asyncRateLimiter = new AsyncRateLimiter(fn, {
169
+ const mergedOptions = {
163
170
  ...useDefaultPacerOptions().asyncRateLimiter,
164
171
  ...options
165
- });
172
+ };
173
+ const asyncRateLimiter = new AsyncRateLimiter(fn, mergedOptions);
166
174
  asyncRateLimiter.Subscribe = function Subscribe(props) {
167
175
  const selected = useStore(asyncRateLimiter.store, props.selector);
168
176
  return typeof props.children === "function" ? props.children(selected) : props.children;
169
177
  };
170
178
  const state = useStore(asyncRateLimiter.store, selector);
179
+ createEffect(() => {
180
+ onCleanup(() => {
181
+ if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncRateLimiter);
182
+ else asyncRateLimiter.abort();
183
+ });
184
+ });
171
185
  return {
172
186
  ...asyncRateLimiter,
173
187
  state