cacheable 2.1.0 → 2.2.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/dist/index.cjs CHANGED
@@ -1 +1,1087 @@
1
- "use strict";var A=Object.defineProperty;var B=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var k=(d,t)=>{for(var i in t)A(d,i,{get:t[i],enumerable:!0})},x=(d,t,i,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of P(t))!G.call(d,s)&&s!==i&&A(d,s,{get:()=>t[s],enumerable:!(e=B(t,s))||e.enumerable});return d};var N=d=>x(A({},"__esModule",{value:!0}),d);var Y={};k(Y,{Cacheable:()=>M,CacheableEvents:()=>R,CacheableHooks:()=>E,CacheableMemory:()=>f.CacheableMemory,CacheableStats:()=>l.Stats,CacheableSync:()=>_,CacheableSyncEvents:()=>S,HashAlgorithm:()=>l.HashAlgorithm,Keyv:()=>v.Keyv,KeyvCacheableMemory:()=>f.KeyvCacheableMemory,KeyvHooks:()=>v.KeyvHooks,calculateTtlFromExpiration:()=>l.calculateTtlFromExpiration,createKeyv:()=>f.createKeyv,getCascadingTtl:()=>l.getCascadingTtl,getOrSet:()=>m.getOrSet,hash:()=>l.hash,shorthandToMilliseconds:()=>l.shorthandToMilliseconds,shorthandToTime:()=>l.shorthandToTime,wrap:()=>m.wrap,wrapSync:()=>m.wrapSync});module.exports=N(Y);var T=require("@cacheable/memoize"),K=require("@cacheable/memory"),o=require("@cacheable/utils"),F=require("hookified"),O=require("keyv");var E=(c=>(c.BEFORE_SET="BEFORE_SET",c.AFTER_SET="AFTER_SET",c.BEFORE_SET_MANY="BEFORE_SET_MANY",c.AFTER_SET_MANY="AFTER_SET_MANY",c.BEFORE_GET="BEFORE_GET",c.AFTER_GET="AFTER_GET",c.BEFORE_GET_MANY="BEFORE_GET_MANY",c.AFTER_GET_MANY="AFTER_GET_MANY",c.BEFORE_SECONDARY_SETS_PRIMARY="BEFORE_SECONDARY_SETS_PRIMARY",c))(E||{}),R=(e=>(e.ERROR="error",e.CACHE_HIT="cache:hit",e.CACHE_MISS="cache:miss",e))(R||{});var I=require("hookified"),g=require("qified"),S=(e=>(e.ERROR="error",e.SET="cache:set",e.DELETE="cache:delete",e))(S||{}),_=class extends I.Hookified{_qified=new g.Qified;constructor(t){super(t),this._qified=this.createQified(t.qified)}get qified(){return this._qified}set qified(t){this._qified=this.createQified(t)}async publish(t,i){await this._qified.publish(t,{id:crypto.randomUUID(),data:i})}subscribe(t,i){this._qified.subscribe("cache:set",{handler:async e=>{let s=e.data;s.cacheId!==i&&await t.set(s.key,s.value,s.ttl)}}),this._qified.subscribe("cache:delete",{handler:async e=>{let s=e.data;s.cacheId!==i&&await t.delete(s.key)}})}createQified(t){if(t instanceof g.Qified)return t;let i=Array.isArray(t)?t:[t];return new g.Qified({messageProviders:i})}};var m=require("@cacheable/memoize"),f=require("@cacheable/memory"),l=require("@cacheable/utils"),v=require("keyv"),M=class extends F.Hookified{_primary=(0,K.createKeyv)();_secondary;_nonBlocking=!1;_ttl;_stats=new o.Stats({enabled:!1});_namespace;_cacheId=Math.random().toString(36).slice(2);_sync;constructor(t){super(),t?.primary&&this.setPrimary(t.primary),t?.secondary&&this.setSecondary(t.secondary),t?.nonBlocking&&(this._nonBlocking=t.nonBlocking),t?.stats&&(this._stats.enabled=t.stats),t?.ttl&&this.setTtl(t.ttl),t?.cacheId&&(this._cacheId=t.cacheId),t?.namespace&&(this._namespace=t.namespace,this._primary.namespace=this.getNameSpace(),this._secondary&&(this._secondary.namespace=this.getNameSpace())),t?.sync&&(this._sync=t.sync instanceof _?t.sync:new _(t.sync),this._sync.subscribe(this._primary,this._cacheId))}get namespace(){return this._namespace}set namespace(t){this._namespace=t,this._primary.namespace=this.getNameSpace(),this._secondary&&(this._secondary.namespace=this.getNameSpace())}get stats(){return this._stats}get primary(){return this._primary}set primary(t){this._primary=t}get secondary(){return this._secondary}set secondary(t){this._secondary=t}get nonBlocking(){return this._nonBlocking}set nonBlocking(t){this._nonBlocking=t}get ttl(){return this._ttl}set ttl(t){this.setTtl(t)}get cacheId(){return this._cacheId}set cacheId(t){this._cacheId=t}get sync(){return this._sync}set sync(t){this._sync=t,this._sync&&this._sync.subscribe(this._primary,this._cacheId)}setPrimary(t){(0,o.isKeyvInstance)(t)?this._primary=t:this._primary=new O.Keyv(t),this._primary.on("error",i=>{this.emit("error",i)})}setSecondary(t){(0,o.isKeyvInstance)(t)?this._secondary=t:this._secondary=new O.Keyv(t),this._secondary.on("error",i=>{this.emit("error",i)})}getNameSpace(){return typeof this._namespace=="function"?this._namespace():this._namespace}async get(t,i){return(await this.getRaw(t,i))?.value}async getRaw(t,i){let e;try{await this.hook("BEFORE_GET",t),e=await this._primary.getRaw(t);let s;e?this.emit("cache:hit",{key:t,value:e.value,store:"primary"}):this.emit("cache:miss",{key:t,store:"primary"});let n=i?.nonBlocking??this._nonBlocking;if(!e&&this._secondary){let a;n?a=await this.processSecondaryForGetRawNonBlocking(this._primary,this._secondary,t):a=await this.processSecondaryForGetRaw(this._primary,this._secondary,t),a&&(e=a.result,s=a.ttl)}await this.hook("AFTER_GET",{key:t,result:e,ttl:s})}catch(s){this.emit("error",s)}return this.stats.enabled&&(e?this._stats.incrementHits():this._stats.incrementMisses(),this.stats.incrementGets()),e}async getManyRaw(t,i){let e=[];try{await this.hook("BEFORE_GET_MANY",t),e=await this._primary.getManyRaw(t);for(let[n,a]of t.entries())e[n]?this.emit("cache:hit",{key:a,value:e[n].value,store:"primary"}):this.emit("cache:miss",{key:a,store:"primary"});let s=i?.nonBlocking??this._nonBlocking;this._secondary&&(s?await this.processSecondaryForGetManyRawNonBlocking(this._primary,this._secondary,t,e):await this.processSecondaryForGetManyRaw(this._primary,this._secondary,t,e)),await this.hook("AFTER_GET_MANY",{keys:t,result:e})}catch(s){this.emit("error",s)}if(this.stats.enabled){for(let s of e)s?this._stats.incrementHits():this._stats.incrementMisses();this.stats.incrementGets()}return e}async getMany(t,i){return(await this.getManyRaw(t,i)).map(s=>s?.value)}async set(t,i,e){let s=!1,n=(0,o.shorthandToMilliseconds)(e??this._ttl);try{let a={key:t,value:i,ttl:n};await this.hook("BEFORE_SET",a);let r=[];if(r.push(this._primary.set(a.key,a.value,a.ttl)),this._secondary&&r.push(this._secondary.set(a.key,a.value,a.ttl)),this._nonBlocking){s=await Promise.race(r);for(let h of r)h.catch(c=>{this.emit("error",c)})}else s=(await Promise.all(r))[0];await this.hook("AFTER_SET",a),this._sync&&s&&await this._sync.publish("cache:set",{cacheId:this._cacheId,key:a.key,value:a.value,ttl:a.ttl})}catch(a){this.emit("error",a)}return this.stats.enabled&&(this.stats.incrementKSize(t),this.stats.incrementCount(),this.stats.incrementVSize(i),this.stats.incrementSets()),s}async setMany(t){let i=!1;try{if(await this.hook("BEFORE_SET_MANY",t),i=await this.setManyKeyv(this._primary,t),this._secondary&&(this._nonBlocking?this.setManyKeyv(this._secondary,t).catch(e=>{this.emit("error",e)}):await this.setManyKeyv(this._secondary,t)),await this.hook("AFTER_SET_MANY",t),this._sync&&i)for(let e of t)await this._sync.publish("cache:set",{cacheId:this._cacheId,key:e.key,value:e.value,ttl:(0,o.shorthandToMilliseconds)(e.ttl)})}catch(e){this.emit("error",e)}if(this.stats.enabled)for(let e of t)this.stats.incrementKSize(e.key),this.stats.incrementCount(),this.stats.incrementVSize(e.value);return i}async take(t){let i=await this.get(t);return await this.delete(t),i}async takeMany(t){let i=await this.getMany(t);return await this.deleteMany(t),i}async has(t){let i=[];i.push(this._primary.has(t)),this._secondary&&i.push(this._secondary.has(t));let e=await Promise.all(i);for(let s of e)if(s)return!0;return!1}async hasMany(t){let i=await this.hasManyKeyv(this._primary,t),e=[];for(let[s,n]of t.entries())!i[s]&&this._secondary&&e.push(n);if(e.length>0&&this._secondary){let s=await this.hasManyKeyv(this._secondary,t);for(let[n,a]of t.entries())!i[n]&&s[n]&&(i[n]=s[n])}return i}async delete(t){let i=!1,e=[];if(this.stats.enabled){let s=await this._primary.get(t);s&&(this.stats.decreaseKSize(t),this.stats.decreaseVSize(s),this.stats.decreaseCount(),this.stats.incrementDeletes())}if(e.push(this._primary.delete(t)),this._secondary&&e.push(this._secondary.delete(t)),this.nonBlocking){i=await Promise.race(e);for(let s of e)s.catch(n=>{this.emit("error",n)})}else i=(await Promise.all(e))[0];return this._sync&&i&&await this._sync.publish("cache:delete",{cacheId:this._cacheId,key:t}),i}async deleteMany(t){if(this.stats.enabled){let e=await this._primary.get(t);for(let s of t)this.stats.decreaseKSize(s),this.stats.decreaseVSize(e),this.stats.decreaseCount(),this.stats.incrementDeletes()}let i=await this._primary.deleteMany(t);if(this._secondary&&(this._nonBlocking?this._secondary.deleteMany(t).catch(e=>{this.emit("error",e)}):await this._secondary.deleteMany(t)),this._sync&&i)for(let e of t)await this._sync.publish("cache:delete",{cacheId:this._cacheId,key:e});return i}async clear(){let t=[];t.push(this._primary.clear()),this._secondary&&t.push(this._secondary.clear()),await(this._nonBlocking?Promise.race(t):Promise.all(t)),this.stats.enabled&&(this._stats.resetStoreValues(),this._stats.incrementClears())}async disconnect(){let t=[];t.push(this._primary.disconnect()),this._secondary&&t.push(this._secondary.disconnect()),await(this._nonBlocking?Promise.race(t):Promise.all(t))}wrap(t,i){let e={get:async n=>this.get(n),has:async n=>this.has(n),set:async(n,a,r)=>{await this.set(n,a,r)},on:(n,a)=>{this.on(n,a)},emit:(n,...a)=>this.emit(n,...a)},s={ttl:i?.ttl??this._ttl,keyPrefix:i?.keyPrefix,createKey:i?.createKey,cacheErrors:i?.cacheErrors,cache:e,cacheId:this._cacheId,serialize:i?.serialize};return(0,T.wrap)(t,s)}async getOrSet(t,i,e){let n={cache:{get:async a=>this.get(a),has:async a=>this.has(a),set:async(a,r,h)=>{await this.set(a,r,h)},on:(a,r)=>{this.on(a,r)},emit:(a,...r)=>this.emit(a,...r)},cacheId:this._cacheId,ttl:e?.ttl??this._ttl,cacheErrors:e?.cacheErrors,throwErrors:e?.throwErrors};return(0,T.getOrSet)(t,i,n)}hash(t,i=o.HashAlgorithm.SHA256){let e=Object.values(o.HashAlgorithm).includes(i)?i:o.HashAlgorithm.SHA256;return(0,o.hash)(t,{algorithm:e})}async setManyKeyv(t,i){let e=[];for(let s of i){let n=(0,o.shorthandToMilliseconds)(s.ttl??this._ttl);e.push({key:s.key,value:s.value,ttl:n})}return await t.setMany(e),!0}async hasManyKeyv(t,i){let e=[];for(let s of i)e.push(t.has(s));return Promise.all(e)}async processSecondaryForGetRaw(t,i,e){let s=await i.getRaw(e);if(s?.value){this.emit("cache:hit",{key:e,value:s.value,store:"secondary"});let n=(0,o.getCascadingTtl)(this._ttl,this._primary.ttl),a=s.expires??void 0,r=(0,o.calculateTtlFromExpiration)(n,a),h={key:e,value:s.value,ttl:r};return await this.hook("BEFORE_SECONDARY_SETS_PRIMARY",h),await t.set(h.key,h.value,h.ttl),{result:s,ttl:r}}else{this.emit("cache:miss",{key:e,store:"secondary"});return}}async processSecondaryForGetRawNonBlocking(t,i,e){let s=await i.getRaw(e);if(s?.value){this.emit("cache:hit",{key:e,value:s.value,store:"secondary"});let n=(0,o.getCascadingTtl)(this._ttl,this._primary.ttl),a=s.expires??void 0,r=(0,o.calculateTtlFromExpiration)(n,a),h={key:e,value:s.value,ttl:r};return this.hook("BEFORE_SECONDARY_SETS_PRIMARY",h).then(async()=>{await t.set(h.key,h.value,h.ttl)}).catch(c=>{this.emit("error",c)}),{result:s,ttl:r}}else{this.emit("cache:miss",{key:e,store:"secondary"});return}}async processSecondaryForGetManyRaw(t,i,e,s){let n=[];for(let[h,c]of e.entries())s[h]||n.push(c);let a=await i.getManyRaw(n),r=0;for await(let[h,c]of e.entries())if(!s[h]){let y=a[r];if(y&&y.value!==void 0){s[h]=y,this.emit("cache:hit",{key:c,value:y.value,store:"secondary"});let b=(0,o.getCascadingTtl)(this._ttl,this._primary.ttl),{expires:u}=y;u===null&&(u=void 0);let w=(0,o.calculateTtlFromExpiration)(b,u),p={key:c,value:y.value,ttl:w};await this.hook("BEFORE_SECONDARY_SETS_PRIMARY",p),await t.set(p.key,p.value,p.ttl)}else this.emit("cache:miss",{key:c,store:"secondary"});r++}}async processSecondaryForGetManyRawNonBlocking(t,i,e,s){let n=[];for(let[h,c]of e.entries())s[h]||n.push(c);let a=await i.getManyRaw(n),r=0;for await(let[h,c]of e.entries())if(!s[h]){let y=a[r];if(y&&y.value!==void 0){s[h]=y,this.emit("cache:hit",{key:c,value:y.value,store:"secondary"});let b=(0,o.getCascadingTtl)(this._ttl,this._primary.ttl),{expires:u}=y;u===null&&(u=void 0);let w=(0,o.calculateTtlFromExpiration)(b,u),p={key:c,value:y.value,ttl:w};this.hook("BEFORE_SECONDARY_SETS_PRIMARY",p).then(async()=>{await t.set(p.key,p.value,p.ttl)}).catch(C=>{this.emit("error",C)})}else this.emit("cache:miss",{key:c,store:"secondary"});r++}}setTtl(t){typeof t=="string"||t===void 0?this._ttl=t:t>0?this._ttl=t:this._ttl=void 0}};0&&(module.exports={Cacheable,CacheableEvents,CacheableHooks,CacheableMemory,CacheableStats,CacheableSync,CacheableSyncEvents,HashAlgorithm,Keyv,KeyvCacheableMemory,KeyvHooks,calculateTtlFromExpiration,createKeyv,getCascadingTtl,getOrSet,hash,shorthandToMilliseconds,shorthandToTime,wrap,wrapSync});
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ Cacheable: () => Cacheable,
24
+ CacheableEvents: () => CacheableEvents,
25
+ CacheableHooks: () => CacheableHooks,
26
+ CacheableMemory: () => import_memory2.CacheableMemory,
27
+ CacheableStats: () => import_utils2.Stats,
28
+ CacheableSync: () => CacheableSync,
29
+ CacheableSyncEvents: () => CacheableSyncEvents,
30
+ HashAlgorithm: () => import_utils2.HashAlgorithm,
31
+ Keyv: () => import_keyv2.Keyv,
32
+ KeyvCacheableMemory: () => import_memory2.KeyvCacheableMemory,
33
+ KeyvHooks: () => import_keyv2.KeyvHooks,
34
+ calculateTtlFromExpiration: () => import_utils2.calculateTtlFromExpiration,
35
+ createKeyv: () => import_memory2.createKeyv,
36
+ getCascadingTtl: () => import_utils2.getCascadingTtl,
37
+ getOrSet: () => import_utils2.getOrSet,
38
+ hash: () => import_utils2.hash,
39
+ shorthandToMilliseconds: () => import_utils2.shorthandToMilliseconds,
40
+ shorthandToTime: () => import_utils2.shorthandToTime,
41
+ wrap: () => import_utils2.wrap,
42
+ wrapSync: () => import_utils2.wrapSync
43
+ });
44
+ module.exports = __toCommonJS(index_exports);
45
+ var import_memory = require("@cacheable/memory");
46
+ var import_utils = require("@cacheable/utils");
47
+ var import_hookified2 = require("hookified");
48
+ var import_keyv = require("keyv");
49
+
50
+ // src/enums.ts
51
+ var CacheableHooks = /* @__PURE__ */ ((CacheableHooks2) => {
52
+ CacheableHooks2["BEFORE_SET"] = "BEFORE_SET";
53
+ CacheableHooks2["AFTER_SET"] = "AFTER_SET";
54
+ CacheableHooks2["BEFORE_SET_MANY"] = "BEFORE_SET_MANY";
55
+ CacheableHooks2["AFTER_SET_MANY"] = "AFTER_SET_MANY";
56
+ CacheableHooks2["BEFORE_GET"] = "BEFORE_GET";
57
+ CacheableHooks2["AFTER_GET"] = "AFTER_GET";
58
+ CacheableHooks2["BEFORE_GET_MANY"] = "BEFORE_GET_MANY";
59
+ CacheableHooks2["AFTER_GET_MANY"] = "AFTER_GET_MANY";
60
+ CacheableHooks2["BEFORE_SECONDARY_SETS_PRIMARY"] = "BEFORE_SECONDARY_SETS_PRIMARY";
61
+ return CacheableHooks2;
62
+ })(CacheableHooks || {});
63
+ var CacheableEvents = /* @__PURE__ */ ((CacheableEvents2) => {
64
+ CacheableEvents2["ERROR"] = "error";
65
+ CacheableEvents2["CACHE_HIT"] = "cache:hit";
66
+ CacheableEvents2["CACHE_MISS"] = "cache:miss";
67
+ return CacheableEvents2;
68
+ })(CacheableEvents || {});
69
+
70
+ // src/sync.ts
71
+ var import_hookified = require("hookified");
72
+ var import_qified = require("qified");
73
+ var CacheableSyncEvents = /* @__PURE__ */ ((CacheableSyncEvents2) => {
74
+ CacheableSyncEvents2["ERROR"] = "error";
75
+ CacheableSyncEvents2["SET"] = "cache:set";
76
+ CacheableSyncEvents2["DELETE"] = "cache:delete";
77
+ return CacheableSyncEvents2;
78
+ })(CacheableSyncEvents || {});
79
+ var CacheableSync = class extends import_hookified.Hookified {
80
+ _qified = new import_qified.Qified();
81
+ /**
82
+ * Creates an instance of CacheableSync
83
+ * @param options - Configuration options for CacheableSync
84
+ */
85
+ constructor(options) {
86
+ super(options);
87
+ this._qified = this.createQified(options.qified);
88
+ }
89
+ /**
90
+ * Gets the Qified instance used for synchronization
91
+ * @returns The Qified instance
92
+ */
93
+ get qified() {
94
+ return this._qified;
95
+ }
96
+ /**
97
+ * Sets the Qified instance used for synchronization
98
+ * @param value - Either an existing Qified instance or MessageProvider(s)
99
+ */
100
+ set qified(value) {
101
+ this._qified = this.createQified(value);
102
+ }
103
+ /**
104
+ * Publishes a cache event to all the cache instances
105
+ * @param data - The cache item data containing cacheId, key, value, and optional ttl
106
+ */
107
+ async publish(event, data) {
108
+ await this._qified.publish(event, {
109
+ id: crypto.randomUUID(),
110
+ data
111
+ });
112
+ }
113
+ /**
114
+ * Subscribes to sync events and updates the provided storage
115
+ * @param storage - The Keyv storage instance to update
116
+ * @param cacheId - The cache ID to identify this instance
117
+ */
118
+ subscribe(storage, cacheId) {
119
+ this._qified.subscribe("cache:set" /* SET */, {
120
+ handler: async (message) => {
121
+ const data = message.data;
122
+ if (data.cacheId !== cacheId) {
123
+ await storage.set(data.key, data.value, data.ttl);
124
+ }
125
+ }
126
+ });
127
+ this._qified.subscribe("cache:delete" /* DELETE */, {
128
+ handler: async (message) => {
129
+ const data = message.data;
130
+ if (data.cacheId !== cacheId) {
131
+ await storage.delete(data.key);
132
+ }
133
+ }
134
+ });
135
+ }
136
+ /**
137
+ * Creates or returns a Qified instance from the provided value
138
+ * @param value - Either an existing Qified instance or MessageProvider(s)
139
+ * @returns A Qified instance configured with the provided message provider(s)
140
+ */
141
+ createQified(value) {
142
+ if (value instanceof import_qified.Qified) {
143
+ return value;
144
+ }
145
+ const providers = Array.isArray(value) ? value : [value];
146
+ return new import_qified.Qified({ messageProviders: providers });
147
+ }
148
+ };
149
+
150
+ // src/index.ts
151
+ var import_memory2 = require("@cacheable/memory");
152
+ var import_utils2 = require("@cacheable/utils");
153
+ var import_keyv2 = require("keyv");
154
+ var Cacheable = class extends import_hookified2.Hookified {
155
+ _primary = (0, import_memory.createKeyv)();
156
+ _secondary;
157
+ _nonBlocking = false;
158
+ _ttl;
159
+ _stats = new import_utils.Stats({ enabled: false });
160
+ _namespace;
161
+ _cacheId = Math.random().toString(36).slice(2);
162
+ _sync;
163
+ /**
164
+ * Creates a new cacheable instance
165
+ * @param {CacheableOptions} [options] The options for the cacheable instance
166
+ */
167
+ constructor(options) {
168
+ super();
169
+ if (options?.primary) {
170
+ this.setPrimary(options.primary);
171
+ }
172
+ if (options?.secondary) {
173
+ this.setSecondary(options.secondary);
174
+ }
175
+ if (options?.nonBlocking) {
176
+ this._nonBlocking = options.nonBlocking;
177
+ }
178
+ if (options?.stats) {
179
+ this._stats.enabled = options.stats;
180
+ }
181
+ if (options?.ttl) {
182
+ this.setTtl(options.ttl);
183
+ }
184
+ if (options?.cacheId) {
185
+ this._cacheId = options.cacheId;
186
+ }
187
+ if (options?.namespace) {
188
+ this._namespace = options.namespace;
189
+ this._primary.namespace = this.getNameSpace();
190
+ if (this._secondary) {
191
+ this._secondary.namespace = this.getNameSpace();
192
+ }
193
+ }
194
+ if (options?.sync) {
195
+ this._sync = options.sync instanceof CacheableSync ? options.sync : new CacheableSync(options.sync);
196
+ this._sync.subscribe(this._primary, this._cacheId);
197
+ }
198
+ }
199
+ /**
200
+ * The namespace for the cacheable instance
201
+ * @returns {string | (() => string) | undefined} The namespace for the cacheable instance
202
+ */
203
+ get namespace() {
204
+ return this._namespace;
205
+ }
206
+ /**
207
+ * Sets the namespace for the cacheable instance
208
+ * @param {string | (() => string) | undefined} namespace The namespace for the cacheable instance
209
+ * @returns {void}
210
+ */
211
+ set namespace(namespace) {
212
+ this._namespace = namespace;
213
+ this._primary.namespace = this.getNameSpace();
214
+ if (this._secondary) {
215
+ this._secondary.namespace = this.getNameSpace();
216
+ }
217
+ }
218
+ /**
219
+ * The statistics for the cacheable instance
220
+ * @returns {CacheableStats} The statistics for the cacheable instance
221
+ */
222
+ get stats() {
223
+ return this._stats;
224
+ }
225
+ /**
226
+ * The primary store for the cacheable instance
227
+ * @returns {Keyv} The primary store for the cacheable instance
228
+ */
229
+ get primary() {
230
+ return this._primary;
231
+ }
232
+ /**
233
+ * Sets the primary store for the cacheable instance
234
+ * @param {Keyv} primary The primary store for the cacheable instance
235
+ */
236
+ set primary(primary) {
237
+ this._primary = primary;
238
+ }
239
+ /**
240
+ * The secondary store for the cacheable instance
241
+ * @returns {Keyv | undefined} The secondary store for the cacheable instance
242
+ */
243
+ get secondary() {
244
+ return this._secondary;
245
+ }
246
+ /**
247
+ * Sets the secondary store for the cacheable instance. If it is set to undefined then the secondary store is disabled.
248
+ * @param {Keyv | undefined} secondary The secondary store for the cacheable instance
249
+ * @returns {void}
250
+ */
251
+ set secondary(secondary) {
252
+ this._secondary = secondary;
253
+ }
254
+ /**
255
+ * Gets whether the secondary store is non-blocking mode. It is set to false by default.
256
+ * If it is set to true then the secondary store will not block the primary store.
257
+ *
258
+ * [Learn more about non-blocking mode](https://cacheable.org/docs/cacheable/#non-blocking-operations).
259
+ *
260
+ * @returns {boolean} Whether the cacheable instance is non-blocking
261
+ */
262
+ get nonBlocking() {
263
+ return this._nonBlocking;
264
+ }
265
+ /**
266
+ * Sets whether the secondary store is non-blocking mode. It is set to false by default.
267
+ * If it is set to true then the secondary store will not block the primary store.
268
+ *
269
+ * [Learn more about non-blocking mode](https://cacheable.org/docs/cacheable/#non-blocking-operations).
270
+ *
271
+ * @param {boolean} nonBlocking Whether the cacheable instance is non-blocking
272
+ * @returns {void}
273
+ */
274
+ set nonBlocking(nonBlocking) {
275
+ this._nonBlocking = nonBlocking;
276
+ }
277
+ /**
278
+ * The time-to-live for the cacheable instance and will be used as the default value.
279
+ * can be a number in milliseconds or a human-readable format such as `1s` for 1 second or `1h` for 1 hour
280
+ * or undefined if there is no time-to-live.
281
+ *
282
+ * [Learn more about time-to-live](https://cacheable.org/docs/cacheable/#shorthand-for-time-to-live-ttl).
283
+ *
284
+ * @returns {number | string | undefined} The time-to-live for the cacheable instance in milliseconds, human-readable format or undefined
285
+ * @example
286
+ * ```typescript
287
+ * const cacheable = new Cacheable({ ttl: '1h' });
288
+ * console.log(cacheable.ttl); // 1h
289
+ * ```
290
+ */
291
+ get ttl() {
292
+ return this._ttl;
293
+ }
294
+ /**
295
+ * Sets the time-to-live for the cacheable instance and will be used as the default value.
296
+ * If you set a number it is miliseconds, if you set a string it is a human-readable
297
+ * format such as `1s` for 1 second or `1h` for 1 hour. Setting undefined means that
298
+ * there is no time-to-live.
299
+ *
300
+ * [Learn more about time-to-live](https://cacheable.org/docs/cacheable/#shorthand-for-time-to-live-ttl).
301
+ *
302
+ * @param {number | string | undefined} ttl The time-to-live for the cacheable instance
303
+ * @example
304
+ * ```typescript
305
+ * const cacheable = new Cacheable();
306
+ * cacheable.ttl = '1h'; // Set the time-to-live to 1 hour
307
+ * ```
308
+ * or setting the time-to-live in milliseconds
309
+ * ```typescript
310
+ * const cacheable = new Cacheable();
311
+ * cacheable.ttl = 3600000; // Set the time-to-live to 1 hour
312
+ * ```
313
+ */
314
+ set ttl(ttl) {
315
+ this.setTtl(ttl);
316
+ }
317
+ /**
318
+ * The cacheId for the cacheable instance. This is primarily used for the wrap function to not have conflicts.
319
+ * If it is not set then it will be a random string that is generated
320
+ * @returns {string} The cacheId for the cacheable instance
321
+ */
322
+ get cacheId() {
323
+ return this._cacheId;
324
+ }
325
+ /**
326
+ * Sets the cacheId for the cacheable instance. This is primarily used for the wrap function to not have conflicts.
327
+ * If it is not set then it will be a random string that is generated
328
+ * @param {string} cacheId The cacheId for the cacheable instance
329
+ */
330
+ set cacheId(cacheId) {
331
+ this._cacheId = cacheId;
332
+ }
333
+ /**
334
+ * Gets the sync instance for the cacheable instance
335
+ * @returns {CacheableSync | undefined} The sync instance for the cacheable instance
336
+ */
337
+ get sync() {
338
+ return this._sync;
339
+ }
340
+ /**
341
+ * Sets the sync instance for the cacheable instance
342
+ * @param {CacheableSync | undefined} sync The sync instance for the cacheable instance
343
+ */
344
+ set sync(sync) {
345
+ this._sync = sync;
346
+ if (this._sync) {
347
+ this._sync.subscribe(this._primary, this._cacheId);
348
+ }
349
+ }
350
+ /**
351
+ * Sets the primary store for the cacheable instance
352
+ * @param {Keyv | KeyvStoreAdapter} primary The primary store for the cacheable instance
353
+ * @returns {void}
354
+ */
355
+ setPrimary(primary) {
356
+ if ((0, import_utils.isKeyvInstance)(primary)) {
357
+ this._primary = primary;
358
+ } else {
359
+ this._primary = new import_keyv.Keyv(primary);
360
+ }
361
+ this._primary.on("error", (error) => {
362
+ this.emit("error" /* ERROR */, error);
363
+ });
364
+ }
365
+ /**
366
+ * Sets the secondary store for the cacheable instance. If it is set to undefined then the secondary store is disabled.
367
+ * @param {Keyv | KeyvStoreAdapter} secondary The secondary store for the cacheable instance
368
+ * @returns {void}
369
+ */
370
+ setSecondary(secondary) {
371
+ if ((0, import_utils.isKeyvInstance)(secondary)) {
372
+ this._secondary = secondary;
373
+ } else {
374
+ this._secondary = new import_keyv.Keyv(secondary);
375
+ }
376
+ this._secondary.on("error", (error) => {
377
+ this.emit("error" /* ERROR */, error);
378
+ });
379
+ }
380
+ getNameSpace() {
381
+ if (typeof this._namespace === "function") {
382
+ return this._namespace();
383
+ }
384
+ return this._namespace;
385
+ }
386
+ /**
387
+ * Retrieves an entry from the cache.
388
+ *
389
+ * Checks the primary store first; if not found and a secondary store is configured,
390
+ * it will fetch from the secondary, repopulate the primary, and return the result.
391
+ *
392
+ * @typeParam T - The expected type of the stored value.
393
+ * @param {string} key - The cache key to retrieve.
394
+ * @param {GetOptions} - options such as to bypass `nonBlocking` for this call
395
+ * @returns {Promise<T | undefined>}
396
+ * A promise that resolves to the cached value if found, or `undefined`.
397
+ */
398
+ async get(key, options) {
399
+ const result = await this.getRaw(key, options);
400
+ return result?.value;
401
+ }
402
+ /**
403
+ * Retrieves the raw entry from the cache including metadata like expiration.
404
+ *
405
+ * Checks the primary store first; if not found and a secondary store is configured,
406
+ * it will fetch from the secondary, repopulate the primary, and return the result.
407
+ *
408
+ * @typeParam T - The expected type of the stored value.
409
+ * @param {string} key - The cache key to retrieve.
410
+ * @param {GetOptions} - options such as to bypass `nonBlocking` for this call
411
+ * @returns {Promise<StoredDataRaw<T>>}
412
+ * A promise that resolves to the full raw data object if found, or undefined.
413
+ */
414
+ async getRaw(key, options) {
415
+ let result;
416
+ try {
417
+ await this.hook("BEFORE_GET" /* BEFORE_GET */, key);
418
+ result = await this._primary.getRaw(key);
419
+ let ttl;
420
+ if (result) {
421
+ this.emit("cache:hit" /* CACHE_HIT */, {
422
+ key,
423
+ value: result.value,
424
+ store: "primary"
425
+ });
426
+ } else {
427
+ this.emit("cache:miss" /* CACHE_MISS */, { key, store: "primary" });
428
+ }
429
+ const nonBlocking = options?.nonBlocking ?? this._nonBlocking;
430
+ if (!result && this._secondary) {
431
+ let secondaryProcessResult;
432
+ if (nonBlocking) {
433
+ secondaryProcessResult = await this.processSecondaryForGetRawNonBlocking(
434
+ this._primary,
435
+ this._secondary,
436
+ key
437
+ );
438
+ } else {
439
+ secondaryProcessResult = await this.processSecondaryForGetRaw(
440
+ this._primary,
441
+ this._secondary,
442
+ key
443
+ );
444
+ }
445
+ if (secondaryProcessResult) {
446
+ result = secondaryProcessResult.result;
447
+ ttl = secondaryProcessResult.ttl;
448
+ }
449
+ }
450
+ await this.hook("AFTER_GET" /* AFTER_GET */, { key, result, ttl });
451
+ } catch (error) {
452
+ this.emit("error" /* ERROR */, error);
453
+ }
454
+ if (this.stats.enabled) {
455
+ if (result) {
456
+ this._stats.incrementHits();
457
+ } else {
458
+ this._stats.incrementMisses();
459
+ }
460
+ this.stats.incrementGets();
461
+ }
462
+ return result;
463
+ }
464
+ /**
465
+ * Retrieves multiple raw entries from the cache including metadata like expiration.
466
+ *
467
+ * Checks the primary store for each key; if a key is missing and a secondary store is configured,
468
+ * it will fetch from the secondary store, repopulate the primary store, and return the results.
469
+ *
470
+ * @typeParam T - The expected type of the stored values.
471
+ * @param {string[]} keys - The cache keys to retrieve.
472
+ * @param {GetOptions} - options such as to bypass `nonBlocking` on this call
473
+ * @returns {Promise<Array<StoredDataRaw<T>>>}
474
+ * A promise that resolves to an array of raw data objects.
475
+ */
476
+ async getManyRaw(keys, options) {
477
+ let result = [];
478
+ try {
479
+ await this.hook("BEFORE_GET_MANY" /* BEFORE_GET_MANY */, keys);
480
+ result = await this._primary.getManyRaw(keys);
481
+ for (const [i, key] of keys.entries()) {
482
+ if (result[i]) {
483
+ this.emit("cache:hit" /* CACHE_HIT */, {
484
+ key,
485
+ value: result[i].value,
486
+ store: "primary"
487
+ });
488
+ } else {
489
+ this.emit("cache:miss" /* CACHE_MISS */, { key, store: "primary" });
490
+ }
491
+ }
492
+ const nonBlocking = options?.nonBlocking ?? this._nonBlocking;
493
+ if (this._secondary) {
494
+ if (nonBlocking) {
495
+ await this.processSecondaryForGetManyRawNonBlocking(
496
+ this._primary,
497
+ this._secondary,
498
+ keys,
499
+ result
500
+ );
501
+ } else {
502
+ await this.processSecondaryForGetManyRaw(
503
+ this._primary,
504
+ this._secondary,
505
+ keys,
506
+ result
507
+ );
508
+ }
509
+ }
510
+ await this.hook("AFTER_GET_MANY" /* AFTER_GET_MANY */, { keys, result });
511
+ } catch (error) {
512
+ this.emit("error" /* ERROR */, error);
513
+ }
514
+ if (this.stats.enabled) {
515
+ for (const item of result) {
516
+ if (item) {
517
+ this._stats.incrementHits();
518
+ } else {
519
+ this._stats.incrementMisses();
520
+ }
521
+ }
522
+ this.stats.incrementGets();
523
+ }
524
+ return result;
525
+ }
526
+ /**
527
+ * Retrieves multiple entries from the cache.
528
+ * Checks the primary store for each key; if a key is missing and a secondary store is configured,
529
+ * it will fetch from the secondary store, repopulate the primary store, and return the results.
530
+ *
531
+ * @typeParam T - The expected type of the stored values.
532
+ * @param {string[]} keys - The cache keys to retrieve.
533
+ * @param {GetOptions} - options such as to bypass `nonBlocking` on this call
534
+ * @returns {Promise<Array<T | undefined>>}
535
+ * A promise that resolves to an array of cached values or `undefined` for misses.
536
+ */
537
+ async getMany(keys, options) {
538
+ const result = await this.getManyRaw(keys, options);
539
+ return result.map((item) => item?.value);
540
+ }
541
+ /**
542
+ * Sets the value of the key. If the secondary store is set then it will also set the value in the secondary store.
543
+ * @param {string} key the key to set the value of
544
+ * @param {T} value The value to set
545
+ * @param {number | string} [ttl] set a number it is miliseconds, set a string it is a human-readable
546
+ * format such as `1s` for 1 second or `1h` for 1 hour. Setting undefined means that it will use the default time-to-live.
547
+ * @returns {boolean} Whether the value was set
548
+ */
549
+ async set(key, value, ttl) {
550
+ let result = false;
551
+ const finalTtl = (0, import_utils.shorthandToMilliseconds)(ttl ?? this._ttl);
552
+ try {
553
+ const item = { key, value, ttl: finalTtl };
554
+ await this.hook("BEFORE_SET" /* BEFORE_SET */, item);
555
+ const promises = [];
556
+ promises.push(this._primary.set(item.key, item.value, item.ttl));
557
+ if (this._secondary) {
558
+ promises.push(this._secondary.set(item.key, item.value, item.ttl));
559
+ }
560
+ if (this._nonBlocking) {
561
+ result = await Promise.race(promises);
562
+ for (const promise of promises) {
563
+ promise.catch((error) => {
564
+ this.emit("error" /* ERROR */, error);
565
+ });
566
+ }
567
+ } else {
568
+ const results = await Promise.all(promises);
569
+ result = results[0];
570
+ }
571
+ await this.hook("AFTER_SET" /* AFTER_SET */, item);
572
+ if (this._sync && result) {
573
+ await this._sync.publish("cache:set" /* SET */, {
574
+ cacheId: this._cacheId,
575
+ key: item.key,
576
+ value: item.value,
577
+ ttl: item.ttl
578
+ });
579
+ }
580
+ } catch (error) {
581
+ this.emit("error" /* ERROR */, error);
582
+ }
583
+ if (this.stats.enabled) {
584
+ this.stats.incrementKSize(key);
585
+ this.stats.incrementCount();
586
+ this.stats.incrementVSize(value);
587
+ this.stats.incrementSets();
588
+ }
589
+ return result;
590
+ }
591
+ /**
592
+ * Sets the values of the keys. If the secondary store is set then it will also set the values in the secondary store.
593
+ * @param {CacheableItem[]} items The items to set
594
+ * @returns {boolean} Whether the values were set
595
+ */
596
+ async setMany(items) {
597
+ let result = false;
598
+ try {
599
+ await this.hook("BEFORE_SET_MANY" /* BEFORE_SET_MANY */, items);
600
+ result = await this.setManyKeyv(this._primary, items);
601
+ if (this._secondary) {
602
+ if (this._nonBlocking) {
603
+ this.setManyKeyv(this._secondary, items).catch((error) => {
604
+ this.emit("error" /* ERROR */, error);
605
+ });
606
+ } else {
607
+ await this.setManyKeyv(this._secondary, items);
608
+ }
609
+ }
610
+ await this.hook("AFTER_SET_MANY" /* AFTER_SET_MANY */, items);
611
+ if (this._sync && result) {
612
+ for (const item of items) {
613
+ await this._sync.publish("cache:set" /* SET */, {
614
+ cacheId: this._cacheId,
615
+ key: item.key,
616
+ value: item.value,
617
+ ttl: (0, import_utils.shorthandToMilliseconds)(item.ttl)
618
+ });
619
+ }
620
+ }
621
+ } catch (error) {
622
+ this.emit("error" /* ERROR */, error);
623
+ }
624
+ if (this.stats.enabled) {
625
+ for (const item of items) {
626
+ this.stats.incrementKSize(item.key);
627
+ this.stats.incrementCount();
628
+ this.stats.incrementVSize(item.value);
629
+ }
630
+ }
631
+ return result;
632
+ }
633
+ /**
634
+ * Takes the value of the key and deletes the key. If the key does not exist then it will return undefined.
635
+ * @param {string} key The key to take the value of
636
+ * @returns {Promise<T | undefined>} The value of the key or undefined if the key does not exist
637
+ */
638
+ async take(key) {
639
+ const result = await this.get(key);
640
+ await this.delete(key);
641
+ return result;
642
+ }
643
+ /**
644
+ * Takes the values of the keys and deletes the keys. If the key does not exist then it will return undefined.
645
+ * @param {string[]} keys The keys to take the values of
646
+ * @returns {Promise<Array<T | undefined>>} The values of the keys or undefined if the key does not exist
647
+ */
648
+ async takeMany(keys) {
649
+ const result = await this.getMany(keys);
650
+ await this.deleteMany(keys);
651
+ return result;
652
+ }
653
+ /**
654
+ * Checks if the key exists in the primary store. If it does not exist then it will check the secondary store.
655
+ * @param {string} key The key to check
656
+ * @returns {Promise<boolean>} Whether the key exists
657
+ */
658
+ async has(key) {
659
+ const promises = [];
660
+ promises.push(this._primary.has(key));
661
+ if (this._secondary) {
662
+ promises.push(this._secondary.has(key));
663
+ }
664
+ const resultAll = await Promise.all(promises);
665
+ for (const result of resultAll) {
666
+ if (result) {
667
+ return true;
668
+ }
669
+ }
670
+ return false;
671
+ }
672
+ /**
673
+ * Checks if the keys exist in the primary store. If it does not exist then it will check the secondary store.
674
+ * @param {string[]} keys The keys to check
675
+ * @returns {Promise<boolean[]>} Whether the keys exist
676
+ */
677
+ async hasMany(keys) {
678
+ const result = await this._primary.hasMany(keys);
679
+ const missingKeys = [];
680
+ for (const [i, key] of keys.entries()) {
681
+ if (!result[i] && this._secondary) {
682
+ missingKeys.push(key);
683
+ }
684
+ }
685
+ if (missingKeys.length > 0 && this._secondary) {
686
+ const secondary = await this._secondary.hasMany(keys);
687
+ for (const [i, _key] of keys.entries()) {
688
+ if (!result[i] && secondary[i]) {
689
+ result[i] = secondary[i];
690
+ }
691
+ }
692
+ }
693
+ return result;
694
+ }
695
+ /**
696
+ * Deletes the key from the primary store. If the secondary store is set then it will also delete the key from the secondary store.
697
+ * @param {string} key The key to delete
698
+ * @returns {Promise<boolean>} Whether the key was deleted
699
+ */
700
+ async delete(key) {
701
+ let result = false;
702
+ const promises = [];
703
+ if (this.stats.enabled) {
704
+ const statResult = await this._primary.get(key);
705
+ if (statResult) {
706
+ this.stats.decreaseKSize(key);
707
+ this.stats.decreaseVSize(statResult);
708
+ this.stats.decreaseCount();
709
+ this.stats.incrementDeletes();
710
+ }
711
+ }
712
+ promises.push(this._primary.delete(key));
713
+ if (this._secondary) {
714
+ promises.push(this._secondary.delete(key));
715
+ }
716
+ if (this.nonBlocking) {
717
+ result = await Promise.race(promises);
718
+ for (const promise of promises) {
719
+ promise.catch((error) => {
720
+ this.emit("error" /* ERROR */, error);
721
+ });
722
+ }
723
+ } else {
724
+ const resultAll = await Promise.all(promises);
725
+ result = resultAll[0];
726
+ }
727
+ if (this._sync && result) {
728
+ await this._sync.publish("cache:delete" /* DELETE */, {
729
+ cacheId: this._cacheId,
730
+ key
731
+ });
732
+ }
733
+ return result;
734
+ }
735
+ /**
736
+ * Deletes the keys from the primary store. If the secondary store is set then it will also delete the keys from the secondary store.
737
+ * @param {string[]} keys The keys to delete
738
+ * @returns {Promise<boolean>} Whether the keys were deleted
739
+ */
740
+ async deleteMany(keys) {
741
+ if (this.stats.enabled) {
742
+ const statResult = await this._primary.get(keys);
743
+ for (const key of keys) {
744
+ this.stats.decreaseKSize(key);
745
+ this.stats.decreaseVSize(statResult);
746
+ this.stats.decreaseCount();
747
+ this.stats.incrementDeletes();
748
+ }
749
+ }
750
+ const result = await this._primary.deleteMany(keys);
751
+ if (this._secondary) {
752
+ if (this._nonBlocking) {
753
+ this._secondary.deleteMany(keys).catch((error) => {
754
+ this.emit("error" /* ERROR */, error);
755
+ });
756
+ } else {
757
+ await this._secondary.deleteMany(keys);
758
+ }
759
+ }
760
+ if (this._sync && result) {
761
+ for (const key of keys) {
762
+ await this._sync.publish("cache:delete" /* DELETE */, {
763
+ cacheId: this._cacheId,
764
+ key
765
+ });
766
+ }
767
+ }
768
+ return result;
769
+ }
770
+ /**
771
+ * Clears the primary store. If the secondary store is set then it will also clear the secondary store.
772
+ * @returns {Promise<void>}
773
+ */
774
+ async clear() {
775
+ const promises = [];
776
+ promises.push(this._primary.clear());
777
+ if (this._secondary) {
778
+ promises.push(this._secondary.clear());
779
+ }
780
+ await (this._nonBlocking ? Promise.race(promises) : Promise.all(promises));
781
+ if (this.stats.enabled) {
782
+ this._stats.resetStoreValues();
783
+ this._stats.incrementClears();
784
+ }
785
+ }
786
+ /**
787
+ * Disconnects the primary store. If the secondary store is set then it will also disconnect the secondary store.
788
+ * @returns {Promise<void>}
789
+ */
790
+ async disconnect() {
791
+ const promises = [];
792
+ promises.push(this._primary.disconnect());
793
+ if (this._secondary) {
794
+ promises.push(this._secondary.disconnect());
795
+ }
796
+ promises.push(this._sync?.qified.disconnect());
797
+ await (this._nonBlocking ? Promise.race(promises) : Promise.all(promises));
798
+ }
799
+ /**
800
+ * Wraps a function with caching
801
+ *
802
+ * [Learn more about wrapping functions](https://cacheable.org/docs/cacheable/#wrap--memoization-for-sync-and-async-functions).
803
+ * @param {Function} function_ The function to wrap
804
+ * @param {WrapOptions} [options] The options for the wrap function
805
+ * @returns {Function} The wrapped function
806
+ */
807
+ // biome-ignore lint/suspicious/noExplicitAny: type format
808
+ wrap(function_, options) {
809
+ const cacheAdapter = {
810
+ get: async (key) => this.get(key),
811
+ /* v8 ignore next -- @preserve */
812
+ has: async (key) => this.has(key),
813
+ set: async (key, value, ttl) => {
814
+ await this.set(key, value, ttl);
815
+ },
816
+ /* v8 ignore next -- @preserve */
817
+ on: (event, listener) => {
818
+ this.on(event, listener);
819
+ },
820
+ /* v8 ignore next -- @preserve */
821
+ emit: (event, ...args) => this.emit(event, ...args)
822
+ };
823
+ const wrapOptions = {
824
+ ttl: options?.ttl ?? this._ttl,
825
+ keyPrefix: options?.keyPrefix,
826
+ createKey: options?.createKey,
827
+ cacheErrors: options?.cacheErrors,
828
+ cache: cacheAdapter,
829
+ cacheId: this._cacheId,
830
+ serialize: options?.serialize
831
+ };
832
+ return (0, import_utils.wrap)(function_, wrapOptions);
833
+ }
834
+ /**
835
+ * Retrieves the value associated with the given key from the cache. If the key is not found,
836
+ * invokes the provided function to calculate the value, stores it in the cache, and then returns it.
837
+ *
838
+ * @param {GetOrSetKey} key - The key to retrieve or set in the cache. This can also be a function that returns a string key.
839
+ * If a function is provided, it will be called with the cache options to generate the key.
840
+ * @param {() => Promise<T>} function_ - The asynchronous function that computes the value to be cached if the key does not exist.
841
+ * @param {GetOrSetFunctionOptions} [options] - Optional settings for caching, such as the time to live (TTL) or whether to cache errors.
842
+ * @return {Promise<T | undefined>} - A promise that resolves to the cached or newly computed value, or undefined if an error occurs and caching is not configured for errors.
843
+ */
844
+ async getOrSet(key, function_, options) {
845
+ const cacheAdapter = {
846
+ get: async (key2) => this.get(key2),
847
+ /* v8 ignore next -- @preserve */
848
+ has: async (key2) => this.has(key2),
849
+ set: async (key2, value, ttl) => {
850
+ await this.set(key2, value, ttl);
851
+ },
852
+ /* v8 ignore next -- @preserve */
853
+ on: (event, listener) => {
854
+ this.on(event, listener);
855
+ },
856
+ emit: (event, ...args) => this.emit(event, ...args)
857
+ };
858
+ const getOrSetOptions = {
859
+ cache: cacheAdapter,
860
+ cacheId: this._cacheId,
861
+ ttl: options?.ttl ?? this._ttl,
862
+ cacheErrors: options?.cacheErrors,
863
+ throwErrors: options?.throwErrors
864
+ };
865
+ return (0, import_utils.getOrSet)(key, function_, getOrSetOptions);
866
+ }
867
+ /**
868
+ * Will hash an object asynchronously using the specified cryptographic algorithm.
869
+ * Use this for cryptographic algorithms (SHA-256, SHA-384, SHA-512).
870
+ * For non-cryptographic algorithms, use hashSync() for better performance.
871
+ * @param {any} object the object to hash
872
+ * @param {string} algorithm the hash algorithm to use. The default is 'SHA-256'
873
+ * @returns {Promise<string>} the hash of the object
874
+ */
875
+ async hash(object, algorithm = import_utils.HashAlgorithm.SHA256) {
876
+ return (0, import_utils.hash)(object, { algorithm });
877
+ }
878
+ /**
879
+ * Will hash an object synchronously using the specified non-cryptographic algorithm.
880
+ * Use this for non-cryptographic algorithms (DJB2, FNV1, MURMER, CRC32).
881
+ * For cryptographic algorithms, use hash() instead.
882
+ * @param {any} object the object to hash
883
+ * @param {string} algorithm the hash algorithm to use. The default is 'djb2'
884
+ * @returns {string} the hash of the object
885
+ */
886
+ hashSync(object, algorithm = import_utils.HashAlgorithm.DJB2) {
887
+ return (0, import_utils.hashSync)(object, { algorithm });
888
+ }
889
+ async setManyKeyv(keyv, items) {
890
+ const entries = [];
891
+ for (const item of items) {
892
+ const finalTtl = (0, import_utils.shorthandToMilliseconds)(item.ttl ?? this._ttl);
893
+ entries.push({ key: item.key, value: item.value, ttl: finalTtl });
894
+ }
895
+ await keyv.setMany(entries);
896
+ return true;
897
+ }
898
+ /**
899
+ * Processes a single key from secondary store for getRaw operation
900
+ * @param primary - the primary store to use
901
+ * @param secondary - the secondary store to use
902
+ * @param key - The key to retrieve from secondary store
903
+ * @returns Promise containing the result and TTL information
904
+ */
905
+ async processSecondaryForGetRaw(primary, secondary, key) {
906
+ const secondaryResult = await secondary.getRaw(key);
907
+ if (secondaryResult?.value) {
908
+ this.emit("cache:hit" /* CACHE_HIT */, {
909
+ key,
910
+ value: secondaryResult.value,
911
+ store: "secondary"
912
+ });
913
+ const cascadeTtl = (0, import_utils.getCascadingTtl)(this._ttl, this._primary.ttl);
914
+ const expires = secondaryResult.expires ?? void 0;
915
+ const ttl = (0, import_utils.calculateTtlFromExpiration)(cascadeTtl, expires);
916
+ const setItem = { key, value: secondaryResult.value, ttl };
917
+ await this.hook("BEFORE_SECONDARY_SETS_PRIMARY" /* BEFORE_SECONDARY_SETS_PRIMARY */, setItem);
918
+ await primary.set(setItem.key, setItem.value, setItem.ttl);
919
+ return { result: secondaryResult, ttl };
920
+ } else {
921
+ this.emit("cache:miss" /* CACHE_MISS */, { key, store: "secondary" });
922
+ return void 0;
923
+ }
924
+ }
925
+ /**
926
+ * Processes a single key from secondary store for getRaw operation in non-blocking mode
927
+ * Non-blocking mode means we don't wait for secondary operations that update primary store
928
+ * @param primary - the primary store to use
929
+ * @param secondary - the secondary store to use
930
+ * @param key - The key to retrieve from secondary store
931
+ * @returns Promise containing the result and TTL information
932
+ */
933
+ async processSecondaryForGetRawNonBlocking(primary, secondary, key) {
934
+ const secondaryResult = await secondary.getRaw(key);
935
+ if (secondaryResult?.value) {
936
+ this.emit("cache:hit" /* CACHE_HIT */, {
937
+ key,
938
+ value: secondaryResult.value,
939
+ store: "secondary"
940
+ });
941
+ const cascadeTtl = (0, import_utils.getCascadingTtl)(this._ttl, this._primary.ttl);
942
+ const expires = secondaryResult.expires ?? void 0;
943
+ const ttl = (0, import_utils.calculateTtlFromExpiration)(cascadeTtl, expires);
944
+ const setItem = { key, value: secondaryResult.value, ttl };
945
+ this.hook("BEFORE_SECONDARY_SETS_PRIMARY" /* BEFORE_SECONDARY_SETS_PRIMARY */, setItem).then(async () => {
946
+ await primary.set(setItem.key, setItem.value, setItem.ttl);
947
+ }).catch((error) => {
948
+ this.emit("error" /* ERROR */, error);
949
+ });
950
+ return { result: secondaryResult, ttl };
951
+ } else {
952
+ this.emit("cache:miss" /* CACHE_MISS */, { key, store: "secondary" });
953
+ return void 0;
954
+ }
955
+ }
956
+ /**
957
+ * Processes missing keys from secondary store for getManyRaw operation
958
+ * @param primary - the primary store to use
959
+ * @param secondary - the secondary store to use
960
+ * @param keys - The original array of keys requested
961
+ * @param result - The result array from primary store (will be modified)
962
+ * @returns Promise<void>
963
+ */
964
+ async processSecondaryForGetManyRaw(primary, secondary, keys, result) {
965
+ const missingKeys = [];
966
+ for (const [i, key] of keys.entries()) {
967
+ if (!result[i]) {
968
+ missingKeys.push(key);
969
+ }
970
+ }
971
+ const secondaryResults = await secondary.getManyRaw(missingKeys);
972
+ let secondaryIndex = 0;
973
+ for await (const [i, key] of keys.entries()) {
974
+ if (!result[i]) {
975
+ const secondaryResult = secondaryResults[secondaryIndex];
976
+ if (secondaryResult && secondaryResult.value !== void 0) {
977
+ result[i] = secondaryResult;
978
+ this.emit("cache:hit" /* CACHE_HIT */, {
979
+ key,
980
+ value: secondaryResult.value,
981
+ store: "secondary"
982
+ });
983
+ const cascadeTtl = (0, import_utils.getCascadingTtl)(this._ttl, this._primary.ttl);
984
+ let { expires } = secondaryResult;
985
+ if (expires === null) {
986
+ expires = void 0;
987
+ }
988
+ const ttl = (0, import_utils.calculateTtlFromExpiration)(cascadeTtl, expires);
989
+ const setItem = { key, value: secondaryResult.value, ttl };
990
+ await this.hook(
991
+ "BEFORE_SECONDARY_SETS_PRIMARY" /* BEFORE_SECONDARY_SETS_PRIMARY */,
992
+ setItem
993
+ );
994
+ await primary.set(setItem.key, setItem.value, setItem.ttl);
995
+ } else {
996
+ this.emit("cache:miss" /* CACHE_MISS */, {
997
+ key,
998
+ store: "secondary"
999
+ });
1000
+ }
1001
+ secondaryIndex++;
1002
+ }
1003
+ }
1004
+ }
1005
+ /**
1006
+ * Processes missing keys from secondary store for getManyRaw operation in non-blocking mode
1007
+ * Non-blocking mode means we don't wait for secondary operations that update primary store
1008
+ * @param secondary - the secondary store to use
1009
+ * @param keys - The original array of keys requested
1010
+ * @param result - The result array from primary store (will be modified)
1011
+ * @returns Promise<void>
1012
+ */
1013
+ async processSecondaryForGetManyRawNonBlocking(primary, secondary, keys, result) {
1014
+ const missingKeys = [];
1015
+ for (const [i, key] of keys.entries()) {
1016
+ if (!result[i]) {
1017
+ missingKeys.push(key);
1018
+ }
1019
+ }
1020
+ const secondaryResults = await secondary.getManyRaw(missingKeys);
1021
+ let secondaryIndex = 0;
1022
+ for await (const [i, key] of keys.entries()) {
1023
+ if (!result[i]) {
1024
+ const secondaryResult = secondaryResults[secondaryIndex];
1025
+ if (secondaryResult && secondaryResult.value !== void 0) {
1026
+ result[i] = secondaryResult;
1027
+ this.emit("cache:hit" /* CACHE_HIT */, {
1028
+ key,
1029
+ value: secondaryResult.value,
1030
+ store: "secondary"
1031
+ });
1032
+ const cascadeTtl = (0, import_utils.getCascadingTtl)(this._ttl, this._primary.ttl);
1033
+ let { expires } = secondaryResult;
1034
+ if (expires === null) {
1035
+ expires = void 0;
1036
+ }
1037
+ const ttl = (0, import_utils.calculateTtlFromExpiration)(cascadeTtl, expires);
1038
+ const setItem = { key, value: secondaryResult.value, ttl };
1039
+ this.hook("BEFORE_SECONDARY_SETS_PRIMARY" /* BEFORE_SECONDARY_SETS_PRIMARY */, setItem).then(async () => {
1040
+ await primary.set(setItem.key, setItem.value, setItem.ttl);
1041
+ }).catch((error) => {
1042
+ this.emit("error" /* ERROR */, error);
1043
+ });
1044
+ } else {
1045
+ this.emit("cache:miss" /* CACHE_MISS */, {
1046
+ key,
1047
+ store: "secondary"
1048
+ });
1049
+ }
1050
+ secondaryIndex++;
1051
+ }
1052
+ }
1053
+ }
1054
+ setTtl(ttl) {
1055
+ if (typeof ttl === "string" || ttl === void 0) {
1056
+ this._ttl = ttl;
1057
+ } else if (ttl > 0) {
1058
+ this._ttl = ttl;
1059
+ } else {
1060
+ this._ttl = void 0;
1061
+ }
1062
+ }
1063
+ };
1064
+ // Annotate the CommonJS export names for ESM import in node:
1065
+ 0 && (module.exports = {
1066
+ Cacheable,
1067
+ CacheableEvents,
1068
+ CacheableHooks,
1069
+ CacheableMemory,
1070
+ CacheableStats,
1071
+ CacheableSync,
1072
+ CacheableSyncEvents,
1073
+ HashAlgorithm,
1074
+ Keyv,
1075
+ KeyvCacheableMemory,
1076
+ KeyvHooks,
1077
+ calculateTtlFromExpiration,
1078
+ createKeyv,
1079
+ getCascadingTtl,
1080
+ getOrSet,
1081
+ hash,
1082
+ shorthandToMilliseconds,
1083
+ shorthandToTime,
1084
+ wrap,
1085
+ wrapSync
1086
+ });
1087
+ /* v8 ignore next -- @preserve */