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