@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/LICENSE +19 -0
- package/README.md +204 -0
- package/dist/index.cjs +462 -0
- package/dist/index.d.cts +195 -0
- package/dist/index.d.ts +195 -0
- package/dist/index.js +415 -0
- package/package.json +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
MIT License & © Jared Wray
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
of this software and associated documentation files (the "Software"), to
|
|
5
|
+
deal in the Software without restriction, including without limitation the
|
|
6
|
+
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
|
7
|
+
sell copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in
|
|
11
|
+
all copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
18
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
19
|
+
DEALINGS IN THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
[<img align="center" src="https://cacheable.org/logo.svg" alt="Cacheable" />](https://github.com/jaredwray/cacheable)
|
|
2
|
+
|
|
3
|
+
> Cacheble Utils
|
|
4
|
+
|
|
5
|
+
[](https://codecov.io/gh/jaredwray/cacheable)
|
|
6
|
+
[](https://github.com/jaredwray/cacheable/actions/workflows/tests.yml)
|
|
7
|
+
[](https://www.npmjs.com/package/cacheable)
|
|
8
|
+
[](https://www.npmjs.com/package/cacheable)
|
|
9
|
+
[](https://github.com/jaredwray/cacheable/blob/main/LICENSE)
|
|
10
|
+
|
|
11
|
+
`@cacheable/utils` is a collecton of utility functions, helpers, and types for `cacheable` and other caching libraries. It provides a robust set of features to enhance caching capabilities, including:
|
|
12
|
+
|
|
13
|
+
* Data Types for Caching Items
|
|
14
|
+
* Hash Functions for Key Generation
|
|
15
|
+
* Coalesce Async for Handling Multiple Promises
|
|
16
|
+
* Stats Helpers for Caching Statistics
|
|
17
|
+
* Sleep / Delay for Testing and Timing
|
|
18
|
+
* Time to Live (TTL) Helpers
|
|
19
|
+
|
|
20
|
+
# Table of Contents
|
|
21
|
+
* [Getting Started](#getting-started)
|
|
22
|
+
* [Cacheable Types](#cacheable-types)
|
|
23
|
+
* [Coalesce Async](#coalesce-async)
|
|
24
|
+
* [Hash Functions](#hash-functions)
|
|
25
|
+
* [Shorthand Time Helpers](#shorthand-time-helpers)
|
|
26
|
+
* [Sleep Helper](#sleep-helper)
|
|
27
|
+
* [Stats Helpers](#stats-helpers)
|
|
28
|
+
* [Time to Live (TTL) Helpers](#time-to-live-ttl-helpers)
|
|
29
|
+
* [How to Contribute](#how-to-contribute)
|
|
30
|
+
* [License and Copyright](#license-and-copyright)
|
|
31
|
+
|
|
32
|
+
# Getting Started
|
|
33
|
+
|
|
34
|
+
`cacheable` is primarily used as an extension to your caching engine with a robust storage backend [Keyv](https://keyv.org), Memoization (Wrap), Hooks, Events, and Statistics.
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
npm install @cacheable/utils --save
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
# Cacheable Types
|
|
41
|
+
|
|
42
|
+
The `@cacheable/utils` package provides various types that are used throughout the caching library. These types help in defining the structure of cached items, ensuring type safety and consistency across your caching operations.
|
|
43
|
+
|
|
44
|
+
```typescript
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* CacheableItem
|
|
48
|
+
* @typedef {Object} CacheableItem
|
|
49
|
+
* @property {string} key - The key of the cacheable item
|
|
50
|
+
* @property {any} value - The value of the cacheable item
|
|
51
|
+
* @property {number|string} [ttl] - Time to Live - If you set a number it is miliseconds, if you set a string it is a human-readable
|
|
52
|
+
* format such as `1s` for 1 second or `1h` for 1 hour. Setting undefined means that it will use the default time-to-live. If both are
|
|
53
|
+
* undefined then it will not have a time-to-live.
|
|
54
|
+
*/
|
|
55
|
+
export type CacheableItem = {
|
|
56
|
+
key: string;
|
|
57
|
+
value: any;
|
|
58
|
+
ttl?: number | string;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* CacheableStoreItem
|
|
63
|
+
* @typedef {Object} CacheableStoreItem
|
|
64
|
+
* @property {string} key - The key of the cacheable store item
|
|
65
|
+
* @property {any} value - The value of the cacheable store item
|
|
66
|
+
* @property {number} [expires] - The expiration time in milliseconds since epoch. If not set, the item does not expire.
|
|
67
|
+
*/
|
|
68
|
+
export type CacheableStoreItem = {
|
|
69
|
+
key: string;
|
|
70
|
+
value: any;
|
|
71
|
+
expires?: number;
|
|
72
|
+
};
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
# Coalesce Async
|
|
76
|
+
|
|
77
|
+
The `coalesceAsync` function is a utility that allows you to handle multiple asynchronous operations efficiently. It was designed by `Douglas Cayers` https://github.com/douglascayers/promise-coalesce. It helps in coalescing multiple promises into a single promise, ensuring that only one operation is executed at a time for the same key.
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
import { coalesceAsync } from '@cacheable/utils';
|
|
81
|
+
|
|
82
|
+
const fetchData = async (key: string) => {
|
|
83
|
+
// Simulate an asynchronous operation
|
|
84
|
+
return new Promise((resolve) => setTimeout(() => resolve(`Data for ${key}`), 1000));
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const result = await Promise.all([
|
|
88
|
+
coalesceAsync('my-key', fetchData),
|
|
89
|
+
coalesceAsync('my-key', fetchData),
|
|
90
|
+
coalesceAsync('my-key', fetchData),
|
|
91
|
+
]);
|
|
92
|
+
console.log(result); // Data for my-key only executed once
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
# Hash Functions
|
|
96
|
+
|
|
97
|
+
The `@cacheable/utils` package provides hash functions that can be used to generate unique keys for caching operations. These functions are useful for creating consistent and unique identifiers for cached items.
|
|
98
|
+
|
|
99
|
+
```typescript
|
|
100
|
+
import { hash } from '@cacheable/utils';
|
|
101
|
+
|
|
102
|
+
const key = hash('my-cache-key');
|
|
103
|
+
console.log(key); // Unique hash for 'my-cache-key'
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
If you want to get a number hash you can use the `hashToNumber` function:
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
import { hash, hashToNumber } from '@cacheable/utils';
|
|
110
|
+
|
|
111
|
+
const hashValue = hash({foo: 'bar'}, HashAlgorithm.DJB2);
|
|
112
|
+
const min = 0;
|
|
113
|
+
const max = 10;
|
|
114
|
+
|
|
115
|
+
const result = hashToNumber(hashValue, min, max);
|
|
116
|
+
console.log(result); // A number between 0 and 10 based on the hash value
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
# Shorthand Time Helpers
|
|
120
|
+
|
|
121
|
+
The `@cacheable/utils` package provides a shorthand function to convert human-readable time strings into milliseconds. This is useful for setting time-to-live (TTL) values in caching operations.
|
|
122
|
+
|
|
123
|
+
You can also use the `shorthandToMilliseconds` function:
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
import { shorthandToMilliseconds } from '@cacheable/utils';
|
|
127
|
+
|
|
128
|
+
const milliseconds = shorthandToMilliseconds('1h');
|
|
129
|
+
console.log(milliseconds); // 3600000
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
You can also use the `shorthandToTime` function to get the current date plus the shorthand time:
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
import { shorthandToTime } from '@cacheable/utils';
|
|
136
|
+
|
|
137
|
+
const currentDate = new Date();
|
|
138
|
+
const timeInMs = shorthandToTime('1h', currentDate);
|
|
139
|
+
console.log(timeInMs); // Current date + 1 hour in milliseconds since epoch
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
# Sleep Helper
|
|
143
|
+
|
|
144
|
+
The `sleep` function is a utility that allows you to pause execution for a specified duration. This can be useful in testing scenarios or when you need to introduce delays in your code.
|
|
145
|
+
|
|
146
|
+
```typescript
|
|
147
|
+
import { sleep } from '@cacheable/utils';
|
|
148
|
+
|
|
149
|
+
await sleep(1000); // Pause for 1 second
|
|
150
|
+
console.log('Execution resumed after 1 second');
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
# Stats Helpers
|
|
154
|
+
|
|
155
|
+
The `@cacheable/utils` package provides statistics helpers that can be used to track and analyze caching operations. These helpers can be used to gather metrics such as hit rates, miss rates, and other performance-related statistics.
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
import { stats } from '@cacheable/utils';
|
|
159
|
+
|
|
160
|
+
const cacheStats = stats();
|
|
161
|
+
cacheStats.incrementHits();
|
|
162
|
+
console.log(cacheStats.hits); // Get the hit rate of the cache
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
# Time to Live (TTL) Helpers
|
|
166
|
+
|
|
167
|
+
The `@cacheable/utils` package provides helpers for managing time-to-live (TTL) values for cached items.
|
|
168
|
+
|
|
169
|
+
You can use the `calculateTtlFromExpiration` function to calculate the TTL based on an expiration date:
|
|
170
|
+
|
|
171
|
+
```typescript
|
|
172
|
+
import { calculateTtlFromExpiration } from '@cacheable/utils';
|
|
173
|
+
|
|
174
|
+
const expirationDate = new Date(Date.now() + 1000 * 60 * 5); // 5 minutes from now
|
|
175
|
+
const ttl = calculateTtlFromExpiration(Date.now(), expirationDate);
|
|
176
|
+
console.log(ttl); // 300000
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
You can also use `getTtlFromExpires` to get the TTL from an expiration date:
|
|
180
|
+
|
|
181
|
+
```typescript
|
|
182
|
+
import { getTtlFromExpires } from '@cacheable/utils';
|
|
183
|
+
|
|
184
|
+
const expirationDate = new Date(Date.now() + 1000 * 60 * 5); // 5 minutes from now
|
|
185
|
+
const ttl = getTtlFromExpires(expirationDate);
|
|
186
|
+
console.log(ttl); // 300000
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
You can use `getCascadingTtl` to get the TTL for cascading cache operations:
|
|
190
|
+
|
|
191
|
+
```typescript
|
|
192
|
+
import { getCascadingTtl } from '@cacheable/utils';
|
|
193
|
+
const cacheableTtl = 1000 * 60 * 5; // 5 minutes
|
|
194
|
+
const primaryTtl = 1000 * 60 * 2; // 2 minutes
|
|
195
|
+
const secondaryTtl = 1000 * 60; // 1 minute
|
|
196
|
+
const ttl = getCascadingTtl(cacheableTtl, primaryTtl, secondaryTtl);
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
# How to Contribute
|
|
200
|
+
|
|
201
|
+
You can contribute by forking the repo and submitting a pull request. Please make sure to add tests and update the documentation. To learn more about how to contribute go to our main README [https://github.com/jaredwray/cacheable](https://github.com/jaredwray/cacheable). This will talk about how to `Open a Pull Request`, `Ask a Question`, or `Post an Issue`.
|
|
202
|
+
|
|
203
|
+
# License and Copyright
|
|
204
|
+
[MIT © Jared Wray](./LICENSE)
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
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
|
+
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;
|
|
19
|
+
};
|
|
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
|
+
HashAlgorithm: () => HashAlgorithm,
|
|
34
|
+
Stats: () => Stats,
|
|
35
|
+
calculateTtlFromExpiration: () => calculateTtlFromExpiration,
|
|
36
|
+
coalesceAsync: () => coalesceAsync,
|
|
37
|
+
getCascadingTtl: () => getCascadingTtl,
|
|
38
|
+
getTtlFromExpires: () => getTtlFromExpires,
|
|
39
|
+
hash: () => hash,
|
|
40
|
+
hashToNumber: () => hashToNumber,
|
|
41
|
+
shorthandToMilliseconds: () => shorthandToMilliseconds,
|
|
42
|
+
shorthandToTime: () => shorthandToTime,
|
|
43
|
+
sleep: () => sleep
|
|
44
|
+
});
|
|
45
|
+
module.exports = __toCommonJS(index_exports);
|
|
46
|
+
|
|
47
|
+
// src/coalesce-async.ts
|
|
48
|
+
var callbacks = /* @__PURE__ */ new Map();
|
|
49
|
+
function hasKey(key) {
|
|
50
|
+
return callbacks.has(key);
|
|
51
|
+
}
|
|
52
|
+
function addKey(key) {
|
|
53
|
+
callbacks.set(key, []);
|
|
54
|
+
}
|
|
55
|
+
function removeKey(key) {
|
|
56
|
+
callbacks.delete(key);
|
|
57
|
+
}
|
|
58
|
+
function addCallbackToKey(key, callback) {
|
|
59
|
+
const stash = getCallbacksByKey(key);
|
|
60
|
+
stash.push(callback);
|
|
61
|
+
callbacks.set(key, stash);
|
|
62
|
+
}
|
|
63
|
+
function getCallbacksByKey(key) {
|
|
64
|
+
return callbacks.get(key) ?? [];
|
|
65
|
+
}
|
|
66
|
+
async function enqueue(key) {
|
|
67
|
+
return new Promise((resolve, reject) => {
|
|
68
|
+
const callback = { resolve, reject };
|
|
69
|
+
addCallbackToKey(key, callback);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
function dequeue(key) {
|
|
73
|
+
const stash = getCallbacksByKey(key);
|
|
74
|
+
removeKey(key);
|
|
75
|
+
return stash;
|
|
76
|
+
}
|
|
77
|
+
function coalesce(options) {
|
|
78
|
+
const { key, error, result } = options;
|
|
79
|
+
for (const callback of dequeue(key)) {
|
|
80
|
+
if (error) {
|
|
81
|
+
callback.reject(error);
|
|
82
|
+
} else {
|
|
83
|
+
callback.resolve(result);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async function coalesceAsync(key, fnc) {
|
|
88
|
+
if (!hasKey(key)) {
|
|
89
|
+
addKey(key);
|
|
90
|
+
try {
|
|
91
|
+
const result = await Promise.resolve(fnc());
|
|
92
|
+
coalesce({ key, result });
|
|
93
|
+
return result;
|
|
94
|
+
} catch (error) {
|
|
95
|
+
coalesce({ key, error });
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return enqueue(key);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// src/hash.ts
|
|
103
|
+
var crypto = __toESM(require("crypto"), 1);
|
|
104
|
+
var HashAlgorithm = /* @__PURE__ */ ((HashAlgorithm2) => {
|
|
105
|
+
HashAlgorithm2["SHA256"] = "sha256";
|
|
106
|
+
HashAlgorithm2["SHA512"] = "sha512";
|
|
107
|
+
HashAlgorithm2["MD5"] = "md5";
|
|
108
|
+
HashAlgorithm2["DJB2"] = "djb2";
|
|
109
|
+
return HashAlgorithm2;
|
|
110
|
+
})(HashAlgorithm || {});
|
|
111
|
+
function hash(object, algorithm = "sha256" /* SHA256 */) {
|
|
112
|
+
const objectString = JSON.stringify(object);
|
|
113
|
+
if (algorithm === "djb2" /* DJB2 */) {
|
|
114
|
+
return djb2Hash(objectString);
|
|
115
|
+
}
|
|
116
|
+
if (!crypto.getHashes().includes(algorithm)) {
|
|
117
|
+
throw new Error(`Unsupported hash algorithm: '${algorithm}'`);
|
|
118
|
+
}
|
|
119
|
+
const hasher = crypto.createHash(algorithm);
|
|
120
|
+
hasher.update(objectString);
|
|
121
|
+
return hasher.digest("hex");
|
|
122
|
+
}
|
|
123
|
+
function hashToNumber(hash2, min = 0, max = 10) {
|
|
124
|
+
const hashNumber = Number.parseInt(hash2, 16);
|
|
125
|
+
const range = max - min + 1;
|
|
126
|
+
return min + hashNumber % range;
|
|
127
|
+
}
|
|
128
|
+
function djb2Hash(string_) {
|
|
129
|
+
let hash2 = 5381;
|
|
130
|
+
for (let i = 0; i < string_.length; i++) {
|
|
131
|
+
hash2 = hash2 * 33 ^ string_.charCodeAt(i);
|
|
132
|
+
}
|
|
133
|
+
return hash2.toString();
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// src/shorthand-time.ts
|
|
137
|
+
var shorthandToMilliseconds = (shorthand) => {
|
|
138
|
+
let milliseconds;
|
|
139
|
+
if (shorthand === void 0) {
|
|
140
|
+
return void 0;
|
|
141
|
+
}
|
|
142
|
+
if (typeof shorthand === "number") {
|
|
143
|
+
milliseconds = shorthand;
|
|
144
|
+
} else if (typeof shorthand === "string") {
|
|
145
|
+
shorthand = shorthand.trim();
|
|
146
|
+
if (Number.isNaN(Number(shorthand))) {
|
|
147
|
+
const match = /^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(shorthand);
|
|
148
|
+
if (!match) {
|
|
149
|
+
throw new Error(`Unsupported time format: "${shorthand}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`);
|
|
150
|
+
}
|
|
151
|
+
const [, value, unit] = match;
|
|
152
|
+
const numericValue = Number.parseFloat(value);
|
|
153
|
+
const unitLower = unit.toLowerCase();
|
|
154
|
+
switch (unitLower) {
|
|
155
|
+
case "ms": {
|
|
156
|
+
milliseconds = numericValue;
|
|
157
|
+
break;
|
|
158
|
+
}
|
|
159
|
+
case "s": {
|
|
160
|
+
milliseconds = numericValue * 1e3;
|
|
161
|
+
break;
|
|
162
|
+
}
|
|
163
|
+
case "m": {
|
|
164
|
+
milliseconds = numericValue * 1e3 * 60;
|
|
165
|
+
break;
|
|
166
|
+
}
|
|
167
|
+
case "h": {
|
|
168
|
+
milliseconds = numericValue * 1e3 * 60 * 60;
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
case "hr": {
|
|
172
|
+
milliseconds = numericValue * 1e3 * 60 * 60;
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
case "d": {
|
|
176
|
+
milliseconds = numericValue * 1e3 * 60 * 60 * 24;
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
/* c8 ignore next 3 */
|
|
180
|
+
default: {
|
|
181
|
+
milliseconds = Number(shorthand);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
} else {
|
|
185
|
+
milliseconds = Number(shorthand);
|
|
186
|
+
}
|
|
187
|
+
} else {
|
|
188
|
+
throw new TypeError("Time must be a string or a number.");
|
|
189
|
+
}
|
|
190
|
+
return milliseconds;
|
|
191
|
+
};
|
|
192
|
+
var shorthandToTime = (shorthand, fromDate) => {
|
|
193
|
+
fromDate ??= /* @__PURE__ */ new Date();
|
|
194
|
+
const milliseconds = shorthandToMilliseconds(shorthand);
|
|
195
|
+
if (milliseconds === void 0) {
|
|
196
|
+
return fromDate.getTime();
|
|
197
|
+
}
|
|
198
|
+
return fromDate.getTime() + milliseconds;
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
// src/sleep.ts
|
|
202
|
+
var sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
203
|
+
|
|
204
|
+
// src/stats.ts
|
|
205
|
+
var Stats = class {
|
|
206
|
+
_hits = 0;
|
|
207
|
+
_misses = 0;
|
|
208
|
+
_gets = 0;
|
|
209
|
+
_sets = 0;
|
|
210
|
+
_deletes = 0;
|
|
211
|
+
_clears = 0;
|
|
212
|
+
_vsize = 0;
|
|
213
|
+
_ksize = 0;
|
|
214
|
+
_count = 0;
|
|
215
|
+
_enabled = false;
|
|
216
|
+
constructor(options) {
|
|
217
|
+
if (options?.enabled) {
|
|
218
|
+
this._enabled = options.enabled;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* @returns {boolean} - Whether the stats are enabled
|
|
223
|
+
*/
|
|
224
|
+
get enabled() {
|
|
225
|
+
return this._enabled;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* @param {boolean} enabled - Whether to enable the stats
|
|
229
|
+
*/
|
|
230
|
+
set enabled(enabled) {
|
|
231
|
+
this._enabled = enabled;
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* @returns {number} - The number of hits
|
|
235
|
+
* @readonly
|
|
236
|
+
*/
|
|
237
|
+
get hits() {
|
|
238
|
+
return this._hits;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* @returns {number} - The number of misses
|
|
242
|
+
* @readonly
|
|
243
|
+
*/
|
|
244
|
+
get misses() {
|
|
245
|
+
return this._misses;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* @returns {number} - The number of gets
|
|
249
|
+
* @readonly
|
|
250
|
+
*/
|
|
251
|
+
get gets() {
|
|
252
|
+
return this._gets;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* @returns {number} - The number of sets
|
|
256
|
+
* @readonly
|
|
257
|
+
*/
|
|
258
|
+
get sets() {
|
|
259
|
+
return this._sets;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* @returns {number} - The number of deletes
|
|
263
|
+
* @readonly
|
|
264
|
+
*/
|
|
265
|
+
get deletes() {
|
|
266
|
+
return this._deletes;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* @returns {number} - The number of clears
|
|
270
|
+
* @readonly
|
|
271
|
+
*/
|
|
272
|
+
get clears() {
|
|
273
|
+
return this._clears;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* @returns {number} - The vsize (value size) of the cache instance
|
|
277
|
+
* @readonly
|
|
278
|
+
*/
|
|
279
|
+
get vsize() {
|
|
280
|
+
return this._vsize;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* @returns {number} - The ksize (key size) of the cache instance
|
|
284
|
+
* @readonly
|
|
285
|
+
*/
|
|
286
|
+
get ksize() {
|
|
287
|
+
return this._ksize;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* @returns {number} - The count of the cache instance
|
|
291
|
+
* @readonly
|
|
292
|
+
*/
|
|
293
|
+
get count() {
|
|
294
|
+
return this._count;
|
|
295
|
+
}
|
|
296
|
+
incrementHits() {
|
|
297
|
+
if (!this._enabled) {
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
this._hits++;
|
|
301
|
+
}
|
|
302
|
+
incrementMisses() {
|
|
303
|
+
if (!this._enabled) {
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
this._misses++;
|
|
307
|
+
}
|
|
308
|
+
incrementGets() {
|
|
309
|
+
if (!this._enabled) {
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
this._gets++;
|
|
313
|
+
}
|
|
314
|
+
incrementSets() {
|
|
315
|
+
if (!this._enabled) {
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
this._sets++;
|
|
319
|
+
}
|
|
320
|
+
incrementDeletes() {
|
|
321
|
+
if (!this._enabled) {
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
this._deletes++;
|
|
325
|
+
}
|
|
326
|
+
incrementClears() {
|
|
327
|
+
if (!this._enabled) {
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
this._clears++;
|
|
331
|
+
}
|
|
332
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
333
|
+
incrementVSize(value) {
|
|
334
|
+
if (!this._enabled) {
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
this._vsize += this.roughSizeOfObject(value);
|
|
338
|
+
}
|
|
339
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
340
|
+
decreaseVSize(value) {
|
|
341
|
+
if (!this._enabled) {
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
this._vsize -= this.roughSizeOfObject(value);
|
|
345
|
+
}
|
|
346
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
347
|
+
incrementKSize(key) {
|
|
348
|
+
if (!this._enabled) {
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
this._ksize += this.roughSizeOfString(key);
|
|
352
|
+
}
|
|
353
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
354
|
+
decreaseKSize(key) {
|
|
355
|
+
if (!this._enabled) {
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
this._ksize -= this.roughSizeOfString(key);
|
|
359
|
+
}
|
|
360
|
+
incrementCount() {
|
|
361
|
+
if (!this._enabled) {
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
this._count++;
|
|
365
|
+
}
|
|
366
|
+
decreaseCount() {
|
|
367
|
+
if (!this._enabled) {
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
this._count--;
|
|
371
|
+
}
|
|
372
|
+
setCount(count) {
|
|
373
|
+
if (!this._enabled) {
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
this._count = count;
|
|
377
|
+
}
|
|
378
|
+
roughSizeOfString(value) {
|
|
379
|
+
return value.length * 2;
|
|
380
|
+
}
|
|
381
|
+
roughSizeOfObject(object) {
|
|
382
|
+
const objectList = [];
|
|
383
|
+
const stack = [object];
|
|
384
|
+
let bytes = 0;
|
|
385
|
+
while (stack.length > 0) {
|
|
386
|
+
const value = stack.pop();
|
|
387
|
+
if (typeof value === "boolean") {
|
|
388
|
+
bytes += 4;
|
|
389
|
+
} else if (typeof value === "string") {
|
|
390
|
+
bytes += value.length * 2;
|
|
391
|
+
} else if (typeof value === "number") {
|
|
392
|
+
bytes += 8;
|
|
393
|
+
} else if (typeof value === "object" && value !== null && !objectList.includes(value)) {
|
|
394
|
+
objectList.push(value);
|
|
395
|
+
for (const key in value) {
|
|
396
|
+
bytes += key.length * 2;
|
|
397
|
+
stack.push(value[key]);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return bytes;
|
|
402
|
+
}
|
|
403
|
+
reset() {
|
|
404
|
+
this._hits = 0;
|
|
405
|
+
this._misses = 0;
|
|
406
|
+
this._gets = 0;
|
|
407
|
+
this._sets = 0;
|
|
408
|
+
this._deletes = 0;
|
|
409
|
+
this._clears = 0;
|
|
410
|
+
this._vsize = 0;
|
|
411
|
+
this._ksize = 0;
|
|
412
|
+
this._count = 0;
|
|
413
|
+
}
|
|
414
|
+
resetStoreValues() {
|
|
415
|
+
this._vsize = 0;
|
|
416
|
+
this._ksize = 0;
|
|
417
|
+
this._count = 0;
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
// src/ttl.ts
|
|
422
|
+
function getTtlFromExpires(expires) {
|
|
423
|
+
if (expires === void 0 || expires === null) {
|
|
424
|
+
return void 0;
|
|
425
|
+
}
|
|
426
|
+
const now = Date.now();
|
|
427
|
+
if (expires < now) {
|
|
428
|
+
return void 0;
|
|
429
|
+
}
|
|
430
|
+
return expires - now;
|
|
431
|
+
}
|
|
432
|
+
function getCascadingTtl(cacheableTtl, primaryTtl, secondaryTtl) {
|
|
433
|
+
return secondaryTtl ?? primaryTtl ?? shorthandToMilliseconds(cacheableTtl);
|
|
434
|
+
}
|
|
435
|
+
function calculateTtlFromExpiration(ttl, expires) {
|
|
436
|
+
const ttlFromExpires = getTtlFromExpires(expires);
|
|
437
|
+
const expiresFromTtl = ttl ? Date.now() + ttl : void 0;
|
|
438
|
+
if (ttlFromExpires === void 0) {
|
|
439
|
+
return ttl;
|
|
440
|
+
}
|
|
441
|
+
if (expiresFromTtl === void 0) {
|
|
442
|
+
return ttlFromExpires;
|
|
443
|
+
}
|
|
444
|
+
if (expires > expiresFromTtl) {
|
|
445
|
+
return ttl;
|
|
446
|
+
}
|
|
447
|
+
return ttlFromExpires;
|
|
448
|
+
}
|
|
449
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
450
|
+
0 && (module.exports = {
|
|
451
|
+
HashAlgorithm,
|
|
452
|
+
Stats,
|
|
453
|
+
calculateTtlFromExpiration,
|
|
454
|
+
coalesceAsync,
|
|
455
|
+
getCascadingTtl,
|
|
456
|
+
getTtlFromExpires,
|
|
457
|
+
hash,
|
|
458
|
+
hashToNumber,
|
|
459
|
+
shorthandToMilliseconds,
|
|
460
|
+
shorthandToTime,
|
|
461
|
+
sleep
|
|
462
|
+
});
|