@cacheable/utils 2.1.0 → 2.3.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 +1,645 @@
1
- "use strict";var N=Object.create;var l=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty;var M=(t,e)=>{for(var r in e)l(t,r,{get:e[r],enumerable:!0})},p=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of H(e))!E.call(t,n)&&n!==r&&l(t,n,{get:()=>e[n],enumerable:!(i=A(e,n))||i.enumerable});return t};var F=(t,e,r)=>(r=t!=null?N(j(t)):{},p(e||!t||!t.__esModule?l(r,"default",{value:t,enumerable:!0}):r,t)),K=t=>p(l({},"__esModule",{value:!0}),t);var U={};M(U,{HashAlgorithm:()=>b,Stats:()=>m,calculateTtlFromExpiration:()=>C,coalesceAsync:()=>T,getCascadingTtl:()=>P,getTtlFromExpires:()=>d,hash:()=>f,hashToNumber:()=>v,isKeyvInstance:()=>z,isObject:()=>S,lessThan:()=>k,runIfFn:()=>w,shorthandToMilliseconds:()=>u,shorthandToTime:()=>g,sleep:()=>O});module.exports=K(U);var u=t=>{let e;if(t!==void 0){if(typeof t=="number")e=t;else if(typeof t=="string")if(t=t.trim(),Number.isNaN(Number(t))){let r=/^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(t);if(!r)throw new Error(`Unsupported time format: "${t}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`);let[,i,n]=r,s=Number.parseFloat(i);switch(n.toLowerCase()){case"ms":{e=s;break}case"s":{e=s*1e3;break}case"m":{e=s*1e3*60;break}case"h":{e=s*1e3*60*60;break}case"hr":{e=s*1e3*60*60;break}case"d":{e=s*1e3*60*60*24;break}default:e=Number(t)}}else e=Number(t);else throw new TypeError("Time must be a string or a number.");return e}},g=(t,e)=>{e??=new Date;let r=u(t);return r===void 0?e.getTime():e.getTime()+r};var a=new Map;function I(t){return a.has(t)}function D(t){a.set(t,[])}function J(t){a.delete(t)}function L(t,e){let r=y(t);r.push(e),a.set(t,r)}function y(t){return a.get(t)??[]}async function $(t){return new Promise((e,r)=>{L(t,{resolve:e,reject:r})})}function V(t){let e=y(t);return J(t),e}function _(t){let{key:e,error:r,result:i}=t;for(let n of V(e))r?n.reject(r):n.resolve(i)}async function T(t,e){if(!I(t)){D(t);try{let r=await Promise.resolve(e());return _({key:t,result:r}),r}catch(r){throw _({key:t,error:r}),r}}return $(t)}var c=F(require("crypto"),1),b=(n=>(n.SHA256="sha256",n.SHA512="sha512",n.MD5="md5",n.DJB2="djb2",n))(b||{});function f(t,e={algorithm:"sha256",serialize:JSON.stringify}){e?.algorithm||(e.algorithm="sha256"),e?.serialize||(e.serialize=JSON.stringify);let r=e.serialize(t);if(e?.algorithm==="djb2")return B(r);if(!c.getHashes().includes(e.algorithm))throw new Error(`Unsupported hash algorithm: '${e?.algorithm}'`);let i=c.createHash(e.algorithm);return i.update(r),i.digest("hex")}function v(t,e={min:0,max:10,algorithm:"sha256",serialize:JSON.stringify}){let r=e?.min??0,i=e?.max??10;if(r>=i)throw new Error(`Invalid range: min (${r}) must be less than max (${i})`);e?.algorithm||(e.algorithm="sha256"),e?.serialize||(e.serialize=JSON.stringify);let n=f(t,e),s=Number.parseInt(n,16),o=i-r+1,h=r+s%o;return h<r?r:h>i?i:h}function B(t){let e=5381;for(let r=0;r<t.length;r++)e=e*33^t.charCodeAt(r);return e.toString()}var x=require("keyv");function z(t){return t==null?!1:t instanceof x.Keyv?!0:["generateIterator","get","getMany","set","setMany","delete","deleteMany","has","hasMany","clear","disconnect","serialize","deserialize"].every(r=>typeof t[r]=="function")}function S(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function k(t,e){return typeof t=="number"&&typeof e=="number"?t<e:!1}function w(t,...e){return typeof t=="function"?t(...e):t}var O=async t=>new Promise(e=>setTimeout(e,t));var m=class{_hits=0;_misses=0;_gets=0;_sets=0;_deletes=0;_clears=0;_vsize=0;_ksize=0;_count=0;_enabled=!1;constructor(e){e?.enabled&&(this._enabled=e.enabled)}get enabled(){return this._enabled}set enabled(e){this._enabled=e}get hits(){return this._hits}get misses(){return this._misses}get gets(){return this._gets}get sets(){return this._sets}get deletes(){return this._deletes}get clears(){return this._clears}get vsize(){return this._vsize}get ksize(){return this._ksize}get count(){return this._count}incrementHits(){this._enabled&&this._hits++}incrementMisses(){this._enabled&&this._misses++}incrementGets(){this._enabled&&this._gets++}incrementSets(){this._enabled&&this._sets++}incrementDeletes(){this._enabled&&this._deletes++}incrementClears(){this._enabled&&this._clears++}incrementVSize(e){this._enabled&&(this._vsize+=this.roughSizeOfObject(e))}decreaseVSize(e){this._enabled&&(this._vsize-=this.roughSizeOfObject(e))}incrementKSize(e){this._enabled&&(this._ksize+=this.roughSizeOfString(e))}decreaseKSize(e){this._enabled&&(this._ksize-=this.roughSizeOfString(e))}incrementCount(){this._enabled&&this._count++}decreaseCount(){this._enabled&&this._count--}setCount(e){this._enabled&&(this._count=e)}roughSizeOfString(e){return e.length*2}roughSizeOfObject(e){let r=[],i=[e],n=0;for(;i.length>0;){let s=i.pop();if(typeof s=="boolean")n+=4;else if(typeof s=="string")n+=s.length*2;else if(typeof s=="number")n+=8;else if(typeof s=="object"&&s!==null&&!r.includes(s)){r.push(s);for(let o in s)n+=o.length*2,i.push(s[o])}}return n}reset(){this._hits=0,this._misses=0,this._gets=0,this._sets=0,this._deletes=0,this._clears=0,this._vsize=0,this._ksize=0,this._count=0}resetStoreValues(){this._vsize=0,this._ksize=0,this._count=0}};function d(t){if(t==null)return;let e=Date.now();if(!(t<e))return t-e}function P(t,e,r){return r??e??u(t)}function C(t,e){let r=d(e),i=t?Date.now()+t:void 0;return r===void 0?t:i===void 0?r:e&&e>i?t:r}0&&(module.exports={HashAlgorithm,Stats,calculateTtlFromExpiration,coalesceAsync,getCascadingTtl,getTtlFromExpires,hash,hashToNumber,isKeyvInstance,isObject,lessThan,runIfFn,shorthandToMilliseconds,shorthandToTime,sleep});
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ HashAlgorithm: () => HashAlgorithm,
24
+ Stats: () => Stats,
25
+ calculateTtlFromExpiration: () => calculateTtlFromExpiration,
26
+ coalesceAsync: () => coalesceAsync,
27
+ createWrapKey: () => createWrapKey,
28
+ getCascadingTtl: () => getCascadingTtl,
29
+ getOrSet: () => getOrSet,
30
+ getTtlFromExpires: () => getTtlFromExpires,
31
+ hash: () => hash,
32
+ hashSync: () => hashSync,
33
+ hashToNumber: () => hashToNumber,
34
+ hashToNumberSync: () => hashToNumberSync,
35
+ isKeyvInstance: () => isKeyvInstance,
36
+ isObject: () => isObject,
37
+ lessThan: () => lessThan,
38
+ runIfFn: () => runIfFn,
39
+ shorthandToMilliseconds: () => shorthandToMilliseconds,
40
+ shorthandToTime: () => shorthandToTime,
41
+ sleep: () => sleep,
42
+ wrap: () => wrap,
43
+ wrapSync: () => wrapSync
44
+ });
45
+ module.exports = __toCommonJS(index_exports);
46
+
47
+ // src/shorthand-time.ts
48
+ var shorthandToMilliseconds = (shorthand) => {
49
+ let milliseconds;
50
+ if (shorthand === void 0) {
51
+ return void 0;
52
+ }
53
+ if (typeof shorthand === "number") {
54
+ milliseconds = shorthand;
55
+ } else {
56
+ if (typeof shorthand !== "string") {
57
+ return void 0;
58
+ }
59
+ shorthand = shorthand.trim();
60
+ if (Number.isNaN(Number(shorthand))) {
61
+ const match = /^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(shorthand);
62
+ if (!match) {
63
+ throw new Error(
64
+ `Unsupported time format: "${shorthand}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`
65
+ );
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
+ /* v8 ignore next -- @preserve */
96
+ default: {
97
+ milliseconds = Number(shorthand);
98
+ }
99
+ }
100
+ } else {
101
+ milliseconds = Number(shorthand);
102
+ }
103
+ }
104
+ return milliseconds;
105
+ };
106
+ var shorthandToTime = (shorthand, fromDate) => {
107
+ fromDate ??= /* @__PURE__ */ new Date();
108
+ const milliseconds = shorthandToMilliseconds(shorthand);
109
+ if (milliseconds === void 0) {
110
+ return fromDate.getTime();
111
+ }
112
+ return fromDate.getTime() + milliseconds;
113
+ };
114
+
115
+ // src/coalesce-async.ts
116
+ var callbacks = /* @__PURE__ */ new Map();
117
+ function hasKey(key) {
118
+ return callbacks.has(key);
119
+ }
120
+ function addKey(key) {
121
+ callbacks.set(key, []);
122
+ }
123
+ function removeKey(key) {
124
+ callbacks.delete(key);
125
+ }
126
+ function addCallbackToKey(key, callback) {
127
+ const stash = getCallbacksByKey(key);
128
+ stash.push(callback);
129
+ callbacks.set(key, stash);
130
+ }
131
+ function getCallbacksByKey(key) {
132
+ return callbacks.get(key) ?? [];
133
+ }
134
+ async function enqueue(key) {
135
+ return new Promise((resolve, reject) => {
136
+ const callback = { resolve, reject };
137
+ addCallbackToKey(key, callback);
138
+ });
139
+ }
140
+ function dequeue(key) {
141
+ const stash = getCallbacksByKey(key);
142
+ removeKey(key);
143
+ return stash;
144
+ }
145
+ function coalesce(options) {
146
+ const { key, error, result } = options;
147
+ for (const callback of dequeue(key)) {
148
+ if (error) {
149
+ callback.reject(error);
150
+ } else {
151
+ callback.resolve(result);
152
+ }
153
+ }
154
+ }
155
+ async function coalesceAsync(key, fnc) {
156
+ if (!hasKey(key)) {
157
+ addKey(key);
158
+ try {
159
+ const result = await Promise.resolve(fnc());
160
+ coalesce({ key, result });
161
+ return result;
162
+ } catch (error) {
163
+ coalesce({ key, error });
164
+ throw error;
165
+ }
166
+ }
167
+ return enqueue(key);
168
+ }
169
+
170
+ // src/hash.ts
171
+ var import_hashery = require("hashery");
172
+ var HashAlgorithm = /* @__PURE__ */ ((HashAlgorithm2) => {
173
+ HashAlgorithm2["SHA256"] = "SHA-256";
174
+ HashAlgorithm2["SHA384"] = "SHA-384";
175
+ HashAlgorithm2["SHA512"] = "SHA-512";
176
+ HashAlgorithm2["DJB2"] = "djb2";
177
+ HashAlgorithm2["FNV1"] = "fnv1";
178
+ HashAlgorithm2["MURMER"] = "murmer";
179
+ HashAlgorithm2["CRC32"] = "crc32";
180
+ return HashAlgorithm2;
181
+ })(HashAlgorithm || {});
182
+ async function hash(object, options = {
183
+ algorithm: "SHA-256" /* SHA256 */,
184
+ serialize: JSON.stringify
185
+ }) {
186
+ const algorithm = options?.algorithm ?? "SHA-256" /* SHA256 */;
187
+ const serialize = options?.serialize ?? JSON.stringify;
188
+ const objectString = serialize(object);
189
+ const hashery = new import_hashery.Hashery();
190
+ return hashery.toHash(objectString, { algorithm });
191
+ }
192
+ function hashSync(object, options = {
193
+ algorithm: "djb2" /* DJB2 */,
194
+ serialize: JSON.stringify
195
+ }) {
196
+ const algorithm = options?.algorithm ?? "djb2" /* DJB2 */;
197
+ const serialize = options?.serialize ?? JSON.stringify;
198
+ const objectString = serialize(object);
199
+ const hashery = new import_hashery.Hashery();
200
+ return hashery.toHashSync(objectString, { algorithm });
201
+ }
202
+ async function hashToNumber(object, options = {
203
+ min: 0,
204
+ max: 10,
205
+ algorithm: "SHA-256" /* SHA256 */,
206
+ serialize: JSON.stringify
207
+ }) {
208
+ const min = options?.min ?? 0;
209
+ const max = options?.max ?? 10;
210
+ const algorithm = options?.algorithm ?? "SHA-256" /* SHA256 */;
211
+ const serialize = options?.serialize ?? JSON.stringify;
212
+ const hashLength = options?.hashLength ?? 16;
213
+ if (min >= max) {
214
+ throw new Error(
215
+ `Invalid range: min (${min}) must be less than max (${max})`
216
+ );
217
+ }
218
+ const objectString = serialize(object);
219
+ const hashery = new import_hashery.Hashery();
220
+ return hashery.toNumber(objectString, {
221
+ algorithm,
222
+ min,
223
+ max,
224
+ hashLength
225
+ });
226
+ }
227
+ function hashToNumberSync(object, options = {
228
+ min: 0,
229
+ max: 10,
230
+ algorithm: "djb2" /* DJB2 */,
231
+ serialize: JSON.stringify
232
+ }) {
233
+ const min = options?.min ?? 0;
234
+ const max = options?.max ?? 10;
235
+ const algorithm = options?.algorithm ?? "djb2" /* DJB2 */;
236
+ const serialize = options?.serialize ?? JSON.stringify;
237
+ const hashLength = options?.hashLength ?? 16;
238
+ if (min >= max) {
239
+ throw new Error(
240
+ `Invalid range: min (${min}) must be less than max (${max})`
241
+ );
242
+ }
243
+ const objectString = serialize(object);
244
+ const hashery = new import_hashery.Hashery();
245
+ return hashery.toNumberSync(objectString, {
246
+ algorithm,
247
+ min,
248
+ max,
249
+ hashLength
250
+ });
251
+ }
252
+
253
+ // src/is-keyv-instance.ts
254
+ var import_keyv = require("keyv");
255
+ function isKeyvInstance(keyv) {
256
+ if (keyv === null || keyv === void 0) {
257
+ return false;
258
+ }
259
+ if (keyv instanceof import_keyv.Keyv) {
260
+ return true;
261
+ }
262
+ const keyvMethods = [
263
+ "generateIterator",
264
+ "get",
265
+ "getMany",
266
+ "set",
267
+ "setMany",
268
+ "delete",
269
+ "deleteMany",
270
+ "has",
271
+ "hasMany",
272
+ "clear",
273
+ "disconnect",
274
+ "serialize",
275
+ "deserialize"
276
+ ];
277
+ return keyvMethods.every((method) => typeof keyv[method] === "function");
278
+ }
279
+
280
+ // src/is-object.ts
281
+ function isObject(value) {
282
+ return value !== null && typeof value === "object" && !Array.isArray(value);
283
+ }
284
+
285
+ // src/less-than.ts
286
+ function lessThan(number1, number2) {
287
+ return typeof number1 === "number" && typeof number2 === "number" ? number1 < number2 : false;
288
+ }
289
+
290
+ // src/memoize.ts
291
+ function wrapSync(function_, options) {
292
+ const { ttl, keyPrefix, cache, serialize } = options;
293
+ return (...arguments_) => {
294
+ let cacheKey = createWrapKey(function_, arguments_, {
295
+ keyPrefix,
296
+ serialize
297
+ });
298
+ if (options.createKey) {
299
+ cacheKey = options.createKey(function_, arguments_, options);
300
+ }
301
+ let value = cache.get(cacheKey);
302
+ if (value === void 0) {
303
+ try {
304
+ value = function_(...arguments_);
305
+ cache.set(cacheKey, value, ttl);
306
+ } catch (error) {
307
+ cache.emit("error", error);
308
+ if (options.cacheErrors) {
309
+ cache.set(cacheKey, error, ttl);
310
+ }
311
+ }
312
+ }
313
+ return value;
314
+ };
315
+ }
316
+ async function getOrSet(key, function_, options) {
317
+ const keyString = typeof key === "function" ? key(options) : key;
318
+ let value = await options.cache.get(keyString);
319
+ if (value === void 0) {
320
+ const cacheId = options.cacheId ?? "default";
321
+ const coalesceKey = `${cacheId}::${keyString}`;
322
+ value = await coalesceAsync(coalesceKey, async () => {
323
+ try {
324
+ const result = await function_();
325
+ await options.cache.set(keyString, result, options.ttl);
326
+ return result;
327
+ } catch (error) {
328
+ options.cache.emit("error", error);
329
+ if (options.cacheErrors) {
330
+ await options.cache.set(keyString, error, options.ttl);
331
+ }
332
+ if (options.throwErrors) {
333
+ throw error;
334
+ }
335
+ }
336
+ });
337
+ }
338
+ return value;
339
+ }
340
+ function wrap(function_, options) {
341
+ const { keyPrefix, serialize } = options;
342
+ return async (...arguments_) => {
343
+ let cacheKey = createWrapKey(function_, arguments_, {
344
+ keyPrefix,
345
+ serialize
346
+ });
347
+ if (options.createKey) {
348
+ cacheKey = options.createKey(function_, arguments_, options);
349
+ }
350
+ return getOrSet(
351
+ cacheKey,
352
+ async () => function_(...arguments_),
353
+ options
354
+ );
355
+ };
356
+ }
357
+ function createWrapKey(function_, arguments_, options) {
358
+ const { keyPrefix, serialize } = options || {};
359
+ if (!keyPrefix) {
360
+ return `${function_.name}::${hashSync(arguments_, { serialize })}`;
361
+ }
362
+ return `${keyPrefix}::${function_.name}::${hashSync(arguments_, { serialize })}`;
363
+ }
364
+
365
+ // src/run-if-fn.ts
366
+ function runIfFn(valueOrFunction, ...arguments_) {
367
+ return typeof valueOrFunction === "function" ? valueOrFunction(...arguments_) : valueOrFunction;
368
+ }
369
+
370
+ // src/sleep.ts
371
+ var sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
372
+
373
+ // src/stats.ts
374
+ var Stats = class {
375
+ _hits = 0;
376
+ _misses = 0;
377
+ _gets = 0;
378
+ _sets = 0;
379
+ _deletes = 0;
380
+ _clears = 0;
381
+ _vsize = 0;
382
+ _ksize = 0;
383
+ _count = 0;
384
+ _enabled = false;
385
+ constructor(options) {
386
+ if (options?.enabled) {
387
+ this._enabled = options.enabled;
388
+ }
389
+ }
390
+ /**
391
+ * @returns {boolean} - Whether the stats are enabled
392
+ */
393
+ get enabled() {
394
+ return this._enabled;
395
+ }
396
+ /**
397
+ * @param {boolean} enabled - Whether to enable the stats
398
+ */
399
+ set enabled(enabled) {
400
+ this._enabled = enabled;
401
+ }
402
+ /**
403
+ * @returns {number} - The number of hits
404
+ * @readonly
405
+ */
406
+ get hits() {
407
+ return this._hits;
408
+ }
409
+ /**
410
+ * @returns {number} - The number of misses
411
+ * @readonly
412
+ */
413
+ get misses() {
414
+ return this._misses;
415
+ }
416
+ /**
417
+ * @returns {number} - The number of gets
418
+ * @readonly
419
+ */
420
+ get gets() {
421
+ return this._gets;
422
+ }
423
+ /**
424
+ * @returns {number} - The number of sets
425
+ * @readonly
426
+ */
427
+ get sets() {
428
+ return this._sets;
429
+ }
430
+ /**
431
+ * @returns {number} - The number of deletes
432
+ * @readonly
433
+ */
434
+ get deletes() {
435
+ return this._deletes;
436
+ }
437
+ /**
438
+ * @returns {number} - The number of clears
439
+ * @readonly
440
+ */
441
+ get clears() {
442
+ return this._clears;
443
+ }
444
+ /**
445
+ * @returns {number} - The vsize (value size) of the cache instance
446
+ * @readonly
447
+ */
448
+ get vsize() {
449
+ return this._vsize;
450
+ }
451
+ /**
452
+ * @returns {number} - The ksize (key size) of the cache instance
453
+ * @readonly
454
+ */
455
+ get ksize() {
456
+ return this._ksize;
457
+ }
458
+ /**
459
+ * @returns {number} - The count of the cache instance
460
+ * @readonly
461
+ */
462
+ get count() {
463
+ return this._count;
464
+ }
465
+ incrementHits() {
466
+ if (!this._enabled) {
467
+ return;
468
+ }
469
+ this._hits++;
470
+ }
471
+ incrementMisses() {
472
+ if (!this._enabled) {
473
+ return;
474
+ }
475
+ this._misses++;
476
+ }
477
+ incrementGets() {
478
+ if (!this._enabled) {
479
+ return;
480
+ }
481
+ this._gets++;
482
+ }
483
+ incrementSets() {
484
+ if (!this._enabled) {
485
+ return;
486
+ }
487
+ this._sets++;
488
+ }
489
+ incrementDeletes() {
490
+ if (!this._enabled) {
491
+ return;
492
+ }
493
+ this._deletes++;
494
+ }
495
+ incrementClears() {
496
+ if (!this._enabled) {
497
+ return;
498
+ }
499
+ this._clears++;
500
+ }
501
+ incrementVSize(value) {
502
+ if (!this._enabled) {
503
+ return;
504
+ }
505
+ this._vsize += this.roughSizeOfObject(value);
506
+ }
507
+ decreaseVSize(value) {
508
+ if (!this._enabled) {
509
+ return;
510
+ }
511
+ this._vsize -= this.roughSizeOfObject(value);
512
+ }
513
+ incrementKSize(key) {
514
+ if (!this._enabled) {
515
+ return;
516
+ }
517
+ this._ksize += this.roughSizeOfString(key);
518
+ }
519
+ decreaseKSize(key) {
520
+ if (!this._enabled) {
521
+ return;
522
+ }
523
+ this._ksize -= this.roughSizeOfString(key);
524
+ }
525
+ incrementCount() {
526
+ if (!this._enabled) {
527
+ return;
528
+ }
529
+ this._count++;
530
+ }
531
+ decreaseCount() {
532
+ if (!this._enabled) {
533
+ return;
534
+ }
535
+ this._count--;
536
+ }
537
+ setCount(count) {
538
+ if (!this._enabled) {
539
+ return;
540
+ }
541
+ this._count = count;
542
+ }
543
+ roughSizeOfString(value) {
544
+ return value.length * 2;
545
+ }
546
+ roughSizeOfObject(object) {
547
+ const objectList = [];
548
+ const stack = [object];
549
+ let bytes = 0;
550
+ while (stack.length > 0) {
551
+ const value = stack.pop();
552
+ if (typeof value === "boolean") {
553
+ bytes += 4;
554
+ } else if (typeof value === "string") {
555
+ bytes += value.length * 2;
556
+ } else if (typeof value === "number") {
557
+ bytes += 8;
558
+ } else {
559
+ if (value === null || value === void 0) {
560
+ bytes += 4;
561
+ continue;
562
+ }
563
+ if (objectList.includes(value)) {
564
+ continue;
565
+ }
566
+ objectList.push(value);
567
+ for (const key in value) {
568
+ bytes += key.length * 2;
569
+ stack.push(value[key]);
570
+ }
571
+ }
572
+ }
573
+ return bytes;
574
+ }
575
+ reset() {
576
+ this._hits = 0;
577
+ this._misses = 0;
578
+ this._gets = 0;
579
+ this._sets = 0;
580
+ this._deletes = 0;
581
+ this._clears = 0;
582
+ this._vsize = 0;
583
+ this._ksize = 0;
584
+ this._count = 0;
585
+ }
586
+ resetStoreValues() {
587
+ this._vsize = 0;
588
+ this._ksize = 0;
589
+ this._count = 0;
590
+ }
591
+ };
592
+
593
+ // src/ttl.ts
594
+ function getTtlFromExpires(expires) {
595
+ if (expires === void 0 || expires === null) {
596
+ return void 0;
597
+ }
598
+ const now = Date.now();
599
+ if (expires < now) {
600
+ return void 0;
601
+ }
602
+ return expires - now;
603
+ }
604
+ function getCascadingTtl(cacheableTtl, primaryTtl, secondaryTtl) {
605
+ return secondaryTtl ?? primaryTtl ?? shorthandToMilliseconds(cacheableTtl);
606
+ }
607
+ function calculateTtlFromExpiration(ttl, expires) {
608
+ const ttlFromExpires = getTtlFromExpires(expires);
609
+ const expiresFromTtl = ttl ? Date.now() + ttl : void 0;
610
+ if (ttlFromExpires === void 0) {
611
+ return ttl;
612
+ }
613
+ if (expiresFromTtl === void 0) {
614
+ return ttlFromExpires;
615
+ }
616
+ if (expires && expires > expiresFromTtl) {
617
+ return ttl;
618
+ }
619
+ return ttlFromExpires;
620
+ }
621
+ // Annotate the CommonJS export names for ESM import in node:
622
+ 0 && (module.exports = {
623
+ HashAlgorithm,
624
+ Stats,
625
+ calculateTtlFromExpiration,
626
+ coalesceAsync,
627
+ createWrapKey,
628
+ getCascadingTtl,
629
+ getOrSet,
630
+ getTtlFromExpires,
631
+ hash,
632
+ hashSync,
633
+ hashToNumber,
634
+ hashToNumberSync,
635
+ isKeyvInstance,
636
+ isObject,
637
+ lessThan,
638
+ runIfFn,
639
+ shorthandToMilliseconds,
640
+ shorthandToTime,
641
+ sleep,
642
+ wrap,
643
+ wrapSync
644
+ });
645
+ /* v8 ignore next -- @preserve */