@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.
@@ -0,0 +1,417 @@
1
+ /**
2
+ * Built-in cache eviction strategies
3
+ */
4
+ type CacheStrategy = 'lru' | 'lfu' | 'fifo' | 'ttl' | 'swr';
5
+ /**
6
+ * Context provided during eviction decisions
7
+ */
8
+ interface EvictionContext {
9
+ currentSize: number;
10
+ maxSize: number;
11
+ maxMemory?: number;
12
+ currentMemory: number;
13
+ }
14
+ /**
15
+ * Custom eviction strategy interface
16
+ */
17
+ interface CustomStrategy<T = unknown> {
18
+ /**
19
+ * Determine which keys to evict when cache is full
20
+ */
21
+ shouldEvict: (entries: CacheEntry<T>[], maxSize: number, context: EvictionContext) => string[];
22
+ /**
23
+ * Called when an entry is accessed
24
+ */
25
+ onAccess?: (entry: CacheEntry<T>) => void;
26
+ /**
27
+ * Called when an entry is set
28
+ */
29
+ onSet?: (entry: CacheEntry<T>) => void;
30
+ }
31
+ /**
32
+ * Individual cache entry with metadata
33
+ */
34
+ interface CacheEntry<T = unknown> {
35
+ key: string;
36
+ value: T;
37
+ createdAt: number;
38
+ updatedAt: number;
39
+ accessedAt: number;
40
+ accessCount: number;
41
+ size: number;
42
+ ttl?: number;
43
+ expiresAt?: number;
44
+ staleAt?: number;
45
+ tags: string[];
46
+ namespace?: string;
47
+ metadata?: Record<string, unknown>;
48
+ }
49
+ /**
50
+ * Built-in storage types
51
+ */
52
+ type StorageType = 'memory' | 'local' | 'session';
53
+ /**
54
+ * Storage adapter interface for custom storage backends
55
+ */
56
+ interface StorageAdapter {
57
+ get: (key: string) => string | null | Promise<string | null>;
58
+ set: (key: string, value: string) => void | Promise<void>;
59
+ delete: (key: string) => void | Promise<void>;
60
+ clear: () => void | Promise<void>;
61
+ keys: () => string[] | Promise<string[]>;
62
+ has: (key: string) => boolean | Promise<boolean>;
63
+ size: () => number | Promise<number>;
64
+ }
65
+ /**
66
+ * Custom serializer interface
67
+ */
68
+ interface Serializer<T = unknown> {
69
+ serialize: (value: T) => string;
70
+ deserialize: (data: string) => T;
71
+ }
72
+ /**
73
+ * Options for set operation
74
+ */
75
+ interface SetOptions {
76
+ ttl?: number;
77
+ tags?: string[];
78
+ stale?: number;
79
+ revalidate?: number;
80
+ metadata?: Record<string, unknown>;
81
+ }
82
+ /**
83
+ * Options for getOrSet operation
84
+ */
85
+ interface GetOrSetOptions extends SetOptions {
86
+ forceRefresh?: boolean;
87
+ }
88
+ /**
89
+ * Cache hit event payload
90
+ */
91
+ interface HitEvent<T> {
92
+ key: string;
93
+ value: T;
94
+ entry: CacheEntry<T>;
95
+ }
96
+ /**
97
+ * Cache miss event payload
98
+ */
99
+ interface MissEvent {
100
+ key: string;
101
+ }
102
+ /**
103
+ * Cache set event payload
104
+ */
105
+ interface SetEvent<T> {
106
+ key: string;
107
+ value: T;
108
+ entry: CacheEntry<T>;
109
+ isUpdate: boolean;
110
+ }
111
+ /**
112
+ * Delete reason types
113
+ */
114
+ type DeleteReason = 'manual' | 'expire' | 'evict' | 'clear' | 'tag';
115
+ /**
116
+ * Cache delete event payload
117
+ */
118
+ interface DeleteEvent<T> {
119
+ key: string;
120
+ value: T;
121
+ reason: DeleteReason;
122
+ }
123
+ /**
124
+ * Cache expire event payload
125
+ */
126
+ interface ExpireEvent<T> {
127
+ key: string;
128
+ value: T;
129
+ entry: CacheEntry<T>;
130
+ }
131
+ /**
132
+ * Cache evict event payload
133
+ */
134
+ interface EvictEvent<T> {
135
+ key: string;
136
+ value: T;
137
+ entry: CacheEntry<T>;
138
+ strategy: CacheStrategy | 'memory' | 'custom';
139
+ }
140
+ /**
141
+ * Cache clear event payload
142
+ */
143
+ interface ClearEvent {
144
+ count: number;
145
+ namespace?: string;
146
+ }
147
+ /**
148
+ * Cache prune event payload
149
+ */
150
+ interface PruneEvent {
151
+ count: number;
152
+ }
153
+ /**
154
+ * All cache event types
155
+ */
156
+ type CacheEvent = 'hit' | 'miss' | 'set' | 'delete' | 'expire' | 'evict' | 'clear' | 'prune';
157
+ /**
158
+ * Event handler type mapping
159
+ */
160
+ type CacheEventHandler<E extends CacheEvent, T> = E extends 'hit' ? (event: HitEvent<T>) => void : E extends 'miss' ? (event: MissEvent) => void : E extends 'set' ? (event: SetEvent<T>) => void : E extends 'delete' ? (event: DeleteEvent<T>) => void : E extends 'expire' ? (event: ExpireEvent<T>) => void : E extends 'evict' ? (event: EvictEvent<T>) => void : E extends 'clear' ? (event: ClearEvent) => void : E extends 'prune' ? (event: PruneEvent) => void : never;
161
+ /**
162
+ * Event map for internal use
163
+ */
164
+ interface CacheEventMap<T> {
165
+ hit: HitEvent<T>;
166
+ miss: MissEvent;
167
+ set: SetEvent<T>;
168
+ delete: DeleteEvent<T>;
169
+ expire: ExpireEvent<T>;
170
+ evict: EvictEvent<T>;
171
+ clear: ClearEvent;
172
+ prune: PruneEvent;
173
+ }
174
+ /**
175
+ * Cache statistics
176
+ */
177
+ interface CacheStats {
178
+ hits: number;
179
+ misses: number;
180
+ hitRate: number;
181
+ sets: number;
182
+ deletes: number;
183
+ evictions: number;
184
+ expirations: number;
185
+ size: number;
186
+ maxSize: number;
187
+ memoryUsage: number;
188
+ maxMemory?: number;
189
+ namespaces: string[];
190
+ oldestEntry?: string;
191
+ newestEntry?: string;
192
+ avgTTL?: number;
193
+ uptime: number;
194
+ }
195
+ /**
196
+ * Cache namespace interface
197
+ */
198
+ interface CacheNamespace<T = unknown> {
199
+ readonly name: string;
200
+ readonly fullPath: string;
201
+ get(key: string): T | undefined;
202
+ get(key: string, defaultValue: T): T;
203
+ set(key: string, value: T, options?: SetOptions): void;
204
+ has(key: string): boolean;
205
+ delete(key: string): boolean;
206
+ clear(): void;
207
+ keys(): string[];
208
+ values(): T[];
209
+ entries(): [string, T][];
210
+ readonly size: number;
211
+ namespace(name: string): CacheNamespace<T>;
212
+ getStats(): CacheStats;
213
+ }
214
+ /**
215
+ * Cache plugin interface
216
+ */
217
+ interface CachePlugin<T = unknown> {
218
+ name: string;
219
+ onInit?: (cache: CacheInstance<T>) => void;
220
+ onDestroy?: (cache: CacheInstance<T>) => void;
221
+ beforeGet?: (key: string) => void;
222
+ afterGet?: (key: string, value: T | undefined) => T | undefined;
223
+ beforeSet?: (key: string, value: T, options?: SetOptions) => {
224
+ value: T;
225
+ options?: SetOptions;
226
+ } | void;
227
+ afterSet?: (key: string, entry: CacheEntry<T>) => void;
228
+ beforeDelete?: (key: string) => boolean;
229
+ afterDelete?: (key: string, value: T) => void;
230
+ beforeSerialize?: (value: T) => T;
231
+ afterDeserialize?: (value: T) => T;
232
+ }
233
+ /**
234
+ * Memoization options
235
+ */
236
+ interface MemoizeOptions<Args extends unknown[]> {
237
+ keyGenerator?: (...args: Args) => string;
238
+ ttl?: number;
239
+ tags?: string[];
240
+ maxSize?: number;
241
+ }
242
+ /**
243
+ * Batch set entry
244
+ */
245
+ interface BatchSetEntry<T> {
246
+ key: string;
247
+ value: T;
248
+ ttl?: number;
249
+ tags?: string[];
250
+ }
251
+ /**
252
+ * Cache dump structure
253
+ */
254
+ interface CacheDump<T> {
255
+ version: string;
256
+ createdAt: number;
257
+ entries: CacheEntry<T>[];
258
+ stats: Partial<CacheStats>;
259
+ metadata?: Record<string, unknown>;
260
+ }
261
+ /**
262
+ * Unsubscribe function type
263
+ */
264
+ type Unsubscribe = () => void;
265
+ /**
266
+ * Cache configuration options
267
+ */
268
+ interface CacheConfig<T = unknown> {
269
+ strategy?: CacheStrategy | CustomStrategy<T>;
270
+ maxSize?: number;
271
+ maxMemory?: number;
272
+ ttl?: number;
273
+ checkInterval?: number;
274
+ staleTime?: number;
275
+ revalidateTime?: number;
276
+ storage?: StorageType | StorageAdapter;
277
+ storageKey?: string;
278
+ serializer?: Serializer<T>;
279
+ plugins?: CachePlugin<T>[];
280
+ onHit?: (event: HitEvent<T>) => void;
281
+ onMiss?: (event: MissEvent) => void;
282
+ onSet?: (event: SetEvent<T>) => void;
283
+ onDelete?: (event: DeleteEvent<T>) => void;
284
+ onExpire?: (event: ExpireEvent<T>) => void;
285
+ onEvict?: (event: EvictEvent<T>) => void;
286
+ onClear?: (event: ClearEvent) => void;
287
+ }
288
+ /**
289
+ * Main cache instance interface
290
+ */
291
+ interface CacheInstance<T = unknown> {
292
+ get(key: string): T | undefined;
293
+ get(key: string, defaultValue: T): T;
294
+ set(key: string, value: T, options?: SetOptions): void;
295
+ has(key: string): boolean;
296
+ delete(key: string): boolean;
297
+ delete(keys: string[]): number;
298
+ clear(): void;
299
+ readonly size: number;
300
+ readonly isEmpty: boolean;
301
+ readonly maxSize: number;
302
+ readonly memoryUsage: number;
303
+ getTTL(key: string): number | undefined;
304
+ setTTL(key: string, ttl: number): boolean;
305
+ touch(key: string): boolean;
306
+ expire(key: string): boolean;
307
+ getExpiration(key: string): Date | null;
308
+ namespace(name: string): CacheNamespace<T>;
309
+ getNamespace(name: string): CacheNamespace<T> | undefined;
310
+ clearNamespace(name: string): number;
311
+ listNamespaces(): string[];
312
+ getTags(key: string): string[];
313
+ addTags(key: string, tags: string[]): boolean;
314
+ removeTags(key: string, tags: string[]): boolean;
315
+ invalidateByTag(tag: string): number;
316
+ invalidateByTag(tags: string[]): number;
317
+ getKeysByTag(tag: string): string[];
318
+ getKeysByTag(tags: string[]): string[];
319
+ isStale(key: string): boolean;
320
+ isFresh(key: string): boolean;
321
+ revalidate<R = T>(key: string, fetcher: () => R | Promise<R>): Promise<R>;
322
+ getOrSet(key: string, factory: () => T, options?: GetOrSetOptions): T;
323
+ getOrSet(key: string, factory: () => Promise<T>, options?: GetOrSetOptions): Promise<T>;
324
+ memoize<Args extends unknown[], R>(fn: (...args: Args) => R, options?: MemoizeOptions<Args>): (...args: Args) => R;
325
+ memoize<Args extends unknown[], R>(fn: (...args: Args) => Promise<R>, options?: MemoizeOptions<Args>): (...args: Args) => Promise<R>;
326
+ getMany(keys: string[]): Map<string, T>;
327
+ setMany(entries: BatchSetEntry<T>[]): void;
328
+ deleteMany(keys: string[]): number;
329
+ hasMany(keys: string[]): Map<string, boolean>;
330
+ getOrSetMany(keys: string[], fetcher: (missingKeys: string[]) => BatchSetEntry<T>[] | Promise<BatchSetEntry<T>[]>, options?: GetOrSetOptions): Promise<Map<string, T>>;
331
+ on<E extends CacheEvent>(event: E, handler: CacheEventHandler<E, T>): Unsubscribe;
332
+ off<E extends CacheEvent>(event: E, handler: CacheEventHandler<E, T>): void;
333
+ once<E extends CacheEvent>(event: E, handler: CacheEventHandler<E, T>): void;
334
+ getStats(): CacheStats;
335
+ readonly hits: number;
336
+ readonly misses: number;
337
+ readonly hitRate: number;
338
+ resetStats(): void;
339
+ keys(): string[];
340
+ keys(filter: (key: string) => boolean): string[];
341
+ values(): T[];
342
+ entries(): [string, T][];
343
+ forEach(callback: (value: T, key: string) => void): void;
344
+ find(predicate: (value: T, key: string) => boolean): T | undefined;
345
+ filter(predicate: (value: T, key: string) => boolean): [string, T][];
346
+ prune(): number;
347
+ resize(maxSize: number): number;
348
+ dump(): CacheDump<T>;
349
+ restore(dump: CacheDump<T>): void;
350
+ destroy(): void;
351
+ getEntry(key: string): CacheEntry<T> | undefined;
352
+ [Symbol.iterator](): Iterator<[string, T]>;
353
+ }
354
+ /**
355
+ * Options for useCachedValue hook
356
+ */
357
+ interface UseCachedValueOptions<T> {
358
+ fetcher?: () => T | Promise<T>;
359
+ ttl?: number;
360
+ staleTime?: number;
361
+ tags?: string[];
362
+ enabled?: boolean;
363
+ onSuccess?: (data: T) => void;
364
+ onError?: (error: Error) => void;
365
+ }
366
+ /**
367
+ * Result from useCachedValue hook
368
+ */
369
+ interface UseCachedValueResult<T> {
370
+ data: T | undefined;
371
+ isLoading: boolean;
372
+ isCached: boolean;
373
+ isStale: boolean;
374
+ isFetching: boolean;
375
+ error: Error | null;
376
+ refresh: () => Promise<void>;
377
+ invalidate: () => void;
378
+ }
379
+ /**
380
+ * Options for useCachedQuery hook
381
+ */
382
+ interface UseCachedQueryOptions<T> {
383
+ ttl?: number;
384
+ staleTime?: number;
385
+ revalidateOnFocus?: boolean;
386
+ revalidateOnReconnect?: boolean;
387
+ revalidateInterval?: number;
388
+ dedupingInterval?: number;
389
+ onSuccess?: (data: T) => void;
390
+ onError?: (error: Error) => void;
391
+ }
392
+ /**
393
+ * Result from useCachedQuery hook
394
+ */
395
+ interface UseCachedQueryResult<T> {
396
+ data: T | undefined;
397
+ error: Error | null;
398
+ isLoading: boolean;
399
+ isValidating: boolean;
400
+ mutate: (data?: T | Promise<T> | ((current: T | undefined) => T)) => Promise<void>;
401
+ }
402
+ /**
403
+ * Result from useCacheInvalidation hook
404
+ */
405
+ interface UseCacheInvalidationResult {
406
+ invalidate: (key: string) => void;
407
+ invalidateByTag: (tag: string | string[]) => number;
408
+ clear: () => void;
409
+ }
410
+ /**
411
+ * Options for useCacheStats hook
412
+ */
413
+ interface UseCacheStatsOptions {
414
+ refreshInterval?: number;
415
+ }
416
+
417
+ export type { BatchSetEntry as B, CacheConfig as C, DeleteEvent as D, EvictionContext as E, GetOrSetOptions as G, HitEvent as H, MissEvent as M, PruneEvent as P, StorageType as S, Unsubscribe as U, CacheInstance as a, CacheStrategy as b, CustomStrategy as c, CacheEntry as d, StorageAdapter as e, Serializer as f, SetOptions as g, SetEvent as h, DeleteReason as i, ExpireEvent as j, EvictEvent as k, ClearEvent as l, CacheEvent as m, CacheEventHandler as n, CacheEventMap as o, CacheStats as p, CacheNamespace as q, CachePlugin as r, MemoizeOptions as s, CacheDump as t, UseCachedValueOptions as u, UseCachedValueResult as v, UseCachedQueryOptions as w, UseCachedQueryResult as x, UseCacheInvalidationResult as y, UseCacheStatsOptions as z };