@cacheable/memory 2.0.3 → 2.0.5

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,765 @@
1
- import{wrapSync as g}from"@cacheable/memoize";import{HashAlgorithm as b,hashToNumber as _,shorthandToTime as d}from"@cacheable/utils";import{Hookified as y}from"hookified";var c=class{value;prev=void 0;next=void 0;constructor(e){this.value=e}},o=class{head=void 0;tail=void 0;nodesMap=new Map;addToFront(e){let t=new c(e);this.head?(t.next=this.head,this.head.prev=t,this.head=t):this.head=this.tail=t,this.nodesMap.set(e,t)}moveToFront(e){let t=this.nodesMap.get(e);!t||this.head===t||(t.prev&&(t.prev.next=t.next),t.next&&(t.next.prev=t.prev),t===this.tail&&(this.tail=t.prev),t.prev=void 0,t.next=this.head,this.head&&(this.head.prev=t),this.head=t,this.tail??=t)}getOldest(){return this.tail?this.tail.value:void 0}removeOldest(){if(!this.tail)return;let e=this.tail.value;return this.tail.prev?(this.tail=this.tail.prev,this.tail.next=void 0):this.head=this.tail=void 0,this.nodesMap.delete(e),e}get size(){return this.nodesMap.size}};import{HashAlgorithm as k,hash as O,hashToNumber as K}from"@cacheable/utils";import{Keyv as m}from"keyv";var l=class{opts={ttl:0,useClone:!0,lruSize:0,checkInterval:0};_defaultCache=new a;_nCache=new Map;_namespace;constructor(e){e&&(this.opts=e,this._defaultCache=new a(e),e.namespace&&(this._namespace=e.namespace,this._nCache.set(this._namespace,new a(e))))}get namespace(){return this._namespace}set namespace(e){this._namespace=e}get store(){return this.getStore(this._namespace)}async get(e){let t=this.getStore(this._namespace).get(e);if(t)return t}async getMany(e){return this.getStore(this._namespace).getMany(e)}async set(e,t,r){this.getStore(this._namespace).set(e,t,r)}async setMany(e){this.getStore(this._namespace).setMany(e)}async delete(e){return this.getStore(this._namespace).delete(e),!0}async deleteMany(e){return this.getStore(this._namespace).deleteMany(e),!0}async clear(){this.getStore(this._namespace).clear()}async has(e){return this.getStore(this._namespace).has(e)}on(e,t){return this.getStore(this._namespace).on(e,t),this}getStore(e){return e?(this._nCache.has(e)||this._nCache.set(e,new a(this.opts)),this._nCache.get(e)):this._defaultCache}};function f(s){let e=new l(s),t=s?.namespace,r;s?.ttl&&Number.isInteger(s.ttl)&&(r=s?.ttl);let i=new m({store:e,namespace:t,ttl:r});return i.serialize=void 0,i.deserialize=void 0,i}var v=16,u=16777216,a=class extends y{_lru=new o;_storeHashSize=v;_storeHashAlgorithm=b.DJB2;_store=Array.from({length:this._storeHashSize},()=>new Map);_ttl;_useClone=!0;_lruSize=0;_checkInterval=0;_interval=0;constructor(e){super(),e?.ttl&&this.setTtl(e.ttl),e?.useClone!==void 0&&(this._useClone=e.useClone),e?.storeHashSize&&e.storeHashSize>0&&(this._storeHashSize=e.storeHashSize),e?.lruSize&&(e.lruSize>u?this.emit("error",new Error(`LRU size cannot be larger than ${u} due to Map limitations.`)):this._lruSize=e.lruSize),e?.checkInterval&&(this._checkInterval=e.checkInterval),e?.storeHashAlgorithm&&(this._storeHashAlgorithm=e.storeHashAlgorithm),this._store=Array.from({length:this._storeHashSize},()=>new Map),this.startIntervalCheck()}get ttl(){return this._ttl}set ttl(e){this.setTtl(e)}get useClone(){return this._useClone}set useClone(e){this._useClone=e}get lruSize(){return this._lruSize}set lruSize(e){if(e>u){this.emit("error",new Error(`LRU size cannot be larger than ${u} due to Map limitations.`));return}if(this._lruSize=e,this._lruSize===0){this._lru=new o;return}this.lruResize()}get checkInterval(){return this._checkInterval}set checkInterval(e){this._checkInterval=e}get size(){let e=0;for(let t of this._store)e+=t.size;return e}get storeHashSize(){return this._storeHashSize}set storeHashSize(e){e!==this._storeHashSize&&(this._storeHashSize=e,this._store=Array.from({length:this._storeHashSize},()=>new Map))}get storeHashAlgorithm(){return this._storeHashAlgorithm}set storeHashAlgorithm(e){this._storeHashAlgorithm=e}get keys(){let e=[];for(let t of this._store)for(let r of t.keys()){let i=t.get(r);if(i&&this.hasExpired(i)){t.delete(r);continue}e.push(r)}return e.values()}get items(){let e=[];for(let t of this._store)for(let r of t.values()){if(this.hasExpired(r)){t.delete(r.key);continue}e.push(r)}return e.values()}get store(){return this._store}get(e){let t=this.getStore(e),r=t.get(e);if(r){if(r.expires&&Date.now()>r.expires){t.delete(e);return}return this.lruMoveToFront(e),this._useClone?this.clone(r.value):r.value}}getMany(e){let t=[];for(let r of e)t.push(this.get(r));return t}getRaw(e){let t=this.getStore(e),r=t.get(e);if(r){if(r.expires&&r.expires&&Date.now()>r.expires){t.delete(e);return}return this.lruMoveToFront(e),r}}getManyRaw(e){let t=[];for(let r of e)t.push(this.getRaw(r));return t}set(e,t,r){let i=this.getStore(e),h;if(r!==void 0||this._ttl!==void 0)if(typeof r=="object"){if(r.expire&&(h=typeof r.expire=="number"?r.expire:r.expire.getTime()),r.ttl){let n=d(r.ttl);n!==void 0&&(h=n)}}else{let n=d(r??this._ttl);n!==void 0&&(h=n)}if(this._lruSize>0){if(i.has(e))this.lruMoveToFront(e);else if(this.lruAddToFront(e),this._lru.size>this._lruSize){let n=this._lru.getOldest();n&&(this._lru.removeOldest(),this.delete(n))}}let p={key:e,value:t,expires:h};i.set(e,p)}setMany(e){for(let t of e)this.set(t.key,t.value,t.ttl)}has(e){return!!this.get(e)}hasMany(e){let t=[];for(let r of e){let i=this.get(r);t.push(!!i)}return t}take(e){let t=this.get(e);if(t)return this.delete(e),t}takeMany(e){let t=[];for(let r of e)t.push(this.take(r));return t}delete(e){this.getStore(e).delete(e)}deleteMany(e){for(let t of e)this.delete(t)}clear(){this._store=Array.from({length:this._storeHashSize},()=>new Map),this._lru=new o}getStore(e){let t=this.getKeyStoreHash(e);return this._store[t]||=new Map,this._store[t]}getKeyStoreHash(e){if(this._store.length===1)return 0;if(typeof this._storeHashAlgorithm=="function")return this._storeHashAlgorithm(e,this._storeHashSize);let t=this._storeHashSize-1;return _(e,{min:0,max:t,algorithm:this._storeHashAlgorithm})}clone(e){return this.isPrimitive(e)?e:structuredClone(e)}lruAddToFront(e){this._lruSize!==0&&this._lru.addToFront(e)}lruMoveToFront(e){this._lruSize!==0&&this._lru.moveToFront(e)}lruResize(){for(;this._lru.size>this._lruSize;){let e=this._lru.getOldest();e&&(this._lru.removeOldest(),this.delete(e))}}checkExpiration(){for(let e of this._store)for(let t of e.values())t.expires&&Date.now()>t.expires&&e.delete(t.key)}startIntervalCheck(){this._checkInterval>0&&(this._interval&&clearInterval(this._interval),this._interval=setInterval(()=>{this.checkExpiration()},this._checkInterval).unref())}stopIntervalCheck(){this._interval&&clearInterval(this._interval),this._interval=0,this._checkInterval=0}wrap(e,t){let r={ttl:t?.ttl??this._ttl,keyPrefix:t?.keyPrefix,createKey:t?.createKey,cache:this};return g(e,r)}isPrimitive(e){return e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}setTtl(e){typeof e=="string"||e===void 0?this._ttl=e:e>0?this._ttl=e:this._ttl=void 0}hasExpired(e){return!!(e.expires&&Date.now()>e.expires)}};export{a as CacheableMemory,k as HashAlgorithm,l as KeyvCacheableMemory,f as createKeyv,v as defaultStoreHashSize,O as hash,K as hashToNumber,u as maximumMapSize};
1
+ // src/index.ts
2
+ import {
3
+ HashAlgorithm,
4
+ hashToNumberSync,
5
+ shorthandToTime,
6
+ wrapSync
7
+ } from "@cacheable/utils";
8
+ import { Hookified } from "hookified";
9
+
10
+ // src/memory-lru.ts
11
+ var ListNode = class {
12
+ value;
13
+ prev = void 0;
14
+ next = void 0;
15
+ constructor(value) {
16
+ this.value = value;
17
+ }
18
+ };
19
+ var DoublyLinkedList = class {
20
+ head = void 0;
21
+ tail = void 0;
22
+ nodesMap = /* @__PURE__ */ new Map();
23
+ // Add a new node to the front (most recently used)
24
+ addToFront(value) {
25
+ const newNode = new ListNode(value);
26
+ if (this.head) {
27
+ newNode.next = this.head;
28
+ this.head.prev = newNode;
29
+ this.head = newNode;
30
+ } else {
31
+ this.head = this.tail = newNode;
32
+ }
33
+ this.nodesMap.set(value, newNode);
34
+ }
35
+ // Move an existing node to the front (most recently used)
36
+ moveToFront(value) {
37
+ const node = this.nodesMap.get(value);
38
+ if (!node || this.head === node) {
39
+ return;
40
+ }
41
+ if (node.prev) {
42
+ node.prev.next = node.next;
43
+ }
44
+ if (node.next) {
45
+ node.next.prev = node.prev;
46
+ }
47
+ if (node === this.tail) {
48
+ this.tail = node.prev;
49
+ }
50
+ node.prev = void 0;
51
+ node.next = this.head;
52
+ if (this.head) {
53
+ this.head.prev = node;
54
+ }
55
+ this.head = node;
56
+ this.tail ??= node;
57
+ }
58
+ // Get the oldest node (tail)
59
+ getOldest() {
60
+ return this.tail ? this.tail.value : void 0;
61
+ }
62
+ // Remove the oldest node (tail)
63
+ removeOldest() {
64
+ if (!this.tail) {
65
+ return void 0;
66
+ }
67
+ const oldValue = this.tail.value;
68
+ if (this.tail.prev) {
69
+ this.tail = this.tail.prev;
70
+ this.tail.next = void 0;
71
+ } else {
72
+ this.head = this.tail = void 0;
73
+ }
74
+ this.nodesMap.delete(oldValue);
75
+ return oldValue;
76
+ }
77
+ get size() {
78
+ return this.nodesMap.size;
79
+ }
80
+ };
81
+
82
+ // src/index.ts
83
+ import {
84
+ HashAlgorithm as HashAlgorithm2,
85
+ hash,
86
+ hashToNumber
87
+ } from "@cacheable/utils";
88
+
89
+ // src/keyv-memory.ts
90
+ import { Keyv } from "keyv";
91
+ var KeyvCacheableMemory = class {
92
+ opts = {
93
+ ttl: 0,
94
+ useClone: true,
95
+ lruSize: 0,
96
+ checkInterval: 0
97
+ };
98
+ _defaultCache = new CacheableMemory();
99
+ _nCache = /* @__PURE__ */ new Map();
100
+ _namespace;
101
+ constructor(options) {
102
+ if (options) {
103
+ this.opts = options;
104
+ this._defaultCache = new CacheableMemory(options);
105
+ if (options.namespace) {
106
+ this._namespace = options.namespace;
107
+ this._nCache.set(this._namespace, new CacheableMemory(options));
108
+ }
109
+ }
110
+ }
111
+ get namespace() {
112
+ return this._namespace;
113
+ }
114
+ set namespace(value) {
115
+ this._namespace = value;
116
+ }
117
+ get store() {
118
+ return this.getStore(this._namespace);
119
+ }
120
+ async get(key) {
121
+ const result = this.getStore(this._namespace).get(key);
122
+ if (result) {
123
+ return result;
124
+ }
125
+ return void 0;
126
+ }
127
+ async getMany(keys) {
128
+ const result = this.getStore(this._namespace).getMany(keys);
129
+ return result;
130
+ }
131
+ // biome-ignore lint/suspicious/noExplicitAny: type format
132
+ async set(key, value, ttl) {
133
+ this.getStore(this._namespace).set(key, value, ttl);
134
+ }
135
+ async setMany(values) {
136
+ this.getStore(this._namespace).setMany(values);
137
+ }
138
+ async delete(key) {
139
+ this.getStore(this._namespace).delete(key);
140
+ return true;
141
+ }
142
+ async deleteMany(key) {
143
+ this.getStore(this._namespace).deleteMany(key);
144
+ return true;
145
+ }
146
+ async clear() {
147
+ this.getStore(this._namespace).clear();
148
+ }
149
+ async has(key) {
150
+ return this.getStore(this._namespace).has(key);
151
+ }
152
+ // biome-ignore lint/suspicious/noExplicitAny: type format
153
+ on(event, listener) {
154
+ this.getStore(this._namespace).on(event, listener);
155
+ return this;
156
+ }
157
+ getStore(namespace) {
158
+ if (!namespace) {
159
+ return this._defaultCache;
160
+ }
161
+ if (!this._nCache.has(namespace)) {
162
+ this._nCache.set(namespace, new CacheableMemory(this.opts));
163
+ }
164
+ return this._nCache.get(namespace);
165
+ }
166
+ };
167
+ function createKeyv(options) {
168
+ const store = new KeyvCacheableMemory(options);
169
+ const namespace = options?.namespace;
170
+ let ttl;
171
+ if (options?.ttl && Number.isInteger(options.ttl)) {
172
+ ttl = options?.ttl;
173
+ }
174
+ const keyv = new Keyv({ store, namespace, ttl });
175
+ keyv.serialize = void 0;
176
+ keyv.deserialize = void 0;
177
+ return keyv;
178
+ }
179
+
180
+ // src/index.ts
181
+ var defaultStoreHashSize = 16;
182
+ var maximumMapSize = 16777216;
183
+ var CacheableMemory = class extends Hookified {
184
+ _lru = new DoublyLinkedList();
185
+ _storeHashSize = defaultStoreHashSize;
186
+ _storeHashAlgorithm = HashAlgorithm.DJB2;
187
+ // Default is djb2Hash
188
+ _store = Array.from(
189
+ { length: this._storeHashSize },
190
+ () => /* @__PURE__ */ new Map()
191
+ );
192
+ _ttl;
193
+ // Turned off by default
194
+ _useClone = true;
195
+ // Turned on by default
196
+ _lruSize = 0;
197
+ // Turned off by default
198
+ _checkInterval = 0;
199
+ // Turned off by default
200
+ _interval = 0;
201
+ // Turned off by default
202
+ /**
203
+ * @constructor
204
+ * @param {CacheableMemoryOptions} [options] - The options for the CacheableMemory
205
+ */
206
+ constructor(options) {
207
+ super();
208
+ if (options?.ttl) {
209
+ this.setTtl(options.ttl);
210
+ }
211
+ if (options?.useClone !== void 0) {
212
+ this._useClone = options.useClone;
213
+ }
214
+ if (options?.storeHashSize && options.storeHashSize > 0) {
215
+ this._storeHashSize = options.storeHashSize;
216
+ }
217
+ if (options?.lruSize) {
218
+ if (options.lruSize > maximumMapSize) {
219
+ this.emit(
220
+ "error",
221
+ new Error(
222
+ `LRU size cannot be larger than ${maximumMapSize} due to Map limitations.`
223
+ )
224
+ );
225
+ } else {
226
+ this._lruSize = options.lruSize;
227
+ }
228
+ }
229
+ if (options?.checkInterval) {
230
+ this._checkInterval = options.checkInterval;
231
+ }
232
+ if (options?.storeHashAlgorithm) {
233
+ this._storeHashAlgorithm = options.storeHashAlgorithm;
234
+ }
235
+ this._store = Array.from(
236
+ { length: this._storeHashSize },
237
+ () => /* @__PURE__ */ new Map()
238
+ );
239
+ this.startIntervalCheck();
240
+ }
241
+ /**
242
+ * Gets the time-to-live
243
+ * @returns {number|string|undefined} - The time-to-live in miliseconds or a human-readable format. If undefined, it will not have a time-to-live.
244
+ */
245
+ get ttl() {
246
+ return this._ttl;
247
+ }
248
+ /**
249
+ * Sets the time-to-live
250
+ * @param {number|string|undefined} value - The time-to-live in miliseconds or a human-readable format (example '1s' = 1 second, '1h' = 1 hour). If undefined, it will not have a time-to-live.
251
+ */
252
+ set ttl(value) {
253
+ this.setTtl(value);
254
+ }
255
+ /**
256
+ * Gets whether to use clone
257
+ * @returns {boolean} - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
258
+ */
259
+ get useClone() {
260
+ return this._useClone;
261
+ }
262
+ /**
263
+ * Sets whether to use clone
264
+ * @param {boolean} value - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
265
+ */
266
+ set useClone(value) {
267
+ this._useClone = value;
268
+ }
269
+ /**
270
+ * Gets the size of the LRU cache
271
+ * @returns {number} - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0. If you are using LRU then the limit is based on Map() size 17mm.
272
+ */
273
+ get lruSize() {
274
+ return this._lruSize;
275
+ }
276
+ /**
277
+ * Sets the size of the LRU cache
278
+ * @param {number} value - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0. If you are using LRU then the limit is based on Map() size 17mm.
279
+ */
280
+ set lruSize(value) {
281
+ if (value > maximumMapSize) {
282
+ this.emit(
283
+ "error",
284
+ new Error(
285
+ `LRU size cannot be larger than ${maximumMapSize} due to Map limitations.`
286
+ )
287
+ );
288
+ return;
289
+ }
290
+ this._lruSize = value;
291
+ if (this._lruSize === 0) {
292
+ this._lru = new DoublyLinkedList();
293
+ return;
294
+ }
295
+ this.lruResize();
296
+ }
297
+ /**
298
+ * Gets the check interval
299
+ * @returns {number} - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
300
+ */
301
+ get checkInterval() {
302
+ return this._checkInterval;
303
+ }
304
+ /**
305
+ * Sets the check interval
306
+ * @param {number} value - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
307
+ */
308
+ set checkInterval(value) {
309
+ this._checkInterval = value;
310
+ }
311
+ /**
312
+ * Gets the size of the cache
313
+ * @returns {number} - The size of the cache
314
+ */
315
+ get size() {
316
+ let size = 0;
317
+ for (const store of this._store) {
318
+ size += store.size;
319
+ }
320
+ return size;
321
+ }
322
+ /**
323
+ * Gets the number of hash stores
324
+ * @returns {number} - The number of hash stores
325
+ */
326
+ get storeHashSize() {
327
+ return this._storeHashSize;
328
+ }
329
+ /**
330
+ * Sets the number of hash stores. This will recreate the store and all data will be cleared
331
+ * @param {number} value - The number of hash stores
332
+ */
333
+ set storeHashSize(value) {
334
+ if (value === this._storeHashSize) {
335
+ return;
336
+ }
337
+ this._storeHashSize = value;
338
+ this._store = Array.from(
339
+ { length: this._storeHashSize },
340
+ () => /* @__PURE__ */ new Map()
341
+ );
342
+ }
343
+ /**
344
+ * Gets the store hash algorithm
345
+ * @returns {HashAlgorithm | StoreHashAlgorithmFunction} - The store hash algorithm
346
+ */
347
+ get storeHashAlgorithm() {
348
+ return this._storeHashAlgorithm;
349
+ }
350
+ /**
351
+ * Sets the store hash algorithm. This will recreate the store and all data will be cleared
352
+ * @param {HashAlgorithm | HashAlgorithmFunction} value - The store hash algorithm
353
+ */
354
+ set storeHashAlgorithm(value) {
355
+ this._storeHashAlgorithm = value;
356
+ }
357
+ /**
358
+ * Gets the keys
359
+ * @returns {IterableIterator<string>} - The keys
360
+ */
361
+ get keys() {
362
+ const keys = [];
363
+ for (const store of this._store) {
364
+ for (const key of store.keys()) {
365
+ const item = store.get(key);
366
+ if (item && this.hasExpired(item)) {
367
+ store.delete(key);
368
+ continue;
369
+ }
370
+ keys.push(key);
371
+ }
372
+ }
373
+ return keys.values();
374
+ }
375
+ /**
376
+ * Gets the items
377
+ * @returns {IterableIterator<CacheableStoreItem>} - The items
378
+ */
379
+ get items() {
380
+ const items = [];
381
+ for (const store of this._store) {
382
+ for (const item of store.values()) {
383
+ if (this.hasExpired(item)) {
384
+ store.delete(item.key);
385
+ continue;
386
+ }
387
+ items.push(item);
388
+ }
389
+ }
390
+ return items.values();
391
+ }
392
+ /**
393
+ * Gets the store
394
+ * @returns {Array<Map<string, CacheableStoreItem>>} - The store
395
+ */
396
+ get store() {
397
+ return this._store;
398
+ }
399
+ /**
400
+ * Gets the value of the key
401
+ * @param {string} key - The key to get the value
402
+ * @returns {T | undefined} - The value of the key
403
+ */
404
+ get(key) {
405
+ const store = this.getStore(key);
406
+ const item = store.get(key);
407
+ if (!item) {
408
+ return void 0;
409
+ }
410
+ if (item.expires && Date.now() > item.expires) {
411
+ store.delete(key);
412
+ return void 0;
413
+ }
414
+ this.lruMoveToFront(key);
415
+ if (!this._useClone) {
416
+ return item.value;
417
+ }
418
+ return this.clone(item.value);
419
+ }
420
+ /**
421
+ * Gets the values of the keys
422
+ * @param {string[]} keys - The keys to get the values
423
+ * @returns {T[]} - The values of the keys
424
+ */
425
+ getMany(keys) {
426
+ const result = [];
427
+ for (const key of keys) {
428
+ result.push(this.get(key));
429
+ }
430
+ return result;
431
+ }
432
+ /**
433
+ * Gets the raw value of the key
434
+ * @param {string} key - The key to get the value
435
+ * @returns {CacheableStoreItem | undefined} - The raw value of the key
436
+ */
437
+ getRaw(key) {
438
+ const store = this.getStore(key);
439
+ const item = store.get(key);
440
+ if (!item) {
441
+ return void 0;
442
+ }
443
+ if (item.expires && item.expires && Date.now() > item.expires) {
444
+ store.delete(key);
445
+ return void 0;
446
+ }
447
+ this.lruMoveToFront(key);
448
+ return item;
449
+ }
450
+ /**
451
+ * Gets the raw values of the keys
452
+ * @param {string[]} keys - The keys to get the values
453
+ * @returns {CacheableStoreItem[]} - The raw values of the keys
454
+ */
455
+ getManyRaw(keys) {
456
+ const result = [];
457
+ for (const key of keys) {
458
+ result.push(this.getRaw(key));
459
+ }
460
+ return result;
461
+ }
462
+ /**
463
+ * Sets the value of the key
464
+ * @param {string} key - The key to set the value
465
+ * @param {any} value - The value to set
466
+ * @param {number|string|SetOptions} [ttl] - Time to Live - If you set a number it is miliseconds, if you set a string it is a human-readable.
467
+ * If you want to set expire directly you can do that by setting the expire property in the SetOptions.
468
+ * If you set undefined, it will use the default time-to-live. If both are undefined then it will not have a time-to-live.
469
+ * @returns {void}
470
+ */
471
+ set(key, value, ttl) {
472
+ const store = this.getStore(key);
473
+ let expires;
474
+ if (ttl !== void 0 || this._ttl !== void 0) {
475
+ if (typeof ttl === "object") {
476
+ if (ttl.expire) {
477
+ expires = typeof ttl.expire === "number" ? ttl.expire : ttl.expire.getTime();
478
+ }
479
+ if (ttl.ttl) {
480
+ const finalTtl = shorthandToTime(ttl.ttl);
481
+ if (finalTtl !== void 0) {
482
+ expires = finalTtl;
483
+ }
484
+ }
485
+ } else {
486
+ const finalTtl = shorthandToTime(ttl ?? this._ttl);
487
+ if (finalTtl !== void 0) {
488
+ expires = finalTtl;
489
+ }
490
+ }
491
+ }
492
+ if (this._lruSize > 0) {
493
+ if (store.has(key)) {
494
+ this.lruMoveToFront(key);
495
+ } else {
496
+ this.lruAddToFront(key);
497
+ if (this._lru.size > this._lruSize) {
498
+ const oldestKey = this._lru.getOldest();
499
+ if (oldestKey) {
500
+ this._lru.removeOldest();
501
+ this.delete(oldestKey);
502
+ }
503
+ }
504
+ }
505
+ }
506
+ const item = { key, value, expires };
507
+ store.set(key, item);
508
+ }
509
+ /**
510
+ * Sets the values of the keys
511
+ * @param {CacheableItem[]} items - The items to set
512
+ * @returns {void}
513
+ */
514
+ setMany(items) {
515
+ for (const item of items) {
516
+ this.set(item.key, item.value, item.ttl);
517
+ }
518
+ }
519
+ /**
520
+ * Checks if the key exists
521
+ * @param {string} key - The key to check
522
+ * @returns {boolean} - If true, the key exists. If false, the key does not exist.
523
+ */
524
+ has(key) {
525
+ const item = this.get(key);
526
+ return Boolean(item);
527
+ }
528
+ /**
529
+ * @function hasMany
530
+ * @param {string[]} keys - The keys to check
531
+ * @returns {boolean[]} - If true, the key exists. If false, the key does not exist.
532
+ */
533
+ hasMany(keys) {
534
+ const result = [];
535
+ for (const key of keys) {
536
+ const item = this.get(key);
537
+ result.push(Boolean(item));
538
+ }
539
+ return result;
540
+ }
541
+ /**
542
+ * Take will get the key and delete the entry from cache
543
+ * @param {string} key - The key to take
544
+ * @returns {T | undefined} - The value of the key
545
+ */
546
+ take(key) {
547
+ const item = this.get(key);
548
+ if (!item) {
549
+ return void 0;
550
+ }
551
+ this.delete(key);
552
+ return item;
553
+ }
554
+ /**
555
+ * TakeMany will get the keys and delete the entries from cache
556
+ * @param {string[]} keys - The keys to take
557
+ * @returns {T[]} - The values of the keys
558
+ */
559
+ takeMany(keys) {
560
+ const result = [];
561
+ for (const key of keys) {
562
+ result.push(this.take(key));
563
+ }
564
+ return result;
565
+ }
566
+ /**
567
+ * Delete the key
568
+ * @param {string} key - The key to delete
569
+ * @returns {void}
570
+ */
571
+ delete(key) {
572
+ const store = this.getStore(key);
573
+ store.delete(key);
574
+ }
575
+ /**
576
+ * Delete the keys
577
+ * @param {string[]} keys - The keys to delete
578
+ * @returns {void}
579
+ */
580
+ deleteMany(keys) {
581
+ for (const key of keys) {
582
+ this.delete(key);
583
+ }
584
+ }
585
+ /**
586
+ * Clear the cache
587
+ * @returns {void}
588
+ */
589
+ clear() {
590
+ this._store = Array.from(
591
+ { length: this._storeHashSize },
592
+ () => /* @__PURE__ */ new Map()
593
+ );
594
+ this._lru = new DoublyLinkedList();
595
+ }
596
+ /**
597
+ * Get the store based on the key (internal use)
598
+ * @param {string} key - The key to get the store
599
+ * @returns {CacheableHashStore} - The store
600
+ */
601
+ getStore(key) {
602
+ const hash2 = this.getKeyStoreHash(key);
603
+ this._store[hash2] ||= /* @__PURE__ */ new Map();
604
+ return this._store[hash2];
605
+ }
606
+ /**
607
+ * Hash the key for which store to go to (internal use)
608
+ * @param {string} key - The key to hash
609
+ * Available algorithms are: SHA256, SHA1, MD5, and djb2Hash.
610
+ * @returns {number} - The hashed key as a number
611
+ */
612
+ getKeyStoreHash(key) {
613
+ if (this._store.length === 1) {
614
+ return 0;
615
+ }
616
+ if (typeof this._storeHashAlgorithm === "function") {
617
+ return this._storeHashAlgorithm(key, this._storeHashSize);
618
+ }
619
+ const storeHashSize = this._storeHashSize - 1;
620
+ const hash2 = hashToNumberSync(key, {
621
+ min: 0,
622
+ max: storeHashSize,
623
+ algorithm: this._storeHashAlgorithm
624
+ });
625
+ return hash2;
626
+ }
627
+ /**
628
+ * Clone the value. This is for internal use
629
+ * @param {any} value - The value to clone
630
+ * @returns {any} - The cloned value
631
+ */
632
+ // biome-ignore lint/suspicious/noExplicitAny: type format
633
+ clone(value) {
634
+ if (this.isPrimitive(value)) {
635
+ return value;
636
+ }
637
+ return structuredClone(value);
638
+ }
639
+ /**
640
+ * Add to the front of the LRU cache. This is for internal use
641
+ * @param {string} key - The key to add to the front
642
+ * @returns {void}
643
+ */
644
+ lruAddToFront(key) {
645
+ if (this._lruSize === 0) {
646
+ return;
647
+ }
648
+ this._lru.addToFront(key);
649
+ }
650
+ /**
651
+ * Move to the front of the LRU cache. This is for internal use
652
+ * @param {string} key - The key to move to the front
653
+ * @returns {void}
654
+ */
655
+ lruMoveToFront(key) {
656
+ if (this._lruSize === 0) {
657
+ return;
658
+ }
659
+ this._lru.moveToFront(key);
660
+ }
661
+ /**
662
+ * Resize the LRU cache. This is for internal use.
663
+ * @returns {void}
664
+ */
665
+ lruResize() {
666
+ while (this._lru.size > this._lruSize) {
667
+ const oldestKey = this._lru.getOldest();
668
+ if (oldestKey) {
669
+ this._lru.removeOldest();
670
+ this.delete(oldestKey);
671
+ }
672
+ }
673
+ }
674
+ /**
675
+ * Check for expiration. This is for internal use
676
+ * @returns {void}
677
+ */
678
+ checkExpiration() {
679
+ for (const store of this._store) {
680
+ for (const item of store.values()) {
681
+ if (item.expires && Date.now() > item.expires) {
682
+ store.delete(item.key);
683
+ }
684
+ }
685
+ }
686
+ }
687
+ /**
688
+ * Start the interval check. This is for internal use
689
+ * @returns {void}
690
+ */
691
+ startIntervalCheck() {
692
+ if (this._checkInterval > 0) {
693
+ if (this._interval) {
694
+ clearInterval(this._interval);
695
+ }
696
+ this._interval = setInterval(() => {
697
+ this.checkExpiration();
698
+ }, this._checkInterval).unref();
699
+ }
700
+ }
701
+ /**
702
+ * Stop the interval check. This is for internal use
703
+ * @returns {void}
704
+ */
705
+ stopIntervalCheck() {
706
+ if (this._interval) {
707
+ clearInterval(this._interval);
708
+ }
709
+ this._interval = 0;
710
+ this._checkInterval = 0;
711
+ }
712
+ /**
713
+ * Wrap the function for caching
714
+ * @param {Function} function_ - The function to wrap
715
+ * @param {Object} [options] - The options to wrap
716
+ * @returns {Function} - The wrapped function
717
+ */
718
+ // biome-ignore lint/suspicious/noExplicitAny: type format
719
+ wrap(function_, options) {
720
+ const wrapOptions = {
721
+ ttl: options?.ttl ?? this._ttl,
722
+ keyPrefix: options?.keyPrefix,
723
+ createKey: options?.createKey,
724
+ cache: this
725
+ };
726
+ return wrapSync(function_, wrapOptions);
727
+ }
728
+ // biome-ignore lint/suspicious/noExplicitAny: type format
729
+ isPrimitive(value) {
730
+ const result = false;
731
+ if (value === null || value === void 0) {
732
+ return true;
733
+ }
734
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
735
+ return true;
736
+ }
737
+ return result;
738
+ }
739
+ setTtl(ttl) {
740
+ if (typeof ttl === "string" || ttl === void 0) {
741
+ this._ttl = ttl;
742
+ } else if (ttl > 0) {
743
+ this._ttl = ttl;
744
+ } else {
745
+ this._ttl = void 0;
746
+ }
747
+ }
748
+ hasExpired(item) {
749
+ if (item.expires && Date.now() > item.expires) {
750
+ return true;
751
+ }
752
+ return false;
753
+ }
754
+ };
755
+ export {
756
+ CacheableMemory,
757
+ HashAlgorithm2 as HashAlgorithm,
758
+ KeyvCacheableMemory,
759
+ createKeyv,
760
+ defaultStoreHashSize,
761
+ hash,
762
+ hashToNumber,
763
+ maximumMapSize
764
+ };
765
+ /* v8 ignore next -- @preserve */