cacheable 1.10.3 → 2.0.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,1822 +1 @@
1
- // src/index.ts
2
- import { Keyv as Keyv2 } from "keyv";
3
- import { Hookified as Hookified2 } from "hookified";
4
-
5
- // src/shorthand-time.ts
6
- var shorthandToMilliseconds = (shorthand) => {
7
- let milliseconds;
8
- if (shorthand === void 0) {
9
- return void 0;
10
- }
11
- if (typeof shorthand === "number") {
12
- milliseconds = shorthand;
13
- } else if (typeof shorthand === "string") {
14
- shorthand = shorthand.trim();
15
- if (Number.isNaN(Number(shorthand))) {
16
- const match = /^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(shorthand);
17
- if (!match) {
18
- throw new Error(`Unsupported time format: "${shorthand}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`);
19
- }
20
- const [, value, unit] = match;
21
- const numericValue = Number.parseFloat(value);
22
- const unitLower = unit.toLowerCase();
23
- switch (unitLower) {
24
- case "ms": {
25
- milliseconds = numericValue;
26
- break;
27
- }
28
- case "s": {
29
- milliseconds = numericValue * 1e3;
30
- break;
31
- }
32
- case "m": {
33
- milliseconds = numericValue * 1e3 * 60;
34
- break;
35
- }
36
- case "h": {
37
- milliseconds = numericValue * 1e3 * 60 * 60;
38
- break;
39
- }
40
- case "hr": {
41
- milliseconds = numericValue * 1e3 * 60 * 60;
42
- break;
43
- }
44
- case "d": {
45
- milliseconds = numericValue * 1e3 * 60 * 60 * 24;
46
- break;
47
- }
48
- /* c8 ignore next 3 */
49
- default: {
50
- milliseconds = Number(shorthand);
51
- }
52
- }
53
- } else {
54
- milliseconds = Number(shorthand);
55
- }
56
- } else {
57
- throw new TypeError("Time must be a string or a number.");
58
- }
59
- return milliseconds;
60
- };
61
- var shorthandToTime = (shorthand, fromDate) => {
62
- fromDate ??= /* @__PURE__ */ new Date();
63
- const milliseconds = shorthandToMilliseconds(shorthand);
64
- if (milliseconds === void 0) {
65
- return fromDate.getTime();
66
- }
67
- return fromDate.getTime() + milliseconds;
68
- };
69
-
70
- // src/keyv-memory.ts
71
- import {
72
- Keyv
73
- } from "keyv";
74
-
75
- // src/memory.ts
76
- import { Hookified } from "hookified";
77
-
78
- // src/hash.ts
79
- import * as crypto from "crypto";
80
- function hash(object, algorithm = "sha256") {
81
- const objectString = JSON.stringify(object);
82
- if (!crypto.getHashes().includes(algorithm)) {
83
- throw new Error(`Unsupported hash algorithm: '${algorithm}'`);
84
- }
85
- const hasher = crypto.createHash(algorithm);
86
- hasher.update(objectString);
87
- return hasher.digest("hex");
88
- }
89
- function hashToNumber(object, min = 0, max = 10, algorithm = "sha256") {
90
- const objectString = JSON.stringify(object);
91
- if (!crypto.getHashes().includes(algorithm)) {
92
- throw new Error(`Unsupported hash algorithm: '${algorithm}'`);
93
- }
94
- const hasher = crypto.createHash(algorithm);
95
- hasher.update(objectString);
96
- const hashHex = hasher.digest("hex");
97
- const hashNumber = Number.parseInt(hashHex, 16);
98
- const range = max - min + 1;
99
- return min + hashNumber % range;
100
- }
101
- function djb2Hash(string_, min = 0, max = 10) {
102
- let hash2 = 5381;
103
- for (let i = 0; i < string_.length; i++) {
104
- hash2 = hash2 * 33 ^ string_.charCodeAt(i);
105
- }
106
- const range = max - min + 1;
107
- return min + Math.abs(hash2) % range;
108
- }
109
-
110
- // src/coalesce-async.ts
111
- var callbacks = /* @__PURE__ */ new Map();
112
- function hasKey(key) {
113
- return callbacks.has(key);
114
- }
115
- function addKey(key) {
116
- callbacks.set(key, []);
117
- }
118
- function removeKey(key) {
119
- callbacks.delete(key);
120
- }
121
- function addCallbackToKey(key, callback) {
122
- const stash = getCallbacksByKey(key);
123
- stash.push(callback);
124
- callbacks.set(key, stash);
125
- }
126
- function getCallbacksByKey(key) {
127
- return callbacks.get(key) ?? [];
128
- }
129
- async function enqueue(key) {
130
- return new Promise((resolve, reject) => {
131
- const callback = { resolve, reject };
132
- addCallbackToKey(key, callback);
133
- });
134
- }
135
- function dequeue(key) {
136
- const stash = getCallbacksByKey(key);
137
- removeKey(key);
138
- return stash;
139
- }
140
- function coalesce(options) {
141
- const { key, error, result } = options;
142
- for (const callback of dequeue(key)) {
143
- if (error) {
144
- callback.reject(error);
145
- } else {
146
- callback.resolve(result);
147
- }
148
- }
149
- }
150
- async function coalesceAsync(key, fnc) {
151
- if (!hasKey(key)) {
152
- addKey(key);
153
- try {
154
- const result = await Promise.resolve(fnc());
155
- coalesce({ key, result });
156
- return result;
157
- } catch (error) {
158
- coalesce({ key, error });
159
- throw error;
160
- }
161
- }
162
- return enqueue(key);
163
- }
164
-
165
- // src/wrap.ts
166
- function wrapSync(function_, options) {
167
- const { ttl, keyPrefix, cache } = options;
168
- return function(...arguments_) {
169
- let cacheKey = createWrapKey(function_, arguments_, keyPrefix);
170
- if (options.createKey) {
171
- cacheKey = options.createKey(function_, arguments_, options);
172
- }
173
- let value = cache.get(cacheKey);
174
- if (value === void 0) {
175
- try {
176
- value = function_(...arguments_);
177
- cache.set(cacheKey, value, ttl);
178
- } catch (error) {
179
- cache.emit("error", error);
180
- if (options.cacheErrors) {
181
- cache.set(cacheKey, error, ttl);
182
- }
183
- }
184
- }
185
- return value;
186
- };
187
- }
188
- async function getOrSet(key, function_, options) {
189
- const keyString = typeof key === "function" ? key(options) : key;
190
- let value = await options.cache.get(keyString);
191
- if (value === void 0) {
192
- const cacheId = options.cacheId ?? "default";
193
- const coalesceKey = `${cacheId}::${keyString}`;
194
- value = await coalesceAsync(coalesceKey, async () => {
195
- try {
196
- const result = await function_();
197
- await options.cache.set(keyString, result, options.ttl);
198
- return result;
199
- } catch (error) {
200
- options.cache.emit("error", error);
201
- if (options.cacheErrors) {
202
- await options.cache.set(keyString, error, options.ttl);
203
- }
204
- if (options.throwErrors) {
205
- throw error;
206
- }
207
- }
208
- });
209
- }
210
- return value;
211
- }
212
- function wrap(function_, options) {
213
- const { keyPrefix, cache } = options;
214
- return async function(...arguments_) {
215
- let cacheKey = createWrapKey(function_, arguments_, keyPrefix);
216
- if (options.createKey) {
217
- cacheKey = options.createKey(function_, arguments_, options);
218
- }
219
- return cache.getOrSet(cacheKey, async () => function_(...arguments_), options);
220
- };
221
- }
222
- function createWrapKey(function_, arguments_, keyPrefix) {
223
- if (!keyPrefix) {
224
- return `${function_.name}::${hash(arguments_)}`;
225
- }
226
- return `${keyPrefix}::${function_.name}::${hash(arguments_)}`;
227
- }
228
-
229
- // src/memory-lru.ts
230
- var ListNode = class {
231
- // eslint-disable-next-line @typescript-eslint/parameter-properties
232
- value;
233
- prev = void 0;
234
- next = void 0;
235
- constructor(value) {
236
- this.value = value;
237
- }
238
- };
239
- var DoublyLinkedList = class {
240
- head = void 0;
241
- tail = void 0;
242
- nodesMap = /* @__PURE__ */ new Map();
243
- // Add a new node to the front (most recently used)
244
- addToFront(value) {
245
- const newNode = new ListNode(value);
246
- if (this.head) {
247
- newNode.next = this.head;
248
- this.head.prev = newNode;
249
- this.head = newNode;
250
- } else {
251
- this.head = this.tail = newNode;
252
- }
253
- this.nodesMap.set(value, newNode);
254
- }
255
- // Move an existing node to the front (most recently used)
256
- moveToFront(value) {
257
- const node = this.nodesMap.get(value);
258
- if (!node || this.head === node) {
259
- return;
260
- }
261
- if (node.prev) {
262
- node.prev.next = node.next;
263
- }
264
- if (node.next) {
265
- node.next.prev = node.prev;
266
- }
267
- if (node === this.tail) {
268
- this.tail = node.prev;
269
- }
270
- node.prev = void 0;
271
- node.next = this.head;
272
- if (this.head) {
273
- this.head.prev = node;
274
- }
275
- this.head = node;
276
- this.tail ??= node;
277
- }
278
- // Get the oldest node (tail)
279
- getOldest() {
280
- return this.tail ? this.tail.value : void 0;
281
- }
282
- // Remove the oldest node (tail)
283
- removeOldest() {
284
- if (!this.tail) {
285
- return void 0;
286
- }
287
- const oldValue = this.tail.value;
288
- if (this.tail.prev) {
289
- this.tail = this.tail.prev;
290
- this.tail.next = void 0;
291
- } else {
292
- this.head = this.tail = void 0;
293
- }
294
- this.nodesMap.delete(oldValue);
295
- return oldValue;
296
- }
297
- get size() {
298
- return this.nodesMap.size;
299
- }
300
- };
301
-
302
- // src/memory.ts
303
- var defaultStoreHashSize = 16;
304
- var maximumMapSize = 16777216;
305
- var CacheableMemory = class extends Hookified {
306
- _lru = new DoublyLinkedList();
307
- _storeHashSize = defaultStoreHashSize;
308
- _storeHashAlgorithm = "djb2Hash" /* djb2Hash */;
309
- // Default is djb2Hash
310
- _store = Array.from({ length: this._storeHashSize }, () => /* @__PURE__ */ new Map());
311
- _ttl;
312
- // Turned off by default
313
- _useClone = true;
314
- // Turned on by default
315
- _lruSize = 0;
316
- // Turned off by default
317
- _checkInterval = 0;
318
- // Turned off by default
319
- _interval = 0;
320
- // Turned off by default
321
- /**
322
- * @constructor
323
- * @param {CacheableMemoryOptions} [options] - The options for the CacheableMemory
324
- */
325
- constructor(options) {
326
- super();
327
- if (options?.ttl) {
328
- this.setTtl(options.ttl);
329
- }
330
- if (options?.useClone !== void 0) {
331
- this._useClone = options.useClone;
332
- }
333
- if (options?.storeHashSize && options.storeHashSize > 0) {
334
- this._storeHashSize = options.storeHashSize;
335
- }
336
- if (options?.lruSize) {
337
- if (options.lruSize > maximumMapSize) {
338
- this.emit("error", new Error(`LRU size cannot be larger than ${maximumMapSize} due to Map limitations.`));
339
- } else {
340
- this._lruSize = options.lruSize;
341
- }
342
- }
343
- if (options?.checkInterval) {
344
- this._checkInterval = options.checkInterval;
345
- }
346
- if (options?.storeHashAlgorithm) {
347
- this._storeHashAlgorithm = options.storeHashAlgorithm;
348
- }
349
- this._store = Array.from({ length: this._storeHashSize }, () => /* @__PURE__ */ new Map());
350
- this.startIntervalCheck();
351
- }
352
- /**
353
- * Gets the time-to-live
354
- * @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.
355
- */
356
- get ttl() {
357
- return this._ttl;
358
- }
359
- /**
360
- * Sets the time-to-live
361
- * @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.
362
- */
363
- set ttl(value) {
364
- this.setTtl(value);
365
- }
366
- /**
367
- * Gets whether to use clone
368
- * @returns {boolean} - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
369
- */
370
- get useClone() {
371
- return this._useClone;
372
- }
373
- /**
374
- * Sets whether to use clone
375
- * @param {boolean} value - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
376
- */
377
- set useClone(value) {
378
- this._useClone = value;
379
- }
380
- /**
381
- * Gets the size of the LRU cache
382
- * @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.
383
- */
384
- get lruSize() {
385
- return this._lruSize;
386
- }
387
- /**
388
- * Sets the size of the LRU cache
389
- * @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.
390
- */
391
- set lruSize(value) {
392
- if (value > maximumMapSize) {
393
- this.emit("error", new Error(`LRU size cannot be larger than ${maximumMapSize} due to Map limitations.`));
394
- return;
395
- }
396
- this._lruSize = value;
397
- if (this._lruSize === 0) {
398
- this._lru = new DoublyLinkedList();
399
- return;
400
- }
401
- this.lruResize();
402
- }
403
- /**
404
- * Gets the check interval
405
- * @returns {number} - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
406
- */
407
- get checkInterval() {
408
- return this._checkInterval;
409
- }
410
- /**
411
- * Sets the check interval
412
- * @param {number} value - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
413
- */
414
- set checkInterval(value) {
415
- this._checkInterval = value;
416
- }
417
- /**
418
- * Gets the size of the cache
419
- * @returns {number} - The size of the cache
420
- */
421
- get size() {
422
- let size = 0;
423
- for (const store of this._store) {
424
- size += store.size;
425
- }
426
- return size;
427
- }
428
- /**
429
- * Gets the number of hash stores
430
- * @returns {number} - The number of hash stores
431
- */
432
- get storeHashSize() {
433
- return this._storeHashSize;
434
- }
435
- /**
436
- * Sets the number of hash stores. This will recreate the store and all data will be cleared
437
- * @param {number} value - The number of hash stores
438
- */
439
- set storeHashSize(value) {
440
- if (value === this._storeHashSize) {
441
- return;
442
- }
443
- this._storeHashSize = value;
444
- this._store = Array.from({ length: this._storeHashSize }, () => /* @__PURE__ */ new Map());
445
- }
446
- /**
447
- * Gets the store hash algorithm
448
- * @returns {StoreHashAlgorithm | StoreHashAlgorithmFunction} - The store hash algorithm
449
- */
450
- get storeHashAlgorithm() {
451
- return this._storeHashAlgorithm;
452
- }
453
- /**
454
- * Sets the store hash algorithm. This will recreate the store and all data will be cleared
455
- * @param {StoreHashAlgorithm | StoreHashAlgorithmFunction} value - The store hash algorithm
456
- */
457
- set storeHashAlgorithm(value) {
458
- this._storeHashAlgorithm = value;
459
- }
460
- /**
461
- * Gets the keys
462
- * @returns {IterableIterator<string>} - The keys
463
- */
464
- get keys() {
465
- const keys = new Array();
466
- for (const store of this._store) {
467
- for (const key of store.keys()) {
468
- const item = store.get(key);
469
- if (item && this.hasExpired(item)) {
470
- store.delete(key);
471
- continue;
472
- }
473
- keys.push(key);
474
- }
475
- }
476
- return keys.values();
477
- }
478
- /**
479
- * Gets the items
480
- * @returns {IterableIterator<CacheableStoreItem>} - The items
481
- */
482
- get items() {
483
- const items = new Array();
484
- for (const store of this._store) {
485
- for (const item of store.values()) {
486
- if (this.hasExpired(item)) {
487
- store.delete(item.key);
488
- continue;
489
- }
490
- items.push(item);
491
- }
492
- }
493
- return items.values();
494
- }
495
- /**
496
- * Gets the store
497
- * @returns {Array<Map<string, CacheableStoreItem>>} - The store
498
- */
499
- get store() {
500
- return this._store;
501
- }
502
- /**
503
- * Gets the value of the key
504
- * @param {string} key - The key to get the value
505
- * @returns {T | undefined} - The value of the key
506
- */
507
- get(key) {
508
- const store = this.getStore(key);
509
- const item = store.get(key);
510
- if (!item) {
511
- return void 0;
512
- }
513
- if (item.expires && Date.now() > item.expires) {
514
- store.delete(key);
515
- return void 0;
516
- }
517
- this.lruMoveToFront(key);
518
- if (!this._useClone) {
519
- return item.value;
520
- }
521
- return this.clone(item.value);
522
- }
523
- /**
524
- * Gets the values of the keys
525
- * @param {string[]} keys - The keys to get the values
526
- * @returns {T[]} - The values of the keys
527
- */
528
- getMany(keys) {
529
- const result = new Array();
530
- for (const key of keys) {
531
- result.push(this.get(key));
532
- }
533
- return result;
534
- }
535
- /**
536
- * Gets the raw value of the key
537
- * @param {string} key - The key to get the value
538
- * @returns {CacheableStoreItem | undefined} - The raw value of the key
539
- */
540
- getRaw(key) {
541
- const store = this.getStore(key);
542
- const item = store.get(key);
543
- if (!item) {
544
- return void 0;
545
- }
546
- if (item.expires && item.expires && Date.now() > item.expires) {
547
- store.delete(key);
548
- return void 0;
549
- }
550
- this.lruMoveToFront(key);
551
- return item;
552
- }
553
- /**
554
- * Gets the raw values of the keys
555
- * @param {string[]} keys - The keys to get the values
556
- * @returns {CacheableStoreItem[]} - The raw values of the keys
557
- */
558
- getManyRaw(keys) {
559
- const result = new Array();
560
- for (const key of keys) {
561
- result.push(this.getRaw(key));
562
- }
563
- return result;
564
- }
565
- /**
566
- * Sets the value of the key
567
- * @param {string} key - The key to set the value
568
- * @param {any} value - The value to set
569
- * @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.
570
- * If you want to set expire directly you can do that by setting the expire property in the SetOptions.
571
- * 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.
572
- * @returns {void}
573
- */
574
- set(key, value, ttl) {
575
- const store = this.getStore(key);
576
- let expires;
577
- if (ttl !== void 0 || this._ttl !== void 0) {
578
- if (typeof ttl === "object") {
579
- if (ttl.expire) {
580
- expires = typeof ttl.expire === "number" ? ttl.expire : ttl.expire.getTime();
581
- }
582
- if (ttl.ttl) {
583
- const finalTtl = shorthandToTime(ttl.ttl);
584
- if (finalTtl !== void 0) {
585
- expires = finalTtl;
586
- }
587
- }
588
- } else {
589
- const finalTtl = shorthandToTime(ttl ?? this._ttl);
590
- if (finalTtl !== void 0) {
591
- expires = finalTtl;
592
- }
593
- }
594
- }
595
- if (this._lruSize > 0) {
596
- if (store.has(key)) {
597
- this.lruMoveToFront(key);
598
- } else {
599
- this.lruAddToFront(key);
600
- if (this._lru.size > this._lruSize) {
601
- const oldestKey = this._lru.getOldest();
602
- if (oldestKey) {
603
- this._lru.removeOldest();
604
- this.delete(oldestKey);
605
- }
606
- }
607
- }
608
- }
609
- const item = { key, value, expires };
610
- store.set(
611
- key,
612
- item
613
- );
614
- }
615
- /**
616
- * Sets the values of the keys
617
- * @param {CacheableItem[]} items - The items to set
618
- * @returns {void}
619
- */
620
- setMany(items) {
621
- for (const item of items) {
622
- this.set(item.key, item.value, item.ttl);
623
- }
624
- }
625
- /**
626
- * Checks if the key exists
627
- * @param {string} key - The key to check
628
- * @returns {boolean} - If true, the key exists. If false, the key does not exist.
629
- */
630
- has(key) {
631
- const item = this.get(key);
632
- return Boolean(item);
633
- }
634
- /**
635
- * @function hasMany
636
- * @param {string[]} keys - The keys to check
637
- * @returns {boolean[]} - If true, the key exists. If false, the key does not exist.
638
- */
639
- hasMany(keys) {
640
- const result = new Array();
641
- for (const key of keys) {
642
- const item = this.get(key);
643
- result.push(Boolean(item));
644
- }
645
- return result;
646
- }
647
- /**
648
- * Take will get the key and delete the entry from cache
649
- * @param {string} key - The key to take
650
- * @returns {T | undefined} - The value of the key
651
- */
652
- take(key) {
653
- const item = this.get(key);
654
- if (!item) {
655
- return void 0;
656
- }
657
- this.delete(key);
658
- return item;
659
- }
660
- /**
661
- * TakeMany will get the keys and delete the entries from cache
662
- * @param {string[]} keys - The keys to take
663
- * @returns {T[]} - The values of the keys
664
- */
665
- takeMany(keys) {
666
- const result = new Array();
667
- for (const key of keys) {
668
- result.push(this.take(key));
669
- }
670
- return result;
671
- }
672
- /**
673
- * Delete the key
674
- * @param {string} key - The key to delete
675
- * @returns {void}
676
- */
677
- delete(key) {
678
- const store = this.getStore(key);
679
- store.delete(key);
680
- }
681
- /**
682
- * Delete the keys
683
- * @param {string[]} keys - The keys to delete
684
- * @returns {void}
685
- */
686
- deleteMany(keys) {
687
- for (const key of keys) {
688
- this.delete(key);
689
- }
690
- }
691
- /**
692
- * Clear the cache
693
- * @returns {void}
694
- */
695
- clear() {
696
- this._store = Array.from({ length: this._storeHashSize }, () => /* @__PURE__ */ new Map());
697
- this._lru = new DoublyLinkedList();
698
- }
699
- /**
700
- * Get the store based on the key (internal use)
701
- * @param {string} key - The key to get the store
702
- * @returns {CacheableHashStore} - The store
703
- */
704
- getStore(key) {
705
- const hash2 = this.getKeyStoreHash(key);
706
- this._store[hash2] ||= /* @__PURE__ */ new Map();
707
- return this._store[hash2];
708
- }
709
- /**
710
- * Hash the key for which store to go to (internal use)
711
- * @param {string} key - The key to hash
712
- * Available algorithms are: SHA256, SHA1, MD5, and djb2Hash.
713
- * @returns {number} - The hashed key as a number
714
- */
715
- getKeyStoreHash(key) {
716
- if (this._store.length === 1) {
717
- return 0;
718
- }
719
- if (this._storeHashAlgorithm === "djb2Hash" /* djb2Hash */) {
720
- return djb2Hash(key, 0, this._storeHashSize);
721
- }
722
- if (typeof this._storeHashAlgorithm === "function") {
723
- return this._storeHashAlgorithm(key, this._storeHashSize);
724
- }
725
- return hashToNumber(key, 0, this._storeHashSize, this._storeHashAlgorithm);
726
- }
727
- /**
728
- * Clone the value. This is for internal use
729
- * @param {any} value - The value to clone
730
- * @returns {any} - The cloned value
731
- */
732
- clone(value) {
733
- if (this.isPrimitive(value)) {
734
- return value;
735
- }
736
- return structuredClone(value);
737
- }
738
- /**
739
- * Add to the front of the LRU cache. This is for internal use
740
- * @param {string} key - The key to add to the front
741
- * @returns {void}
742
- */
743
- lruAddToFront(key) {
744
- if (this._lruSize === 0) {
745
- return;
746
- }
747
- this._lru.addToFront(key);
748
- }
749
- /**
750
- * Move to the front of the LRU cache. This is for internal use
751
- * @param {string} key - The key to move to the front
752
- * @returns {void}
753
- */
754
- lruMoveToFront(key) {
755
- if (this._lruSize === 0) {
756
- return;
757
- }
758
- this._lru.moveToFront(key);
759
- }
760
- /**
761
- * Resize the LRU cache. This is for internal use.
762
- * @returns {void}
763
- */
764
- lruResize() {
765
- while (this._lru.size > this._lruSize) {
766
- const oldestKey = this._lru.getOldest();
767
- if (oldestKey) {
768
- this._lru.removeOldest();
769
- this.delete(oldestKey);
770
- }
771
- }
772
- }
773
- /**
774
- * Check for expiration. This is for internal use
775
- * @returns {void}
776
- */
777
- checkExpiration() {
778
- for (const store of this._store) {
779
- for (const item of store.values()) {
780
- if (item.expires && Date.now() > item.expires) {
781
- store.delete(item.key);
782
- }
783
- }
784
- }
785
- }
786
- /**
787
- * Start the interval check. This is for internal use
788
- * @returns {void}
789
- */
790
- startIntervalCheck() {
791
- if (this._checkInterval > 0) {
792
- if (this._interval) {
793
- clearInterval(this._interval);
794
- }
795
- this._interval = setInterval(() => {
796
- this.checkExpiration();
797
- }, this._checkInterval).unref();
798
- }
799
- }
800
- /**
801
- * Stop the interval check. This is for internal use
802
- * @returns {void}
803
- */
804
- stopIntervalCheck() {
805
- if (this._interval) {
806
- clearInterval(this._interval);
807
- }
808
- this._interval = 0;
809
- this._checkInterval = 0;
810
- }
811
- /**
812
- * Wrap the function for caching
813
- * @param {Function} function_ - The function to wrap
814
- * @param {Object} [options] - The options to wrap
815
- * @returns {Function} - The wrapped function
816
- */
817
- wrap(function_, options) {
818
- const wrapOptions = {
819
- ttl: options?.ttl ?? this._ttl,
820
- keyPrefix: options?.keyPrefix,
821
- cache: this
822
- };
823
- return wrapSync(function_, wrapOptions);
824
- }
825
- isPrimitive(value) {
826
- const result = false;
827
- if (value === null || value === void 0) {
828
- return true;
829
- }
830
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
831
- return true;
832
- }
833
- return result;
834
- }
835
- setTtl(ttl) {
836
- if (typeof ttl === "string" || ttl === void 0) {
837
- this._ttl = ttl;
838
- } else if (ttl > 0) {
839
- this._ttl = ttl;
840
- } else {
841
- this._ttl = void 0;
842
- }
843
- }
844
- hasExpired(item) {
845
- if (item.expires && Date.now() > item.expires) {
846
- return true;
847
- }
848
- return false;
849
- }
850
- };
851
-
852
- // src/keyv-memory.ts
853
- var KeyvCacheableMemory = class {
854
- opts = {
855
- ttl: 0,
856
- useClone: true,
857
- lruSize: 0,
858
- checkInterval: 0
859
- };
860
- _defaultCache = new CacheableMemory();
861
- _nCache = /* @__PURE__ */ new Map();
862
- _namespace;
863
- constructor(options) {
864
- if (options) {
865
- this.opts = options;
866
- this._defaultCache = new CacheableMemory(options);
867
- if (options.namespace) {
868
- this._namespace = options.namespace;
869
- this._nCache.set(this._namespace, new CacheableMemory(options));
870
- }
871
- }
872
- }
873
- get namespace() {
874
- return this._namespace;
875
- }
876
- set namespace(value) {
877
- this._namespace = value;
878
- }
879
- get store() {
880
- return this.getStore(this._namespace);
881
- }
882
- async get(key) {
883
- const result = this.getStore(this._namespace).get(key);
884
- if (result) {
885
- return result;
886
- }
887
- return void 0;
888
- }
889
- async getMany(keys) {
890
- const result = this.getStore(this._namespace).getMany(keys);
891
- return result;
892
- }
893
- async set(key, value, ttl) {
894
- this.getStore(this._namespace).set(key, value, ttl);
895
- }
896
- async setMany(values) {
897
- this.getStore(this._namespace).setMany(values);
898
- }
899
- async delete(key) {
900
- this.getStore(this._namespace).delete(key);
901
- return true;
902
- }
903
- async deleteMany(key) {
904
- this.getStore(this._namespace).deleteMany(key);
905
- return true;
906
- }
907
- async clear() {
908
- this.getStore(this._namespace).clear();
909
- }
910
- async has(key) {
911
- return this.getStore(this._namespace).has(key);
912
- }
913
- on(event, listener) {
914
- this.getStore(this._namespace).on(event, listener);
915
- return this;
916
- }
917
- getStore(namespace) {
918
- if (!namespace) {
919
- return this._defaultCache;
920
- }
921
- if (!this._nCache.has(namespace)) {
922
- this._nCache.set(namespace, new CacheableMemory(this.opts));
923
- }
924
- return this._nCache.get(namespace);
925
- }
926
- };
927
- function createKeyv(options) {
928
- const store = new KeyvCacheableMemory(options);
929
- const namespace = options?.namespace;
930
- let ttl;
931
- if (options?.ttl && Number.isInteger(options.ttl)) {
932
- ttl = options?.ttl;
933
- }
934
- const keyv = new Keyv({ store, namespace, ttl });
935
- keyv.serialize = void 0;
936
- keyv.deserialize = void 0;
937
- return keyv;
938
- }
939
-
940
- // src/stats.ts
941
- var CacheableStats = class {
942
- _hits = 0;
943
- _misses = 0;
944
- _gets = 0;
945
- _sets = 0;
946
- _deletes = 0;
947
- _clears = 0;
948
- _vsize = 0;
949
- _ksize = 0;
950
- _count = 0;
951
- _enabled = false;
952
- constructor(options) {
953
- if (options?.enabled) {
954
- this._enabled = options.enabled;
955
- }
956
- }
957
- /**
958
- * @returns {boolean} - Whether the stats are enabled
959
- */
960
- get enabled() {
961
- return this._enabled;
962
- }
963
- /**
964
- * @param {boolean} enabled - Whether to enable the stats
965
- */
966
- set enabled(enabled) {
967
- this._enabled = enabled;
968
- }
969
- /**
970
- * @returns {number} - The number of hits
971
- * @readonly
972
- */
973
- get hits() {
974
- return this._hits;
975
- }
976
- /**
977
- * @returns {number} - The number of misses
978
- * @readonly
979
- */
980
- get misses() {
981
- return this._misses;
982
- }
983
- /**
984
- * @returns {number} - The number of gets
985
- * @readonly
986
- */
987
- get gets() {
988
- return this._gets;
989
- }
990
- /**
991
- * @returns {number} - The number of sets
992
- * @readonly
993
- */
994
- get sets() {
995
- return this._sets;
996
- }
997
- /**
998
- * @returns {number} - The number of deletes
999
- * @readonly
1000
- */
1001
- get deletes() {
1002
- return this._deletes;
1003
- }
1004
- /**
1005
- * @returns {number} - The number of clears
1006
- * @readonly
1007
- */
1008
- get clears() {
1009
- return this._clears;
1010
- }
1011
- /**
1012
- * @returns {number} - The vsize (value size) of the cache instance
1013
- * @readonly
1014
- */
1015
- get vsize() {
1016
- return this._vsize;
1017
- }
1018
- /**
1019
- * @returns {number} - The ksize (key size) of the cache instance
1020
- * @readonly
1021
- */
1022
- get ksize() {
1023
- return this._ksize;
1024
- }
1025
- /**
1026
- * @returns {number} - The count of the cache instance
1027
- * @readonly
1028
- */
1029
- get count() {
1030
- return this._count;
1031
- }
1032
- incrementHits() {
1033
- if (!this._enabled) {
1034
- return;
1035
- }
1036
- this._hits++;
1037
- }
1038
- incrementMisses() {
1039
- if (!this._enabled) {
1040
- return;
1041
- }
1042
- this._misses++;
1043
- }
1044
- incrementGets() {
1045
- if (!this._enabled) {
1046
- return;
1047
- }
1048
- this._gets++;
1049
- }
1050
- incrementSets() {
1051
- if (!this._enabled) {
1052
- return;
1053
- }
1054
- this._sets++;
1055
- }
1056
- incrementDeletes() {
1057
- if (!this._enabled) {
1058
- return;
1059
- }
1060
- this._deletes++;
1061
- }
1062
- incrementClears() {
1063
- if (!this._enabled) {
1064
- return;
1065
- }
1066
- this._clears++;
1067
- }
1068
- // eslint-disable-next-line @typescript-eslint/naming-convention
1069
- incrementVSize(value) {
1070
- if (!this._enabled) {
1071
- return;
1072
- }
1073
- this._vsize += this.roughSizeOfObject(value);
1074
- }
1075
- // eslint-disable-next-line @typescript-eslint/naming-convention
1076
- decreaseVSize(value) {
1077
- if (!this._enabled) {
1078
- return;
1079
- }
1080
- this._vsize -= this.roughSizeOfObject(value);
1081
- }
1082
- // eslint-disable-next-line @typescript-eslint/naming-convention
1083
- incrementKSize(key) {
1084
- if (!this._enabled) {
1085
- return;
1086
- }
1087
- this._ksize += this.roughSizeOfString(key);
1088
- }
1089
- // eslint-disable-next-line @typescript-eslint/naming-convention
1090
- decreaseKSize(key) {
1091
- if (!this._enabled) {
1092
- return;
1093
- }
1094
- this._ksize -= this.roughSizeOfString(key);
1095
- }
1096
- incrementCount() {
1097
- if (!this._enabled) {
1098
- return;
1099
- }
1100
- this._count++;
1101
- }
1102
- decreaseCount() {
1103
- if (!this._enabled) {
1104
- return;
1105
- }
1106
- this._count--;
1107
- }
1108
- setCount(count) {
1109
- if (!this._enabled) {
1110
- return;
1111
- }
1112
- this._count = count;
1113
- }
1114
- roughSizeOfString(value) {
1115
- return value.length * 2;
1116
- }
1117
- roughSizeOfObject(object) {
1118
- const objectList = [];
1119
- const stack = [object];
1120
- let bytes = 0;
1121
- while (stack.length > 0) {
1122
- const value = stack.pop();
1123
- if (typeof value === "boolean") {
1124
- bytes += 4;
1125
- } else if (typeof value === "string") {
1126
- bytes += value.length * 2;
1127
- } else if (typeof value === "number") {
1128
- bytes += 8;
1129
- } else if (typeof value === "object" && value !== null && !objectList.includes(value)) {
1130
- objectList.push(value);
1131
- for (const key in value) {
1132
- bytes += key.length * 2;
1133
- stack.push(value[key]);
1134
- }
1135
- }
1136
- }
1137
- return bytes;
1138
- }
1139
- reset() {
1140
- this._hits = 0;
1141
- this._misses = 0;
1142
- this._gets = 0;
1143
- this._sets = 0;
1144
- this._deletes = 0;
1145
- this._clears = 0;
1146
- this._vsize = 0;
1147
- this._ksize = 0;
1148
- this._count = 0;
1149
- }
1150
- resetStoreValues() {
1151
- this._vsize = 0;
1152
- this._ksize = 0;
1153
- this._count = 0;
1154
- }
1155
- };
1156
-
1157
- // src/ttl.ts
1158
- function getTtlFromExpires(expires) {
1159
- if (expires === void 0 || expires === null) {
1160
- return void 0;
1161
- }
1162
- const now = Date.now();
1163
- if (expires < now) {
1164
- return void 0;
1165
- }
1166
- return expires - now;
1167
- }
1168
- function getCascadingTtl(cacheableTtl, primaryTtl, secondaryTtl) {
1169
- return secondaryTtl ?? primaryTtl ?? shorthandToMilliseconds(cacheableTtl);
1170
- }
1171
- function calculateTtlFromExpiration(ttl, expires) {
1172
- const ttlFromExpires = getTtlFromExpires(expires);
1173
- const expiresFromTtl = ttl ? Date.now() + ttl : void 0;
1174
- if (ttlFromExpires === void 0) {
1175
- return ttl;
1176
- }
1177
- if (expiresFromTtl === void 0) {
1178
- return ttlFromExpires;
1179
- }
1180
- if (expires > expiresFromTtl) {
1181
- return ttl;
1182
- }
1183
- return ttlFromExpires;
1184
- }
1185
-
1186
- // src/index.ts
1187
- import {
1188
- KeyvHooks,
1189
- Keyv as Keyv3
1190
- } from "keyv";
1191
- var CacheableHooks = /* @__PURE__ */ ((CacheableHooks2) => {
1192
- CacheableHooks2["BEFORE_SET"] = "BEFORE_SET";
1193
- CacheableHooks2["AFTER_SET"] = "AFTER_SET";
1194
- CacheableHooks2["BEFORE_SET_MANY"] = "BEFORE_SET_MANY";
1195
- CacheableHooks2["AFTER_SET_MANY"] = "AFTER_SET_MANY";
1196
- CacheableHooks2["BEFORE_GET"] = "BEFORE_GET";
1197
- CacheableHooks2["AFTER_GET"] = "AFTER_GET";
1198
- CacheableHooks2["BEFORE_GET_MANY"] = "BEFORE_GET_MANY";
1199
- CacheableHooks2["AFTER_GET_MANY"] = "AFTER_GET_MANY";
1200
- CacheableHooks2["BEFORE_SECONDARY_SETS_PRIMARY"] = "BEFORE_SECONDARY_SETS_PRIMARY";
1201
- return CacheableHooks2;
1202
- })(CacheableHooks || {});
1203
- var CacheableEvents = /* @__PURE__ */ ((CacheableEvents2) => {
1204
- CacheableEvents2["ERROR"] = "error";
1205
- return CacheableEvents2;
1206
- })(CacheableEvents || {});
1207
- var Cacheable = class extends Hookified2 {
1208
- _primary = createKeyv();
1209
- _secondary;
1210
- _nonBlocking = false;
1211
- _ttl;
1212
- _stats = new CacheableStats({ enabled: false });
1213
- _namespace;
1214
- _cacheId = Math.random().toString(36).slice(2);
1215
- /**
1216
- * Creates a new cacheable instance
1217
- * @param {CacheableOptions} [options] The options for the cacheable instance
1218
- */
1219
- constructor(options) {
1220
- super();
1221
- if (options?.primary) {
1222
- this.setPrimary(options.primary);
1223
- }
1224
- if (options?.secondary) {
1225
- this.setSecondary(options.secondary);
1226
- }
1227
- if (options?.nonBlocking) {
1228
- this._nonBlocking = options.nonBlocking;
1229
- }
1230
- if (options?.stats) {
1231
- this._stats.enabled = options.stats;
1232
- }
1233
- if (options?.ttl) {
1234
- this.setTtl(options.ttl);
1235
- }
1236
- if (options?.cacheId) {
1237
- this._cacheId = options.cacheId;
1238
- }
1239
- if (options?.namespace) {
1240
- this._namespace = options.namespace;
1241
- this._primary.namespace = this.getNameSpace();
1242
- if (this._secondary) {
1243
- this._secondary.namespace = this.getNameSpace();
1244
- }
1245
- }
1246
- }
1247
- /**
1248
- * The namespace for the cacheable instance
1249
- * @returns {string | (() => string) | undefined} The namespace for the cacheable instance
1250
- */
1251
- get namespace() {
1252
- return this._namespace;
1253
- }
1254
- /**
1255
- * Sets the namespace for the cacheable instance
1256
- * @param {string | (() => string) | undefined} namespace The namespace for the cacheable instance
1257
- * @returns {void}
1258
- */
1259
- set namespace(namespace) {
1260
- this._namespace = namespace;
1261
- this._primary.namespace = this.getNameSpace();
1262
- if (this._secondary) {
1263
- this._secondary.namespace = this.getNameSpace();
1264
- }
1265
- }
1266
- /**
1267
- * The statistics for the cacheable instance
1268
- * @returns {CacheableStats} The statistics for the cacheable instance
1269
- */
1270
- get stats() {
1271
- return this._stats;
1272
- }
1273
- /**
1274
- * The primary store for the cacheable instance
1275
- * @returns {Keyv} The primary store for the cacheable instance
1276
- */
1277
- get primary() {
1278
- return this._primary;
1279
- }
1280
- /**
1281
- * Sets the primary store for the cacheable instance
1282
- * @param {Keyv} primary The primary store for the cacheable instance
1283
- */
1284
- set primary(primary) {
1285
- this._primary = primary;
1286
- }
1287
- /**
1288
- * The secondary store for the cacheable instance
1289
- * @returns {Keyv | undefined} The secondary store for the cacheable instance
1290
- */
1291
- get secondary() {
1292
- return this._secondary;
1293
- }
1294
- /**
1295
- * Sets the secondary store for the cacheable instance. If it is set to undefined then the secondary store is disabled.
1296
- * @param {Keyv | undefined} secondary The secondary store for the cacheable instance
1297
- * @returns {void}
1298
- */
1299
- set secondary(secondary) {
1300
- this._secondary = secondary;
1301
- }
1302
- /**
1303
- * Gets whether the secondary store is non-blocking mode. It is set to false by default.
1304
- * If it is set to true then the secondary store will not block the primary store.
1305
- *
1306
- * [Learn more about non-blocking mode](https://cacheable.org/docs/cacheable/#non-blocking-operations).
1307
- *
1308
- * @returns {boolean} Whether the cacheable instance is non-blocking
1309
- */
1310
- get nonBlocking() {
1311
- return this._nonBlocking;
1312
- }
1313
- /**
1314
- * Sets whether the secondary store is non-blocking mode. It is set to false by default.
1315
- * If it is set to true then the secondary store will not block the primary store.
1316
- *
1317
- * [Learn more about non-blocking mode](https://cacheable.org/docs/cacheable/#non-blocking-operations).
1318
- *
1319
- * @param {boolean} nonBlocking Whether the cacheable instance is non-blocking
1320
- * @returns {void}
1321
- */
1322
- set nonBlocking(nonBlocking) {
1323
- this._nonBlocking = nonBlocking;
1324
- }
1325
- /**
1326
- * The time-to-live for the cacheable instance and will be used as the default value.
1327
- * can be a number in milliseconds or a human-readable format such as `1s` for 1 second or `1h` for 1 hour
1328
- * or undefined if there is no time-to-live.
1329
- *
1330
- * [Learn more about time-to-live](https://cacheable.org/docs/cacheable/#shorthand-for-time-to-live-ttl).
1331
- *
1332
- * @returns {number | string | undefined} The time-to-live for the cacheable instance in milliseconds, human-readable format or undefined
1333
- * @example
1334
- * ```typescript
1335
- * const cacheable = new Cacheable({ ttl: '1h' });
1336
- * console.log(cacheable.ttl); // 1h
1337
- * ```
1338
- */
1339
- get ttl() {
1340
- return this._ttl;
1341
- }
1342
- /**
1343
- * Sets the time-to-live for the cacheable instance and will be used as the default value.
1344
- * If you set a number it is miliseconds, if you set a string it is a human-readable
1345
- * format such as `1s` for 1 second or `1h` for 1 hour. Setting undefined means that
1346
- * there is no time-to-live.
1347
- *
1348
- * [Learn more about time-to-live](https://cacheable.org/docs/cacheable/#shorthand-for-time-to-live-ttl).
1349
- *
1350
- * @param {number | string | undefined} ttl The time-to-live for the cacheable instance
1351
- * @example
1352
- * ```typescript
1353
- * const cacheable = new Cacheable();
1354
- * cacheable.ttl = '1h'; // Set the time-to-live to 1 hour
1355
- * ```
1356
- * or setting the time-to-live in milliseconds
1357
- * ```typescript
1358
- * const cacheable = new Cacheable();
1359
- * cacheable.ttl = 3600000; // Set the time-to-live to 1 hour
1360
- * ```
1361
- */
1362
- set ttl(ttl) {
1363
- this.setTtl(ttl);
1364
- }
1365
- /**
1366
- * The cacheId for the cacheable instance. This is primarily used for the wrap function to not have conflicts.
1367
- * If it is not set then it will be a random string that is generated
1368
- * @returns {string} The cacheId for the cacheable instance
1369
- */
1370
- get cacheId() {
1371
- return this._cacheId;
1372
- }
1373
- /**
1374
- * Sets the cacheId for the cacheable instance. This is primarily used for the wrap function to not have conflicts.
1375
- * If it is not set then it will be a random string that is generated
1376
- * @param {string} cacheId The cacheId for the cacheable instance
1377
- */
1378
- set cacheId(cacheId) {
1379
- this._cacheId = cacheId;
1380
- }
1381
- /**
1382
- * Sets the primary store for the cacheable instance
1383
- * @param {Keyv | KeyvStoreAdapter} primary The primary store for the cacheable instance
1384
- * @returns {void}
1385
- */
1386
- setPrimary(primary) {
1387
- if (this.isKeyvInstance(primary)) {
1388
- this._primary = primary;
1389
- } else {
1390
- this._primary = new Keyv2(primary);
1391
- }
1392
- this._primary.on("error", (error) => {
1393
- this.emit("error" /* ERROR */, error);
1394
- });
1395
- }
1396
- /**
1397
- * Sets the secondary store for the cacheable instance. If it is set to undefined then the secondary store is disabled.
1398
- * @param {Keyv | KeyvStoreAdapter} secondary The secondary store for the cacheable instance
1399
- * @returns {void}
1400
- */
1401
- setSecondary(secondary) {
1402
- if (this.isKeyvInstance(secondary)) {
1403
- this._secondary = secondary;
1404
- } else {
1405
- this._secondary = new Keyv2(secondary);
1406
- }
1407
- this._secondary.on("error", (error) => {
1408
- this.emit("error" /* ERROR */, error);
1409
- });
1410
- }
1411
- isKeyvInstance(keyv) {
1412
- if (keyv instanceof Keyv2) {
1413
- return true;
1414
- }
1415
- const keyvMethods = ["generateIterator", "get", "getMany", "set", "setMany", "delete", "deleteMany", "has", "hasMany", "clear", "disconnect", "serialize", "deserialize"];
1416
- return keyvMethods.every((method) => typeof keyv[method] === "function");
1417
- }
1418
- getNameSpace() {
1419
- if (typeof this._namespace === "function") {
1420
- return this._namespace();
1421
- }
1422
- return this._namespace;
1423
- }
1424
- async get(key, options = {}) {
1425
- let result;
1426
- const { raw = false } = options;
1427
- try {
1428
- await this.hook("BEFORE_GET" /* BEFORE_GET */, key);
1429
- result = await this._primary.get(key, { raw: true });
1430
- let ttl;
1431
- if (!result && this._secondary) {
1432
- const secondaryResult = await this.getSecondaryRawResults(key);
1433
- if (secondaryResult?.value) {
1434
- result = secondaryResult;
1435
- const cascadeTtl = getCascadingTtl(this._ttl, this._primary.ttl);
1436
- const expires = secondaryResult.expires ?? void 0;
1437
- ttl = calculateTtlFromExpiration(cascadeTtl, expires);
1438
- const setItem = { key, value: result.value, ttl };
1439
- await this.hook("BEFORE_SECONDARY_SETS_PRIMARY" /* BEFORE_SECONDARY_SETS_PRIMARY */, setItem);
1440
- await this._primary.set(setItem.key, setItem.value, setItem.ttl);
1441
- }
1442
- }
1443
- await this.hook("AFTER_GET" /* AFTER_GET */, { key, result, ttl });
1444
- } catch (error) {
1445
- this.emit("error" /* ERROR */, error);
1446
- }
1447
- if (this.stats.enabled) {
1448
- if (result) {
1449
- this._stats.incrementHits();
1450
- } else {
1451
- this._stats.incrementMisses();
1452
- }
1453
- this.stats.incrementGets();
1454
- }
1455
- return raw ? result : result?.value;
1456
- }
1457
- async getMany(keys, options = {}) {
1458
- let result = [];
1459
- const { raw = false } = options;
1460
- try {
1461
- await this.hook("BEFORE_GET_MANY" /* BEFORE_GET_MANY */, keys);
1462
- result = await this._primary.get(keys, { raw: true });
1463
- if (this._secondary) {
1464
- const missingKeys = [];
1465
- for (const [i, key] of keys.entries()) {
1466
- if (!result[i]) {
1467
- missingKeys.push(key);
1468
- }
1469
- }
1470
- const secondaryResults = await this.getManySecondaryRawResults(missingKeys);
1471
- for await (const [i, key] of keys.entries()) {
1472
- if (!result[i] && secondaryResults[i]) {
1473
- result[i] = secondaryResults[i];
1474
- const cascadeTtl = getCascadingTtl(this._ttl, this._primary.ttl);
1475
- let { expires } = secondaryResults[i];
1476
- if (expires === null) {
1477
- expires = void 0;
1478
- }
1479
- const ttl = calculateTtlFromExpiration(cascadeTtl, expires);
1480
- const setItem = { key, value: result[i].value, ttl };
1481
- await this.hook("BEFORE_SECONDARY_SETS_PRIMARY" /* BEFORE_SECONDARY_SETS_PRIMARY */, setItem);
1482
- await this._primary.set(setItem.key, setItem.value, setItem.ttl);
1483
- }
1484
- }
1485
- }
1486
- await this.hook("AFTER_GET_MANY" /* AFTER_GET_MANY */, { keys, result });
1487
- } catch (error) {
1488
- this.emit("error" /* ERROR */, error);
1489
- }
1490
- if (this.stats.enabled) {
1491
- for (const item of result) {
1492
- if (item) {
1493
- this._stats.incrementHits();
1494
- } else {
1495
- this._stats.incrementMisses();
1496
- }
1497
- }
1498
- this.stats.incrementGets();
1499
- }
1500
- return raw ? result : result.map((item) => item?.value);
1501
- }
1502
- /**
1503
- * Sets the value of the key. If the secondary store is set then it will also set the value in the secondary store.
1504
- * @param {string} key the key to set the value of
1505
- * @param {T} value The value to set
1506
- * @param {number | string} [ttl] set a number it is miliseconds, set a string it is a human-readable
1507
- * format such as `1s` for 1 second or `1h` for 1 hour. Setting undefined means that it will use the default time-to-live.
1508
- * @returns {boolean} Whether the value was set
1509
- */
1510
- async set(key, value, ttl) {
1511
- let result = false;
1512
- const finalTtl = shorthandToMilliseconds(ttl ?? this._ttl);
1513
- try {
1514
- const item = { key, value, ttl: finalTtl };
1515
- await this.hook("BEFORE_SET" /* BEFORE_SET */, item);
1516
- const promises = [];
1517
- promises.push(this._primary.set(item.key, item.value, item.ttl));
1518
- if (this._secondary) {
1519
- promises.push(this._secondary.set(item.key, item.value, item.ttl));
1520
- }
1521
- if (this._nonBlocking) {
1522
- result = await Promise.race(promises);
1523
- } else {
1524
- const results = await Promise.all(promises);
1525
- result = results[0];
1526
- }
1527
- await this.hook("AFTER_SET" /* AFTER_SET */, item);
1528
- } catch (error) {
1529
- this.emit("error" /* ERROR */, error);
1530
- }
1531
- if (this.stats.enabled) {
1532
- this.stats.incrementKSize(key);
1533
- this.stats.incrementCount();
1534
- this.stats.incrementVSize(value);
1535
- this.stats.incrementSets();
1536
- }
1537
- return result;
1538
- }
1539
- /**
1540
- * Sets the values of the keys. If the secondary store is set then it will also set the values in the secondary store.
1541
- * @param {CacheableItem[]} items The items to set
1542
- * @returns {boolean} Whether the values were set
1543
- */
1544
- async setMany(items) {
1545
- let result = false;
1546
- try {
1547
- await this.hook("BEFORE_SET_MANY" /* BEFORE_SET_MANY */, items);
1548
- result = await this.setManyKeyv(this._primary, items);
1549
- if (this._secondary) {
1550
- if (this._nonBlocking) {
1551
- this.setManyKeyv(this._secondary, items);
1552
- } else {
1553
- await this.setManyKeyv(this._secondary, items);
1554
- }
1555
- }
1556
- await this.hook("AFTER_SET_MANY" /* AFTER_SET_MANY */, items);
1557
- } catch (error) {
1558
- this.emit("error" /* ERROR */, error);
1559
- }
1560
- if (this.stats.enabled) {
1561
- for (const item of items) {
1562
- this.stats.incrementKSize(item.key);
1563
- this.stats.incrementCount();
1564
- this.stats.incrementVSize(item.value);
1565
- }
1566
- }
1567
- return result;
1568
- }
1569
- /**
1570
- * Takes the value of the key and deletes the key. If the key does not exist then it will return undefined.
1571
- * @param {string} key The key to take the value of
1572
- * @returns {Promise<T | undefined>} The value of the key or undefined if the key does not exist
1573
- */
1574
- async take(key) {
1575
- const result = await this.get(key);
1576
- await this.delete(key);
1577
- return result;
1578
- }
1579
- /**
1580
- * Takes the values of the keys and deletes the keys. If the key does not exist then it will return undefined.
1581
- * @param {string[]} keys The keys to take the values of
1582
- * @returns {Promise<Array<T | undefined>>} The values of the keys or undefined if the key does not exist
1583
- */
1584
- async takeMany(keys) {
1585
- const result = await this.getMany(keys);
1586
- await this.deleteMany(keys);
1587
- return result;
1588
- }
1589
- /**
1590
- * Checks if the key exists in the primary store. If it does not exist then it will check the secondary store.
1591
- * @param {string} key The key to check
1592
- * @returns {Promise<boolean>} Whether the key exists
1593
- */
1594
- async has(key) {
1595
- const promises = [];
1596
- promises.push(this._primary.has(key));
1597
- if (this._secondary) {
1598
- promises.push(this._secondary.has(key));
1599
- }
1600
- const resultAll = await Promise.all(promises);
1601
- for (const result of resultAll) {
1602
- if (result) {
1603
- return true;
1604
- }
1605
- }
1606
- return false;
1607
- }
1608
- /**
1609
- * Checks if the keys exist in the primary store. If it does not exist then it will check the secondary store.
1610
- * @param {string[]} keys The keys to check
1611
- * @returns {Promise<boolean[]>} Whether the keys exist
1612
- */
1613
- async hasMany(keys) {
1614
- const result = await this.hasManyKeyv(this._primary, keys);
1615
- const missingKeys = [];
1616
- for (const [i, key] of keys.entries()) {
1617
- if (!result[i] && this._secondary) {
1618
- missingKeys.push(key);
1619
- }
1620
- }
1621
- if (missingKeys.length > 0 && this._secondary) {
1622
- const secondary = await this.hasManyKeyv(this._secondary, keys);
1623
- for (const [i, key] of keys.entries()) {
1624
- if (!result[i] && secondary[i]) {
1625
- result[i] = secondary[i];
1626
- }
1627
- }
1628
- }
1629
- return result;
1630
- }
1631
- /**
1632
- * Deletes the key from the primary store. If the secondary store is set then it will also delete the key from the secondary store.
1633
- * @param {string} key The key to delete
1634
- * @returns {Promise<boolean>} Whether the key was deleted
1635
- */
1636
- async delete(key) {
1637
- let result = false;
1638
- const promises = [];
1639
- if (this.stats.enabled) {
1640
- const statResult = await this._primary.get(key);
1641
- if (statResult) {
1642
- this.stats.decreaseKSize(key);
1643
- this.stats.decreaseVSize(statResult);
1644
- this.stats.decreaseCount();
1645
- this.stats.incrementDeletes();
1646
- }
1647
- }
1648
- promises.push(this._primary.delete(key));
1649
- if (this._secondary) {
1650
- promises.push(this._secondary.delete(key));
1651
- }
1652
- if (this.nonBlocking) {
1653
- result = await Promise.race(promises);
1654
- } else {
1655
- const resultAll = await Promise.all(promises);
1656
- result = resultAll[0];
1657
- }
1658
- return result;
1659
- }
1660
- /**
1661
- * Deletes the keys from the primary store. If the secondary store is set then it will also delete the keys from the secondary store.
1662
- * @param {string[]} keys The keys to delete
1663
- * @returns {Promise<boolean>} Whether the keys were deleted
1664
- */
1665
- async deleteMany(keys) {
1666
- if (this.stats.enabled) {
1667
- const statResult = await this._primary.get(keys);
1668
- for (const key of keys) {
1669
- this.stats.decreaseKSize(key);
1670
- this.stats.decreaseVSize(statResult);
1671
- this.stats.decreaseCount();
1672
- this.stats.incrementDeletes();
1673
- }
1674
- }
1675
- const result = await this.deleteManyKeyv(this._primary, keys);
1676
- if (this._secondary) {
1677
- if (this._nonBlocking) {
1678
- this.deleteManyKeyv(this._secondary, keys);
1679
- } else {
1680
- await this.deleteManyKeyv(this._secondary, keys);
1681
- }
1682
- }
1683
- return result;
1684
- }
1685
- /**
1686
- * Clears the primary store. If the secondary store is set then it will also clear the secondary store.
1687
- * @returns {Promise<void>}
1688
- */
1689
- async clear() {
1690
- const promises = [];
1691
- promises.push(this._primary.clear());
1692
- if (this._secondary) {
1693
- promises.push(this._secondary.clear());
1694
- }
1695
- await (this._nonBlocking ? Promise.race(promises) : Promise.all(promises));
1696
- if (this.stats.enabled) {
1697
- this._stats.resetStoreValues();
1698
- this._stats.incrementClears();
1699
- }
1700
- }
1701
- /**
1702
- * Disconnects the primary store. If the secondary store is set then it will also disconnect the secondary store.
1703
- * @returns {Promise<void>}
1704
- */
1705
- async disconnect() {
1706
- const promises = [];
1707
- promises.push(this._primary.disconnect());
1708
- if (this._secondary) {
1709
- promises.push(this._secondary.disconnect());
1710
- }
1711
- await (this._nonBlocking ? Promise.race(promises) : Promise.all(promises));
1712
- }
1713
- /**
1714
- * Wraps a function with caching
1715
- *
1716
- * [Learn more about wrapping functions](https://cacheable.org/docs/cacheable/#wrap--memoization-for-sync-and-async-functions).
1717
- * @param {Function} function_ The function to wrap
1718
- * @param {WrapOptions} [options] The options for the wrap function
1719
- * @returns {Function} The wrapped function
1720
- */
1721
- wrap(function_, options) {
1722
- const wrapOptions = {
1723
- ttl: options?.ttl ?? this._ttl,
1724
- keyPrefix: options?.keyPrefix,
1725
- cache: this,
1726
- cacheId: this._cacheId
1727
- };
1728
- return wrap(function_, wrapOptions);
1729
- }
1730
- /**
1731
- * Retrieves the value associated with the given key from the cache. If the key is not found,
1732
- * invokes the provided function to calculate the value, stores it in the cache, and then returns it.
1733
- *
1734
- * @param {GetOrSetKey} key - The key to retrieve or set in the cache. This can also be a function that returns a string key.
1735
- * If a function is provided, it will be called with the cache options to generate the key.
1736
- * @param {() => Promise<T>} function_ - The asynchronous function that computes the value to be cached if the key does not exist.
1737
- * @param {GetOrSetFunctionOptions} [options] - Optional settings for caching, such as the time to live (TTL) or whether to cache errors.
1738
- * @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.
1739
- */
1740
- async getOrSet(key, function_, options) {
1741
- const getOrSetOptions = {
1742
- cache: this,
1743
- cacheId: this._cacheId,
1744
- ttl: options?.ttl ?? this._ttl,
1745
- cacheErrors: options?.cacheErrors,
1746
- throwErrors: options?.throwErrors
1747
- };
1748
- return getOrSet(key, function_, getOrSetOptions);
1749
- }
1750
- /**
1751
- * Will hash an object using the specified algorithm. The default algorithm is 'sha256'.
1752
- * @param {any} object the object to hash
1753
- * @param {string} algorithm the hash algorithm to use. The default is 'sha256'
1754
- * @returns {string} the hash of the object
1755
- */
1756
- hash(object, algorithm = "sha256") {
1757
- return hash(object, algorithm);
1758
- }
1759
- async getSecondaryRawResults(key) {
1760
- let result;
1761
- if (this._secondary) {
1762
- result = await this._secondary.get(key, { raw: true });
1763
- }
1764
- return result;
1765
- }
1766
- async getManySecondaryRawResults(keys) {
1767
- let result = new Array();
1768
- if (this._secondary) {
1769
- result = await this._secondary.get(keys, { raw: true });
1770
- }
1771
- return result;
1772
- }
1773
- async deleteManyKeyv(keyv, keys) {
1774
- const promises = [];
1775
- for (const key of keys) {
1776
- promises.push(keyv.delete(key));
1777
- }
1778
- await Promise.all(promises);
1779
- return true;
1780
- }
1781
- async setManyKeyv(keyv, items) {
1782
- const promises = [];
1783
- for (const item of items) {
1784
- const finalTtl = shorthandToMilliseconds(item.ttl ?? this._ttl);
1785
- promises.push(keyv.set(item.key, item.value, finalTtl));
1786
- }
1787
- await Promise.all(promises);
1788
- return true;
1789
- }
1790
- async hasManyKeyv(keyv, keys) {
1791
- const promises = [];
1792
- for (const key of keys) {
1793
- promises.push(keyv.has(key));
1794
- }
1795
- return Promise.all(promises);
1796
- }
1797
- setTtl(ttl) {
1798
- if (typeof ttl === "string" || ttl === void 0) {
1799
- this._ttl = ttl;
1800
- } else if (ttl > 0) {
1801
- this._ttl = ttl;
1802
- } else {
1803
- this._ttl = void 0;
1804
- }
1805
- }
1806
- };
1807
- export {
1808
- Cacheable,
1809
- CacheableEvents,
1810
- CacheableHooks,
1811
- CacheableMemory,
1812
- CacheableStats,
1813
- Keyv3 as Keyv,
1814
- KeyvCacheableMemory,
1815
- KeyvHooks,
1816
- createKeyv,
1817
- getOrSet,
1818
- shorthandToMilliseconds,
1819
- shorthandToTime,
1820
- wrap,
1821
- wrapSync
1822
- };
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};