@cacheable/node-cache 3.0.1 → 3.1.1

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.mjs ADDED
@@ -0,0 +1,769 @@
1
+ import { Stats, shorthandToMilliseconds, shorthandToTime } from "@cacheable/utils";
2
+ import { Hookified } from "hookified";
3
+ import Keyv from "keyv";
4
+ //#region src/store.ts
5
+ var NodeCacheStore = class extends Hookified {
6
+ _keyv;
7
+ _ttl;
8
+ _stats = new Stats({ enabled: true });
9
+ _useClones;
10
+ _deleteOnExpire;
11
+ _keys = /* @__PURE__ */ new Set();
12
+ _values = /* @__PURE__ */ new Map();
13
+ _ttls = /* @__PURE__ */ new Map();
14
+ _intervalId = 0;
15
+ constructor(options) {
16
+ super();
17
+ this._ttl = options?.ttl;
18
+ this._keyv = options?.store ?? new Keyv();
19
+ this._useClones = options?.useClones ?? false;
20
+ this._deleteOnExpire = options?.deleteOnExpire ?? true;
21
+ this._keyv.on("error", (error) => {
22
+ /* v8 ignore next -- @preserve */
23
+ this.emit("error", error);
24
+ });
25
+ this.startInterval(options?.checkperiod);
26
+ }
27
+ /**
28
+ * Time to live in milliseconds.
29
+ * @returns {number | string | undefined}
30
+ * @readonly
31
+ */
32
+ get ttl() {
33
+ return this._ttl;
34
+ }
35
+ /**
36
+ * Time to live in milliseconds.
37
+ * @param {number | string | undefined} ttl
38
+ */
39
+ set ttl(ttl) {
40
+ this._ttl = ttl;
41
+ }
42
+ /**
43
+ * Whether to clone values on get/set.
44
+ * @returns {boolean}
45
+ */
46
+ get useClones() {
47
+ return this._useClones;
48
+ }
49
+ /**
50
+ * Whether to clone values on get/set.
51
+ * @param {boolean} value
52
+ */
53
+ set useClones(value) {
54
+ this._useClones = value;
55
+ }
56
+ /**
57
+ * Whether to delete expired items when detected.
58
+ * @returns {boolean}
59
+ */
60
+ get deleteOnExpire() {
61
+ return this._deleteOnExpire;
62
+ }
63
+ /**
64
+ * Whether to delete expired items when detected.
65
+ * @param {boolean} value
66
+ */
67
+ set deleteOnExpire(value) {
68
+ this._deleteOnExpire = value;
69
+ }
70
+ /**
71
+ * The Keyv store instance.
72
+ * @returns {Keyv<T>}
73
+ * @readonly
74
+ */
75
+ get store() {
76
+ return this._keyv;
77
+ }
78
+ /**
79
+ * Set a key/value pair in the cache.
80
+ * @param {string | number} key
81
+ * @param {T} value
82
+ * @param {number} [ttl]
83
+ * @returns {boolean}
84
+ */
85
+ async set(key, value, ttl) {
86
+ const keyValue = key.toString();
87
+ const finalTtl = this.resolveTtl(ttl);
88
+ const valueToStore = this._useClones ? this.clone(value) : value;
89
+ const isOverwrite = this._values.has(keyValue);
90
+ this._keys.add(keyValue);
91
+ if (isOverwrite) {
92
+ const oldValue = this._values.get(keyValue);
93
+ this._stats.decreaseKSize(keyValue);
94
+ this._stats.decreaseVSize(oldValue);
95
+ this._stats.decreaseCount();
96
+ }
97
+ await this._keyv.set(keyValue, valueToStore, finalTtl);
98
+ this._values.set(keyValue, value);
99
+ this.trackExpiration(keyValue, finalTtl);
100
+ this._stats.incrementKSize(keyValue);
101
+ this._stats.incrementVSize(value);
102
+ this._stats.incrementCount();
103
+ const expirationTimestamp = this._ttls.get(keyValue) ?? 0;
104
+ this.emit("set", keyValue, value, expirationTimestamp);
105
+ return true;
106
+ }
107
+ /**
108
+ * Set multiple key/value pairs in the cache.
109
+ * @param {PartialNodeCacheItem[]} list
110
+ * @returns {void}
111
+ */
112
+ async mset(list) {
113
+ await Promise.all(list.map((item) => this.set(item.key, item.value, item.ttl)));
114
+ }
115
+ /**
116
+ * Get a value from the cache.
117
+ * @param {string | number} key
118
+ * @returns {any | undefined}
119
+ */
120
+ async get(key) {
121
+ const keyValue = key.toString();
122
+ if (this.isExpired(keyValue)) {
123
+ await this.handleExpired(keyValue);
124
+ this._stats.incrementMisses();
125
+ return;
126
+ }
127
+ const result = await this._keyv.get(keyValue);
128
+ if (result === void 0) this._stats.incrementMisses();
129
+ else {
130
+ this._stats.incrementHits();
131
+ if (this._useClones) return this.clone(result);
132
+ }
133
+ return result;
134
+ }
135
+ /**
136
+ * Get multiple values from the cache.
137
+ * @param {Array<string | number>} keys
138
+ * @returns {Record<string, any | undefined>}
139
+ */
140
+ async mget(keys) {
141
+ const result = Object.create(null);
142
+ await Promise.all(keys.map(async (key) => {
143
+ const value = await this.get(key);
144
+ result[key.toString()] = value;
145
+ }));
146
+ return result;
147
+ }
148
+ /**
149
+ * Delete a key from the cache.
150
+ * @param {string | number} key
151
+ * @returns {boolean}
152
+ */
153
+ async del(key) {
154
+ const keyValue = key.toString();
155
+ const hadValue = this._values.has(keyValue);
156
+ const value = hadValue ? this._values.get(keyValue) : void 0;
157
+ const result = await this._keyv.delete(keyValue);
158
+ if (result) {
159
+ this._keys.delete(keyValue);
160
+ this._values.delete(keyValue);
161
+ this._ttls.delete(keyValue);
162
+ this._stats.decreaseKSize(keyValue);
163
+ if (hadValue) this._stats.decreaseVSize(value);
164
+ this._stats.decreaseCount();
165
+ this.emit("del", keyValue, value);
166
+ }
167
+ return result;
168
+ }
169
+ /**
170
+ * Delete multiple keys from the cache.
171
+ * @param {Array<string | number>} keys
172
+ * @returns {boolean}
173
+ */
174
+ async mdel(keys) {
175
+ await Promise.all(keys.map((key) => this.del(key)));
176
+ return true;
177
+ }
178
+ /**
179
+ * Clear the cache.
180
+ * @returns {void}
181
+ */
182
+ async clear() {
183
+ await this._keyv.clear();
184
+ this._keys.clear();
185
+ this._values.clear();
186
+ this._ttls.clear();
187
+ this._stats.resetStoreValues();
188
+ }
189
+ /**
190
+ * Flush all data and stats. Emits a "flush" event.
191
+ * @returns {void}
192
+ */
193
+ async flushAll() {
194
+ await this._keyv.clear();
195
+ this._keys.clear();
196
+ this._values.clear();
197
+ this._ttls.clear();
198
+ this._stats = new Stats({ enabled: true });
199
+ this.emit("flush");
200
+ }
201
+ /**
202
+ * Set the TTL of an existing key in the cache.
203
+ * @param {string | number} key
204
+ * @param {number | string} [ttl]
205
+ * @returns {boolean}
206
+ */
207
+ async setTtl(key, ttl) {
208
+ const keyValue = key.toString();
209
+ if (this._values.has(keyValue)) {
210
+ const item = this._values.get(keyValue);
211
+ const finalTtl = this.resolveTtl(ttl);
212
+ await this._keyv.set(keyValue, item, finalTtl);
213
+ this.trackExpiration(keyValue, finalTtl);
214
+ return true;
215
+ }
216
+ return false;
217
+ }
218
+ /**
219
+ * Get the TTL of a key. Returns 0 if the key has no TTL (unlimited),
220
+ * undefined if the key does not exist, or a timestamp in ms of when the key will expire.
221
+ * @param {string | number} key
222
+ * @returns {number | undefined}
223
+ */
224
+ async getTtl(key) {
225
+ const keyValue = key.toString();
226
+ if (!this._keys.has(keyValue)) return;
227
+ const expiration = this._ttls.get(keyValue);
228
+ if (expiration === void 0 || expiration === 0) return 0;
229
+ if (expiration > 0 && expiration < Date.now()) {
230
+ await this.handleExpired(keyValue);
231
+ return;
232
+ }
233
+ return expiration;
234
+ }
235
+ /**
236
+ * Returns an array of all existing keys.
237
+ * @returns {string[]}
238
+ */
239
+ async keys() {
240
+ return [...this._keys];
241
+ }
242
+ /**
243
+ * Returns boolean indicating if the key is cached and not expired.
244
+ * @param {string | number} key
245
+ * @returns {boolean}
246
+ */
247
+ async has(key) {
248
+ const keyValue = key.toString();
249
+ if (!this._keys.has(keyValue)) return false;
250
+ if (this.isExpired(keyValue)) {
251
+ await this.handleExpired(keyValue);
252
+ return false;
253
+ }
254
+ return true;
255
+ }
256
+ /**
257
+ * Get a key from the cache and delete it. If it does exist it will get the value and delete the item from the cache.
258
+ * @param {string | number} key
259
+ * @returns {T | undefined}
260
+ */
261
+ async take(key) {
262
+ const keyValue = key.toString();
263
+ if (this.isExpired(keyValue)) {
264
+ await this.handleExpired(keyValue);
265
+ this._stats.incrementMisses();
266
+ return;
267
+ }
268
+ const result = await this._keyv.get(keyValue);
269
+ if (this._values.has(keyValue)) {
270
+ await this._keyv.delete(keyValue);
271
+ this._keys.delete(keyValue);
272
+ this._values.delete(keyValue);
273
+ this._ttls.delete(keyValue);
274
+ this._stats.incrementHits();
275
+ this._stats.decreaseKSize(keyValue);
276
+ this._stats.decreaseVSize(result);
277
+ this._stats.decreaseCount();
278
+ this.emit("del", keyValue, result);
279
+ if (this._useClones) return this.clone(result);
280
+ } else this._stats.incrementMisses();
281
+ return result;
282
+ }
283
+ /**
284
+ * Gets the stats of the cache
285
+ * @returns {NodeCacheStats} the stats of the cache
286
+ */
287
+ getStats() {
288
+ return {
289
+ keys: this._stats.count,
290
+ hits: this._stats.hits,
291
+ misses: this._stats.misses,
292
+ ksize: this._stats.ksize,
293
+ vsize: this._stats.vsize
294
+ };
295
+ }
296
+ /**
297
+ * Flush the stats.
298
+ * @returns {void}
299
+ */
300
+ flushStats() {
301
+ this._stats = new Stats({ enabled: true });
302
+ this.emit("flush_stats");
303
+ }
304
+ /**
305
+ * Disconnect from the cache.
306
+ * @returns {void}
307
+ */
308
+ async disconnect() {
309
+ this.stopInterval();
310
+ await this._keyv.disconnect();
311
+ }
312
+ /**
313
+ * Close the cache. Stops the interval timer.
314
+ * @returns {void}
315
+ */
316
+ close() {
317
+ this.stopInterval();
318
+ }
319
+ /**
320
+ * Get the interval id.
321
+ * @returns {number | NodeJS.Timeout}
322
+ */
323
+ getIntervalId() {
324
+ return this._intervalId;
325
+ }
326
+ /**
327
+ * Start the check interval for expired items.
328
+ * @param {number} [checkperiod] interval in seconds
329
+ */
330
+ startInterval(checkperiod) {
331
+ this.stopInterval();
332
+ const period = checkperiod ?? 0;
333
+ if (period > 0) {
334
+ const periodMs = period * 1e3;
335
+ this._intervalId = setInterval(() => {
336
+ this.checkData().catch(
337
+ /* v8 ignore next -- @preserve */
338
+ (error) => {
339
+ this.emit("error", error);
340
+ }
341
+ );
342
+ }, periodMs).unref();
343
+ return;
344
+ }
345
+ this._intervalId = 0;
346
+ }
347
+ /**
348
+ * Stop the check interval.
349
+ */
350
+ stopInterval() {
351
+ if (this._intervalId !== 0) {
352
+ clearInterval(this._intervalId);
353
+ this._intervalId = 0;
354
+ }
355
+ }
356
+ clone(value) {
357
+ if (value === null || value === void 0) return value;
358
+ if (typeof value !== "object") return value;
359
+ return structuredClone(value);
360
+ }
361
+ isExpired(key) {
362
+ const expiration = this._ttls.get(key);
363
+ if (expiration !== void 0 && expiration > 0 && expiration < Date.now()) return true;
364
+ return false;
365
+ }
366
+ async handleExpired(key) {
367
+ /* v8 ignore next 3 -- @preserve: race condition guard when key is refreshed between caller's check and this call */
368
+ if (!this.isExpired(key)) return;
369
+ const hadValue = this._values.has(key);
370
+ const value = hadValue ? this._values.get(key) : void 0;
371
+ /* v8 ignore next 3 -- @preserve: race condition guard when key is refreshed during async get */
372
+ if (!this.isExpired(key)) return;
373
+ const wasTracked = this._keys.has(key);
374
+ if (this._deleteOnExpire) {
375
+ await this._keyv.delete(key);
376
+ this._keys.delete(key);
377
+ this._values.delete(key);
378
+ this._ttls.delete(key);
379
+ if (wasTracked) {
380
+ this._stats.decreaseKSize(key);
381
+ if (hadValue) this._stats.decreaseVSize(value);
382
+ this._stats.decreaseCount();
383
+ }
384
+ }
385
+ this.emit("expired", key, value);
386
+ }
387
+ async checkData() {
388
+ for (const [key, expiration] of [...this._ttls.entries()]) if (expiration > 0 && expiration < Date.now()) await this.handleExpired(key);
389
+ }
390
+ trackExpiration(key, ttlMs) {
391
+ if (ttlMs !== void 0 && ttlMs > 0) this._ttls.set(key, Date.now() + ttlMs);
392
+ else this._ttls.set(key, 0);
393
+ }
394
+ /**
395
+ * Resolve the TTL to milliseconds.
396
+ * @param {number | string | undefined} ttl
397
+ * @returns {number | undefined}
398
+ */
399
+ resolveTtl(ttl) {
400
+ const effectiveTtl = ttl ?? this._ttl;
401
+ if (effectiveTtl === void 0) return;
402
+ if (typeof effectiveTtl === "string") return shorthandToMilliseconds(effectiveTtl);
403
+ if (effectiveTtl === 0) return;
404
+ return effectiveTtl;
405
+ }
406
+ };
407
+ //#endregion
408
+ //#region src/index.ts
409
+ let NodeCacheErrors = /* @__PURE__ */ function(NodeCacheErrors) {
410
+ NodeCacheErrors["ECACHEFULL"] = "Cache max keys amount exceeded";
411
+ NodeCacheErrors["EKEYTYPE"] = "The key argument has to be of type `string` or `number`. Found: `__key`";
412
+ NodeCacheErrors["EKEYSTYPE"] = "The keys argument has to be an array.";
413
+ NodeCacheErrors["ETTLTYPE"] = "The ttl argument has to be a number or a string for shorthand ttl.";
414
+ return NodeCacheErrors;
415
+ }({});
416
+ var NodeCache = class extends Hookified {
417
+ options = {
418
+ stdTTL: 0,
419
+ checkperiod: 600,
420
+ useClones: true,
421
+ deleteOnExpire: true,
422
+ maxKeys: -1
423
+ };
424
+ store = /* @__PURE__ */ new Map();
425
+ _stats = new Stats({ enabled: true });
426
+ intervalId = 0;
427
+ constructor(options) {
428
+ super({ throwOnHookError: false });
429
+ if (options) this.options = {
430
+ ...this.options,
431
+ ...options
432
+ };
433
+ this.startInterval();
434
+ }
435
+ /**
436
+ * Sets a key value pair. It is possible to define a ttl (in seconds). Returns true on success.
437
+ *
438
+ * TTL behavior:
439
+ * - `ttl > 0`: cache expires after the given number of seconds
440
+ * - `ttl === 0`: cache indefinitely (overrides stdTTL)
441
+ * - `ttl < 0`: store the value but it expires immediately on next access (matches original node-cache behavior)
442
+ * - `ttl` omitted/undefined: use `stdTTL` from options (0 = unlimited if stdTTL is 0 or not set)
443
+ * - `ttl` as string: shorthand format like '1h', '30s', '5m', '2d'
444
+ *
445
+ * @param {string | number} key - it will convert the key to a string
446
+ * @param {T} value
447
+ * @param {number | string} [ttl] - TTL in seconds. 0 = unlimited, negative = expires immediately, string = shorthand format
448
+ * @returns {boolean} true on success
449
+ * @throws {Error} If the `key` or `ttl` is of an invalid type.
450
+ */
451
+ set(key, value, ttl) {
452
+ /* v8 ignore next -- @preserve */
453
+ if (typeof key !== "string" && typeof key !== "number") throw this.createError("The key argument has to be of type `string` or `number`. Found: `__key`", key);
454
+ /* v8 ignore next -- @preserve */
455
+ if (ttl !== void 0 && typeof ttl !== "number" && typeof ttl !== "string") throw this.createError("The ttl argument has to be a number or a string for shorthand ttl.", this.formatKey(key));
456
+ const keyValue = this.formatKey(key);
457
+ const existing = this.store.get(keyValue);
458
+ let expirationTimestamp = 0;
459
+ if (this.isNegativeTtl(ttl)) expirationTimestamp = Math.max(1, this.getExpirationTimestamp(typeof ttl === "string" ? Number(ttl) : ttl));
460
+ else if (ttl !== void 0 && (typeof ttl === "string" || ttl > 0)) expirationTimestamp = this.resolveExpiration(ttl);
461
+ else if (ttl === void 0 && this.options.stdTTL !== void 0 && this.options.stdTTL !== 0) expirationTimestamp = this.resolveExpiration(this.options.stdTTL);
462
+ /* v8 ignore next -- @preserve */
463
+ if (this.options.maxKeys) {
464
+ const { maxKeys } = this.options;
465
+ if (maxKeys > -1 && this.store.size >= maxKeys && !existing) throw this.createError("Cache max keys amount exceeded", this.formatKey(key));
466
+ }
467
+ this.store.set(keyValue, {
468
+ key: keyValue,
469
+ value,
470
+ ttl: expirationTimestamp
471
+ });
472
+ this.emit("set", keyValue, value, expirationTimestamp);
473
+ if (existing) {
474
+ this._stats.decreaseKSize(keyValue);
475
+ this._stats.decreaseVSize(existing.value);
476
+ }
477
+ this._stats.incrementKSize(keyValue);
478
+ this._stats.incrementVSize(value);
479
+ this._stats.setCount(this.store.size);
480
+ return true;
481
+ }
482
+ /**
483
+ * Sets multiple key val pairs. It is possible to define a ttl (seconds). Returns true on success.
484
+ *
485
+ * Each item follows the same TTL behavior as `set()`:
486
+ * - Positive TTL: expires after the given seconds
487
+ * - `0`: cache indefinitely
488
+ * - Negative TTL: stored but expires immediately on next access
489
+ * - Omitted: uses `stdTTL` from options
490
+ *
491
+ * @param {PartialNodeCacheItem<T>[]} data an array of key value pairs with optional ttl
492
+ * @returns {boolean} true on success
493
+ * @throws {Error} If `data` is not an array, or if any item has an invalid key or ttl type.
494
+ */
495
+ mset(data) {
496
+ /* v8 ignore next -- @preserve */
497
+ if (!Array.isArray(data)) throw this.createError("The keys argument has to be an array.");
498
+ for (const item of data) this.set(item.key, item.value, item.ttl);
499
+ return true;
500
+ }
501
+ /**
502
+ * Gets a saved value from the cache. Returns a undefined if not found or expired. If the value was found it returns the value.
503
+ * @param {string | number} key if the key is a number it will convert it to a string
504
+ * @returns {T} the value or undefined
505
+ */
506
+ get(key) {
507
+ const result = this.store.get(this.formatKey(key));
508
+ if (result) {
509
+ if (result.ttl > 0) {
510
+ if (result.ttl < Date.now()) {
511
+ this._stats.incrementMisses();
512
+ this.handleExpired(key, result);
513
+ return;
514
+ }
515
+ this._stats.incrementHits();
516
+ if (this.options.useClones) return this.clone(result.value);
517
+ return result.value;
518
+ }
519
+ this._stats.incrementHits();
520
+ if (this.options.useClones) return this.clone(result.value);
521
+ return result.value;
522
+ }
523
+ this._stats.incrementMisses();
524
+ }
525
+ /**
526
+ * Gets multiple saved values from the cache. Returns an empty object {} if not found or expired.
527
+ * If the value was found it returns an object with the key value pair.
528
+ * @param {Array<string | number} keys an array of keys
529
+ * @returns {Record<string, T | undefined>} an object with the key as a property and the value as the value
530
+ */
531
+ mget(keys) {
532
+ const result = Object.create(null);
533
+ for (const key of keys) {
534
+ const value = this.get(key);
535
+ /* v8 ignore next -- @preserve */
536
+ if (value) result[this.formatKey(key)] = value;
537
+ }
538
+ return result;
539
+ }
540
+ /**
541
+ * Get the cached value and remove the key from the cache. Equivalent to calling get(key) + del(key).
542
+ * Useful for implementing single use mechanism such as OTP, where once a value is read it will become obsolete.
543
+ * @param {string | number} key
544
+ * @returns {T | undefined} the value or undefined
545
+ */
546
+ take(key) {
547
+ const keyValue = this.formatKey(key);
548
+ const item = this.store.get(keyValue);
549
+ const exists = item ? !(item.ttl > 0 && item.ttl < Date.now()) : false;
550
+ const result = this.get(key);
551
+ if (exists) {
552
+ this.del(key);
553
+ if (this.options.useClones) return this.clone(result);
554
+ return result;
555
+ }
556
+ return result;
557
+ }
558
+ /**
559
+ * Delete a key. Returns the number of deleted entries. A delete will never fail.
560
+ * @param {string | number | Array<string | number>} key if the key is a number it will convert it to a string. if an array is passed it will delete all keys in the array.
561
+ * @returns {number} if it was successful it will return the count that was deleted
562
+ */
563
+ del(key) {
564
+ if (Array.isArray(key)) return this.mdel(key);
565
+ const result = this.store.get(this.formatKey(key));
566
+ if (result) {
567
+ const keyValue = this.formatKey(key);
568
+ this.store.delete(keyValue);
569
+ this.emit("del", keyValue, result.value);
570
+ this._stats.decreaseKSize(keyValue);
571
+ this._stats.decreaseVSize(result.value);
572
+ this._stats.setCount(this.store.size);
573
+ return 1;
574
+ }
575
+ return 0;
576
+ }
577
+ /**
578
+ * Delete all keys in Array that exist. Returns the number of deleted entries.
579
+ * @param {Array<string | number>} keys an array of keys
580
+ * @returns {number} the count of deleted keys
581
+ */
582
+ mdel(keys) {
583
+ let result = 0;
584
+ for (const key of keys) result += this.del(key);
585
+ return result;
586
+ }
587
+ /**
588
+ * Redefine the ttl of a key. Returns true if the key has been found and changed.
589
+ * Otherwise returns false. If the ttl-argument isn't passed the default-TTL will be used.
590
+ *
591
+ * TTL behavior:
592
+ * - `ttl > 0`: key expires after the given number of seconds
593
+ * - `ttl === 0`: key lives indefinitely (overrides stdTTL)
594
+ * - `ttl < 0`: key expires immediately on next access (matches original node-cache behavior)
595
+ * - `ttl` omitted/undefined: use `stdTTL` from options (0 = unlimited if stdTTL is 0 or not set)
596
+ * - `ttl` as string: shorthand format like '1h', '30s', '5m', '2d'
597
+ *
598
+ * @param {string | number} key if the key is a number it will convert it to a string
599
+ * @param {number | string} [ttl] TTL in seconds. 0 = unlimited, negative = expires immediately, string = shorthand format
600
+ * @returns {boolean} true if the key has been found and changed. Otherwise returns false.
601
+ * @throws {Error} If the `ttl` is of an invalid type (must be a number or string).
602
+ */
603
+ ttl(key, ttl) {
604
+ /* v8 ignore next -- @preserve */
605
+ if (ttl !== void 0 && typeof ttl !== "number" && typeof ttl !== "string") throw this.createError("The ttl argument has to be a number or a string for shorthand ttl.", this.formatKey(key));
606
+ const result = this.store.get(this.formatKey(key));
607
+ if (result) {
608
+ if (this.isNegativeTtl(ttl)) result.ttl = Math.max(1, this.getExpirationTimestamp(typeof ttl === "string" ? Number(ttl) : ttl));
609
+ else if (ttl !== void 0 && (typeof ttl === "string" || ttl > 0)) result.ttl = this.resolveExpiration(ttl);
610
+ else if (ttl === 0) result.ttl = 0;
611
+ else if (this.options.stdTTL !== void 0 && this.options.stdTTL !== 0) result.ttl = this.resolveExpiration(this.options.stdTTL);
612
+ else result.ttl = 0;
613
+ this.store.set(this.formatKey(key), result);
614
+ return true;
615
+ }
616
+ return false;
617
+ }
618
+ /**
619
+ * Receive the ttl of a key.
620
+ * @param {string | number} key if the key is a number it will convert it to a string
621
+ * @returns {number | undefined} 0 if this key has no ttl, undefined if this key is not in the cache,
622
+ * a timestamp in ms representing the time at which this key will expire
623
+ */
624
+ getTtl(key) {
625
+ const result = this.store.get(this.formatKey(key));
626
+ if (result) {
627
+ if (result.ttl === 0) return 0;
628
+ return result.ttl;
629
+ }
630
+ }
631
+ /**
632
+ * Returns an array of all existing keys. [ "all", "my", "keys", "foo", "bar" ]
633
+ * @returns {string[]} an array of all keys
634
+ */
635
+ keys() {
636
+ const result = [];
637
+ for (const key of this.store.keys()) result.push(key);
638
+ return result;
639
+ }
640
+ /**
641
+ * Returns boolean indicating if the key is cached. If the key has expired, it
642
+ * will return false and the key will be removed from the cache when
643
+ * `deleteOnExpire` is enabled (matches the original node-cache behavior).
644
+ * @param {string | number} key if the key is a number it will convert it to a string
645
+ * @returns {boolean} true if the key is cached and not expired
646
+ */
647
+ has(key) {
648
+ const result = this.store.get(this.formatKey(key));
649
+ if (!result) return false;
650
+ if (result.ttl > 0 && result.ttl < Date.now()) {
651
+ this.handleExpired(key, result);
652
+ return false;
653
+ }
654
+ return true;
655
+ }
656
+ /**
657
+ * Gets the stats of the cache
658
+ * @returns {NodeCacheStats} the stats of the cache
659
+ */
660
+ getStats() {
661
+ return {
662
+ keys: this._stats.count,
663
+ hits: this._stats.hits,
664
+ misses: this._stats.misses,
665
+ ksize: this._stats.ksize,
666
+ vsize: this._stats.vsize
667
+ };
668
+ }
669
+ /**
670
+ * Flush the whole data.
671
+ * @returns {void}
672
+ */
673
+ flushAll() {
674
+ this.store.clear();
675
+ this.flushStats();
676
+ this.emit("flush");
677
+ }
678
+ /**
679
+ * Flush the stats.
680
+ * @returns {void}
681
+ */
682
+ flushStats() {
683
+ this._stats = new Stats({ enabled: true });
684
+ this.emit("flush_stats");
685
+ }
686
+ /**
687
+ * Close the cache. This will clear the interval timeout which is set on check period option.
688
+ * @returns {void}
689
+ */
690
+ close() {
691
+ this.stopInterval();
692
+ }
693
+ /**
694
+ * Get the interval id
695
+ * @returns {number | NodeJS.Timeout} the interval id
696
+ */
697
+ getIntervalId() {
698
+ return this.intervalId;
699
+ }
700
+ startInterval() {
701
+ if (this.options.checkperiod && this.options.checkperiod > 0) {
702
+ const checkPeriodinSeconds = this.options.checkperiod * 1e3;
703
+ this.intervalId = setInterval(() => {
704
+ this.checkData();
705
+ }, checkPeriodinSeconds).unref();
706
+ return;
707
+ }
708
+ this.intervalId = 0;
709
+ }
710
+ stopInterval() {
711
+ if (this.intervalId !== 0) {
712
+ clearInterval(this.intervalId);
713
+ this.intervalId = 0;
714
+ }
715
+ }
716
+ formatKey(key) {
717
+ return key.toString();
718
+ }
719
+ clone(value) {
720
+ if (value === null || value === void 0) return value;
721
+ if (typeof value !== "object") return value;
722
+ return structuredClone(value);
723
+ }
724
+ getExpirationTimestamp(ttlInSeconds) {
725
+ if (typeof ttlInSeconds === "string") return shorthandToTime(ttlInSeconds);
726
+ return Date.now() + ttlInSeconds * 1e3;
727
+ }
728
+ /**
729
+ * Resolves a TTL value to an expiration timestamp, returning 0 (unlimited) if the
730
+ * resolved timestamp is not in the future (e.g. "0s" or a zero-duration string).
731
+ */
732
+ resolveExpiration(ttl) {
733
+ const timestamp = this.getExpirationTimestamp(ttl);
734
+ if (timestamp <= Date.now()) return 0;
735
+ return timestamp;
736
+ }
737
+ /**
738
+ * Checks whether a TTL value is negative. Handles both numbers and
739
+ * purely numeric strings (e.g. "-1").
740
+ */
741
+ isNegativeTtl(ttl) {
742
+ if (typeof ttl === "number") return ttl < 0;
743
+ if (typeof ttl === "string") {
744
+ const num = Number(ttl);
745
+ if (!Number.isNaN(num) && num < 0) return true;
746
+ }
747
+ return false;
748
+ }
749
+ checkData() {
750
+ for (const [key, value] of this.store.entries()) if (value.ttl > 0 && value.ttl < Date.now()) this.handleExpired(key, value);
751
+ }
752
+ /**
753
+ * Handles expiration for a cache entry. Deletes the entry when
754
+ * `deleteOnExpire` is enabled and emits the "expired" event.
755
+ */
756
+ handleExpired(key, entry) {
757
+ const keyValue = this.formatKey(key);
758
+ if (this.options.deleteOnExpire) this.del(key);
759
+ this.emit("expired", keyValue, entry.value);
760
+ }
761
+ createError(errorCode, key) {
762
+ let error = errorCode;
763
+ /* v8 ignore next -- @preserve */
764
+ if (key) error = error.replace("__key", key);
765
+ return new Error(error);
766
+ }
767
+ };
768
+ //#endregion
769
+ export { NodeCache, NodeCache as default, NodeCacheErrors, NodeCacheStore };