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