@asaidimu/utils-cache 2.0.0 → 2.0.2
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.md +21 -0
- package/index.d.mts +141 -0
- package/index.d.ts +141 -0
- package/index.js +1 -0
- package/index.mjs +1 -0
- package/package.json +4 -4
package/LICENSE.md
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
MIT License
|
2
|
+
|
3
|
+
Copyright (c) 2025 Saidimu
|
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/index.d.mts
ADDED
@@ -0,0 +1,141 @@
|
|
1
|
+
import { S as SimplePersistence } from '../types-dsQOAvmQ.js';
|
2
|
+
|
3
|
+
interface CacheOptions {
|
4
|
+
staleTime?: number;
|
5
|
+
cacheTime?: number;
|
6
|
+
retryAttempts?: number;
|
7
|
+
retryDelay?: number;
|
8
|
+
maxSize?: number;
|
9
|
+
enableMetrics?: boolean;
|
10
|
+
persistence?: SimplePersistence<SerializableCacheState>;
|
11
|
+
persistenceId?: string;
|
12
|
+
serializeValue?: (value: any) => any;
|
13
|
+
deserializeValue?: (value: any) => any;
|
14
|
+
persistenceDebounceTime?: number;
|
15
|
+
}
|
16
|
+
interface CacheMetrics {
|
17
|
+
hits: number;
|
18
|
+
misses: number;
|
19
|
+
fetches: number;
|
20
|
+
errors: number;
|
21
|
+
evictions: number;
|
22
|
+
staleHits: number;
|
23
|
+
}
|
24
|
+
interface SerializableCacheEntry {
|
25
|
+
data: any;
|
26
|
+
lastUpdated: number;
|
27
|
+
lastAccessed: number;
|
28
|
+
accessCount: number;
|
29
|
+
error?: {
|
30
|
+
name: string;
|
31
|
+
message: string;
|
32
|
+
stack?: string;
|
33
|
+
};
|
34
|
+
}
|
35
|
+
type SerializableCacheState = Array<[string, SerializableCacheEntry]>;
|
36
|
+
type CacheEventBase<Type extends string, Payload = {}> = {
|
37
|
+
type: Type;
|
38
|
+
key: string;
|
39
|
+
timestamp: number;
|
40
|
+
} & Payload;
|
41
|
+
type CacheHitEvent<T = any> = CacheEventBase<'hit', {
|
42
|
+
data: T;
|
43
|
+
isStale: boolean;
|
44
|
+
}>;
|
45
|
+
type CacheMissEvent = CacheEventBase<'miss'>;
|
46
|
+
type CacheFetchEvent = CacheEventBase<'fetch', {
|
47
|
+
attempt: number;
|
48
|
+
}>;
|
49
|
+
type CacheErrorEvent = CacheEventBase<'error', {
|
50
|
+
error: Error;
|
51
|
+
attempt: number;
|
52
|
+
}>;
|
53
|
+
type CacheEvictionEvent = CacheEventBase<'eviction', {
|
54
|
+
reason?: string;
|
55
|
+
}>;
|
56
|
+
type CacheInvalidationEvent = CacheEventBase<'invalidation'>;
|
57
|
+
type CacheSetDataEvent<T = any> = CacheEventBase<'set_data', {
|
58
|
+
newData: T;
|
59
|
+
oldData?: T;
|
60
|
+
}>;
|
61
|
+
type CachePersistenceEventPayload = {
|
62
|
+
event: 'load_success' | 'remote_update';
|
63
|
+
message?: string;
|
64
|
+
} | {
|
65
|
+
event: 'load_fail' | 'save_fail' | 'clear_fail';
|
66
|
+
message?: string;
|
67
|
+
error?: any;
|
68
|
+
} | {
|
69
|
+
event: 'save_success' | 'clear_success';
|
70
|
+
};
|
71
|
+
type CachePersistenceEvent = CacheEventBase<'persistence', CachePersistenceEventPayload>;
|
72
|
+
type CacheEvent = CacheHitEvent | CacheMissEvent | CacheFetchEvent | CacheErrorEvent | CacheEvictionEvent | CacheInvalidationEvent | CacheSetDataEvent | CachePersistenceEvent;
|
73
|
+
type CacheEventType = CacheEvent['type'];
|
74
|
+
|
75
|
+
declare class Cache {
|
76
|
+
private cache;
|
77
|
+
private queries;
|
78
|
+
private fetching;
|
79
|
+
private readonly defaultOptions;
|
80
|
+
private metrics;
|
81
|
+
private eventListeners;
|
82
|
+
private gcTimer?;
|
83
|
+
private readonly persistenceId;
|
84
|
+
private persistenceUnsubscribe?;
|
85
|
+
private persistenceDebounceTimer?;
|
86
|
+
private isHandlingRemoteUpdate;
|
87
|
+
constructor(defaultOptions?: CacheOptions);
|
88
|
+
private initializePersistence;
|
89
|
+
private serializeCache;
|
90
|
+
private deserializeAndLoadCache;
|
91
|
+
private schedulePersistState;
|
92
|
+
private handleRemoteStateChange;
|
93
|
+
registerQuery<T>(key: string, fetchFunction: () => Promise<T>, options?: CacheOptions): void;
|
94
|
+
get<T>(key: string, options?: {
|
95
|
+
waitForFresh?: boolean;
|
96
|
+
throwOnError?: boolean;
|
97
|
+
}): Promise<T | undefined>;
|
98
|
+
peek<T>(key: string): T | undefined;
|
99
|
+
has(key: string): boolean;
|
100
|
+
private fetch;
|
101
|
+
private fetchAndWait;
|
102
|
+
private performFetchWithRetry;
|
103
|
+
private isStale;
|
104
|
+
invalidate(key: string, refetch?: boolean): Promise<void>;
|
105
|
+
invalidatePattern(pattern: RegExp, refetch?: boolean): Promise<void>;
|
106
|
+
prefetch(key: string): Promise<void>;
|
107
|
+
refresh<T>(key: string): Promise<T | undefined>;
|
108
|
+
setData<T>(key: string, data: T): void;
|
109
|
+
remove(key: string): boolean;
|
110
|
+
private enforceSizeLimit;
|
111
|
+
private startGarbageCollection;
|
112
|
+
garbageCollect(): number;
|
113
|
+
getStats(): {
|
114
|
+
size: number;
|
115
|
+
metrics: CacheMetrics;
|
116
|
+
hitRate: number;
|
117
|
+
staleHitRate: number;
|
118
|
+
entries: Array<{
|
119
|
+
key: string;
|
120
|
+
lastAccessed: number;
|
121
|
+
lastUpdated: number;
|
122
|
+
accessCount: number;
|
123
|
+
isStale: boolean;
|
124
|
+
isLoading?: boolean;
|
125
|
+
error?: boolean;
|
126
|
+
}>;
|
127
|
+
};
|
128
|
+
on<EType extends CacheEventType>(event: EType, listener: (ev: Extract<CacheEvent, {
|
129
|
+
type: EType;
|
130
|
+
}>) => void): void;
|
131
|
+
off<EType extends CacheEventType>(event: EType, listener: (ev: Extract<CacheEvent, {
|
132
|
+
type: EType;
|
133
|
+
}>) => void): void;
|
134
|
+
private emitEvent;
|
135
|
+
private updateMetrics;
|
136
|
+
private delay;
|
137
|
+
clear(): Promise<void>;
|
138
|
+
destroy(): void;
|
139
|
+
}
|
140
|
+
|
141
|
+
export { Cache };
|
package/index.d.ts
ADDED
@@ -0,0 +1,141 @@
|
|
1
|
+
import { S as SimplePersistence } from '../types-dsQOAvmQ.js';
|
2
|
+
|
3
|
+
interface CacheOptions {
|
4
|
+
staleTime?: number;
|
5
|
+
cacheTime?: number;
|
6
|
+
retryAttempts?: number;
|
7
|
+
retryDelay?: number;
|
8
|
+
maxSize?: number;
|
9
|
+
enableMetrics?: boolean;
|
10
|
+
persistence?: SimplePersistence<SerializableCacheState>;
|
11
|
+
persistenceId?: string;
|
12
|
+
serializeValue?: (value: any) => any;
|
13
|
+
deserializeValue?: (value: any) => any;
|
14
|
+
persistenceDebounceTime?: number;
|
15
|
+
}
|
16
|
+
interface CacheMetrics {
|
17
|
+
hits: number;
|
18
|
+
misses: number;
|
19
|
+
fetches: number;
|
20
|
+
errors: number;
|
21
|
+
evictions: number;
|
22
|
+
staleHits: number;
|
23
|
+
}
|
24
|
+
interface SerializableCacheEntry {
|
25
|
+
data: any;
|
26
|
+
lastUpdated: number;
|
27
|
+
lastAccessed: number;
|
28
|
+
accessCount: number;
|
29
|
+
error?: {
|
30
|
+
name: string;
|
31
|
+
message: string;
|
32
|
+
stack?: string;
|
33
|
+
};
|
34
|
+
}
|
35
|
+
type SerializableCacheState = Array<[string, SerializableCacheEntry]>;
|
36
|
+
type CacheEventBase<Type extends string, Payload = {}> = {
|
37
|
+
type: Type;
|
38
|
+
key: string;
|
39
|
+
timestamp: number;
|
40
|
+
} & Payload;
|
41
|
+
type CacheHitEvent<T = any> = CacheEventBase<'hit', {
|
42
|
+
data: T;
|
43
|
+
isStale: boolean;
|
44
|
+
}>;
|
45
|
+
type CacheMissEvent = CacheEventBase<'miss'>;
|
46
|
+
type CacheFetchEvent = CacheEventBase<'fetch', {
|
47
|
+
attempt: number;
|
48
|
+
}>;
|
49
|
+
type CacheErrorEvent = CacheEventBase<'error', {
|
50
|
+
error: Error;
|
51
|
+
attempt: number;
|
52
|
+
}>;
|
53
|
+
type CacheEvictionEvent = CacheEventBase<'eviction', {
|
54
|
+
reason?: string;
|
55
|
+
}>;
|
56
|
+
type CacheInvalidationEvent = CacheEventBase<'invalidation'>;
|
57
|
+
type CacheSetDataEvent<T = any> = CacheEventBase<'set_data', {
|
58
|
+
newData: T;
|
59
|
+
oldData?: T;
|
60
|
+
}>;
|
61
|
+
type CachePersistenceEventPayload = {
|
62
|
+
event: 'load_success' | 'remote_update';
|
63
|
+
message?: string;
|
64
|
+
} | {
|
65
|
+
event: 'load_fail' | 'save_fail' | 'clear_fail';
|
66
|
+
message?: string;
|
67
|
+
error?: any;
|
68
|
+
} | {
|
69
|
+
event: 'save_success' | 'clear_success';
|
70
|
+
};
|
71
|
+
type CachePersistenceEvent = CacheEventBase<'persistence', CachePersistenceEventPayload>;
|
72
|
+
type CacheEvent = CacheHitEvent | CacheMissEvent | CacheFetchEvent | CacheErrorEvent | CacheEvictionEvent | CacheInvalidationEvent | CacheSetDataEvent | CachePersistenceEvent;
|
73
|
+
type CacheEventType = CacheEvent['type'];
|
74
|
+
|
75
|
+
declare class Cache {
|
76
|
+
private cache;
|
77
|
+
private queries;
|
78
|
+
private fetching;
|
79
|
+
private readonly defaultOptions;
|
80
|
+
private metrics;
|
81
|
+
private eventListeners;
|
82
|
+
private gcTimer?;
|
83
|
+
private readonly persistenceId;
|
84
|
+
private persistenceUnsubscribe?;
|
85
|
+
private persistenceDebounceTimer?;
|
86
|
+
private isHandlingRemoteUpdate;
|
87
|
+
constructor(defaultOptions?: CacheOptions);
|
88
|
+
private initializePersistence;
|
89
|
+
private serializeCache;
|
90
|
+
private deserializeAndLoadCache;
|
91
|
+
private schedulePersistState;
|
92
|
+
private handleRemoteStateChange;
|
93
|
+
registerQuery<T>(key: string, fetchFunction: () => Promise<T>, options?: CacheOptions): void;
|
94
|
+
get<T>(key: string, options?: {
|
95
|
+
waitForFresh?: boolean;
|
96
|
+
throwOnError?: boolean;
|
97
|
+
}): Promise<T | undefined>;
|
98
|
+
peek<T>(key: string): T | undefined;
|
99
|
+
has(key: string): boolean;
|
100
|
+
private fetch;
|
101
|
+
private fetchAndWait;
|
102
|
+
private performFetchWithRetry;
|
103
|
+
private isStale;
|
104
|
+
invalidate(key: string, refetch?: boolean): Promise<void>;
|
105
|
+
invalidatePattern(pattern: RegExp, refetch?: boolean): Promise<void>;
|
106
|
+
prefetch(key: string): Promise<void>;
|
107
|
+
refresh<T>(key: string): Promise<T | undefined>;
|
108
|
+
setData<T>(key: string, data: T): void;
|
109
|
+
remove(key: string): boolean;
|
110
|
+
private enforceSizeLimit;
|
111
|
+
private startGarbageCollection;
|
112
|
+
garbageCollect(): number;
|
113
|
+
getStats(): {
|
114
|
+
size: number;
|
115
|
+
metrics: CacheMetrics;
|
116
|
+
hitRate: number;
|
117
|
+
staleHitRate: number;
|
118
|
+
entries: Array<{
|
119
|
+
key: string;
|
120
|
+
lastAccessed: number;
|
121
|
+
lastUpdated: number;
|
122
|
+
accessCount: number;
|
123
|
+
isStale: boolean;
|
124
|
+
isLoading?: boolean;
|
125
|
+
error?: boolean;
|
126
|
+
}>;
|
127
|
+
};
|
128
|
+
on<EType extends CacheEventType>(event: EType, listener: (ev: Extract<CacheEvent, {
|
129
|
+
type: EType;
|
130
|
+
}>) => void): void;
|
131
|
+
off<EType extends CacheEventType>(event: EType, listener: (ev: Extract<CacheEvent, {
|
132
|
+
type: EType;
|
133
|
+
}>) => void): void;
|
134
|
+
private emitEvent;
|
135
|
+
private updateMetrics;
|
136
|
+
private delay;
|
137
|
+
clear(): Promise<void>;
|
138
|
+
destroy(): void;
|
139
|
+
}
|
140
|
+
|
141
|
+
export { Cache };
|
package/index.js
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
"use strict";var e=require("uuid");exports.Cache=class{cache=new Map;queries=new Map;fetching=new Map;defaultOptions;metrics;eventListeners=new Map;gcTimer;persistenceId;persistenceUnsubscribe;persistenceDebounceTimer;isHandlingRemoteUpdate=!1;constructor(t={}){void 0!==t.staleTime&&t.staleTime<0&&(console.warn("CacheOptions: staleTime should be non-negative. Using 0."),t.staleTime=0),void 0!==t.cacheTime&&t.cacheTime<0&&(console.warn("CacheOptions: cacheTime should be non-negative. Using 0."),t.cacheTime=0),void 0!==t.retryAttempts&&t.retryAttempts<0&&(console.warn("CacheOptions: retryAttempts should be non-negative. Using 0."),t.retryAttempts=0),void 0!==t.retryDelay&&t.retryDelay<0&&(console.warn("CacheOptions: retryDelay should be non-negative. Using 0."),t.retryDelay=0),void 0!==t.maxSize&&t.maxSize<0&&(console.warn("CacheOptions: maxSize should be non-negative. Using 0."),t.maxSize=0),this.defaultOptions={staleTime:3e5,cacheTime:18e5,retryAttempts:3,retryDelay:1e3,maxSize:1e3,enableMetrics:!0,persistence:void 0,persistenceId:void 0,serializeValue:e=>e,deserializeValue:e=>e,persistenceDebounceTime:500,...t},this.metrics={hits:0,misses:0,fetches:0,errors:0,evictions:0,staleHits:0},this.persistenceId=this.defaultOptions.persistenceId||e.v4(),this.startGarbageCollection(),this.initializePersistence()}async initializePersistence(){const{persistence:e}=this.defaultOptions;if(e){try{const t=await e.get();t&&(this.deserializeAndLoadCache(t),this.emitEvent({type:"persistence",key:this.persistenceId,timestamp:Date.now(),event:"load_success",message:`Cache loaded for ID: ${this.persistenceId}`}))}catch(e){console.error(`Cache (${this.persistenceId}): Failed to load state from persistence:`,e),this.emitEvent({type:"persistence",key:this.persistenceId,timestamp:Date.now(),event:"load_fail",error:e,message:`Failed to load cache for ID: ${this.persistenceId}`})}if("function"==typeof e.subscribe)try{this.persistenceUnsubscribe=e.subscribe(this.persistenceId,(e=>{this.handleRemoteStateChange(e)}))}catch(e){console.error(`Cache (${this.persistenceId}): Failed to subscribe to persistence:`,e)}}}serializeCache(){const e=[],{serializeValue:t}=this.defaultOptions;for(const[s,i]of this.cache)i.isLoading&&void 0===i.data&&0===i.lastUpdated||e.push([s,{data:t(i.data),lastUpdated:i.lastUpdated,lastAccessed:i.lastAccessed,accessCount:i.accessCount,error:i.error?{name:i.error.name,message:i.error.message,stack:i.error.stack}:void 0}]);return e}deserializeAndLoadCache(e){this.isHandlingRemoteUpdate=!0;const t=new Map,{deserializeValue:s}=this.defaultOptions;for(const[i,a]of e){let e;a.error&&(e=new Error(a.error.message),e.name=a.error.name,e.stack=a.error.stack),t.set(i,{data:s(a.data),lastUpdated:a.lastUpdated,lastAccessed:a.lastAccessed,accessCount:a.accessCount,error:e,isLoading:!1})}this.cache=t,this.enforceSizeLimit(!1),this.isHandlingRemoteUpdate=!1}schedulePersistState(){this.defaultOptions.persistence&&!this.isHandlingRemoteUpdate&&(this.persistenceDebounceTimer&&clearTimeout(this.persistenceDebounceTimer),this.persistenceDebounceTimer=setTimeout((async()=>{try{const e=this.serializeCache();await this.defaultOptions.persistence.set(this.persistenceId,e),this.emitEvent({type:"persistence",key:this.persistenceId,timestamp:Date.now(),event:"save_success"})}catch(e){console.error(`Cache (${this.persistenceId}): Failed to persist state:`,e),this.emitEvent({type:"persistence",key:this.persistenceId,timestamp:Date.now(),event:"save_fail",error:e})}}),this.defaultOptions.persistenceDebounceTime))}handleRemoteStateChange(e){if(this.isHandlingRemoteUpdate||!e)return;this.isHandlingRemoteUpdate=!0;const{deserializeValue:t}=this.defaultOptions,s=new Map;let i=!1;for(const[a,r]of e){let e;r.error&&(e=new Error(r.error.message),e.name=r.error.name,e.stack=r.error.stack);const c={data:t(r.data),lastUpdated:r.lastUpdated,lastAccessed:r.lastAccessed,accessCount:r.accessCount,error:e,isLoading:!1};s.set(a,c);const n=this.cache.get(a);(!n||n.lastUpdated<c.lastUpdated||JSON.stringify(n.data)!==JSON.stringify(c.data))&&(i=!0)}this.cache.size!==s.size&&(i=!0),i&&(this.cache=s,this.enforceSizeLimit(!1),this.emitEvent({type:"persistence",key:this.persistenceId,timestamp:Date.now(),event:"remote_update",message:"Cache updated from remote state."})),this.isHandlingRemoteUpdate=!1}registerQuery(e,t,s={}){void 0!==s.staleTime&&s.staleTime<0&&(s.staleTime=0),void 0!==s.cacheTime&&s.cacheTime<0&&(s.cacheTime=0),this.queries.set(e,{fetchFunction:t,options:{...this.defaultOptions,...s}})}async get(e,t){const s=this.queries.get(e);if(!s)throw new Error(`No query registered for key: ${e}`);let i=this.cache.get(e);const a=this.isStale(i,s.options);let r=!1;if(i)i.lastAccessed=Date.now(),i.accessCount++,this.updateMetrics("hits"),a&&this.updateMetrics("staleHits"),this.emitEvent({type:"hit",key:e,timestamp:Date.now(),data:i.data,isStale:a});else if(this.updateMetrics("misses"),this.emitEvent({type:"miss",key:e,timestamp:Date.now()}),!t?.waitForFresh||a){const t={data:void 0,lastUpdated:0,lastAccessed:Date.now(),accessCount:1,isLoading:!0,error:void 0};this.cache.set(e,t),i=t,r=!0}if(t?.waitForFresh&&(!i||a||i.isLoading))try{const t=await this.fetchAndWait(e,s);return r&&this.cache.get(e)===i&&this.schedulePersistState(),t}catch(s){if(t.throwOnError)throw s;return this.cache.get(e)?.data}if(!i||a||i&&!i.isLoading&&0===i.lastUpdated&&!i.error){if(i&&!i.isLoading)i.isLoading=!0;else if(!i){const t={data:void 0,lastUpdated:0,lastAccessed:Date.now(),accessCount:0,isLoading:!0,error:void 0};this.cache.set(e,t),i=t,r=!0}this.fetch(e,s).catch((()=>{}))}if(r&&this.schedulePersistState(),i?.error&&t?.throwOnError)throw i.error;return i?.data}peek(e){const t=this.cache.get(e);return t&&(t.lastAccessed=Date.now(),t.accessCount++),t?.data}has(e){const t=this.cache.get(e),s=this.queries.get(e);return!(!t||!s)&&(!this.isStale(t,s.options)&&!t.isLoading)}async fetch(e,t){if(this.fetching.has(e))return this.fetching.get(e);let s=this.cache.get(e);s?s.isLoading||(s.isLoading=!0,s.error=void 0):(s={data:void 0,lastUpdated:0,lastAccessed:Date.now(),accessCount:0,isLoading:!0,error:void 0},this.cache.set(e,s),this.schedulePersistState());const i=this.performFetchWithRetry(e,t,s);this.fetching.set(e,i);try{return await i}finally{this.fetching.delete(e)}}async fetchAndWait(e,t){const s=this.fetching.get(e);if(s)return s;const i=await this.fetch(e,t);if(void 0===i){const t=this.cache.get(e);if(t?.error)throw t.error;throw new Error(`Failed to fetch data for key: ${e} after retries.`)}return i}async performFetchWithRetry(e,t,s){const{retryAttempts:i,retryDelay:a}=t.options;let r;s.isLoading=!0;for(let c=0;c<=i;c++)try{this.emitEvent({type:"fetch",key:e,timestamp:Date.now(),attempt:c}),this.updateMetrics("fetches");const i=await t.fetchFunction();return s.data=i,s.lastUpdated=Date.now(),s.isLoading=!1,s.error=void 0,this.cache.set(e,s),this.schedulePersistState(),this.enforceSizeLimit(),i}catch(t){r=t,this.emitEvent({type:"error",key:e,timestamp:Date.now(),error:r,attempt:c}),c<i&&await this.delay(a*Math.pow(2,c))}this.updateMetrics("errors"),s.error=r,s.isLoading=!1,this.cache.set(e,s),this.schedulePersistState()}isStale(e,t){if(!e||e.error)return!0;if(e.isLoading&&!e.data)return!0;const{staleTime:s}=t;return 0!==s&&s!==1/0&&Date.now()-e.lastUpdated>s}async invalidate(e,t=!0){const s=this.cache.get(e),i=this.queries.get(e);let a=!1;s&&(a=0!==s.lastUpdated||void 0!==s.error,s.lastUpdated=0,s.error=void 0,this.emitEvent({type:"invalidation",key:e,timestamp:Date.now()}),a&&this.schedulePersistState(),t&&i&&this.fetch(e,i).catch((()=>{})))}async invalidatePattern(e,t=!0){const s=[];let i=!1;for(const t of this.cache.keys())e.test(t)&&s.push(t);s.forEach((e=>{const t=this.cache.get(e);t&&(0===t.lastUpdated&&void 0===t.error||(i=!0),t.lastUpdated=0,t.error=void 0,this.emitEvent({type:"invalidation",key:e,timestamp:Date.now()}))})),i&&this.schedulePersistState(),t&&s.length>0&&await Promise.all(s.map((e=>{const t=this.queries.get(e);return t?this.fetch(e,t).catch((()=>{})):Promise.resolve()})))}async prefetch(e){const t=this.queries.get(e);if(!t)return void console.warn(`Cannot prefetch: No query registered for key: ${e}`);const s=this.cache.get(e);s&&!this.isStale(s,t.options)||this.fetch(e,t).catch((()=>{}))}async refresh(e){const t=this.queries.get(e);if(!t)return void console.warn(`Cannot refresh: No query registered for key: ${e}`);this.fetching.delete(e);let s=this.cache.get(e);s?(s.isLoading=!0,s.error=void 0):(s={data:void 0,lastUpdated:0,lastAccessed:Date.now(),accessCount:0,isLoading:!0,error:void 0},this.cache.set(e,s),this.schedulePersistState());const i=this.performFetchWithRetry(e,t,s);this.fetching.set(e,i);try{return await i}finally{this.fetching.delete(e)}}setData(e,t){const s=this.cache.get(e),i=s?.data,a={data:t,lastUpdated:Date.now(),lastAccessed:Date.now(),accessCount:(s?.accessCount||0)+1,isLoading:!1,error:void 0};this.cache.set(e,a),this.schedulePersistState(),this.enforceSizeLimit(),this.emitEvent({type:"set_data",key:e,timestamp:Date.now(),newData:t,oldData:i})}remove(e){this.fetching.delete(e);const t=this.cache.has(e),s=this.cache.delete(e);return s&&t&&this.schedulePersistState(),s}enforceSizeLimit(e=!0){const{maxSize:t}=this.defaultOptions;if(t===1/0||this.cache.size<=t)return;let s=0;if(0===t){s=this.cache.size;for(const e of this.cache.keys())this.cache.delete(e),this.emitEvent({type:"eviction",key:e,timestamp:Date.now(),reason:"size_limit_zero"}),this.updateMetrics("evictions")}else{const e=Array.from(this.cache.entries()).sort((([,e],[,t])=>e.lastAccessed-t.lastAccessed)),i=this.cache.size-t;if(i>0){e.slice(0,i).forEach((([e])=>{this.cache.delete(e)&&(s++,this.emitEvent({type:"eviction",key:e,timestamp:Date.now(),reason:"size_limit_lru"}),this.updateMetrics("evictions"))}))}}s>0&&e&&this.schedulePersistState()}startGarbageCollection(){const{cacheTime:e}=this.defaultOptions;if(e===1/0||e<=0)return;const t=Math.max(1e3,Math.min(e/4,3e5));this.gcTimer=setInterval((()=>this.garbageCollect()),t)}garbageCollect(){const e=Date.now();let t=0;const s=[];for(const[t,i]of this.cache){if(i.isLoading)continue;const a=this.queries.get(t),r=a?.options.cacheTime??this.defaultOptions.cacheTime;r===1/0||r<=0||e-i.lastAccessed>r&&s.push(t)}return s.length>0&&(s.forEach((e=>{this.cache.delete(e)&&(this.fetching.delete(e),this.emitEvent({type:"eviction",key:e,timestamp:Date.now(),reason:"garbage_collected_idle"}),this.updateMetrics("evictions"),t++)})),this.schedulePersistState()),t}getStats(){const e=this.metrics.hits+this.metrics.misses,t=e>0?this.metrics.hits/e:0,s=this.metrics.hits>0?this.metrics.staleHits/this.metrics.hits:0,i=Array.from(this.cache.entries()).map((([e,t])=>{const s=this.queries.get(e),i=!s||this.isStale(t,s.options);return{key:e,lastAccessed:t.lastAccessed,lastUpdated:t.lastUpdated,accessCount:t.accessCount,isStale:i,isLoading:t.isLoading,error:!!t.error}}));return{size:this.cache.size,metrics:{...this.metrics},hitRate:t,staleHitRate:s,entries:i}}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}off(e,t){this.eventListeners.get(e)?.delete(t)}emitEvent(e){const t=this.eventListeners.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(t){const s="persistence"===e.type?`for ID ${e.key}`:`for key ${e.key}`;console.error(`Cache event listener error during ${e.type} ${s}:`,t)}}))}updateMetrics(e,t=1){this.defaultOptions.enableMetrics&&(this.metrics[e]=(this.metrics[e]||0)+t)}delay(e){return new Promise((t=>setTimeout(t,e)))}async clear(){const e=this.cache.size>0;if(this.cache.clear(),this.fetching.clear(),this.defaultOptions.enableMetrics&&(this.metrics={hits:0,misses:0,fetches:0,errors:0,evictions:0,staleHits:0}),this.defaultOptions.persistence)try{await this.defaultOptions.persistence.clear(),this.emitEvent({type:"persistence",key:this.persistenceId,timestamp:Date.now(),event:"clear_success"})}catch(e){console.error(`Cache (${this.persistenceId}): Failed to clear persisted state:`,e),this.emitEvent({type:"persistence",key:this.persistenceId,timestamp:Date.now(),event:"clear_fail",error:e})}else e&&this.schedulePersistState()}destroy(){if(this.gcTimer&&(clearInterval(this.gcTimer),this.gcTimer=void 0),this.persistenceDebounceTimer&&clearTimeout(this.persistenceDebounceTimer),this.persistenceUnsubscribe)try{this.persistenceUnsubscribe()}catch(e){console.error(`Cache (${this.persistenceId}): Error unsubscribing persistence:`,e)}this.cache.clear(),this.fetching.clear(),this.queries.clear(),this.eventListeners.clear(),this.metrics={hits:0,misses:0,fetches:0,errors:0,evictions:0,staleHits:0}}};
|
package/index.mjs
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
import{v4 as e}from"uuid";var t=class{cache=new Map;queries=new Map;fetching=new Map;defaultOptions;metrics;eventListeners=new Map;gcTimer;persistenceId;persistenceUnsubscribe;persistenceDebounceTimer;isHandlingRemoteUpdate=!1;constructor(t={}){void 0!==t.staleTime&&t.staleTime<0&&(console.warn("CacheOptions: staleTime should be non-negative. Using 0."),t.staleTime=0),void 0!==t.cacheTime&&t.cacheTime<0&&(console.warn("CacheOptions: cacheTime should be non-negative. Using 0."),t.cacheTime=0),void 0!==t.retryAttempts&&t.retryAttempts<0&&(console.warn("CacheOptions: retryAttempts should be non-negative. Using 0."),t.retryAttempts=0),void 0!==t.retryDelay&&t.retryDelay<0&&(console.warn("CacheOptions: retryDelay should be non-negative. Using 0."),t.retryDelay=0),void 0!==t.maxSize&&t.maxSize<0&&(console.warn("CacheOptions: maxSize should be non-negative. Using 0."),t.maxSize=0),this.defaultOptions={staleTime:3e5,cacheTime:18e5,retryAttempts:3,retryDelay:1e3,maxSize:1e3,enableMetrics:!0,persistence:void 0,persistenceId:void 0,serializeValue:e=>e,deserializeValue:e=>e,persistenceDebounceTime:500,...t},this.metrics={hits:0,misses:0,fetches:0,errors:0,evictions:0,staleHits:0},this.persistenceId=this.defaultOptions.persistenceId||e(),this.startGarbageCollection(),this.initializePersistence()}async initializePersistence(){const{persistence:e}=this.defaultOptions;if(e){try{const t=await e.get();t&&(this.deserializeAndLoadCache(t),this.emitEvent({type:"persistence",key:this.persistenceId,timestamp:Date.now(),event:"load_success",message:`Cache loaded for ID: ${this.persistenceId}`}))}catch(e){console.error(`Cache (${this.persistenceId}): Failed to load state from persistence:`,e),this.emitEvent({type:"persistence",key:this.persistenceId,timestamp:Date.now(),event:"load_fail",error:e,message:`Failed to load cache for ID: ${this.persistenceId}`})}if("function"==typeof e.subscribe)try{this.persistenceUnsubscribe=e.subscribe(this.persistenceId,(e=>{this.handleRemoteStateChange(e)}))}catch(e){console.error(`Cache (${this.persistenceId}): Failed to subscribe to persistence:`,e)}}}serializeCache(){const e=[],{serializeValue:t}=this.defaultOptions;for(const[s,i]of this.cache)i.isLoading&&void 0===i.data&&0===i.lastUpdated||e.push([s,{data:t(i.data),lastUpdated:i.lastUpdated,lastAccessed:i.lastAccessed,accessCount:i.accessCount,error:i.error?{name:i.error.name,message:i.error.message,stack:i.error.stack}:void 0}]);return e}deserializeAndLoadCache(e){this.isHandlingRemoteUpdate=!0;const t=new Map,{deserializeValue:s}=this.defaultOptions;for(const[i,a]of e){let e;a.error&&(e=new Error(a.error.message),e.name=a.error.name,e.stack=a.error.stack),t.set(i,{data:s(a.data),lastUpdated:a.lastUpdated,lastAccessed:a.lastAccessed,accessCount:a.accessCount,error:e,isLoading:!1})}this.cache=t,this.enforceSizeLimit(!1),this.isHandlingRemoteUpdate=!1}schedulePersistState(){this.defaultOptions.persistence&&!this.isHandlingRemoteUpdate&&(this.persistenceDebounceTimer&&clearTimeout(this.persistenceDebounceTimer),this.persistenceDebounceTimer=setTimeout((async()=>{try{const e=this.serializeCache();await this.defaultOptions.persistence.set(this.persistenceId,e),this.emitEvent({type:"persistence",key:this.persistenceId,timestamp:Date.now(),event:"save_success"})}catch(e){console.error(`Cache (${this.persistenceId}): Failed to persist state:`,e),this.emitEvent({type:"persistence",key:this.persistenceId,timestamp:Date.now(),event:"save_fail",error:e})}}),this.defaultOptions.persistenceDebounceTime))}handleRemoteStateChange(e){if(this.isHandlingRemoteUpdate||!e)return;this.isHandlingRemoteUpdate=!0;const{deserializeValue:t}=this.defaultOptions,s=new Map;let i=!1;for(const[a,r]of e){let e;r.error&&(e=new Error(r.error.message),e.name=r.error.name,e.stack=r.error.stack);const c={data:t(r.data),lastUpdated:r.lastUpdated,lastAccessed:r.lastAccessed,accessCount:r.accessCount,error:e,isLoading:!1};s.set(a,c);const n=this.cache.get(a);(!n||n.lastUpdated<c.lastUpdated||JSON.stringify(n.data)!==JSON.stringify(c.data))&&(i=!0)}this.cache.size!==s.size&&(i=!0),i&&(this.cache=s,this.enforceSizeLimit(!1),this.emitEvent({type:"persistence",key:this.persistenceId,timestamp:Date.now(),event:"remote_update",message:"Cache updated from remote state."})),this.isHandlingRemoteUpdate=!1}registerQuery(e,t,s={}){void 0!==s.staleTime&&s.staleTime<0&&(s.staleTime=0),void 0!==s.cacheTime&&s.cacheTime<0&&(s.cacheTime=0),this.queries.set(e,{fetchFunction:t,options:{...this.defaultOptions,...s}})}async get(e,t){const s=this.queries.get(e);if(!s)throw new Error(`No query registered for key: ${e}`);let i=this.cache.get(e);const a=this.isStale(i,s.options);let r=!1;if(i)i.lastAccessed=Date.now(),i.accessCount++,this.updateMetrics("hits"),a&&this.updateMetrics("staleHits"),this.emitEvent({type:"hit",key:e,timestamp:Date.now(),data:i.data,isStale:a});else if(this.updateMetrics("misses"),this.emitEvent({type:"miss",key:e,timestamp:Date.now()}),!t?.waitForFresh||a){const t={data:void 0,lastUpdated:0,lastAccessed:Date.now(),accessCount:1,isLoading:!0,error:void 0};this.cache.set(e,t),i=t,r=!0}if(t?.waitForFresh&&(!i||a||i.isLoading))try{const t=await this.fetchAndWait(e,s);return r&&this.cache.get(e)===i&&this.schedulePersistState(),t}catch(s){if(t.throwOnError)throw s;return this.cache.get(e)?.data}if(!i||a||i&&!i.isLoading&&0===i.lastUpdated&&!i.error){if(i&&!i.isLoading)i.isLoading=!0;else if(!i){const t={data:void 0,lastUpdated:0,lastAccessed:Date.now(),accessCount:0,isLoading:!0,error:void 0};this.cache.set(e,t),i=t,r=!0}this.fetch(e,s).catch((()=>{}))}if(r&&this.schedulePersistState(),i?.error&&t?.throwOnError)throw i.error;return i?.data}peek(e){const t=this.cache.get(e);return t&&(t.lastAccessed=Date.now(),t.accessCount++),t?.data}has(e){const t=this.cache.get(e),s=this.queries.get(e);return!(!t||!s)&&(!this.isStale(t,s.options)&&!t.isLoading)}async fetch(e,t){if(this.fetching.has(e))return this.fetching.get(e);let s=this.cache.get(e);s?s.isLoading||(s.isLoading=!0,s.error=void 0):(s={data:void 0,lastUpdated:0,lastAccessed:Date.now(),accessCount:0,isLoading:!0,error:void 0},this.cache.set(e,s),this.schedulePersistState());const i=this.performFetchWithRetry(e,t,s);this.fetching.set(e,i);try{return await i}finally{this.fetching.delete(e)}}async fetchAndWait(e,t){const s=this.fetching.get(e);if(s)return s;const i=await this.fetch(e,t);if(void 0===i){const t=this.cache.get(e);if(t?.error)throw t.error;throw new Error(`Failed to fetch data for key: ${e} after retries.`)}return i}async performFetchWithRetry(e,t,s){const{retryAttempts:i,retryDelay:a}=t.options;let r;s.isLoading=!0;for(let c=0;c<=i;c++)try{this.emitEvent({type:"fetch",key:e,timestamp:Date.now(),attempt:c}),this.updateMetrics("fetches");const i=await t.fetchFunction();return s.data=i,s.lastUpdated=Date.now(),s.isLoading=!1,s.error=void 0,this.cache.set(e,s),this.schedulePersistState(),this.enforceSizeLimit(),i}catch(t){r=t,this.emitEvent({type:"error",key:e,timestamp:Date.now(),error:r,attempt:c}),c<i&&await this.delay(a*Math.pow(2,c))}this.updateMetrics("errors"),s.error=r,s.isLoading=!1,this.cache.set(e,s),this.schedulePersistState()}isStale(e,t){if(!e||e.error)return!0;if(e.isLoading&&!e.data)return!0;const{staleTime:s}=t;return 0!==s&&s!==1/0&&Date.now()-e.lastUpdated>s}async invalidate(e,t=!0){const s=this.cache.get(e),i=this.queries.get(e);let a=!1;s&&(a=0!==s.lastUpdated||void 0!==s.error,s.lastUpdated=0,s.error=void 0,this.emitEvent({type:"invalidation",key:e,timestamp:Date.now()}),a&&this.schedulePersistState(),t&&i&&this.fetch(e,i).catch((()=>{})))}async invalidatePattern(e,t=!0){const s=[];let i=!1;for(const t of this.cache.keys())e.test(t)&&s.push(t);s.forEach((e=>{const t=this.cache.get(e);t&&(0===t.lastUpdated&&void 0===t.error||(i=!0),t.lastUpdated=0,t.error=void 0,this.emitEvent({type:"invalidation",key:e,timestamp:Date.now()}))})),i&&this.schedulePersistState(),t&&s.length>0&&await Promise.all(s.map((e=>{const t=this.queries.get(e);return t?this.fetch(e,t).catch((()=>{})):Promise.resolve()})))}async prefetch(e){const t=this.queries.get(e);if(!t)return void console.warn(`Cannot prefetch: No query registered for key: ${e}`);const s=this.cache.get(e);s&&!this.isStale(s,t.options)||this.fetch(e,t).catch((()=>{}))}async refresh(e){const t=this.queries.get(e);if(!t)return void console.warn(`Cannot refresh: No query registered for key: ${e}`);this.fetching.delete(e);let s=this.cache.get(e);s?(s.isLoading=!0,s.error=void 0):(s={data:void 0,lastUpdated:0,lastAccessed:Date.now(),accessCount:0,isLoading:!0,error:void 0},this.cache.set(e,s),this.schedulePersistState());const i=this.performFetchWithRetry(e,t,s);this.fetching.set(e,i);try{return await i}finally{this.fetching.delete(e)}}setData(e,t){const s=this.cache.get(e),i=s?.data,a={data:t,lastUpdated:Date.now(),lastAccessed:Date.now(),accessCount:(s?.accessCount||0)+1,isLoading:!1,error:void 0};this.cache.set(e,a),this.schedulePersistState(),this.enforceSizeLimit(),this.emitEvent({type:"set_data",key:e,timestamp:Date.now(),newData:t,oldData:i})}remove(e){this.fetching.delete(e);const t=this.cache.has(e),s=this.cache.delete(e);return s&&t&&this.schedulePersistState(),s}enforceSizeLimit(e=!0){const{maxSize:t}=this.defaultOptions;if(t===1/0||this.cache.size<=t)return;let s=0;if(0===t){s=this.cache.size;for(const e of this.cache.keys())this.cache.delete(e),this.emitEvent({type:"eviction",key:e,timestamp:Date.now(),reason:"size_limit_zero"}),this.updateMetrics("evictions")}else{const e=Array.from(this.cache.entries()).sort((([,e],[,t])=>e.lastAccessed-t.lastAccessed)),i=this.cache.size-t;if(i>0){e.slice(0,i).forEach((([e])=>{this.cache.delete(e)&&(s++,this.emitEvent({type:"eviction",key:e,timestamp:Date.now(),reason:"size_limit_lru"}),this.updateMetrics("evictions"))}))}}s>0&&e&&this.schedulePersistState()}startGarbageCollection(){const{cacheTime:e}=this.defaultOptions;if(e===1/0||e<=0)return;const t=Math.max(1e3,Math.min(e/4,3e5));this.gcTimer=setInterval((()=>this.garbageCollect()),t)}garbageCollect(){const e=Date.now();let t=0;const s=[];for(const[t,i]of this.cache){if(i.isLoading)continue;const a=this.queries.get(t),r=a?.options.cacheTime??this.defaultOptions.cacheTime;r===1/0||r<=0||e-i.lastAccessed>r&&s.push(t)}return s.length>0&&(s.forEach((e=>{this.cache.delete(e)&&(this.fetching.delete(e),this.emitEvent({type:"eviction",key:e,timestamp:Date.now(),reason:"garbage_collected_idle"}),this.updateMetrics("evictions"),t++)})),this.schedulePersistState()),t}getStats(){const e=this.metrics.hits+this.metrics.misses,t=e>0?this.metrics.hits/e:0,s=this.metrics.hits>0?this.metrics.staleHits/this.metrics.hits:0,i=Array.from(this.cache.entries()).map((([e,t])=>{const s=this.queries.get(e),i=!s||this.isStale(t,s.options);return{key:e,lastAccessed:t.lastAccessed,lastUpdated:t.lastUpdated,accessCount:t.accessCount,isStale:i,isLoading:t.isLoading,error:!!t.error}}));return{size:this.cache.size,metrics:{...this.metrics},hitRate:t,staleHitRate:s,entries:i}}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}off(e,t){this.eventListeners.get(e)?.delete(t)}emitEvent(e){const t=this.eventListeners.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(t){const s="persistence"===e.type?`for ID ${e.key}`:`for key ${e.key}`;console.error(`Cache event listener error during ${e.type} ${s}:`,t)}}))}updateMetrics(e,t=1){this.defaultOptions.enableMetrics&&(this.metrics[e]=(this.metrics[e]||0)+t)}delay(e){return new Promise((t=>setTimeout(t,e)))}async clear(){const e=this.cache.size>0;if(this.cache.clear(),this.fetching.clear(),this.defaultOptions.enableMetrics&&(this.metrics={hits:0,misses:0,fetches:0,errors:0,evictions:0,staleHits:0}),this.defaultOptions.persistence)try{await this.defaultOptions.persistence.clear(),this.emitEvent({type:"persistence",key:this.persistenceId,timestamp:Date.now(),event:"clear_success"})}catch(e){console.error(`Cache (${this.persistenceId}): Failed to clear persisted state:`,e),this.emitEvent({type:"persistence",key:this.persistenceId,timestamp:Date.now(),event:"clear_fail",error:e})}else e&&this.schedulePersistState()}destroy(){if(this.gcTimer&&(clearInterval(this.gcTimer),this.gcTimer=void 0),this.persistenceDebounceTimer&&clearTimeout(this.persistenceDebounceTimer),this.persistenceUnsubscribe)try{this.persistenceUnsubscribe()}catch(e){console.error(`Cache (${this.persistenceId}): Error unsubscribing persistence:`,e)}this.cache.clear(),this.fetching.clear(),this.queries.clear(),this.eventListeners.clear(),this.metrics={hits:0,misses:0,fetches:0,errors:0,evictions:0,staleHits:0}}};export{t as Cache};
|
package/package.json
CHANGED
@@ -1,12 +1,12 @@
|
|
1
1
|
{
|
2
2
|
"name": "@asaidimu/utils-cache",
|
3
|
-
"version": "2.0.
|
3
|
+
"version": "2.0.2",
|
4
4
|
"description": "Caching utilities for @asaidimu applications.",
|
5
5
|
"main": "index.js",
|
6
6
|
"module": "index.mjs",
|
7
7
|
"types": "index.d.ts",
|
8
8
|
"files": [
|
9
|
-
"
|
9
|
+
"./*"
|
10
10
|
],
|
11
11
|
"keywords": [
|
12
12
|
"typescript",
|
@@ -29,7 +29,7 @@
|
|
29
29
|
"access": "public"
|
30
30
|
},
|
31
31
|
"dependencies": {
|
32
|
-
"@asaidimu/utils-persistence": "2.0.
|
32
|
+
"@asaidimu/utils-persistence": "2.0.1",
|
33
33
|
"uuid": "^11.1.0"
|
34
34
|
},
|
35
35
|
"exports": {
|
@@ -49,7 +49,7 @@
|
|
49
49
|
[
|
50
50
|
"@semantic-release/npm",
|
51
51
|
{
|
52
|
-
"pkgRoot": "
|
52
|
+
"pkgRoot": "./dist"
|
53
53
|
}
|
54
54
|
],
|
55
55
|
[
|