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