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