@oxog/cachekeeper 1.0.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/CHANGELOG.md +80 -0
- package/LICENSE +21 -0
- package/README.md +298 -0
- package/dist/chunk-2NFW4LZU.cjs +2 -0
- package/dist/chunk-2NFW4LZU.cjs.map +1 -0
- package/dist/chunk-CCPC3U3G.js +2 -0
- package/dist/chunk-CCPC3U3G.js.map +1 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +35 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/plugins.cjs +2 -0
- package/dist/plugins.cjs.map +1 -0
- package/dist/plugins.d.cts +126 -0
- package/dist/plugins.d.ts +126 -0
- package/dist/plugins.js +2 -0
- package/dist/plugins.js.map +1 -0
- package/dist/react.cjs +2 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.d.cts +221 -0
- package/dist/react.d.ts +221 -0
- package/dist/react.js +2 -0
- package/dist/react.js.map +1 -0
- package/dist/storage.cjs +2 -0
- package/dist/storage.cjs.map +1 -0
- package/dist/storage.d.cts +119 -0
- package/dist/storage.d.ts +119 -0
- package/dist/storage.js +2 -0
- package/dist/storage.js.map +1 -0
- package/dist/types-B0XHVTZf.d.cts +417 -0
- package/dist/types-B0XHVTZf.d.ts +417 -0
- package/package.json +129 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [1.0.0] - 2025-12-29
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- Initial release of CacheKeeper
|
|
13
|
+
- Core cache functionality with full TypeScript support
|
|
14
|
+
- Multiple eviction strategies:
|
|
15
|
+
- LRU (Least Recently Used)
|
|
16
|
+
- LFU (Least Frequently Used)
|
|
17
|
+
- FIFO (First In First Out)
|
|
18
|
+
- TTL (Time To Live only)
|
|
19
|
+
- SWR (Stale-While-Revalidate)
|
|
20
|
+
- Custom strategy support
|
|
21
|
+
- Storage adapters:
|
|
22
|
+
- Memory storage (default)
|
|
23
|
+
- localStorage adapter
|
|
24
|
+
- sessionStorage adapter
|
|
25
|
+
- IndexedDB adapter
|
|
26
|
+
- Custom adapter interface
|
|
27
|
+
- TTL and expiration:
|
|
28
|
+
- Per-entry TTL configuration
|
|
29
|
+
- Automatic expiration checking
|
|
30
|
+
- Manual expiration (touch, expire)
|
|
31
|
+
- Sliding expiration support
|
|
32
|
+
- Namespace system:
|
|
33
|
+
- Hierarchical namespaces
|
|
34
|
+
- Namespace isolation
|
|
35
|
+
- Nested namespace support
|
|
36
|
+
- Tag system:
|
|
37
|
+
- Tag-based entry grouping
|
|
38
|
+
- Tag-based invalidation
|
|
39
|
+
- Multiple tag support
|
|
40
|
+
- Memoization:
|
|
41
|
+
- getOrSet for lazy computation
|
|
42
|
+
- Function memoization wrapper
|
|
43
|
+
- Custom key generators
|
|
44
|
+
- Async function support
|
|
45
|
+
- Batch operations:
|
|
46
|
+
- getMany
|
|
47
|
+
- setMany
|
|
48
|
+
- deleteMany
|
|
49
|
+
- hasMany
|
|
50
|
+
- getOrSetMany
|
|
51
|
+
- Event system:
|
|
52
|
+
- hit, miss, set, delete events
|
|
53
|
+
- expire, evict, clear, prune events
|
|
54
|
+
- Subscribe/unsubscribe support
|
|
55
|
+
- Statistics:
|
|
56
|
+
- Hit/miss counting
|
|
57
|
+
- Hit rate calculation
|
|
58
|
+
- Memory usage tracking
|
|
59
|
+
- Uptime tracking
|
|
60
|
+
- Plugins:
|
|
61
|
+
- Plugin lifecycle hooks
|
|
62
|
+
- Compression plugin
|
|
63
|
+
- Logging plugin
|
|
64
|
+
- Encryption plugin
|
|
65
|
+
- Tiered cache plugin
|
|
66
|
+
- React adapter:
|
|
67
|
+
- CacheProvider component
|
|
68
|
+
- useCache hook
|
|
69
|
+
- useCachedValue hook
|
|
70
|
+
- useCachedQuery hook
|
|
71
|
+
- useCacheInvalidation hook
|
|
72
|
+
- useCacheStats hook
|
|
73
|
+
- withCache HOC
|
|
74
|
+
- Serialization:
|
|
75
|
+
- dump() for state export
|
|
76
|
+
- restore() for state import
|
|
77
|
+
- Custom serializer support
|
|
78
|
+
- Zero runtime dependencies
|
|
79
|
+
- Full TypeScript support with strict mode
|
|
80
|
+
- Comprehensive test suite
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Ersin KOC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
# CacheKeeper
|
|
2
|
+
|
|
3
|
+
<div align="center">
|
|
4
|
+
<h3>Zero-dependency caching toolkit with multiple strategies</h3>
|
|
5
|
+
<p>
|
|
6
|
+
<a href="https://cachekeeper.oxog.dev">Documentation</a> •
|
|
7
|
+
<a href="https://cachekeeper.oxog.dev/docs/getting-started">Getting Started</a> •
|
|
8
|
+
<a href="https://cachekeeper.oxog.dev/examples">Examples</a>
|
|
9
|
+
</p>
|
|
10
|
+
</div>
|
|
11
|
+
|
|
12
|
+
<div align="center">
|
|
13
|
+
|
|
14
|
+
[](https://www.npmjs.com/package/@oxog/cachekeeper)
|
|
15
|
+
[](https://bundlephobia.com/package/@oxog/cachekeeper)
|
|
16
|
+
[](LICENSE)
|
|
17
|
+
|
|
18
|
+
</div>
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## Features
|
|
23
|
+
|
|
24
|
+
- **Multiple Strategies** - LRU, LFU, FIFO, TTL, SWR
|
|
25
|
+
- **TTL Support** - Automatic expiration with configurable intervals
|
|
26
|
+
- **Namespaces** - Organized cache groups with hierarchical structure
|
|
27
|
+
- **Tags** - Tag-based invalidation for flexible cache management
|
|
28
|
+
- **SWR** - Stale-while-revalidate pattern for optimal UX
|
|
29
|
+
- **Statistics** - Hit rate, memory usage, and performance metrics
|
|
30
|
+
- **Storage** - Memory, localStorage, sessionStorage, IndexedDB
|
|
31
|
+
- **React Adapter** - Hooks & components for seamless React integration
|
|
32
|
+
- **Zero Dependencies** - Lightweight with no external dependencies
|
|
33
|
+
- **< 4KB** - Tiny bundle size, fully tree-shakeable
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npm install @oxog/cachekeeper
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
yarn add @oxog/cachekeeper
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pnpm add @oxog/cachekeeper
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Quick Start
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
import { createCache } from '@oxog/cachekeeper'
|
|
53
|
+
|
|
54
|
+
// Create a cache with LRU strategy
|
|
55
|
+
const cache = createCache({
|
|
56
|
+
strategy: 'lru',
|
|
57
|
+
maxSize: 1000,
|
|
58
|
+
ttl: 5 * 60 * 1000, // 5 minutes
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
// Basic operations
|
|
62
|
+
cache.set('user:1', { name: 'Alice', email: 'alice@example.com' })
|
|
63
|
+
const user = cache.get('user:1')
|
|
64
|
+
|
|
65
|
+
// With TTL
|
|
66
|
+
cache.set('session', sessionData, { ttl: 3600000 }) // 1 hour
|
|
67
|
+
|
|
68
|
+
// With tags
|
|
69
|
+
cache.set('product:1', productData, {
|
|
70
|
+
tags: ['products', 'electronics'],
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
// Invalidate by tag
|
|
74
|
+
cache.invalidateByTag('products')
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Memoization
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
// Memoize expensive function
|
|
81
|
+
const fetchUser = cache.memoize(
|
|
82
|
+
async (userId: string) => {
|
|
83
|
+
const response = await fetch(`/api/users/${userId}`)
|
|
84
|
+
return response.json()
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
keyGenerator: (userId) => `user:${userId}`,
|
|
88
|
+
ttl: 60000,
|
|
89
|
+
tags: ['users'],
|
|
90
|
+
}
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
// First call: fetches from API
|
|
94
|
+
const user = await fetchUser('123')
|
|
95
|
+
|
|
96
|
+
// Second call: returns cached result
|
|
97
|
+
const cachedUser = await fetchUser('123')
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Namespaces
|
|
101
|
+
|
|
102
|
+
```typescript
|
|
103
|
+
// Create namespaces for organization
|
|
104
|
+
const userCache = cache.namespace('user')
|
|
105
|
+
const productCache = cache.namespace('product')
|
|
106
|
+
|
|
107
|
+
userCache.set('1', { name: 'Alice' })
|
|
108
|
+
productCache.set('1', { name: 'Widget' })
|
|
109
|
+
|
|
110
|
+
// Clear only user namespace
|
|
111
|
+
userCache.clear()
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## Stale-While-Revalidate
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
const cache = createCache({
|
|
118
|
+
strategy: 'swr',
|
|
119
|
+
staleTime: 60000, // Fresh for 1 min
|
|
120
|
+
revalidateTime: 300000, // Expire after 5 min
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
// Returns stale data immediately while revalidating in background
|
|
124
|
+
const data = await cache.getOrSet('api:data', fetchData)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## React Integration
|
|
128
|
+
|
|
129
|
+
```tsx
|
|
130
|
+
import { CacheProvider, useCachedQuery } from '@oxog/cachekeeper/react'
|
|
131
|
+
import { createCache } from '@oxog/cachekeeper'
|
|
132
|
+
|
|
133
|
+
const cache = createCache({
|
|
134
|
+
strategy: 'lru',
|
|
135
|
+
maxSize: 1000,
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
function App() {
|
|
139
|
+
return (
|
|
140
|
+
<CacheProvider cache={cache}>
|
|
141
|
+
<Products />
|
|
142
|
+
</CacheProvider>
|
|
143
|
+
)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function Products() {
|
|
147
|
+
const { data, isLoading, error, mutate } = useCachedQuery(
|
|
148
|
+
'products',
|
|
149
|
+
fetchProducts,
|
|
150
|
+
{
|
|
151
|
+
ttl: 300000,
|
|
152
|
+
revalidateOnFocus: true,
|
|
153
|
+
}
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
if (isLoading) return <Spinner />
|
|
157
|
+
if (error) return <Error error={error} />
|
|
158
|
+
|
|
159
|
+
return <ProductList products={data} />
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## Cache Strategies
|
|
164
|
+
|
|
165
|
+
| Strategy | Description | Best For |
|
|
166
|
+
|----------|-------------|----------|
|
|
167
|
+
| **LRU** | Least Recently Used | General purpose caching |
|
|
168
|
+
| **LFU** | Least Frequently Used | Hot/cold data patterns |
|
|
169
|
+
| **FIFO** | First In First Out | Queue-like patterns |
|
|
170
|
+
| **TTL** | Time-based expiration only | Session data, tokens |
|
|
171
|
+
| **SWR** | Stale-While-Revalidate | API responses |
|
|
172
|
+
|
|
173
|
+
## Storage Backends
|
|
174
|
+
|
|
175
|
+
```typescript
|
|
176
|
+
// Memory (default)
|
|
177
|
+
const memoryCache = createCache({ storage: 'memory' })
|
|
178
|
+
|
|
179
|
+
// localStorage (persistent)
|
|
180
|
+
const localCache = createCache({
|
|
181
|
+
storage: 'local',
|
|
182
|
+
storageKey: 'my-app-cache',
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
// sessionStorage
|
|
186
|
+
const sessionCache = createCache({
|
|
187
|
+
storage: 'session',
|
|
188
|
+
storageKey: 'my-app-cache',
|
|
189
|
+
})
|
|
190
|
+
|
|
191
|
+
// IndexedDB (for large data)
|
|
192
|
+
import { indexedDBStorage } from '@oxog/cachekeeper/storage'
|
|
193
|
+
|
|
194
|
+
const idbCache = createCache({
|
|
195
|
+
storage: indexedDBStorage({
|
|
196
|
+
dbName: 'my-cache-db',
|
|
197
|
+
storeName: 'cache',
|
|
198
|
+
}),
|
|
199
|
+
})
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
## Plugins
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
import { compressionPlugin, loggingPlugin } from '@oxog/cachekeeper/plugins'
|
|
206
|
+
|
|
207
|
+
const cache = createCache({
|
|
208
|
+
plugins: [
|
|
209
|
+
compressionPlugin({ threshold: 1024 }),
|
|
210
|
+
loggingPlugin({ level: 'debug' }),
|
|
211
|
+
],
|
|
212
|
+
})
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
## Statistics
|
|
216
|
+
|
|
217
|
+
```typescript
|
|
218
|
+
const stats = cache.getStats()
|
|
219
|
+
|
|
220
|
+
console.log({
|
|
221
|
+
hitRate: stats.hitRate, // 0.85 (85%)
|
|
222
|
+
size: stats.size, // 150 entries
|
|
223
|
+
memoryUsage: stats.memoryUsage, // bytes
|
|
224
|
+
uptime: stats.uptime, // ms
|
|
225
|
+
})
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## API Reference
|
|
229
|
+
|
|
230
|
+
### createCache(config?)
|
|
231
|
+
|
|
232
|
+
Creates a new cache instance.
|
|
233
|
+
|
|
234
|
+
```typescript
|
|
235
|
+
const cache = createCache({
|
|
236
|
+
strategy: 'lru', // 'lru' | 'lfu' | 'fifo' | 'ttl' | 'swr' | CustomStrategy
|
|
237
|
+
maxSize: 1000, // Maximum number of entries
|
|
238
|
+
maxMemory: 50 * 1024 * 1024, // Max memory in bytes
|
|
239
|
+
ttl: 300000, // Default TTL in ms
|
|
240
|
+
checkInterval: 60000, // Expiration check interval
|
|
241
|
+
storage: 'memory', // 'memory' | 'local' | 'session' | StorageAdapter
|
|
242
|
+
storageKey: 'cache', // Prefix for storage keys
|
|
243
|
+
plugins: [], // Array of plugins
|
|
244
|
+
})
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
### CacheInstance Methods
|
|
248
|
+
|
|
249
|
+
| Method | Description |
|
|
250
|
+
|--------|-------------|
|
|
251
|
+
| `get(key)` | Get a value |
|
|
252
|
+
| `set(key, value, options?)` | Set a value |
|
|
253
|
+
| `has(key)` | Check if key exists |
|
|
254
|
+
| `delete(key)` | Delete a key |
|
|
255
|
+
| `clear()` | Clear all entries |
|
|
256
|
+
| `getTTL(key)` | Get remaining TTL |
|
|
257
|
+
| `setTTL(key, ttl)` | Update TTL |
|
|
258
|
+
| `touch(key)` | Refresh TTL |
|
|
259
|
+
| `namespace(name)` | Get/create namespace |
|
|
260
|
+
| `invalidateByTag(tag)` | Invalidate by tag |
|
|
261
|
+
| `getOrSet(key, factory)` | Get or compute value |
|
|
262
|
+
| `memoize(fn, options)` | Memoize a function |
|
|
263
|
+
| `getStats()` | Get statistics |
|
|
264
|
+
| `dump()` | Export cache state |
|
|
265
|
+
| `restore(dump)` | Import cache state |
|
|
266
|
+
|
|
267
|
+
## TypeScript Support
|
|
268
|
+
|
|
269
|
+
CacheKeeper is written in TypeScript and provides full type definitions.
|
|
270
|
+
|
|
271
|
+
```typescript
|
|
272
|
+
interface User {
|
|
273
|
+
id: string
|
|
274
|
+
name: string
|
|
275
|
+
email: string
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const cache = createCache<User>()
|
|
279
|
+
|
|
280
|
+
cache.set('user:1', { id: '1', name: 'Alice', email: 'alice@example.com' })
|
|
281
|
+
|
|
282
|
+
const user = cache.get('user:1') // User | undefined
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
## Browser Support
|
|
286
|
+
|
|
287
|
+
- Chrome 90+
|
|
288
|
+
- Firefox 90+
|
|
289
|
+
- Safari 14+
|
|
290
|
+
- Edge 90+
|
|
291
|
+
|
|
292
|
+
## Documentation
|
|
293
|
+
|
|
294
|
+
Visit [cachekeeper.oxog.dev](https://cachekeeper.oxog.dev) for full documentation.
|
|
295
|
+
|
|
296
|
+
## License
|
|
297
|
+
|
|
298
|
+
MIT © [Ersin KOC](https://github.com/ersinkoc)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';function u(){return Date.now()}function M(n){return n===void 0?false:u()>=n}function y(n){if(!(n===void 0||n<=0))return u()+n}function I(n){if(!(n===void 0||n<=0))return u()+n}function D(n){if(n===void 0)return;let e=n-u();return e>0?e:0}function B(n){return n===void 0?null:new Date(n)}function f(n){if(n==null)return 0;switch(typeof n){case "boolean":return 4;case "number":return 8;case "string":return n.length*2;case "bigint":return n.toString().length*2+8;case "symbol":return (n.description?.length??0)*2+8;case "function":return 32;case "object":return J(n);default:return 0}}function J(n){if(n===null)return 0;if(Array.isArray(n)){let s=8;for(let i of n)s+=f(i);return s}if(n instanceof Date)return 8;if(n instanceof RegExp)return n.source.length*2+16;if(n instanceof Map){let s=16;return n.forEach((i,a)=>{s+=f(a)+f(i);}),s}if(n instanceof Set){let s=16;return n.forEach(i=>{s+=f(i);}),s}if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return n.byteLength;if(n instanceof WeakMap||n instanceof WeakSet)return 16;if(n instanceof Error)return (n.message?.length??0)*2+(n.stack?.length??0)*2+32;let e=8,t=new WeakSet;function r(s){if(t.has(s))return 0;t.add(s);let i=0;for(let a in s)if(Object.prototype.hasOwnProperty.call(s,a)){i+=a.length*2;let o=s[a];o!==null&&typeof o=="object"?i+=r(o):i+=f(o);}return i}return e+=r(n),e}function Q(n){if(n===0)return "0 B";let e=["B","KB","MB","GB","TB"],t=1024,r=Math.floor(Math.log(n)/Math.log(t)),s=Math.min(r,e.length-1),i=e[s];return i===void 0?`${n} B`:`${parseFloat((n/Math.pow(t,s)).toFixed(2))} ${i}`}var T=class{name="lru";shouldEvict(e,t,r){if(e.length<t)return [];let s=[...e].sort((a,o)=>a.accessedAt-o.accessedAt),i=Math.max(1,e.length-t+1);return s.slice(0,i).map(a=>a.key)}onAccess(e){}};function v(){return new T}var E=class{name="lfu";shouldEvict(e,t,r){if(e.length<t)return [];let s=[...e].sort((a,o)=>a.accessCount!==o.accessCount?a.accessCount-o.accessCount:a.accessedAt-o.accessedAt),i=Math.max(1,e.length-t+1);return s.slice(0,i).map(a=>a.key)}onAccess(e){}};function N(){return new E}var x=class{name="fifo";shouldEvict(e,t,r){if(e.length<t)return [];let s=[...e].sort((a,o)=>a.createdAt-o.createdAt),i=Math.max(1,e.length-t+1);return s.slice(0,i).map(a=>a.key)}};function O(){return new x}var S=class{name="ttl";shouldEvict(e,t,r){let s=u();return e.filter(i=>i.expiresAt!==void 0&&i.expiresAt<=s).map(i=>i.key)}};function L(){return new S}var _=class{name="swr";shouldEvict(e,t,r){if(e.length<t)return [];let s=u(),i=e.filter(c=>c.expiresAt!==void 0&&c.expiresAt<=s),a=Math.max(1,e.length-t+1);if(i.length>=a)return i.slice(0,a).map(c=>c.key);let o=i.map(c=>c.key),h=new Set(o),g=[...e.filter(c=>!h.has(c.key))].sort((c,d)=>c.accessedAt-d.accessedAt),m=a-i.length,p=g.slice(0,m).map(c=>c.key);return [...o,...p]}onAccess(e){}};function F(){return new _}function K(n){if(n.staleAt===void 0)return false;let e=u();return e>=n.staleAt&&(n.expiresAt===void 0||e<n.expiresAt)}function z(n){return n.staleAt===void 0?n.expiresAt===void 0?true:u()<n.expiresAt:u()<n.staleAt}function U(n){if(!n)return v();if(typeof n=="object")return {name:"custom",shouldEvict:n.shouldEvict,onAccess:n.onAccess,onSet:n.onSet};switch(n){case "lru":return v();case "lfu":return N();case "fifo":return O();case "ttl":return L();case "swr":return F();default:return v()}}function R(n){return n?typeof n=="object"?"custom":n:"lru"}var C=class{listeners=new Map;on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){let r=this.listeners.get(e);r&&(r.delete(t),r.size===0&&this.listeners.delete(e));}once(e,t){let r=s=>{this.off(e,r),t(s);};this.on(e,r);}emit(e,t){let r=this.listeners.get(e);r&&r.forEach(s=>{try{s(t);}catch(i){console.error(`Error in event handler for "${e}":`,i);}});}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear();}listenerCount(e){return this.listeners.get(e)?.size??0}hasListeners(e){return this.listenerCount(e)>0}eventNames(){return Array.from(this.listeners.keys())}};function $(n,e,t,r,s){let i=u(),a=t?.ttl??r,o=t?.stale??s,h=t?.revalidate?y(t.revalidate):y(a),l=I(o);return {key:n,value:e,createdAt:i,updatedAt:i,accessedAt:i,accessCount:0,size:f(e),ttl:a,expiresAt:h,staleAt:l,tags:t?.tags??[],namespace:t?.metadata?.namespace,metadata:t?.metadata}}function W(n,e,t,r){let s=u(),i=t?.ttl??n.ttl??r,a=t?.revalidate?y(t.revalidate):y(i),o=t?.stale?I(t.stale):n.staleAt,h=t?.tags??[],l=n.tags,g=[...new Set([...l,...h])];return {...n,value:e,updatedAt:s,accessedAt:s,size:f(e),ttl:i,expiresAt:a,staleAt:o,tags:g,metadata:t?.metadata?{...n.metadata,...t.metadata}:n.metadata}}function G(n){let e=u(),t=n.ttl?e+n.ttl:n.expiresAt,r=n.staleAt?e+(n.staleAt-n.createdAt):void 0;return {...n,accessedAt:e,accessCount:n.accessCount+1,expiresAt:t,staleAt:r}}function H(n){return {...n,accessedAt:u(),accessCount:n.accessCount+1}}var A=class{_hits=0;_misses=0;_sets=0;_deletes=0;_evictions=0;_expirations=0;startTime;constructor(){this.startTime=u();}recordHit(){this._hits++;}recordMiss(){this._misses++;}recordSet(){this._sets++;}recordDelete(){this._deletes++;}recordEviction(){this._evictions++;}recordExpiration(){this._expirations++;}get hits(){return this._hits}get misses(){return this._misses}get hitRate(){let e=this._hits+this._misses;return e===0?0:this._hits/e}get sets(){return this._sets}get deletes(){return this._deletes}get evictions(){return this._evictions}get expirations(){return this._expirations}get uptime(){return u()-this.startTime}reset(){this._hits=0,this._misses=0,this._sets=0,this._deletes=0,this._evictions=0,this._expirations=0,this.startTime=u();}getStats(e,t,r){let s=Array.from(e.values()),i=s.reduce((c,d)=>c+d.size,0),a,o,h=1/0,l=0,g=0,m=0,p=new Set;for(let c of s){c.createdAt<h&&(h=c.createdAt,a=c.key),c.createdAt>l&&(l=c.createdAt,o=c.key),c.ttl!==void 0&&(g+=c.ttl,m++),c.namespace&&p.add(c.namespace);let d=c.key.indexOf(":");d>0&&p.add(c.key.slice(0,d));}return {hits:this._hits,misses:this._misses,hitRate:this.hitRate,sets:this._sets,deletes:this._deletes,evictions:this._evictions,expirations:this._expirations,size:e.size,maxSize:t,memoryUsage:i,maxMemory:r,namespaces:Array.from(p),oldestEntry:a,newestEntry:o,avgTTL:m>0?g/m:void 0,uptime:this.uptime}}};var b=class{tagToKeys=new Map;keyToTags=new Map;setTags(e,t){if(this.removeKey(e),t.length===0)return;let r=new Set(t);this.keyToTags.set(e,r);for(let s of r)this.tagToKeys.has(s)||this.tagToKeys.set(s,new Set),this.tagToKeys.get(s).add(e);}getTags(e){let t=this.keyToTags.get(e);return t?Array.from(t):[]}addTags(e,t){let r=this.keyToTags.get(e)??new Set;for(let s of t)r.has(s)||(r.add(s),this.tagToKeys.has(s)||this.tagToKeys.set(s,new Set),this.tagToKeys.get(s).add(e));this.keyToTags.set(e,r);}removeTags(e,t){let r=this.keyToTags.get(e);if(r){for(let s of t){r.delete(s);let i=this.tagToKeys.get(s);i&&(i.delete(e),i.size===0&&this.tagToKeys.delete(s));}r.size===0&&this.keyToTags.delete(e);}}removeKey(e){let t=this.keyToTags.get(e);if(t){for(let r of t){let s=this.tagToKeys.get(r);s&&(s.delete(e),s.size===0&&this.tagToKeys.delete(r));}this.keyToTags.delete(e);}}getKeysByTag(e){let t=this.tagToKeys.get(e);return t?Array.from(t):[]}getKeysByTags(e){if(e.length===0)return [];if(e.length===1)return this.getKeysByTag(e[0]);let t=e[0],r=this.tagToKeys.get(t);if(!r||r.size===0)return [];let s=new Set(r);for(let i=1;i<e.length;i++){let a=e[i],o=this.tagToKeys.get(a);if(!o)return [];for(let h of s)o.has(h)||s.delete(h);if(s.size===0)return []}return Array.from(s)}getKeysByAnyTag(e){let t=new Set;for(let r of e){let s=this.tagToKeys.get(r);if(s)for(let i of s)t.add(i);}return Array.from(t)}hasTag(e,t){let r=this.keyToTags.get(e);return r?r.has(t):false}getAllTags(){return Array.from(this.tagToKeys.keys())}clear(){this.tagToKeys.clear(),this.keyToTags.clear();}};var w=class n{cache;_name;parentPath;constructor(e,t,r=""){this.cache=e,this._name=t,this.parentPath=r;}get name(){return this._name}get fullPath(){return this.parentPath?`${this.parentPath}:${this._name}`:this._name}prefixKey(e){return `${this.fullPath}:${e}`}get(e,t){let r=this.cache.get(this.prefixKey(e));return r!==void 0?r:t}set(e,t,r){this.cache.set(this.prefixKey(e),t,{...r,metadata:{...r?.metadata,namespace:this.fullPath}});}has(e){return this.cache.has(this.prefixKey(e))}delete(e){return this.cache.delete(this.prefixKey(e))}clear(){let e=`${this.fullPath}:`;this.cache.keys().filter(r=>r.startsWith(e)).forEach(r=>this.cache.delete(r));}keys(){let e=`${this.fullPath}:`;return this.cache.keys().filter(t=>t.startsWith(e)).map(t=>t.slice(e.length))}values(){let e=`${this.fullPath}:`;return this.cache.entries().filter(([t])=>t.startsWith(e)).map(([t,r])=>r)}entries(){let e=`${this.fullPath}:`;return this.cache.entries().filter(([t])=>t.startsWith(e)).map(([t,r])=>[t.slice(e.length),r])}get size(){return this.keys().length}namespace(e){return new n(this.cache,e,this.fullPath)}getStats(){let e=this.cache.getStats(),t=this.size;return {...e,size:t,namespaces:e.namespaces.filter(r=>r.startsWith(this.fullPath))}}};function k(n){return typeof n=="string"&&n.length>0}function V(n){return n.length===0?"__memoize_no_args__":n.map(e=>{if(e===null)return "null";if(e===void 0)return "undefined";let t=typeof e;if(t==="string"||t==="number"||t==="boolean")return String(e);if(t==="object")try{return JSON.stringify(e)}catch{return "[object]"}return String(e)}).join(":")}var X=1e3,Z=6e4,P=class{constructor(e={}){this.config=e;this._maxSize=e.maxSize??X,this._maxMemory=e.maxMemory,this._defaultTTL=e.ttl,this._defaultStaleTime=e.staleTime,this._checkInterval=e.checkInterval??Z,this.strategy=U(e.strategy),e.plugins&&(this.plugins=e.plugins,this.plugins.forEach(t=>t.onInit?.(this))),this.setupEventCallbacks(),(this._defaultTTL||this._checkInterval)&&this._checkInterval!==0&&this.startExpirationChecker();}_entries=new Map;strategy;emitter=new C;stats=new A;tagIndex=new b;namespaceRegistry=new Map;plugins=[];_maxSize;_maxMemory;_defaultTTL;_defaultStaleTime;_checkInterval;expirationTimer=null;destroyed=false;setupEventCallbacks(){this.config.onHit&&this.on("hit",this.config.onHit),this.config.onMiss&&this.on("miss",this.config.onMiss),this.config.onSet&&this.on("set",this.config.onSet),this.config.onDelete&&this.on("delete",this.config.onDelete),this.config.onExpire&&this.on("expire",this.config.onExpire),this.config.onEvict&&this.on("evict",this.config.onEvict),this.config.onClear&&this.on("clear",this.config.onClear);}startExpirationChecker(){this.expirationTimer||(this.expirationTimer=setInterval(()=>{this.prune();},this._checkInterval));}stopExpirationChecker(){this.expirationTimer&&(clearInterval(this.expirationTimer),this.expirationTimer=null);}get(e,t){if(this.ensureNotDestroyed(),!k(e))return t;this.plugins.forEach(a=>a.beforeGet?.(e));let r=this._entries.get(e);if(!r)return this.stats.recordMiss(),this.emitter.emit("miss",{key:e}),t;if(M(r.expiresAt))return this.deleteInternal(e,"expire"),this.stats.recordMiss(),this.emitter.emit("miss",{key:e}),t;let s=H(r);this._entries.set(e,s),this.strategy.onAccess?.(s),this.stats.recordHit(),this.emitter.emit("hit",{key:e,value:s.value,entry:s});let i=s.value;for(let a of this.plugins)i=a.afterGet?.(e,i)??i;return i}set(e,t,r){if(this.ensureNotDestroyed(),!k(e))throw new Error("Invalid cache key: key must be a non-empty string");let s=t,i=r;for(let l of this.plugins){let g=l.beforeSet?.(e,s,i);g&&(s=g.value,i=g.options);}let a=this._entries.get(e),o=a!==void 0,h=o?W(a,s,i,this._defaultTTL):$(e,s,i,this._defaultTTL,this._defaultStaleTime);!o&&this._entries.size>=this._maxSize&&this.evict(),this._maxMemory&&this.enforceMemoryLimit(h.size),this._entries.set(e,h),this.strategy.onSet?.(h),h.tags.length>0&&this.tagIndex.setTags(e,h.tags),this.stats.recordSet(),this.emitter.emit("set",{key:e,value:h.value,entry:h,isUpdate:o}),this.plugins.forEach(l=>l.afterSet?.(e,h));}has(e){if(this.ensureNotDestroyed(),!k(e))return false;let t=this._entries.get(e);return t?M(t.expiresAt)?(this.deleteInternal(e,"expire"),false):true:false}delete(e){return this.ensureNotDestroyed(),Array.isArray(e)?this.deleteMany(e):this.deleteInternal(e,"manual")}deleteInternal(e,t){for(let s of this.plugins)if(s.beforeDelete?.(e)===false)return false;let r=this._entries.get(e);return r?(this._entries.delete(e),this.tagIndex.removeKey(e),this.stats.recordDelete(),t==="expire"&&(this.stats.recordExpiration(),this.emitter.emit("expire",{key:e,value:r.value,entry:r})),this.emitter.emit("delete",{key:e,value:r.value,reason:t}),this.plugins.forEach(s=>s.afterDelete?.(e,r.value)),true):false}clear(){this.ensureNotDestroyed();let e=this._entries.size;this._entries.clear(),this.tagIndex.clear(),this.emitter.emit("clear",{count:e});}get size(){return this._entries.size}get isEmpty(){return this._entries.size===0}get maxSize(){return this._maxSize}get memoryUsage(){let e=0;for(let t of this._entries.values())e+=t.size;return e}getTTL(e){let t=this._entries.get(e);if(t)return D(t.expiresAt)}setTTL(e,t){let r=this._entries.get(e);if(!r)return false;let s={...r,ttl:t,expiresAt:u()+t};return this._entries.set(e,s),true}touch(e){let t=this._entries.get(e);if(!t)return false;let r=G(t);return this._entries.set(e,r),true}expire(e){return this.deleteInternal(e,"expire")}getExpiration(e){let t=this._entries.get(e);return t?B(t.expiresAt):null}namespace(e){let t=this.namespaceRegistry.get(e);return t||(t=new w(this,e),this.namespaceRegistry.set(e,t)),t}getNamespace(e){return this.namespaceRegistry.get(e)}clearNamespace(e){let t=`${e}:`,r=this.keys().filter(s=>s.startsWith(t));return this.deleteMany(r)}listNamespaces(){let e=new Set;for(let t of this._entries.keys()){let r=t.indexOf(":");r>0&&e.add(t.slice(0,r));}return Array.from(e)}getTags(e){return this.tagIndex.getTags(e)}addTags(e,t){let r=this._entries.get(e);return r?(this.tagIndex.addTags(e,t),r.tags=[...new Set([...r.tags,...t])],true):false}removeTags(e,t){let r=this._entries.get(e);return r?(this.tagIndex.removeTags(e,t),r.tags=r.tags.filter(s=>!t.includes(s)),true):false}invalidateByTag(e){let t=Array.isArray(e)?e:[e];return this.tagIndex.getKeysByAnyTag(t).reduce((s,i)=>s+(this.deleteInternal(i,"tag")?1:0),0)}getKeysByTag(e){return Array.isArray(e)?this.tagIndex.getKeysByTags(e):this.tagIndex.getKeysByTag(e)}isStale(e){let t=this._entries.get(e);return t?K(t):false}isFresh(e){let t=this._entries.get(e);return t?z(t):false}async revalidate(e,t){let r=await Promise.resolve(t());return this.set(e,r),r}getOrSet(e,t,r){if(r?.forceRefresh){let a=t();return a instanceof Promise?a.then(o=>(this.set(e,o,r),o)):(this.set(e,a,r),a)}let s=this.get(e);if(s!==void 0)return this.isStale(e)&&Promise.resolve(t()).then(a=>{this.set(e,a,r);}).catch(()=>{}),s;let i=t();return i instanceof Promise?i.then(a=>(this.set(e,a,r),a)):(this.set(e,i,r),i)}memoize(e,t){let r=t?.keyGenerator;return (...s)=>{let i=r?r(...s):V(s),a=this.get(i);if(a!==void 0)return a;let o=e(...s);return o instanceof Promise?o.then(h=>(this.set(i,h,{ttl:t?.ttl,tags:t?.tags}),h)):(this.set(i,o,{ttl:t?.ttl,tags:t?.tags}),o)}}getMany(e){let t=new Map;for(let r of e){let s=this.get(r);s!==void 0&&t.set(r,s);}return t}setMany(e){for(let t of e)this.set(t.key,t.value,{ttl:t.ttl,tags:t.tags});}deleteMany(e){let t=0;for(let r of e)this.deleteInternal(r,"manual")&&t++;return t}hasMany(e){let t=new Map;for(let r of e)t.set(r,this.has(r));return t}async getOrSetMany(e,t,r){let s=new Map,i=[];for(let a of e){let o=this.get(a);o!==void 0?s.set(a,o):i.push(a);}if(i.length>0){let a=await Promise.resolve(t(i));for(let o of a)this.set(o.key,o.value,{ttl:o.ttl??r?.ttl,tags:o.tags??r?.tags}),s.set(o.key,o.value);}return s}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t);}once(e,t){this.emitter.once(e,t);}getStats(){return this.stats.getStats(this._entries,this._maxSize,this._maxMemory)}get hits(){return this.stats.hits}get misses(){return this.stats.misses}get hitRate(){return this.stats.hitRate}resetStats(){this.stats.reset();}keys(e){let t=Array.from(this._entries.keys());return e?t.filter(e):t}values(){return Array.from(this._entries.values()).map(e=>e.value)}entries(){return Array.from(this._entries.entries()).map(([e,t])=>[e,t.value])}forEach(e){this._entries.forEach((t,r)=>{e(t.value,r);});}find(e){for(let[t,r]of this._entries)if(e(r.value,t))return r.value}filter(e){let t=[];for(let[r,s]of this._entries)e(s.value,r)&&t.push([r,s.value]);return t}prune(){let e=u(),t=0;for(let[r,s]of this._entries)s.expiresAt!==void 0&&s.expiresAt<=e&&(this.deleteInternal(r,"expire"),t++);return t>0&&this.emitter.emit("prune",{count:t}),t}resize(e){if(e<1)throw new Error("maxSize must be at least 1");this._maxSize=e;let t=0;for(;this._entries.size>this._maxSize;){let i=[...Array.from(this._entries.values())].sort((a,o)=>a.accessedAt-o.accessedAt)[0]?.key;if(i){let a=this._entries.get(i);a&&(this._entries.delete(i),this.tagIndex.removeKey(i),this.stats.recordEviction(),this.emitter.emit("evict",{key:i,value:a.value,entry:a,strategy:R(this.config.strategy)}),this.emitter.emit("delete",{key:i,value:a.value,reason:"evict"}),t++);}else break}return t}evict(){let e=Array.from(this._entries.values()),t=this.strategy.shouldEvict(e,this._maxSize,{currentSize:this._entries.size,maxSize:this._maxSize,maxMemory:this._maxMemory,currentMemory:this.memoryUsage});for(let r of t){let s=this._entries.get(r);s&&(this._entries.delete(r),this.tagIndex.removeKey(r),this.stats.recordEviction(),this.emitter.emit("evict",{key:r,value:s.value,entry:s,strategy:R(this.config.strategy)}),this.emitter.emit("delete",{key:r,value:s.value,reason:"evict"}));}}enforceMemoryLimit(e){if(!this._maxMemory)return;let t=this.memoryUsage,r=this._maxMemory-e;if(t<=r)return;let s=Array.from(this._entries.entries()).sort(([,a],[,o])=>a.accessedAt-o.accessedAt),i=0;for(let[a,o]of s){if(t-i<=r)break;this._entries.delete(a),this.tagIndex.removeKey(a),this.stats.recordEviction(),this.emitter.emit("evict",{key:a,value:o.value,entry:o,strategy:"memory"}),i+=o.size;}}dump(){return {version:"1.0.0",createdAt:u(),entries:Array.from(this._entries.values()),stats:{hits:this.stats.hits,misses:this.stats.misses,sets:this.stats.sets,deletes:this.stats.deletes,evictions:this.stats.evictions,expirations:this.stats.expirations}}}restore(e){this.clear();let t=u();for(let r of e.entries)r.expiresAt!==void 0&&r.expiresAt<=t||(this._entries.set(r.key,r),r.tags.length>0&&this.tagIndex.setTags(r.key,r.tags));}destroy(){this.destroyed||(this.destroyed=true,this.stopExpirationChecker(),this.plugins.forEach(e=>e.onDestroy?.(this)),this._entries.clear(),this.tagIndex.clear(),this.namespaceRegistry.clear(),this.emitter.removeAllListeners());}getEntry(e){return this._entries.get(e)}ensureNotDestroyed(){if(this.destroyed)throw new Error("Cache has been destroyed")}[Symbol.iterator](){let e=this._entries.entries();return {next:()=>{let t=e.next();if(t.done)return {done:true,value:void 0};let[r,s]=t.value;return {done:false,value:[r,s.value]}}}}};function Me(n){return new P(n)}exports.a=u;exports.b=M;exports.c=D;exports.d=B;exports.e=f;exports.f=Q;exports.g=Me;//# sourceMappingURL=chunk-2NFW4LZU.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-2NFW4LZU.cjs.map
|