@cacheable/utils 2.0.3 → 2.2.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.d.ts CHANGED
@@ -88,10 +88,63 @@ type hashToNumberOptions = HashOptions & {
88
88
  declare function hash(object: any, options?: HashOptions): string;
89
89
  declare function hashToNumber(object: any, options?: hashToNumberOptions): number;
90
90
 
91
+ declare function isKeyvInstance(keyv: any): boolean;
92
+
91
93
  declare function isObject<T = Record<string, unknown>>(value: unknown): value is T;
92
94
 
93
95
  declare function lessThan(number1?: number, number2?: number): boolean;
94
96
 
97
+ type CacheInstance = {
98
+ get: (key: string) => Promise<any | undefined>;
99
+ has: (key: string) => Promise<boolean>;
100
+ set: (key: string, value: any, ttl?: number | string) => Promise<void>;
101
+ on: (event: string, listener: (...args: any[]) => void) => void;
102
+ emit: (event: string, ...args: any[]) => boolean;
103
+ };
104
+ type CacheSyncInstance = {
105
+ get: (key: string) => any | undefined;
106
+ has: (key: string) => boolean;
107
+ set: (key: string, value: any, ttl?: number | string) => void;
108
+ on: (event: string, listener: (...args: any[]) => void) => void;
109
+ emit: (event: string, ...args: any[]) => boolean;
110
+ };
111
+ type GetOrSetKey = string | ((options?: GetOrSetOptions) => string);
112
+ type GetOrSetFunctionOptions = {
113
+ ttl?: number | string;
114
+ cacheErrors?: boolean;
115
+ throwErrors?: boolean;
116
+ };
117
+ type GetOrSetOptions = GetOrSetFunctionOptions & {
118
+ cacheId?: string;
119
+ cache: CacheInstance;
120
+ };
121
+ type CreateWrapKey = (function_: AnyFunction, arguments_: any[], options?: WrapFunctionOptions) => string;
122
+ type WrapFunctionOptions = {
123
+ ttl?: number | string;
124
+ keyPrefix?: string;
125
+ createKey?: CreateWrapKey;
126
+ cacheErrors?: boolean;
127
+ cacheId?: string;
128
+ serialize?: (object: any) => string;
129
+ };
130
+ type WrapOptions = WrapFunctionOptions & {
131
+ cache: CacheInstance;
132
+ serialize?: (object: any) => string;
133
+ };
134
+ type WrapSyncOptions = WrapFunctionOptions & {
135
+ cache: CacheSyncInstance;
136
+ serialize?: (object: any) => string;
137
+ };
138
+ type AnyFunction = (...arguments_: any[]) => any;
139
+ declare function wrapSync<T>(function_: AnyFunction, options: WrapSyncOptions): AnyFunction;
140
+ declare function getOrSet<T>(key: GetOrSetKey, function_: () => Promise<T>, options: GetOrSetOptions): Promise<T | undefined>;
141
+ declare function wrap<T>(function_: AnyFunction, options: WrapOptions): AnyFunction;
142
+ type CreateWrapKeyOptions = {
143
+ keyPrefix?: string;
144
+ serialize?: (object: any) => string;
145
+ };
146
+ declare function createWrapKey(function_: AnyFunction, arguments_: any[], options?: CreateWrapKeyOptions): string;
147
+
95
148
  type Function_<P, T> = (...arguments_: P[]) => T;
96
149
  declare function runIfFn<T, P>(valueOrFunction: T | Function_<P, T>, ...arguments_: P[]): T;
97
150
 
@@ -207,4 +260,4 @@ declare function getCascadingTtl(cacheableTtl?: number | string, primaryTtl?: nu
207
260
  */
208
261
  declare function calculateTtlFromExpiration(ttl: number | undefined, expires: number | undefined): number | undefined;
209
262
 
210
- export { type CacheableItem, type CacheableStoreItem, HashAlgorithm, Stats, type StatsOptions, calculateTtlFromExpiration, coalesceAsync, getCascadingTtl, getTtlFromExpires, hash, hashToNumber, isObject, lessThan, runIfFn, shorthandToMilliseconds, shorthandToTime, sleep };
263
+ export { type AnyFunction, type CacheInstance, type CacheSyncInstance, type CacheableItem, type CacheableStoreItem, type CreateWrapKey, type CreateWrapKeyOptions, type GetOrSetFunctionOptions, type GetOrSetKey, type GetOrSetOptions, HashAlgorithm, Stats, type StatsOptions, type WrapFunctionOptions, type WrapOptions, type WrapSyncOptions, calculateTtlFromExpiration, coalesceAsync, createWrapKey, getCascadingTtl, getOrSet, getTtlFromExpires, hash, hashToNumber, isKeyvInstance, isObject, lessThan, runIfFn, shorthandToMilliseconds, shorthandToTime, sleep, wrap, wrapSync };
package/dist/index.js CHANGED
@@ -1 +1,582 @@
1
- var a=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,s]=r,n=Number.parseFloat(i);switch(s.toLowerCase()){case"ms":{e=n;break}case"s":{e=n*1e3;break}case"m":{e=n*1e3*60;break}case"h":{e=n*1e3*60*60;break}case"hr":{e=n*1e3*60*60;break}case"d":{e=n*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=a(t);return r===void 0?e.getTime():e.getTime()+r};var u=new Map;function _(t){return u.has(t)}function T(t){u.set(t,[])}function y(t){u.delete(t)}function v(t,e){let r=b(t);r.push(e),u.set(t,r)}function b(t){return u.get(t)??[]}async function x(t){return new Promise((e,r)=>{v(t,{resolve:e,reject:r})})}function z(t){let e=b(t);return y(t),e}function h(t){let{key:e,error:r,result:i}=t;for(let s of z(e))r?s.reject(r):s.resolve(i)}async function S(t,e){if(!_(t)){T(t);try{let r=await Promise.resolve(e());return h({key:t,result:r}),r}catch(r){throw h({key:t,error:r}),r}}return x(t)}import*as l from"crypto";var f=(s=>(s.SHA256="sha256",s.SHA512="sha512",s.MD5="md5",s.DJB2="djb2",s))(f||{});function d(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 w(r);if(!l.getHashes().includes(e.algorithm))throw new Error(`Unsupported hash algorithm: '${e?.algorithm}'`);let i=l.createHash(e.algorithm);return i.update(r),i.digest("hex")}function k(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 s=d(t,e),n=Number.parseInt(s,16),o=i-r+1,c=r+n%o;return c<r?r:c>i?i:c}function w(t){let e=5381;for(let r=0;r<t.length;r++)e=e*33^t.charCodeAt(r);return e.toString()}function O(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function P(t,e){return typeof t=="number"&&typeof e=="number"?t<e:!1}function C(t,...e){return typeof t=="function"?t(...e):t}var N=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],s=0;for(;i.length>0;){let n=i.pop();if(typeof n=="boolean")s+=4;else if(typeof n=="string")s+=n.length*2;else if(typeof n=="number")s+=8;else if(typeof n=="object"&&n!==null&&!r.includes(n)){r.push(n);for(let o in n)s+=o.length*2,i.push(n[o])}}return s}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 p(t){if(t==null)return;let e=Date.now();if(!(t<e))return t-e}function A(t,e,r){return r??e??a(t)}function H(t,e){let r=p(e),i=t?Date.now()+t:void 0;return r===void 0?t:i===void 0?r:e&&e>i?t:r}export{f as HashAlgorithm,m as Stats,H as calculateTtlFromExpiration,S as coalesceAsync,A as getCascadingTtl,p as getTtlFromExpires,d as hash,k as hashToNumber,O as isObject,P as lessThan,C as runIfFn,a as shorthandToMilliseconds,g as shorthandToTime,N as sleep};
1
+ // src/shorthand-time.ts
2
+ var shorthandToMilliseconds = (shorthand) => {
3
+ let milliseconds;
4
+ if (shorthand === void 0) {
5
+ return void 0;
6
+ }
7
+ if (typeof shorthand === "number") {
8
+ milliseconds = shorthand;
9
+ } else {
10
+ if (typeof shorthand !== "string") {
11
+ return void 0;
12
+ }
13
+ shorthand = shorthand.trim();
14
+ if (Number.isNaN(Number(shorthand))) {
15
+ const match = /^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(shorthand);
16
+ if (!match) {
17
+ throw new Error(
18
+ `Unsupported time format: "${shorthand}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`
19
+ );
20
+ }
21
+ const [, value, unit] = match;
22
+ const numericValue = Number.parseFloat(value);
23
+ const unitLower = unit.toLowerCase();
24
+ switch (unitLower) {
25
+ case "ms": {
26
+ milliseconds = numericValue;
27
+ break;
28
+ }
29
+ case "s": {
30
+ milliseconds = numericValue * 1e3;
31
+ break;
32
+ }
33
+ case "m": {
34
+ milliseconds = numericValue * 1e3 * 60;
35
+ break;
36
+ }
37
+ case "h": {
38
+ milliseconds = numericValue * 1e3 * 60 * 60;
39
+ break;
40
+ }
41
+ case "hr": {
42
+ milliseconds = numericValue * 1e3 * 60 * 60;
43
+ break;
44
+ }
45
+ case "d": {
46
+ milliseconds = numericValue * 1e3 * 60 * 60 * 24;
47
+ break;
48
+ }
49
+ /* v8 ignore next -- @preserve */
50
+ default: {
51
+ milliseconds = Number(shorthand);
52
+ }
53
+ }
54
+ } else {
55
+ milliseconds = Number(shorthand);
56
+ }
57
+ }
58
+ return milliseconds;
59
+ };
60
+ var shorthandToTime = (shorthand, fromDate) => {
61
+ fromDate ??= /* @__PURE__ */ new Date();
62
+ const milliseconds = shorthandToMilliseconds(shorthand);
63
+ if (milliseconds === void 0) {
64
+ return fromDate.getTime();
65
+ }
66
+ return fromDate.getTime() + milliseconds;
67
+ };
68
+
69
+ // src/coalesce-async.ts
70
+ var callbacks = /* @__PURE__ */ new Map();
71
+ function hasKey(key) {
72
+ return callbacks.has(key);
73
+ }
74
+ function addKey(key) {
75
+ callbacks.set(key, []);
76
+ }
77
+ function removeKey(key) {
78
+ callbacks.delete(key);
79
+ }
80
+ function addCallbackToKey(key, callback) {
81
+ const stash = getCallbacksByKey(key);
82
+ stash.push(callback);
83
+ callbacks.set(key, stash);
84
+ }
85
+ function getCallbacksByKey(key) {
86
+ return callbacks.get(key) ?? [];
87
+ }
88
+ async function enqueue(key) {
89
+ return new Promise((resolve, reject) => {
90
+ const callback = { resolve, reject };
91
+ addCallbackToKey(key, callback);
92
+ });
93
+ }
94
+ function dequeue(key) {
95
+ const stash = getCallbacksByKey(key);
96
+ removeKey(key);
97
+ return stash;
98
+ }
99
+ function coalesce(options) {
100
+ const { key, error, result } = options;
101
+ for (const callback of dequeue(key)) {
102
+ if (error) {
103
+ callback.reject(error);
104
+ } else {
105
+ callback.resolve(result);
106
+ }
107
+ }
108
+ }
109
+ async function coalesceAsync(key, fnc) {
110
+ if (!hasKey(key)) {
111
+ addKey(key);
112
+ try {
113
+ const result = await Promise.resolve(fnc());
114
+ coalesce({ key, result });
115
+ return result;
116
+ } catch (error) {
117
+ coalesce({ key, error });
118
+ throw error;
119
+ }
120
+ }
121
+ return enqueue(key);
122
+ }
123
+
124
+ // src/hash.ts
125
+ import * as crypto from "crypto";
126
+ var HashAlgorithm = /* @__PURE__ */ ((HashAlgorithm2) => {
127
+ HashAlgorithm2["SHA256"] = "sha256";
128
+ HashAlgorithm2["SHA512"] = "sha512";
129
+ HashAlgorithm2["MD5"] = "md5";
130
+ HashAlgorithm2["DJB2"] = "djb2";
131
+ return HashAlgorithm2;
132
+ })(HashAlgorithm || {});
133
+ function hash(object, options = {
134
+ algorithm: "sha256" /* SHA256 */,
135
+ serialize: JSON.stringify
136
+ }) {
137
+ if (!options?.algorithm) {
138
+ options.algorithm = "sha256" /* SHA256 */;
139
+ }
140
+ if (!options?.serialize) {
141
+ options.serialize = JSON.stringify;
142
+ }
143
+ const objectString = options.serialize(object);
144
+ if (options?.algorithm === "djb2" /* DJB2 */) {
145
+ return djb2Hash(objectString);
146
+ }
147
+ if (!crypto.getHashes().includes(options.algorithm)) {
148
+ throw new Error(`Unsupported hash algorithm: '${options?.algorithm}'`);
149
+ }
150
+ const hasher = crypto.createHash(options.algorithm);
151
+ hasher.update(objectString);
152
+ return hasher.digest("hex");
153
+ }
154
+ function hashToNumber(object, options = {
155
+ min: 0,
156
+ max: 10,
157
+ algorithm: "sha256" /* SHA256 */,
158
+ serialize: JSON.stringify
159
+ }) {
160
+ const min = options?.min ?? 0;
161
+ const max = options?.max ?? 10;
162
+ if (min >= max) {
163
+ throw new Error(
164
+ `Invalid range: min (${min}) must be less than max (${max})`
165
+ );
166
+ }
167
+ if (!options?.algorithm) {
168
+ options.algorithm = "sha256" /* SHA256 */;
169
+ }
170
+ if (!options?.serialize) {
171
+ options.serialize = JSON.stringify;
172
+ }
173
+ const hashResult = hash(object, options);
174
+ const hashNumber = Number.parseInt(hashResult, 16);
175
+ const range = max - min + 1;
176
+ const result = min + hashNumber % range;
177
+ if (result < min) {
178
+ return min;
179
+ }
180
+ if (result > max) {
181
+ return max;
182
+ }
183
+ return result;
184
+ }
185
+ function djb2Hash(string_) {
186
+ let hash2 = 5381;
187
+ for (let i = 0; i < string_.length; i++) {
188
+ hash2 = hash2 * 33 ^ string_.charCodeAt(i);
189
+ }
190
+ return hash2.toString();
191
+ }
192
+
193
+ // src/is-keyv-instance.ts
194
+ import { Keyv } from "keyv";
195
+ function isKeyvInstance(keyv) {
196
+ if (keyv === null || keyv === void 0) {
197
+ return false;
198
+ }
199
+ if (keyv instanceof Keyv) {
200
+ return true;
201
+ }
202
+ const keyvMethods = [
203
+ "generateIterator",
204
+ "get",
205
+ "getMany",
206
+ "set",
207
+ "setMany",
208
+ "delete",
209
+ "deleteMany",
210
+ "has",
211
+ "hasMany",
212
+ "clear",
213
+ "disconnect",
214
+ "serialize",
215
+ "deserialize"
216
+ ];
217
+ return keyvMethods.every((method) => typeof keyv[method] === "function");
218
+ }
219
+
220
+ // src/is-object.ts
221
+ function isObject(value) {
222
+ return value !== null && typeof value === "object" && !Array.isArray(value);
223
+ }
224
+
225
+ // src/less-than.ts
226
+ function lessThan(number1, number2) {
227
+ return typeof number1 === "number" && typeof number2 === "number" ? number1 < number2 : false;
228
+ }
229
+
230
+ // src/memoize.ts
231
+ function wrapSync(function_, options) {
232
+ const { ttl, keyPrefix, cache, serialize } = options;
233
+ return (...arguments_) => {
234
+ let cacheKey = createWrapKey(function_, arguments_, {
235
+ keyPrefix,
236
+ serialize
237
+ });
238
+ if (options.createKey) {
239
+ cacheKey = options.createKey(function_, arguments_, options);
240
+ }
241
+ let value = cache.get(cacheKey);
242
+ if (value === void 0) {
243
+ try {
244
+ value = function_(...arguments_);
245
+ cache.set(cacheKey, value, ttl);
246
+ } catch (error) {
247
+ cache.emit("error", error);
248
+ if (options.cacheErrors) {
249
+ cache.set(cacheKey, error, ttl);
250
+ }
251
+ }
252
+ }
253
+ return value;
254
+ };
255
+ }
256
+ async function getOrSet(key, function_, options) {
257
+ const keyString = typeof key === "function" ? key(options) : key;
258
+ let value = await options.cache.get(keyString);
259
+ if (value === void 0) {
260
+ const cacheId = options.cacheId ?? "default";
261
+ const coalesceKey = `${cacheId}::${keyString}`;
262
+ value = await coalesceAsync(coalesceKey, async () => {
263
+ try {
264
+ const result = await function_();
265
+ await options.cache.set(keyString, result, options.ttl);
266
+ return result;
267
+ } catch (error) {
268
+ options.cache.emit("error", error);
269
+ if (options.cacheErrors) {
270
+ await options.cache.set(keyString, error, options.ttl);
271
+ }
272
+ if (options.throwErrors) {
273
+ throw error;
274
+ }
275
+ }
276
+ });
277
+ }
278
+ return value;
279
+ }
280
+ function wrap(function_, options) {
281
+ const { keyPrefix, serialize } = options;
282
+ return async (...arguments_) => {
283
+ let cacheKey = createWrapKey(function_, arguments_, {
284
+ keyPrefix,
285
+ serialize
286
+ });
287
+ if (options.createKey) {
288
+ cacheKey = options.createKey(function_, arguments_, options);
289
+ }
290
+ return getOrSet(
291
+ cacheKey,
292
+ async () => function_(...arguments_),
293
+ options
294
+ );
295
+ };
296
+ }
297
+ function createWrapKey(function_, arguments_, options) {
298
+ const { keyPrefix, serialize } = options || {};
299
+ if (!keyPrefix) {
300
+ return `${function_.name}::${hash(arguments_, { serialize })}`;
301
+ }
302
+ return `${keyPrefix}::${function_.name}::${hash(arguments_, { serialize })}`;
303
+ }
304
+
305
+ // src/run-if-fn.ts
306
+ function runIfFn(valueOrFunction, ...arguments_) {
307
+ return typeof valueOrFunction === "function" ? valueOrFunction(...arguments_) : valueOrFunction;
308
+ }
309
+
310
+ // src/sleep.ts
311
+ var sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
312
+
313
+ // src/stats.ts
314
+ var Stats = class {
315
+ _hits = 0;
316
+ _misses = 0;
317
+ _gets = 0;
318
+ _sets = 0;
319
+ _deletes = 0;
320
+ _clears = 0;
321
+ _vsize = 0;
322
+ _ksize = 0;
323
+ _count = 0;
324
+ _enabled = false;
325
+ constructor(options) {
326
+ if (options?.enabled) {
327
+ this._enabled = options.enabled;
328
+ }
329
+ }
330
+ /**
331
+ * @returns {boolean} - Whether the stats are enabled
332
+ */
333
+ get enabled() {
334
+ return this._enabled;
335
+ }
336
+ /**
337
+ * @param {boolean} enabled - Whether to enable the stats
338
+ */
339
+ set enabled(enabled) {
340
+ this._enabled = enabled;
341
+ }
342
+ /**
343
+ * @returns {number} - The number of hits
344
+ * @readonly
345
+ */
346
+ get hits() {
347
+ return this._hits;
348
+ }
349
+ /**
350
+ * @returns {number} - The number of misses
351
+ * @readonly
352
+ */
353
+ get misses() {
354
+ return this._misses;
355
+ }
356
+ /**
357
+ * @returns {number} - The number of gets
358
+ * @readonly
359
+ */
360
+ get gets() {
361
+ return this._gets;
362
+ }
363
+ /**
364
+ * @returns {number} - The number of sets
365
+ * @readonly
366
+ */
367
+ get sets() {
368
+ return this._sets;
369
+ }
370
+ /**
371
+ * @returns {number} - The number of deletes
372
+ * @readonly
373
+ */
374
+ get deletes() {
375
+ return this._deletes;
376
+ }
377
+ /**
378
+ * @returns {number} - The number of clears
379
+ * @readonly
380
+ */
381
+ get clears() {
382
+ return this._clears;
383
+ }
384
+ /**
385
+ * @returns {number} - The vsize (value size) of the cache instance
386
+ * @readonly
387
+ */
388
+ get vsize() {
389
+ return this._vsize;
390
+ }
391
+ /**
392
+ * @returns {number} - The ksize (key size) of the cache instance
393
+ * @readonly
394
+ */
395
+ get ksize() {
396
+ return this._ksize;
397
+ }
398
+ /**
399
+ * @returns {number} - The count of the cache instance
400
+ * @readonly
401
+ */
402
+ get count() {
403
+ return this._count;
404
+ }
405
+ incrementHits() {
406
+ if (!this._enabled) {
407
+ return;
408
+ }
409
+ this._hits++;
410
+ }
411
+ incrementMisses() {
412
+ if (!this._enabled) {
413
+ return;
414
+ }
415
+ this._misses++;
416
+ }
417
+ incrementGets() {
418
+ if (!this._enabled) {
419
+ return;
420
+ }
421
+ this._gets++;
422
+ }
423
+ incrementSets() {
424
+ if (!this._enabled) {
425
+ return;
426
+ }
427
+ this._sets++;
428
+ }
429
+ incrementDeletes() {
430
+ if (!this._enabled) {
431
+ return;
432
+ }
433
+ this._deletes++;
434
+ }
435
+ incrementClears() {
436
+ if (!this._enabled) {
437
+ return;
438
+ }
439
+ this._clears++;
440
+ }
441
+ incrementVSize(value) {
442
+ if (!this._enabled) {
443
+ return;
444
+ }
445
+ this._vsize += this.roughSizeOfObject(value);
446
+ }
447
+ decreaseVSize(value) {
448
+ if (!this._enabled) {
449
+ return;
450
+ }
451
+ this._vsize -= this.roughSizeOfObject(value);
452
+ }
453
+ incrementKSize(key) {
454
+ if (!this._enabled) {
455
+ return;
456
+ }
457
+ this._ksize += this.roughSizeOfString(key);
458
+ }
459
+ decreaseKSize(key) {
460
+ if (!this._enabled) {
461
+ return;
462
+ }
463
+ this._ksize -= this.roughSizeOfString(key);
464
+ }
465
+ incrementCount() {
466
+ if (!this._enabled) {
467
+ return;
468
+ }
469
+ this._count++;
470
+ }
471
+ decreaseCount() {
472
+ if (!this._enabled) {
473
+ return;
474
+ }
475
+ this._count--;
476
+ }
477
+ setCount(count) {
478
+ if (!this._enabled) {
479
+ return;
480
+ }
481
+ this._count = count;
482
+ }
483
+ roughSizeOfString(value) {
484
+ return value.length * 2;
485
+ }
486
+ roughSizeOfObject(object) {
487
+ const objectList = [];
488
+ const stack = [object];
489
+ let bytes = 0;
490
+ while (stack.length > 0) {
491
+ const value = stack.pop();
492
+ if (typeof value === "boolean") {
493
+ bytes += 4;
494
+ } else if (typeof value === "string") {
495
+ bytes += value.length * 2;
496
+ } else if (typeof value === "number") {
497
+ bytes += 8;
498
+ } else {
499
+ if (value === null || value === void 0) {
500
+ bytes += 4;
501
+ continue;
502
+ }
503
+ if (objectList.includes(value)) {
504
+ continue;
505
+ }
506
+ objectList.push(value);
507
+ for (const key in value) {
508
+ bytes += key.length * 2;
509
+ stack.push(value[key]);
510
+ }
511
+ }
512
+ }
513
+ return bytes;
514
+ }
515
+ reset() {
516
+ this._hits = 0;
517
+ this._misses = 0;
518
+ this._gets = 0;
519
+ this._sets = 0;
520
+ this._deletes = 0;
521
+ this._clears = 0;
522
+ this._vsize = 0;
523
+ this._ksize = 0;
524
+ this._count = 0;
525
+ }
526
+ resetStoreValues() {
527
+ this._vsize = 0;
528
+ this._ksize = 0;
529
+ this._count = 0;
530
+ }
531
+ };
532
+
533
+ // src/ttl.ts
534
+ function getTtlFromExpires(expires) {
535
+ if (expires === void 0 || expires === null) {
536
+ return void 0;
537
+ }
538
+ const now = Date.now();
539
+ if (expires < now) {
540
+ return void 0;
541
+ }
542
+ return expires - now;
543
+ }
544
+ function getCascadingTtl(cacheableTtl, primaryTtl, secondaryTtl) {
545
+ return secondaryTtl ?? primaryTtl ?? shorthandToMilliseconds(cacheableTtl);
546
+ }
547
+ function calculateTtlFromExpiration(ttl, expires) {
548
+ const ttlFromExpires = getTtlFromExpires(expires);
549
+ const expiresFromTtl = ttl ? Date.now() + ttl : void 0;
550
+ if (ttlFromExpires === void 0) {
551
+ return ttl;
552
+ }
553
+ if (expiresFromTtl === void 0) {
554
+ return ttlFromExpires;
555
+ }
556
+ if (expires && expires > expiresFromTtl) {
557
+ return ttl;
558
+ }
559
+ return ttlFromExpires;
560
+ }
561
+ export {
562
+ HashAlgorithm,
563
+ Stats,
564
+ calculateTtlFromExpiration,
565
+ coalesceAsync,
566
+ createWrapKey,
567
+ getCascadingTtl,
568
+ getOrSet,
569
+ getTtlFromExpires,
570
+ hash,
571
+ hashToNumber,
572
+ isKeyvInstance,
573
+ isObject,
574
+ lessThan,
575
+ runIfFn,
576
+ shorthandToMilliseconds,
577
+ shorthandToTime,
578
+ sleep,
579
+ wrap,
580
+ wrapSync
581
+ };
582
+ /* v8 ignore next -- @preserve */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cacheable/utils",
3
- "version": "2.0.3",
3
+ "version": "2.2.0",
4
4
  "description": "Cacheable Utilities for Caching Libraries",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -21,17 +21,15 @@
21
21
  "license": "MIT",
22
22
  "private": false,
23
23
  "devDependencies": {
24
- "@biomejs/biome": "^2.2.4",
25
- "@faker-js/faker": "^10.0.0",
26
- "@keyv/redis": "^5.1.2",
27
- "@keyv/valkey": "^1.0.8",
28
- "@types/node": "^24.5.2",
29
- "@vitest/coverage-v8": "^3.2.4",
24
+ "@biomejs/biome": "^2.3.0",
25
+ "@faker-js/faker": "^10.1.0",
26
+ "@types/node": "^24.9.1",
27
+ "@vitest/coverage-v8": "^4.0.3",
30
28
  "lru-cache": "^11.2.2",
31
29
  "rimraf": "^6.0.1",
32
30
  "tsup": "^8.5.0",
33
- "typescript": "^5.9.2",
34
- "vitest": "^3.2.4"
31
+ "typescript": "^5.9.3",
32
+ "vitest": "^4.0.3"
35
33
  },
36
34
  "keywords": [
37
35
  "cacheable",
@@ -45,8 +43,11 @@
45
43
  "dist",
46
44
  "LICENSE"
47
45
  ],
46
+ "dependencies": {
47
+ "keyv": "^5.5.3"
48
+ },
48
49
  "scripts": {
49
- "build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean --minify",
50
+ "build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean",
50
51
  "prepublish": "pnpm build",
51
52
  "lint": "biome check --write --error-on-warnings",
52
53
  "test": "pnpm lint && vitest run --coverage",