@cacheable/utils 2.4.0 → 2.5.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.js DELETED
@@ -1,630 +0,0 @@
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 { Hashery } from "hashery";
126
- var HashAlgorithm = /* @__PURE__ */ ((HashAlgorithm2) => {
127
- HashAlgorithm2["SHA256"] = "SHA-256";
128
- HashAlgorithm2["SHA384"] = "SHA-384";
129
- HashAlgorithm2["SHA512"] = "SHA-512";
130
- HashAlgorithm2["DJB2"] = "djb2";
131
- HashAlgorithm2["FNV1"] = "fnv1";
132
- HashAlgorithm2["MURMER"] = "murmer";
133
- HashAlgorithm2["CRC32"] = "crc32";
134
- return HashAlgorithm2;
135
- })(HashAlgorithm || {});
136
- async function hash(object, options = {
137
- algorithm: "SHA-256" /* SHA256 */,
138
- serialize: JSON.stringify
139
- }) {
140
- const algorithm = options?.algorithm ?? "SHA-256" /* SHA256 */;
141
- const serialize = options?.serialize ?? JSON.stringify;
142
- const objectString = serialize(object);
143
- const hashery = new Hashery();
144
- return hashery.toHash(objectString, { algorithm });
145
- }
146
- function hashSync(object, options = {
147
- algorithm: "djb2" /* DJB2 */,
148
- serialize: JSON.stringify
149
- }) {
150
- const algorithm = options?.algorithm ?? "djb2" /* DJB2 */;
151
- const serialize = options?.serialize ?? JSON.stringify;
152
- const objectString = serialize(object);
153
- const hashery = new Hashery();
154
- return hashery.toHashSync(objectString, { algorithm });
155
- }
156
- async function hashToNumber(object, options = {
157
- min: 0,
158
- max: 10,
159
- algorithm: "SHA-256" /* SHA256 */,
160
- serialize: JSON.stringify
161
- }) {
162
- const min = options?.min ?? 0;
163
- const max = options?.max ?? 10;
164
- const algorithm = options?.algorithm ?? "SHA-256" /* SHA256 */;
165
- const serialize = options?.serialize ?? JSON.stringify;
166
- const hashLength = options?.hashLength ?? 16;
167
- if (min >= max) {
168
- throw new Error(
169
- `Invalid range: min (${min}) must be less than max (${max})`
170
- );
171
- }
172
- const objectString = serialize(object);
173
- const hashery = new Hashery();
174
- return hashery.toNumber(objectString, {
175
- algorithm,
176
- min,
177
- max,
178
- hashLength
179
- });
180
- }
181
- function hashToNumberSync(object, options = {
182
- min: 0,
183
- max: 10,
184
- algorithm: "djb2" /* DJB2 */,
185
- serialize: JSON.stringify
186
- }) {
187
- const min = options?.min ?? 0;
188
- const max = options?.max ?? 10;
189
- const algorithm = options?.algorithm ?? "djb2" /* DJB2 */;
190
- const serialize = options?.serialize ?? JSON.stringify;
191
- const hashLength = options?.hashLength ?? 16;
192
- if (min >= max) {
193
- throw new Error(
194
- `Invalid range: min (${min}) must be less than max (${max})`
195
- );
196
- }
197
- const objectString = serialize(object);
198
- const hashery = new Hashery();
199
- return hashery.toNumberSync(objectString, {
200
- algorithm,
201
- min,
202
- max,
203
- hashLength
204
- });
205
- }
206
-
207
- // src/is-keyv-instance.ts
208
- import { Keyv } from "keyv";
209
- function isKeyvInstance(keyv) {
210
- if (keyv === null || keyv === void 0) {
211
- return false;
212
- }
213
- if (keyv instanceof Keyv) {
214
- return true;
215
- }
216
- const keyvMethods = [
217
- "generateIterator",
218
- "get",
219
- "getMany",
220
- "set",
221
- "setMany",
222
- "delete",
223
- "deleteMany",
224
- "has",
225
- "hasMany",
226
- "clear",
227
- "disconnect",
228
- "serialize",
229
- "deserialize"
230
- ];
231
- return keyvMethods.every((method) => typeof keyv[method] === "function");
232
- }
233
-
234
- // src/is-object.ts
235
- function isObject(value) {
236
- return value !== null && typeof value === "object" && !Array.isArray(value);
237
- }
238
-
239
- // src/less-than.ts
240
- function lessThan(number1, number2) {
241
- return typeof number1 === "number" && typeof number2 === "number" ? number1 < number2 : false;
242
- }
243
-
244
- // src/memoize.ts
245
- function wrapSync(function_, options) {
246
- const { ttl, keyPrefix, cache, serialize } = options;
247
- return (...arguments_) => {
248
- let cacheKey = createWrapKey(function_, arguments_, {
249
- keyPrefix,
250
- serialize
251
- });
252
- if (options.createKey) {
253
- cacheKey = options.createKey(function_, arguments_, options);
254
- }
255
- let value = cache.get(cacheKey);
256
- if (value === void 0) {
257
- try {
258
- value = function_(...arguments_);
259
- cache.set(cacheKey, value, ttl);
260
- } catch (error) {
261
- cache.emit("error", error);
262
- if (options.cacheErrors) {
263
- cache.set(cacheKey, error, ttl);
264
- }
265
- }
266
- }
267
- return value;
268
- };
269
- }
270
- async function getOrSet(key, function_, options) {
271
- const keyString = typeof key === "function" ? key(options) : key;
272
- let value;
273
- try {
274
- value = await options.cache.get(keyString);
275
- } catch (error) {
276
- options.cache.emit("error", error);
277
- if (options.throwErrors === true || options.throwErrors === "store") {
278
- throw error;
279
- }
280
- }
281
- if (value === void 0) {
282
- const cacheId = options.cacheId ?? "default";
283
- const coalesceKey = `${cacheId}::${keyString}`;
284
- value = await coalesceAsync(coalesceKey, async () => {
285
- let result;
286
- try {
287
- try {
288
- result = await function_();
289
- } catch (error) {
290
- throw new ErrorEnvelope(
291
- error,
292
- "function"
293
- );
294
- }
295
- try {
296
- await options.cache.set(keyString, result, options.ttl);
297
- } catch (error) {
298
- throw new ErrorEnvelope(error, "store");
299
- }
300
- return result;
301
- } catch (caught) {
302
- const errorType = caught instanceof ErrorEnvelope ? caught.context : (
303
- /* c8 ignore next 1 */
304
- void 0
305
- );
306
- const error = caught instanceof ErrorEnvelope ? caught.error : caught;
307
- options.cache.emit("error", error);
308
- if (options.cacheErrors) {
309
- await options.cache.set(keyString, error, options.ttl);
310
- }
311
- if (options.throwErrors === true || options.throwErrors === errorType) {
312
- throw error;
313
- }
314
- }
315
- return result;
316
- });
317
- }
318
- return value;
319
- }
320
- function wrap(function_, options) {
321
- const { keyPrefix, serialize } = options;
322
- return async (...arguments_) => {
323
- let cacheKey = createWrapKey(function_, arguments_, {
324
- keyPrefix,
325
- serialize
326
- });
327
- if (options.createKey) {
328
- cacheKey = options.createKey(function_, arguments_, options);
329
- }
330
- return getOrSet(
331
- cacheKey,
332
- async () => function_(...arguments_),
333
- options
334
- );
335
- };
336
- }
337
- function createWrapKey(function_, arguments_, options) {
338
- const { keyPrefix, serialize } = options || {};
339
- if (!keyPrefix) {
340
- return `${function_.name}::${hashSync(arguments_, { serialize })}`;
341
- }
342
- return `${keyPrefix}::${function_.name}::${hashSync(arguments_, { serialize })}`;
343
- }
344
- var ErrorEnvelope = class {
345
- constructor(error, context) {
346
- this.error = error;
347
- this.context = context;
348
- }
349
- };
350
-
351
- // src/run-if-fn.ts
352
- function runIfFn(valueOrFunction, ...arguments_) {
353
- return typeof valueOrFunction === "function" ? valueOrFunction(...arguments_) : valueOrFunction;
354
- }
355
-
356
- // src/sleep.ts
357
- var sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
358
-
359
- // src/stats.ts
360
- var Stats = class {
361
- _hits = 0;
362
- _misses = 0;
363
- _gets = 0;
364
- _sets = 0;
365
- _deletes = 0;
366
- _clears = 0;
367
- _vsize = 0;
368
- _ksize = 0;
369
- _count = 0;
370
- _enabled = false;
371
- constructor(options) {
372
- if (options?.enabled) {
373
- this._enabled = options.enabled;
374
- }
375
- }
376
- /**
377
- * @returns {boolean} - Whether the stats are enabled
378
- */
379
- get enabled() {
380
- return this._enabled;
381
- }
382
- /**
383
- * @param {boolean} enabled - Whether to enable the stats
384
- */
385
- set enabled(enabled) {
386
- this._enabled = enabled;
387
- }
388
- /**
389
- * @returns {number} - The number of hits
390
- * @readonly
391
- */
392
- get hits() {
393
- return this._hits;
394
- }
395
- /**
396
- * @returns {number} - The number of misses
397
- * @readonly
398
- */
399
- get misses() {
400
- return this._misses;
401
- }
402
- /**
403
- * @returns {number} - The number of gets
404
- * @readonly
405
- */
406
- get gets() {
407
- return this._gets;
408
- }
409
- /**
410
- * @returns {number} - The number of sets
411
- * @readonly
412
- */
413
- get sets() {
414
- return this._sets;
415
- }
416
- /**
417
- * @returns {number} - The number of deletes
418
- * @readonly
419
- */
420
- get deletes() {
421
- return this._deletes;
422
- }
423
- /**
424
- * @returns {number} - The number of clears
425
- * @readonly
426
- */
427
- get clears() {
428
- return this._clears;
429
- }
430
- /**
431
- * @returns {number} - The vsize (value size) of the cache instance
432
- * @readonly
433
- */
434
- get vsize() {
435
- return this._vsize;
436
- }
437
- /**
438
- * @returns {number} - The ksize (key size) of the cache instance
439
- * @readonly
440
- */
441
- get ksize() {
442
- return this._ksize;
443
- }
444
- /**
445
- * @returns {number} - The count of the cache instance
446
- * @readonly
447
- */
448
- get count() {
449
- return this._count;
450
- }
451
- incrementHits() {
452
- if (!this._enabled) {
453
- return;
454
- }
455
- this._hits++;
456
- }
457
- incrementMisses() {
458
- if (!this._enabled) {
459
- return;
460
- }
461
- this._misses++;
462
- }
463
- incrementGets() {
464
- if (!this._enabled) {
465
- return;
466
- }
467
- this._gets++;
468
- }
469
- incrementSets() {
470
- if (!this._enabled) {
471
- return;
472
- }
473
- this._sets++;
474
- }
475
- incrementDeletes() {
476
- if (!this._enabled) {
477
- return;
478
- }
479
- this._deletes++;
480
- }
481
- incrementClears() {
482
- if (!this._enabled) {
483
- return;
484
- }
485
- this._clears++;
486
- }
487
- incrementVSize(value) {
488
- if (!this._enabled) {
489
- return;
490
- }
491
- this._vsize += this.roughSizeOfObject(value);
492
- }
493
- decreaseVSize(value) {
494
- if (!this._enabled) {
495
- return;
496
- }
497
- this._vsize -= this.roughSizeOfObject(value);
498
- }
499
- incrementKSize(key) {
500
- if (!this._enabled) {
501
- return;
502
- }
503
- this._ksize += this.roughSizeOfString(key);
504
- }
505
- decreaseKSize(key) {
506
- if (!this._enabled) {
507
- return;
508
- }
509
- this._ksize -= this.roughSizeOfString(key);
510
- }
511
- incrementCount() {
512
- if (!this._enabled) {
513
- return;
514
- }
515
- this._count++;
516
- }
517
- decreaseCount() {
518
- if (!this._enabled) {
519
- return;
520
- }
521
- this._count--;
522
- }
523
- setCount(count) {
524
- if (!this._enabled) {
525
- return;
526
- }
527
- this._count = count;
528
- }
529
- roughSizeOfString(value) {
530
- return value.length * 2;
531
- }
532
- roughSizeOfObject(object) {
533
- const objectList = [];
534
- const stack = [object];
535
- let bytes = 0;
536
- while (stack.length > 0) {
537
- const value = stack.pop();
538
- if (typeof value === "boolean") {
539
- bytes += 4;
540
- } else if (typeof value === "string") {
541
- bytes += value.length * 2;
542
- } else if (typeof value === "number") {
543
- bytes += 8;
544
- } else {
545
- if (value === null || value === void 0) {
546
- bytes += 4;
547
- continue;
548
- }
549
- if (objectList.includes(value)) {
550
- continue;
551
- }
552
- objectList.push(value);
553
- for (const key in value) {
554
- bytes += key.length * 2;
555
- stack.push(value[key]);
556
- }
557
- }
558
- }
559
- return bytes;
560
- }
561
- reset() {
562
- this._hits = 0;
563
- this._misses = 0;
564
- this._gets = 0;
565
- this._sets = 0;
566
- this._deletes = 0;
567
- this._clears = 0;
568
- this._vsize = 0;
569
- this._ksize = 0;
570
- this._count = 0;
571
- }
572
- resetStoreValues() {
573
- this._vsize = 0;
574
- this._ksize = 0;
575
- this._count = 0;
576
- }
577
- };
578
-
579
- // src/ttl.ts
580
- function getTtlFromExpires(expires) {
581
- if (expires === void 0 || expires === null) {
582
- return void 0;
583
- }
584
- const now = Date.now();
585
- if (expires < now) {
586
- return void 0;
587
- }
588
- return expires - now;
589
- }
590
- function getCascadingTtl(cacheableTtl, primaryTtl, secondaryTtl) {
591
- return secondaryTtl ?? primaryTtl ?? shorthandToMilliseconds(cacheableTtl);
592
- }
593
- function calculateTtlFromExpiration(ttl, expires) {
594
- const ttlFromExpires = getTtlFromExpires(expires);
595
- const expiresFromTtl = ttl ? Date.now() + ttl : void 0;
596
- if (ttlFromExpires === void 0) {
597
- return ttl;
598
- }
599
- if (expiresFromTtl === void 0) {
600
- return ttlFromExpires;
601
- }
602
- if (expires && expires > expiresFromTtl) {
603
- return ttl;
604
- }
605
- return ttlFromExpires;
606
- }
607
- export {
608
- HashAlgorithm,
609
- Stats,
610
- calculateTtlFromExpiration,
611
- coalesceAsync,
612
- createWrapKey,
613
- getCascadingTtl,
614
- getOrSet,
615
- getTtlFromExpires,
616
- hash,
617
- hashSync,
618
- hashToNumber,
619
- hashToNumberSync,
620
- isKeyvInstance,
621
- isObject,
622
- lessThan,
623
- runIfFn,
624
- shorthandToMilliseconds,
625
- shorthandToTime,
626
- sleep,
627
- wrap,
628
- wrapSync
629
- };
630
- /* v8 ignore next -- @preserve */