@tanstack/solid-pacer 0.21.1 → 0.23.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 (170) hide show
  1. package/README.md +21 -6
  2. package/dist/async-batcher/createAsyncBatcher.d.ts +5 -10
  3. package/dist/async-batcher/createAsyncBatcher.js +2 -5
  4. package/dist/async-debouncer/createAsyncDebouncer.d.ts +8 -12
  5. package/dist/async-debouncer/createAsyncDebouncer.js +5 -7
  6. package/dist/async-queuer/createAsyncQueuer.d.ts +9 -12
  7. package/dist/async-queuer/createAsyncQueuer.js +4 -5
  8. package/dist/async-rate-limiter/createAsyncRateLimiter.d.ts +10 -13
  9. package/dist/async-rate-limiter/createAsyncRateLimiter.js +7 -8
  10. package/dist/async-throttler/createAsyncThrottler.d.ts +8 -14
  11. package/dist/async-throttler/createAsyncThrottler.js +5 -9
  12. package/dist/batcher/createBatcher.d.ts +11 -15
  13. package/dist/batcher/createBatcher.js +6 -8
  14. package/dist/debouncer/createDebouncedSignal.d.ts +2 -5
  15. package/dist/debouncer/createDebouncedSignal.js +1 -2
  16. package/dist/debouncer/createDebouncedValue.d.ts +2 -5
  17. package/dist/debouncer/createDebouncedValue.js +1 -2
  18. package/dist/debouncer/createDebouncer.d.ts +4 -7
  19. package/dist/debouncer/createDebouncer.js +1 -2
  20. package/dist/provider/PacerProvider.d.ts +6 -9
  21. package/dist/provider/PacerProvider.js +1 -2
  22. package/dist/queuer/createQueuedSignal.d.ts +2 -5
  23. package/dist/queuer/createQueuedSignal.js +1 -2
  24. package/dist/queuer/createQueuer.d.ts +4 -7
  25. package/dist/queuer/createQueuer.js +1 -2
  26. package/dist/rate-limiter/createRateLimitedSignal.d.ts +12 -14
  27. package/dist/rate-limiter/createRateLimitedSignal.js +11 -11
  28. package/dist/rate-limiter/createRateLimitedValue.d.ts +2 -5
  29. package/dist/rate-limiter/createRateLimitedValue.js +1 -2
  30. package/dist/rate-limiter/createRateLimiter.d.ts +8 -10
  31. package/dist/rate-limiter/createRateLimiter.js +5 -5
  32. package/dist/throttler/createThrottledSignal.d.ts +2 -7
  33. package/dist/throttler/createThrottledSignal.js +1 -4
  34. package/dist/throttler/createThrottledValue.d.ts +2 -7
  35. package/dist/throttler/createThrottledValue.js +1 -4
  36. package/dist/throttler/createThrottler.d.ts +4 -9
  37. package/dist/throttler/createThrottler.js +1 -4
  38. package/package.json +24 -68
  39. package/dist/async-batcher/createAsyncBatcher.cjs +0 -166
  40. package/dist/async-batcher/createAsyncBatcher.cjs.map +0 -1
  41. package/dist/async-batcher/createAsyncBatcher.d.cts +0 -178
  42. package/dist/async-batcher/createAsyncBatcher.js.map +0 -1
  43. package/dist/async-batcher/index.cjs +0 -11
  44. package/dist/async-batcher/index.d.cts +0 -3
  45. package/dist/async-debouncer/createAsyncDebouncer.cjs +0 -151
  46. package/dist/async-debouncer/createAsyncDebouncer.cjs.map +0 -1
  47. package/dist/async-debouncer/createAsyncDebouncer.d.cts +0 -164
  48. package/dist/async-debouncer/createAsyncDebouncer.js.map +0 -1
  49. package/dist/async-debouncer/index.cjs +0 -11
  50. package/dist/async-debouncer/index.d.cts +0 -3
  51. package/dist/async-queuer/createAsyncQueuer.cjs +0 -158
  52. package/dist/async-queuer/createAsyncQueuer.cjs.map +0 -1
  53. package/dist/async-queuer/createAsyncQueuer.d.cts +0 -170
  54. package/dist/async-queuer/createAsyncQueuer.js.map +0 -1
  55. package/dist/async-queuer/index.cjs +0 -11
  56. package/dist/async-queuer/index.d.cts +0 -3
  57. package/dist/async-rate-limiter/createAsyncRateLimiter.cjs +0 -193
  58. package/dist/async-rate-limiter/createAsyncRateLimiter.cjs.map +0 -1
  59. package/dist/async-rate-limiter/createAsyncRateLimiter.d.cts +0 -209
  60. package/dist/async-rate-limiter/createAsyncRateLimiter.js.map +0 -1
  61. package/dist/async-rate-limiter/index.cjs +0 -11
  62. package/dist/async-rate-limiter/index.d.cts +0 -3
  63. package/dist/async-throttler/createAsyncThrottler.cjs +0 -151
  64. package/dist/async-throttler/createAsyncThrottler.cjs.map +0 -1
  65. package/dist/async-throttler/createAsyncThrottler.d.cts +0 -164
  66. package/dist/async-throttler/createAsyncThrottler.js.map +0 -1
  67. package/dist/async-throttler/index.cjs +0 -11
  68. package/dist/async-throttler/index.d.cts +0 -3
  69. package/dist/batcher/createBatcher.cjs +0 -132
  70. package/dist/batcher/createBatcher.cjs.map +0 -1
  71. package/dist/batcher/createBatcher.d.cts +0 -147
  72. package/dist/batcher/createBatcher.js.map +0 -1
  73. package/dist/batcher/index.cjs +0 -11
  74. package/dist/batcher/index.d.cts +0 -3
  75. package/dist/debouncer/createDebouncedSignal.cjs +0 -88
  76. package/dist/debouncer/createDebouncedSignal.cjs.map +0 -1
  77. package/dist/debouncer/createDebouncedSignal.d.cts +0 -80
  78. package/dist/debouncer/createDebouncedSignal.js.map +0 -1
  79. package/dist/debouncer/createDebouncedValue.cjs +0 -77
  80. package/dist/debouncer/createDebouncedValue.cjs.map +0 -1
  81. package/dist/debouncer/createDebouncedValue.d.cts +0 -71
  82. package/dist/debouncer/createDebouncedValue.js.map +0 -1
  83. package/dist/debouncer/createDebouncer.cjs +0 -129
  84. package/dist/debouncer/createDebouncer.cjs.map +0 -1
  85. package/dist/debouncer/createDebouncer.d.cts +0 -145
  86. package/dist/debouncer/createDebouncer.js.map +0 -1
  87. package/dist/debouncer/index.cjs +0 -15
  88. package/dist/debouncer/index.d.cts +0 -5
  89. package/dist/index.cjs +0 -47
  90. package/dist/index.d.cts +0 -20
  91. package/dist/provider/PacerProvider.cjs +0 -27
  92. package/dist/provider/PacerProvider.cjs.map +0 -1
  93. package/dist/provider/PacerProvider.d.cts +0 -29
  94. package/dist/provider/PacerProvider.js.map +0 -1
  95. package/dist/provider/index.cjs +0 -6
  96. package/dist/provider/index.d.cts +0 -2
  97. package/dist/queuer/createQueuedSignal.cjs +0 -129
  98. package/dist/queuer/createQueuedSignal.cjs.map +0 -1
  99. package/dist/queuer/createQueuedSignal.d.cts +0 -122
  100. package/dist/queuer/createQueuedSignal.js.map +0 -1
  101. package/dist/queuer/createQueuer.cjs +0 -133
  102. package/dist/queuer/createQueuer.cjs.map +0 -1
  103. package/dist/queuer/createQueuer.d.cts +0 -148
  104. package/dist/queuer/createQueuer.js.map +0 -1
  105. package/dist/queuer/index.cjs +0 -13
  106. package/dist/queuer/index.d.cts +0 -4
  107. package/dist/rate-limiter/createRateLimitedSignal.cjs +0 -102
  108. package/dist/rate-limiter/createRateLimitedSignal.cjs.map +0 -1
  109. package/dist/rate-limiter/createRateLimitedSignal.d.cts +0 -94
  110. package/dist/rate-limiter/createRateLimitedSignal.js.map +0 -1
  111. package/dist/rate-limiter/createRateLimitedValue.cjs +0 -102
  112. package/dist/rate-limiter/createRateLimitedValue.cjs.map +0 -1
  113. package/dist/rate-limiter/createRateLimitedValue.d.cts +0 -96
  114. package/dist/rate-limiter/createRateLimitedValue.js.map +0 -1
  115. package/dist/rate-limiter/createRateLimiter.cjs +0 -157
  116. package/dist/rate-limiter/createRateLimiter.cjs.map +0 -1
  117. package/dist/rate-limiter/createRateLimiter.d.cts +0 -174
  118. package/dist/rate-limiter/createRateLimiter.js.map +0 -1
  119. package/dist/rate-limiter/index.cjs +0 -15
  120. package/dist/rate-limiter/index.d.cts +0 -5
  121. package/dist/throttler/createThrottledSignal.cjs +0 -79
  122. package/dist/throttler/createThrottledSignal.cjs.map +0 -1
  123. package/dist/throttler/createThrottledSignal.d.cts +0 -71
  124. package/dist/throttler/createThrottledSignal.js.map +0 -1
  125. package/dist/throttler/createThrottledValue.cjs +0 -74
  126. package/dist/throttler/createThrottledValue.cjs.map +0 -1
  127. package/dist/throttler/createThrottledValue.d.cts +0 -68
  128. package/dist/throttler/createThrottledValue.js.map +0 -1
  129. package/dist/throttler/createThrottler.cjs +0 -132
  130. package/dist/throttler/createThrottler.cjs.map +0 -1
  131. package/dist/throttler/createThrottler.d.cts +0 -148
  132. package/dist/throttler/createThrottler.js.map +0 -1
  133. package/dist/throttler/index.cjs +0 -15
  134. package/dist/throttler/index.d.cts +0 -5
  135. package/dist/types/index.cjs +0 -9
  136. package/dist/types/index.d.cts +0 -1
  137. package/dist/utils/index.cjs +0 -9
  138. package/dist/utils/index.d.cts +0 -1
  139. package/src/async-batcher/createAsyncBatcher.ts +0 -234
  140. package/src/async-batcher/index.ts +0 -3
  141. package/src/async-debouncer/createAsyncDebouncer.ts +0 -225
  142. package/src/async-debouncer/index.ts +0 -4
  143. package/src/async-queuer/createAsyncQueuer.ts +0 -226
  144. package/src/async-queuer/index.ts +0 -3
  145. package/src/async-rate-limiter/createAsyncRateLimiter.ts +0 -269
  146. package/src/async-rate-limiter/index.ts +0 -4
  147. package/src/async-throttler/createAsyncThrottler.ts +0 -225
  148. package/src/async-throttler/index.ts +0 -4
  149. package/src/batcher/createBatcher.ts +0 -199
  150. package/src/batcher/index.ts +0 -3
  151. package/src/debouncer/createDebouncedSignal.ts +0 -92
  152. package/src/debouncer/createDebouncedValue.ts +0 -85
  153. package/src/debouncer/createDebouncer.ts +0 -201
  154. package/src/debouncer/index.ts +0 -6
  155. package/src/index.ts +0 -46
  156. package/src/provider/PacerProvider.tsx +0 -63
  157. package/src/provider/index.ts +0 -1
  158. package/src/queuer/createQueuedSignal.ts +0 -138
  159. package/src/queuer/createQueuer.ts +0 -199
  160. package/src/queuer/index.ts +0 -4
  161. package/src/rate-limiter/createRateLimitedSignal.ts +0 -117
  162. package/src/rate-limiter/createRateLimitedValue.ts +0 -110
  163. package/src/rate-limiter/createRateLimiter.ts +0 -226
  164. package/src/rate-limiter/index.ts +0 -5
  165. package/src/throttler/createThrottledSignal.ts +0 -81
  166. package/src/throttler/createThrottledValue.ts +0 -82
  167. package/src/throttler/createThrottler.ts +0 -204
  168. package/src/throttler/index.ts +0 -6
  169. package/src/types/index.ts +0 -1
  170. package/src/utils/index.ts +0 -1
@@ -1,170 +0,0 @@
1
- import { Store } from "@tanstack/solid-store";
2
- import { Accessor, JSX } from "solid-js";
3
- import { AsyncQueuer, AsyncQueuerOptions, AsyncQueuerState } from "@tanstack/pacer/async-queuer";
4
-
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
- }
13
- interface SolidAsyncQueuer<TValue, TSelected = {}> extends Omit<AsyncQueuer<TValue>, 'store'> {
14
- /**
15
- * A Solid component that allows you to subscribe to the queuer state.
16
- *
17
- * This is useful for tracking specific parts of the queuer state
18
- * deep in your component tree without needing to pass a selector to the hook.
19
- *
20
- * @example
21
- * <queuer.Subscribe selector={(state) => ({ pendingItems: state.pendingItems, activeItems: state.activeItems })}>
22
- * {(state) => (
23
- * <div>Pending: {state().pendingItems.length}, Active: {state().activeItems.length}</div>
24
- * )}
25
- * </queuer.Subscribe>
26
- */
27
- Subscribe: <TSelected>(props: {
28
- selector: (state: AsyncQueuerState<TValue>) => TSelected;
29
- children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element;
30
- }) => JSX.Element;
31
- /**
32
- * Reactive state that will be updated when the queuer state changes
33
- *
34
- * Use this instead of `queuer.store.state`
35
- */
36
- readonly state: Accessor<Readonly<TSelected>>;
37
- /**
38
- * @deprecated Use `queuer.state` instead of `queuer.store.state` if you want to read reactive state.
39
- * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
40
- * Although, you can make the state reactive by using the `useSelector` in your own usage.
41
- */
42
- readonly store: Store<Readonly<AsyncQueuerState<TValue>>>;
43
- }
44
- /**
45
- * Creates a Solid-compatible AsyncQueuer instance for managing an asynchronous queue of items, exposing Solid signals for all stateful properties.
46
- *
47
- * Features:
48
- * - Priority queueing via `getPriority` or item `priority` property
49
- * - Configurable concurrency limit
50
- * - FIFO (First In First Out) or LIFO (Last In First Out) queue behavior
51
- * - Pause/resume processing
52
- * - Task cancellation
53
- * - Item expiration
54
- * - Lifecycle callbacks for success, error, settled, items change, etc.
55
- * - All stateful properties (active items, pending items, counts, etc.) are exposed as Solid signals for reactivity
56
- *
57
- * Tasks are processed concurrently up to the configured concurrency limit. When a task completes,
58
- * the next pending task is processed if the concurrency limit allows.
59
- *
60
- * Error Handling:
61
- * - If an `onError` handler is provided, it will be called with the error and queuer instance
62
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
63
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
64
- * - Both onError and throwOnError can be used together; the handler will be called before any error is thrown
65
- * - The error state can be checked using the underlying AsyncQueuer instance
66
- *
67
- * ## State Management and Selector
68
- *
69
- * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
70
- * in two ways:
71
- *
72
- * **1. Using `queuer.Subscribe` component (Recommended for component tree subscriptions)**
73
- *
74
- * Use the `Subscribe` component to subscribe to state changes deep in your component tree without
75
- * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
76
- * in child components.
77
- *
78
- * **2. Using the `selector` parameter (For hook-level subscriptions)**
79
- *
80
- * The `selector` parameter allows you to specify which state changes will trigger reactive updates
81
- * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant
82
- * state changes occur.
83
- *
84
- * **By default, there will be no reactive state subscriptions** and you must opt-in to state
85
- * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary
86
- * updates and gives you full control over when your component tracks state changes.
87
- *
88
- * Available state properties:
89
- * - `activeItems`: Array of items currently being processed
90
- * - `errorCount`: Number of items that failed processing
91
- * - `isRunning`: Whether the queuer is currently running (not stopped)
92
- * - `pendingItems`: Array of items waiting to be processed
93
- * - `rejectionCount`: Number of items that were rejected (expired or failed validation)
94
- * - `settleCount`: Number of items that have completed processing (successful or failed)
95
- * - `successCount`: Number of items that were processed successfully
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
- *
116
- * Example usage:
117
- * ```tsx
118
- * // Default behavior - no reactive state subscriptions
119
- * const asyncQueuer = createAsyncQueuer(async (item) => {
120
- * // process item
121
- * return await fetchData(item);
122
- * }, {
123
- * initialItems: [],
124
- * concurrency: 2,
125
- * maxSize: 100,
126
- * started: false,
127
- * onSuccess: (result) => {
128
- * console.log('Item processed:', result);
129
- * },
130
- * onError: (error) => {
131
- * console.error('Processing failed:', error);
132
- * }
133
- * });
134
- *
135
- * // Opt-in to track queue state changes (optimized for UI updates)
136
- * const asyncQueuer = createAsyncQueuer(
137
- * async (item) => await fetchData(item),
138
- * { concurrency: 2, started: true },
139
- * (state) => ({
140
- * pendingItems: state.pendingItems,
141
- * activeItems: state.activeItems,
142
- * isRunning: state.isRunning
143
- * })
144
- * );
145
- *
146
- * // Opt-in to track processing metrics changes (optimized for tracking progress)
147
- * const asyncQueuer = createAsyncQueuer(
148
- * async (item) => await fetchData(item),
149
- * { concurrency: 2, started: true },
150
- * (state) => ({
151
- * successCount: state.successCount,
152
- * errorCount: state.errorCount,
153
- * settleCount: state.settleCount
154
- * })
155
- * );
156
- *
157
- * // Add items to queue
158
- * asyncQueuer.addItem(newItem);
159
- *
160
- * // Start processing
161
- * asyncQueuer.start();
162
- *
163
- * // Access the selected state (will be empty object {} unless selector provided)
164
- * const { pendingItems, activeItems } = asyncQueuer.state();
165
- * ```
166
- */
167
- declare function createAsyncQueuer<TValue, TSelected = {}>(fn: (value: TValue) => Promise<any>, options?: SolidAsyncQueuerOptions<TValue, TSelected>, selector?: (state: AsyncQueuerState<TValue>) => TSelected): SolidAsyncQueuer<TValue, TSelected>;
168
- //#endregion
169
- export { SolidAsyncQueuer, SolidAsyncQueuerOptions, createAsyncQueuer };
170
- //# sourceMappingURL=createAsyncQueuer.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"createAsyncQueuer.js","names":[],"sources":["../../src/async-queuer/createAsyncQueuer.ts"],"sourcesContent":["import { AsyncQueuer } from '@tanstack/pacer/async-queuer'\nimport { shallow, useSelector } 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 `useSelector` hook internally.\n * Although, you can make the state reactive by using the `useSelector` in your own usage.\n */\n readonly store: Store<Readonly<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 = useSelector(asyncQueuer.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useSelector(asyncQueuer.store, selector, { compare: shallow })\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;CAED,YAAY,YAAY,SAAS,UAAqB,OAGnD;EACD,MAAM,WAAW,YAAY,YAAY,OAAO,MAAM,UAAU,EAC9D,SAAS,SACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,YAAY,YAAY,OAAO,UAAU,EAAE,SAAS,SAAS,CAAC;CAE5E,mBAAmB;EACjB,gBAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,YAAY;QAC/B;IACL,YAAY,MAAM;IAClB,YAAY,OAAO;;IAErB;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"}
@@ -1,11 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_createAsyncQueuer = require('./createAsyncQueuer.cjs');
3
-
4
- exports.createAsyncQueuer = require_createAsyncQueuer.createAsyncQueuer;
5
- var _tanstack_pacer_async_queuer = require("@tanstack/pacer/async-queuer");
6
- Object.keys(_tanstack_pacer_async_queuer).forEach(function (k) {
7
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
8
- enumerable: true,
9
- get: function () { return _tanstack_pacer_async_queuer[k]; }
10
- });
11
- });
@@ -1,3 +0,0 @@
1
- import { SolidAsyncQueuer, SolidAsyncQueuerOptions, createAsyncQueuer } from "./createAsyncQueuer.cjs";
2
- export * from "@tanstack/pacer/async-queuer";
3
- export { SolidAsyncQueuer, SolidAsyncQueuerOptions, createAsyncQueuer };
@@ -1,193 +0,0 @@
1
- const require_PacerProvider = require('../provider/PacerProvider.cjs');
2
- let solid_js = require("solid-js");
3
- let _tanstack_solid_store = require("@tanstack/solid-store");
4
- let _tanstack_pacer_async_rate_limiter = require("@tanstack/pacer/async-rate-limiter");
5
-
6
- //#region src/async-rate-limiter/createAsyncRateLimiter.ts
7
- /**
8
- * A low-level Solid hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.
9
- *
10
- * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that
11
- * you can integrate with any state management solution (createSignal, etc).
12
- *
13
- * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
14
- * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
15
- * all executions happen immediately, followed by a complete block.
16
- *
17
- * The rate limiter supports two types of windows:
18
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
19
- * towards the limit, and the window resets completely after the period.
20
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
21
- * consistent rate of execution over time.
22
- *
23
- * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,
24
- * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
25
- * instead of setting the result on a state variable from within the rate-limited function.
26
- *
27
- * For smoother execution patterns, consider using:
28
- * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
29
- * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
30
- *
31
- * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
32
- * smoothing out frequent events, throttling or debouncing usually provide better user experience.
33
- *
34
- * Error Handling:
35
- * - If an `onError` handler is provided, it will be called with the error and rate limiter instance
36
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
37
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
38
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
39
- * - The error state can be checked using the underlying AsyncRateLimiter instance
40
- * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler
41
- *
42
- * ## State Management and Selector
43
- *
44
- * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
45
- * in two ways:
46
- *
47
- * **1. Using `rateLimiter.Subscribe` component (Recommended for component tree subscriptions)**
48
- *
49
- * Use the `Subscribe` component to subscribe to state changes deep in your component tree without
50
- * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
51
- * in child components.
52
- *
53
- * **2. Using the `selector` parameter (For hook-level subscriptions)**
54
- *
55
- * The `selector` parameter allows you to specify which state changes will trigger reactive updates
56
- * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant
57
- * state changes occur.
58
- *
59
- * **By default, there will be no reactive state subscriptions** and you must opt-in to state
60
- * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary
61
- * updates and gives you full control over when your component tracks state changes.
62
- *
63
- * Available state properties:
64
- * - `currentWindowStart`: Timestamp when the current window started
65
- * - `executionCount`: Number of function executions that have been completed
66
- * - `hasError`: Whether the last execution resulted in an error
67
- * - `isExecuting`: Whether an async function execution is currently in progress
68
- * - `lastError`: The error from the most recent failed execution (if any)
69
- * - `lastResult`: The result from the most recent successful execution
70
- * - `nextWindowTime`: Timestamp when the next window begins
71
- * - `rejectionCount`: Number of function calls that were rejected due to rate limiting
72
- * - `remainingInWindow`: Number of executions remaining in the current window
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
- *
80
- * @example
81
- * ```tsx
82
- * // Default behavior - no reactive state subscriptions
83
- * const asyncRateLimiter = createAsyncRateLimiter(
84
- * async (id: string) => {
85
- * const data = await api.fetchData(id);
86
- * return data; // Return value is preserved
87
- * },
88
- * { limit: 5, window: 1000 } // 5 calls per second
89
- * );
90
- *
91
- * // Subscribe to state changes deep in component tree using Subscribe component
92
- * <asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount, isExecuting: state.isExecuting })}>
93
- * {(state) => (
94
- * <div>Rejected: {state().rejectionCount}, {state().isExecuting ? 'Executing' : 'Idle'}</div>
95
- * )}
96
- * </asyncRateLimiter.Subscribe>
97
- *
98
- * // Opt-in to track execution state changes at hook level (optimized for loading indicators)
99
- * const asyncRateLimiter = createAsyncRateLimiter(
100
- * async (id: string) => {
101
- * const data = await api.fetchData(id);
102
- * return data;
103
- * },
104
- * { limit: 5, window: 1000 },
105
- * (state) => ({ isExecuting: state.isExecuting })
106
- * );
107
- *
108
- * // Opt-in to track results when available (optimized for data display)
109
- * const asyncRateLimiter = createAsyncRateLimiter(
110
- * async (id: string) => {
111
- * const data = await api.fetchData(id);
112
- * return data;
113
- * },
114
- * { limit: 5, window: 1000 },
115
- * (state) => ({
116
- * lastResult: state.lastResult,
117
- * successCount: state.successCount
118
- * })
119
- * );
120
- *
121
- * // Opt-in to track error/rejection state changes (optimized for error handling)
122
- * const asyncRateLimiter = createAsyncRateLimiter(
123
- * async (id: string) => {
124
- * const data = await api.fetchData(id);
125
- * return data;
126
- * },
127
- * {
128
- * limit: 5,
129
- * window: 1000,
130
- * onError: (error) => console.error('API call failed:', error),
131
- * onReject: (rateLimiter) => console.log('Rate limit exceeded')
132
- * },
133
- * (state) => ({
134
- * errorCount: state.errorCount,
135
- * rejectionCount: state.rejectionCount
136
- * })
137
- * );
138
- *
139
- * // Opt-in to track execution metrics changes (optimized for stats display)
140
- * const asyncRateLimiter = createAsyncRateLimiter(
141
- * async (id: string) => {
142
- * const data = await api.fetchData(id);
143
- * return data;
144
- * },
145
- * { limit: 5, window: 1000 },
146
- * (state) => ({
147
- * successCount: state.successCount,
148
- * errorCount: state.errorCount,
149
- * settleCount: state.settleCount,
150
- * rejectionCount: state.rejectionCount
151
- * })
152
- * );
153
- *
154
- * // Opt-in to track execution times changes (optimized for window calculations)
155
- * const asyncRateLimiter = createAsyncRateLimiter(
156
- * async (id: string) => {
157
- * const data = await api.fetchData(id);
158
- * return data;
159
- * },
160
- * { limit: 5, window: 1000 },
161
- * (state) => ({ executionTimes: state.executionTimes })
162
- * );
163
- *
164
- * // Access the selected state (will be empty object {} unless selector provided)
165
- * const { isExecuting, lastResult, rejectionCount } = asyncRateLimiter.state();
166
- * ```
167
- */
168
- function createAsyncRateLimiter(fn, options, selector = () => ({})) {
169
- const mergedOptions = {
170
- ...require_PacerProvider.useDefaultPacerOptions().asyncRateLimiter,
171
- ...options
172
- };
173
- const asyncRateLimiter = new _tanstack_pacer_async_rate_limiter.AsyncRateLimiter(fn, mergedOptions);
174
- asyncRateLimiter.Subscribe = function Subscribe(props) {
175
- const selected = (0, _tanstack_solid_store.useSelector)(asyncRateLimiter.store, props.selector, { compare: _tanstack_solid_store.shallow });
176
- return typeof props.children === "function" ? props.children(selected) : props.children;
177
- };
178
- const state = (0, _tanstack_solid_store.useSelector)(asyncRateLimiter.store, selector, { compare: _tanstack_solid_store.shallow });
179
- (0, solid_js.createEffect)(() => {
180
- (0, solid_js.onCleanup)(() => {
181
- if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncRateLimiter);
182
- else asyncRateLimiter.abort();
183
- });
184
- });
185
- return {
186
- ...asyncRateLimiter,
187
- state
188
- };
189
- }
190
-
191
- //#endregion
192
- exports.createAsyncRateLimiter = createAsyncRateLimiter;
193
- //# sourceMappingURL=createAsyncRateLimiter.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"createAsyncRateLimiter.cjs","names":["useDefaultPacerOptions","AsyncRateLimiter","shallow"],"sources":["../../src/async-rate-limiter/createAsyncRateLimiter.ts"],"sourcesContent":["import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { shallow, useSelector } 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 `useSelector` hook internally.\n * Although, you can make the state reactive by using the `useSelector` in your own usage.\n */\n readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>\n}\n\n/**\n * A low-level 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 = useSelector(asyncRateLimiter.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useSelector(asyncRateLimiter.store, selector, {\n compare: shallow,\n })\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;CAED,iBAAiB,YAAY,SAAS,UAAqB,OAGxD;EACD,MAAM,kDAAuB,iBAAiB,OAAO,MAAM,UAAU,EACnE,SAASC,+BACV,CAAC;EAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,+CAAoB,iBAAiB,OAAO,UAAU,EAC1D,SAASA,+BACV,CAAC;CAEF,iCAAmB;EACjB,8BAAgB;GACd,IAAI,cAAc,WAChB,cAAc,UAAU,iBAAiB;QAEzC,iBAAiB,OAAO;IAE1B;GACF;CAEF,OAAO;EACL,GAAG;EACH;EACD"}
@@ -1,209 +0,0 @@
1
- import { Store } from "@tanstack/solid-store";
2
- import { Accessor, JSX } from "solid-js";
3
- import { AnyAsyncFunction } from "@tanstack/pacer/types";
4
- import { AsyncRateLimiter, AsyncRateLimiterOptions, AsyncRateLimiterState } from "@tanstack/pacer/async-rate-limiter";
5
-
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
- }
14
- interface SolidAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncRateLimiter<TFn>, 'store'> {
15
- /**
16
- * A Solid component that allows you to subscribe to the rate limiter state.
17
- *
18
- * This is useful for tracking specific parts of the rate limiter state
19
- * deep in your component tree without needing to pass a selector to the hook.
20
- *
21
- * @example
22
- * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount, isExecuting: state.isExecuting })}>
23
- * {(state) => (
24
- * <div>Rejected: {state().rejectionCount}, {state().isExecuting ? 'Executing' : 'Idle'}</div>
25
- * )}
26
- * </rateLimiter.Subscribe>
27
- */
28
- Subscribe: <TSelected>(props: {
29
- selector: (state: AsyncRateLimiterState<TFn>) => TSelected;
30
- children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element;
31
- }) => JSX.Element;
32
- /**
33
- * Reactive state that will be updated when the rate limiter state changes
34
- *
35
- * Use this instead of `rateLimiter.store.state`
36
- */
37
- readonly state: Accessor<Readonly<TSelected>>;
38
- /**
39
- * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.
40
- * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
41
- * Although, you can make the state reactive by using the `useSelector` in your own usage.
42
- */
43
- readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>;
44
- }
45
- /**
46
- * A low-level Solid hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.
47
- *
48
- * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that
49
- * you can integrate with any state management solution (createSignal, etc).
50
- *
51
- * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
52
- * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
53
- * all executions happen immediately, followed by a complete block.
54
- *
55
- * The rate limiter supports two types of windows:
56
- * - 'fixed': A strict window that resets after the window period. All executions within the window count
57
- * towards the limit, and the window resets completely after the period.
58
- * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
59
- * consistent rate of execution over time.
60
- *
61
- * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,
62
- * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
63
- * instead of setting the result on a state variable from within the rate-limited function.
64
- *
65
- * For smoother execution patterns, consider using:
66
- * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
67
- * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
68
- *
69
- * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
70
- * smoothing out frequent events, throttling or debouncing usually provide better user experience.
71
- *
72
- * Error Handling:
73
- * - If an `onError` handler is provided, it will be called with the error and rate limiter instance
74
- * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
75
- * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
76
- * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
77
- * - The error state can be checked using the underlying AsyncRateLimiter instance
78
- * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler
79
- *
80
- * ## State Management and Selector
81
- *
82
- * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
83
- * in two ways:
84
- *
85
- * **1. Using `rateLimiter.Subscribe` component (Recommended for component tree subscriptions)**
86
- *
87
- * Use the `Subscribe` component to subscribe to state changes deep in your component tree without
88
- * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
89
- * in child components.
90
- *
91
- * **2. Using the `selector` parameter (For hook-level subscriptions)**
92
- *
93
- * The `selector` parameter allows you to specify which state changes will trigger reactive updates
94
- * at the hook level, optimizing performance by preventing unnecessary updates when irrelevant
95
- * state changes occur.
96
- *
97
- * **By default, there will be no reactive state subscriptions** and you must opt-in to state
98
- * tracking by providing a selector function or using the `Subscribe` component. This prevents unnecessary
99
- * updates and gives you full control over when your component tracks state changes.
100
- *
101
- * Available state properties:
102
- * - `currentWindowStart`: Timestamp when the current window started
103
- * - `executionCount`: Number of function executions that have been completed
104
- * - `hasError`: Whether the last execution resulted in an error
105
- * - `isExecuting`: Whether an async function execution is currently in progress
106
- * - `lastError`: The error from the most recent failed execution (if any)
107
- * - `lastResult`: The result from the most recent successful execution
108
- * - `nextWindowTime`: Timestamp when the next window begins
109
- * - `rejectionCount`: Number of function calls that were rejected due to rate limiting
110
- * - `remainingInWindow`: Number of executions remaining in the current window
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
- *
118
- * @example
119
- * ```tsx
120
- * // Default behavior - no reactive state subscriptions
121
- * const asyncRateLimiter = createAsyncRateLimiter(
122
- * async (id: string) => {
123
- * const data = await api.fetchData(id);
124
- * return data; // Return value is preserved
125
- * },
126
- * { limit: 5, window: 1000 } // 5 calls per second
127
- * );
128
- *
129
- * // Subscribe to state changes deep in component tree using Subscribe component
130
- * <asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount, isExecuting: state.isExecuting })}>
131
- * {(state) => (
132
- * <div>Rejected: {state().rejectionCount}, {state().isExecuting ? 'Executing' : 'Idle'}</div>
133
- * )}
134
- * </asyncRateLimiter.Subscribe>
135
- *
136
- * // Opt-in to track execution state changes at hook level (optimized for loading indicators)
137
- * const asyncRateLimiter = createAsyncRateLimiter(
138
- * async (id: string) => {
139
- * const data = await api.fetchData(id);
140
- * return data;
141
- * },
142
- * { limit: 5, window: 1000 },
143
- * (state) => ({ isExecuting: state.isExecuting })
144
- * );
145
- *
146
- * // Opt-in to track results when available (optimized for data display)
147
- * const asyncRateLimiter = createAsyncRateLimiter(
148
- * async (id: string) => {
149
- * const data = await api.fetchData(id);
150
- * return data;
151
- * },
152
- * { limit: 5, window: 1000 },
153
- * (state) => ({
154
- * lastResult: state.lastResult,
155
- * successCount: state.successCount
156
- * })
157
- * );
158
- *
159
- * // Opt-in to track error/rejection state changes (optimized for error handling)
160
- * const asyncRateLimiter = createAsyncRateLimiter(
161
- * async (id: string) => {
162
- * const data = await api.fetchData(id);
163
- * return data;
164
- * },
165
- * {
166
- * limit: 5,
167
- * window: 1000,
168
- * onError: (error) => console.error('API call failed:', error),
169
- * onReject: (rateLimiter) => console.log('Rate limit exceeded')
170
- * },
171
- * (state) => ({
172
- * errorCount: state.errorCount,
173
- * rejectionCount: state.rejectionCount
174
- * })
175
- * );
176
- *
177
- * // Opt-in to track execution metrics changes (optimized for stats display)
178
- * const asyncRateLimiter = createAsyncRateLimiter(
179
- * async (id: string) => {
180
- * const data = await api.fetchData(id);
181
- * return data;
182
- * },
183
- * { limit: 5, window: 1000 },
184
- * (state) => ({
185
- * successCount: state.successCount,
186
- * errorCount: state.errorCount,
187
- * settleCount: state.settleCount,
188
- * rejectionCount: state.rejectionCount
189
- * })
190
- * );
191
- *
192
- * // Opt-in to track execution times changes (optimized for window calculations)
193
- * const asyncRateLimiter = createAsyncRateLimiter(
194
- * async (id: string) => {
195
- * const data = await api.fetchData(id);
196
- * return data;
197
- * },
198
- * { limit: 5, window: 1000 },
199
- * (state) => ({ executionTimes: state.executionTimes })
200
- * );
201
- *
202
- * // Access the selected state (will be empty object {} unless selector provided)
203
- * const { isExecuting, lastResult, rejectionCount } = asyncRateLimiter.state();
204
- * ```
205
- */
206
- declare function createAsyncRateLimiter<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: SolidAsyncRateLimiterOptions<TFn, TSelected>, selector?: (state: AsyncRateLimiterState<TFn>) => TSelected): SolidAsyncRateLimiter<TFn, TSelected>;
207
- //#endregion
208
- export { SolidAsyncRateLimiter, SolidAsyncRateLimiterOptions, createAsyncRateLimiter };
209
- //# sourceMappingURL=createAsyncRateLimiter.d.cts.map