@cacheable/utils 1.0.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 ADDED
@@ -0,0 +1,415 @@
1
+ // src/coalesce-async.ts
2
+ var callbacks = /* @__PURE__ */ new Map();
3
+ function hasKey(key) {
4
+ return callbacks.has(key);
5
+ }
6
+ function addKey(key) {
7
+ callbacks.set(key, []);
8
+ }
9
+ function removeKey(key) {
10
+ callbacks.delete(key);
11
+ }
12
+ function addCallbackToKey(key, callback) {
13
+ const stash = getCallbacksByKey(key);
14
+ stash.push(callback);
15
+ callbacks.set(key, stash);
16
+ }
17
+ function getCallbacksByKey(key) {
18
+ return callbacks.get(key) ?? [];
19
+ }
20
+ async function enqueue(key) {
21
+ return new Promise((resolve, reject) => {
22
+ const callback = { resolve, reject };
23
+ addCallbackToKey(key, callback);
24
+ });
25
+ }
26
+ function dequeue(key) {
27
+ const stash = getCallbacksByKey(key);
28
+ removeKey(key);
29
+ return stash;
30
+ }
31
+ function coalesce(options) {
32
+ const { key, error, result } = options;
33
+ for (const callback of dequeue(key)) {
34
+ if (error) {
35
+ callback.reject(error);
36
+ } else {
37
+ callback.resolve(result);
38
+ }
39
+ }
40
+ }
41
+ async function coalesceAsync(key, fnc) {
42
+ if (!hasKey(key)) {
43
+ addKey(key);
44
+ try {
45
+ const result = await Promise.resolve(fnc());
46
+ coalesce({ key, result });
47
+ return result;
48
+ } catch (error) {
49
+ coalesce({ key, error });
50
+ throw error;
51
+ }
52
+ }
53
+ return enqueue(key);
54
+ }
55
+
56
+ // src/hash.ts
57
+ import * as crypto from "crypto";
58
+ var HashAlgorithm = /* @__PURE__ */ ((HashAlgorithm2) => {
59
+ HashAlgorithm2["SHA256"] = "sha256";
60
+ HashAlgorithm2["SHA512"] = "sha512";
61
+ HashAlgorithm2["MD5"] = "md5";
62
+ HashAlgorithm2["DJB2"] = "djb2";
63
+ return HashAlgorithm2;
64
+ })(HashAlgorithm || {});
65
+ function hash(object, algorithm = "sha256" /* SHA256 */) {
66
+ const objectString = JSON.stringify(object);
67
+ if (algorithm === "djb2" /* DJB2 */) {
68
+ return djb2Hash(objectString);
69
+ }
70
+ if (!crypto.getHashes().includes(algorithm)) {
71
+ throw new Error(`Unsupported hash algorithm: '${algorithm}'`);
72
+ }
73
+ const hasher = crypto.createHash(algorithm);
74
+ hasher.update(objectString);
75
+ return hasher.digest("hex");
76
+ }
77
+ function hashToNumber(hash2, min = 0, max = 10) {
78
+ const hashNumber = Number.parseInt(hash2, 16);
79
+ const range = max - min + 1;
80
+ return min + hashNumber % range;
81
+ }
82
+ function djb2Hash(string_) {
83
+ let hash2 = 5381;
84
+ for (let i = 0; i < string_.length; i++) {
85
+ hash2 = hash2 * 33 ^ string_.charCodeAt(i);
86
+ }
87
+ return hash2.toString();
88
+ }
89
+
90
+ // src/shorthand-time.ts
91
+ var shorthandToMilliseconds = (shorthand) => {
92
+ let milliseconds;
93
+ if (shorthand === void 0) {
94
+ return void 0;
95
+ }
96
+ if (typeof shorthand === "number") {
97
+ milliseconds = shorthand;
98
+ } else if (typeof shorthand === "string") {
99
+ shorthand = shorthand.trim();
100
+ if (Number.isNaN(Number(shorthand))) {
101
+ const match = /^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(shorthand);
102
+ if (!match) {
103
+ throw new Error(`Unsupported time format: "${shorthand}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`);
104
+ }
105
+ const [, value, unit] = match;
106
+ const numericValue = Number.parseFloat(value);
107
+ const unitLower = unit.toLowerCase();
108
+ switch (unitLower) {
109
+ case "ms": {
110
+ milliseconds = numericValue;
111
+ break;
112
+ }
113
+ case "s": {
114
+ milliseconds = numericValue * 1e3;
115
+ break;
116
+ }
117
+ case "m": {
118
+ milliseconds = numericValue * 1e3 * 60;
119
+ break;
120
+ }
121
+ case "h": {
122
+ milliseconds = numericValue * 1e3 * 60 * 60;
123
+ break;
124
+ }
125
+ case "hr": {
126
+ milliseconds = numericValue * 1e3 * 60 * 60;
127
+ break;
128
+ }
129
+ case "d": {
130
+ milliseconds = numericValue * 1e3 * 60 * 60 * 24;
131
+ break;
132
+ }
133
+ /* c8 ignore next 3 */
134
+ default: {
135
+ milliseconds = Number(shorthand);
136
+ }
137
+ }
138
+ } else {
139
+ milliseconds = Number(shorthand);
140
+ }
141
+ } else {
142
+ throw new TypeError("Time must be a string or a number.");
143
+ }
144
+ return milliseconds;
145
+ };
146
+ var shorthandToTime = (shorthand, fromDate) => {
147
+ fromDate ??= /* @__PURE__ */ new Date();
148
+ const milliseconds = shorthandToMilliseconds(shorthand);
149
+ if (milliseconds === void 0) {
150
+ return fromDate.getTime();
151
+ }
152
+ return fromDate.getTime() + milliseconds;
153
+ };
154
+
155
+ // src/sleep.ts
156
+ var sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
157
+
158
+ // src/stats.ts
159
+ var Stats = class {
160
+ _hits = 0;
161
+ _misses = 0;
162
+ _gets = 0;
163
+ _sets = 0;
164
+ _deletes = 0;
165
+ _clears = 0;
166
+ _vsize = 0;
167
+ _ksize = 0;
168
+ _count = 0;
169
+ _enabled = false;
170
+ constructor(options) {
171
+ if (options?.enabled) {
172
+ this._enabled = options.enabled;
173
+ }
174
+ }
175
+ /**
176
+ * @returns {boolean} - Whether the stats are enabled
177
+ */
178
+ get enabled() {
179
+ return this._enabled;
180
+ }
181
+ /**
182
+ * @param {boolean} enabled - Whether to enable the stats
183
+ */
184
+ set enabled(enabled) {
185
+ this._enabled = enabled;
186
+ }
187
+ /**
188
+ * @returns {number} - The number of hits
189
+ * @readonly
190
+ */
191
+ get hits() {
192
+ return this._hits;
193
+ }
194
+ /**
195
+ * @returns {number} - The number of misses
196
+ * @readonly
197
+ */
198
+ get misses() {
199
+ return this._misses;
200
+ }
201
+ /**
202
+ * @returns {number} - The number of gets
203
+ * @readonly
204
+ */
205
+ get gets() {
206
+ return this._gets;
207
+ }
208
+ /**
209
+ * @returns {number} - The number of sets
210
+ * @readonly
211
+ */
212
+ get sets() {
213
+ return this._sets;
214
+ }
215
+ /**
216
+ * @returns {number} - The number of deletes
217
+ * @readonly
218
+ */
219
+ get deletes() {
220
+ return this._deletes;
221
+ }
222
+ /**
223
+ * @returns {number} - The number of clears
224
+ * @readonly
225
+ */
226
+ get clears() {
227
+ return this._clears;
228
+ }
229
+ /**
230
+ * @returns {number} - The vsize (value size) of the cache instance
231
+ * @readonly
232
+ */
233
+ get vsize() {
234
+ return this._vsize;
235
+ }
236
+ /**
237
+ * @returns {number} - The ksize (key size) of the cache instance
238
+ * @readonly
239
+ */
240
+ get ksize() {
241
+ return this._ksize;
242
+ }
243
+ /**
244
+ * @returns {number} - The count of the cache instance
245
+ * @readonly
246
+ */
247
+ get count() {
248
+ return this._count;
249
+ }
250
+ incrementHits() {
251
+ if (!this._enabled) {
252
+ return;
253
+ }
254
+ this._hits++;
255
+ }
256
+ incrementMisses() {
257
+ if (!this._enabled) {
258
+ return;
259
+ }
260
+ this._misses++;
261
+ }
262
+ incrementGets() {
263
+ if (!this._enabled) {
264
+ return;
265
+ }
266
+ this._gets++;
267
+ }
268
+ incrementSets() {
269
+ if (!this._enabled) {
270
+ return;
271
+ }
272
+ this._sets++;
273
+ }
274
+ incrementDeletes() {
275
+ if (!this._enabled) {
276
+ return;
277
+ }
278
+ this._deletes++;
279
+ }
280
+ incrementClears() {
281
+ if (!this._enabled) {
282
+ return;
283
+ }
284
+ this._clears++;
285
+ }
286
+ // eslint-disable-next-line @typescript-eslint/naming-convention
287
+ incrementVSize(value) {
288
+ if (!this._enabled) {
289
+ return;
290
+ }
291
+ this._vsize += this.roughSizeOfObject(value);
292
+ }
293
+ // eslint-disable-next-line @typescript-eslint/naming-convention
294
+ decreaseVSize(value) {
295
+ if (!this._enabled) {
296
+ return;
297
+ }
298
+ this._vsize -= this.roughSizeOfObject(value);
299
+ }
300
+ // eslint-disable-next-line @typescript-eslint/naming-convention
301
+ incrementKSize(key) {
302
+ if (!this._enabled) {
303
+ return;
304
+ }
305
+ this._ksize += this.roughSizeOfString(key);
306
+ }
307
+ // eslint-disable-next-line @typescript-eslint/naming-convention
308
+ decreaseKSize(key) {
309
+ if (!this._enabled) {
310
+ return;
311
+ }
312
+ this._ksize -= this.roughSizeOfString(key);
313
+ }
314
+ incrementCount() {
315
+ if (!this._enabled) {
316
+ return;
317
+ }
318
+ this._count++;
319
+ }
320
+ decreaseCount() {
321
+ if (!this._enabled) {
322
+ return;
323
+ }
324
+ this._count--;
325
+ }
326
+ setCount(count) {
327
+ if (!this._enabled) {
328
+ return;
329
+ }
330
+ this._count = count;
331
+ }
332
+ roughSizeOfString(value) {
333
+ return value.length * 2;
334
+ }
335
+ roughSizeOfObject(object) {
336
+ const objectList = [];
337
+ const stack = [object];
338
+ let bytes = 0;
339
+ while (stack.length > 0) {
340
+ const value = stack.pop();
341
+ if (typeof value === "boolean") {
342
+ bytes += 4;
343
+ } else if (typeof value === "string") {
344
+ bytes += value.length * 2;
345
+ } else if (typeof value === "number") {
346
+ bytes += 8;
347
+ } else if (typeof value === "object" && value !== null && !objectList.includes(value)) {
348
+ objectList.push(value);
349
+ for (const key in value) {
350
+ bytes += key.length * 2;
351
+ stack.push(value[key]);
352
+ }
353
+ }
354
+ }
355
+ return bytes;
356
+ }
357
+ reset() {
358
+ this._hits = 0;
359
+ this._misses = 0;
360
+ this._gets = 0;
361
+ this._sets = 0;
362
+ this._deletes = 0;
363
+ this._clears = 0;
364
+ this._vsize = 0;
365
+ this._ksize = 0;
366
+ this._count = 0;
367
+ }
368
+ resetStoreValues() {
369
+ this._vsize = 0;
370
+ this._ksize = 0;
371
+ this._count = 0;
372
+ }
373
+ };
374
+
375
+ // src/ttl.ts
376
+ function getTtlFromExpires(expires) {
377
+ if (expires === void 0 || expires === null) {
378
+ return void 0;
379
+ }
380
+ const now = Date.now();
381
+ if (expires < now) {
382
+ return void 0;
383
+ }
384
+ return expires - now;
385
+ }
386
+ function getCascadingTtl(cacheableTtl, primaryTtl, secondaryTtl) {
387
+ return secondaryTtl ?? primaryTtl ?? shorthandToMilliseconds(cacheableTtl);
388
+ }
389
+ function calculateTtlFromExpiration(ttl, expires) {
390
+ const ttlFromExpires = getTtlFromExpires(expires);
391
+ const expiresFromTtl = ttl ? Date.now() + ttl : void 0;
392
+ if (ttlFromExpires === void 0) {
393
+ return ttl;
394
+ }
395
+ if (expiresFromTtl === void 0) {
396
+ return ttlFromExpires;
397
+ }
398
+ if (expires > expiresFromTtl) {
399
+ return ttl;
400
+ }
401
+ return ttlFromExpires;
402
+ }
403
+ export {
404
+ HashAlgorithm,
405
+ Stats,
406
+ calculateTtlFromExpiration,
407
+ coalesceAsync,
408
+ getCascadingTtl,
409
+ getTtlFromExpires,
410
+ hash,
411
+ hashToNumber,
412
+ shorthandToMilliseconds,
413
+ shorthandToTime,
414
+ sleep
415
+ };
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@cacheable/utils",
3
+ "version": "1.0.0",
4
+ "description": "Cacheable Utilities for Caching Libraries",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "require": "./dist/index.cjs",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/jaredwray/cacheable.git",
18
+ "directory": "packages/utils"
19
+ },
20
+ "author": "Jared Wray <me@jaredwray.com>",
21
+ "license": "MIT",
22
+ "private": false,
23
+ "devDependencies": {
24
+ "@faker-js/faker": "^9.9.0",
25
+ "@keyv/redis": "^5.0.0",
26
+ "@keyv/valkey": "^1.0.7",
27
+ "@types/eslint": "^9.6.1",
28
+ "@types/node": "^24.1.0",
29
+ "@vitest/coverage-v8": "^3.2.4",
30
+ "lru-cache": "^11.1.0",
31
+ "rimraf": "^6.0.1",
32
+ "tsup": "^8.5.0",
33
+ "typescript": "^5.8.3",
34
+ "vitest": "^3.2.4",
35
+ "xo": "^1.2.1"
36
+ },
37
+ "keywords": [
38
+ "cacheable",
39
+ "caching",
40
+ "utilities",
41
+ "hashing",
42
+ "keyv",
43
+ "cache utils"
44
+ ],
45
+ "files": [
46
+ "dist",
47
+ "LICENSE"
48
+ ],
49
+ "scripts": {
50
+ "build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean",
51
+ "prepublish": "pnpm build",
52
+ "test": "xo --fix && vitest run --coverage",
53
+ "test:ci": "xo && vitest run --coverage",
54
+ "clean": "rimraf ./dist ./coverage ./node_modules"
55
+ }
56
+ }