@tanstack/preact-pacer 0.0.1 → 0.18.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.
- package/LICENSE +21 -0
- package/README.md +165 -45
- package/dist/async-batcher/index.cjs +12 -0
- package/dist/async-batcher/index.d.cts +4 -0
- package/dist/async-batcher/index.d.ts +4 -0
- package/dist/async-batcher/index.js +6 -0
- package/dist/async-batcher/useAsyncBatchedCallback.cjs +51 -0
- package/dist/async-batcher/useAsyncBatchedCallback.cjs.map +1 -0
- package/dist/async-batcher/useAsyncBatchedCallback.d.cts +46 -0
- package/dist/async-batcher/useAsyncBatchedCallback.d.ts +46 -0
- package/dist/async-batcher/useAsyncBatchedCallback.js +51 -0
- package/dist/async-batcher/useAsyncBatchedCallback.js.map +1 -0
- package/dist/async-batcher/useAsyncBatcher.cjs +165 -0
- package/dist/async-batcher/useAsyncBatcher.cjs.map +1 -0
- package/dist/async-batcher/useAsyncBatcher.d.cts +163 -0
- package/dist/async-batcher/useAsyncBatcher.d.ts +163 -0
- package/dist/async-batcher/useAsyncBatcher.js +165 -0
- package/dist/async-batcher/useAsyncBatcher.js.map +1 -0
- package/dist/async-debouncer/index.cjs +12 -0
- package/dist/async-debouncer/index.d.cts +4 -0
- package/dist/async-debouncer/index.d.ts +4 -0
- package/dist/async-debouncer/index.js +6 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.cjs +50 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.cjs.map +1 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.d.cts +47 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.d.ts +47 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.js +50 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.js.map +1 -0
- package/dist/async-debouncer/useAsyncDebouncer.cjs +149 -0
- package/dist/async-debouncer/useAsyncDebouncer.cjs.map +1 -0
- package/dist/async-debouncer/useAsyncDebouncer.d.cts +143 -0
- package/dist/async-debouncer/useAsyncDebouncer.d.ts +143 -0
- package/dist/async-debouncer/useAsyncDebouncer.js +149 -0
- package/dist/async-debouncer/useAsyncDebouncer.js.map +1 -0
- package/dist/async-queuer/index.cjs +12 -0
- package/dist/async-queuer/index.d.cts +4 -0
- package/dist/async-queuer/index.d.ts +4 -0
- package/dist/async-queuer/index.js +6 -0
- package/dist/async-queuer/useAsyncQueuedState.cjs +154 -0
- package/dist/async-queuer/useAsyncQueuedState.cjs.map +1 -0
- package/dist/async-queuer/useAsyncQueuedState.d.cts +152 -0
- package/dist/async-queuer/useAsyncQueuedState.d.ts +152 -0
- package/dist/async-queuer/useAsyncQueuedState.js +154 -0
- package/dist/async-queuer/useAsyncQueuedState.js.map +1 -0
- package/dist/async-queuer/useAsyncQueuer.cjs +165 -0
- package/dist/async-queuer/useAsyncQueuer.cjs.map +1 -0
- package/dist/async-queuer/useAsyncQueuer.d.cts +163 -0
- package/dist/async-queuer/useAsyncQueuer.d.ts +163 -0
- package/dist/async-queuer/useAsyncQueuer.js +165 -0
- package/dist/async-queuer/useAsyncQueuer.js.map +1 -0
- package/dist/async-rate-limiter/index.cjs +12 -0
- package/dist/async-rate-limiter/index.d.cts +4 -0
- package/dist/async-rate-limiter/index.d.ts +4 -0
- package/dist/async-rate-limiter/index.js +6 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.cjs +65 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.cjs.map +1 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.d.cts +62 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.d.ts +62 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.js +65 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.js.map +1 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs +173 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs.map +1 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.cts +172 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.ts +172 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.js +173 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.js.map +1 -0
- package/dist/async-retryer/index.cjs +9 -0
- package/dist/async-retryer/index.d.cts +1 -0
- package/dist/async-retryer/index.d.ts +1 -0
- package/dist/async-retryer/index.js +3 -0
- package/dist/async-throttler/index.cjs +12 -0
- package/dist/async-throttler/index.d.cts +4 -0
- package/dist/async-throttler/index.d.ts +4 -0
- package/dist/async-throttler/index.js +6 -0
- package/dist/async-throttler/useAsyncThrottledCallback.cjs +48 -0
- package/dist/async-throttler/useAsyncThrottledCallback.cjs.map +1 -0
- package/dist/async-throttler/useAsyncThrottledCallback.d.cts +45 -0
- package/dist/async-throttler/useAsyncThrottledCallback.d.ts +45 -0
- package/dist/async-throttler/useAsyncThrottledCallback.js +48 -0
- package/dist/async-throttler/useAsyncThrottledCallback.js.map +1 -0
- package/dist/async-throttler/useAsyncThrottler.cjs +158 -0
- package/dist/async-throttler/useAsyncThrottler.cjs.map +1 -0
- package/dist/async-throttler/useAsyncThrottler.d.cts +154 -0
- package/dist/async-throttler/useAsyncThrottler.d.ts +154 -0
- package/dist/async-throttler/useAsyncThrottler.js +158 -0
- package/dist/async-throttler/useAsyncThrottler.js.map +1 -0
- package/dist/batcher/index.cjs +12 -0
- package/dist/batcher/index.d.cts +4 -0
- package/dist/batcher/index.d.ts +4 -0
- package/dist/batcher/index.js +6 -0
- package/dist/batcher/useBatchedCallback.cjs +47 -0
- package/dist/batcher/useBatchedCallback.cjs.map +1 -0
- package/dist/batcher/useBatchedCallback.d.cts +44 -0
- package/dist/batcher/useBatchedCallback.d.ts +44 -0
- package/dist/batcher/useBatchedCallback.js +47 -0
- package/dist/batcher/useBatchedCallback.js.map +1 -0
- package/dist/batcher/useBatcher.cjs +122 -0
- package/dist/batcher/useBatcher.cjs.map +1 -0
- package/dist/batcher/useBatcher.d.cts +120 -0
- package/dist/batcher/useBatcher.d.ts +120 -0
- package/dist/batcher/useBatcher.js +122 -0
- package/dist/batcher/useBatcher.js.map +1 -0
- package/dist/debouncer/index.cjs +16 -0
- package/dist/debouncer/index.d.cts +6 -0
- package/dist/debouncer/index.d.ts +6 -0
- package/dist/debouncer/index.js +8 -0
- package/dist/debouncer/useDebouncedCallback.cjs +48 -0
- package/dist/debouncer/useDebouncedCallback.cjs.map +1 -0
- package/dist/debouncer/useDebouncedCallback.d.cts +45 -0
- package/dist/debouncer/useDebouncedCallback.d.ts +45 -0
- package/dist/debouncer/useDebouncedCallback.js +48 -0
- package/dist/debouncer/useDebouncedCallback.js.map +1 -0
- package/dist/debouncer/useDebouncedState.cjs +89 -0
- package/dist/debouncer/useDebouncedState.cjs.map +1 -0
- package/dist/debouncer/useDebouncedState.d.cts +82 -0
- package/dist/debouncer/useDebouncedState.d.ts +82 -0
- package/dist/debouncer/useDebouncedState.js +89 -0
- package/dist/debouncer/useDebouncedState.js.map +1 -0
- package/dist/debouncer/useDebouncedValue.cjs +96 -0
- package/dist/debouncer/useDebouncedValue.cjs.map +1 -0
- package/dist/debouncer/useDebouncedValue.d.cts +91 -0
- package/dist/debouncer/useDebouncedValue.d.ts +91 -0
- package/dist/debouncer/useDebouncedValue.js +96 -0
- package/dist/debouncer/useDebouncedValue.js.map +1 -0
- package/dist/debouncer/useDebouncer.cjs +104 -0
- package/dist/debouncer/useDebouncer.cjs.map +1 -0
- package/dist/debouncer/useDebouncer.d.cts +98 -0
- package/dist/debouncer/useDebouncer.d.ts +98 -0
- package/dist/debouncer/useDebouncer.js +104 -0
- package/dist/debouncer/useDebouncer.js.map +1 -0
- package/dist/index.cjs +66 -0
- package/dist/index.d.cts +30 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +32 -0
- package/dist/provider/PacerProvider.cjs +26 -0
- package/dist/provider/PacerProvider.cjs.map +1 -0
- package/dist/provider/PacerProvider.d.cts +33 -0
- package/dist/provider/PacerProvider.d.ts +33 -0
- package/dist/provider/PacerProvider.js +24 -0
- package/dist/provider/PacerProvider.js.map +1 -0
- package/dist/provider/index.cjs +5 -0
- package/dist/provider/index.d.cts +2 -0
- package/dist/provider/index.d.ts +2 -0
- package/dist/provider/index.js +3 -0
- package/dist/queuer/index.cjs +14 -0
- package/dist/queuer/index.d.cts +5 -0
- package/dist/queuer/index.d.ts +5 -0
- package/dist/queuer/index.js +7 -0
- package/dist/queuer/useQueuedState.cjs +129 -0
- package/dist/queuer/useQueuedState.cjs.map +1 -0
- package/dist/queuer/useQueuedState.d.cts +123 -0
- package/dist/queuer/useQueuedState.d.ts +123 -0
- package/dist/queuer/useQueuedState.js +129 -0
- package/dist/queuer/useQueuedState.js.map +1 -0
- package/dist/queuer/useQueuedValue.cjs +115 -0
- package/dist/queuer/useQueuedValue.cjs.map +1 -0
- package/dist/queuer/useQueuedValue.d.cts +106 -0
- package/dist/queuer/useQueuedValue.d.ts +106 -0
- package/dist/queuer/useQueuedValue.js +115 -0
- package/dist/queuer/useQueuedValue.js.map +1 -0
- package/dist/queuer/useQueuer.cjs +133 -0
- package/dist/queuer/useQueuer.cjs.map +1 -0
- package/dist/queuer/useQueuer.d.cts +131 -0
- package/dist/queuer/useQueuer.d.ts +131 -0
- package/dist/queuer/useQueuer.js +133 -0
- package/dist/queuer/useQueuer.js.map +1 -0
- package/dist/rate-limiter/index.cjs +16 -0
- package/dist/rate-limiter/index.d.cts +6 -0
- package/dist/rate-limiter/index.d.ts +6 -0
- package/dist/rate-limiter/index.js +8 -0
- package/dist/rate-limiter/useRateLimitedCallback.cjs +65 -0
- package/dist/rate-limiter/useRateLimitedCallback.cjs.map +1 -0
- package/dist/rate-limiter/useRateLimitedCallback.d.cts +62 -0
- package/dist/rate-limiter/useRateLimitedCallback.d.ts +62 -0
- package/dist/rate-limiter/useRateLimitedCallback.js +65 -0
- package/dist/rate-limiter/useRateLimitedCallback.js.map +1 -0
- package/dist/rate-limiter/useRateLimitedState.cjs +115 -0
- package/dist/rate-limiter/useRateLimitedState.cjs.map +1 -0
- package/dist/rate-limiter/useRateLimitedState.d.cts +108 -0
- package/dist/rate-limiter/useRateLimitedState.d.ts +108 -0
- package/dist/rate-limiter/useRateLimitedState.js +115 -0
- package/dist/rate-limiter/useRateLimitedState.js.map +1 -0
- package/dist/rate-limiter/useRateLimitedValue.cjs +102 -0
- package/dist/rate-limiter/useRateLimitedValue.cjs.map +1 -0
- package/dist/rate-limiter/useRateLimitedValue.d.cts +97 -0
- package/dist/rate-limiter/useRateLimitedValue.d.ts +97 -0
- package/dist/rate-limiter/useRateLimitedValue.js +102 -0
- package/dist/rate-limiter/useRateLimitedValue.js.map +1 -0
- package/dist/rate-limiter/useRateLimiter.cjs +138 -0
- package/dist/rate-limiter/useRateLimiter.cjs.map +1 -0
- package/dist/rate-limiter/useRateLimiter.d.cts +137 -0
- package/dist/rate-limiter/useRateLimiter.d.ts +137 -0
- package/dist/rate-limiter/useRateLimiter.js +138 -0
- package/dist/rate-limiter/useRateLimiter.js.map +1 -0
- package/dist/throttler/index.cjs +16 -0
- package/dist/throttler/index.d.cts +6 -0
- package/dist/throttler/index.d.ts +6 -0
- package/dist/throttler/index.js +8 -0
- package/dist/throttler/useThrottledCallback.cjs +49 -0
- package/dist/throttler/useThrottledCallback.cjs.map +1 -0
- package/dist/throttler/useThrottledCallback.d.cts +46 -0
- package/dist/throttler/useThrottledCallback.d.ts +46 -0
- package/dist/throttler/useThrottledCallback.js +49 -0
- package/dist/throttler/useThrottledCallback.js.map +1 -0
- package/dist/throttler/useThrottledState.cjs +100 -0
- package/dist/throttler/useThrottledState.cjs.map +1 -0
- package/dist/throttler/useThrottledState.d.cts +93 -0
- package/dist/throttler/useThrottledState.d.ts +93 -0
- package/dist/throttler/useThrottledState.js +100 -0
- package/dist/throttler/useThrottledState.js.map +1 -0
- package/dist/throttler/useThrottledValue.cjs +91 -0
- package/dist/throttler/useThrottledValue.cjs.map +1 -0
- package/dist/throttler/useThrottledValue.d.cts +86 -0
- package/dist/throttler/useThrottledValue.d.ts +86 -0
- package/dist/throttler/useThrottledValue.js +91 -0
- package/dist/throttler/useThrottledValue.js.map +1 -0
- package/dist/throttler/useThrottler.cjs +109 -0
- package/dist/throttler/useThrottler.cjs.map +1 -0
- package/dist/throttler/useThrottler.d.cts +103 -0
- package/dist/throttler/useThrottler.d.ts +103 -0
- package/dist/throttler/useThrottler.js +109 -0
- package/dist/throttler/useThrottler.js.map +1 -0
- package/dist/types/index.cjs +9 -0
- package/dist/types/index.d.cts +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js +3 -0
- package/dist/utils/index.cjs +9 -0
- package/dist/utils/index.d.cts +1 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.js +3 -0
- package/package.json +118 -7
- package/src/async-batcher/index.ts +4 -0
- package/src/async-batcher/useAsyncBatchedCallback.ts +54 -0
- package/src/async-batcher/useAsyncBatcher.ts +198 -0
- package/src/async-debouncer/index.ts +5 -0
- package/src/async-debouncer/useAsyncDebouncedCallback.ts +54 -0
- package/src/async-debouncer/useAsyncDebouncer.ts +184 -0
- package/src/async-queuer/index.ts +4 -0
- package/src/async-queuer/useAsyncQueuedState.ts +165 -0
- package/src/async-queuer/useAsyncQueuer.ts +198 -0
- package/src/async-rate-limiter/index.ts +5 -0
- package/src/async-rate-limiter/useAsyncRateLimitedCallback.ts +69 -0
- package/src/async-rate-limiter/useAsyncRateLimiter.ts +210 -0
- package/src/async-retryer/index.ts +2 -0
- package/src/async-throttler/index.ts +5 -0
- package/src/async-throttler/useAsyncThrottledCallback.ts +52 -0
- package/src/async-throttler/useAsyncThrottler.ts +193 -0
- package/src/batcher/index.ts +4 -0
- package/src/batcher/useBatchedCallback.ts +50 -0
- package/src/batcher/useBatcher.ts +150 -0
- package/src/debouncer/index.ts +7 -0
- package/src/debouncer/useDebouncedCallback.ts +51 -0
- package/src/debouncer/useDebouncedState.ts +109 -0
- package/src/debouncer/useDebouncedValue.ts +112 -0
- package/src/debouncer/useDebouncer.ts +136 -0
- package/src/index.ts +56 -0
- package/src/provider/PacerProvider.tsx +70 -0
- package/src/provider/index.ts +1 -0
- package/src/queuer/index.ts +5 -0
- package/src/queuer/useQueuedState.ts +133 -0
- package/src/queuer/useQueuedValue.ts +129 -0
- package/src/queuer/useQueuer.ts +160 -0
- package/src/rate-limiter/index.ts +6 -0
- package/src/rate-limiter/useRateLimitedCallback.ts +68 -0
- package/src/rate-limiter/useRateLimitedState.ts +124 -0
- package/src/rate-limiter/useRateLimitedValue.ts +110 -0
- package/src/rate-limiter/useRateLimiter.ts +169 -0
- package/src/throttler/index.ts +7 -0
- package/src/throttler/useThrottledCallback.ts +52 -0
- package/src/throttler/useThrottledState.ts +121 -0
- package/src/throttler/useThrottledValue.ts +107 -0
- package/src/throttler/useThrottler.ts +141 -0
- package/src/types/index.ts +1 -0
- package/src/utils/index.ts +1 -0
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { useRateLimitedState } from "./useRateLimitedState.js";
|
|
2
|
+
import { useEffect } from "preact/hooks";
|
|
3
|
+
|
|
4
|
+
//#region src/rate-limiter/useRateLimitedValue.ts
|
|
5
|
+
/**
|
|
6
|
+
* A high-level Preact hook that creates a rate-limited version of a value that updates at most a certain number of times within a time window.
|
|
7
|
+
* This hook uses Preact's useState internally to manage the rate-limited state.
|
|
8
|
+
*
|
|
9
|
+
* Rate limiting is a simple "hard limit" approach - it allows all updates until the limit is reached, then blocks
|
|
10
|
+
* subsequent updates until the window resets. Unlike throttling or debouncing, it does not attempt to space out
|
|
11
|
+
* or intelligently collapse updates. This can lead to bursts of rapid updates followed by periods of no updates.
|
|
12
|
+
*
|
|
13
|
+
* The rate limiter supports two types of windows:
|
|
14
|
+
* - 'fixed': A strict window that resets after the window period. All updates within the window count
|
|
15
|
+
* towards the limit, and the window resets completely after the period.
|
|
16
|
+
* - 'sliding': A rolling window that allows updates as old ones expire. This provides a more
|
|
17
|
+
* consistent rate of updates over time.
|
|
18
|
+
*
|
|
19
|
+
* For smoother update patterns, consider:
|
|
20
|
+
* - useThrottledValue: When you want consistent spacing between updates (e.g. UI changes)
|
|
21
|
+
* - useDebouncedValue: When you want to collapse rapid updates into a single update (e.g. search input)
|
|
22
|
+
*
|
|
23
|
+
* Rate limiting should primarily be used when you need to enforce strict limits, like API rate limits.
|
|
24
|
+
*
|
|
25
|
+
* The hook returns a tuple containing:
|
|
26
|
+
* - The rate-limited value that updates according to the configured rate limit
|
|
27
|
+
* - The rate limiter instance with control methods
|
|
28
|
+
*
|
|
29
|
+
* For more direct control over rate limiting behavior without Preact state management,
|
|
30
|
+
* consider using the lower-level useRateLimiter hook instead.
|
|
31
|
+
*
|
|
32
|
+
* ## State Management and Selector
|
|
33
|
+
*
|
|
34
|
+
* The hook uses TanStack Store for reactive state management via the underlying rate limiter instance.
|
|
35
|
+
* The `selector` parameter allows you to specify which rate limiter state changes will trigger a re-render,
|
|
36
|
+
* optimizing performance by preventing unnecessary re-renders when irrelevant state changes occur.
|
|
37
|
+
*
|
|
38
|
+
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
39
|
+
* tracking by providing a selector function. This prevents unnecessary re-renders and gives you
|
|
40
|
+
* full control over when your component updates. Only when you provide a selector will the
|
|
41
|
+
* component re-render when the selected state values change.
|
|
42
|
+
*
|
|
43
|
+
* Available rate limiter state properties:
|
|
44
|
+
* - `executionCount`: Number of function executions that have been completed
|
|
45
|
+
* - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations
|
|
46
|
+
* - `rejectionCount`: Number of function executions that have been rejected due to rate limiting
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```tsx
|
|
50
|
+
* // Default behavior - no reactive state subscriptions
|
|
51
|
+
* const [rateLimitedValue, rateLimiter] = useRateLimitedValue(rawValue, {
|
|
52
|
+
* limit: 5,
|
|
53
|
+
* window: 60000,
|
|
54
|
+
* windowType: 'sliding'
|
|
55
|
+
* });
|
|
56
|
+
*
|
|
57
|
+
* // Opt-in to re-render when execution count changes (optimized for tracking successful updates)
|
|
58
|
+
* const [rateLimitedValue, rateLimiter] = useRateLimitedValue(
|
|
59
|
+
* rawValue,
|
|
60
|
+
* { limit: 5, window: 60000, windowType: 'sliding' },
|
|
61
|
+
* (state) => ({ executionCount: state.executionCount })
|
|
62
|
+
* );
|
|
63
|
+
*
|
|
64
|
+
* // Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)
|
|
65
|
+
* const [rateLimitedValue, rateLimiter] = useRateLimitedValue(
|
|
66
|
+
* rawValue,
|
|
67
|
+
* { limit: 5, window: 60000, windowType: 'sliding' },
|
|
68
|
+
* (state) => ({ rejectionCount: state.rejectionCount })
|
|
69
|
+
* );
|
|
70
|
+
*
|
|
71
|
+
* // Opt-in to re-render when execution times change (optimized for window calculations)
|
|
72
|
+
* const [rateLimitedValue, rateLimiter] = useRateLimitedValue(
|
|
73
|
+
* rawValue,
|
|
74
|
+
* { limit: 5, window: 60000, windowType: 'sliding' },
|
|
75
|
+
* (state) => ({ executionTimes: state.executionTimes })
|
|
76
|
+
* );
|
|
77
|
+
*
|
|
78
|
+
* // With rejection callback and fixed window
|
|
79
|
+
* const [rateLimitedValue, rateLimiter] = useRateLimitedValue(rawValue, {
|
|
80
|
+
* limit: 3,
|
|
81
|
+
* window: 5000,
|
|
82
|
+
* windowType: 'fixed',
|
|
83
|
+
* onReject: (rateLimiter) => {
|
|
84
|
+
* console.log(`Update rejected. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
|
|
85
|
+
* }
|
|
86
|
+
* });
|
|
87
|
+
*
|
|
88
|
+
* // Access the selected rate limiter state (will be empty object {} unless selector provided)
|
|
89
|
+
* const { executionCount, rejectionCount } = rateLimiter.state;
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
92
|
+
function useRateLimitedValue(value, options, selector) {
|
|
93
|
+
const [rateLimitedValue, setRateLimitedValue, rateLimiter] = useRateLimitedState(value, options, selector);
|
|
94
|
+
useEffect(() => {
|
|
95
|
+
setRateLimitedValue(value);
|
|
96
|
+
}, [value, setRateLimitedValue]);
|
|
97
|
+
return [rateLimitedValue, rateLimiter];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
//#endregion
|
|
101
|
+
export { useRateLimitedValue };
|
|
102
|
+
//# sourceMappingURL=useRateLimitedValue.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useRateLimitedValue.js","names":[],"sources":["../../src/rate-limiter/useRateLimitedValue.ts"],"sourcesContent":["import { useEffect } from 'preact/hooks'\nimport { useRateLimitedState } from './useRateLimitedState'\nimport type { Dispatch, StateUpdater } from 'preact/hooks'\nimport type { PreactRateLimiter } from './useRateLimiter'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} from '@tanstack/pacer/rate-limiter'\n\n/**\n * A high-level Preact hook that creates a rate-limited version of a value that updates at most a certain number of times within a time window.\n * This hook uses Preact's useState internally to manage the rate-limited state.\n *\n * Rate limiting is a simple \"hard limit\" approach - it allows all updates until the limit is reached, then blocks\n * subsequent updates until the window resets. Unlike throttling or debouncing, it does not attempt to space out\n * or intelligently collapse updates. This can lead to bursts of rapid updates followed by periods of no updates.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All updates within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows updates as old ones expire. This provides a more\n * consistent rate of updates over time.\n *\n * For smoother update patterns, consider:\n * - useThrottledValue: When you want consistent spacing between updates (e.g. UI changes)\n * - useDebouncedValue: When you want to collapse rapid updates into a single update (e.g. search input)\n *\n * Rate limiting should primarily be used when you need to enforce strict limits, like API rate limits.\n *\n * The hook returns a tuple containing:\n * - The rate-limited value that updates according to the configured rate limit\n * - The rate limiter instance with control methods\n *\n * For more direct control over rate limiting behavior without Preact state management,\n * consider using the lower-level useRateLimiter hook instead.\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management via the underlying rate limiter instance.\n * The `selector` parameter allows you to specify which rate limiter state changes will trigger a re-render,\n * optimizing performance by preventing unnecessary re-renders when irrelevant 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. This prevents unnecessary re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available rate limiter state properties:\n * - `executionCount`: Number of function executions that have been completed\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const [rateLimitedValue, rateLimiter] = useRateLimitedValue(rawValue, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding'\n * });\n *\n * // Opt-in to re-render when execution count changes (optimized for tracking successful updates)\n * const [rateLimitedValue, rateLimiter] = useRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)\n * const [rateLimitedValue, rateLimiter] = useRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ rejectionCount: state.rejectionCount })\n * );\n *\n * // Opt-in to re-render when execution times change (optimized for window calculations)\n * const [rateLimitedValue, rateLimiter] = useRateLimitedValue(\n * rawValue,\n * { limit: 5, window: 60000, windowType: 'sliding' },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // With rejection callback and fixed window\n * const [rateLimitedValue, rateLimiter] = useRateLimitedValue(rawValue, {\n * limit: 3,\n * window: 5000,\n * windowType: 'fixed',\n * onReject: (rateLimiter) => {\n * console.log(`Update rejected. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // Access the selected rate limiter state (will be empty object {} unless selector provided)\n * const { executionCount, rejectionCount } = rateLimiter.state;\n * ```\n */\nexport function useRateLimitedValue<TValue, TSelected = RateLimiterState>(\n value: TValue,\n options: RateLimiterOptions<Dispatch<StateUpdater<TValue>>>,\n selector?: (state: RateLimiterState) => TSelected,\n): [TValue, PreactRateLimiter<Dispatch<StateUpdater<TValue>>, TSelected>] {\n const [rateLimitedValue, setRateLimitedValue, rateLimiter] =\n useRateLimitedState(value, options, selector)\n\n useEffect(() => {\n ;(setRateLimitedValue as (value: TValue) => void)(value)\n }, [value, setRateLimitedValue])\n\n return [rateLimitedValue, rateLimiter]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,SAAgB,oBACd,OACA,SACA,UACwE;CACxE,MAAM,CAAC,kBAAkB,qBAAqB,eAC5C,oBAAoB,OAAO,SAAS,SAAS;AAE/C,iBAAgB;AACb,EAAC,oBAAgD,MAAM;IACvD,CAAC,OAAO,oBAAoB,CAAC;AAEhC,QAAO,CAAC,kBAAkB,YAAY"}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
const require_PacerProvider = require('../provider/PacerProvider.cjs');
|
|
2
|
+
let preact_hooks = require("preact/hooks");
|
|
3
|
+
let __tanstack_preact_store = require("@tanstack/preact-store");
|
|
4
|
+
let __tanstack_pacer_rate_limiter = require("@tanstack/pacer/rate-limiter");
|
|
5
|
+
|
|
6
|
+
//#region src/rate-limiter/useRateLimiter.ts
|
|
7
|
+
/**
|
|
8
|
+
* A low-level Preact hook that creates a `RateLimiter` instance to enforce rate limits on function execution.
|
|
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 (useState, Redux, Zustand, Jotai, etc).
|
|
12
|
+
*
|
|
13
|
+
* Rate limiting is a simple "hard limit" approach that allows executions until a maximum count is reached within
|
|
14
|
+
* a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,
|
|
15
|
+
* it does not attempt to space out or collapse executions intelligently.
|
|
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
|
+
* For smoother execution patterns:
|
|
24
|
+
* - Use throttling when you want consistent spacing between executions (e.g. UI updates)
|
|
25
|
+
* - Use debouncing when you want to collapse rapid-fire events (e.g. search input)
|
|
26
|
+
* - Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)
|
|
27
|
+
*
|
|
28
|
+
* ## State Management and Selector
|
|
29
|
+
*
|
|
30
|
+
* The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
|
|
31
|
+
* to specify which state changes will trigger a re-render, optimizing performance by preventing
|
|
32
|
+
* unnecessary re-renders when irrelevant state changes occur.
|
|
33
|
+
*
|
|
34
|
+
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
35
|
+
* tracking by providing a selector function. This prevents unnecessary re-renders and gives you
|
|
36
|
+
* full control over when your component updates. Only when you provide a selector will the
|
|
37
|
+
* component re-render when the selected state values change.
|
|
38
|
+
*
|
|
39
|
+
* Available state properties:
|
|
40
|
+
* - `executionCount`: Number of function executions that have been completed
|
|
41
|
+
* - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations
|
|
42
|
+
* - `rejectionCount`: Number of function executions that have been rejected due to rate limiting
|
|
43
|
+
*
|
|
44
|
+
* The hook returns an object containing:
|
|
45
|
+
* - maybeExecute: The rate-limited function that respects the configured limits
|
|
46
|
+
* - getExecutionCount: Returns the number of successful executions
|
|
47
|
+
* - getRejectionCount: Returns the number of rejected executions due to rate limiting
|
|
48
|
+
* - getRemainingInWindow: Returns how many more executions are allowed in the current window
|
|
49
|
+
* - reset: Resets the execution counts and window timing
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```tsx
|
|
53
|
+
* // Default behavior - no reactive state subscriptions
|
|
54
|
+
* const rateLimiter = useRateLimiter(apiCall, {
|
|
55
|
+
* limit: 5,
|
|
56
|
+
* window: 60000,
|
|
57
|
+
* windowType: 'sliding',
|
|
58
|
+
* });
|
|
59
|
+
*
|
|
60
|
+
* // Opt-in to re-render when execution count changes (optimized for tracking successful executions)
|
|
61
|
+
* const rateLimiter = useRateLimiter(
|
|
62
|
+
* apiCall,
|
|
63
|
+
* {
|
|
64
|
+
* limit: 5,
|
|
65
|
+
* window: 60000,
|
|
66
|
+
* windowType: 'sliding',
|
|
67
|
+
* },
|
|
68
|
+
* (state) => ({ executionCount: state.executionCount })
|
|
69
|
+
* );
|
|
70
|
+
*
|
|
71
|
+
* // Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)
|
|
72
|
+
* const rateLimiter = useRateLimiter(
|
|
73
|
+
* apiCall,
|
|
74
|
+
* {
|
|
75
|
+
* limit: 5,
|
|
76
|
+
* window: 60000,
|
|
77
|
+
* windowType: 'sliding',
|
|
78
|
+
* },
|
|
79
|
+
* (state) => ({ rejectionCount: state.rejectionCount })
|
|
80
|
+
* );
|
|
81
|
+
*
|
|
82
|
+
* // Opt-in to re-render when execution times change (optimized for window calculations)
|
|
83
|
+
* const rateLimiter = useRateLimiter(
|
|
84
|
+
* apiCall,
|
|
85
|
+
* {
|
|
86
|
+
* limit: 5,
|
|
87
|
+
* window: 60000,
|
|
88
|
+
* windowType: 'sliding',
|
|
89
|
+
* },
|
|
90
|
+
* (state) => ({ executionTimes: state.executionTimes })
|
|
91
|
+
* );
|
|
92
|
+
*
|
|
93
|
+
* // Multiple state properties - re-render when any of these change
|
|
94
|
+
* const rateLimiter = useRateLimiter(
|
|
95
|
+
* apiCall,
|
|
96
|
+
* {
|
|
97
|
+
* limit: 5,
|
|
98
|
+
* window: 60000,
|
|
99
|
+
* windowType: 'sliding',
|
|
100
|
+
* },
|
|
101
|
+
* (state) => ({
|
|
102
|
+
* executionCount: state.executionCount,
|
|
103
|
+
* rejectionCount: state.rejectionCount
|
|
104
|
+
* })
|
|
105
|
+
* );
|
|
106
|
+
*
|
|
107
|
+
* // Monitor rate limit status
|
|
108
|
+
* const handleClick = () => {
|
|
109
|
+
* const remaining = rateLimiter.getRemainingInWindow();
|
|
110
|
+
* if (remaining > 0) {
|
|
111
|
+
* rateLimiter.maybeExecute(data);
|
|
112
|
+
* } else {
|
|
113
|
+
* showRateLimitWarning();
|
|
114
|
+
* }
|
|
115
|
+
* };
|
|
116
|
+
*
|
|
117
|
+
* // Access the selected state (will be empty object {} unless selector provided)
|
|
118
|
+
* const { executionCount, rejectionCount } = rateLimiter.state;
|
|
119
|
+
* ```
|
|
120
|
+
*/
|
|
121
|
+
function useRateLimiter(fn, options, selector = () => ({})) {
|
|
122
|
+
const mergedOptions = {
|
|
123
|
+
...require_PacerProvider.useDefaultPacerOptions().rateLimiter,
|
|
124
|
+
...options
|
|
125
|
+
};
|
|
126
|
+
const [rateLimiter] = (0, preact_hooks.useState)(() => new __tanstack_pacer_rate_limiter.RateLimiter(fn, mergedOptions));
|
|
127
|
+
rateLimiter.fn = fn;
|
|
128
|
+
rateLimiter.setOptions(mergedOptions);
|
|
129
|
+
const state = (0, __tanstack_preact_store.useStore)(rateLimiter.store, selector);
|
|
130
|
+
return (0, preact_hooks.useMemo)(() => ({
|
|
131
|
+
...rateLimiter,
|
|
132
|
+
state
|
|
133
|
+
}), [rateLimiter, state]);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
//#endregion
|
|
137
|
+
exports.useRateLimiter = useRateLimiter;
|
|
138
|
+
//# sourceMappingURL=useRateLimiter.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useRateLimiter.cjs","names":["useDefaultPacerOptions","RateLimiter"],"sources":["../../src/rate-limiter/useRateLimiter.ts"],"sourcesContent":["import { useMemo, useState } from 'preact/hooks'\nimport { RateLimiter } from '@tanstack/pacer/rate-limiter'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n RateLimiterOptions,\n RateLimiterState,\n} from '@tanstack/pacer/rate-limiter'\nimport type { AnyFunction } from '@tanstack/pacer/types'\n\nexport interface PreactRateLimiter<\n TFn extends AnyFunction,\n TSelected = {},\n> extends Omit<RateLimiter<TFn>, 'store'> {\n /**\n * Reactive state that will be updated and re-rendered when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` in your own usage.\n */\n readonly store: Store<Readonly<RateLimiterState>>\n}\n\n/**\n * A low-level Preact hook that creates a `RateLimiter` instance to enforce rate limits on function execution.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Rate limiting is a simple \"hard limit\" approach that allows executions until a maximum count is reached within\n * a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,\n * it does not attempt to space out or collapse executions intelligently.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * For smoother execution patterns:\n * - Use throttling when you want consistent spacing between executions (e.g. UI updates)\n * - Use debouncing when you want to collapse rapid-fire events (e.g. search input)\n * - Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders when irrelevant 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. This prevents unnecessary re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `executionCount`: Number of function executions that have been completed\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n *\n * The hook returns an object containing:\n * - maybeExecute: The rate-limited function that respects the configured limits\n * - getExecutionCount: Returns the number of successful executions\n * - getRejectionCount: Returns the number of rejected executions due to rate limiting\n * - getRemainingInWindow: Returns how many more executions are allowed in the current window\n * - reset: Resets the execution counts and window timing\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const rateLimiter = useRateLimiter(apiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * });\n *\n * // Opt-in to re-render when execution count changes (optimized for tracking successful executions)\n * const rateLimiter = useRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ executionCount: state.executionCount })\n * );\n *\n * // Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)\n * const rateLimiter = useRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ rejectionCount: state.rejectionCount })\n * );\n *\n * // Opt-in to re-render when execution times change (optimized for window calculations)\n * const rateLimiter = useRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // Multiple state properties - re-render when any of these change\n * const rateLimiter = useRateLimiter(\n * apiCall,\n * {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * },\n * (state) => ({\n * executionCount: state.executionCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Monitor rate limit status\n * const handleClick = () => {\n * const remaining = rateLimiter.getRemainingInWindow();\n * if (remaining > 0) {\n * rateLimiter.maybeExecute(data);\n * } else {\n * showRateLimitWarning();\n * }\n * };\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { executionCount, rejectionCount } = rateLimiter.state;\n * ```\n */\nexport function useRateLimiter<TFn extends AnyFunction, TSelected = {}>(\n fn: TFn,\n options: RateLimiterOptions<TFn>,\n selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,\n): PreactRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().rateLimiter,\n ...options,\n } as RateLimiterOptions<TFn>\n\n const [rateLimiter] = useState(() => new RateLimiter<TFn>(fn, mergedOptions))\n\n rateLimiter.fn = fn\n rateLimiter.setOptions(mergedOptions)\n\n const state = useStore(rateLimiter.store, selector)\n\n return useMemo(\n () =>\n ({\n ...rateLimiter,\n state,\n }) as PreactRateLimiter<TFn, TSelected>, // omit `store` in favor of `state`\n [rateLimiter, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+IA,SAAgB,eACd,IACA,SACA,kBAA0D,EAAE,GACzB;CACnC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,gDAA8B,IAAIC,0CAAiB,IAAI,cAAc,CAAC;AAE7E,aAAY,KAAK;AACjB,aAAY,WAAW,cAAc;CAErC,MAAM,8CAAiB,YAAY,OAAO,SAAS;AAEnD,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,aAAa,MAAM,CACrB"}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { Store } from "@tanstack/preact-store";
|
|
2
|
+
import { AnyFunction } from "@tanstack/pacer/types";
|
|
3
|
+
import { RateLimiter, RateLimiterOptions, RateLimiterState } from "@tanstack/pacer/rate-limiter";
|
|
4
|
+
|
|
5
|
+
//#region src/rate-limiter/useRateLimiter.d.ts
|
|
6
|
+
interface PreactRateLimiter<TFn extends AnyFunction, TSelected = {}> extends Omit<RateLimiter<TFn>, 'store'> {
|
|
7
|
+
/**
|
|
8
|
+
* Reactive state that will be updated and re-rendered when the rate limiter state changes
|
|
9
|
+
*
|
|
10
|
+
* Use this instead of `rateLimiter.store.state`
|
|
11
|
+
*/
|
|
12
|
+
readonly state: Readonly<TSelected>;
|
|
13
|
+
/**
|
|
14
|
+
* @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.
|
|
15
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
|
|
16
|
+
* Although, you can make the state reactive by using the `useStore` in your own usage.
|
|
17
|
+
*/
|
|
18
|
+
readonly store: Store<Readonly<RateLimiterState>>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A low-level Preact hook that creates a `RateLimiter` instance to enforce rate limits on function execution.
|
|
22
|
+
*
|
|
23
|
+
* This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that
|
|
24
|
+
* you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
|
|
25
|
+
*
|
|
26
|
+
* Rate limiting is a simple "hard limit" approach that allows executions until a maximum count is reached within
|
|
27
|
+
* a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,
|
|
28
|
+
* it does not attempt to space out or collapse executions intelligently.
|
|
29
|
+
*
|
|
30
|
+
* The rate limiter supports two types of windows:
|
|
31
|
+
* - 'fixed': A strict window that resets after the window period. All executions within the window count
|
|
32
|
+
* towards the limit, and the window resets completely after the period.
|
|
33
|
+
* - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
|
|
34
|
+
* consistent rate of execution over time.
|
|
35
|
+
*
|
|
36
|
+
* For smoother execution patterns:
|
|
37
|
+
* - Use throttling when you want consistent spacing between executions (e.g. UI updates)
|
|
38
|
+
* - Use debouncing when you want to collapse rapid-fire events (e.g. search input)
|
|
39
|
+
* - Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)
|
|
40
|
+
*
|
|
41
|
+
* ## State Management and Selector
|
|
42
|
+
*
|
|
43
|
+
* The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
|
|
44
|
+
* to specify which state changes will trigger a re-render, optimizing performance by preventing
|
|
45
|
+
* unnecessary re-renders when irrelevant state changes occur.
|
|
46
|
+
*
|
|
47
|
+
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
48
|
+
* tracking by providing a selector function. This prevents unnecessary re-renders and gives you
|
|
49
|
+
* full control over when your component updates. Only when you provide a selector will the
|
|
50
|
+
* component re-render when the selected state values change.
|
|
51
|
+
*
|
|
52
|
+
* Available state properties:
|
|
53
|
+
* - `executionCount`: Number of function executions that have been completed
|
|
54
|
+
* - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations
|
|
55
|
+
* - `rejectionCount`: Number of function executions that have been rejected due to rate limiting
|
|
56
|
+
*
|
|
57
|
+
* The hook returns an object containing:
|
|
58
|
+
* - maybeExecute: The rate-limited function that respects the configured limits
|
|
59
|
+
* - getExecutionCount: Returns the number of successful executions
|
|
60
|
+
* - getRejectionCount: Returns the number of rejected executions due to rate limiting
|
|
61
|
+
* - getRemainingInWindow: Returns how many more executions are allowed in the current window
|
|
62
|
+
* - reset: Resets the execution counts and window timing
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```tsx
|
|
66
|
+
* // Default behavior - no reactive state subscriptions
|
|
67
|
+
* const rateLimiter = useRateLimiter(apiCall, {
|
|
68
|
+
* limit: 5,
|
|
69
|
+
* window: 60000,
|
|
70
|
+
* windowType: 'sliding',
|
|
71
|
+
* });
|
|
72
|
+
*
|
|
73
|
+
* // Opt-in to re-render when execution count changes (optimized for tracking successful executions)
|
|
74
|
+
* const rateLimiter = useRateLimiter(
|
|
75
|
+
* apiCall,
|
|
76
|
+
* {
|
|
77
|
+
* limit: 5,
|
|
78
|
+
* window: 60000,
|
|
79
|
+
* windowType: 'sliding',
|
|
80
|
+
* },
|
|
81
|
+
* (state) => ({ executionCount: state.executionCount })
|
|
82
|
+
* );
|
|
83
|
+
*
|
|
84
|
+
* // Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)
|
|
85
|
+
* const rateLimiter = useRateLimiter(
|
|
86
|
+
* apiCall,
|
|
87
|
+
* {
|
|
88
|
+
* limit: 5,
|
|
89
|
+
* window: 60000,
|
|
90
|
+
* windowType: 'sliding',
|
|
91
|
+
* },
|
|
92
|
+
* (state) => ({ rejectionCount: state.rejectionCount })
|
|
93
|
+
* );
|
|
94
|
+
*
|
|
95
|
+
* // Opt-in to re-render when execution times change (optimized for window calculations)
|
|
96
|
+
* const rateLimiter = useRateLimiter(
|
|
97
|
+
* apiCall,
|
|
98
|
+
* {
|
|
99
|
+
* limit: 5,
|
|
100
|
+
* window: 60000,
|
|
101
|
+
* windowType: 'sliding',
|
|
102
|
+
* },
|
|
103
|
+
* (state) => ({ executionTimes: state.executionTimes })
|
|
104
|
+
* );
|
|
105
|
+
*
|
|
106
|
+
* // Multiple state properties - re-render when any of these change
|
|
107
|
+
* const rateLimiter = useRateLimiter(
|
|
108
|
+
* apiCall,
|
|
109
|
+
* {
|
|
110
|
+
* limit: 5,
|
|
111
|
+
* window: 60000,
|
|
112
|
+
* windowType: 'sliding',
|
|
113
|
+
* },
|
|
114
|
+
* (state) => ({
|
|
115
|
+
* executionCount: state.executionCount,
|
|
116
|
+
* rejectionCount: state.rejectionCount
|
|
117
|
+
* })
|
|
118
|
+
* );
|
|
119
|
+
*
|
|
120
|
+
* // Monitor rate limit status
|
|
121
|
+
* const handleClick = () => {
|
|
122
|
+
* const remaining = rateLimiter.getRemainingInWindow();
|
|
123
|
+
* if (remaining > 0) {
|
|
124
|
+
* rateLimiter.maybeExecute(data);
|
|
125
|
+
* } else {
|
|
126
|
+
* showRateLimitWarning();
|
|
127
|
+
* }
|
|
128
|
+
* };
|
|
129
|
+
*
|
|
130
|
+
* // Access the selected state (will be empty object {} unless selector provided)
|
|
131
|
+
* const { executionCount, rejectionCount } = rateLimiter.state;
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
134
|
+
declare function useRateLimiter<TFn extends AnyFunction, TSelected = {}>(fn: TFn, options: RateLimiterOptions<TFn>, selector?: (state: RateLimiterState) => TSelected): PreactRateLimiter<TFn, TSelected>;
|
|
135
|
+
//#endregion
|
|
136
|
+
export { PreactRateLimiter, useRateLimiter };
|
|
137
|
+
//# sourceMappingURL=useRateLimiter.d.cts.map
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { Store } from "@tanstack/preact-store";
|
|
2
|
+
import { RateLimiter, RateLimiterOptions, RateLimiterState } from "@tanstack/pacer/rate-limiter";
|
|
3
|
+
import { AnyFunction } from "@tanstack/pacer/types";
|
|
4
|
+
|
|
5
|
+
//#region src/rate-limiter/useRateLimiter.d.ts
|
|
6
|
+
interface PreactRateLimiter<TFn extends AnyFunction, TSelected = {}> extends Omit<RateLimiter<TFn>, 'store'> {
|
|
7
|
+
/**
|
|
8
|
+
* Reactive state that will be updated and re-rendered when the rate limiter state changes
|
|
9
|
+
*
|
|
10
|
+
* Use this instead of `rateLimiter.store.state`
|
|
11
|
+
*/
|
|
12
|
+
readonly state: Readonly<TSelected>;
|
|
13
|
+
/**
|
|
14
|
+
* @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.
|
|
15
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
|
|
16
|
+
* Although, you can make the state reactive by using the `useStore` in your own usage.
|
|
17
|
+
*/
|
|
18
|
+
readonly store: Store<Readonly<RateLimiterState>>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A low-level Preact hook that creates a `RateLimiter` instance to enforce rate limits on function execution.
|
|
22
|
+
*
|
|
23
|
+
* This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that
|
|
24
|
+
* you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
|
|
25
|
+
*
|
|
26
|
+
* Rate limiting is a simple "hard limit" approach that allows executions until a maximum count is reached within
|
|
27
|
+
* a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,
|
|
28
|
+
* it does not attempt to space out or collapse executions intelligently.
|
|
29
|
+
*
|
|
30
|
+
* The rate limiter supports two types of windows:
|
|
31
|
+
* - 'fixed': A strict window that resets after the window period. All executions within the window count
|
|
32
|
+
* towards the limit, and the window resets completely after the period.
|
|
33
|
+
* - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
|
|
34
|
+
* consistent rate of execution over time.
|
|
35
|
+
*
|
|
36
|
+
* For smoother execution patterns:
|
|
37
|
+
* - Use throttling when you want consistent spacing between executions (e.g. UI updates)
|
|
38
|
+
* - Use debouncing when you want to collapse rapid-fire events (e.g. search input)
|
|
39
|
+
* - Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)
|
|
40
|
+
*
|
|
41
|
+
* ## State Management and Selector
|
|
42
|
+
*
|
|
43
|
+
* The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
|
|
44
|
+
* to specify which state changes will trigger a re-render, optimizing performance by preventing
|
|
45
|
+
* unnecessary re-renders when irrelevant state changes occur.
|
|
46
|
+
*
|
|
47
|
+
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
48
|
+
* tracking by providing a selector function. This prevents unnecessary re-renders and gives you
|
|
49
|
+
* full control over when your component updates. Only when you provide a selector will the
|
|
50
|
+
* component re-render when the selected state values change.
|
|
51
|
+
*
|
|
52
|
+
* Available state properties:
|
|
53
|
+
* - `executionCount`: Number of function executions that have been completed
|
|
54
|
+
* - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations
|
|
55
|
+
* - `rejectionCount`: Number of function executions that have been rejected due to rate limiting
|
|
56
|
+
*
|
|
57
|
+
* The hook returns an object containing:
|
|
58
|
+
* - maybeExecute: The rate-limited function that respects the configured limits
|
|
59
|
+
* - getExecutionCount: Returns the number of successful executions
|
|
60
|
+
* - getRejectionCount: Returns the number of rejected executions due to rate limiting
|
|
61
|
+
* - getRemainingInWindow: Returns how many more executions are allowed in the current window
|
|
62
|
+
* - reset: Resets the execution counts and window timing
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```tsx
|
|
66
|
+
* // Default behavior - no reactive state subscriptions
|
|
67
|
+
* const rateLimiter = useRateLimiter(apiCall, {
|
|
68
|
+
* limit: 5,
|
|
69
|
+
* window: 60000,
|
|
70
|
+
* windowType: 'sliding',
|
|
71
|
+
* });
|
|
72
|
+
*
|
|
73
|
+
* // Opt-in to re-render when execution count changes (optimized for tracking successful executions)
|
|
74
|
+
* const rateLimiter = useRateLimiter(
|
|
75
|
+
* apiCall,
|
|
76
|
+
* {
|
|
77
|
+
* limit: 5,
|
|
78
|
+
* window: 60000,
|
|
79
|
+
* windowType: 'sliding',
|
|
80
|
+
* },
|
|
81
|
+
* (state) => ({ executionCount: state.executionCount })
|
|
82
|
+
* );
|
|
83
|
+
*
|
|
84
|
+
* // Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)
|
|
85
|
+
* const rateLimiter = useRateLimiter(
|
|
86
|
+
* apiCall,
|
|
87
|
+
* {
|
|
88
|
+
* limit: 5,
|
|
89
|
+
* window: 60000,
|
|
90
|
+
* windowType: 'sliding',
|
|
91
|
+
* },
|
|
92
|
+
* (state) => ({ rejectionCount: state.rejectionCount })
|
|
93
|
+
* );
|
|
94
|
+
*
|
|
95
|
+
* // Opt-in to re-render when execution times change (optimized for window calculations)
|
|
96
|
+
* const rateLimiter = useRateLimiter(
|
|
97
|
+
* apiCall,
|
|
98
|
+
* {
|
|
99
|
+
* limit: 5,
|
|
100
|
+
* window: 60000,
|
|
101
|
+
* windowType: 'sliding',
|
|
102
|
+
* },
|
|
103
|
+
* (state) => ({ executionTimes: state.executionTimes })
|
|
104
|
+
* );
|
|
105
|
+
*
|
|
106
|
+
* // Multiple state properties - re-render when any of these change
|
|
107
|
+
* const rateLimiter = useRateLimiter(
|
|
108
|
+
* apiCall,
|
|
109
|
+
* {
|
|
110
|
+
* limit: 5,
|
|
111
|
+
* window: 60000,
|
|
112
|
+
* windowType: 'sliding',
|
|
113
|
+
* },
|
|
114
|
+
* (state) => ({
|
|
115
|
+
* executionCount: state.executionCount,
|
|
116
|
+
* rejectionCount: state.rejectionCount
|
|
117
|
+
* })
|
|
118
|
+
* );
|
|
119
|
+
*
|
|
120
|
+
* // Monitor rate limit status
|
|
121
|
+
* const handleClick = () => {
|
|
122
|
+
* const remaining = rateLimiter.getRemainingInWindow();
|
|
123
|
+
* if (remaining > 0) {
|
|
124
|
+
* rateLimiter.maybeExecute(data);
|
|
125
|
+
* } else {
|
|
126
|
+
* showRateLimitWarning();
|
|
127
|
+
* }
|
|
128
|
+
* };
|
|
129
|
+
*
|
|
130
|
+
* // Access the selected state (will be empty object {} unless selector provided)
|
|
131
|
+
* const { executionCount, rejectionCount } = rateLimiter.state;
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
134
|
+
declare function useRateLimiter<TFn extends AnyFunction, TSelected = {}>(fn: TFn, options: RateLimiterOptions<TFn>, selector?: (state: RateLimiterState) => TSelected): PreactRateLimiter<TFn, TSelected>;
|
|
135
|
+
//#endregion
|
|
136
|
+
export { PreactRateLimiter, useRateLimiter };
|
|
137
|
+
//# sourceMappingURL=useRateLimiter.d.ts.map
|